Skip to main content

agentmux_srv/server/streamed_browser/
cdp.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A small Chrome DevTools Protocol client over a pipe: JSON messages each ended by a NUL byte
5//! (what `--remote-debugging-pipe` speaks). Calls are matched to their answers by id; events go
6//! to the session they belong to, each session with a queue of its own, so a screencast frame is
7//! never dropped (a frame that is not acknowledged stops the stream).
8//! docs/specs/SPEC_STREAMED_BROWSER_PANE_DEMO_2026_11_15.md ยง3.
9
10use std::collections::HashMap;
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14
15use serde_json::{json, Value};
16use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
17use tokio::sync::{mpsc, oneshot};
18
19/// How long a call may wait for its answer.
20const CALL_TIMEOUT: Duration = Duration::from_secs(20);
21/// The longest message read from the browser (a screencast frame is the largest by far).
22const MAX_MESSAGE: usize = 32 * 1024 * 1024;
23
24/// An event the browser sent.
25#[derive(Debug, Clone, PartialEq)]
26pub struct Event {
27    pub method: String,
28    pub params: Value,
29}
30
31type Pending = Mutex<HashMap<u64, oneshot::Sender<Result<Value, String>>>>;
32/// Where a session's events go: a function, so a pane can have the events of all its windows arrive on one queue, each tagged.
33type Deliver = Box<dyn Fn(Event) + Send + Sync>;
34type Sessions = Mutex<HashMap<String, Deliver>>;
35
36pub struct Cdp {
37    out: mpsc::UnboundedSender<Vec<u8>>,
38    next: AtomicU64,
39    pending: Pending,
40    sessions: Sessions,
41    /// Events about the browser itself (no session).
42    browser: Mutex<Option<mpsc::UnboundedSender<Event>>>,
43    dead: AtomicBool,
44}
45
46/// One message as it goes on the pipe.
47pub fn encode(message: &Value) -> Vec<u8> {
48    let mut bytes = serde_json::to_vec(message).unwrap_or_default();
49    bytes.push(0);
50    bytes
51}
52
53/// Split what has been read into whole messages, keeping the unfinished tail.
54pub fn split_messages(buffer: &mut Vec<u8>) -> Vec<Vec<u8>> {
55    let mut out = Vec::new();
56    while let Some(end) = buffer.iter().position(|b| *b == 0) {
57        let rest = buffer.split_off(end + 1);
58        buffer.pop();
59        if !buffer.is_empty() {
60            out.push(std::mem::take(buffer));
61        }
62        *buffer = rest;
63    }
64    out
65}
66
67impl Cdp {
68    /// A client over a reader and a writer to the browser. Its tasks end with the reader.
69    pub fn over<R, W>(mut reader: R, mut writer: W) -> Arc<Cdp>
70    where
71        R: AsyncRead + Unpin + Send + 'static,
72        W: AsyncWrite + Unpin + Send + 'static,
73    {
74        let (out, mut out_rx) = mpsc::unbounded_channel::<Vec<u8>>();
75        let cdp = Arc::new(Cdp {
76            out,
77            next: AtomicU64::new(1),
78            pending: Mutex::new(HashMap::new()),
79            sessions: Mutex::new(HashMap::new()),
80            browser: Mutex::new(None),
81            dead: AtomicBool::new(false),
82        });
83        tokio::spawn(async move {
84            while let Some(bytes) = out_rx.recv().await {
85                if writer.write_all(&bytes).await.is_err() || writer.flush().await.is_err() {
86                    break;
87                }
88            }
89        });
90        let reading = cdp.clone();
91        tokio::spawn(async move {
92            let mut buffer = Vec::new();
93            let mut chunk = vec![0u8; 64 * 1024];
94            loop {
95                match reader.read(&mut chunk).await {
96                    Ok(0) | Err(_) => break,
97                    Ok(n) => buffer.extend_from_slice(&chunk[..n]),
98                }
99                if buffer.len() > MAX_MESSAGE {
100                    break;
101                }
102                for message in split_messages(&mut buffer) {
103                    reading.dispatch(&message);
104                }
105            }
106            reading.finish();
107        });
108        cdp
109    }
110
111    /// The browser has gone: every waiting call fails and every session's queue ends.
112    fn finish(&self) {
113        self.dead.store(true, Ordering::SeqCst);
114        for (_, tx) in self.pending.lock().unwrap().drain() {
115            let _ = tx.send(Err("the browser stopped".into()));
116        }
117        self.sessions.lock().unwrap().clear();
118        *self.browser.lock().unwrap() = None;
119    }
120
121    /// Give up on the browser (its start did not complete): calls fail now, and whoever holds the process ends it.
122    pub fn abandon(&self) {
123        self.finish();
124    }
125
126    pub fn is_dead(&self) -> bool {
127        self.dead.load(Ordering::SeqCst)
128    }
129
130    fn dispatch(&self, message: &[u8]) {
131        let Ok(value) = serde_json::from_slice::<Value>(message) else { return };
132        if let Some(id) = value.get("id").and_then(Value::as_u64) {
133            let answer = match value.get("error") {
134                Some(e) => Err(e.get("message").and_then(Value::as_str).unwrap_or("the browser refused that").to_string()),
135                None => Ok(value.get("result").cloned().unwrap_or(Value::Null)),
136            };
137            if let Some(tx) = self.pending.lock().unwrap().remove(&id) {
138                let _ = tx.send(answer);
139            }
140            return;
141        }
142        let Some(method) = value.get("method").and_then(Value::as_str) else { return };
143        let event = Event { method: method.to_string(), params: value.get("params").cloned().unwrap_or(Value::Null) };
144        match value.get("sessionId").and_then(Value::as_str) {
145            Some(session) => {
146                if let Some(deliver) = self.sessions.lock().unwrap().get(session) {
147                    deliver(event);
148                }
149            }
150            None => {
151                if let Some(tx) = self.browser.lock().unwrap().as_ref() {
152                    let _ = tx.send(event);
153                }
154            }
155        }
156    }
157
158    /// The events of one session, from now on.
159    pub fn subscribe(&self, session: &str) -> mpsc::UnboundedReceiver<Event> {
160        let (tx, rx) = mpsc::unbounded_channel();
161        self.subscribe_with(session, move |event| {
162            let _ = tx.send(event);
163        });
164        rx
165    }
166
167    /// The events of one session, from now on, handed to `deliver` in the order they arrive (it must not block).
168    pub fn subscribe_with(&self, session: &str, deliver: impl Fn(Event) + Send + Sync + 'static) {
169        self.sessions.lock().unwrap().insert(session.to_string(), Box::new(deliver));
170    }
171
172    pub fn unsubscribe(&self, session: &str) {
173        self.sessions.lock().unwrap().remove(session);
174    }
175
176    /// The events about the browser itself (a window a page opened).
177    pub fn browser_events(&self) -> mpsc::UnboundedReceiver<Event> {
178        let (tx, rx) = mpsc::unbounded_channel();
179        *self.browser.lock().unwrap() = Some(tx);
180        rx
181    }
182
183    /// Send a call and do not wait for its answer: input and acknowledgements, which must keep their order
184    /// and must never hold up the stream behind a page that is busy.
185    pub fn send(&self, method: &str, params: Value, session: Option<&str>) {
186        let id = self.next.fetch_add(1, Ordering::SeqCst);
187        let mut message = json!({ "id": id, "method": method, "params": params });
188        if let Some(s) = session {
189            message["sessionId"] = json!(s);
190        }
191        let _ = self.out.send(encode(&message));
192    }
193
194    /// Call a method, on a session or on the browser, and wait for the answer.
195    pub async fn call(&self, method: &str, params: Value, session: Option<&str>) -> Result<Value, String> {
196        if self.is_dead() {
197            return Err("the browser stopped".into());
198        }
199        let id = self.next.fetch_add(1, Ordering::SeqCst);
200        let (tx, rx) = oneshot::channel();
201        self.pending.lock().unwrap().insert(id, tx);
202        let mut message = json!({ "id": id, "method": method, "params": params });
203        if let Some(s) = session {
204            message["sessionId"] = json!(s);
205        }
206        if self.out.send(encode(&message)).is_err() {
207            self.pending.lock().unwrap().remove(&id);
208            return Err("the browser stopped".into());
209        }
210        match tokio::time::timeout(CALL_TIMEOUT, rx).await {
211            Ok(Ok(answer)) => answer,
212            Ok(Err(_)) => Err("the browser stopped".into()),
213            Err(_) => {
214                self.pending.lock().unwrap().remove(&id);
215                Err(format!("the browser did not answer {method} in time"))
216            }
217        }
218    }
219}
220
221#[cfg(test)]
222mod tests {
223    use super::*;
224    use tokio::io::duplex;
225
226    /// A fake browser: reads our calls and lets the test answer them.
227    struct Peer {
228        read: tokio::io::DuplexStream,
229        write: tokio::io::DuplexStream,
230        buffer: Vec<u8>,
231    }
232
233    impl Peer {
234        async fn next_call(&mut self) -> Value {
235            loop {
236                if let Some(m) = split_messages(&mut self.buffer).into_iter().next() {
237                    return serde_json::from_slice(&m).unwrap();
238                }
239                let mut chunk = [0u8; 4096];
240                let n = self.read.read(&mut chunk).await.unwrap();
241                self.buffer.extend_from_slice(&chunk[..n]);
242            }
243        }
244        async fn say(&mut self, value: Value) {
245            self.write.write_all(&encode(&value)).await.unwrap();
246        }
247    }
248
249    fn pair() -> (Arc<Cdp>, Peer) {
250        let (to_peer_w, to_peer_r) = duplex(1 << 20);
251        let (from_peer_w, from_peer_r) = duplex(1 << 20);
252        (Cdp::over(from_peer_r, to_peer_w), Peer { read: to_peer_r, write: from_peer_w, buffer: Vec::new() })
253    }
254
255    #[test]
256    fn messages_are_split_at_the_nul_and_a_partial_one_waits() {
257        let mut buf = b"{\"a\":1}\0{\"b\":2}\0{\"c\"".to_vec();
258        let got = split_messages(&mut buf);
259        assert_eq!(got, vec![b"{\"a\":1}".to_vec(), b"{\"b\":2}".to_vec()]);
260        assert_eq!(buf, b"{\"c\"".to_vec());
261        buf.extend_from_slice(b":3}\0");
262        assert_eq!(split_messages(&mut buf), vec![b"{\"c\":3}".to_vec()]);
263        assert!(buf.is_empty());
264        assert!(split_messages(&mut b"\0\0".to_vec()).is_empty());
265    }
266
267    #[tokio::test]
268    async fn a_call_gets_its_own_answer_and_an_error_is_its_message() {
269        let (cdp, mut peer) = pair();
270        let c = cdp.clone();
271        let a = tokio::spawn(async move { c.call("Page.enable", json!({}), Some("s1")).await });
272        let call = peer.next_call().await;
273        assert_eq!((call["method"].as_str(), call["sessionId"].as_str()), (Some("Page.enable"), Some("s1")));
274        peer.say(json!({ "id": call["id"], "result": { "ok": true } })).await;
275        assert_eq!(a.await.unwrap().unwrap(), json!({ "ok": true }));
276
277        let c = cdp.clone();
278        let b = tokio::spawn(async move { c.call("Page.navigate", json!({ "url": "x" }), None).await });
279        let call = peer.next_call().await;
280        assert!(call.get("sessionId").is_none());
281        peer.say(json!({ "id": call["id"], "error": { "code": -32000, "message": "Cannot navigate" } })).await;
282        assert_eq!(b.await.unwrap().unwrap_err(), "Cannot navigate");
283    }
284
285    #[tokio::test]
286    async fn an_event_reaches_only_the_session_it_belongs_to_and_in_order() {
287        let (cdp, mut peer) = pair();
288        let mut one = cdp.subscribe("s1");
289        let mut two = cdp.subscribe("s2");
290        for i in 0..3 {
291            peer.say(json!({ "method": "Page.screencastFrame", "sessionId": "s1", "params": { "n": i } })).await;
292        }
293        peer.say(json!({ "method": "Page.frameNavigated", "sessionId": "s2", "params": {} })).await;
294        for i in 0..3 {
295            assert_eq!(one.recv().await.unwrap().params["n"], i);
296        }
297        assert_eq!(two.recv().await.unwrap().method, "Page.frameNavigated");
298        assert!(one.try_recv().is_err());
299    }
300
301    #[tokio::test]
302    async fn when_the_browser_goes_a_waiting_call_fails_and_the_client_is_dead() {
303        let (cdp, peer) = pair();
304        let c = cdp.clone();
305        let waiting = tokio::spawn(async move { c.call("Page.enable", json!({}), None).await });
306        tokio::time::sleep(Duration::from_millis(30)).await;
307        drop(peer);
308        assert_eq!(waiting.await.unwrap().unwrap_err(), "the browser stopped");
309        assert!(cdp.is_dead());
310        assert_eq!(cdp.call("Page.enable", json!({}), None).await.unwrap_err(), "the browser stopped");
311    }
312}