agentmux_srv/server/
browser_hibernation.rs1use std::collections::HashMap;
14use std::sync::{Mutex, OnceLock};
15use std::time::{Duration, Instant};
16
17use serde_json::json;
18
19use crate::server::AppState;
20use crate::backend::obj::{Block, MetaMapType};
21
22pub(crate) const SLEEP_META_KEY: &str = "browser:sleep";
24pub(crate) const WAKE_META_KEY: &str = "browser:wake";
26
27pub(crate) const LAST_CALL_META_KEY: &str = "browser:lastcall";
31const LAST_CALL_EVERY: Duration = Duration::from_secs(5 * 60);
33
34const WAKE_TIMEOUT: Duration = Duration::from_secs(30);
36const POLL: Duration = Duration::from_millis(150);
37
38fn call_due(last: Option<Instant>, now: Instant) -> bool {
40 last.map_or(true, |t| now.saturating_duration_since(t) >= LAST_CALL_EVERY)
41}
42
43fn note_call(state: &AppState, block_id: &str) {
46 static LAST: OnceLock<Mutex<HashMap<String, Instant>>> = OnceLock::new();
47 let now = Instant::now();
48 {
49 let mut last = LAST.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
50 if !call_due(last.get(block_id).copied(), now) {
51 return;
52 }
53 last.insert(block_id.to_string(), now);
54 }
55 let mut meta = MetaMapType::new();
56 meta.insert(LAST_CALL_META_KEY.to_string(), json!(chrono::Utc::now().timestamp_millis()));
57 let _ = super::http_shell::broadcast_meta_update(state, block_id, &meta);
58}
59
60fn is_asleep(block: &Block) -> bool {
61 block
62 .meta
63 .get(SLEEP_META_KEY)
64 .is_some_and(|v| v.is_object())
65}
66
67fn asleep(state: &AppState, block_id: &str) -> bool {
68 state
69 .mstore
70 .get::<Block>(block_id)
71 .ok()
72 .flatten()
73 .is_some_and(|b| is_asleep(&b))
74}
75
76pub(crate) async fn ensure_awake(state: &AppState, block_id: &str) -> Result<bool, String> {
80 if block_id.is_empty() || !asleep(state, block_id) {
81 return Ok(false);
82 }
83 tracing::info!(block_id = %block_id, "[hibernate] waking a sleeping browser pane for an agent's call");
84 let mut meta = MetaMapType::new();
85 meta.insert(WAKE_META_KEY.to_string(), json!(chrono::Utc::now().timestamp_millis()));
86 super::http_shell::broadcast_meta_update(state, block_id, &meta)?;
87 let end = Instant::now() + WAKE_TIMEOUT;
88 while Instant::now() < end {
89 tokio::time::sleep(POLL).await;
90 if !asleep(state, block_id) {
91 return Ok(true);
92 }
93 }
94 Err(format!(
95 "this browser pane was asleep to save memory and didn't wake within {} s; \
96 is its window open? Try again, or open the pane",
97 WAKE_TIMEOUT.as_secs()
98 ))
99}
100
101pub(crate) async fn post_to_host_awake(
105 state: &AppState,
106 host: &crate::server::HostIpc,
107 route: &str,
108 body: serde_json::Value,
109 timeout: Option<Duration>,
110) -> Result<serde_json::Value, String> {
111 let block_id = body.get("block_id").and_then(|v| v.as_str()).unwrap_or("").to_string();
112 let woke = ensure_awake(state, &block_id).await?;
113 if !block_id.is_empty() {
114 note_call(state, &block_id);
115 }
116 let resp = super::host_http::post_to_host(&state.http_client, host, route, body, timeout).await?;
117 Ok(if woke { mark_woken(resp) } else { resp })
118}
119
120pub(crate) fn mark_woken(mut host_resp: serde_json::Value) -> serde_json::Value {
123 if let Some(data) = host_resp.get_mut("data").and_then(|d| d.as_object_mut()) {
124 data.insert("woke_from_sleep".to_string(), json!(true));
125 }
126 host_resp
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132
133 #[test]
134 fn a_sleep_record_is_an_object_and_null_is_awake() {
135 let mut b = Block::default();
136 assert!(!is_asleep(&b));
137 b.meta.insert(SLEEP_META_KEY.into(), serde_json::Value::Null);
138 assert!(!is_asleep(&b));
139 b.meta.insert(SLEEP_META_KEY.into(), json!({ "since": 1, "url": "https://x" }));
140 assert!(is_asleep(&b));
141 }
142
143 #[test]
144 fn a_pane_an_agent_owns_is_woken_by_the_agents_call_like_any_other() {
145 let mut b = Block::default();
146 b.meta.insert("browser:owner_agent".into(), json!("agent-x"));
147 b.meta.insert(SLEEP_META_KEY.into(), json!({ "since": 1, "reason": "hidden", "url": "https://x" }));
148 assert!(is_asleep(&b), "the sleep record is all `ensure_awake` looks at: ownership never blocks the wake");
149 }
150
151 #[test]
152 fn a_call_is_noted_once_in_a_while_not_on_every_snapshot() {
153 let t0 = Instant::now();
154 assert!(call_due(None, t0));
155 assert!(!call_due(Some(t0), t0 + Duration::from_secs(60)));
156 assert!(!call_due(Some(t0), t0 + LAST_CALL_EVERY - Duration::from_secs(1)));
157 assert!(call_due(Some(t0), t0 + LAST_CALL_EVERY));
158 }
159
160 #[test]
161 fn a_woken_answer_says_so_in_its_data() {
162 let r = mark_woken(json!({ "ok": true, "data": { "snapshot": "x" } }));
163 assert_eq!(r["data"]["woke_from_sleep"], json!(true));
164 let r = mark_woken(json!({ "ok": false, "error": "e" }));
165 assert!(r.get("data").is_none());
166 }
167}