Skip to main content

agentmux_srv/sagas/
sensitive_fallback.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3//
4//! A request nobody reviewed (`SPEC_SUPER_AGENT_2026_10_25.md` ยง6). The request still gets its
5//! countdown; only the agent in front is missing. When no super agent holds the seat or runs
6//! here for a few seconds, or the one that does hasn't answered in two minutes, the countdown
7//! starts anyway with twice the usual window (at most the longest), the banner says no super
8//! agent reviewed it, and the person's veto is the only check.
9
10// The watcher is started only outside tests, so the constants and `watch` look unused there.
11#![cfg_attr(test, allow(dead_code))]
12
13use std::time::Duration;
14
15use crate::backend::sensitive_ops;
16use crate::backend::sensitive_requests::{self as requests, Status};
17use crate::sagas::sensitive_window as window;
18use crate::server::AppState;
19use agentmux_common::time::now_ms;
20
21/// How long a super agent has to answer before the request goes ahead without it.
22const ASK_WAIT: Duration = Duration::from_secs(120);
23/// How long there may be no super agent running here before it does. Covers a restart.
24const ABSENT_GRACE: Duration = Duration::from_secs(10);
25const POLL: Duration = Duration::from_secs(2);
26
27#[derive(Clone, Copy)]
28pub struct Timing {
29    pub poll: Duration,
30    pub absent_grace: Duration,
31    pub ask_wait: Duration,
32}
33
34pub const TIMING: Timing = Timing { poll: POLL, absent_grace: ABSENT_GRACE, ask_wait: ASK_WAIT };
35
36/// Watch a request just filed, and send it to the countdown if no super agent reviews it.
37/// Tests drive `watch_with` directly: a watcher started by every filed request would answer
38/// the ones that test the super agent's side.
39pub fn watch(state: &AppState, request_id: &str) {
40    #[cfg(not(test))]
41    {
42        let (state, id) = (state.clone(), request_id.to_string());
43        tokio::spawn(async move { watch_with(&state, &id, TIMING, reviewer_here).await });
44    }
45    #[cfg(test)]
46    let _ = (state, request_id);
47}
48
49/// Whether a super agent holds the seat and runs in this AgentMux.
50fn reviewer_here(state: &AppState) -> bool {
51    let defs = state.mstore.agent_def_list().unwrap_or_default();
52    crate::backend::agent_seat::super_holder(&state.mstore, &defs).is_some_and(|uid| crate::backend::reactive::get_global_handler().has_uid_registration(&uid))
53}
54
55/// Wait until the request is answered, or no one is left to answer it, then act.
56/// `reviewer` says whether a super agent is there to answer.
57pub async fn watch_with(state: &AppState, request_id: &str, timing: Timing, reviewer: impl Fn(&AppState) -> bool) {
58    let started = tokio::time::Instant::now();
59    let mut absent_since: Option<tokio::time::Instant> = None;
60    loop {
61        match requests::registry().get(request_id) {
62            Some(r) if r.status == Status::Asked => {}
63            _ => return,
64        }
65        if reviewer(state) {
66            absent_since = None;
67        } else {
68            absent_since.get_or_insert_with(tokio::time::Instant::now);
69        }
70        let absent = absent_since.is_some_and(|t| t.elapsed() >= timing.absent_grace);
71        if absent || started.elapsed() >= timing.ask_wait {
72            go_ahead(state, request_id, absent);
73            return;
74        }
75        tokio::time::sleep(timing.poll).await;
76    }
77}
78
79/// The countdown for a request no super agent reviewed, or its end when nothing can run it.
80fn go_ahead(state: &AppState, request_id: &str, no_reviewer: bool) {
81    let Some(request) = requests::registry().get(request_id) else { return };
82    let Some(spec) = sensitive_ops::spec(&request.op) else { return };
83    let why = if no_reviewer { "no super agent is running" } else { "the super agent didn't answer in time" };
84    if !window::has_runner(&request.op) {
85        // Nothing here can do it: say so, rather than count down to nothing.
86        if requests::registry().finish(request_id, Status::Expired, now_ms()).is_ok() {
87            window::audit_step(state, "no super agent", &request, "sensitive.fallback", false, Some("nothing can run it from here"), "expired");
88            if crate::server::app_api::desktop::settled(&request, crate::server::app_api::desktop_group::Settled::Ended) {
89                return;
90            }
91            window::tell_askers(&request, &format!("[AgentMux] Nobody reviewed your request to {} ({why}), and this AgentMux can't run it, so it ended.", request.summary));
92        }
93        return;
94    }
95    // Answered meanwhile: the super agent's answer stands.
96    let Ok(request) = requests::registry().fallback(request_id, now_ms()) else { return };
97    let window_secs = spec.fallback_window_secs();
98    if let Err(e) = window::open(state, request_id, Duration::from_secs(window_secs)) {
99        tracing::warn!(request_id, error = %e, "sensitive request: the fallback countdown did not start");
100        crate::server::app_api::desktop::settled(&request, crate::server::app_api::desktop_group::Settled::Ended);
101        return;
102    }
103    window::audit_step(state, "no super agent", &request, "sensitive.fallback", true, None, &format!("countdown {window_secs} s, no super agent reviewed it"));
104    if crate::server::app_api::desktop::holds_progress_notes(&request) {
105        return;
106    }
107    window::tell_askers(
108        &request,
109        &format!("[AgentMux] Nobody reviewed your request to {} ({why}). The person has {window_secs} s to veto it; after that it happens.", request.summary),
110    );
111}
112
113#[cfg(test)]
114#[path = "sensitive_fallback_tests.rs"]
115mod tests;