Skip to main content

agentmux_srv/server/streamed_browser/
host.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `agentmux-srv --streamed-browser-host`: the streamed browser as a server of its own. It runs in a task made for one
5//! person's browser and serves nothing else: the pane's WebSocket and `/health`. No database, no agents, no auth key,
6//! none of srv's other routes.
7//!
8//! A connection must carry a lease token (`x-agentmux-lease`) signed for this lease and workspace, checked against the
9//! public keys the host was given (`lease_token`). A token opens one connection; a second connection while one is open is
10//! refused. The page, the stream and the input are the same code as the headless pane's.
11//!
12//! Settings: `--browser-host-listen <address:port>` (default `0.0.0.0:8291`), and the environment
13//! `AGENTMUX_BROWSER_HOST_PUBLIC_KEYS` (JSON, key id to base64 SPKI), `AGENTMUX_BROWSER_HOST_LEASE` and
14//! `AGENTMUX_BROWSER_HOST_WORKSPACE`. The profile is a fresh folder under the temp directory.
15
16use std::net::SocketAddr;
17use std::sync::atomic::{AtomicBool, Ordering};
18use std::sync::Arc;
19
20use axum::extract::{Query, State, WebSocketUpgrade};
21use axum::extract::ws::rejection::WebSocketUpgradeRejection;
22use axum::http::{HeaderMap, StatusCode};
23use axum::response::{IntoResponse, Response};
24use axum::routing::get;
25use axum::Router;
26use tokio_util::sync::CancellationToken;
27
28use super::lease_token::{parse_public_keys, LeaseGate};
29use super::{start_from, Params, ROUTE};
30
31/// The flag that starts srv in this mode.
32pub const FLAG: &str = "--streamed-browser-host";
33const LISTEN_FLAG: &str = "--browser-host-listen";
34const DEFAULT_LISTEN: &str = "0.0.0.0:8291";
35const KEYS_ENV: &str = "AGENTMUX_BROWSER_HOST_PUBLIC_KEYS";
36const LEASE_ENV: &str = "AGENTMUX_BROWSER_HOST_LEASE";
37const WORKSPACE_ENV: &str = "AGENTMUX_BROWSER_HOST_WORKSPACE";
38/// The header the lease token arrives in.
39pub const TOKEN_HEADER: &str = "x-agentmux-lease";
40
41/// How long an open pane gets to end after the server is told to stop.
42const STOP_GRACE: std::time::Duration = std::time::Duration::from_secs(5);
43
44/// How long the host may have no pane open before it ends itself: the task then stops, and the lease that named it
45/// ends with it. Counted from the start, and again from each time a pane that was let in goes away.
46const IDLE_EXIT: std::time::Duration = std::time::Duration::from_secs(10 * 60);
47/// How often the idle clock is looked at.
48const IDLE_CHECK_EVERY: std::time::Duration = std::time::Duration::from_secs(15);
49
50/// What the server holds: the gate, whether a connection is open, the signal that ends the server and its pane, and
51/// since when no accepted pane has been open (`None` while one is).
52struct Host {
53    gate: LeaseGate,
54    open: AtomicBool,
55    stop: CancellationToken,
56    idle_since: std::sync::Mutex<Option<std::time::Instant>>,
57}
58
59impl Host {
60    fn idle_for(&self) -> Option<std::time::Duration> {
61        self.idle_since.lock().ok().and_then(|s| s.map(|t| t.elapsed()))
62    }
63
64    fn set_idle(&self, since: Option<std::time::Instant>) {
65        if let Ok(mut s) = self.idle_since.lock() {
66            *s = since;
67        }
68    }
69}
70
71/// Ends the server once it has had no accepted pane for `limit`, looking every `every`. A refused connection
72/// (no token, a bad token) does not count as a pane, so it cannot keep the host alive.
73async fn end_when_idle(host: Arc<Host>, limit: std::time::Duration, every: std::time::Duration) {
74    loop {
75        tokio::select! {
76            _ = host.stop.cancelled() => return,
77            _ = tokio::time::sleep(every) => {}
78        }
79        if host.idle_for().is_some_and(|idle| idle >= limit) {
80            eprintln!("agentmux-srv {FLAG}: no pane for {} s, ending", limit.as_secs());
81            host.stop.cancel();
82            return;
83        }
84    }
85}
86
87/// Was srv started as the browser host?
88pub(crate) fn requested() -> bool {
89    std::env::args_os().any(|a| a == FLAG)
90}
91
92/// Runs the browser host and exits when srv was started as one; returns when it was not.
93pub(crate) async fn exit_if_requested() {
94    if !requested() {
95        return;
96    }
97    let args: Vec<String> = std::env::args().collect();
98    match run(&args).await {
99        Ok(()) => std::process::exit(0),
100        Err(e) => {
101            eprintln!("agentmux-srv {FLAG}: {e}");
102            std::process::exit(1);
103        }
104    }
105}
106
107/// The address to listen on: the flag's value, else the default.
108fn listen_from(args: &[String]) -> Result<SocketAddr, String> {
109    let value = args.iter().position(|a| a == LISTEN_FLAG).map(|i| args.get(i + 1).ok_or(format!("{LISTEN_FLAG} needs an address")));
110    let text = match value {
111        Some(v) => v?.as_str(),
112        None => DEFAULT_LISTEN,
113    };
114    text.parse().map_err(|e| format!("{LISTEN_FLAG} {text}: {e}"))
115}
116
117fn host_from(env: impl Fn(&str) -> Option<String>) -> Result<Host, String> {
118    let need = |name: &str| env(name).filter(|v| !v.trim().is_empty()).ok_or(format!("{name} is not set"));
119    let keys = parse_public_keys(&need(KEYS_ENV)?)?;
120    Ok(Host {
121        gate: LeaseGate::new(keys, need(LEASE_ENV)?, need(WORKSPACE_ENV)?),
122        open: AtomicBool::new(false),
123        stop: CancellationToken::new(),
124        idle_since: std::sync::Mutex::new(Some(std::time::Instant::now())),
125    })
126}
127
128/// A folder only this process can open, named at random: the browser's profile lives under it, and it is removed at exit.
129fn private_dir() -> Result<std::path::PathBuf, String> {
130    let dir = std::env::temp_dir().join(format!("agentmux-browser-{}", uuid::Uuid::new_v4()));
131    let mut make = std::fs::DirBuilder::new();
132    #[cfg(unix)]
133    std::os::unix::fs::DirBuilderExt::mode(&mut make, 0o700);
134    make.create(&dir).map_err(|e| format!("cannot make the browser's profile folder: {e}"))?;
135    Ok(dir)
136}
137
138fn router(host: Arc<Host>) -> Router {
139    Router::new().route("/health", get(|| async { "ok" })).route(ROUTE, get(connect)).with_state(host)
140}
141
142async fn run(args: &[String]) -> Result<(), String> {
143    let listen = listen_from(args)?;
144    let host = Arc::new(host_from(|n| std::env::var(n).ok())?);
145    let profile = private_dir()?;
146    super::chromium::use_profile_root(profile.clone());
147    let served = serve(listen, host).await;
148    let _ = std::fs::remove_dir_all(&profile);
149    served
150}
151
152async fn serve(listen: SocketAddr, host: Arc<Host>) -> Result<(), String> {
153    super::address_policy::note_ports_from_env();
154    let listener = tokio::net::TcpListener::bind(listen).await.map_err(|e| format!("cannot listen on {listen}: {e}"))?;
155    if let Ok(addr) = listener.local_addr() {
156        // A page in the browser may never connect to this server's own port.
157        super::address_policy::note_own_port(addr.port());
158    }
159    eprintln!("agentmux-srv {FLAG}: listening on {listen}");
160    let stop = host.stop.clone();
161    tokio::spawn(end_when_idle(host.clone(), IDLE_EXIT, IDLE_CHECK_EVERY));
162    tokio::spawn({
163        let stop = stop.clone();
164        async move {
165            shutdown().await;
166            stop.cancel();
167        }
168    });
169    let served = axum::serve(listener, router(host)).with_graceful_shutdown(stop.clone().cancelled_owned());
170    // An open pane ends with the stop signal; the grace bounds the wait for one that does not.
171    tokio::select! {
172        r = served => r.map_err(|e| e.to_string()),
173        _ = async { stop.cancelled().await; tokio::time::sleep(STOP_GRACE).await } => Ok(()),
174    }
175}
176
177/// SIGTERM (a task being stopped) and SIGINT end the server; as a container's first process it has no default for them.
178async fn shutdown() {
179    #[cfg(unix)]
180    {
181        use tokio::signal::unix::{signal, SignalKind};
182        let (Ok(mut term), Ok(mut int)) = (signal(SignalKind::terminate()), signal(SignalKind::interrupt())) else {
183            return std::future::pending().await;
184        };
185        tokio::select! { _ = term.recv() => {}, _ = int.recv() => {} }
186    }
187    #[cfg(not(unix))]
188    std::future::pending::<()>().await;
189}
190
191/// Releases the one open connection when the pane ends, however it ends.
192struct Open(Arc<Host>);
193
194impl Drop for Open {
195    fn drop(&mut self) {
196        self.0.open.store(false, Ordering::SeqCst);
197    }
198}
199
200/// Held by a pane the host let in: while it lives the host is not idle, and when it goes the idle clock starts over.
201struct Serving(Arc<Host>);
202
203impl Serving {
204    fn begin(host: &Arc<Host>) -> Self {
205        host.set_idle(None);
206        Self(host.clone())
207    }
208}
209
210impl Drop for Serving {
211    fn drop(&mut self) {
212        self.0.set_idle(Some(std::time::Instant::now()));
213    }
214}
215
216/// `GET /agentmux/streamed-browser?url=&w=&h=` with a lease token, upgraded to a WebSocket.
217async fn connect(
218    State(host): State<Arc<Host>>,
219    headers: HeaderMap,
220    Query(params): Query<Params>,
221    ws: Result<WebSocketUpgrade, WebSocketUpgradeRejection>,
222) -> Response {
223    let Some(token) = headers.get(TOKEN_HEADER).and_then(|v| v.to_str().ok()) else {
224        return (StatusCode::UNAUTHORIZED, "a lease token is needed").into_response();
225    };
226    let Ok(ws) = ws else {
227        return (StatusCode::UPGRADE_REQUIRED, "this route is a WebSocket").into_response();
228    };
229    let start = match start_from(&params) {
230        Ok(s) => s,
231        Err(e) => return (StatusCode::BAD_REQUEST, e).into_response(),
232    };
233    // Checked last of the refusals that cost nothing, so a refused connection never uses up a token.
234    if host.open.swap(true, Ordering::SeqCst) {
235        return (StatusCode::CONFLICT, "this browser is already open").into_response();
236    }
237    let open = Open(host.clone());
238    if let Err(why) = host.gate.accept(token, agentmux_common::time::now_secs_u64()) {
239        tracing::warn!(?why, "browser host: a lease token was refused");
240        return (StatusCode::FORBIDDEN, "the lease token was refused").into_response();
241    }
242    let stop = host.stop.clone();
243    let serving = Serving::begin(&host);
244    super::open_pane(params.mode.as_deref(), ws, start, async move {
245        let _open = open;
246        let _serving = serving;
247        stop.cancelled().await
248    })
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    fn args(list: &[&str]) -> Vec<String> {
256        list.iter().map(|s| s.to_string()).collect()
257    }
258
259    #[test]
260    fn it_listens_where_it_is_told_and_otherwise_on_the_default() {
261        assert_eq!(listen_from(&args(&["srv", FLAG])).unwrap().port(), 8291);
262        assert_eq!(listen_from(&args(&["srv", FLAG, LISTEN_FLAG, "10.0.0.5:9000"])).unwrap().to_string(), "10.0.0.5:9000");
263        assert!(listen_from(&args(&["srv", FLAG, LISTEN_FLAG])).is_err());
264        assert!(listen_from(&args(&["srv", FLAG, LISTEN_FLAG, "nonsense"])).is_err());
265    }
266
267    #[tokio::test]
268    async fn it_serves_health_and_the_pane_route_and_nothing_else() {
269        let keys = r#"{"k1":"MCowBQYDK2VwAyEA6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw="}"#;
270        let host = Arc::new(host_from(|n| Some(if n == KEYS_ENV { keys } else { "x1234567890a" }.to_string())).unwrap());
271        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
272        let base = format!("http://{}", listener.local_addr().unwrap());
273        tokio::spawn(async move { axum::serve(listener, router(host)).await.unwrap() });
274        let get = |path: &str, token: Option<&str>| {
275            let mut req = reqwest::Client::new().get(format!("{base}{path}"));
276            if let Some(t) = token {
277                req = req.header(TOKEN_HEADER, t);
278            }
279            async move { req.send().await.unwrap().status() }
280        };
281        assert_eq!(get("/health", None).await, StatusCode::OK);
282        assert_eq!(get(ROUTE, None).await, StatusCode::UNAUTHORIZED, "no token, no pane");
283        assert_eq!(get(ROUTE, Some("lease1")).await, StatusCode::UPGRADE_REQUIRED, "a plain request is told to upgrade");
284        for other in ["/", "/ws", "/agentmux/streamed-browser/x", "/api/anything"] {
285            assert_eq!(get(other, None).await, StatusCode::NOT_FOUND, "{other}");
286        }
287    }
288
289    fn test_host() -> Arc<Host> {
290        let keys = r#"{"k1":"MCowBQYDK2VwAyEA6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw="}"#;
291        Arc::new(host_from(|n| Some(if n == KEYS_ENV { keys } else { "x1234567890a" }.to_string())).unwrap())
292    }
293
294    #[tokio::test]
295    async fn it_ends_when_it_is_told_to_stop() {
296        let host = test_host();
297        let stop = host.stop.clone();
298        let served = tokio::spawn(serve("127.0.0.1:0".parse().unwrap(), host));
299        stop.cancel();
300        let ended = tokio::time::timeout(STOP_GRACE + std::time::Duration::from_secs(2), served).await;
301        assert!(matches!(ended, Ok(Ok(Ok(())))), "{ended:?}");
302    }
303
304    const SHORT: std::time::Duration = std::time::Duration::from_millis(60);
305    const TICK: std::time::Duration = std::time::Duration::from_millis(10);
306
307    #[tokio::test]
308    async fn it_ends_itself_when_no_pane_has_come_for_the_idle_limit() {
309        let host = test_host();
310        let watcher = tokio::spawn(end_when_idle(host.clone(), SHORT, TICK));
311        tokio::time::timeout(std::time::Duration::from_secs(5), host.stop.cancelled()).await.expect("it stops itself");
312        watcher.await.unwrap();
313    }
314
315    #[tokio::test]
316    async fn it_does_not_end_while_a_pane_is_open_and_starts_the_clock_again_when_it_goes() {
317        let host = test_host();
318        let watcher = tokio::spawn(end_when_idle(host.clone(), SHORT, TICK));
319        let serving = Serving::begin(&host);
320        assert!(host.idle_for().is_none());
321        tokio::time::sleep(SHORT * 4).await;
322        assert!(!host.stop.is_cancelled(), "a pane is open, so it is not idle");
323        drop(serving);
324        // The clock restarts at the pane's end, not at the host's start.
325        assert!(host.idle_for().unwrap() < SHORT);
326        tokio::time::timeout(std::time::Duration::from_secs(5), host.stop.cancelled()).await.expect("idle again, so it ends");
327        watcher.await.unwrap();
328    }
329
330    #[tokio::test]
331    async fn a_refused_connection_does_not_keep_it_alive() {
332        let host = test_host();
333        // What `connect` does before the token is checked: take the open flag, then give it back on a refusal.
334        let before = host.idle_for().unwrap();
335        host.open.store(true, Ordering::SeqCst);
336        drop(Open(host.clone()));
337        assert!(host.idle_for().unwrap() >= before, "the idle clock was not reset by a refusal");
338    }
339
340    #[tokio::test]
341    async fn it_stops_looking_when_it_was_stopped_for_another_reason() {
342        let host = test_host();
343        let watcher = tokio::spawn(end_when_idle(host.clone(), std::time::Duration::from_secs(3600), TICK));
344        host.stop.cancel();
345        tokio::time::timeout(std::time::Duration::from_secs(5), watcher).await.expect("the watcher returns").unwrap();
346    }
347
348    #[test]
349    fn the_profile_folder_is_new_each_time_and_private() {
350        let (a, b) = (private_dir().unwrap(), private_dir().unwrap());
351        assert_ne!(a, b);
352        #[cfg(unix)]
353        {
354            use std::os::unix::fs::PermissionsExt;
355            assert_eq!(std::fs::metadata(&a).unwrap().permissions().mode() & 0o777, 0o700);
356        }
357        for d in [a, b] {
358            std::fs::remove_dir_all(d).unwrap();
359        }
360    }
361
362    #[test]
363    fn it_does_not_start_without_its_keys_lease_and_workspace() {
364        let keys = r#"{"k1":"MCowBQYDK2VwAyEA6kpsY+KcUgq+9VB7Ey7F+ZVHdq6+vnuSQh7qaRRG0iw="}"#;
365        let env = |missing: &'static str| {
366            move |n: &str| match n {
367                _ if n == missing => None,
368                KEYS_ENV => Some(keys.to_string()),
369                LEASE_ENV => Some("lse-abc123".to_string()),
370                WORKSPACE_ENV => Some("abcdefghijkl".to_string()),
371                _ => None,
372            }
373        };
374        assert!(host_from(env("")).is_ok());
375        for missing in [KEYS_ENV, LEASE_ENV, WORKSPACE_ENV] {
376            let why = host_from(env(missing)).err().unwrap();
377            assert!(why.contains(missing), "{why}");
378        }
379    }
380}