Skip to main content

agentmux_srv/server/streamed_browser/screen/
session.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One screen-mode session: a virtual X screen, a window manager (when the server has one) and an ordinary Chrome on it, started the way a
5//! person starts Chrome: no debugging pipe or port, no automation or headless switch, no script put into a page. The only extra
6//! arguments are a window size and the page to open (the network is the browser's managed policy). The browser's own sandbox is always on: no switch turns it off,
7//! and a server asked to start without it refuses.
8
9use std::path::Path;
10use std::process::Stdio;
11use std::time::Duration;
12
13use tokio::io::{AsyncBufReadExt, BufReader};
14use tokio::process::{Child, Command};
15
16use super::super::chromium;
17
18/// The virtual screen's colour depth.
19const DEPTH: u32 = 24;
20/// How long a new first session waits for the browser of the pane before it to finish going away.
21const LEFTOVER_WAIT: Duration = Duration::from_secs(5);
22
23/// What one session keeps alive: the processes end when it is dropped.
24pub struct Session {
25    pub display: String,
26    _xvfb: Child,
27    _wm: Option<Child>,
28    _chrome: Child,
29    /// The browser's process group: it and all its helpers (its crash handler, zygote, renderers) are ended together.
30    chrome_group: Option<u32>,
31    _profile: tempfile::TempDir,
32}
33
34impl Drop for Session {
35    fn drop(&mut self) {
36        if let Some(group) = self.chrome_group {
37            kill_group(group);
38        }
39    }
40}
41
42/// End every process in the process group `group` (the browser and what it started). Nothing is left running that the next session's
43/// "no other browser in this container" check would find.
44#[cfg(unix)]
45fn kill_group(group: u32) {
46    // SAFETY: `killpg` takes a group number and a signal and has no other effect; a group that is already gone answers an error that is ignored.
47    unsafe {
48        libc::killpg(group as libc::pid_t, libc::SIGKILL);
49    }
50}
51
52#[cfg(not(unix))]
53fn kill_group(_group: u32) {}
54
55/// The arguments of the virtual screen: the largest size it can be (it is set to the pane's size at once, and follows it after: `randr`), no
56/// network listener, and the display number written to standard output.
57pub fn xvfb_args() -> Vec<String> {
58    vec!["-displayfd".into(), "1".into(), "-screen".into(), "0".into(), format!("{}x{}x{DEPTH}", super::randr::MAX_W, super::randr::MAX_H), "-nolisten".into(), "tcp".into(), "-noreset".into()]
59}
60
61/// The arguments of the browser: a profile of its own, the address proxy, a window the size of the screen, and the page to open.
62pub fn chrome_args(profile: &Path, w: u32, h: u32, url: &str, has_wm: bool) -> Vec<String> {
63    let mut a = vec![
64        format!("--user-data-dir={}", profile.display()),
65        "--no-first-run".to_string(),
66        "--no-default-browser-check".to_string(),
67        "--force-webrtc-ip-handling-policy=disable_non_proxied_udp".to_string(),
68        "--dns-prefetch-disable".to_string(),
69        "--window-position=0,0".to_string(),
70        format!("--window-size={w},{h}"),
71    ];
72    if has_wm {
73        a.push("--start-maximized".to_string());
74    }
75    a.push(url.to_string());
76    a
77}
78
79/// The browser's own sandbox is part of what keeps a page away from the container, so screen mode never starts without it: the switch the
80/// streamed pane has for a test host (`NO_SANDBOX_ENV`) is refused here, in words, and `chrome_args` has no way to add `--no-sandbox`.
81pub fn sandbox_on(asked_off: Option<&str>) -> Result<(), String> {
82    match asked_off {
83        Some("1") => Err(format!(
84            "screen mode does not start without the browser's own sandbox ({} is set): run it in a container that lets the browser's sandbox start, or unset that setting",
85            chromium::NO_SANDBOX_ENV
86        )),
87        _ => Ok(()),
88    }
89}
90
91/// A process that is stopped when its handle is dropped, with the environment it needs and nothing else of srv's.
92fn command(program: &Path, args: &[String], display: Option<&str>) -> Command {
93    let mut c = Command::new(program);
94    c.args(args).stdin(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true);
95    c.env_clear().envs(chromium::allowed_env(std::env::vars()));
96    if let Some(d) = display {
97        c.env("DISPLAY", d);
98    }
99    c
100}
101
102/// Start the screen, the window manager and the browser, and say which display they are on.
103pub async fn start(w: u32, h: u32, url: &str, first: bool) -> Result<Session, String> {
104    sandbox_on(std::env::var(chromium::NO_SANDBOX_ENV).ok().as_deref())?;
105    let xvfb_bin = which::which("Xvfb").map_err(|_| "this server has no Xvfb to make a virtual screen with".to_string())?;
106    let chrome_bin = chromium::find_binary()?;
107    // The one way out for the browser, as for every pane: if the proxy cannot start, nothing runs.
108    let proxy_port = super::super::address_proxy::start().await.map_err(|e| format!("the browser's address proxy did not start: {e}"))?;
109    // The browser of the pane that just ended may still be going away (a page that is reloaded closes the old pane and opens the new one at
110    // once): wait for it to be gone before the check that this container holds one browser.
111    if first {
112        let until = std::time::Instant::now() + LEFTOVER_WAIT;
113        while super::policy::browser_running() && std::time::Instant::now() < until {
114            tokio::time::sleep(Duration::from_millis(100)).await;
115        }
116    }
117    // What the browser may open and the network it has (the proxy's port) are its managed policy: nothing starts without it.
118    super::policy::ensure(&chrome_bin, first, proxy_port)?;
119
120    let mut xvfb = command(&xvfb_bin, &xvfb_args(), None).stdout(Stdio::piped()).spawn().map_err(|e| format!("cannot start Xvfb: {e}"))?;
121    let out = xvfb.stdout.take().ok_or("Xvfb has no output")?;
122    let mut line = String::new();
123    tokio::time::timeout(Duration::from_secs(15), BufReader::new(out).read_line(&mut line))
124        .await
125        .map_err(|_| "the virtual screen did not say which display it is".to_string())?
126        .map_err(|e| format!("the virtual screen's display could not be read: {e}"))?;
127    let number: u32 = line.trim().parse().map_err(|_| format!("the virtual screen said {:?}, not a display number", line.trim()))?;
128    let display = format!(":{number}");
129    // The screen starts as large as it can be; it is made the pane's size before the browser opens, so its window is that size from the start.
130    let (w, h) = super::randr::clamp(w, h);
131    super::x::Screen::connect(&display)?.resize(w, h)?;
132    let (w, h) = (u32::from(w), u32::from(h));
133
134    let profile = tempfile::Builder::new().prefix("agentmux-screen-browser-").tempdir().map_err(|e| format!("cannot make the browser's profile folder: {e}"))?;
135    // The window manager runs with settings that bind nothing (wm.rs): a client's keys and mouse reach the browser and nothing else.
136    let wm = match which::which("openbox") {
137        Ok(bin) => command(&bin, &super::wm::write(&profile.path().join("wm"))?, Some(&display)).spawn().ok(),
138        Err(_) => None,
139    };
140    let args = chrome_args(profile.path(), w, h, url, wm.is_some());
141    let mut chrome = command(&chrome_bin, &args, Some(&display));
142    // The browser leads a process group of its own, so that it and everything it starts can be ended together.
143    #[cfg(unix)]
144    chrome.process_group(0);
145    let chrome = chrome.spawn().map_err(|e| format!("cannot start {}: {e}", chrome_bin.display()))?;
146    let chrome_group = chrome.id();
147    Ok(Session { display, _xvfb: xvfb, _wm: wm, _chrome: chrome, chrome_group, _profile: profile })
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    #[test]
155    fn the_browser_is_started_like_a_persons_browser() {
156        let a = chrome_args(Path::new("/tmp/p"), 1024, 640, "https://a.example/", true);
157        for banned in ["--remote-debugging", "--enable-automation", "--headless", "--disable-blink-features", "--enable-blink-features", "--user-agent", "--load-extension", "--disable-web-security"] {
158            assert!(!a.iter().any(|x| x.starts_with(banned)), "{banned} is not allowed: {a:?}");
159        }
160        assert!(a.contains(&"--user-data-dir=/tmp/p".to_string()));
161        assert!(a.contains(&"--no-first-run".to_string()) && a.contains(&"--no-default-browser-check".to_string()));
162        assert_eq!(a.last().map(String::as_str), Some("https://a.example/"));
163        assert!(!a.contains(&"--no-sandbox".to_string()));
164    }
165
166    #[test]
167    fn the_browser_gets_its_network_from_policy_and_no_switch_that_chrome_calls_unsupported() {
168        let a = chrome_args(Path::new("/tmp/p"), 800, 600, "about:blank", false);
169        // The network is the container's policy (policy.rs), not switches: no switch that Chrome calls unsupported, no way around the proxy.
170        assert!(!a.iter().any(|x| x.starts_with("--proxy-") || x == "--no-proxy-server" || x.starts_with("--host-resolver-rules") || x == "--disable-quic"), "{a:?}");
171        let policy = super::super::policy::wanted(41234);
172        assert_eq!(policy["ProxyServer"], "socks5://127.0.0.1:41234");
173        assert_eq!(policy["ProxyMode"], "fixed_servers");
174        assert_eq!(policy["QuicAllowed"], false);
175    }
176
177    #[test]
178    fn the_window_is_the_screen() {
179        let a = chrome_args(Path::new("/tmp/p"), 1280, 720, "about:blank", false);
180        assert!(a.contains(&"--window-size=1280,720".to_string()) && a.contains(&"--window-position=0,0".to_string()));
181        assert!(!a.contains(&"--start-maximized".to_string()));
182        assert!(chrome_args(Path::new("/tmp/p"), 1280, 720, "about:blank", true).contains(&"--start-maximized".to_string()));
183    }
184
185    #[test]
186    fn a_start_with_the_sandbox_off_is_refused_in_words_and_no_argument_turns_it_off() {
187        assert!(sandbox_on(None).is_ok() && sandbox_on(Some("0")).is_ok() && sandbox_on(Some("")).is_ok());
188        let words = sandbox_on(Some("1")).unwrap_err();
189        assert!(words.contains("sandbox") && words.contains(chromium::NO_SANDBOX_ENV), "{words}");
190        for has_wm in [false, true] {
191            let a = chrome_args(Path::new("/tmp/p"), 800, 600, "about:blank", has_wm);
192            assert!(!a.iter().any(|x| x.contains("sandbox")), "{a:?}");
193        }
194    }
195
196    /// A browser that starts helpers leaves none of them behind: ending its group ends them all.
197    #[cfg(target_os = "linux")]
198    #[tokio::test]
199    async fn ending_the_group_ends_what_the_browser_started_too() {
200        use tokio::io::{AsyncBufReadExt, BufReader};
201        // A "browser" (the shell) that starts a helper (a long sleep) and prints the helper's number. Started the way the browser is.
202        let args = vec!["-c".to_string(), "/bin/sleep 60 & echo $!; wait".to_string()];
203        let mut leader = command(Path::new("/bin/sh"), &args, None);
204        leader.stdout(Stdio::piped()).process_group(0);
205        let mut leader = leader.spawn().expect("sh starts");
206        let mut line = String::new();
207        BufReader::new(leader.stdout.take().unwrap()).read_line(&mut line).await.unwrap();
208        let helper: u32 = line.trim().parse().expect("the helper's number");
209        // A process that has ended but is not yet collected (a zombie) is gone for this purpose.
210        let alive = |pid: u32| {
211            std::fs::read_to_string(format!("/proc/{pid}/stat")).is_ok_and(|s| !s.rsplit(')').next().unwrap_or("").trim_start().starts_with('Z'))
212        };
213        assert!(alive(helper));
214        kill_group(leader.id().expect("the shell is running"));
215        leader.wait().await.unwrap();
216        let until = std::time::Instant::now() + Duration::from_secs(3);
217        while alive(helper) && std::time::Instant::now() < until {
218            tokio::time::sleep(Duration::from_millis(20)).await;
219        }
220        assert!(!alive(helper), "the helper outlived its group");
221    }
222
223    #[test]
224    fn the_virtual_screen_starts_as_large_as_it_can_be_and_has_no_network_listener() {
225        let a = xvfb_args();
226        let largest = format!("{}x{}x24", super::super::randr::MAX_W, super::super::randr::MAX_H);
227        assert!(a.windows(2).any(|p| p == ["-screen", "0"]) && a.contains(&largest));
228        assert!(a.windows(2).any(|p| p == ["-nolisten", "tcp"]));
229        assert!(a.windows(2).any(|p| p == ["-displayfd", "1"]));
230    }
231}