Skip to main content

agentmux_srv/server/streamed_browser/
chromium.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The server-side Chromium: found, started once with a profile of its own and a CDP pipe, shared by
5//! the panes, and stopped when the last pane has been gone a while.
6//! docs/specs/SPEC_STREAMED_BROWSER_PANE_DEMO_2026_11_15.md §2 and §3.
7
8use std::path::{Path, PathBuf};
9use std::sync::{Arc, Mutex, OnceLock};
10use std::time::Duration;
11
12use super::cdp::Cdp;
13
14/// At most this many panes at once: a CPU budget, not a memory one (report finding 4).
15pub const MAX_PANES: usize = 4;
16/// How long Chromium is kept after its last pane closed.
17const IDLE_STOP: Duration = Duration::from_secs(60);
18/// `1` in the environment asks `--no-sandbox` (the demo only).
19pub const NO_SANDBOX_ENV: &str = "AGENTMUX_STREAMED_BROWSER_NO_SANDBOX";
20/// A path to the Chromium binary, when it is not on the PATH under a usual name.
21pub const BINARY_ENV: &str = "AGENTMUX_STREAMED_BROWSER_BIN";
22const USUAL_NAMES: &[&str] = &["chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "chrome"];
23
24/// The Chromium arguments: headless, its own profile, its pipe, nothing it does not need, and the one way out it
25/// has: the address proxy on `proxy_port` (`address_proxy`). Every connection goes through it, names are resolved
26/// by it (a local lookup is made to fail), and no route around it is left: no QUIC (UDP), no WebRTC over UDP
27/// that is not proxied, no DNS prefetch.
28pub fn args(profile: &Path, no_sandbox: bool, proxy_port: u16) -> Vec<String> {
29    let mut a = vec![
30        "--headless=new".to_string(),
31        "--remote-debugging-pipe".to_string(),
32        format!("--user-data-dir={}", profile.display()),
33        format!("--proxy-server=socks5://127.0.0.1:{proxy_port}"),
34        // The loopback addresses are proxied too (the proxy decides which loopback ports a page may reach).
35        "--proxy-bypass-list=<-loopback>".to_string(),
36        // Every name is unresolvable inside Chromium (the proxy resolves); the proxy's own address is a literal.
37        "--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".to_string(),
38        "--disable-quic".to_string(),
39        "--force-webrtc-ip-handling-policy=disable_non_proxied_udp".to_string(),
40        "--dns-prefetch-disable".to_string(),
41        "--disable-gpu".to_string(),
42        "--no-first-run".to_string(),
43        "--no-default-browser-check".to_string(),
44        "--disable-extensions".to_string(),
45        "--disable-background-networking".to_string(),
46        "--disable-sync".to_string(),
47        "--disable-default-apps".to_string(),
48        "--mute-audio".to_string(),
49        "--hide-scrollbars".to_string(),
50        "about:blank".to_string(),
51    ];
52    if no_sandbox {
53        a.insert(1, "--no-sandbox".to_string());
54    }
55    a
56}
57
58/// The environment variables Chromium gets, and nothing else: it opens pages from the web, so it gets none of
59/// srv's own (the key, the local address) and none of the platform's (cloud credentials, injected secrets).
60const ENV_KEEP: &[&str] = &["PATH", "HOME", "USER", "LOGNAME", "LANG", "LANGUAGE", "LC_ALL", "LC_CTYPE", "TZ", "TMPDIR", "FONTCONFIG_FILE", "FONTCONFIG_PATH"];
61
62/// `vars` cut down to the ones Chromium may have.
63pub fn allowed_env(vars: impl IntoIterator<Item = (String, String)>) -> Vec<(String, String)> {
64    vars.into_iter().filter(|(k, _)| ENV_KEEP.contains(&k.as_str())).collect()
65}
66
67/// The profile folder under a data directory: nothing else is ever a profile of this browser.
68pub fn profile_under(data: &Path) -> PathBuf {
69    data.join("streamed-browser").join("profile")
70}
71
72/// The profile folder a browser host was given: it has no data directory, and its profile is one fresh folder.
73static HOST_PROFILE: std::sync::OnceLock<PathBuf> = std::sync::OnceLock::new();
74
75pub fn use_profile_root(dir: PathBuf) {
76    let _ = HOST_PROFILE.set(profile_under(&dir));
77}
78
79/// The profile folder: under srv's data directory, never a desktop profile.
80fn profile_dir() -> Option<PathBuf> {
81    // The directory srv itself keeps its databases in (`--wavedata` first), so two servers never share a profile.
82    HOST_PROFILE.get().cloned().or_else(|| crate::headless::data_dir().map(profile_under))
83}
84
85pub(super) fn find_binary() -> Result<PathBuf, String> {
86    if let Some(path) = std::env::var_os(BINARY_ENV).filter(|p| !p.is_empty()) {
87        return Ok(PathBuf::from(path));
88    }
89    USUAL_NAMES
90        .iter()
91        .find_map(|n| which::which(n).ok())
92        .ok_or_else(|| "this server has no Chromium to run a page in".to_string())
93}
94
95/// How many panes are open, held to a limit.
96#[derive(Default)]
97pub struct Slots {
98    open: usize,
99}
100
101impl Slots {
102    pub fn take(&mut self, max: usize) -> bool {
103        if self.open >= max {
104            return false;
105        }
106        self.open += 1;
107        true
108    }
109    /// Give one back; the count left.
110    pub fn give(&mut self) -> usize {
111        self.open = self.open.saturating_sub(1);
112        self.open
113    }
114    pub fn is_empty(&self) -> bool {
115        self.open == 0
116    }
117}
118
119struct Pool {
120    browser: Option<Arc<Cdp>>,
121    slots: Slots,
122    /// Counts every release, so an idle stop knows whether anything happened since it was set.
123    epoch: u64,
124}
125
126fn pool() -> &'static Mutex<Pool> {
127    static POOL: OnceLock<Mutex<Pool>> = OnceLock::new();
128    POOL.get_or_init(|| Mutex::new(Pool { browser: None, slots: Slots::default(), epoch: 0 }))
129}
130
131/// A pane's hold on the browser; letting go of it frees its place.
132pub struct Lease {
133    pub cdp: Arc<Cdp>,
134}
135
136impl Drop for Lease {
137    fn drop(&mut self) {
138        let epoch = {
139            let mut p = pool().lock().unwrap();
140            p.epoch += 1;
141            if p.slots.give() > 0 {
142                return;
143            }
144            p.epoch
145        };
146        let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
147        runtime.spawn(async move {
148            tokio::time::sleep(IDLE_STOP).await;
149            // Holding the start lock, so a pane opened now waits until the old browser is gone before it starts one.
150            let _starting = starting().lock().await;
151            let idle = {
152                let mut p = pool().lock().unwrap();
153                if p.epoch == epoch && p.slots.is_empty() { p.browser.take() } else { None }
154            };
155            // Ask it to close; its pipe then ends and the client and the process are let go.
156            if let Some(browser) = idle {
157                let _ = browser.call("Browser.close", serde_json::json!({}), None).await;
158                for _ in 0..50 {
159                    if browser.is_dead() {
160                        break;
161                    }
162                    tokio::time::sleep(Duration::from_millis(100)).await;
163                }
164            }
165        });
166    }
167}
168
169/// Starting the browser is one at a time: two panes opened together must not start two Chromiums on one profile.
170fn starting() -> &'static tokio::sync::Mutex<()> {
171    static START: OnceLock<tokio::sync::Mutex<()>> = OnceLock::new();
172    START.get_or_init(|| tokio::sync::Mutex::new(()))
173}
174
175fn running() -> Option<Arc<Cdp>> {
176    pool().lock().unwrap().browser.clone().filter(|c| !c.is_dead())
177}
178
179/// A place in the shared browser, starting it when it is not running.
180pub async fn lease() -> Result<Lease, String> {
181    if !pool().lock().unwrap().slots.take(MAX_PANES) {
182        return Err(format!("the server's browser is busy ({MAX_PANES} panes are open)"));
183    }
184    if let Some(cdp) = running() {
185        return Ok(Lease { cdp });
186    }
187    let _starting = starting().lock().await;
188    // A pane that waited here finds the browser the one before it started.
189    if let Some(cdp) = running() {
190        return Ok(Lease { cdp });
191    }
192    match start().await {
193        Ok(cdp) => {
194            pool().lock().unwrap().browser = Some(cdp.clone());
195            Ok(Lease { cdp })
196        }
197        Err(e) => {
198            pool().lock().unwrap().slots.give();
199            Err(e)
200        }
201    }
202}
203
204#[cfg(unix)]
205async fn start() -> Result<Arc<Cdp>, String> {
206    let binary = find_binary()?;
207    let profile = profile_dir().ok_or("this server has no data folder to keep the browser's profile in")?;
208    std::fs::create_dir_all(&profile).map_err(|e| format!("cannot make the browser's profile folder: {e}"))?;
209    let no_sandbox = std::env::var(NO_SANDBOX_ENV).is_ok_and(|v| v == "1");
210    if no_sandbox {
211        tracing::warn!("streamed browser: Chromium starts WITHOUT its sandbox ({NO_SANDBOX_ENV}=1)");
212    }
213    // The one way out for the browser. If it cannot start, the browser does not start: nothing runs unproxied.
214    let proxy_port = super::address_proxy::start().await.map_err(|e| format!("the browser's address proxy did not start: {e}"))?;
215    let (cmd_read, cmd_write) = pipe_pair()?;
216    let (resp_read, resp_write) = pipe_pair()?;
217    let (cmd_read_fd, resp_write_fd) = (cmd_read.as_raw_fd(), resp_write.as_raw_fd());
218    let mut command = tokio::process::Command::new(&binary);
219    command.args(args(&profile, no_sandbox, proxy_port)).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::piped()).kill_on_drop(true);
220    // The browser opens pages from the web: it gets the few variables it needs and nothing else (not srv's key or
221    // local address, not the platform's credentials).
222    command.env_clear().envs(allowed_env(std::env::vars()));
223    // SAFETY: only dup2 and close run between fork and exec, both async-signal-safe.
224    unsafe {
225        command.pre_exec(move || {
226            if libc::dup2(cmd_read_fd, 3) < 0 || libc::dup2(resp_write_fd, 4) < 0 {
227                return Err(std::io::Error::last_os_error());
228            }
229            Ok(())
230        });
231    }
232    let mut child = command.spawn().map_err(|e| format!("cannot start {}: {e}", binary.display()))?;
233    drop((cmd_read, resp_write));
234    let tail = child.stderr.take().map(keep_stderr_tail);
235    let reader = tokio::fs::File::from_std(std::fs::File::from(resp_read));
236    let writer = tokio::fs::File::from_std(std::fs::File::from(cmd_write));
237    let cdp = Cdp::over(reader, writer);
238    keep_child(child, cdp.clone());
239    if let Err(e) = cdp.call("Browser.getVersion", serde_json::json!({}), None).await {
240        // The process is ended within a second (`keep_child`), so a stuck start leaves nothing holding the profile.
241        cdp.abandon();
242        // One line that says whether the sandbox was asked for and what Chromium said, so a server that cannot give
243        // the browser its sandbox says why (spec §2).
244        tokio::time::sleep(Duration::from_millis(300)).await;
245        let said = tail.as_ref().map(|t| t.lock().unwrap().join(" | ")).unwrap_or_default();
246        tracing::warn!(
247            sandbox = !no_sandbox,
248            "streamed browser: Chromium did not start {} its sandbox: {e}; it said: {said}",
249            if no_sandbox { "without" } else { "with" }
250        );
251        return Err(format!("the browser did not start: {e}"));
252    }
253    tracing::info!(sandbox = !no_sandbox, "streamed browser: Chromium started with its sandbox {}", if no_sandbox { "OFF" } else { "ON" });
254    // Downloads are refused in the demo (spec §8); a later PR gives them a place.
255    let _ = cdp.call("Browser.setDownloadBehavior", serde_json::json!({ "behavior": "deny" }), None).await;
256    route_windows(&cdp).await;
257    Ok(cdp)
258}
259
260/// The browser's new and ended pages are told to the pane that owns them (`popups`): a window a pane's page opens is shown by that pane.
261/// A page no pane lists is closed as it appears, with an opener or without one. The page the browser started with (blank) is srv's own
262/// and is kept, so it is marked before news of pages is asked for.
263#[cfg(unix)]
264async fn route_windows(cdp: &Arc<Cdp>) {
265    let mut events = cdp.browser_events();
266    if let Ok(found) = cdp.call("Target.getTargets", serde_json::json!({}), None).await {
267        for info in found["targetInfos"].as_array().into_iter().flatten().filter(|i| i["type"] == "page") {
268            if let Some(id) = info["targetId"].as_str() {
269                super::popups::claim_for_srv(id);
270            }
271        }
272    }
273    let _ = cdp.call("Target.setDiscoverTargets", serde_json::json!({ "discover": true }), None).await;
274    let cdp = cdp.clone();
275    tokio::spawn(async move {
276        while let Some(event) = events.recv().await {
277            for target in super::popups::route(&event.method, &event.params) {
278                cdp.send("Target.closeTarget", serde_json::json!({ "targetId": target }), None);
279            }
280        }
281    });
282}
283
284#[cfg(not(unix))]
285async fn start() -> Result<Arc<Cdp>, String> {
286    Err("the streamed browser runs on Linux and macOS servers".into())
287}
288
289#[cfg(unix)]
290use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
291#[cfg(unix)]
292use std::os::unix::process::CommandExt as _;
293
294/// A pipe, both ends close-on-exec and above descriptor 4, so `dup2` onto 3 and 4 never lands on one.
295#[cfg(unix)]
296fn pipe_pair() -> Result<(OwnedFd, OwnedFd), String> {
297    let mut fds = [0i32; 2];
298    // SAFETY: `fds` is two ints, as pipe(2) wants.
299    if unsafe { libc::pipe(fds.as_mut_ptr()) } != 0 {
300        return Err(format!("cannot make a pipe: {}", std::io::Error::last_os_error()));
301    }
302    let lift = |fd: i32| -> Result<OwnedFd, String> {
303        // SAFETY: fcntl on a descriptor this function owns; the original is closed after the copy.
304        let moved = unsafe { libc::fcntl(fd, libc::F_DUPFD_CLOEXEC, 10) };
305        unsafe { libc::close(fd) };
306        if moved < 0 {
307            return Err(format!("cannot move a pipe: {}", std::io::Error::last_os_error()));
308        }
309        Ok(unsafe { OwnedFd::from_raw_fd(moved) })
310    };
311    Ok((lift(fds[0])?, lift(fds[1])?))
312}
313
314/// How many of Chromium's last stderr lines are kept, and how long each may be.
315const TAIL_LINES: usize = 20;
316const TAIL_LINE_CHARS: usize = 300;
317
318/// Drain Chromium's stderr (so the pipe never fills), keeping the last few lines for a start that fails.
319#[cfg(unix)]
320fn keep_stderr_tail(stderr: tokio::process::ChildStderr) -> Arc<Mutex<Vec<String>>> {
321    use tokio::io::{AsyncBufReadExt, BufReader};
322    let tail = Arc::new(Mutex::new(Vec::<String>::new()));
323    let kept = tail.clone();
324    tokio::spawn(async move {
325        let mut lines = BufReader::new(stderr).lines();
326        while let Ok(Some(line)) = lines.next_line().await {
327            let mut t = kept.lock().unwrap();
328            t.push(line.chars().take(TAIL_LINE_CHARS).collect());
329            if t.len() > TAIL_LINES {
330                t.remove(0);
331            }
332        }
333    });
334    tail
335}
336
337/// Hold the process until the browser's pipe closes, then reap it.
338#[cfg(unix)]
339fn keep_child(mut child: tokio::process::Child, cdp: Arc<Cdp>) {
340    tokio::spawn(async move {
341        while !cdp.is_dead() {
342            tokio::time::sleep(Duration::from_secs(1)).await;
343        }
344        let _ = child.kill().await;
345    });
346}
347
348#[cfg(test)]
349mod tests {
350    use super::*;
351
352    #[test]
353    fn chromium_gets_its_own_profile_a_pipe_and_no_sandbox_flag_unless_asked() {
354        let a = args(Path::new("/data/streamed-browser/profile"), false, 41000);
355        assert!(a.contains(&"--remote-debugging-pipe".to_string()));
356        assert!(a.contains(&"--user-data-dir=/data/streamed-browser/profile".to_string()));
357        assert!(a.contains(&"--headless=new".to_string()));
358        assert!(!a.iter().any(|x| x.contains("remote-debugging-port") || x.contains("no-sandbox")));
359        let demo = args(Path::new("/p"), true, 41000);
360        assert!(demo.contains(&"--no-sandbox".to_string()));
361        assert_eq!(demo.last().map(String::as_str), Some("about:blank"));
362    }
363
364    #[test]
365    fn chromium_has_no_way_around_the_address_proxy() {
366        for no_sandbox in [false, true] {
367            let a = args(Path::new("/p"), no_sandbox, 41234);
368            // Every connection goes through the proxy, loopback included, and names are the proxy's to resolve.
369            assert!(a.contains(&"--proxy-server=socks5://127.0.0.1:41234".to_string()));
370            assert!(a.contains(&"--proxy-bypass-list=<-loopback>".to_string()));
371            assert!(a.contains(&"--host-resolver-rules=MAP * ~NOTFOUND , EXCLUDE 127.0.0.1".to_string()));
372            // No UDP out of it (QUIC, WebRTC that is not proxied) and no lookups ahead of a click.
373            assert!(a.contains(&"--disable-quic".to_string()));
374            assert!(a.contains(&"--force-webrtc-ip-handling-policy=disable_non_proxied_udp".to_string()));
375            assert!(a.contains(&"--dns-prefetch-disable".to_string()));
376            // A debugging port on a TCP address would let anything on the machine drive it.
377            assert!(!a.iter().any(|x| x.contains("remote-debugging-port") || x.contains("remote-debugging-address")));
378            // Nothing in the arguments turns the proxy off.
379            assert!(!a.iter().any(|x| x == "--no-proxy-server" || x.starts_with("--proxy-auto-detect") || x.starts_with("--proxy-pac-url")));
380        }
381    }
382
383    #[test]
384    fn the_engine_s_pop_up_blocking_is_left_on_so_a_page_opens_a_window_only_on_a_gesture() {
385        // The real-Chromium test `real_chromium_a_page_can_open_a_window_only_on_a_gesture` shows the engine's behaviour with these
386        // arguments; this keeps anything from switching the blocking off.
387        for no_sandbox in [false, true] {
388            let a = args(Path::new("/p"), no_sandbox, 41234);
389            assert!(!a.iter().any(|x| x.contains("popup") || x.contains("pop-up") || x.contains("user-gesture") || x.contains("autoplay-policy")), "{a:?}");
390        }
391    }
392
393    #[test]
394    fn chromium_gets_a_few_variables_and_never_a_key_or_a_credential() {
395        let env = [
396            ("PATH", "/usr/bin"), ("HOME", "/home/agentmux"), ("LANG", "C.UTF-8"), ("TZ", "UTC"),
397            ("AGENTMUX_AUTH_KEY", "k"), ("AGENTMUX_LOCAL_URL", "http://127.0.0.1:8190"),
398            ("AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "/v2/credentials/x"), ("AWS_ACCESS_KEY_ID", "a"),
399            ("ECS_CONTAINER_METADATA_URI_V4", "http://169.254.170.2/v4/x"), ("ANTHROPIC_API_KEY", "s"), ("GITHUB_TOKEN", "t"),
400        ];
401        let kept = allowed_env(env.iter().map(|(k, v)| (k.to_string(), v.to_string())));
402        let names: Vec<&str> = kept.iter().map(|(k, _)| k.as_str()).collect();
403        assert_eq!(names, ["PATH", "HOME", "LANG", "TZ"]);
404    }
405
406    #[test]
407    fn panes_are_limited_and_a_place_given_back_can_be_taken() {
408        let mut s = Slots::default();
409        for _ in 0..MAX_PANES {
410            assert!(s.take(MAX_PANES));
411        }
412        assert!(!s.take(MAX_PANES));
413        assert_eq!(s.give(), MAX_PANES - 1);
414        assert!(s.take(MAX_PANES));
415        for _ in 0..MAX_PANES + 2 {
416            s.give();
417        }
418        assert!(s.is_empty());
419    }
420
421    #[test]
422    fn the_profile_is_under_the_data_folder_and_nowhere_else() {
423        // The path is built from the data folder only: no home directory, no desktop profile.
424        assert_eq!(profile_under(Path::new("/srv/amx/data")), PathBuf::from("/srv/amx/data/streamed-browser/profile"));
425    }
426}