Skip to main content

agentmux_srv/server/
browser_hibernation.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An agent's `Browser` call on a hibernated browser pane wakes it first
5//! (docs/specs/SPEC_BROWSER_PANE_HIBERNATION_2026_10_20.md ยง8).
6//!
7//! A hibernated pane has no page: its window closed it to free memory and keeps
8//! `browser:sleep` in the block's meta until a wake has loaded it again. srv
9//! can't create the page itself (the window owns where it goes), so it asks:
10//! it writes `browser:wake`, which the pane's view answers by waking, and waits
11//! for `browser:sleep` to clear.
12
13use 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
22/// Block meta while a browser pane is asleep or waking.
23pub(crate) const SLEEP_META_KEY: &str = "browser:sleep";
24/// Block meta srv writes to ask the pane's view to wake it.
25pub(crate) const WAKE_META_KEY: &str = "browser:wake";
26
27/// Block meta srv writes when an agent's `Browser` call reaches the pane (ms). The
28/// action log holds only what changed the page, so a pane an agent reads (snapshot,
29/// find) would look unused; the window counts this too before letting it sleep.
30pub(crate) const LAST_CALL_META_KEY: &str = "browser:lastcall";
31/// A call is noted at most this often per pane: the window's sleep time is minutes.
32const LAST_CALL_EVERY: Duration = Duration::from_secs(5 * 60);
33
34/// How long a `Browser` call waits for a pane to wake before failing.
35const WAKE_TIMEOUT: Duration = Duration::from_secs(30);
36const POLL: Duration = Duration::from_millis(150);
37
38/// Whether a call at `now` is due to be noted, given when the last one was.
39fn call_due(last: Option<Instant>, now: Instant) -> bool {
40    last.map_or(true, |t| now.saturating_duration_since(t) >= LAST_CALL_EVERY)
41}
42
43/// Notes in the pane's meta that an agent's call reached it, at most once per
44/// `LAST_CALL_EVERY`. A failed write is only a missed note.
45fn 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
76/// Wakes `block_id` if it is a hibernated browser pane, and waits for its page.
77/// `Ok(true)` when it was asleep and is awake now, `Ok(false)` when it wasn't
78/// asleep (or isn't a browser pane).
79pub(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
101/// Every srv call into the host's browser API goes through here: a hibernated
102/// browser pane named by the body's `block_id` has no page, so it is woken
103/// first, and the answer says so.
104pub(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
120/// The host's answer to a call that woke the pane, marked so the agent's tool
121/// can say its page was reloaded.
122pub(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}