1use super::html_escape;
11use crate::config;
12use serde::{Deserialize, Serialize};
13
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
16#[serde(rename_all = "snake_case")]
17pub enum NotificationLevel {
18 All,
22 Verbose,
24 ErrorsOnly,
26 None,
28}
29
30impl NotificationLevel {
31 pub fn from_config() -> Self {
33 match config::get("notifications.level") {
34 Ok(val) => match val.as_str() {
35 "verbose" => Self::Verbose,
36 "errors_only" => Self::ErrorsOnly,
37 "none" => Self::None,
38 _ => Self::All,
39 },
40 Err(_) => Self::All,
41 }
42 }
43
44 pub fn should_notify(&self, status: &str) -> bool {
52 match self {
53 Self::All => matches!(
54 status,
55 "done" | "in_review" | "approved" | "blocked" | "failed"
56 ),
57 Self::Verbose => true,
58 Self::ErrorsOnly => matches!(status, "blocked" | "failed"),
59 Self::None => false,
60 }
61 }
62}
63
64#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct TaskNotification {
67 pub task_id: String,
68 pub title: String,
69 pub status: String,
70 pub agent: String,
71 pub duration_seconds: f64,
72 pub summary: String,
73 pub repo: Option<String>,
75 #[serde(default)]
79 pub notify_target: Option<String>,
80 #[serde(default)]
82 pub pr_number: Option<String>,
83}
84
85fn github_link(repo: Option<&str>, task_id: &str, pr_number: Option<&str>) -> Option<String> {
88 let repo = repo?;
89 if let Some(pr) = pr_number {
90 return Some(format!("https://github.com/{repo}/pull/{pr}"));
91 }
92 if !task_id.starts_with("internal:") && task_id.chars().all(|c| c.is_ascii_digit()) {
94 return Some(format!("https://github.com/{repo}/issues/{task_id}"));
95 }
96 None
97}
98
99struct ChannelBody<'a> {
101 title: &'a str,
102 status: &'a str,
103 agent: &'a str,
104 task_id: &'a str,
105 summary: &'a str,
106 link_suffix: &'a str,
107}
108
109impl TaskNotification {
110 fn github_link_suffix(&self, wrap: impl FnOnce(&str) -> String) -> String {
111 match github_link(
112 self.repo.as_deref(),
113 &self.task_id,
114 self.pr_number.as_deref(),
115 ) {
116 Some(url) => format!("\n\n{}", wrap(&url)),
117 None => String::new(),
118 }
119 }
120
121 fn render(&self, body: &ChannelBody<'_>) -> String {
122 let emoji = status_emoji(&self.status);
123 let duration = format_duration(self.duration_seconds);
124 format!(
125 "{emoji} {title}\n\
126 {status} · {agent} · {duration} · #{task_id}\n\
127 \n\
128 {summary}{link_suffix}",
129 title = body.title,
130 status = body.status,
131 agent = body.agent,
132 task_id = body.task_id,
133 summary = body.summary,
134 link_suffix = body.link_suffix,
135 )
136 }
137
138 pub fn format_telegram(&self) -> String {
144 let title = format!("<b>{}</b>", html_escape(&self.title));
145 let status = html_escape(&self.status);
146 let agent = format!("<code>{}</code>", html_escape(&self.agent));
147 let task_id = html_escape(&self.task_id);
148 let summary = html_escape(&self.summary);
149 let link_suffix = self.github_link_suffix(|url| {
150 format!("<a href=\"{}\">View on GitHub</a>", html_escape(url))
151 });
152 self.render(&ChannelBody {
153 title: &title,
154 status: &status,
155 agent: &agent,
156 task_id: &task_id,
157 summary: &summary,
158 link_suffix: &link_suffix,
159 })
160 }
161
162 pub fn format_slack(&self) -> String {
166 let title = format!("*{}*", self.title);
167 let agent = format!("`{}`", self.agent);
168 let link_suffix = self.github_link_suffix(|url| format!("<{url}|View on GitHub>"));
169 self.render(&ChannelBody {
170 title: &title,
171 status: &self.status,
172 agent: &agent,
173 task_id: &self.task_id,
174 summary: &self.summary,
175 link_suffix: &link_suffix,
176 })
177 }
178
179 pub fn format_discord(&self) -> String {
181 let title = format!("**{}**", self.title);
182 let agent = format!("`{}`", self.agent);
183 let link_suffix = self.github_link_suffix(|url| format!("[View on GitHub]({url})"));
184 self.render(&ChannelBody {
185 title: &title,
186 status: &self.status,
187 agent: &agent,
188 task_id: &self.task_id,
189 summary: &self.summary,
190 link_suffix: &link_suffix,
191 })
192 }
193
194 pub fn format_with_project(&self, channel: &str) -> String {
199 let project_name = self
200 .repo
201 .as_deref()
202 .and_then(|r| r.split('/').next_back())
203 .unwrap_or("unknown");
204
205 let base = match channel {
206 "discord" => self.format_discord(),
207 "slack" => self.format_slack(),
208 _ => self.format_telegram(),
209 };
210
211 let project_name = if channel == "telegram" {
212 html_escape(project_name)
213 } else {
214 project_name.to_string()
215 };
216 format!("[{project_name}] {base}")
217 }
218}
219
220fn status_emoji(status: &str) -> &'static str {
221 match status {
222 "done" => "✅",
223 "in_review" => "🔍",
224 "approved" => "👍",
225 "in_progress" => "🔄",
226 "needs_review" => "⚠️",
227 "blocked" => "🚫",
228 "failed" => "❌",
229 _ => "📋",
230 }
231}
232
233pub fn format_duration(seconds: f64) -> String {
235 if seconds < 60.0 {
236 format!("{seconds:.0}s")
237 } else if seconds < 3600.0 {
238 format!("{:.0}m {:.0}s", (seconds / 60.0).floor(), seconds % 60.0)
239 } else {
240 let hours = (seconds / 3600.0).floor();
241 let mins = ((seconds % 3600.0) / 60.0).floor();
242 format!("{hours:.0}h {mins:.0}m")
243 }
244}
245
246#[cfg(test)]
247mod tests {
248 use super::*;
249
250 #[test]
251 fn notification_level_should_notify_all_active_review_only() {
252 let level = NotificationLevel::All;
253 assert!(level.should_notify("done"));
255 assert!(level.should_notify("in_review"));
256 assert!(level.should_notify("blocked"));
257 assert!(level.should_notify("failed"));
258 assert!(!level.should_notify("needs_review"));
261 assert!(!level.should_notify("new"));
263 assert!(!level.should_notify("routed"));
264 assert!(!level.should_notify("in_progress"));
265 }
266
267 #[test]
268 fn notification_level_should_notify_verbose_fires_for_all() {
269 let level = NotificationLevel::Verbose;
270 assert!(level.should_notify("done"));
271 assert!(level.should_notify("needs_review"));
272 assert!(level.should_notify("blocked"));
273 assert!(level.should_notify("failed"));
274 assert!(level.should_notify("new"));
275 assert!(level.should_notify("routed"));
276 assert!(level.should_notify("in_progress"));
277 assert!(level.should_notify("in_review"));
278 }
279
280 #[test]
281 fn notification_level_should_notify_errors_only() {
282 let level = NotificationLevel::ErrorsOnly;
283 assert!(!level.should_notify("done"));
284 assert!(!level.should_notify("in_progress"));
285 assert!(!level.should_notify("in_review"));
286 assert!(!level.should_notify("needs_review"));
287 assert!(level.should_notify("blocked"));
288 assert!(level.should_notify("failed"));
289 }
290
291 #[test]
292 fn notification_level_should_notify_none() {
293 let level = NotificationLevel::None;
294 assert!(!level.should_notify("done"));
295 assert!(!level.should_notify("needs_review"));
296 assert!(!level.should_notify("in_review"));
297 assert!(!level.should_notify("blocked"));
298 }
299
300 #[test]
301 fn notification_level_default_is_all() {
302 let level = NotificationLevel::from_config();
304 assert_eq!(level, NotificationLevel::All);
305 }
306
307 #[test]
308 fn format_duration_seconds() {
309 assert_eq!(format_duration(30.0), "30s");
310 assert_eq!(format_duration(0.0), "0s");
311 assert_eq!(format_duration(59.9), "60s");
312 }
313
314 #[test]
315 fn format_duration_minutes() {
316 assert_eq!(format_duration(90.0), "1m 30s");
317 assert_eq!(format_duration(3599.0), "59m 59s");
318 }
319
320 #[test]
321 fn format_duration_hours() {
322 assert_eq!(format_duration(3600.0), "1h 0m");
323 assert_eq!(format_duration(7200.0), "2h 0m");
324 assert_eq!(format_duration(5400.0), "1h 30m");
325 }
326
327 #[test]
328 fn format_telegram_done() {
329 let n = TaskNotification {
330 task_id: "42".to_string(),
331 title: "Fix auth bug".to_string(),
332 status: "done".to_string(),
333 agent: "claude".to_string(),
334 duration_seconds: 120.0,
335 summary: "Fixed the OAuth flow".to_string(),
336 repo: Some("owner/my-project".to_string()),
337 notify_target: None,
338 pr_number: None,
339 };
340 let msg = n.format_telegram();
341 assert!(msg.contains("✅"));
342 assert!(
344 msg.contains("<b>Fix auth bug</b>"),
345 "title should be the headline: {msg}"
346 );
347 assert!(msg.contains("#42"));
348 assert!(msg.contains("done"));
349 assert!(msg.contains("claude"));
350 assert!(msg.contains("2m 0s"));
351 assert!(msg.contains("Fixed the OAuth flow"));
352 }
353
354 #[test]
355 fn format_telegram_escapes_markdown() {
356 let n = TaskNotification {
357 task_id: "1".to_string(),
358 title: "Fix _underscores_ and *bold*".to_string(),
359 status: "done".to_string(),
360 agent: "claude".to_string(),
361 duration_seconds: 10.0,
362 summary: "Done".to_string(),
363 repo: None,
364 notify_target: None,
365 pr_number: None,
366 };
367 let msg = n.format_telegram();
368 assert!(msg.contains("Fix _underscores_ and *bold*"));
371 assert!(msg.contains("<b>Fix _underscores_ and *bold*</b>"));
373 }
374
375 #[test]
376 fn format_telegram_escapes_status_with_underscores() {
377 let n = TaskNotification {
378 task_id: "5".to_string(),
379 title: "Test task".to_string(),
380 status: "needs_review".to_string(),
381 agent: "claude".to_string(),
382 duration_seconds: 30.0,
383 summary: "Ready for review".to_string(),
384 repo: None,
385 notify_target: None,
386 pr_number: None,
387 };
388 let msg = n.format_telegram();
389 assert!(msg.contains("needs_review"));
392 }
393
394 #[test]
395 fn format_telegram_escapes_agent_with_underscores() {
396 let n = TaskNotification {
397 task_id: "6".to_string(),
398 title: "Test".to_string(),
399 status: "done".to_string(),
400 agent: "my_agent".to_string(),
401 duration_seconds: 15.0,
402 summary: "Done".to_string(),
403 repo: None,
404 notify_target: None,
405 pr_number: None,
406 };
407 let msg = n.format_telegram();
408 assert!(msg.contains("<code>my_agent</code>"));
411 }
412
413 #[test]
414 fn format_slack_done() {
415 let n = TaskNotification {
416 task_id: "7".to_string(),
417 title: "Refactor engine".to_string(),
418 status: "done".to_string(),
419 agent: "claude".to_string(),
420 duration_seconds: 60.0,
421 summary: "Decomposed mod.rs".to_string(),
422 repo: Some("org/refactor-repo".to_string()),
423 notify_target: None,
424 pr_number: None,
425 };
426 let msg = n.format_slack();
427 assert!(msg.contains("✅"));
428 assert!(
429 msg.contains("*Refactor engine*"),
430 "title should be the headline: {msg}"
431 );
432 assert!(msg.contains("#7"));
433 assert!(msg.contains("done"));
434 assert!(msg.contains("`claude`"));
435 assert!(msg.contains("1m 0s"));
436 assert!(msg.contains("Decomposed mod.rs"));
437 }
438
439 #[test]
440 fn format_discord_needs_review() {
441 let n = TaskNotification {
442 task_id: "99".to_string(),
443 title: "Deploy service".to_string(),
444 status: "needs_review".to_string(),
445 agent: "codex".to_string(),
446 duration_seconds: 1800.0,
447 summary: "Timed out waiting for tests".to_string(),
448 repo: Some("acme/deploy-svc".to_string()),
449 notify_target: None,
450 pr_number: None,
451 };
452 let msg = n.format_discord();
453 assert!(msg.contains("⚠️"));
454 assert!(
455 msg.contains("**Deploy service**"),
456 "title should be the headline: {msg}"
457 );
458 assert!(msg.contains("#99"));
459 assert!(msg.contains("needs_review"));
460 assert!(msg.contains("codex"));
461 assert!(msg.contains("30m 0s"));
462 }
463
464 #[test]
465 fn format_with_project_prepends_repo_name() {
466 let n = TaskNotification {
467 task_id: "10".to_string(),
468 title: "Add feature".to_string(),
469 status: "done".to_string(),
470 agent: "claude".to_string(),
471 duration_seconds: 45.0,
472 summary: "Feature added".to_string(),
473 repo: Some("acme/widgets".to_string()),
474 notify_target: None,
475 pr_number: None,
476 };
477 let msg = n.format_with_project("telegram");
478 assert!(msg.starts_with("[widgets] "));
479 assert!(msg.contains("#10"));
480 assert!(msg.contains("<b>Add feature</b>"));
481 }
482
483 #[test]
484 fn format_with_project_unknown_when_no_repo() {
485 let n = TaskNotification {
486 task_id: "11".to_string(),
487 title: "Task".to_string(),
488 status: "done".to_string(),
489 agent: "claude".to_string(),
490 duration_seconds: 5.0,
491 summary: "Done".to_string(),
492 repo: None,
493 notify_target: None,
494 pr_number: None,
495 };
496 let msg = n.format_with_project("discord");
497 assert!(msg.starts_with("[unknown] "));
498 }
499
500 #[test]
501 fn status_emoji_mapping() {
502 assert_eq!(status_emoji("done"), "✅");
503 assert_eq!(status_emoji("in_review"), "🔍");
504 assert_eq!(status_emoji("in_progress"), "🔄");
505 assert_eq!(status_emoji("needs_review"), "⚠️");
506 assert_eq!(status_emoji("blocked"), "🚫");
507 assert_eq!(status_emoji("failed"), "❌");
508 assert_eq!(status_emoji("unknown"), "📋");
509 }
510
511 #[test]
512 fn format_with_project_includes_repo_name() {
513 let n = TaskNotification {
514 task_id: "42".into(),
515 title: "Fix bug".into(),
516 status: "done".into(),
517 agent: "claude".into(),
518 duration_seconds: 90.0,
519 summary: "Fixed it".into(),
520 repo: Some("owner/myproject".into()),
521 notify_target: None,
522 pr_number: None,
523 };
524 let formatted = n.format_with_project("telegram");
525 assert!(
526 formatted.starts_with("[myproject]"),
527 "should start with project name: {formatted}"
528 );
529 assert!(formatted.contains("Fix bug"));
530 }
531
532 #[test]
533 fn format_with_project_no_repo_still_works() {
534 let n = TaskNotification {
535 task_id: "42".into(),
536 title: "Fix bug".into(),
537 status: "done".into(),
538 agent: "claude".into(),
539 duration_seconds: 90.0,
540 summary: "Fixed it".into(),
541 repo: None,
542 notify_target: None,
543 pr_number: None,
544 };
545 let formatted = n.format_with_project("telegram");
546 assert!(
547 formatted.starts_with("[unknown]"),
548 "should fallback: {formatted}"
549 );
550 }
551
552 #[test]
553 fn title_appears_before_metadata_in_telegram() {
554 let n = TaskNotification {
555 task_id: "internal:151694".to_string(),
556 title: "Morning briefing: daily focus plan".to_string(),
557 status: "done".to_string(),
558 agent: "opencode".to_string(),
559 duration_seconds: 1821.0,
560 summary: "Recap delivered".to_string(),
561 repo: Some("owner/repo".to_string()),
562 notify_target: None,
563 pr_number: None,
564 };
565 let msg = n.format_telegram();
566 let title_pos = msg.find("Morning briefing").expect("title present");
567 let id_pos = msg.find("#internal:151694").expect("id present");
568 assert!(
569 title_pos < id_pos,
570 "title must appear before task id: {msg}"
571 );
572 }
573
574 #[test]
575 fn title_appears_before_metadata_in_discord() {
576 let n = TaskNotification {
577 task_id: "internal:5".to_string(),
578 title: "Deploy svc".to_string(),
579 status: "done".to_string(),
580 agent: "codex".to_string(),
581 duration_seconds: 60.0,
582 summary: "ok".to_string(),
583 repo: Some("acme/svc".to_string()),
584 notify_target: None,
585 pr_number: None,
586 };
587 let msg = n.format_discord();
588 let title_pos = msg.find("Deploy svc").expect("title present");
589 let id_pos = msg.find("#internal:5").expect("id present");
590 assert!(title_pos < id_pos, "title before id: {msg}");
591 }
592
593 #[test]
594 fn format_with_project_uses_channel_format() {
595 let n = TaskNotification {
596 task_id: "5".into(),
597 title: "Deploy".into(),
598 status: "done".into(),
599 agent: "codex".into(),
600 duration_seconds: 60.0,
601 summary: "Deployed".into(),
602 repo: Some("acme/svc".into()),
603 notify_target: None,
604 pr_number: None,
605 };
606 let tg = n.format_with_project("telegram");
607 let dc = n.format_with_project("discord");
608 assert!(tg.starts_with("[svc]"));
610 assert!(dc.starts_with("[svc]"));
611 assert!(dc.contains("**Deploy**"));
613 assert!(tg.contains("<b>Deploy</b>"));
614 assert!(tg.contains("#5"));
616 assert!(dc.contains("#5"));
617 }
618
619 #[test]
620 fn telegram_appends_pr_link_when_pr_number_present() {
621 let n = TaskNotification {
622 task_id: "internal:151696".to_string(),
623 title: "Market intelligence".to_string(),
624 status: "done".to_string(),
625 agent: "claude".to_string(),
626 duration_seconds: 39.0,
627 summary: "Trending topics".to_string(),
628 repo: Some("owner/repo".to_string()),
629 notify_target: None,
630 pr_number: Some("4242".to_string()),
631 };
632 let msg = n.format_telegram();
633 assert!(
634 msg.contains("https://github.com/owner/repo/pull/4242"),
635 "expected PR link in {msg}"
636 );
637 assert!(msg.contains("View on GitHub"));
638 }
639
640 #[test]
641 fn telegram_falls_back_to_issue_link_for_external_task_without_pr() {
642 let n = TaskNotification {
643 task_id: "1234".to_string(),
644 title: "An issue".to_string(),
645 status: "needs_review".to_string(),
646 agent: "claude".to_string(),
647 duration_seconds: 10.0,
648 summary: "Awaiting review".to_string(),
649 repo: Some("owner/repo".to_string()),
650 notify_target: None,
651 pr_number: None,
652 };
653 let msg = n.format_telegram();
654 assert!(
655 msg.contains("https://github.com/owner/repo/issues/1234"),
656 "expected issue link in {msg}"
657 );
658 }
659
660 #[test]
661 fn no_link_for_internal_task_without_pr() {
662 let n = TaskNotification {
663 task_id: "internal:99".to_string(),
664 title: "Internal task".to_string(),
665 status: "done".to_string(),
666 agent: "claude".to_string(),
667 duration_seconds: 5.0,
668 summary: "Done".to_string(),
669 repo: Some("owner/repo".to_string()),
670 notify_target: None,
671 pr_number: None,
672 };
673 let msg = n.format_telegram();
674 assert!(!msg.contains("github.com"), "should not link: {msg}");
675 }
676
677 #[test]
678 fn discord_appends_pr_link() {
679 let n = TaskNotification {
680 task_id: "internal:7".to_string(),
681 title: "T".to_string(),
682 status: "done".to_string(),
683 agent: "claude".to_string(),
684 duration_seconds: 1.0,
685 summary: "S".to_string(),
686 repo: Some("owner/repo".to_string()),
687 notify_target: None,
688 pr_number: Some("9".to_string()),
689 };
690 let msg = n.format_discord();
691 assert!(msg.contains("[View on GitHub](https://github.com/owner/repo/pull/9)"));
692 }
693
694 #[test]
695 fn slack_appends_pr_link() {
696 let n = TaskNotification {
697 task_id: "internal:7".to_string(),
698 title: "T".to_string(),
699 status: "done".to_string(),
700 agent: "claude".to_string(),
701 duration_seconds: 1.0,
702 summary: "S".to_string(),
703 repo: Some("owner/repo".to_string()),
704 notify_target: None,
705 pr_number: Some("9".to_string()),
706 };
707 let msg = n.format_slack();
708 assert!(msg.contains("<https://github.com/owner/repo/pull/9|View on GitHub>"));
709 }
710
711 #[test]
712 fn format_telegram_exact_layout_with_issue_link() {
713 let n = TaskNotification {
714 task_id: "42".to_string(),
715 title: "Fix auth bug".to_string(),
716 status: "done".to_string(),
717 agent: "claude".to_string(),
718 duration_seconds: 120.0,
719 summary: "Fixed the OAuth flow".to_string(),
720 repo: Some("owner/my-project".to_string()),
721 notify_target: None,
722 pr_number: None,
723 };
724 assert_eq!(
725 n.format_telegram(),
726 "✅ <b>Fix auth bug</b>\n\
727 done · <code>claude</code> · 2m 0s · #42\n\
728 \n\
729 Fixed the OAuth flow\n\
730 \n\
731 <a href=\"https://github.com/owner/my-project/issues/42\">View on GitHub</a>"
732 );
733 }
734
735 #[test]
736 fn format_slack_exact_layout_with_pr_link() {
737 let n = TaskNotification {
738 task_id: "internal:7".to_string(),
739 title: "T".to_string(),
740 status: "done".to_string(),
741 agent: "claude".to_string(),
742 duration_seconds: 1.0,
743 summary: "S".to_string(),
744 repo: Some("owner/repo".to_string()),
745 notify_target: None,
746 pr_number: Some("9".to_string()),
747 };
748 assert_eq!(
749 n.format_slack(),
750 "✅ *T*\n\
751 done · `claude` · 1s · #internal:7\n\
752 \n\
753 S\n\
754 \n\
755 <https://github.com/owner/repo/pull/9|View on GitHub>"
756 );
757 }
758
759 #[test]
760 fn format_discord_exact_layout_with_pr_link() {
761 let n = TaskNotification {
762 task_id: "internal:7".to_string(),
763 title: "T".to_string(),
764 status: "done".to_string(),
765 agent: "claude".to_string(),
766 duration_seconds: 1.0,
767 summary: "S".to_string(),
768 repo: Some("owner/repo".to_string()),
769 notify_target: None,
770 pr_number: Some("9".to_string()),
771 };
772 assert_eq!(
773 n.format_discord(),
774 "✅ **T**\n\
775 done · `claude` · 1s · #internal:7\n\
776 \n\
777 S\n\
778 \n\
779 [View on GitHub](https://github.com/owner/repo/pull/9)"
780 );
781 }
782
783 #[test]
784 fn format_telegram_escapes_html_entities_in_every_field() {
785 let n = TaskNotification {
786 task_id: "1<2".to_string(),
787 title: "a < b & c > d".to_string(),
788 status: "done".to_string(),
789 agent: "my_agent".to_string(),
790 duration_seconds: 10.0,
791 summary: "x < y".to_string(),
792 repo: Some("owner/repo".to_string()),
793 notify_target: None,
794 pr_number: None,
795 };
796 let msg = n.format_telegram();
797 assert!(msg.contains("<b>a < b & c > d</b>"));
798 assert!(msg.contains("<code>my_agent</code>"));
799 assert!(msg.contains("x < y"));
800 assert!(msg.contains("#1<2"));
801 assert!(
802 !msg.contains("github.com"),
803 "non-numeric id has no issue link: {msg}"
804 );
805 }
806
807 #[test]
808 fn github_link_prefers_pr_then_issue_then_none() {
809 assert_eq!(
810 github_link(Some("owner/repo"), "internal:1", Some("9")),
811 Some("https://github.com/owner/repo/pull/9".into())
812 );
813 assert_eq!(
814 github_link(Some("owner/repo"), "1234", None),
815 Some("https://github.com/owner/repo/issues/1234".into())
816 );
817 assert_eq!(github_link(Some("owner/repo"), "internal:99", None), None);
818 assert_eq!(github_link(None, "1234", Some("9")), None);
819 }
820}