1use 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#[derive(Clone, Debug, PartialEq)]
34struct Pause {
35 since_ms: i64,
36 by: Option<String>,
37}
38
39fn 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 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 static FORCED: std::cell::Cell<Option<bool>> = const { std::cell::Cell::new(None) };
75}
76
77#[cfg(test)]
79pub(crate) fn force_for_test(on: Option<bool>) {
80 FORCED.with(|f| f.set(on));
81}
82
83pub(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
98pub(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
113fn began_after(cur: &Option<Pause>, asked_ms: i64) -> bool {
115 cur.as_ref().is_some_and(|p| p.since_ms > asked_ms)
116}
117
118fn 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
134pub(crate) fn set(state: &AppState, on: bool, by: Option<&str>) -> BrowserPauseAll {
138 change(state, on, by, None)
139}
140
141pub(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
152fn change(state: &AppState, on: bool, by: Option<&str>, lift_only_if_asked_at: Option<i64>) -> BrowserPauseAll {
154 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
174fn 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 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 save(&p, None);
222 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 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 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}