Skip to main content

agentmux_srv/server/streamed_browser/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Browser pane for the web UI of a headless srv: a Chromium on the server, its page streamed to the
5//! pane as JPEG frames over a WebSocket, input sent back. Opt-in (`AGENTMUX_STREAMED_BROWSER=1`,
6//! headless only); see docs/specs/SPEC_STREAMED_BROWSER_PANE_DEMO_2026_11_15.md for the conditions it runs
7//! under (our own hosts, behind the sign-in, its own profile, `--no-sandbox` for the demo only).
8//!
9//! The route is behind the same layers as `/ws`: the key, or a signed-in browser's cookie and token.
10
11mod address_policy;
12#[cfg_attr(not(unix), allow(dead_code))]
13mod address_proxy;
14#[cfg_attr(not(unix), allow(dead_code))]
15mod cdp;
16#[cfg_attr(not(unix), allow(dead_code))]
17mod chromium;
18#[cfg(test)]
19mod fake_browser;
20mod host;
21mod lease_token;
22mod nav;
23#[cfg_attr(not(unix), allow(dead_code))]
24mod pane;
25#[cfg_attr(not(unix), allow(dead_code))]
26mod popups;
27mod protocol;
28#[cfg(target_os = "linux")]
29mod screen;
30#[cfg_attr(not(unix), allow(dead_code))]
31mod windows;
32
33use axum::extract::ws::rejection::WebSocketUpgradeRejection;
34use axum::extract::{Extension, Query, WebSocketUpgrade};
35use axum::http::StatusCode;
36use axum::response::{IntoResponse, Response};
37use serde::Deserialize;
38
39use super::local_session::SessionId;
40use super::local_session_routes::{session_ended, WS_PROTOCOL};
41
42pub(crate) use host::exit_if_requested as exit_if_browser_host;
43
44/// Note a port this server listens on: a page in the browser may never connect to it (`address_policy`).
45pub fn note_own_port(port: u16) {
46    address_policy::note_own_port(port);
47}
48
49/// The route (the same literal is registered in `routes.rs`; a test holds them together).
50pub const ROUTE: &str = "/agentmux/streamed-browser";
51/// `1` in the environment turns the streamed browser on.
52pub const ENABLE_ENV: &str = "AGENTMUX_STREAMED_BROWSER";
53/// Is the streamed browser on? Only a headless srv, only when asked, only on Unix.
54pub fn enabled() -> bool {
55    cfg!(unix) && crate::headless::active() && enabled_by(std::env::var(ENABLE_ENV).ok().as_deref())
56}
57
58fn enabled_by(value: Option<&str>) -> bool {
59    value == Some("1")
60}
61
62#[derive(Deserialize)]
63pub(in crate::server) struct Params {
64    url: Option<String>,
65    w: Option<u32>,
66    h: Option<u32>,
67    /// `screen`: an ordinary Chrome on a virtual screen, with nothing attached (`screen`, on when `AGENTMUX_STREAMED_BROWSER_SCREEN=1`).
68    mode: Option<String>,
69}
70
71/// The pane's start: a web address (or none) and a size within the limits.
72fn start_from(p: &Params) -> Result<pane::Start, String> {
73    let (w, h) = (p.w.unwrap_or(1024), p.h.unwrap_or(640));
74    let range = protocol::MIN_SIDE..=protocol::MAX_SIDE;
75    if !range.contains(&w) || !range.contains(&h) {
76        return Err(format!("the pane's size must be between {} and {}", protocol::MIN_SIDE, protocol::MAX_SIDE));
77    }
78    let url = match p.url.as_deref().filter(|u| !u.trim().is_empty()) {
79        Some(u) => protocol::check_url(u)?,
80        None => "about:blank".to_string(),
81    };
82    Ok(pane::Start { url, w, h })
83}
84
85/// `GET /agentmux/streamed-browser?url=&w=&h=`, upgraded to a WebSocket.
86pub(in crate::server) async fn handle(
87    session: Option<Extension<SessionId>>,
88    Query(params): Query<Params>,
89    ws: Result<WebSocketUpgrade, WebSocketUpgradeRejection>,
90) -> Response {
91    // The route table is static: the opt-in is answered here, so the route is always registered.
92    if !enabled() {
93        return (StatusCode::NOT_FOUND, "the streamed browser is not on in this server").into_response();
94    }
95    // A plain request (the web UI asking whether the pane exists here) is told to upgrade: 404 is "off", this is "on".
96    let Ok(ws) = ws else {
97        return (StatusCode::UPGRADE_REQUIRED, "this route is a WebSocket").into_response();
98    };
99    let start = match start_from(&params) {
100        Ok(s) => s,
101        Err(e) => return (StatusCode::BAD_REQUEST, e).into_response(),
102    };
103    let session = session.map(|Extension(s)| s);
104    open_pane(params.mode.as_deref(), ws, start, session_ended(session))
105}
106
107/// Open the pane's browser for the mode asked for: the full browser a person drives (`screen`), or the streamed browser. One dispatch for every
108/// route that opens a pane (this server's and the dedicated browser host's), so each honours the mode.
109pub(in crate::server) fn open_pane(
110    mode: Option<&str>,
111    ws: WebSocketUpgrade,
112    start: pane::Start,
113    ended: impl std::future::Future<Output = ()> + Send + 'static,
114) -> Response {
115    if mode == Some("screen") {
116        return screen_pane(ws, start, ended);
117    }
118    // A server with screen mode on (its policy file is the container's own) serves no streamed browser: the two would share one policy file.
119    if streamed_closed() {
120        return (StatusCode::NOT_FOUND, "this server's browser is the full browser only").into_response();
121    }
122    upgrade(ws, start, ended)
123}
124
125#[cfg(target_os = "linux")]
126fn streamed_closed() -> bool {
127    screen::enabled()
128}
129
130#[cfg(not(target_os = "linux"))]
131fn streamed_closed() -> bool {
132    false
133}
134
135/// A screen-mode pane, when this server has that mode on.
136#[cfg(target_os = "linux")]
137fn screen_pane(ws: WebSocketUpgrade, start: pane::Start, ended: impl std::future::Future<Output = ()> + Send + 'static) -> Response {
138    if !screen::enabled() {
139        return (StatusCode::NOT_FOUND, "screen mode is not on in this server").into_response();
140    }
141    screen::upgrade(ws, start, ended)
142}
143
144#[cfg(not(target_os = "linux"))]
145fn screen_pane(_ws: WebSocketUpgrade, _start: pane::Start, _ended: impl std::future::Future<Output = ()> + Send + 'static) -> Response {
146    (StatusCode::NOT_FOUND, "screen mode needs a Linux server").into_response()
147}
148
149/// Upgrade to the pane's WebSocket and run the pane until it ends (or `ended` does).
150fn upgrade(ws: WebSocketUpgrade, start: pane::Start, ended: impl std::future::Future<Output = ()> + Send + 'static) -> Response {
151    ws.protocols([WS_PROTOCOL]).on_upgrade(move |mut socket| async move {
152        match chromium::lease().await {
153            Ok(lease) => pane::run(socket, lease, start, ended).await,
154            Err(e) => {
155                tracing::warn!(error = %e, "streamed browser: no browser for a pane");
156                let _ = socket.send(axum::extract::ws::Message::Text(serde_json::json!({ "t": "error", "message": e }).to_string().into())).await;
157            }
158        }
159    })
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn it_is_on_only_when_asked_with_a_one() {
168        assert!(enabled_by(Some("1")));
169        for off in [None, Some("0"), Some("true"), Some("")] {
170            assert!(!enabled_by(off));
171        }
172        // A server that is not headless never has it, whatever its environment says.
173        assert!(!enabled());
174    }
175
176    #[test]
177    fn a_pane_starts_with_a_web_address_or_a_blank_page_and_a_size_in_range() {
178        let p = |url: Option<&str>, w, h| Params { url: url.map(str::to_string), w, h, mode: None };
179        let s = start_from(&p(None, None, None)).unwrap();
180        assert_eq!((s.url.as_str(), s.w, s.h), ("about:blank", 1024, 640));
181        assert_eq!(start_from(&p(Some("https://example.com"), Some(800), Some(600))).unwrap().url, "https://example.com/");
182        assert!(start_from(&p(Some("file:///etc/passwd"), None, None)).is_err());
183        assert!(start_from(&p(None, Some(50), None)).is_err());
184        assert!(start_from(&p(None, None, Some(5000))).is_err());
185    }
186}