Skip to main content

agentmux_srv/server/
browser_pause_all.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! "Pause all agent browsing": one emergency switch
5//! (docs/specs/SPEC_BROWSER_WEB_TERMINAL_TYPING_2026_10_23.md ยง7, D9). While
6//! it is on, every pane an agent drives refuses every agent call, and the
7//! clocks of their Auto-approve grants stand still (`browser_actions::is_paused`
8//! answers for it, so everything that honours a pane's Pause honours this).
9//!
10//! It is kept in a file in the config folder, so a restart does not switch it
11//! off: an emergency stop that reset itself would defeat its point. A file
12//! that exists but can't be read counts as on.
13//!
14//! Anyone may turn it on (`browsergrants.pauseall`): the person from their
15//! window, an agent from its connection, and it records who. The person turns
16//! it off from their window. An agent asks for that as the sensitive operation
17//! `resume_agent_browsing`: the super agent reviews it, the person sees a
18//! countdown and can veto it, and it is recorded as that agent, never as the
19//! person (docs/specs/SPEC_SUPER_AGENT_2026_10_25.md).
20
21use std::sync::{Mutex, OnceLock};
22
23use crate::backend::rpc_types::BrowserPauseAll;
24use crate::server::AppState;
25
26const FILE_NAME: &str = "browser-pause-all.json";
27
28fn path() -> std::path::PathBuf {
29    crate::backend::base::get_mux_config_dir().join(FILE_NAME)
30}
31
32/// The switch while it is on: when, and who turned it on (None: the person).
33#[derive(Clone, Debug, PartialEq)]
34struct Pause {
35    since_ms: i64,
36    by: Option<String>,
37}
38
39/// The switch as `path` holds it: on if the file is there. A file that exists but can't be read,
40/// or has nothing readable in it, reads as on since 0: fail closed. No file is off.
41fn read_file(path: &std::path::Path) -> Option<Pause> {
42    match std::fs::read(path) {
43        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
44        Err(_) => Some(Pause { since_ms: 0, by: None }),
45        Ok(bytes) => {
46            let v = serde_json::from_slice::<serde_json::Value>(&bytes).ok();
47            let field = |k: &str| v.as_ref().and_then(|v| v.get(k).cloned());
48            Some(Pause {
49                since_ms: field("since_ms").and_then(|m| m.as_i64()).unwrap_or(0),
50                by: field("by").and_then(|b| b.as_str().map(str::to_string)).filter(|b| !b.is_empty()),
51            })
52        }
53    }
54}
55
56fn slot() -> std::sync::MutexGuard<'static, Option<Pause>> {
57    static S: OnceLock<Mutex<Option<Pause>>> = OnceLock::new();
58    // A test never reads the real config folder: it starts with the switch off.
59    S.get_or_init(|| Mutex::new(if cfg!(test) { None } else { read_file(&path()) })).lock().unwrap_or_else(|p| p.into_inner())
60}
61
62pub(crate) fn is_on() -> bool {
63    #[cfg(test)]
64    if let Some(on) = FORCED.with(|f| f.get()) {
65        return on;
66    }
67    slot().is_some()
68}
69
70#[cfg(test)]
71thread_local! {
72    /// A test's own answer for [`is_on`], on its own thread: the switch is
73    /// process-wide and kept in the config folder, which a test must not touch.
74    static FORCED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
75}
76
77/// Make [`is_on`] answer `on` on this thread (`None`: the real switch again).
78#[cfg(test)]
79pub(crate) fn force_for_test(on: Option<bool>) {
80    FORCED.with(|f| f.set(on));
81}
82
83/// For `Browser` `open`, which resolves no pane of its own: the caller's pane,
84/// once its identity is verified, and a refusal while the switch is on (a new
85/// pane is a pane an agent would drive).
86pub(crate) fn open_block_id(
87    state: &AppState,
88    caller: Option<&crate::server::caller::Caller>,
89    auth: &agentmux_common::api_types::UiAutomationAuth,
90) -> Result<String, (axum::http::StatusCode, String)> {
91    let own = crate::server::ui_handlers::verified_block_id(state, caller, auth).map_err(|e| (axum::http::StatusCode::UNAUTHORIZED, e))?;
92    if is_on() {
93        return Err((axum::http::StatusCode::CONFLICT, format!("{} (no pane was opened)", refusal())));
94    }
95    Ok(own)
96}
97
98/// What an agent is told while the switch is on: who paused all agent browsing (the person, or the
99/// agent that did) and how it is lifted.
100pub(crate) fn refusal() -> String {
101    let who = status().by.unwrap_or_else(|| "the user".to_string());
102    format!(
103        "{who} paused all agent browsing; your calls on browser panes wait until it is resumed. Ask the person in chat, or file the \
104         resume_agent_browsing operation with the Sensitive tool (the person can veto it)"
105    )
106}
107
108pub(crate) fn status() -> BrowserPauseAll {
109    let pause = slot().clone();
110    BrowserPauseAll { paused: pause.is_some(), since_ms: pause.as_ref().map(|p| p.since_ms), by: pause.and_then(|p| p.by) }
111}
112
113/// Whether the pause on began after `asked_ms`: a different one from the pause a request was made about.
114fn began_after(cur: &Option<Pause>, asked_ms: i64) -> bool {
115    cur.as_ref().is_some_and(|p| p.since_ms > asked_ms)
116}
117
118/// Move `cur` to on or off. Returns whether that changed anything: turning it on again keeps who
119/// turned it on first, and off again is nothing.
120fn apply(cur: &mut Option<Pause>, on: bool, by: Option<&str>, now_ms: i64) -> bool {
121    match (on, cur.is_some()) {
122        (true, false) => {
123            *cur = Some(Pause { since_ms: now_ms, by: by.map(str::to_string) });
124            true
125        }
126        (false, true) => {
127            *cur = None;
128            true
129        }
130        _ => false,
131    }
132}
133
134/// Turn the switch on or off, as `by` (None: the person). Returns where it stands now. A change
135/// is kept in the file, held on every grant's clock, shown on every driven pane's header and Log
136/// (as `by`, never as the person when an agent did it), and sent to the windows' status bars.
137pub(crate) fn set(state: &AppState, on: bool, by: Option<&str>) -> BrowserPauseAll {
138    change(state, on, by, None)
139}
140
141/// Lift the switch for a request made at `asked_ms`, if the pause it was made about is still the one
142/// on: a pause turned on after the request is a new emergency, and the old approval doesn't undo it.
143/// Err says why nothing was lifted.
144pub(crate) fn lift_asked_at(state: &AppState, by: &str, asked_ms: i64) -> Result<(), String> {
145    let now = change(state, false, Some(by), Some(asked_ms));
146    match now.since_ms {
147        Some(since) if now.paused && since > asked_ms => Err("agent browsing was paused again after this was asked, so it stays paused: ask again".to_string()),
148        _ => Ok(()),
149    }
150}
151
152/// [`set`], with `lift_only_if_asked_at`: when given, a pause that began after that time is left alone.
153fn change(state: &AppState, on: bool, by: Option<&str>, lift_only_if_asked_at: Option<i64>) -> BrowserPauseAll {
154    // The file is written under the same hold as the slot, so two changes at once can't leave
155    // the file saying one thing and memory another (a missing file means unpaused after a restart).
156    let changed = {
157        let mut s = slot();
158        let newer = lift_only_if_asked_at.is_some_and(|t| began_after(&s, t));
159        let changed = !newer && apply(&mut s, on, by, chrono::Utc::now().timestamp_millis());
160        if changed {
161            persist(s.as_ref());
162        }
163        changed
164    };
165    let now = status();
166    if changed {
167        tracing::info!(paused = on, by = by.unwrap_or("the user"), "[browser-pause-all] all agent browsing was {}", if on { "paused" } else { "resumed" });
168        crate::server::browser_actions::pause_all_changed(state, on, by);
169        state.broker.publish_event::<crate::backend::mps_events::BrowserPauseAllChanged>(&now, vec![], 1);
170    }
171    now
172}
173
174/// Keep the switch in its file. A test keeps nothing on disk.
175fn persist(pause: Option<&Pause>) {
176    if !cfg!(test) {
177        save(&path(), pause);
178    }
179}
180
181fn save(path: &std::path::Path, pause: Option<&Pause>) {
182    let done = match pause {
183        Some(p) => std::fs::create_dir_all(path.parent().unwrap_or(std::path::Path::new(".")))
184            .and_then(|()| std::fs::write(path, serde_json::json!({ "since_ms": p.since_ms, "by": p.by }).to_string())),
185        None => match std::fs::remove_file(path) {
186            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
187            r => r,
188        },
189    };
190    if let Err(e) = done {
191        // The switch holds for this run; it won't survive a restart.
192        tracing::warn!(error = %e, "[browser-pause-all] couldn't keep the switch in its file");
193    }
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199
200    #[test]
201    fn a_request_to_lift_does_not_undo_a_pause_made_after_it() {
202        let paused_at = |ms| Some(Pause { since_ms: ms, by: None });
203        assert!(!began_after(&paused_at(100), 100), "the pause it was asked about");
204        assert!(!began_after(&paused_at(50), 100), "an older one still counts as the same");
205        assert!(began_after(&paused_at(101), 100), "a new emergency after the request");
206        assert!(!began_after(&None, 100), "nothing on: nothing to protect");
207    }
208
209    #[test]
210    fn an_unreadable_file_reads_as_on_and_a_missing_one_as_off() {
211        let dir = tempfile::tempdir().unwrap();
212        let p = dir.path().join(FILE_NAME);
213        assert_eq!(read_file(&p), None);
214        save(&p, Some(&Pause { since_ms: 1234, by: None }));
215        assert_eq!(read_file(&p), Some(Pause { since_ms: 1234, by: None }));
216        std::fs::write(&p, "not json").unwrap();
217        assert_eq!(read_file(&p), Some(Pause { since_ms: 0, by: None }));
218        save(&p, None);
219        assert_eq!(read_file(&p), None);
220        // Turning it off twice is fine.
221        save(&p, None);
222        // A path that is there but can't be read as a file (here a folder) is on, not off.
223        std::fs::create_dir(&p).unwrap();
224        assert_eq!(read_file(&p), Some(Pause { since_ms: 0, by: None }));
225    }
226
227    #[test]
228    fn the_file_keeps_who_paused_so_a_restart_still_says() {
229        let dir = tempfile::tempdir().unwrap();
230        let p = dir.path().join(FILE_NAME);
231        save(&p, Some(&Pause { since_ms: 5, by: Some("naki-2".to_string()) }));
232        assert_eq!(read_file(&p), Some(Pause { since_ms: 5, by: Some("naki-2".to_string()) }));
233        // A file from before the switch recorded who reads as the person's.
234        std::fs::write(&p, r#"{"since_ms":9}"#).unwrap();
235        assert_eq!(read_file(&p), Some(Pause { since_ms: 9, by: None }));
236    }
237
238    #[test]
239    fn turning_it_on_records_who_and_again_changes_nothing() {
240        let mut cur = None;
241        assert!(apply(&mut cur, true, Some("naki-2"), 10));
242        assert_eq!(cur, Some(Pause { since_ms: 10, by: Some("naki-2".to_string()) }));
243        // Another agent turning it on again doesn't take over the record.
244        assert!(!apply(&mut cur, true, None, 20));
245        assert_eq!(cur.as_ref().unwrap().by.as_deref(), Some("naki-2"));
246        assert!(apply(&mut cur, false, Some("agent1"), 30));
247        assert_eq!(cur, None);
248        assert!(!apply(&mut cur, false, None, 40));
249    }
250}