Skip to main content

agentmux_srv_core/backend/notify/
router.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Notification Router — the side-effecting shell around `policy.rs`
5//! (`SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24.md` §3, §5).
6//!
7//! Owns: settings resolution, agent-name lookup + sanitization, body
8//! redaction (§9), publishing on the mps broker, a 500 ms tick task for
9//! debounce release, and the single pending "activate on next window" slot
10//! for a click that arrived while no window was open.
11//!
12//! One Router per broker (i.e. per `AppState`), kept in a small registry
13//! keyed by the broker's identity rather than as an `AppState` field: it is
14//! created lazily by the first WS connection and outlives any one connection.
15//! Keying by broker (not a single global) means a second `AppState` in the
16//! same process — tests, or any future multi-state setup — never has its
17//! events published onto someone else's bus.
18
19use 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";
35/// Tray snapshot (`TrayState`), published on change with persist=1 so a
36/// presenter that (re)subscribes gets the current state immediately.
37pub const EVENT_NOTIFICATION_STATE: &str = "notification:state";
38/// `block.reveal`: the named window's renderer reveals the block itself
39/// (`SPEC_REVEAL_BLOCK_ONE_PATH_2026_09_27.md` §4.3). Payload: `BlockRevealEvent`.
40pub const EVENT_BLOCK_REVEAL: &str = "block:reveal";
41
42/// `notification:retract`: take a shown notification down.
43#[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/// `notification:activate`: the user clicked a notification; this window shows its block.
51#[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/// Where `block.reveal` reveals a block — also the `block:reveal` payload.
64#[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    /// The open window showing the block's workspace; only it acts.
70    pub window_id: String,
71    /// Set when the caller waits for the window's answer (`block.revealed`).
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    #[ts(optional)]
74    pub request_id: Option<String>,
75}
76
77/// A window's answer to `block:reveal`: whether it showed the block, and if not, why.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct RevealAck {
80    pub ok: bool,
81    pub reason: Option<String>,
82}
83
84/// srv-internal sources, fed from places that must not block (the broker's
85/// publish path, the jekt delivery path) and drained by the router's task.
86enum Internal {
87    /// `own_blocks_only`: the source is process-global (the reactive handler
88    /// is shared by every AppState), so drop blocks this Router's store
89    /// doesn't know.
90    /// `account_failure`: a usage limit or refused sign-in, which an account
91    /// episode may speak for instead.
92    Emit { kind: NotifyKind, block_id: String, body: Option<String>, own_blocks_only: bool, account_failure: bool },
93    /// Raw question text — redacted by `emit` like a renderer report.
94    /// `count`: how many questions the call asks (0 = unknown).
95    InputWaiting { block_id: String, question: Option<String>, count: usize },
96    /// Resolve through the SAME ordered queue as the srv-side emits, so a
97    /// resolve can never overtake the emit it cancels (Codex P2 on #3662).
98    Resolve { block_id: String, family: Family },
99    /// A controller's authoritative `turn_active` (from `controllerstatus`).
100    TurnStatus { block_id: String, active: bool },
101    /// The user stopped/interrupted this block's turn in its pane.
102    TurnStopped { block_id: String },
103    /// A block's turn ledger (`agentturn`) reports the turn over.
104    TurnEnded(LedgerEnd),
105}
106
107/// What the router needs from an ended turn's ledger (`agentturn`).
108#[derive(Clone, Debug, PartialEq, Eq)]
109pub struct LedgerEnd {
110    pub block_id: String,
111    pub turn_id: u64,
112    /// When it ended: a turn rejoined by a held message ends again later, and
113    /// that end is a new one (#4511).
114    pub ended_at_ms: u64,
115    /// Started by something other than the user: another agent, a service, a
116    /// schedule, a background task (spec §5.2).
117    pub external: bool,
118    /// AgentMux's own hidden turn (memory reinjection): never notified.
119    pub system: bool,
120}
121
122/// The fields of a published ledger the router reads, typed by the same
123/// enums srv serializes it with.
124#[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
136/// The turn is over by its ledger: `end: "completed"` (an exit is a crash,
137/// which `agentfailure` reports). `None` for a turn still running or settling.
138pub 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
153/// Whether a finished turn is notified: never AgentMux's own hidden turn; a
154/// turn something else started only when the user asked for those too.
155pub fn notify_turn_end(end: &LedgerEnd, external_turns: bool) -> bool {
156    !end.system && (!end.external || external_turns)
157}
158
159/// Whether the Swarm Supervisor watches this pane, so it, not the generic
160/// "finished", speaks when a turn ends. BLOCKING (store read).
161pub 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
169/// Cap on tracked blocks' turn state (see `Internal::TurnStatus` handling).
170const TURN_MAP_MAX: usize = 1024;
171
172/// What the Router does with a `controllerstatus` turn transition.
173#[derive(Debug, PartialEq, Eq)]
174pub enum TurnTransition {
175    /// Turn (re)started: anything "finished" for this block is moot.
176    Started,
177    /// Turn really ended: notify "finished" (subject to policy).
178    Finished,
179    /// No transition, first sighting, or ended by the user's own Stop.
180    Nothing,
181}
182
183/// `(blockid, turn_active)` from a serialized `BlockControllerRuntimeStatus`.
184/// `turn_active` is `skip_serializing_if = "is_false"`, so a turn that ENDED
185/// arrives with the field absent — absent means false (Codex P1 on #3705;
186/// treating it as "unknown" dropped every end-of-turn and "finished" never
187/// fired).
188pub 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
194/// Pure: `prev` = last known `turn_active` for the block (None = never seen,
195/// e.g. right after srv start — a replayed/first status is not a transition).
196pub 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
205/// A click's target is picked up by a newly opened window only this long
206/// after the click (rich-content spec §3.3 D) — never "jumps to an old block
207/// much later".
208pub const PENDING_ACTIVATION_MAX_AGE_MS: i64 = 30_000;
209
210/// Where a toast click lands (rich-content spec §3.3 A). Resolved by srv from
211/// its own store for the notification the click acked — never taken from the
212/// toast's launch argument (§3.4).
213#[derive(Clone, Debug, Default, PartialEq, Eq)]
214pub struct ClickTarget {
215    pub block_id: String,
216    pub tab_id: String,
217    /// `None` when the tab belongs to no workspace any more.
218    pub workspace_id: Option<String>,
219    /// Every `Window` object showing that workspace. Whether one is actually
220    /// open is the policy's call (a connected frontend reports it).
221    pub window_ids: Vec<String>,
222}
223
224/// Walk block → tab → workspace → windows. `None` when the block or its tab
225/// is gone. BLOCKING (store reads).
226pub 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/// What a click asks of the launcher (the `notify.ack` response).
251#[derive(Clone, Debug, Default, PartialEq, Eq)]
252pub struct AckOutcome {
253    /// The ack named a live notification. An unknown id (a toast from before
254    /// an srv restart) still raises the app (§3.3 F).
255    pub known: bool,
256    /// The window to raise, when one is open. For a pane's toast it is the
257    /// window showing the pane; otherwise the most recently focused window.
258    pub window_id: Option<String>,
259    /// For a pane whose workspace is open in no window: open a window on it.
260    pub workspace_id: Option<String>,
261    /// Kept for launchers older than `window_id`: false means "open a window".
262    pub has_window: bool,
263}
264
265/// A click that arrived while its pane's workspace was open in no window.
266#[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
274/// Pure: may a window showing `workspace_id` (None = an older frontend that
275/// doesn't say) take `pending` at `now_ms`?
276pub 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
286/// Of `window_ids` (a workspace's windows), the one a connected frontend
287/// reports open. Two open windows on one workspace: prefer the one the user
288/// was last in.
289fn 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
295/// The body of the `CloudSignedOut` notification.
296pub 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;
301/// Rich-content spec §1.2: the summary line's cap, before the `…`.
302const 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    /// Clicks and reveals whose pane's workspace was open in no window, one per workspace: each is
310    /// taken by the window opened on that workspace.
311    pending_activation: Mutex<Vec<PendingActivation>>,
312    internal: tokio::sync::mpsc::UnboundedSender<Internal>,
313    last_tray: Mutex<Option<TrayState>>,
314    /// block_id → last `turn_active` seen in `controllerstatus`.
315    turn_active: Mutex<std::collections::HashMap<String, bool>>,
316    /// block_id → when its latest turn was seen to start (epoch ms): a status line set since is about
317    /// the turn a toast reports (`toast_line`).
318    turn_started_ms: Mutex<std::collections::HashMap<String, i64>>,
319    /// (block_id, turn_id, ended_at_ms) of turn ends already notified.
320    notified_turns: Mutex<std::collections::HashSet<(String, u64, u64)>>,
321    /// `block:reveal` requests whose caller waits for the window's answer, by request id.
322    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
336/// The router for this broker, if a connection has created it yet.
337pub fn get(broker: &Arc<Broker>) -> Option<Arc<Router>> {
338    registry().lock().unwrap_or_else(|e| e.into_inner()).get(&key(broker)).cloned()
339}
340
341/// Get-or-create the router for this broker. Idempotent.
342///
343/// On creation it also attaches the srv-side sources: an observer on the
344/// broker (`agentfailure` → `AgentCrashed`) and the reactive handler's
345/// needs-review hook (`ESCALATE=required` jekt → `MessageNeedsReview`).
346pub 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
377/// Both hooks run on hot, lock-holding paths (the broker's publish; jekt
378/// delivery). They only parse and enqueue — never call back into the broker
379/// or touch the store inline.
380fn 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        // "Finished" comes from the controller's own turn state, not from the
384        // renderer's reducer — which can report turn-ended mid-turn (e.g. a
385        // queued message released straight into the next turn), producing
386        // "finished" toasts for an agent that is still working.
387        if ev.event == crate::backend::mps::EVENT_CONTROLLER_STATUS {
388            // No `is_agent_pane` filter: the subprocess controller (Codex,
389            // Gemini, …) publishes `is_agent_pane: false` for its agent panes
390            // (Codex P1 on #3705), and only real agent turns ever report
391            // turn_active=true (shell controllers hardcode false), so a
392            // true→false edge is agent-specific on its own.
393            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        // "Finished" is the TURN's end, as its ledger reports it: one per
399        // turn the user sees, not one per CLI pass (spec §4.3).
400        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                // Per-broker observer: already scoped to this AppState.
417                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            // Fixed text only — never the message, sender or trust label
428            // (spec §9.1: the toast can only say "go look").
429            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                    // Store lookups — off the async workers.
446                    let _ = tokio::task::spawn_blocking(move || {
447                        if own_blocks_only && !r.owns_block(&block_id) {
448                            return;
449                        }
450                        // The account's one notice speaks for it
451                        // (SPEC_UNRESPONSIVE_AGENTS_2026_10_23.md §6.2).
452                        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                        // One end can be published twice (its lapse, then the
470                        // lazy close): notify once. A turn reopened by a held
471                        // message and ended again is a new end. Bounded.
472                        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                        // A supervised pane's Supervisor says "finished" or
486                        // "needs you" itself, once it has judged the turn
487                        // (SPEC_SWARM_SUPERVISOR_2026_10_16.md §3.7).
488                        if is_supervised_block(&r.store, &block_id) {
489                            return;
490                        }
491                        // A turn that ended on its account's limit or sign-in
492                        // finished nothing: the account's notice speaks for it.
493                        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                    // `notify.emit` recorded the stop before queueing this, so
502                    // a turn start queued ahead of it may have forgotten it
503                    // since: record it again, in order (`backend::user_stop`).
504                    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
513/// `AgentFailure.code` → the fixed body for its toast; `None` = don't notify.
514/// Only `agent_deleted` (a user action) is skipped. `killed` is NOT a user
515/// Stop — those go through the controllers' kill arm and are never
516/// classified (host_spawn.rs) — it means a signal/137, most often the OOM
517/// killer: exactly the "stopped while you were away" case (ReAgent P1 on
518/// #3654). Detail/stderr never reach a toast.
519pub 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    // Only when a Tokio runtime exists (always true in srv; unit tests of the
537    // pure policy never reach here).
538    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
557/// Strip control + bidi-override characters and cap length — the only
558/// user-influenced text that reaches a title (§9.1).
559pub 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
576/// Rich-content spec §1.2: what the agent is on (`toast_line`) as a single line —
577/// controls and bidi stripped, whitespace collapsed, capped at 90 characters.
578/// A summary that trips the jekt keyword list is dropped, not replaced: it is
579/// decoration, not something the user needs to be told is hidden.
580pub 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
600/// Rich-content spec §2.1: " (+N more)" after the (already truncated) first
601/// question, so the count survives truncation. No body, no suffix — the
602/// title "has a question" stands on its own.
603pub 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
607/// §9.2 body policy: first line, sanitized, truncated, and replaced wholesale
608/// when it trips the same credential/destructive keyword list the jekt tier
609/// gate uses.
610pub 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
627/// `notify:quiethours` = `"HH:MM-HH:MM"` in local time. If `now` is inside
628/// the window, return when it ends (epoch ms); `None` outside it or on a
629/// malformed/empty value. A window whose end is before its start spans
630/// midnight ("22:00-08:00"). Equal start and end means "off".
631pub 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
667/// Resolve the policy's settings view from `settings.json` (§8).
668pub 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    /// Whether a pause or quiet hours would drop an Attention notification now.
714    /// A source that records what it sent (`vault::expiry`) waits it out.
715    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    /// Whether the user asked to hear about turns something other than them
721    /// started (`notify:os:turncompleted:external`): the Swarm Supervisor
722    /// applies the same rule to its own "finished" notice.
723    pub fn external_turns_notified(&self) -> bool {
724        self.settings().external_turns
725    }
726
727    /// Does this Router's store know the block? BLOCKING (SQLite).
728    fn owns_block(&self, block_id: &str) -> bool {
729        matches!(self.store.get::<Block>(block_id), Ok(Some(_)))
730    }
731
732    /// The block's sanitized agent name and the line saying what it is on, from one read.
733    /// BLOCKING (SQLite behind `Store`'s process-wide mutex) — only ever
734    /// reached through `emit` / `emit_fixed`, which callers must run off the
735    /// async workers (`spawn_blocking`; the #1782 failure class, see
736    /// websocket.rs's controllerinput note). Not cached: the summary changes
737    /// every turn and emits are rare, so the read the summary needs anyway
738    /// also serves the name.
739    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        // The line under the name is the agent's own status line or its held task, when fresh; never
749        // the ambient title, which nothing checks the age of (`toast_line`).
750        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        // A pane that holds no agent (a browser, an editor) is named by what it is,
753        // not "An agent": the countdown to close it says what is closing.
754        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    /// A controller's `turn_active` for `block_id`: a turn that starts forgets the stop that ended
762    /// the one before, records when it began (`toast_line` reads it) and retracts the turn's toast.
763    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            // Bounded: forgetting an IDLE block is
767            // harmless — its next `true` still reads as Started.
768            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                // A new turn: the earlier stop no longer applies
777                // to it (Codex P2 on #3705).
778                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            // Notified from the turn's ledger instead
789            // (`Internal::TurnEnded`): a pass ending is not the
790            // turn ending.
791            TurnTransition::Finished => {}
792            TurnTransition::Nothing => {}
793        }
794    }
795
796    /// Run the policy and publish what it decided. `Activate` is returned,
797    /// not published: only `ack` produces it, and it needs a store lookup.
798    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            // Resolved and published by `ack`.
831            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    // ── Source entry points ───────────────────────────────────────────────
841
842    /// A frontend reports a pane event. `question` is only used for
843    /// `InputWaiting` and goes through `redact_body`; `question_count` adds
844    /// " (+N more)" after it.
845    ///
846    /// BLOCKING (the block lookup hits the store) — call from
847    /// `spawn_blocking`, never inline on an async worker.
848    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    /// srv-internal sources: the body is app-controlled fixed text, so it is
861    /// not redacted — only the preview=none setting strips it (in policy).
862    /// BLOCKING, like `emit`.
863    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    /// A shutdown waiting on the user's override: the toast says what will
869    /// happen, counts down and offers Keep running (spec §3.8). The body is
870    /// app wording and the asker's cleaned name; never the reason. BLOCKING,
871    /// like `emit`.
872    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    /// A countdown that is no one pane's: a sensitive operation, or a close of several agents at once.
885    /// The toast names what will happen, counts down and offers its two buttons.
886    /// `block_id` is the countdown's own group (there is no pane); `what` and `body` are app
887    /// wording and cleaned names, never the requester's words. Not blocking: nothing is read.
888    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    /// What a press on the live notification `id` is about: its kind, block
900    /// and (for a shutdown) request, from this router's own record.
901    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    /// srv-observed "agent is waiting on you" (Phase 5). Non-blocking: safe
906    /// from the controller's stdout reader thread. Coalesces with the
907    /// renderer's own report for the same block (same `input:` group).
908    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    /// The user stopped this block's turn: cancel "finished" for it, and keep
913    /// the resulting turn end from becoming a new one (queued, ordered; the
914    /// stop is recorded in `backend::user_stop`).
915    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    /// Ordered counterpart of `resolve`: queued behind any emit already sent
920    /// for the same block.
921    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    /// Agents on one account can't work (`server::account_episodes`). `key`
941    /// is the account's toast key (`account:<hash>`); the body is fixed text
942    /// with a count, never the account. Taken down with
943    /// `resolve(key, Family::Account)`.
944    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    /// A job failed and opened an incident (`jobs::incidents`). `key` is the
956    /// job's (`job:<id>`); the title names the job, the body is fixed text
957    /// with the reason, never the run's summary. Taken down with
958    /// `resolve(key, Family::Job)` when the job recovers.
959    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    /// A Vault entry's expiry date is near (`vault::expiry`). `key` is the
971    /// entry's (`vault:<id>`); the title names the entry by its label, the body
972    /// is fixed text with the date. Never a value: the Vault doesn't open one.
973    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    /// A drone's Notify block (`drone::executor::blocks::notify`). `key` is
985    /// `drone:<id>`, one per notification; `title` is the block's own words,
986    /// written in the graph (never a value from outside); the body is the
987    /// block's text with its outside values quoted.
988    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    /// This channel's MuxBus sign-in stopped working
1000    /// (`muxbus::delivery_status`). Fixed text; about no agent. Taken down
1001    /// with `resolve("", Family::Cloud)`.
1002    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    /// Whether any window of this AgentMux is focused now.
1014    pub fn app_focused(&self) -> bool {
1015        self.policy.lock().unwrap_or_else(|e| e.into_inner()).app_focused()
1016    }
1017
1018    /// The window the person was in last (a connected frontend's `Window` oid), else any connected one.
1019    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    /// Presenter feedback (rich-content spec §3.3 A–D, F). For a click on a
1032    /// pane's toast: find the open window showing the pane and tell only it
1033    /// to select the pane (`notification:activate` names the window); if the
1034    /// pane's workspace is open nowhere, park the click for the window the
1035    /// launcher will open on it. The outcome tells the launcher what to raise
1036    /// or open — every click ends with something in front.
1037    ///
1038    /// BLOCKING (store reads) — call from `spawn_blocking`.
1039    pub fn ack(&self, id: &str, clicked: bool) -> AckOutcome {
1040        let actions = self.step(Input::Ack { id: id.to_string(), clicked });
1041        // A live notification always retracts on ack; an unknown id yields nothing.
1042        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            // A summary toast, or an id this srv never issued: raise the app.
1085            (None, _) if clicked => outcome.window_id = raise,
1086            (None, _) => {}
1087        }
1088        outcome
1089    }
1090
1091    /// `block.reveal`: the block's tab and the open window showing it,
1092    /// resolved exactly as a toast click is (`resolve_click_target` + the
1093    /// same open-window pick). `None` when the block is gone or its
1094    /// workspace is open in no window.
1095    ///
1096    /// BLOCKING (store reads) — call from `spawn_blocking`.
1097    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    /// Wait for the answer to the `block:reveal` that carries `request_id`: register before publishing.
1107    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    /// Stop waiting for `request_id` (its answer did not come in time).
1114    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    /// A window's answer (`block.revealed`). Whether a caller was still waiting for it.
1119    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    /// `block.reveal` for a pane whose workspace no window shows: park the pane as the pending
1125    /// activation (as a toast click does) and name the workspace, so the caller can open a window
1126    /// on it and that window takes the pane up (`take_pending_activation`). `None` when the block
1127    /// or its tab is gone, or its tab belongs to no workspace.
1128    ///
1129    /// BLOCKING (store reads) — call from `spawn_blocking`.
1130    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    /// Hold `pending` for a window opened on its workspace. A newer request for the same workspace
1138    /// replaces the older one; requests for other workspaces are kept, so two panes in two closed
1139    /// workspaces both reach their windows.
1140    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    /// Tell `target.window_id`'s renderer to reveal the block.
1147    pub fn publish_block_reveal(&self, target: &BlockRevealEvent) {
1148        self.publish_event::<crate::backend::mps_events::BlockReveal>(target);
1149    }
1150
1151    /// One-shot: the pane a click asked for while its workspace was open in
1152    /// no window. Only a window on that workspace takes it (`workspace_id`
1153    /// None = an older frontend, which takes any), and only for 30 s.
1154    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    // ---- the turn's end, from its ledger (turn-model spec §4.3, §5) ----
1167
1168    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    /// Against the REAL serialized status type, not a hand-written JSON — the
1231    /// omitted-when-false field is exactly what a hand-written fixture hid.
1232    #[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        // End to end with the transition rule: start then end = Finished.
1255        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        // First sighting (srv start / replay) is never a transition to "finished".
1265        assert_eq!(turn_transition(None, false, false), Nothing);
1266        assert_eq!(turn_transition(None, true, false), Started);
1267        // Real end of a turn.
1268        assert_eq!(turn_transition(Some(true), false, false), Finished);
1269        // Ended by the user's own Stop.
1270        assert_eq!(turn_transition(Some(true), false, true), Nothing);
1271        // Repeated statuses are not transitions.
1272        assert_eq!(turn_transition(Some(true), true, false), Nothing);
1273        assert_eq!(turn_transition(Some(false), false, false), Nothing);
1274        // Next turn starts.
1275        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        // Spans midnight.
1284        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        // Same-day window.
1289        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        // Off / malformed.
1292        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    /// SPEC_SWARM_SUPERVISOR_2026_10_16.md §3.7: a supervised Claude pane gets
1334    /// its notice from the Supervisor; any other pane from the router.
1335    #[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        // Sensitive → dropped entirely, never "sensitive content".
1373        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}