Skip to main content

agentmux_srv/sagas/
sensitive_window.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The countdown for an approved sensitive request
5//! (`SPEC_SUPER_AGENT_2026_10_25.md` §5), beside `pending_shutdown`'s window for
6//! stops and closes. `open` starts the clock; the person can veto it, or approve
7//! it now to skip the wait. No click is needed to let it proceed: at the deadline
8//! the operation runs as the super agent's approved act on behalf of the
9//! requester, through the runner registered for its operation. Each operation's
10//! own code path runs unchanged, so no new power is added; only who may trigger
11//! it changes.
12//!
13//! A veto or an approve-now is the person's, and only the person's: the RPC
14//! below accepts them only from the proven AgentMux window (`operator_only`),
15//! never from an agent. The banner, toast and chime that tell the person arrive
16//! with the next steps of the spec's §9; the events here carry what they show.
17//!
18//! The `Sensitive` routes start a countdown when the super agent approves. The
19//! runners, the code that does each operation, arrive with the later steps of
20//! that spec's §9; an operation with none is not approved.
21#![allow(dead_code)]
22
23use std::collections::{BTreeMap, HashMap};
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::{Arc, LazyLock, Mutex};
27use std::time::Duration;
28
29use serde::{Deserialize, Serialize};
30
31pub use crate::backend::prompt_events::{SensitiveClearedEvent, SensitiveView, EVENT_SENSITIVE_CLEARED, EVENT_SENSITIVE_PENDING};
32use crate::backend::rpc::engine::WshRpcEngine;
33use crate::backend::sensitive_ops;
34use crate::backend::sensitive_requests::{self as requests, Request, Status};
35use crate::server::AppState;
36use agentmux_common::time::now_ms;
37
38/// The person's veto or approve-now of a countdown.
39pub const COMMAND_SENSITIVE_DECIDE: &str = "sensitive.decide";
40/// A settled window stays answerable this long, then is dropped.
41const KEEP_FINISHED_MS: i64 = 10 * 60 * 1000;
42/// How many of each event are kept for a window that opens mid-countdown: more than the
43/// countdowns that can overlap in the longest wait.
44const REPLAY_EVENTS: usize = 32;
45
46/// Data for `sensitive.decide`: the countdown's `request_id` (from `sensitive:pending`).
47#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
48#[ts(export, export_to = "../../../frontend/types/rpc/")]
49pub struct CommandSensitiveDecideData {
50    pub request_id: String,
51    #[ts(type = r#""veto" | "approve_now""#)]
52    pub decision: String,
53}
54
55/// How the person's decision came out: `too_late` when the countdown had begun or ended.
56#[derive(Debug, Clone, Serialize, Deserialize, Default, ts_rs::TS)]
57#[ts(export, export_to = "../../../frontend/types/rpc/")]
58pub struct SensitiveDecideResult {
59    #[ts(type = r#""vetoed" | "approved_now" | "too_late""#)]
60    pub outcome: String,
61}
62
63struct Entry {
64    view: SensitiveView,
65    wake: Arc<tokio::sync::Notify>,
66    /// The person approved it now: run without waiting out the window.
67    now: bool,
68    finished_at_ms: Option<i64>,
69}
70
71static ENTRIES: LazyLock<Mutex<HashMap<String, Entry>>> = LazyLock::new(Default::default);
72
73fn entries() -> std::sync::MutexGuard<'static, HashMap<String, Entry>> {
74    ENTRIES.lock().unwrap_or_else(|e| e.into_inner())
75}
76
77/// What runs an operation when its window runs out.
78pub type RunFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
79pub type Runner = Arc<dyn Fn(AppState, Request) -> RunFuture + Send + Sync>;
80
81static RUNNERS: LazyLock<Mutex<HashMap<&'static str, Runner>>> = LazyLock::new(Default::default);
82
83/// Say what runs `op` when its window runs out.
84pub fn register_runner(op: &'static str, runner: Runner) {
85    RUNNERS.lock().unwrap_or_else(|e| e.into_inner()).insert(op, runner);
86}
87
88/// Say what runs `op` unless something already says: how the real runners are registered, so
89/// registering them again (each connection does) never replaces one a test put there.
90pub fn register_default_runner(op: &'static str, runner: Runner) {
91    RUNNERS.lock().unwrap_or_else(|e| e.into_inner()).entry(op).or_insert(runner);
92}
93
94/// Take back what `register_runner` said, for a test of an operation nothing runs.
95#[cfg(test)]
96pub fn unregister_runner(op: &str) {
97    RUNNERS.lock().unwrap_or_else(|e| e.into_inner()).remove(op);
98}
99
100/// Whether something runs `op` when its window runs out.
101pub fn has_runner(op: &str) -> bool {
102    runner_for(op).is_some()
103}
104
105fn runner_for(op: &str) -> Option<Runner> {
106    RUNNERS.lock().unwrap_or_else(|e| e.into_inner()).get(op).cloned()
107}
108
109pub fn status(request_id: &str) -> Option<SensitiveView> {
110    entries().get(request_id).map(|e| e.view.clone())
111}
112
113/// `sensitive.decide`: only the AgentMux window, proven, may veto or approve a
114/// countdown now. An agent's connection is refused whatever it holds.
115pub fn register(engine: &Arc<WshRpcEngine>, state: &AppState) {
116    let state = state.clone();
117    engine.register_typed(COMMAND_SENSITIVE_DECIDE, move |cmd: CommandSensitiveDecideData, ctx| {
118        let state = state.clone();
119        async move {
120            ctx.operator_only("only the person can veto or approve a sensitive request")?;
121            let outcome = match cmd.decision.as_str() {
122                "veto" => veto(&state, &cmd.request_id),
123                "approve_now" => approve_now(&cmd.request_id),
124                other => return Err(format!("INVALID_ARG: decision is 'veto' or 'approve_now', not '{}'", other.chars().take(20).collect::<String>())),
125            };
126            Ok(SensitiveDecideResult { outcome: outcome.to_string() })
127        }
128    });
129}
130
131/// The countdowns still running, for a window that opens during one.
132pub fn pending() -> Vec<SensitiveView> {
133    entries().values().filter(|e| e.view.status == "pending").map(|e| e.view.clone()).collect()
134}
135
136/// Start the countdown for the approved request `request_id`, running `window`.
137/// One already counting for the request is returned as it is: the clock never restarts.
138pub fn open(state: &AppState, request_id: &str, window: Duration) -> Result<SensitiveView, String> {
139    let request = requests::registry().get(request_id).ok_or_else(|| format!("no request {request_id}"))?;
140    if request.status != Status::Pending {
141        return Err(format!("request {request_id} has not been approved"));
142    }
143    let view = {
144        let mut map = entries();
145        let now = now_ms();
146        map.retain(|_, e| e.finished_at_ms.is_none_or(|t| now - t < KEEP_FINISHED_MS));
147        if let Some(existing) = map.get(request_id) {
148            return Ok(existing.view.clone());
149        }
150        let view = SensitiveView {
151            request_id: request.id.clone(),
152            op: request.op.clone(),
153            summary: request.summary.clone(),
154            cancel_label: sensitive_ops::spec(&request.op).map_or("Veto", |o| o.cancel).to_string(),
155            now_label: sensitive_ops::spec(&request.op).map_or("Approve now", |o| o.now).to_string(),
156            requester: request.requester_slug.clone(),
157            approver: request.decided_by.clone(),
158            deadline_ms: now + window.as_millis() as i64,
159            opened_ms: now,
160            status: "pending",
161            error: None,
162        };
163        map.insert(
164            request.id.clone(),
165            Entry { view: view.clone(), wake: Arc::new(tokio::sync::Notify::new()), now: false, finished_at_ms: None },
166        );
167        view
168    };
169    state.broker.publish_event::<crate::backend::mps_events::SensitivePending>(&view, vec![], REPLAY_EVENTS);
170    raise_toast(state, &view);
171    tracing::info!(request_id, op = %view.op, requester = %view.requester, "sensitive request: the person has {} s to veto it", window.as_secs());
172
173    let wake = entries().get(request_id).map(|e| e.wake.clone());
174    let (state, v) = (state.clone(), view.clone());
175    tokio::spawn(async move {
176        if let Some(wake) = wake {
177            tokio::select! {
178                _ = tokio::time::sleep(window) => {}
179                _ = wake.notified() => {}
180            }
181        }
182        // Exactly one of the window running out and a veto wins.
183        if !begin(&v.request_id) {
184            return;
185        }
186        // A request withdrawn in the last moment is not run.
187        let request = match requests::registry().start(&v.request_id) {
188            Ok(request) => request,
189            Err(_) => {
190                set_status(&v.request_id, "cancelled", None);
191                cleared(&state, &v.request_id, "cancelled");
192                return;
193            }
194        };
195        cleared(&state, &v.request_id, "proceeding");
196        let outcome = run(&state, request.clone()).await;
197        let settled = match &outcome {
198            Ok(()) => crate::server::app_api::desktop_group::Settled::Allowed,
199            Err(e) => crate::server::app_api::desktop_group::Settled::Failed(e.clone()),
200        };
201        if !crate::server::app_api::desktop::settled(&request, settled) {
202            tell_askers(&request, &ran_note(&request, &outcome));
203        }
204        let (status, error, end) = match outcome {
205            Ok(()) => ("done", None, Status::Done),
206            Err(e) => ("failed", Some(e), Status::Failed),
207        };
208        let _ = requests::registry().finish(&v.request_id, end, now_ms());
209        set_status(&v.request_id, status, error.clone());
210        audit(&state, &v, "sensitive.run", error.is_none(), error.as_deref(), status, Some(&request.facts));
211    });
212    Ok(view)
213}
214
215/// `pending` → `proceeding`, atomically.
216fn begin(request_id: &str) -> bool {
217    let mut map = entries();
218    match map.get_mut(request_id) {
219        Some(e) if e.view.status == "pending" => {
220            e.view.status = "proceeding";
221            true
222        }
223        _ => false,
224    }
225}
226
227fn set_status(request_id: &str, status: &'static str, error: Option<String>) {
228    if let Some(e) = entries().get_mut(request_id) {
229        e.view.status = status;
230        e.view.error = error;
231        e.finished_at_ms = Some(now_ms());
232    }
233}
234
235/// Something else did what the open requests for `op` (whose fact `key` is `value`) asked for, for
236/// example the person's own request started the same upgrade: end them, their countdowns included,
237/// so none runs it a second time, and tell the agents that asked.
238pub fn answered_by_another(state: &AppState, op: &str, key: &str, value: &str, how: &str) {
239    for request in requests::registry().open_matching(op, key, value) {
240        if request.status == Status::Pending {
241            cancelled(state, &request.id);
242        }
243        if requests::registry().finish(&request.id, Status::Done, now_ms()).is_ok() {
244            let what = crate::backend::reactive::sanitize::quote_in_system_note(&request.summary);
245            if !crate::server::app_api::desktop::settled(&request, crate::server::app_api::desktop_group::Settled::Ended) {
246                tell_askers(&request, &format!("[AgentMux] {how}, so your request to {what} is no longer needed."));
247            }
248        }
249    }
250}
251
252/// What the agents that asked are told when the countdown ended and the operation ran, or could not.
253fn ran_note(request: &Request, outcome: &Result<(), String>) -> String {
254    let what = crate::backend::reactive::sanitize::quote_in_system_note(&request.summary);
255    match outcome {
256        Ok(()) => format!("[AgentMux] Your request to {what} went ahead."),
257        Err(e) => format!("[AgentMux] Your request to {what} could not go ahead: {}", crate::backend::reactive::sanitize::quote_in_system_note(e)),
258    }
259}
260
261/// What they are told when the person vetoed it.
262fn vetoed_note(request: &Request) -> String {
263    format!("[AgentMux] The person vetoed your request to {}; it did not happen.", crate::backend::reactive::sanitize::quote_in_system_note(&request.summary))
264}
265
266/// Run the operation in a task of its own, so one that panics settles the
267/// window as failed instead of leaving it counted as under way.
268async fn run(state: &AppState, request: Request) -> Result<(), String> {
269    let runner = runner_for(&request.op).ok_or_else(|| format!("nothing runs {} yet", request.op))?;
270    let state = state.clone();
271    // The runner is called inside the task too: one that panics before it hands back a future is caught the same way.
272    match tokio::spawn(async move { runner(state, request).await }).await {
273        Ok(result) => result,
274        Err(e) => Err(format!("the operation stopped unexpectedly: {e}")),
275    }
276}
277
278/// The person vetoes the countdown: `vetoed`, or `too_late` once it has begun
279/// or ended.
280pub fn veto(state: &AppState, request_id: &str) -> &'static str {
281    let view = {
282        let mut map = entries();
283        match map.get_mut(request_id) {
284            Some(e) if e.view.status == "pending" => {
285                // Decided here, under the lock; the window task only wakes to
286                // find it no longer pending.
287                e.view.status = "vetoed";
288                e.finished_at_ms = Some(now_ms());
289                e.wake.notify_one();
290                e.view.clone()
291            }
292            _ => return "too_late",
293        }
294    };
295    let _ = requests::registry().finish(request_id, Status::Vetoed, now_ms());
296    let request = requests::registry().get(request_id);
297    if let Some(r) = &request {
298        if !crate::server::app_api::desktop::settled(r, crate::server::app_api::desktop_group::Settled::Vetoed) {
299            tell_askers(r, &vetoed_note(r));
300        }
301    }
302    cleared(state, request_id, "vetoed");
303    audit(state, &view, "sensitive.veto", true, None, "vetoed", request.as_ref().map(|r| &r.facts));
304    tracing::info!(request_id, "sensitive request: vetoed by the person");
305    "vetoed"
306}
307
308/// The request was withdrawn (see `Registry::cancel`) while the countdown ran:
309/// end it, so the banner stops counting for an operation that will not run.
310/// `cancelled`, or `too_late` once it has begun or ended.
311pub fn cancelled(state: &AppState, request_id: &str) -> &'static str {
312    {
313        let mut map = entries();
314        match map.get_mut(request_id) {
315            Some(e) if e.view.status == "pending" => {
316                e.view.status = "cancelled";
317                e.finished_at_ms = Some(now_ms());
318                e.wake.notify_one();
319            }
320            _ => return "too_late",
321        }
322    }
323    cleared(state, request_id, "cancelled");
324    "cancelled"
325}
326
327/// The person approves it now, skipping the rest of the wait: `approved_now`,
328/// or `too_late` once it has begun or ended.
329pub fn approve_now(request_id: &str) -> &'static str {
330    let mut map = entries();
331    match map.get_mut(request_id) {
332        Some(e) if e.view.status == "pending" && !e.now => {
333            e.now = true;
334            e.wake.notify_one();
335            "approved_now"
336        }
337        _ => "too_late",
338    }
339}
340
341fn cleared(state: &AppState, request_id: &str, outcome: &str) {
342    if let Some(router) = crate::backend::notify::router::get(&state.broker) {
343        router.resolve_nonblocking(&toast_group(request_id), crate::backend::notify::policy::Family::Shutdown);
344    }
345    let data = SensitiveClearedEvent { request_id: request_id.to_string(), outcome: outcome.to_string() };
346    state.broker.publish_event::<crate::backend::mps_events::SensitiveCleared>(&data, vec![], REPLAY_EVENTS);
347}
348
349/// The notification group of a countdown's toast: there is no pane, so the request is its own.
350pub const TOAST_GROUP_PREFIX: &str = "sensitive:";
351
352fn toast_group(request_id: &str) -> String {
353    format!("{TOAST_GROUP_PREFIX}{request_id}")
354}
355
356/// What the OS notification says: the title (what will happen, from the operation's table, not
357/// from any request text) and the body (who asked and who approved, by display name). The
358/// request's facts are left out on purpose: a toast also lands in the Action Center and on a
359/// lock screen, and a fact can be a path or an address. The banner in AgentMux shows them.
360fn toast_text(requester: &str, approver: Option<&str>, op: &str) -> (String, String) {
361    let label = sensitive_ops::spec(op).map_or("A sensitive operation", |s| s.label);
362    let mut title = label.to_string();
363    if let Some(first) = title.get_mut(0..1) {
364        first.make_ascii_uppercase();
365    }
366    let reviewed = match approver {
367        Some(a) => format!("Approved by {a}."),
368        None => "No super agent reviewed this.".to_string(),
369    };
370    (title, format!("{requester} asked. {reviewed} It happens when the countdown ends unless you veto it in AgentMux."))
371}
372
373/// The OS notification for a countdown: what will happen, the seconds left, and its two buttons
374/// (cancel and do it now), which `notify.ack` accepts only with the launcher's proof.
375fn raise_toast(state: &AppState, view: &SensitiveView) {
376    let Some(router) = crate::backend::notify::router::get(&state.broker) else { return };
377    let name = |slug: &str| crate::sagas::pending_shutdown::clean_by(&crate::sagas::pending_shutdown::asker_name(state, slug));
378    let (title, body) = toast_text(&name(&view.requester), view.approver.as_deref().map(name).as_deref(), &view.op);
379    let info = crate::backend::notify::policy::ShutdownInfo {
380        deadline_ms: view.deadline_ms,
381        effect: crate::backend::notify::policy::SENSITIVE_EFFECT,
382        running: true,
383        request_id: view.request_id.clone(),
384        labels: Some((view.cancel_label.clone(), view.now_label.clone())),
385    };
386    router.emit_group(&toast_group(&view.request_id), &title, Some(body), info);
387    // A withdrawal or veto that settled the countdown while this was being raised asked the router
388    // to retract the toast before it existed: look again now it does, and retract it.
389    if status(&view.request_id).is_none_or(|v| v.status != "pending") {
390        router.resolve_nonblocking(&toast_group(&view.request_id), crate::backend::notify::policy::Family::Shutdown);
391    }
392}
393
394/// One audit row for a step of the window: the person's veto, or the run. `facts` are the request's,
395/// when known, for the typed audit fields (§4.6); `os_prompt_answer` is the only op with `prompt`,
396/// `answer` and `level` among them today, so every other op's row carries none of the three.
397fn audit(state: &AppState, v: &SensitiveView, action: &str, ok: bool, error: Option<&str>, outcome: &str, facts: Option<&BTreeMap<String, String>>) {
398    let source = if action == "sensitive.veto" { "operator".to_string() } else { approver_label(v.approver.as_deref().unwrap_or("no super agent")) };
399    let note = format!("{}: {} | requested by {} | {outcome}", v.op, v.summary, v.requester);
400    state.reactive_handler.log_sensitive_op_audit(
401        Some(&source),
402        &v.requester,
403        action,
404        ok,
405        error,
406        &v.request_id,
407        Some(&note),
408        facts.and_then(|f| f.get("prompt")).map(String::as_str),
409        facts.and_then(|f| f.get("answer")).map(String::as_str),
410        facts.and_then(|f| f.get("level")).map(String::as_str),
411        false,
412    );
413}
414
415/// Tell every agent that asked for a request, those that joined included. An agent that isn't
416/// running is not an error.
417pub fn tell_askers(request: &Request, note: &str) {
418    for uid in request.askers() {
419        tell_one(uid, note);
420    }
421}
422
423/// Tell one asker, from AgentMux; whether the note was delivered. An agent of another machine (`remote:agent@machine`)
424/// has no pane here to put a note in, and srv can't speak as one of that machine's agents: it is not told from here,
425/// and that is no failure. Its own machine reads where the request stands (`app.upgrade` with `status`) and tells
426/// it how it ended (`remote_ops::upgrade_watch`); the agent can read the same itself.
427pub fn tell_one(uid: &str, note: &str) -> bool {
428    if uid.starts_with(crate::backend::sensitive_requests::REMOTE_OWNER_PREFIX) {
429        tracing::debug!(requester = %uid, "sensitive request: the asker is on another machine; it reads the request's status");
430        return false;
431    }
432    match crate::backend::reactive::get_global_handler().deliver_system_note(uid, note) {
433        Ok(()) => true,
434        Err(e) => {
435            tracing::info!(error = %e, "sensitive request: note not delivered");
436            false
437        }
438    }
439}
440
441
442/// How an audit row names the approver: an agent with its prefix, so none can read as the person; the
443/// fallback's own words stay as they are.
444fn approver_label(approver: &str) -> String {
445    if approver == "no super agent" { approver.to_string() } else { crate::backend::rpc::actor::Actor::Agent(approver.to_string()).label() }
446}
447
448/// One audit row for a step of a request, done by `actor` (the agent that did it, or
449/// "no super agent" for the fallback): the request, the approval, the denial, the withdrawal.
450pub fn audit_step(state: &AppState, actor: &str, r: &Request, action: &str, ok: bool, error: Option<&str>, outcome: &str) {
451    let note = format!("{}: {} | requested by {} | {outcome}", r.op, r.summary, r.requester_slug);
452    let actor = approver_label(actor);
453    state.reactive_handler.log_sensitive_op_audit(
454        Some(&actor),
455        &r.requester_slug,
456        action,
457        ok,
458        error,
459        &r.id,
460        Some(&note),
461        r.facts.get("prompt").map(String::as_str),
462        r.facts.get("answer").map(String::as_str),
463        r.facts.get("level").map(String::as_str),
464        false,
465    );
466}
467
468/// The runner of an operation is one for the whole process, so the tests that need one (or none)
469/// of a shared operation take turns.
470#[cfg(test)]
471pub(crate) static TEST_RUNNER_TURN: Mutex<()> = Mutex::new(());
472
473#[cfg(test)]
474#[path = "sensitive_window_tests.rs"]
475mod tests;
476
477#[cfg(test)]
478mod approver_label_tests {
479    use super::approver_label;
480
481    #[test]
482    fn an_approving_agent_is_named_with_its_prefix_and_the_fallback_keeps_its_words() {
483        assert_eq!(approver_label("opaz"), "agent:opaz");
484        assert_eq!(approver_label("operator"), "agent:operator");
485        assert_eq!(approver_label("no super agent"), "no super agent");
486    }
487}