1use serde::Deserialize;
20use std::sync::{Arc, Mutex, OnceLock};
21
22use crate::backend::blockcontroller::health::{TriggerKind, TurnEnd, TurnTrigger};
23use crate::backend::mps::{Broker, MuxEvent};
24use crate::backend::obj::{Block, Tab, Window, Workspace};
25use crate::backend::storage::store::Store;
26use crate::backend::wconfig::ConfigState;
27
28use super::policy::{
29 Action, Family, FocusReport, Input, NotifyKind, PolicyState, Preview, Request, Settings, ShutdownInfo, TrayState, When,
30};
31
32pub const EVENT_NOTIFICATION: &str = "notification";
33pub const EVENT_NOTIFICATION_RETRACT: &str = "notification:retract";
34pub const EVENT_NOTIFICATION_ACTIVATE: &str = "notification:activate";
35pub const EVENT_NOTIFICATION_STATE: &str = "notification:state";
38pub const EVENT_BLOCK_REVEAL: &str = "block:reveal";
41
42#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
44#[ts(export, export_to = "../../../frontend/types/rpc/")]
45pub struct NotificationRetractEvent {
46 pub id: String,
47 pub tag: String,
48}
49
50#[derive(Clone, Debug, serde::Serialize, ts_rs::TS)]
52#[ts(export, export_to = "../../../frontend/types/rpc/")]
53pub struct NotificationActivateEvent {
54 pub id: String,
55 pub block_id: String,
56 pub tab_id: String,
57 pub window_id: String,
58 pub workspace_id: Option<String>,
59 #[ts(type = "number")]
60 pub at_ms: i64,
61}
62
63#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, ts_rs::TS)]
65#[ts(export, export_to = "../../../frontend/types/rpc/")]
66pub struct BlockRevealEvent {
67 pub block_id: String,
68 pub tab_id: String,
69 pub window_id: String,
71 #[serde(default, skip_serializing_if = "Option::is_none")]
73 #[ts(optional)]
74 pub request_id: Option<String>,
75}
76
77#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct RevealAck {
80 pub ok: bool,
81 pub reason: Option<String>,
82}
83
84enum Internal {
87 Emit { kind: NotifyKind, block_id: String, body: Option<String>, own_blocks_only: bool, account_failure: bool },
93 InputWaiting { block_id: String, question: Option<String>, count: usize },
96 Resolve { block_id: String, family: Family },
99 TurnStatus { block_id: String, active: bool },
101 TurnStopped { block_id: String },
103 TurnEnded(LedgerEnd),
105}
106
107#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct LedgerEnd {
110 pub block_id: String,
111 pub turn_id: u64,
112 pub ended_at_ms: u64,
115 pub external: bool,
118 pub system: bool,
120}
121
122#[derive(serde::Deserialize)]
125struct PublishedLedger {
126 block_id: String,
127 turn_id: u64,
128 #[serde(default)]
129 ended_at_ms: Option<u64>,
130 #[serde(default)]
131 end: Option<TurnEnd>,
132 #[serde(default)]
133 trigger: Option<TurnTrigger>,
134}
135
136pub fn parse_ledger_end(d: &serde_json::Value) -> Option<LedgerEnd> {
139 let l = PublishedLedger::deserialize(d).ok()?;
140 if l.end != Some(TurnEnd::Completed) {
141 return None;
142 }
143 let kind = l.trigger.map(|t| t.kind);
144 Some(LedgerEnd {
145 block_id: l.block_id,
146 turn_id: l.turn_id,
147 ended_at_ms: l.ended_at_ms.unwrap_or(0),
148 external: kind.is_some_and(TriggerKind::is_external),
149 system: kind == Some(TriggerKind::System),
150 })
151}
152
153pub fn notify_turn_end(end: &LedgerEnd, external_turns: bool) -> bool {
156 !end.system && (!end.external || external_turns)
157}
158
159pub fn is_supervised_block(store: &Store, block_id: &str) -> bool {
162 store
163 .get::<Block>(block_id)
164 .ok()
165 .flatten()
166 .is_some_and(|b| crate::backend::supervisor::is_supervised(&b.meta))
167}
168
169const TURN_MAP_MAX: usize = 1024;
171
172#[derive(Debug, PartialEq, Eq)]
174pub enum TurnTransition {
175 Started,
177 Finished,
179 Nothing,
181}
182
183pub fn parse_turn_status(d: &serde_json::Value) -> Option<(String, bool)> {
189 let block_id = d.get("blockid")?.as_str()?.to_string();
190 let active = d.get("turn_active").and_then(|v| v.as_bool()).unwrap_or(false);
191 Some((block_id, active))
192}
193
194pub fn turn_transition(prev: Option<bool>, active: bool, stopped_recently: bool) -> TurnTransition {
197 match (prev, active) {
198 (Some(true), true) | (Some(false), false) => TurnTransition::Nothing,
199 (_, true) => TurnTransition::Started,
200 (Some(true), false) if !stopped_recently => TurnTransition::Finished,
201 _ => TurnTransition::Nothing,
202 }
203}
204
205pub const PENDING_ACTIVATION_MAX_AGE_MS: i64 = 30_000;
209
210#[derive(Clone, Debug, Default, PartialEq, Eq)]
214pub struct ClickTarget {
215 pub block_id: String,
216 pub tab_id: String,
217 pub workspace_id: Option<String>,
219 pub window_ids: Vec<String>,
222}
223
224pub fn resolve_click_target(store: &Store, block_id: &str) -> Option<ClickTarget> {
227 let block = store.get::<Block>(block_id).ok().flatten()?;
228 let tab_id = block.parentoref.strip_prefix("tab:")?.to_string();
229 store.get::<Tab>(&tab_id).ok().flatten()?;
230 let workspace_id = store
231 .get_all::<Workspace>()
232 .unwrap_or_default()
233 .into_iter()
234 .find(|w| w.tabids.contains(&tab_id) || w.pinnedtabids.contains(&tab_id))
235 .map(|w| w.oid);
236 let mut window_ids: Vec<String> = match &workspace_id {
237 Some(ws) => store
238 .get_all::<Window>()
239 .unwrap_or_default()
240 .into_iter()
241 .filter(|w| &w.workspaceid == ws)
242 .map(|w| w.oid)
243 .collect(),
244 None => Vec::new(),
245 };
246 window_ids.sort();
247 Some(ClickTarget { block_id: block_id.to_string(), tab_id, workspace_id, window_ids })
248}
249
250#[derive(Clone, Debug, Default, PartialEq, Eq)]
252pub struct AckOutcome {
253 pub known: bool,
256 pub window_id: Option<String>,
259 pub workspace_id: Option<String>,
261 pub has_window: bool,
263}
264
265#[derive(Clone, Debug, PartialEq, Eq)]
267pub struct PendingActivation {
268 pub block_id: String,
269 pub tab_id: String,
270 pub workspace_id: Option<String>,
271 pub at_ms: i64,
272}
273
274pub fn may_take_pending(pending: &PendingActivation, workspace_id: Option<&str>, now_ms: i64) -> bool {
277 if now_ms - pending.at_ms > PENDING_ACTIVATION_MAX_AGE_MS {
278 return false;
279 }
280 match (pending.workspace_id.as_deref(), workspace_id) {
281 (Some(want), Some(have)) => want == have,
282 _ => true,
283 }
284}
285
286fn pick_open_window(p: &PolicyState, window_ids: &[String]) -> Option<String> {
290 let raise = p.raise_window();
291 let open: Vec<&String> = window_ids.iter().filter(|w| p.window_open(w)).collect();
292 open.iter().find(|w| Some(w.as_str()) == raise.as_deref()).or(open.first()).map(|w| (*w).clone())
293}
294
295pub const CLOUD_SIGNED_OUT_BODY: &str =
297 "Agents won't get messages from other computers or GitHub until you sign in.";
298
299const AGENT_NAME_MAX: usize = 32;
300const BODY_MAX: usize = 80;
301const SUMMARY_MAX: usize = 90;
303
304pub struct Router {
305 policy: Mutex<PolicyState>,
306 broker: Arc<Broker>,
307 config: Arc<ConfigState>,
308 store: Arc<Store>,
309 pending_activation: Mutex<Vec<PendingActivation>>,
312 internal: tokio::sync::mpsc::UnboundedSender<Internal>,
313 last_tray: Mutex<Option<TrayState>>,
314 turn_active: Mutex<std::collections::HashMap<String, bool>>,
316 turn_started_ms: Mutex<std::collections::HashMap<String, i64>>,
319 notified_turns: Mutex<std::collections::HashSet<(String, u64, u64)>>,
321 reveal_waiters: Mutex<std::collections::HashMap<String, tokio::sync::oneshot::Sender<RevealAck>>>,
323}
324
325type Registry = Mutex<std::collections::HashMap<usize, Arc<Router>>>;
326static ROUTERS: OnceLock<Registry> = OnceLock::new();
327
328fn registry() -> &'static Registry {
329 ROUTERS.get_or_init(Default::default)
330}
331
332fn key(broker: &Arc<Broker>) -> usize {
333 Arc::as_ptr(broker) as usize
334}
335
336pub fn get(broker: &Arc<Broker>) -> Option<Arc<Router>> {
338 registry().lock().unwrap_or_else(|e| e.into_inner()).get(&key(broker)).cloned()
339}
340
341pub fn init(
347 broker: Arc<Broker>,
348 config: Arc<ConfigState>,
349 store: Arc<Store>,
350 reactive: &'static crate::backend::reactive::ReactiveHandler,
351) -> Arc<Router> {
352 let mut reg = registry().lock().unwrap_or_else(|e| e.into_inner());
353 reg.entry(key(&broker))
354 .or_insert_with(|| {
355 let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
356 let r = Arc::new(Router {
357 policy: Mutex::new(PolicyState::new()),
358 broker: broker.clone(),
359 config,
360 store,
361 pending_activation: Mutex::new(Vec::new()),
362 internal: tx,
363 last_tray: Mutex::new(None),
364 turn_active: Mutex::new(Default::default()),
365 turn_started_ms: Mutex::new(Default::default()),
366 notified_turns: Mutex::new(Default::default()),
367 reveal_waiters: Mutex::new(Default::default()),
368 });
369 spawn_ticker(Arc::downgrade(&r));
370 spawn_internal(Arc::downgrade(&r), rx);
371 attach_sources(&r, &broker, reactive);
372 r
373 })
374 .clone()
375}
376
377fn attach_sources(r: &Arc<Router>, broker: &Arc<Broker>, reactive: &'static crate::backend::reactive::ReactiveHandler) {
381 let tx = r.internal.clone();
382 broker.add_observer(Arc::new(move |ev: &MuxEvent| {
383 if ev.event == crate::backend::mps::EVENT_CONTROLLER_STATUS {
388 if let Some((block_id, active)) = ev.data.as_ref().and_then(parse_turn_status) {
394 let _ = tx.send(Internal::TurnStatus { block_id, active });
395 }
396 return;
397 }
398 if ev.event == crate::backend::mps::EVENT_AGENT_TURN {
401 if let Some(end) = ev.data.as_ref().and_then(parse_ledger_end) {
402 let _ = tx.send(Internal::TurnEnded(end));
403 }
404 return;
405 }
406 if ev.event != crate::backend::mps::EVENT_AGENT_FAILURE {
407 return;
408 }
409 let Some(block_id) = ev.scopes.iter().find_map(|s| s.strip_prefix("block:")) else { return };
410 let code = ev.data.as_ref().and_then(|d| d.get("code")).and_then(|c| c.as_str()).unwrap_or("");
411 if let Some(body) = failure_body(code) {
412 let _ = tx.send(Internal::Emit {
413 kind: NotifyKind::AgentCrashed,
414 block_id: block_id.to_string(),
415 body: Some(body.to_string()),
416 own_blocks_only: false,
418 account_failure: matches!(code, "usage_limit" | "auth"),
419 });
420 }
421 }));
422 let tx = r.internal.clone();
423 reactive.add_needs_review_hook(Arc::new(move |block_id: &str| {
424 let _ = tx.send(Internal::Emit {
425 kind: NotifyKind::MessageNeedsReview,
426 block_id: block_id.to_string(),
427 body: Some("Open AgentMux to see the sender and trust level before it acts.".to_string()),
430 own_blocks_only: true,
431 account_failure: false,
432 });
433 }));
434}
435
436fn spawn_internal(r: std::sync::Weak<Router>, mut rx: tokio::sync::mpsc::UnboundedReceiver<Internal>) {
437 if tokio::runtime::Handle::try_current().is_err() {
438 return;
439 }
440 tokio::spawn(async move {
441 while let Some(msg) = rx.recv().await {
442 let Some(r) = r.upgrade() else { return };
443 match msg {
444 Internal::Emit { kind, block_id, body, own_blocks_only, account_failure } => {
445 let _ = tokio::task::spawn_blocking(move || {
447 if own_blocks_only && !r.owns_block(&block_id) {
448 return;
449 }
450 if account_failure && crate::backend::account_availability::covers_block(&block_id) {
453 return;
454 }
455 r.emit_fixed(kind, &block_id, body)
456 })
457 .await;
458 }
459 Internal::InputWaiting { block_id, question, count } => {
460 let _ = tokio::task::spawn_blocking(move || {
461 r.emit(NotifyKind::InputWaiting, &block_id, question.as_deref(), count)
462 })
463 .await;
464 }
465 Internal::Resolve { block_id, family } => r.resolve(&block_id, family),
466 Internal::TurnEnded(end) => {
467 {
468 let mut notified = r.notified_turns.lock().unwrap_or_else(|e| e.into_inner());
469 if notified.len() > TURN_MAP_MAX {
473 notified.clear();
474 }
475 if !notified.insert((end.block_id.clone(), end.turn_id, end.ended_at_ms)) {
476 continue;
477 }
478 }
479 let stopped_recently = crate::backend::user_stop::stopped_recently(&end.block_id);
480 if stopped_recently || !notify_turn_end(&end, r.settings().external_turns) {
481 continue;
482 }
483 let block_id = end.block_id;
484 let _ = tokio::task::spawn_blocking(move || {
485 if is_supervised_block(&r.store, &block_id) {
489 return;
490 }
491 if crate::backend::account_availability::covers_block(&block_id) {
494 return;
495 }
496 r.emit(NotifyKind::TurnCompleted, &block_id, None, 0)
497 })
498 .await;
499 }
500 Internal::TurnStopped { block_id } => {
501 crate::backend::user_stop::note_user_stop(&block_id);
505 r.resolve(&block_id, Family::Turn)
506 }
507 Internal::TurnStatus { block_id, active } => r.on_turn_status(&block_id, active),
508 }
509 }
510 });
511}
512
513pub fn failure_body(code: &str) -> Option<&'static str> {
520 Some(match code {
521 "rate_limited" => "Hit a rate limit.",
522 "overloaded" => "The model provider is overloaded.",
523 "usage_limit" => "Reached its usage limit.",
524 "auth" => "Needs you to sign in again.",
525 "context_exceeded" => "Ran out of context.",
526 "max_turns" => "Reached its turn limit.",
527 "network" => "Lost its network connection.",
528 "spawn_failure" => "Couldn't start.",
529 "no_output" | "unknown_non_zero" => "Exited unexpectedly.",
530 "killed" => "Was stopped by the system (possibly out of memory).",
531 _ => return None,
532 })
533}
534
535fn spawn_ticker(r: std::sync::Weak<Router>) {
536 if tokio::runtime::Handle::try_current().is_err() {
539 return;
540 }
541 tokio::spawn(async move {
542 let mut iv = tokio::time::interval(std::time::Duration::from_millis(500));
543 loop {
544 iv.tick().await;
545 match r.upgrade() {
546 Some(r) => {
547 r.step(Input::Tick);
548 }
549 None => return,
550 }
551 }
552 });
553}
554
555pub use agentmux_common::time::now_ms;
556
557pub fn sanitize_name(raw: &str) -> String {
560 let cleaned: String = raw
561 .chars()
562 .filter(|c| !c.is_control() && !is_bidi_control(*c))
563 .collect();
564 let trimmed = cleaned.trim();
565 let mut out: String = trimmed.chars().take(AGENT_NAME_MAX).collect();
566 if out.is_empty() {
567 out = "An agent".to_string();
568 }
569 out
570}
571
572pub(crate) fn is_bidi_control(c: char) -> bool {
573 matches!(c, '\u{200E}' | '\u{200F}' | '\u{061C}' | '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')
574}
575
576pub fn sanitize_summary(raw: &str) -> Option<String> {
581 if crate::backend::reactive::sanitize::is_sensitive_message(raw) {
582 return None;
583 }
584 let cleaned: String = raw
585 .chars()
586 .filter(|c| !is_bidi_control(*c))
587 .map(|c| if c.is_control() { ' ' } else { c })
588 .collect();
589 let line = cleaned.split_whitespace().collect::<Vec<_>>().join(" ");
590 if line.is_empty() {
591 return None;
592 }
593 let mut out: String = line.chars().take(SUMMARY_MAX).collect();
594 if line.chars().count() > SUMMARY_MAX {
595 out.push('…');
596 }
597 Some(out)
598}
599
600pub fn with_question_count(body: Option<String>, count: usize) -> Option<String> {
604 body.map(|b| if count > 1 { format!("{b} (+{} more)", count - 1) } else { b })
605}
606
607pub fn redact_body(raw: &str, preview: Preview) -> Option<String> {
611 if preview == Preview::None {
612 return None;
613 }
614 let max = if preview == Preview::Full { 200 } else { BODY_MAX };
615 let first = raw.lines().map(str::trim).find(|l| !l.is_empty())?;
616 if crate::backend::reactive::sanitize::is_sensitive_message(raw) {
617 return Some("Contains sensitive content — open AgentMux to view.".to_string());
618 }
619 let cleaned: String = first.chars().filter(|c| !c.is_control() && !is_bidi_control(*c)).collect();
620 let mut out: String = cleaned.chars().take(max).collect();
621 if cleaned.chars().count() > max {
622 out.push('…');
623 }
624 Some(out)
625}
626
627pub fn quiet_hours_until(spec: &str, now: chrono::DateTime<chrono::Local>) -> Option<i64> {
632 use chrono::{NaiveTime, TimeZone};
633 let (a, b) = spec.trim().split_once('-')?;
634 let start = NaiveTime::parse_from_str(a.trim(), "%H:%M").ok()?;
635 let end = NaiveTime::parse_from_str(b.trim(), "%H:%M").ok()?;
636 if start == end {
637 return None;
638 }
639 let t = now.time();
640 let today = now.date_naive();
641 let end_date = if start < end {
642 if !(t >= start && t < end) {
643 return None;
644 }
645 today
646 } else if t >= start {
647 today + chrono::Days::new(1)
648 } else if t < end {
649 today
650 } else {
651 return None;
652 };
653 chrono::Local
654 .from_local_datetime(&end_date.and_time(end))
655 .earliest()
656 .map(|dt| dt.timestamp_millis())
657}
658
659fn setting_bool(extra: &std::collections::HashMap<String, serde_json::Value>, key: &str, default: bool) -> bool {
660 extra.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
661}
662
663fn setting_str<'a>(extra: &'a std::collections::HashMap<String, serde_json::Value>, key: &str) -> Option<&'a str> {
664 extra.get(key).and_then(|v| v.as_str())
665}
666
667pub fn settings_from_extra(extra: &std::collections::HashMap<String, serde_json::Value>) -> Settings {
669 let mut s = Settings {
670 enabled: setting_bool(extra, "notify:os:enabled", true),
671 when: match setting_str(extra, "notify:os:when") {
672 Some("always") => When::Always,
673 Some("never") => When::Never,
674 _ => When::Unfocused,
675 },
676 preview: match setting_str(extra, "notify:os:preview") {
677 Some("full") => Preview::Full,
678 Some("none") => Preview::None,
679 _ => Preview::Redacted,
680 },
681 kind_enabled: Default::default(),
682 pause_until_ms: extra.get("notify:pause:until").and_then(|v| v.as_i64()).unwrap_or(0),
683 pause_allow_attention: setting_bool(extra, "notify:pause:allowattention", false),
684 quiet_until_ms: setting_str(extra, "notify:quiethours")
685 .and_then(|spec| quiet_hours_until(spec, chrono::Local::now()))
686 .unwrap_or(0),
687 show_summary: setting_bool(extra, "notify:os:summary", true),
688 external_turns: setting_bool(extra, "notify:os:turncompleted:external", false),
689 };
690 for kind in [
691 NotifyKind::InputWaiting,
692 NotifyKind::TurnCompleted,
693 NotifyKind::TurnErrored,
694 NotifyKind::AgentCrashed,
695 NotifyKind::MessageNeedsReview,
696 NotifyKind::CloudSignedOut,
697 NotifyKind::AccountUnavailable,
698 NotifyKind::JobFailed,
699 NotifyKind::VaultExpiring,
700 ] {
701 if let Some(sfx) = kind.setting_suffix() {
702 s.kind_enabled.insert(kind, setting_bool(extra, &format!("notify:os:{sfx}"), true));
703 }
704 }
705 s
706}
707
708impl Router {
709 fn settings(&self) -> Settings {
710 settings_from_extra(&self.config.get_settings().extra)
711 }
712
713 pub fn holds_back_attention(&self) -> bool {
716 let s = self.settings();
717 agentmux_common::time::now_ms() < s.pause_until_ms.max(s.quiet_until_ms) && !s.pause_allow_attention
718 }
719
720 pub fn external_turns_notified(&self) -> bool {
724 self.settings().external_turns
725 }
726
727 fn owns_block(&self, block_id: &str) -> bool {
729 matches!(self.store.get::<Block>(block_id), Ok(Some(_)))
730 }
731
732 fn block_labels(&self, block_id: &str) -> (String, Option<String>) {
740 let block = self.store.get::<Block>(block_id).ok().flatten();
741 let meta = |key: &str| {
742 block.as_ref().map(|b| crate::backend::obj::meta_get_string(&b.meta, key, "")).unwrap_or_default()
743 };
744 let mut raw_name = meta("agentName");
745 if raw_name.is_empty() {
746 raw_name = meta("agentId");
747 }
748 let turn_started = self.turn_started_ms.lock().unwrap_or_else(|e| e.into_inner()).get(block_id).copied();
751 let summary = block.as_ref().and_then(|b| super::toast_line::of_block(b, turn_started, now_ms()));
752 let name = match block.as_ref().filter(|_| raw_name.trim().is_empty()) {
755 Some(b) => super::pane_label::pane_label(&b.meta),
756 None => sanitize_name(&raw_name),
757 };
758 (name, summary)
759 }
760
761 fn on_turn_status(&self, block_id: &str, active: bool) {
764 let prev = {
765 let mut turns = self.turn_active.lock().unwrap_or_else(|e| e.into_inner());
766 if turns.len() > TURN_MAP_MAX {
769 turns.retain(|_, active| *active);
770 }
771 turns.insert(block_id.to_string(), active)
772 };
773 let stopped_recently = crate::backend::user_stop::stopped_recently(block_id);
774 match turn_transition(prev, active, stopped_recently) {
775 TurnTransition::Started => {
776 crate::backend::user_stop::forget(block_id);
779 {
780 let mut starts = self.turn_started_ms.lock().unwrap_or_else(|e| e.into_inner());
781 if starts.len() > TURN_MAP_MAX {
782 starts.clear();
783 }
784 starts.insert(block_id.to_string(), now_ms());
785 }
786 self.resolve(block_id, Family::Turn)
787 }
788 TurnTransition::Finished => {}
792 TurnTransition::Nothing => {}
793 }
794 }
795
796 fn step(&self, input: Input) -> Vec<Action> {
799 let settings = self.settings();
800 let now = now_ms();
801 let (actions, tray) = {
802 let mut p = self.policy.lock().unwrap_or_else(|e| e.into_inner());
803 let actions = p.step(input, now, &settings);
804 (actions, p.tray_state(&settings, now))
805 };
806 for a in &actions {
807 self.publish(a);
808 }
809 self.publish_tray_if_changed(tray);
810 actions
811 }
812
813 fn publish_tray_if_changed(&self, tray: TrayState) {
814 {
815 let mut last = self.last_tray.lock().unwrap_or_else(|e| e.into_inner());
816 if last.as_ref() == Some(&tray) {
817 return;
818 }
819 *last = Some(tray.clone());
820 }
821 self.broker.publish_event::<crate::backend::mps_events::NotificationState>(&tray, vec![], 1);
822 }
823
824 fn publish(&self, action: &Action) {
825 match action {
826 Action::Show(n) => self.publish_event::<crate::backend::mps_events::Notification>(n),
827 Action::Retract { id, tag } => {
828 self.publish_event::<crate::backend::mps_events::NotificationRetract>(&NotificationRetractEvent { id: id.clone(), tag: tag.clone() })
829 }
830 Action::Activate { .. } => {}
832 }
833 }
834
835 fn publish_event<E: crate::backend::mps_events::Event>(&self, payload: &E::Payload) {
836 tracing::info!(event = E::NAME, "notify: publish");
837 self.broker.publish_event::<E>(payload, vec![], 0);
838 }
839
840 pub fn emit(&self, kind: NotifyKind, block_id: &str, question: Option<&str>, question_count: usize) {
849 let preview = self.settings().preview;
850 let body = match kind {
851 NotifyKind::InputWaiting => {
852 with_question_count(question.and_then(|q| redact_body(q, preview)), question_count)
853 }
854 _ => None,
855 };
856 let (agent_name, summary) = self.block_labels(block_id);
857 self.step(Input::Emit(Request { kind, block_id: block_id.to_string(), agent_name, body, summary, shutdown: None }));
858 }
859
860 pub fn emit_fixed(&self, kind: NotifyKind, block_id: &str, body: Option<String>) {
864 let (agent_name, summary) = self.block_labels(block_id);
865 self.step(Input::Emit(Request { kind, block_id: block_id.to_string(), agent_name, body, summary, shutdown: None }));
866 }
867
868 pub fn emit_shutdown(&self, block_id: &str, body: Option<String>, info: ShutdownInfo) {
873 let (agent_name, summary) = self.block_labels(block_id);
874 self.step(Input::Emit(Request {
875 kind: NotifyKind::ShutdownPending,
876 block_id: block_id.to_string(),
877 agent_name,
878 body,
879 summary,
880 shutdown: Some(info),
881 }));
882 }
883
884 pub fn emit_group(&self, block_id: &str, what: &str, body: Option<String>, info: ShutdownInfo) {
889 self.step(Input::Emit(Request {
890 kind: NotifyKind::ShutdownPending,
891 block_id: block_id.to_string(),
892 agent_name: sanitize_name(what),
893 body,
894 summary: None,
895 shutdown: Some(info),
896 }));
897 }
898
899 pub fn live_by_id(&self, id: &str) -> Option<(NotifyKind, String, Option<String>)> {
902 self.policy.lock().unwrap_or_else(|e| e.into_inner()).live_by_id(id)
903 }
904
905 pub fn input_waiting_nonblocking(&self, block_id: &str, question: Option<String>, count: usize) {
909 let _ = self.internal.send(Internal::InputWaiting { block_id: block_id.to_string(), question, count });
910 }
911
912 pub fn turn_stopped_nonblocking(&self, block_id: &str) {
916 let _ = self.internal.send(Internal::TurnStopped { block_id: block_id.to_string() });
917 }
918
919 pub fn resolve_nonblocking(&self, block_id: &str, family: Family) {
922 let _ = self.internal.send(Internal::Resolve { block_id: block_id.to_string(), family });
923 }
924
925 pub fn resolve(&self, block_id: &str, family: Family) {
926 self.step(Input::Resolve { block_id: block_id.to_string(), family });
927 }
928
929 pub fn test(&self) {
930 self.step(Input::Emit(Request {
931 kind: NotifyKind::Test,
932 block_id: String::new(),
933 agent_name: String::new(),
934 body: Some("You'll see alerts like this when an agent needs you.".to_string()),
935 summary: None,
936 shutdown: None,
937 }));
938 }
939
940 pub fn account_unavailable(&self, key: &str, body: String) {
945 self.step(Input::Emit(Request {
946 kind: NotifyKind::AccountUnavailable,
947 block_id: key.to_string(),
948 agent_name: String::new(),
949 body: Some(body),
950 summary: None,
951 shutdown: None,
952 }));
953 }
954
955 pub fn job_failed(&self, key: &str, job_name: &str, body: String) {
960 self.step(Input::Emit(Request {
961 kind: NotifyKind::JobFailed,
962 block_id: key.to_string(),
963 agent_name: sanitize_name(job_name),
964 body: Some(body),
965 summary: None,
966 shutdown: None,
967 }));
968 }
969
970 pub fn vault_expiring(&self, key: &str, label: &str, body: String) {
974 self.step(Input::Emit(Request {
975 kind: NotifyKind::VaultExpiring,
976 block_id: key.to_string(),
977 agent_name: sanitize_name(label),
978 body: Some(body),
979 summary: None,
980 shutdown: None,
981 }));
982 }
983
984 pub fn drone_note(&self, key: &str, title: &str, body: String) {
989 self.step(Input::Emit(Request {
990 kind: NotifyKind::DroneNote,
991 block_id: key.to_string(),
992 agent_name: sanitize_name(title),
993 body: Some(body),
994 summary: None,
995 shutdown: None,
996 }));
997 }
998
999 pub fn cloud_signed_out(&self) {
1003 self.step(Input::Emit(Request {
1004 kind: NotifyKind::CloudSignedOut,
1005 block_id: String::new(),
1006 agent_name: String::new(),
1007 body: Some(CLOUD_SIGNED_OUT_BODY.to_string()),
1008 summary: None,
1009 shutdown: None,
1010 }));
1011 }
1012
1013 pub fn app_focused(&self) -> bool {
1015 self.policy.lock().unwrap_or_else(|e| e.into_inner()).app_focused()
1016 }
1017
1018 pub fn last_window(&self) -> Option<String> {
1020 self.policy.lock().unwrap_or_else(|e| e.into_inner()).raise_window()
1021 }
1022
1023 pub fn focus(&self, conn_id: &str, report: FocusReport) {
1024 self.step(Input::Focus { conn_id: conn_id.to_string(), report });
1025 }
1026
1027 pub fn disconnect(&self, conn_id: &str) {
1028 self.step(Input::Disconnect { conn_id: conn_id.to_string() });
1029 }
1030
1031 pub fn ack(&self, id: &str, clicked: bool) -> AckOutcome {
1040 let actions = self.step(Input::Ack { id: id.to_string(), clicked });
1041 let known = !actions.is_empty();
1043 let activated = actions.into_iter().find_map(|a| match a {
1044 Action::Activate { id, block_id } => Some((id, block_id)),
1045 _ => None,
1046 });
1047 let target = activated.as_ref().and_then(|(_, block_id)| resolve_click_target(&self.store, block_id));
1048 let (open_window, raise, any_window) = {
1049 let p = self.policy.lock().unwrap_or_else(|e| e.into_inner());
1050 let pick = target.as_ref().and_then(|t| pick_open_window(&p, &t.window_ids));
1051 (pick, p.raise_window(), p.has_window())
1052 };
1053 let mut outcome = AckOutcome { known, window_id: None, workspace_id: None, has_window: any_window };
1054 match (activated, target) {
1055 (Some((id, _)), Some(t)) => {
1056 if let Some(window_id) = open_window {
1057 let activate = NotificationActivateEvent {
1058 id,
1059 block_id: t.block_id,
1060 tab_id: t.tab_id,
1061 window_id: window_id.clone(),
1062 workspace_id: t.workspace_id,
1063 at_ms: now_ms(),
1064 };
1065 self.publish_event::<crate::backend::mps_events::NotificationActivate>(&activate);
1066 outcome.window_id = Some(window_id);
1067 outcome.has_window = true;
1068 } else {
1069 tracing::info!(workspace = ?t.workspace_id, "notify: click target's workspace is open in no window");
1070 outcome.workspace_id = t.workspace_id.clone();
1071 outcome.has_window = false;
1072 self.park_activation(PendingActivation {
1073 block_id: t.block_id,
1074 tab_id: t.tab_id,
1075 workspace_id: t.workspace_id,
1076 at_ms: now_ms(),
1077 });
1078 }
1079 }
1080 (Some((_, block_id)), None) => {
1081 tracing::info!(block_id, "notify: click target is gone; raising the app");
1082 outcome.window_id = raise;
1083 }
1084 (None, _) if clicked => outcome.window_id = raise,
1086 (None, _) => {}
1087 }
1088 outcome
1089 }
1090
1091 pub fn reveal_target(&self, block_id: &str) -> Option<BlockRevealEvent> {
1098 let t = resolve_click_target(&self.store, block_id)?;
1099 let window_id = {
1100 let p = self.policy.lock().unwrap_or_else(|e| e.into_inner());
1101 pick_open_window(&p, &t.window_ids)
1102 }?;
1103 Some(BlockRevealEvent { block_id: t.block_id, tab_id: t.tab_id, window_id, request_id: None })
1104 }
1105
1106 pub fn expect_reveal_ack(&self, request_id: &str) -> tokio::sync::oneshot::Receiver<RevealAck> {
1108 let (tx, rx) = tokio::sync::oneshot::channel();
1109 self.reveal_waiters.lock().unwrap_or_else(|e| e.into_inner()).insert(request_id.to_string(), tx);
1110 rx
1111 }
1112
1113 pub fn forget_reveal_ack(&self, request_id: &str) {
1115 self.reveal_waiters.lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
1116 }
1117
1118 pub fn reveal_acked(&self, request_id: &str, ack: RevealAck) -> bool {
1120 let tx = self.reveal_waiters.lock().unwrap_or_else(|e| e.into_inner()).remove(request_id);
1121 tx.is_some_and(|tx| tx.send(ack).is_ok())
1122 }
1123
1124 pub fn park_activation_for_closed_workspace(&self, block_id: &str) -> Option<String> {
1131 let t = resolve_click_target(&self.store, block_id)?;
1132 let workspace_id = t.workspace_id.clone()?;
1133 self.park_activation(PendingActivation { block_id: t.block_id, tab_id: t.tab_id, workspace_id: t.workspace_id, at_ms: now_ms() });
1134 Some(workspace_id)
1135 }
1136
1137 pub fn park_activation(&self, pending: PendingActivation) {
1141 let mut parked = self.pending_activation.lock().unwrap_or_else(|e| e.into_inner());
1142 parked.retain(|p| now_ms() - p.at_ms <= PENDING_ACTIVATION_MAX_AGE_MS && p.workspace_id != pending.workspace_id);
1143 parked.push(pending);
1144 }
1145
1146 pub fn publish_block_reveal(&self, target: &BlockRevealEvent) {
1148 self.publish_event::<crate::backend::mps_events::BlockReveal>(target);
1149 }
1150
1151 pub fn take_pending_activation(&self, workspace_id: Option<&str>) -> Option<PendingActivation> {
1155 let mut parked = self.pending_activation.lock().unwrap_or_else(|e| e.into_inner());
1156 let now = now_ms();
1157 parked.retain(|p| now - p.at_ms <= PENDING_ACTIVATION_MAX_AGE_MS);
1158 let at = parked.iter().position(|p| may_take_pending(p, workspace_id, now))?;
1159 Some(parked.remove(at))
1160 }
1161}
1162
1163#[cfg(test)]
1164mod tests {
1165
1166 fn ledger(end: Option<&str>, kind: &str) -> serde_json::Value {
1169 let mut v = serde_json::json!({ "block_id": "b1", "turn_id": 42, "ended_at_ms": 7, "active": false, "trigger": { "kind": kind } });
1170 if let Some(e) = end {
1171 v["end"] = serde_json::json!(e);
1172 }
1173 v
1174 }
1175
1176 #[test]
1177 fn only_a_completed_turn_is_an_end() {
1178 assert_eq!(
1179 parse_ledger_end(&ledger(Some("completed"), "user")),
1180 Some(LedgerEnd { block_id: "b1".into(), turn_id: 42, ended_at_ms: 7, external: false, system: false })
1181 );
1182 assert_eq!(parse_ledger_end(&ledger(None, "user")), None, "running or settling");
1183 assert_eq!(parse_ledger_end(&ledger(Some("exited"), "user")), None, "a crash reports itself");
1184 }
1185
1186 #[test]
1187 fn a_turn_something_else_started_is_notified_only_when_asked() {
1188 for kind in ["agent", "service", "schedule", "task", "supervisor"] {
1189 let end = parse_ledger_end(&ledger(Some("completed"), kind)).unwrap();
1190 assert!(end.external, "{kind}");
1191 assert!(!notify_turn_end(&end, false), "{kind}: quiet by default");
1192 assert!(notify_turn_end(&end, true), "{kind}: notified when asked");
1193 }
1194 for kind in ["user", "broadcast"] {
1195 assert!(notify_turn_end(&parse_ledger_end(&ledger(Some("completed"), kind)).unwrap(), false), "{kind}");
1196 }
1197 let system = parse_ledger_end(&ledger(Some("completed"), "system")).unwrap();
1198 assert!(!notify_turn_end(&system, true), "AgentMux's own hidden turn, never");
1199 }
1200
1201 #[test]
1202 fn a_rejoined_turn_s_second_end_is_a_new_end() {
1203 let first = parse_ledger_end(&ledger(Some("completed"), "user")).unwrap();
1204 let mut again = ledger(Some("completed"), "user");
1205 again["ended_at_ms"] = serde_json::json!(99);
1206 let second = parse_ledger_end(&again).unwrap();
1207 assert_eq!(first.turn_id, second.turn_id);
1208 assert_ne!((first.turn_id, first.ended_at_ms), (second.turn_id, second.ended_at_ms), "a dedupe key that tells them apart");
1209 }
1210
1211 #[test]
1212 fn the_external_turns_setting_is_off_unless_set() {
1213 let mut extra = std::collections::HashMap::new();
1214 assert!(!settings_from_extra(&extra).external_turns);
1215 extra.insert("notify:os:turncompleted:external".to_string(), serde_json::json!(true));
1216 assert!(settings_from_extra(&extra).external_turns);
1217 }
1218
1219 use super::*;
1220
1221 #[test]
1222 fn name_sanitization_strips_bidi_and_controls_and_caps() {
1223 assert_eq!(sanitize_name("lark"), "lark");
1224 assert_eq!(sanitize_name("evil\u{202E}txt.exe"), "eviltxt.exe");
1225 assert_eq!(sanitize_name("a\nb\tc"), "abc");
1226 assert_eq!(sanitize_name(" "), "An agent");
1227 assert_eq!(sanitize_name(&"x".repeat(100)).chars().count(), AGENT_NAME_MAX);
1228 }
1229
1230 #[test]
1233 fn parses_real_serialized_controller_status_including_omitted_false() {
1234 use crate::backend::blockcontroller::BlockControllerRuntimeStatus;
1235 let mk = |turn_active: bool| BlockControllerRuntimeStatus {
1236 durable: false,
1237 blockid: "b1".into(),
1238 version: 1,
1239 shellprocstatus: "running".into(),
1240 shellprocconnname: "local".into(),
1241 shellprocexitcode: 0,
1242 shellprocpid: None,
1243 shellprocname: String::new(),
1244 spawn_ts_ms: None,
1245 is_agent_pane: false,
1246 turn_active,
1247 };
1248 let started = serde_json::to_value(mk(true)).unwrap();
1249 let ended = serde_json::to_value(mk(false)).unwrap();
1250 assert!(ended.get("turn_active").is_none(), "precondition: false is omitted on the wire");
1251 assert_eq!(parse_turn_status(&started), Some(("b1".to_string(), true)));
1252 assert_eq!(parse_turn_status(&ended), Some(("b1".to_string(), false)));
1253 assert_eq!(parse_turn_status(&serde_json::json!({"turn_active": true})), None);
1254 let (_, a) = parse_turn_status(&started).unwrap();
1256 let (_, b) = parse_turn_status(&ended).unwrap();
1257 assert_eq!(turn_transition(None, a, false), TurnTransition::Started);
1258 assert_eq!(turn_transition(Some(a), b, false), TurnTransition::Finished);
1259 }
1260
1261 #[test]
1262 fn turn_transitions_come_only_from_real_flips() {
1263 use TurnTransition::*;
1264 assert_eq!(turn_transition(None, false, false), Nothing);
1266 assert_eq!(turn_transition(None, true, false), Started);
1267 assert_eq!(turn_transition(Some(true), false, false), Finished);
1269 assert_eq!(turn_transition(Some(true), false, true), Nothing);
1271 assert_eq!(turn_transition(Some(true), true, false), Nothing);
1273 assert_eq!(turn_transition(Some(false), false, false), Nothing);
1274 assert_eq!(turn_transition(Some(false), true, false), Started);
1276 }
1277
1278 #[test]
1279 fn quiet_hours_windows() {
1280 use chrono::TimeZone;
1281 let at = |h, m| chrono::Local.with_ymd_and_hms(2026, 9, 24, h, m, 0).unwrap();
1282 let ms = |d: u32, h, m| chrono::Local.with_ymd_and_hms(2026, 9, d, h, m, 0).unwrap().timestamp_millis();
1283 assert_eq!(quiet_hours_until("22:00-08:00", at(23, 30)), Some(ms(25, 8, 0)));
1285 assert_eq!(quiet_hours_until("22:00-08:00", at(6, 0)), Some(ms(24, 8, 0)));
1286 assert_eq!(quiet_hours_until("22:00-08:00", at(12, 0)), None);
1287 assert_eq!(quiet_hours_until("22:00-08:00", at(8, 0)), None, "end is exclusive");
1288 assert_eq!(quiet_hours_until("12:00-13:30", at(12, 45)), Some(ms(24, 13, 30)));
1290 assert_eq!(quiet_hours_until("12:00-13:30", at(14, 0)), None);
1291 assert_eq!(quiet_hours_until("", at(12, 0)), None);
1293 assert_eq!(quiet_hours_until("09:00-09:00", at(9, 0)), None);
1294 assert_eq!(quiet_hours_until("nonsense", at(12, 0)), None);
1295 assert_eq!(quiet_hours_until("25:00-08:00", at(1, 0)), None);
1296 }
1297
1298 #[test]
1299 fn failure_classes_map_to_fixed_bodies_and_skip_user_deletes() {
1300 assert_eq!(failure_body("auth"), Some("Needs you to sign in again."));
1301 assert_eq!(failure_body("unknown_non_zero"), Some("Exited unexpectedly."));
1302 assert_eq!(failure_body("killed"), Some("Was stopped by the system (possibly out of memory)."));
1303 assert_eq!(failure_body("agent_deleted"), None);
1304 assert_eq!(failure_body("<script>"), None);
1305 }
1306
1307 #[test]
1308 fn pending_activation_is_scoped_to_its_workspace_and_expires() {
1309 let p = PendingActivation { block_id: "b".into(), tab_id: "t".into(), workspace_id: Some("ws1".into()), at_ms: 1_000 };
1310 assert!(may_take_pending(&p, Some("ws1"), 2_000));
1311 assert!(!may_take_pending(&p, Some("ws2"), 2_000), "another workspace's window must not steal it");
1312 assert!(may_take_pending(&p, None, 2_000), "an older frontend doesn't say");
1313 assert!(may_take_pending(&p, Some("ws1"), 1_000 + PENDING_ACTIVATION_MAX_AGE_MS));
1314 assert!(!may_take_pending(&p, Some("ws1"), 1_001 + PENDING_ACTIVATION_MAX_AGE_MS), "30 s, then gone");
1315 let orphan = PendingActivation { workspace_id: None, ..p };
1316 assert!(may_take_pending(&orphan, Some("ws2"), 2_000));
1317 }
1318
1319 #[test]
1320 fn click_target_walks_block_to_tab_workspace_and_windows() {
1321 let store = Store::open_in_memory().unwrap();
1322 crate::backend::wcore::ensure_initial_data(&store).unwrap();
1323 let block = store.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
1324 let t = resolve_click_target(&store, &block.oid).expect("resolves");
1325 let ws = store.get_all::<Workspace>().unwrap().into_iter().next().unwrap();
1326 let win = store.get_all::<Window>().unwrap().into_iter().next().unwrap();
1327 assert_eq!(t.workspace_id.as_deref(), Some(ws.oid.as_str()));
1328 assert!(ws.tabids.contains(&t.tab_id) || ws.pinnedtabids.contains(&t.tab_id));
1329 assert_eq!(t.window_ids, vec![win.oid]);
1330 assert_eq!(resolve_click_target(&store, "gone"), None);
1331 }
1332
1333 #[test]
1336 fn a_supervised_pane_is_left_to_the_supervisor() {
1337 crate::backend::supervisor::settings::set_enabled_for_test(true);
1338 let store = Store::open_in_memory().unwrap();
1339 crate::backend::wcore::ensure_initial_data(&store).unwrap();
1340 let mut block = store.get_all::<Block>().unwrap().into_iter().next().expect("seeded block");
1341 assert!(!is_supervised_block(&store, &block.oid), "a pane with no mode");
1342 for (k, v) in [("agentProvider", "claude"), ("agentOutputFormat", "claude-stream-json"), ("supervisor:mode", "drive")] {
1343 block.meta.insert(k.into(), serde_json::json!(v));
1344 }
1345 store.update(&mut block).unwrap();
1346 assert!(is_supervised_block(&store, &block.oid));
1347 block.meta.insert("agentProvider".into(), serde_json::json!("codex"));
1348 store.update(&mut block).unwrap();
1349 assert!(!is_supervised_block(&store, &block.oid), "the Supervisor can't watch it");
1350 assert!(!is_supervised_block(&store, "gone"));
1351 }
1352
1353 #[test]
1354 fn body_redaction() {
1355 assert_eq!(redact_body("\n Which branch?\nmore", Preview::Redacted).as_deref(), Some("Which branch?"));
1356 assert_eq!(redact_body("Paste your API token here", Preview::Redacted).as_deref(),
1357 Some("Contains sensitive content — open AgentMux to view."));
1358 assert_eq!(redact_body("ok", Preview::None), None);
1359 let long = "y".repeat(300);
1360 assert_eq!(redact_body(&long, Preview::Redacted).unwrap().chars().count(), BODY_MAX + 1);
1361 assert_eq!(redact_body(&long, Preview::Full).unwrap().chars().count(), 201);
1362 assert_eq!(redact_body(" \n ", Preview::Redacted), None);
1363 }
1364
1365 #[test]
1366 fn summary_sanitization() {
1367 assert_eq!(sanitize_summary("Fix resize repaint delay").as_deref(), Some("Fix resize repaint delay"));
1368 assert_eq!(sanitize_summary(" two\nlines\tand spaces ").as_deref(), Some("two lines and spaces"));
1369 assert_eq!(sanitize_summary("evil\u{202E}gnp.exe").as_deref(), Some("evilgnp.exe"));
1370 assert_eq!(sanitize_summary(" "), None);
1371 assert_eq!(sanitize_summary(""), None);
1372 assert_eq!(sanitize_summary("Rotate the api_key for staging"), None);
1374 let long = "word ".repeat(40);
1375 let s = sanitize_summary(&long).unwrap();
1376 assert_eq!(s.chars().count(), SUMMARY_MAX + 1);
1377 assert!(s.ends_with('…'));
1378 }
1379
1380 #[test]
1381 fn question_count_suffix_survives_truncation() {
1382 let long = "q".repeat(300);
1383 let body = with_question_count(redact_body(&long, Preview::Redacted), 3).unwrap();
1384 assert!(body.ends_with("… (+2 more)"), "{body}");
1385 assert_eq!(with_question_count(Some("Which branch?".into()), 1).as_deref(), Some("Which branch?"));
1386 assert_eq!(with_question_count(Some("Which branch?".into()), 0).as_deref(), Some("Which branch?"));
1387 assert_eq!(with_question_count(None, 4), None, "no text → the title stands alone");
1388 }
1389
1390 #[test]
1391 fn settings_defaults_and_overrides() {
1392 let mut extra = std::collections::HashMap::new();
1393 let s = settings_from_extra(&extra);
1394 assert!(s.enabled);
1395 assert!(s.show_summary);
1396 assert_eq!(s.when, When::Unfocused);
1397 assert_eq!(s.preview, Preview::Redacted);
1398 extra.insert("notify:os:when".into(), serde_json::json!("never"));
1399 extra.insert("notify:os:preview".into(), serde_json::json!("none"));
1400 extra.insert("notify:os:turncompleted".into(), serde_json::json!(false));
1401 extra.insert("notify:os:enabled".into(), serde_json::json!(false));
1402 extra.insert("notify:pause:until".into(), serde_json::json!(1234));
1403 extra.insert("notify:os:agentcrashed".into(), serde_json::json!(false));
1404 extra.insert("notify:os:summary".into(), serde_json::json!(false));
1405 let s = settings_from_extra(&extra);
1406 assert!(!s.show_summary);
1407 assert_eq!(s.pause_until_ms, 1234);
1408 assert!(!s.pause_allow_attention);
1409 assert_eq!(s.kind_enabled.get(&NotifyKind::AgentCrashed), Some(&false));
1410 assert_eq!(s.kind_enabled.get(&NotifyKind::MessageNeedsReview), Some(&true));
1411 assert!(!s.enabled);
1412 assert_eq!(s.when, When::Never);
1413 assert_eq!(s.preview, Preview::None);
1414 assert_eq!(s.kind_enabled.get(&NotifyKind::TurnCompleted), Some(&false));
1415 assert_eq!(s.kind_enabled.get(&NotifyKind::InputWaiting), Some(&true));
1416 }
1417}