Skip to main content

agentmux_srv/server/streamed_browser/
protocol.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the pane in the web UI says to srv, and how each message becomes a CDP call.
5//! docs/specs/SPEC_STREAMED_BROWSER_PANE_DEMO_2026_11_15.md §4.
6//!
7//! Everything here is pure: a message that is too long, malformed or out of range is refused with
8//! words, never a panic, and a navigation to anything but http or https is refused.
9
10use serde::Deserialize;
11use serde_json::{json, Value};
12
13/// The longest text message the pane may send.
14pub const MAX_MESSAGE_BYTES: usize = 64 * 1024;
15/// The longest paste (it arrives as a message of its own size class).
16pub const MAX_PASTE_BYTES: usize = 1024 * 1024;
17/// The smallest and largest side of the pane's viewport.
18pub const MIN_SIDE: u32 = 100;
19pub const MAX_SIDE: u32 = 4096;
20
21/// A message from the pane.
22#[derive(Debug, Deserialize, PartialEq)]
23#[serde(tag = "t", rename_all = "lowercase")]
24pub enum ClientMsg {
25    Mouse {
26        #[serde(rename = "type")]
27        kind: MouseKind,
28        x: f64,
29        y: f64,
30        #[serde(default)]
31        button: Button,
32        #[serde(default)]
33        buttons: u32,
34        #[serde(default)]
35        clicks: u32,
36        #[serde(default)]
37        mods: u32,
38    },
39    Wheel { x: f64, y: f64, dx: f64, dy: f64, #[serde(default)] mods: u32 },
40    Key {
41        #[serde(rename = "type")]
42        kind: KeyKind,
43        key: String,
44        #[serde(default)]
45        code: String,
46        #[serde(default)]
47        text: String,
48        #[serde(default)]
49        vk: u32,
50        #[serde(default)]
51        mods: u32,
52    },
53    Paste { text: String },
54    /// The person asked for what the browser copied (they pressed Ctrl+C or Ctrl+X): screen mode answers with that text.
55    Copy,
56    Resize { w: u32, h: u32 },
57    Nav { go: Go, #[serde(default)] url: String },
58    /// Show or close one of the pane's windows (`windows.rs`).
59    Window { op: WindowOp, id: u32 },
60}
61
62#[derive(Debug, Deserialize, PartialEq, Clone, Copy)]
63#[serde(rename_all = "lowercase")]
64pub enum WindowOp {
65    Focus,
66    Close,
67}
68
69#[derive(Debug, Deserialize, PartialEq, Clone, Copy)]
70#[serde(rename_all = "lowercase")]
71pub enum MouseKind {
72    Down,
73    Up,
74    Move,
75}
76
77#[derive(Debug, Deserialize, PartialEq, Clone, Copy, Default)]
78#[serde(rename_all = "lowercase")]
79pub enum Button {
80    Left,
81    Middle,
82    Right,
83    #[default]
84    None,
85}
86
87#[derive(Debug, Deserialize, PartialEq, Clone, Copy)]
88#[serde(rename_all = "lowercase")]
89pub enum KeyKind {
90    Down,
91    Up,
92}
93
94#[derive(Debug, Deserialize, PartialEq, Clone, Copy)]
95#[serde(rename_all = "lowercase")]
96pub enum Go {
97    Url,
98    Back,
99    Forward,
100    Reload,
101    Stop,
102}
103
104/// Parse one text message, with the size limits applied before any parsing.
105pub fn parse(text: &str) -> Result<ClientMsg, String> {
106    let paste = text.starts_with(r#"{"t":"paste""#);
107    let limit = if paste { MAX_PASTE_BYTES + 64 } else { MAX_MESSAGE_BYTES };
108    if text.len() > limit {
109        return Err("that message is too long".into());
110    }
111    let msg: ClientMsg = serde_json::from_str(text).map_err(|_| "that message is not one the pane understands".to_string())?;
112    check(&msg)?;
113    Ok(msg)
114}
115
116fn finite(values: &[f64]) -> bool {
117    values.iter().all(|v| v.is_finite() && v.abs() < 1.0e6)
118}
119
120fn check(msg: &ClientMsg) -> Result<(), String> {
121    match msg {
122        ClientMsg::Mouse { x, y, .. } if !finite(&[*x, *y]) => Err("a mouse position is out of range".into()),
123        ClientMsg::Wheel { x, y, dx, dy, .. } if !finite(&[*x, *y, *dx, *dy]) => Err("a wheel position is out of range".into()),
124        ClientMsg::Resize { w, h } if !(MIN_SIDE..=MAX_SIDE).contains(w) || !(MIN_SIDE..=MAX_SIDE).contains(h) => {
125            Err(format!("the pane's size must be between {MIN_SIDE} and {MAX_SIDE}"))
126        }
127        ClientMsg::Paste { text } if text.len() > MAX_PASTE_BYTES => Err("that paste is too long".into()),
128        ClientMsg::Nav { go: Go::Url, url } => check_url(url).map(|_| ()),
129        _ => Ok(()),
130    }
131}
132
133/// The address a pane may be sent to: http or https with a host, and nothing else (no `file:`,
134/// `chrome:`, `devtools:`, `view-source:`, `javascript:` or `data:`). `about:blank` is how a pane starts.
135pub fn check_url(raw: &str) -> Result<String, String> {
136    let raw = raw.trim();
137    if raw == "about:blank" {
138        return Ok(raw.to_string());
139    }
140    let url = url::Url::parse(raw).map_err(|_| "that is not a web address".to_string())?;
141    if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none_or(str::is_empty) {
142        return Err("only http and https addresses can be opened here".into());
143    }
144    Ok(url.to_string())
145}
146
147fn button_name(b: Button) -> &'static str {
148    match b {
149        Button::Left => "left",
150        Button::Middle => "middle",
151        Button::Right => "right",
152        Button::None => "none",
153    }
154}
155
156/// The CDP call for an input message: its method and parameters, or none for a message that is not input.
157pub fn input_call(msg: &ClientMsg) -> Option<(&'static str, Value)> {
158    match msg {
159        ClientMsg::Mouse { kind, x, y, button, buttons, clicks, mods } => {
160            let ty = match kind {
161                MouseKind::Down => "mousePressed",
162                MouseKind::Up => "mouseReleased",
163                MouseKind::Move => "mouseMoved",
164            };
165            let clicks = if matches!(kind, MouseKind::Move) { 0 } else { (*clicks).clamp(1, 3) };
166            Some((
167                "Input.dispatchMouseEvent",
168                json!({ "type": ty, "x": x, "y": y, "button": button_name(*button), "buttons": buttons, "clickCount": clicks, "modifiers": mods & 15 }),
169            ))
170        }
171        ClientMsg::Wheel { x, y, dx, dy, mods } => Some((
172            "Input.dispatchMouseEvent",
173            json!({ "type": "mouseWheel", "x": x, "y": y, "deltaX": dx, "deltaY": dy, "modifiers": mods & 15 }),
174        )),
175        ClientMsg::Key { kind, key, code, text, vk, mods } => {
176            // A key that types something is a `keyDown` with its text; one that does not (an arrow, Shift) is a raw one.
177            let ty = match kind {
178                KeyKind::Up => "keyUp",
179                KeyKind::Down if text.is_empty() => "rawKeyDown",
180                KeyKind::Down => "keyDown",
181            };
182            let mut p = json!({ "type": ty, "key": key, "code": code, "windowsVirtualKeyCode": vk, "nativeVirtualKeyCode": vk, "modifiers": mods & 15 });
183            if matches!(kind, KeyKind::Down) && !text.is_empty() {
184                p["text"] = json!(text);
185                p["unmodifiedText"] = json!(text);
186            }
187            Some(("Input.dispatchKeyEvent", p))
188        }
189        ClientMsg::Paste { text } => Some(("Input.insertText", json!({ "text": text }))),
190        _ => None,
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    #[test]
199    fn a_copy_request_has_no_fields_and_a_paste_keeps_its_text_exactly() {
200        assert_eq!(parse(r#"{"t":"copy"}"#), Ok(ClientMsg::Copy));
201        let text = "Hello, Wörld! #42
202line two	日本";
203        let sent = serde_json::json!({ "t": "paste", "text": text }).to_string();
204        assert_eq!(parse(&sent), Ok(ClientMsg::Paste { text: text.to_string() }));
205        assert!(input_call(&ClientMsg::Copy).is_none(), "a copy request is not an input of the streamed pane");
206    }
207
208    #[test]
209    fn a_mouse_press_becomes_a_cdp_press_with_a_click_count() {
210        let m = parse(r#"{"t":"mouse","type":"down","x":10.5,"y":20,"button":"left","buttons":1,"clicks":1}"#).unwrap();
211        let (method, p) = input_call(&m).unwrap();
212        assert_eq!(method, "Input.dispatchMouseEvent");
213        assert_eq!(p["type"], "mousePressed");
214        assert_eq!(p["button"], "left");
215        assert_eq!(p["clickCount"], 1);
216        assert_eq!(p["x"], 10.5);
217    }
218
219    #[test]
220    fn a_move_has_no_click_and_modifiers_keep_only_the_four_known_bits() {
221        let m = parse(r#"{"t":"mouse","type":"move","x":1,"y":2,"mods":255}"#).unwrap();
222        let (_, p) = input_call(&m).unwrap();
223        assert_eq!(p["type"], "mouseMoved");
224        assert_eq!(p["clickCount"], 0);
225        assert_eq!(p["modifiers"], 15);
226    }
227
228    #[test]
229    fn a_key_with_text_types_it_and_one_without_is_raw() {
230        let typed = parse(r#"{"t":"key","type":"down","key":"a","code":"KeyA","text":"a","vk":65}"#).unwrap();
231        let (method, p) = input_call(&typed).unwrap();
232        assert_eq!((method, p["type"].as_str(), p["text"].as_str()), ("Input.dispatchKeyEvent", Some("keyDown"), Some("a")));
233        let arrow = parse(r#"{"t":"key","type":"down","key":"ArrowLeft","code":"ArrowLeft","vk":37}"#).unwrap();
234        let (_, p) = input_call(&arrow).unwrap();
235        assert_eq!(p["type"], "rawKeyDown");
236        assert!(p.get("text").is_none());
237        let up = parse(r#"{"t":"key","type":"up","key":"a","code":"KeyA","text":"a","vk":65}"#).unwrap();
238        assert_eq!(input_call(&up).unwrap().1["type"], "keyUp");
239    }
240
241    #[test]
242    fn a_wheel_and_a_paste_are_input_and_a_resize_is_not() {
243        let w = parse(r#"{"t":"wheel","x":5,"y":6,"dx":0,"dy":120}"#).unwrap();
244        assert_eq!(input_call(&w).unwrap().1["deltaY"], 120.0);
245        let p = parse(r#"{"t":"paste","text":"hello"}"#).unwrap();
246        assert_eq!(input_call(&p).unwrap(), ("Input.insertText", json!({ "text": "hello" })));
247        assert!(input_call(&parse(r#"{"t":"resize","w":800,"h":600}"#).unwrap()).is_none());
248    }
249
250    #[test]
251    fn a_size_outside_the_limits_is_refused() {
252        assert!(parse(r#"{"t":"resize","w":99,"h":600}"#).is_err());
253        assert!(parse(r#"{"t":"resize","w":800,"h":4097}"#).is_err());
254        assert!(parse(r#"{"t":"resize","w":100,"h":4096}"#).is_ok());
255    }
256
257    #[test]
258    fn a_malformed_or_unknown_message_is_refused_in_words() {
259        for bad in ["", "nonsense", r#"{"t":"mouse"}"#, r#"{"t":"launch","cmd":"x"}"#, r#"{"t":"mouse","type":"down","x":"a","y":1}"#] {
260            let e = parse(bad).unwrap_err();
261            assert!(e.contains("pane understands"), "{bad}: {e}");
262        }
263        assert!(parse(r#"{"t":"wheel","x":1e300,"y":0,"dx":0,"dy":0}"#).is_err());
264    }
265
266    #[test]
267    fn a_message_over_its_limit_is_refused_before_it_is_parsed() {
268        let long = format!(r#"{{"t":"key","type":"down","key":"{}"}}"#, "k".repeat(MAX_MESSAGE_BYTES));
269        assert!(parse(&long).unwrap_err().contains("too long"));
270        let paste = |n: usize| format!(r#"{{"t":"paste","text":"{}"}}"#, "p".repeat(n));
271        assert!(parse(&paste(MAX_PASTE_BYTES)).is_ok());
272        assert!(parse(&paste(MAX_PASTE_BYTES + 1)).is_err());
273    }
274
275    #[test]
276    fn a_window_can_be_shown_or_closed_by_its_number_and_nothing_else_is_taken() {
277        assert_eq!(parse(r#"{"t":"window","op":"focus","id":2}"#).unwrap(), ClientMsg::Window { op: WindowOp::Focus, id: 2 });
278        assert_eq!(parse(r#"{"t":"window","op":"close","id":1}"#).unwrap(), ClientMsg::Window { op: WindowOp::Close, id: 1 });
279        for bad in [r#"{"t":"window","op":"open","id":1}"#, r#"{"t":"window","op":"focus"}"#, r#"{"t":"window","op":"focus","id":-1}"#, r#"{"t":"window","op":"focus","id":"1"}"#] {
280            assert!(parse(bad).is_err(), "{bad}");
281        }
282        assert!(input_call(&ClientMsg::Window { op: WindowOp::Focus, id: 0 }).is_none(), "a window move is not input to the page");
283    }
284
285    #[test]
286    fn only_web_addresses_can_be_opened() {
287        assert_eq!(check_url("about:blank").unwrap(), "about:blank");
288        assert_eq!(check_url(" https://example.com/a?b=1 ").unwrap(), "https://example.com/a?b=1");
289        assert!(check_url("http://127.0.0.1:8080/").is_ok());
290        for bad in ["file:///etc/passwd", "chrome://settings", "devtools://x", "view-source:https://a.test", "javascript:alert(1)", "data:text/html,x", "ftp://a.test", "example.com", "https://", ""] {
291            assert!(check_url(bad).is_err(), "{bad} must be refused");
292        }
293        assert!(parse(r#"{"t":"nav","go":"url","url":"file:///etc/passwd"}"#).is_err());
294        assert!(parse(r#"{"t":"nav","go":"back"}"#).is_ok());
295    }
296}