Skip to main content

agentmux_srv/server/
browser_session_close.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! When a background browser session closes by itself (docs/specs/SPEC_BACKGROUND_BROWSER_SESSIONS_2026_11_28.md ยง4
5//! item 9): its agent was stopped, the agent has done nothing for an hour, or the app restarted. A session has no
6//! window the person sees, so one nobody closes would hold a page, its memory and its sign-in for as long as the app
7//! runs. A pane the person Showed is a pane, not a session, and none of this touches it.
8
9use crate::backend::obj::Block;
10use crate::server::pane_openers::{background_sessions, Session};
11use crate::server::AppState;
12
13/// How long the agent can do nothing before its sessions close: its transcript has not been written for this long.
14pub(crate) const IDLE_LIMIT_MS: u64 = 60 * 60 * 1000;
15
16/// How long after srv starts the sessions the last run left are closed: the workspace is loaded by then.
17const RESTART_CLOSE_DELAY: std::time::Duration = std::time::Duration::from_secs(10);
18
19/// Whether an agent last active at `last_ms` has been idle for the limit at `now_ms`.
20pub(crate) fn idle_for_the_limit(last_ms: u64, now_ms: u64) -> bool {
21    now_ms.saturating_sub(last_ms) >= IDLE_LIMIT_MS
22}
23
24/// The sessions held by the agent pane `agent_block`.
25fn held_by(sessions: Vec<Session>, agent_block: &str) -> Vec<Session> {
26    sessions.into_iter().filter(|s| s.from_block.as_deref() == Some(agent_block)).collect()
27}
28
29/// Close the session `s` for `why`, now: the person is not asked to keep it (a tab the agent closes itself has that
30/// window; a session has no window to ask in, and one that was kept would be asked about again every minute). The Audit
31/// row is written once the pane is closed, with the site read before it goes.
32async fn close_one(state: &AppState, s: &Session, why: &str) {
33    // The person may have Showed it since the sweep listed it: it is a pane then, and stays.
34    if !crate::server::pane_openers::is_background(&s.pane) {
35        return;
36    }
37    let site = crate::server::browser_sessions::site_of(state, &s.pane);
38    let opts = crate::sagas::close_pane::CloseOpts { frontend_waits: true, ..Default::default() };
39    match crate::sagas::close_pane::run_with(state, vec![s.pane.clone()], opts).await {
40        Ok(_) => crate::server::browser_sessions::audit_closed(state, &s.agent, &format!("close ({why})"), &s.pane, &site),
41        Err(e) => tracing::warn!(pane = %s.pane, agent = %s.agent, "[browser-sessions] a session did not close ({why}): {e}"),
42    }
43}
44
45/// The agent panes whose agent was stopped, whose sessions the next sweep closes.
46static STOPPED: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
47
48/// The agent in the pane `agent_block` was stopped: its sessions close with it, at once (the sweep is woken). A Stop docks
49/// only the floating panes the person sees, so nothing else would end them. Not closed here: the teardown that calls this
50/// is itself part of closing a pane, and a close from inside it would be a cycle.
51pub(crate) fn close_for_stop(agent_block: &str) {
52    if held_by(background_sessions(), agent_block).is_empty() {
53        return;
54    }
55    STOPPED.lock().unwrap_or_else(|p| p.into_inner()).push(agent_block.to_string());
56    crate::server::browser_owner::changed().notify_one();
57}
58
59/// The sessions of the agents stopped since the last sweep close.
60async fn close_stopped(state: &AppState) {
61    let stopped: Vec<String> = std::mem::take(&mut *STOPPED.lock().unwrap_or_else(|p| p.into_inner()));
62    for agent_block in stopped {
63        for s in held_by(background_sessions(), &agent_block) {
64            close_one(state, &s, "its agent was stopped").await;
65        }
66    }
67}
68
69/// The sessions that are due to close: those of an agent that was stopped, and of one that has done nothing for an hour.
70/// Called every minute and when an agent is stopped.
71pub(crate) async fn close_due(state: &AppState) {
72    close_stopped(state).await;
73    let now = agentmux_common::time::now_ms_u64();
74    for s in background_sessions() {
75        let Some(from) = s.from_block.as_deref() else { continue };
76        let block = match state.mstore.get::<Block>(from) {
77            Ok(Some(block)) => block,
78            // Its agent's pane is gone: no one is left to hold the session.
79            Ok(None) => {
80                close_one(state, &s, "its agent's pane is gone").await;
81                continue;
82            }
83            // The store failed to answer: nothing says the pane is gone.
84            Err(_) => continue,
85        };
86        // A turn still running (a long tool call writes nothing for a while) is not idle.
87        if crate::backend::blockcontroller::get_block_controller_status(from).is_some_and(|status| status.turn_active) {
88            continue;
89        }
90        // No transcript: nothing says it is idle, so the session stays until the agent is stopped.
91        let Some(last) = crate::server::restart_resume::last_active_ms(state, &s.agent, &block) else { continue };
92        if idle_for_the_limit(last, now) {
93            close_one(state, &s, "its agent was idle for an hour").await;
94        }
95    }
96}
97
98/// The sessions the last run left close: a session is not restored.
99pub(crate) fn close_left_by_the_last_run(state: &AppState) {
100    let state = state.clone();
101    // The ones left now: a session an agent opens while srv is starting is this run's, and stays.
102    let left = background_sessions();
103    tokio::spawn(async move {
104        tokio::time::sleep(RESTART_CLOSE_DELAY).await;
105        for s in left {
106            close_one(&state, &s, "the app restarted").await;
107        }
108    });
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    fn session(pane: &str, from: Option<&str>) -> Session {
116        Session { pane: pane.to_string(), agent: "alice".to_string(), from_block: from.map(str::to_string) }
117    }
118
119    #[test]
120    fn idle_only_from_the_limit_on() {
121        let hour = IDLE_LIMIT_MS;
122        assert!(!idle_for_the_limit(1_000, 1_000 + hour - 1));
123        assert!(idle_for_the_limit(1_000, 1_000 + hour));
124        // A clock that went back is not idle.
125        assert!(!idle_for_the_limit(5_000, 1_000));
126    }
127
128    #[test]
129    fn a_stop_marks_only_an_agent_pane_that_holds_a_session() {
130        crate::server::pane_openers::record_floating("bsc-s1", "alice", true, Some("bsc-agent"));
131        close_for_stop("bsc-agent");
132        close_for_stop("bsc-no-session");
133        let marked = STOPPED.lock().unwrap_or_else(|p| p.into_inner()).clone();
134        assert!(marked.contains(&"bsc-agent".to_string()));
135        assert!(!marked.contains(&"bsc-no-session".to_string()));
136        crate::server::pane_openers::forget("bsc-s1");
137    }
138
139    #[test]
140    fn a_stop_takes_the_sessions_of_its_own_pane_only() {
141        let all = vec![session("s1", Some("agent-a")), session("s2", Some("agent-b")), session("s3", None), session("s4", Some("agent-a"))];
142        let panes: Vec<String> = held_by(all, "agent-a").into_iter().map(|s| s.pane).collect();
143        assert_eq!(panes, ["s1", "s4"]);
144    }
145}