Skip to main content

agentmux_srv/server/streamed_browser/screen/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Screen mode: a Browser pane whose browser is an ordinary, visible Chrome on a virtual X screen, with nothing attached to it. The pane
5//! gets the same frames and sends the same messages as the streamed browser (`pane.rs`, `protocol.rs`), but a frame is the whole screen
6//! (the browser's own tab strip and address bar included) and input goes to the screen as a person's mouse and keyboard would, so the browser
7//! does not report itself as remote-controlled (Chromium turns that report on for a debugging pipe, an automation or headless switch).
8//! A prototype for the decision in task 48354: no agent driving, no windows list, a US keyboard. The screen follows the pane's size (`randr`).
9
10mod clipboard;
11mod ewmh;
12mod frames;
13mod held;
14mod keymap;
15mod pace;
16mod policy;
17mod randr;
18mod session;
19mod watch;
20mod wm;
21mod x;
22
23use std::sync::atomic::{AtomicUsize, Ordering};
24use std::sync::Arc;
25use std::time::{Duration, Instant};
26
27use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
28use axum::response::Response;
29use serde_json::json;
30use tokio::sync::mpsc;
31
32use super::pane::Start;
33use super::protocol::{self, Button, ClientMsg, Go, KeyKind, MouseKind};
34use crate::server::local_session_routes::WS_PROTOCOL;
35
36/// `1` in the environment turns screen mode on (with the streamed browser on, and the pane asking for `mode=screen`).
37pub const ENABLE_ENV: &str = "AGENTMUX_STREAMED_BROWSER_SCREEN";
38/// The setting that allows more than one screen session at once, up to `MAX_SESSIONS` (a test host).
39pub const MAX_ENV: &str = "AGENTMUX_STREAMED_BROWSER_SCREEN_MAX";
40/// At most this many screen panes at once: each is a browser and a screen of its own.
41const MAX_SESSIONS: usize = 4;
42/// Frames per second at most; a screen that did not change makes none.
43const FPS: u64 = 15;
44/// How long to wait after Ctrl+L before typing an address.
45const ADDRESS_BAR_FOCUS_MS: u64 = 250;
46/// The longest paste that is typed key by key.
47const MAX_TYPED: usize = 4000;
48
49static OPEN: AtomicUsize = AtomicUsize::new(0);
50
51/// A place among the open sessions, given back when it is dropped (however the session ended).
52struct Place;
53
54impl Place {
55    fn take() -> Option<Self> {
56        if OPEN.fetch_add(1, Ordering::SeqCst) >= limit() {
57            OPEN.fetch_sub(1, Ordering::SeqCst);
58            return None;
59        }
60        Some(Place)
61    }
62}
63
64impl Drop for Place {
65    fn drop(&mut self) {
66        OPEN.fetch_sub(1, Ordering::SeqCst);
67    }
68}
69
70/// Screen mode holds its browser's policy in the folder of the container (or dedicated machine) it runs in, so a server with screen mode on serves
71/// no streamed browser (the two would share one policy file) and, by default, one screen session: a hosted task holds one browser. A test host
72/// may allow more with `MAX_ENV`.
73pub fn limit() -> usize {
74    std::env::var(MAX_ENV).ok().and_then(|v| v.parse::<usize>().ok()).map_or(1, |n| n.clamp(1, MAX_SESSIONS))
75}
76
77pub fn enabled() -> bool {
78    std::env::var(ENABLE_ENV).is_ok_and(|v| v == "1")
79}
80
81/// Upgrade to the pane's WebSocket and run a screen session until it ends (or `ended` does).
82pub fn upgrade(ws: WebSocketUpgrade, start: Start, ended: impl std::future::Future<Output = ()> + Send + 'static) -> Response {
83    ws.protocols([WS_PROTOCOL]).on_upgrade(move |mut socket| async move {
84        let Some(_place) = Place::take() else {
85            let _ = socket.send(error(&format!("the server's browser is busy ({} panes are open)", limit()))).await;
86            return;
87        };
88        run(socket, start, ended).await;
89    })
90}
91
92fn size_message(w: u16, h: u16) -> Message {
93    Message::Text(json!({ "t": "size", "w": w, "h": h }).to_string().into())
94}
95
96fn error(message: &str) -> Message {
97    Message::Text(json!({ "t": "error", "message": message }).to_string().into())
98}
99
100/// The screen's frames, made on a thread of their own (reading and encoding a screen is work that must not hold up input). The screen says
101/// when a part of it changed: nothing is read while it is still, so a page that is not moving costs next to nothing. A change is read where
102/// it happened and written into the picture of the whole screen, and a frame is made only if some pixel really differs. Frames are at most
103/// `FPS` a second, but come at once and quickly just after the person's input (`pace`).
104fn capture(display: &str, tx: mpsc::Sender<Vec<u8>>, activity: pace::Activity) -> Result<(), String> {
105    let screen = x::Screen::connect(display)?;
106    // A screen that changes size is read at its new size, whole.
107    screen.follow_size()?;
108    let damage = screen.watch_damage()?;
109    let (mut w, mut h) = screen.size();
110    std::thread::spawn(move || {
111        let steady = Duration::from_millis(1000 / FPS);
112        let mut picture = frames::Picture::new(w, h);
113        // The first picture is the whole screen, and is sent whatever it holds.
114        let mut pending = Some(frames::Rect::whole(w, h));
115        let mut unsent = true;
116        let mut last_frame: Option<Instant> = None;
117        while !tx.is_closed() {
118            if pending.is_none() && !unsent {
119                // Waits until the screen changes; ends with the screen (the thread goes when the browser's screen does).
120                match screen.wait_damage() {
121                    Ok(Some(at)) => pending = Some(at),
122                    // The screen changed size: handled below, with whatever else changed.
123                    Ok(None) => {}
124                    Err(_) => return,
125                }
126            }
127            // The gap runs from the start of the last frame, so making a frame (which takes time) is part of the gap and not on top of it.
128            if let Some(at) = last_frame {
129                std::thread::sleep(pace::gap(activity.since(), steady).saturating_sub(at.elapsed()));
130            }
131            let began = Instant::now();
132            match screen.take_damage() {
133                Ok(Some(more)) => pending = Some(pending.map_or(more, |p| p.union(more))),
134                Ok(None) => {}
135                Err(_) => return,
136            }
137            if screen.take_resized() {
138                (w, h) = screen.size();
139                picture = frames::Picture::new(w, h);
140                pending = Some(frames::Rect::whole(w, h));
141                unsent = true;
142            }
143            if let Some(at) = pending.take() {
144                // Taken in before it is read, so a change made while it is read is not lost.
145                if screen.clear_damage(damage).is_err() {
146                    return;
147                }
148                match screen.grab_rect(at) {
149                    Ok(part) => unsent |= picture.update(at, &part),
150                    // A read that fails because the screen changed size just then is made again, whole, at the new size; any other is the end.
151                    Err(_) if screen.refresh_size() => unsent = true,
152                    Err(_) => return,
153                }
154            }
155            if unsent {
156                let Ok(frame) = frames::frame_message(picture.pixels(), u32::from(w), u32::from(h)) else { return };
157                match tx.try_send(frame) {
158                    Ok(()) => unsent = false,
159                    Err(mpsc::error::TrySendError::Closed(_)) => return,
160                    // A frame the pane is too slow to take is dropped: the picture is still unsent, so it is tried again after the gap,
161                    // from the newest screen, and the pane never stays on a picture that is out of date.
162                    Err(mpsc::error::TrySendError::Full(_)) => {}
163                }
164                last_frame = Some(began);
165            }
166        }
167    });
168    Ok(())
169}
170
171/// Run one pane until its socket closes, its screen goes, or the sign-in behind it ends.
172async fn run(mut socket: WebSocket, start: Start, ended: impl std::future::Future<Output = ()>) {
173    let session = match session::start(start.w, start.h, &start.url, OPEN.load(Ordering::SeqCst) <= 1).await {
174        Ok(s) => s,
175        Err(e) => {
176            tracing::warn!(error = %e, "screen browser: a pane could not be opened");
177            let _ = socket.send(error(&e)).await;
178            return;
179        }
180    };
181    // The browser takes a moment to put its window up: the screen is reachable at once.
182    let input = match x::Screen::connect(&session.display) {
183        Ok(s) => s,
184        Err(e) => {
185            let _ = socket.send(error(&e)).await;
186            return;
187        }
188    };
189    let (tx, mut frames) = mpsc::channel::<Vec<u8>>(2);
190    let activity = pace::Activity::default();
191    if let Err(e) = capture(&session.display, tx, activity.clone()) {
192        let _ = socket.send(error(&e)).await;
193        return;
194    }
195    // The screen's clipboard, for an exact paste and a copy on the person's request; without it a paste is typed key by key.
196    let clip = clipboard::Clipboard::connect(&session.display).map(Arc::new).map_err(|e| tracing::warn!(error = %e, "screen browser: no clipboard")).ok();
197    let (wtx, mut counts) = mpsc::unbounded_channel::<usize>();
198    if let Err(e) = watch_windows(&session.display, wtx, input.opened.clone()) {
199        let _ = socket.send(error(&e)).await;
200        return;
201    }
202    // The browser's window fills the screen once it is up, and (maximised) follows the screen when the pane is resized (`ewmh`).
203    let display = session.display.clone();
204    tokio::task::spawn_blocking(move || {
205        if let Err(e) = x::Screen::connect(&display).and_then(|s| s.maximize_first_within(Duration::from_secs(15))) {
206            tracing::warn!(error = %e, "screen browser: the window was not maximised");
207        }
208    });
209    let mut watch = watch::Watch::default();
210    let (sw, sh) = input.size();
211    let _ = socket.send(size_message(sw, sh)).await;
212    let mut held = held::Held::default();
213    let mut settle = randr::Settle::default();
214    tokio::pin!(ended);
215    loop {
216        let settled = settle.due_at().map(tokio::time::Instant::from_std);
217        let keep = tokio::select! {
218            // A window opening is handled before the next thing the person typed, so the key hold starts first; what the person sends is
219            // read before the next frame is sent, so a slow link that keeps the frame channel full never starves the person's input.
220            biased;
221            _ = &mut ended => false,
222            count = counts.recv() => match count {
223                Some(n) => match watch.seen(n, Instant::now()) {
224                    Some(notice) => socket.send(Message::Text(json!({ "t": "notice", "message": notice }).to_string().into())).await.is_ok(),
225                    None => true,
226                },
227                None => false,
228            },
229            incoming = socket.recv() => match incoming {
230                Some(Ok(Message::Text(t))) => {
231                    if let Some(said) = on_client(&input, t.as_str(), &mut settle, watch.keys_held(Instant::now()), &mut held, &activity, clip.as_ref()).await {
232                        socket.send(said).await.is_ok()
233                    } else {
234                        true
235                    }
236                }
237                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => false,
238                Some(Ok(_)) => true,
239            },
240            // The pane's size has stayed the same for a moment: the screen is made that size, and the pane is told.
241            () = async { tokio::time::sleep_until(settled.unwrap_or_else(tokio::time::Instant::now)).await }, if settled.is_some() => match settle.take(Instant::now()) {
242                Some((w, h)) => match input.resize(w, h) {
243                    Ok(()) => socket.send(size_message(w, h)).await.is_ok(),
244                    Err(e) => socket.send(error(&e)).await.is_ok(),
245                },
246                None => true,
247            },
248            frame = frames.recv() => match frame {
249                Some(f) => socket.send(Message::Binary(f.into())).await.is_ok(),
250                None => false,
251            },
252        };
253        if !keep {
254            break;
255        }
256    }
257    drop(session);
258}
259
260/// How many windows the screen shows, told whenever it changes: at the moment a window is mapped or unmapped (the screen's own events, on a
261/// thread of its own), so what is typed after a window opens is held from that moment.
262fn watch_windows(display: &str, tx: mpsc::UnboundedSender<usize>, opened: Arc<AtomicUsize>) -> Result<(), String> {
263    let screen = x::Screen::connect(display)?;
264    screen.follow_windows()?;
265    std::thread::spawn(move || {
266        let mut last = usize::MAX;
267        loop {
268            match screen.visible_windows() {
269                Ok(n) if n != last => {
270                    // Before the person's next key is read, anything being typed is told a window opened.
271                    if last != usize::MAX && watch::opened_one(last, n) {
272                        opened.fetch_add(1, Ordering::SeqCst);
273                    }
274                    last = n;
275                    if tx.send(n).is_err() {
276                        return;
277                    }
278                }
279                Ok(_) => {}
280                Err(_) => return,
281            }
282            // Blocks until the screen says a window changed; ends with the screen (the thread goes when the browser's screen does).
283            if screen.next_window_event().is_err() {
284                return;
285            }
286        }
287    });
288    Ok(())
289}
290
291/// One message from the pane, sent to the screen. A word for the pane when there is one to say. While `keys_held`, a key press or a
292/// paste is dropped (a window just opened that the person did not choose); a release still goes, so no key is left down.
293async fn on_client(screen: &x::Screen, text: &str, settle: &mut randr::Settle, keys_held: bool, held: &mut held::Held, activity: &pace::Activity, clip: Option<&Arc<clipboard::Clipboard>>) -> Option<Message> {
294    let msg = match protocol::parse(text) {
295        Ok(m) => m,
296        Err(e) => return Some(error(&e)),
297    };
298    if keys_held && matches!(msg, ClientMsg::Key { kind: KeyKind::Down, .. } | ClientMsg::Paste { .. }) {
299        return None;
300    }
301    if let ClientMsg::Key { kind, code, .. } = &msg {
302        held.note(code, matches!(kind, KeyKind::Down));
303    }
304    // What the person does is seen as it happens: frames come quickly for a moment (a pointer that only moves does not count).
305    if !matches!(msg, ClientMsg::Mouse { kind: MouseKind::Move, .. } | ClientMsg::Resize { .. }) {
306        activity.touch();
307    }
308    if matches!(msg, ClientMsg::Copy) {
309        return copy_out(clip).await;
310    }
311    // The pane's size is followed once it has stayed the same for a moment (`randr::Settle`), and the pane is told then.
312    if let ClientMsg::Resize { w, h } = msg {
313        settle.ask(randr::clamp(w, h), Instant::now());
314        return None;
315    }
316    let sent = match msg {
317        // The text goes to the screen's clipboard and Ctrl+V is pressed, with the other modifiers let go; without a clipboard it is typed key by key.
318        ClientMsg::Paste { ref text } if clip.is_some() => paste_exact(screen, clip, text, held.keys()).await,
319        // The paste is typed with the modifiers let go (Ctrl+V is the paste itself), and they are pressed again after.
320        ClientMsg::Paste { .. } => send_without_modifiers(screen, &msg, held.keys()).await,
321        _ => send_input(screen, &msg).await,
322    };
323    sent.err().map(|e| error(&e))
324}
325
326/// Paste `text` exactly: offer it as the screen's clipboard and press Ctrl+V (the other modifiers the person holds are let go for the while, and
327/// pressed again). The offer ends a moment later, so nothing stays on the screen's clipboard for the browser to read on its own.
328async fn paste_exact(screen: &x::Screen, clip: Option<&Arc<clipboard::Clipboard>>, text: &str, held: &[u8]) -> Result<(), String> {
329    let clip = clip.ok_or("no clipboard")?;
330    let generation = clip.offer(text)?;
331    let v = keymap::keycode("KeyV").ok_or("no such key")?;
332    for k in held {
333        screen.key(*k, false)?;
334    }
335    screen.key(keymap::CONTROL, true)?;
336    let tapped = tap(screen, v, false);
337    screen.key(keymap::CONTROL, false)?;
338    for k in held {
339        screen.key(*k, true)?;
340    }
341    let clip = clip.clone();
342    tokio::spawn(async move {
343        tokio::time::sleep(clipboard::OFFER_HOLD).await;
344        clip.end(generation);
345    });
346    tapped
347}
348
349/// What the browser copied, for the pane (which puts it on the person's clipboard): asked for by the person (Ctrl+C or Ctrl+X in the pane).
350/// None when the browser has copied nothing.
351async fn copy_out(clip: Option<&Arc<clipboard::Clipboard>>) -> Option<Message> {
352    let clip = clip?.clone();
353    match tokio::task::spawn_blocking(move || clip.fetch()).await {
354        Ok(Ok(Some(text))) => Some(Message::Text(json!({ "t": "clipboard", "text": text }).to_string().into())),
355        Ok(Ok(None)) => None,
356        Ok(Err(e)) => Some(error(&e)),
357        Err(_) => Some(error("the remote browser's clipboard could not be read")),
358    }
359}
360
361/// Send `msg` with the modifier keys in `held` let go for the while, then pressed again, so what the person still holds stays held.
362async fn send_without_modifiers(screen: &x::Screen, msg: &ClientMsg, held: &[u8]) -> Result<(), String> {
363    for k in held {
364        screen.key(*k, false)?;
365    }
366    let sent = send_input(screen, msg).await;
367    for k in held {
368        screen.key(*k, true)?;
369    }
370    sent
371}
372
373fn button_number(b: Button) -> Option<u8> {
374    match b {
375        Button::Left => Some(1),
376        Button::Middle => Some(2),
377        Button::Right => Some(3),
378        Button::None => None,
379    }
380}
381
382/// How many wheel notches a scroll of `delta` pixels is (the pane sends 100 to 120 a notch).
383fn notches(delta: f64) -> u32 {
384    if delta.abs() < 1.0 {
385        0
386    } else {
387        ((delta.abs() / 100.0).round() as u32).clamp(1, 10)
388    }
389}
390
391async fn send_input(screen: &x::Screen, msg: &ClientMsg) -> Result<(), String> {
392    match msg {
393        ClientMsg::Mouse { kind, x, y, button, .. } => {
394            screen.move_to(*x, *y)?;
395            if let (Some(n), MouseKind::Down | MouseKind::Up) = (button_number(*button), kind) {
396                screen.button(n, matches!(kind, MouseKind::Down))?;
397            }
398        }
399        ClientMsg::Wheel { x, y, dx, dy, .. } => {
400            screen.move_to(*x, *y)?;
401            for (delta, negative, positive) in [(*dy, 4, 5), (*dx, 6, 7)] {
402                for _ in 0..notches(delta) {
403                    let b = if delta < 0.0 { negative } else { positive };
404                    screen.button(b, true)?;
405                    screen.button(b, false)?;
406                }
407            }
408        }
409        ClientMsg::Key { kind, code, text, .. } => {
410            let down = matches!(kind, KeyKind::Down);
411            if let Some(k) = keymap::keycode(code) {
412                screen.key(k, down)?;
413            } else if down && text.chars().count() == 1 {
414                // A key whose place is not known (another layout) that types one character: typed as the US key that makes it.
415                type_text(screen, text).await?;
416            }
417        }
418        ClientMsg::Paste { text } => {
419            type_text(screen, text).await?;
420        }
421        ClientMsg::Nav { go: Go::Url, url } => {
422            // The checked, normalised address is what is typed: the raw string could carry a tab or a newline that moves the typing elsewhere.
423            let url = protocol::check_url(url)?;
424            navigate(screen, Go::Url, &url).await?
425        }
426        ClientMsg::Nav { go, url } => navigate(screen, *go, url).await?,
427        ClientMsg::Resize { .. } | ClientMsg::Window { .. } | ClientMsg::Copy => {}
428    }
429    Ok(())
430}
431
432/// Press and release a key, with Shift when it needs it.
433fn tap(screen: &x::Screen, key: u8, shift: bool) -> Result<(), String> {
434    if shift {
435        screen.key(keymap::SHIFT, true)?;
436    }
437    screen.key(key, true)?;
438    screen.key(key, false)?;
439    if shift {
440        screen.key(keymap::SHIFT, false)?;
441    }
442    Ok(())
443}
444
445/// Type text key by key. A character with no US key is skipped; the text is cut at `MAX_TYPED` characters. When a window opens while it is
446/// being typed, the rest is dropped: it was meant for the window the person was looking at.
447async fn type_text(screen: &x::Screen, text: &str) -> Result<Typed, String> {
448    let windows = screen.opened.load(Ordering::SeqCst);
449    type_chars(text, || screen.opened.load(Ordering::SeqCst) != windows, |key, shift| tap(screen, key, shift)).await
450}
451
452/// How typing ended: all of the text was typed, or it stopped because the person's screen changed under it.
453#[derive(Debug, PartialEq, Eq)]
454enum Typed {
455    Done,
456    Interrupted,
457}
458
459/// The typing itself: `stop` is asked before every character, `press` types one key (with Shift or not).
460async fn type_chars(text: &str, stop: impl Fn() -> bool, mut press: impl FnMut(u8, bool) -> Result<(), String>) -> Result<Typed, String> {
461    for (i, c) in text.chars().take(MAX_TYPED).enumerate() {
462        if stop() {
463            return Ok(Typed::Interrupted);
464        }
465        if let Some((key, shift)) = keymap::ascii(c) {
466            press(key, shift)?;
467        }
468        if i % 64 == 63 {
469            tokio::time::sleep(Duration::from_millis(5)).await;
470        }
471    }
472    Ok(Typed::Done)
473}
474
475/// Back, forward, reload and stop are the browser's own keys; an address is typed into its address bar.
476async fn navigate(screen: &x::Screen, go: Go, url: &str) -> Result<(), String> {
477    let chord = |modifier: u8, code: &str| -> Result<(), String> {
478        let key = keymap::keycode(code).ok_or("no such key")?;
479        screen.key(modifier, true)?;
480        tap(screen, key, false)?;
481        screen.key(modifier, false)
482    };
483    match go {
484        Go::Back => chord(keymap::ALT, "ArrowLeft"),
485        Go::Forward => chord(keymap::ALT, "ArrowRight"),
486        Go::Reload => tap(screen, keymap::keycode("F5").ok_or("no such key")?, false),
487        Go::Stop => tap(screen, keymap::keycode("Escape").ok_or("no such key")?, false),
488        Go::Url => {
489            // `parse` has already checked the address: only http, https or about:blank.
490            chord(keymap::CONTROL, "KeyL")?;
491            // The address bar takes the focus a moment after the chord: typing at once loses the first letters (found on a real run).
492            tokio::time::sleep(Duration::from_millis(ADDRESS_BAR_FOCUS_MS)).await;
493            // A window that opened while the address was typed took what was left of it: Enter would send half an address (or go to the new window).
494            if type_text(screen, url).await? == Typed::Interrupted {
495                return Ok(());
496            }
497            tap(screen, keymap::keycode("Enter").ok_or("no such key")?, false)
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests;