Skip to main content

agentmux_srv/server/streamed_browser/
pane.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One streamed pane: its windows (a page of the server's Chromium each, `windows.rs`) behind one WebSocket. Frames of the shown
5//! window go out as JPEG and are acknowledged only once handed to the socket; input comes in and goes to the shown window.
6//! docs/specs/SPEC_STREAMED_BROWSER_PANE_DEMO_2026_11_15.md §4 to §6.
7//!
8//! The logic is in `Pane`, which answers each event or message with the things to send (`Out`), so it is tested with a stand-in
9//! browser and no socket; `run` is the loop that connects it to a WebSocket.
10
11use std::collections::HashMap;
12use std::sync::Arc;
13use std::time::Instant;
14
15use axum::extract::ws::{Message, WebSocket};
16use base64::Engine as _;
17use serde_json::{json, Value};
18use tokio::sync::mpsc::{self, UnboundedReceiver, UnboundedSender, WeakUnboundedSender};
19
20use super::cdp::{Cdp, Event};
21use super::chromium::Lease;
22use super::nav;
23use super::popups::{self, TargetEvent};
24use super::protocol::{self, ClientMsg, WindowOp};
25use super::windows::{self, NoticeLimiter, WindowId, Windows, FIRST, KEY_GAP};
26
27/// Kind byte of a binary message: a JPEG frame.
28const FRAME: u8 = 1;
29/// The quality of the screencast (report section 6: SSIM 0.998 at 141 kB for a full frame).
30const JPEG_QUALITY: u32 = 70;
31
32pub struct Start {
33    pub url: String,
34    pub w: u32,
35    pub h: u32,
36}
37
38/// What a pane has to send, in order.
39#[derive(Debug, PartialEq)]
40pub(super) enum Out {
41    Text(Value),
42    /// A frame (kind byte first), and the screencast session to acknowledge once it is handed to the socket.
43    Frame { bytes: Vec<u8>, ack: Option<(String, i64)> },
44}
45
46/// What the pane keeps of a window that the list of windows does not.
47struct PageState {
48    loading: bool,
49    /// When the last resize was asked for, to say how long the new frame took.
50    resized_at: Option<Instant>,
51}
52
53/// URL patterns no page may load (`Network.setBlockedURLs`): local files and the browser's own internal pages.
54pub(super) const BLOCKED_URLS: &[&str] = &["file:*", "chrome:*", "chrome-untrusted:*", "chrome-extension:*", "devtools:*", "view-source:*"];
55
56fn screencast(w: u32, h: u32) -> Value {
57    json!({ "format": "jpeg", "quality": JPEG_QUALITY, "maxWidth": w, "maxHeight": h, "everyNthFrame": 1 })
58}
59
60fn viewport(w: u32, h: u32) -> Value {
61    json!({ "width": w, "height": h, "deviceScaleFactor": 1, "mobile": false })
62}
63
64type Events = UnboundedReceiver<(WindowId, Event)>;
65
66pub(super) struct Pane {
67    cdp: Arc<Cdp>,
68    windows: Windows,
69    state: HashMap<WindowId, PageState>,
70    size: (u32, u32),
71    /// Where the events of a window's session go, tagged with the window. Weak: when the browser goes, every session's end drops the
72    /// last strong sender and the pane's queue ends with it.
73    events: WeakUnboundedSender<(WindowId, Event)>,
74    /// Where the browser's news of this pane's windows is told (`popups`).
75    targets: UnboundedSender<TargetEvent>,
76    /// The pages this pane has claimed: released with the pane, however it ends.
77    claims: popups::Claims,
78    limiter: NoticeLimiter,
79    /// Keys are dropped until then: the shown window just changed and the person did not choose it (`windows::KEY_GAP`).
80    keys_held_until: Option<Instant>,
81}
82
83fn listen(cdp: &Cdp, session: &str, id: WindowId, tx: UnboundedSender<(WindowId, Event)>) {
84    cdp.subscribe_with(session, move |event| {
85        let _ = tx.send((id, event));
86    });
87}
88
89impl Pane {
90    /// The pane's first window: a page made for it, switched on and sent to its first address. Closed again if it cannot be made ready.
91    pub(super) async fn open(cdp: &Arc<Cdp>, start: &Start) -> Result<(Pane, Events, UnboundedReceiver<TargetEvent>), String> {
92        // The page is made for this pane: it is claimed the moment its id is known, and until then the browser's news of a new page
93        // with no opener is held, not closed as nobody's.
94        let (targets, told) = mpsc::unbounded_channel();
95        let making = popups::making_a_page();
96        let made = cdp.call("Target.createTarget", json!({ "url": "about:blank" }), None).await;
97        let made_id = made.as_ref().ok().and_then(|m| m.get("targetId").and_then(Value::as_str)).map(str::to_string);
98        let mut claims = popups::Claims::default();
99        if let Some(id) = &made_id {
100            claims.claim(id, targets.clone());
101        }
102        for stray in making.done() {
103            let _ = cdp.call("Target.closeTarget", json!({ "targetId": stray }), None).await;
104        }
105        let target = match (made, made_id) {
106            (Err(e), _) => return Err(e),
107            (Ok(_), None) => return Err("the browser made no page".to_string()),
108            (Ok(_), Some(id)) => id,
109        };
110        let attached = cdp.call("Target.attachToTarget", json!({ "targetId": target, "flatten": true }), None).await;
111        let session = match attached {
112            Ok(a) => a.get("sessionId").and_then(Value::as_str).map(str::to_string).ok_or_else(|| "the browser gave no session".to_string()),
113            Err(e) => Err(e),
114        };
115        let session = match session {
116            Ok(s) => s,
117            Err(e) => {
118                claims.release(&target);
119                let _ = cdp.call("Target.closeTarget", json!({ "targetId": target }), None).await;
120                return Err(e);
121            }
122        };
123        let (tx, events) = mpsc::unbounded_channel();
124        let weak = tx.downgrade();
125        listen(cdp, &session, FIRST, tx);
126        let mut state = HashMap::new();
127        state.insert(FIRST, PageState { loading: false, resized_at: None });
128        let pane = Pane { cdp: cdp.clone(), windows: Windows::starting(target, session), state, size: (start.w, start.h), events: weak, targets, claims, limiter: NoticeLimiter::default(), keys_held_until: None };
129        match pane.prepare(FIRST, Some(&start.url)).await {
130            Ok(()) => Ok((pane, events, told)),
131            Err(e) => {
132                pane.finish().await;
133                Err(e)
134            }
135        }
136    }
137
138    fn session_of(&self, id: WindowId) -> Option<String> {
139        self.windows.get(id).map(|w| w.session.clone())
140    }
141
142    fn active_session(&self) -> Option<String> {
143        self.session_of(self.windows.active())
144    }
145
146    /// Switch a window on: events, the viewport, focus, the screencast and, for the first window, its first address.
147    async fn prepare(&self, id: WindowId, url: Option<&str>) -> Result<(), String> {
148        let session = self.session_of(id).ok_or("that window is gone")?;
149        let (cdp, s) = (&self.cdp, Some(session.as_str()));
150        cdp.call("Page.enable", json!({}), s).await?;
151        cdp.call("Emulation.setDeviceMetricsOverride", viewport(self.size.0, self.size.1), s).await?;
152        // The page counts as focused, so its carets and :focus styles show.
153        cdp.call("Emulation.setFocusEmulationEnabled", json!({ "enabled": true }), s).await?;
154        // A page's file chooser is intercepted and never answered: nothing on the server's disks is offered to a page.
155        cdp.call("Page.setInterceptFileChooserDialog", json!({ "enabled": true }), s).await?;
156        // No page loads, or navigates to, the server's own files or the browser's internal pages, in the top frame, in a
157        // frame, or as a script, image or request of a page. (The address bar already takes only http and https.) A window a
158        // page opens is switched on the same way as the first one.
159        cdp.call("Network.enable", json!({ "maxTotalBufferSize": 0, "maxResourceBufferSize": 0 }), s).await?;
160        cdp.call("Network.setBlockedURLs", json!({ "urls": BLOCKED_URLS }), s).await?;
161        cdp.call("Page.startScreencast", screencast(self.size.0, self.size.1), s).await?;
162        if let Some(url) = url.filter(|u| *u != "about:blank") {
163            nav::go(cdp, &session, protocol::Go::Url, url).await?;
164        }
165        Ok(())
166    }
167
168    /// The pane has ended: every window is let go and closed.
169    pub(super) async fn finish(mut self) {
170        for w in self.windows.entries() {
171            self.cdp.unsubscribe(&w.session);
172            self.claims.release(&w.target);
173        }
174        for w in self.windows.entries() {
175            let _ = self.cdp.call("Target.closeTarget", json!({ "targetId": w.target }), None).await;
176        }
177    }
178
179    /// The shown window changed and the person did not choose it: keys are held back for a moment, so one typed for the window
180    /// they were looking at does not land in another.
181    fn hold_keys(&mut self, now: Instant) {
182        self.keys_held_until = Some(now + KEY_GAP);
183    }
184
185    /// The person comes back to `id`: if it went to another site while it was not shown, say which.
186    fn say_moved(&mut self, id: WindowId, out: &mut Vec<Out>) {
187        if let Some((from, to)) = self.windows.take_moved(id) {
188            self.notice(windows::window_changed_site(&from, &to), out);
189        }
190    }
191
192    fn notice(&mut self, text: String, out: &mut Vec<Out>) {
193        if self.limiter.allow(Instant::now()) {
194            out.push(Out::Text(json!({ "t": "notice", "message": text })));
195        }
196    }
197
198    /// Tell the pane which windows there are and where the shown one is.
199    async fn announce(&mut self, out: &mut Vec<Out>) {
200        out.push(Out::Text(self.windows.message()));
201        let id = self.windows.active();
202        self.nav_update(id, out, false).await;
203    }
204
205    /// A window's address or loading state changed: remember it, tell the pane the windows, and the shown window's bar.
206    async fn nav_update(&mut self, id: WindowId, out: &mut Vec<Out>, windows_too: bool) {
207        let Some(session) = self.session_of(id) else { return };
208        let loading = self.state.get(&id).is_some_and(|s| s.loading);
209        let message = nav::nav_message(&nav::history(&self.cdp, &session).await, loading);
210        let text = |key: &str| message.get(key).and_then(Value::as_str).unwrap_or("").to_string();
211        let (url, title) = (text("url"), text("title"));
212        if self.windows.get(id).is_some_and(|w| w.url != url || w.title != title) {
213            self.windows.set_location(id, url.clone(), title);
214            if windows_too {
215                out.push(Out::Text(self.windows.message()));
216            }
217            if let Some(line) = windows::provider_refusal(&url) {
218                self.notice(line, out);
219            }
220        }
221        if id == self.windows.active() {
222            out.push(Out::Text(message));
223        }
224    }
225
226    /// Show `id`: the screencast moves to it.
227    async fn show(&mut self, id: WindowId, out: &mut Vec<Out>) {
228        let before = self.windows.active();
229        if !self.windows.focus(id) {
230            return;
231        }
232        if before != id {
233            if let Some(old) = self.session_of(before) {
234                let _ = self.cdp.call("Page.stopScreencast", json!({}), Some(&old)).await;
235            }
236            if let Some(new) = self.session_of(id) {
237                let _ = self.cdp.call("Page.startScreencast", screencast(self.size.0, self.size.1), Some(&new)).await;
238            }
239        }
240        self.announce(out).await;
241        self.say_moved(id, out);
242    }
243
244    /// A window ended (or was closed): it is let go, and when it was the shown one the window that opened it is shown again.
245    /// False when it was the pane's first, which ends the pane. `chosen` is whether the person closed it (else it closed itself or
246    /// crashed, and the window that is shown now was not their choice).
247    async fn forget(&mut self, id: WindowId, chosen: bool, out: &mut Vec<Out>) -> bool {
248        if id == FIRST {
249            return false;
250        }
251        let Some(gone) = self.windows.get(id).cloned() else { return true };
252        let Some(removed) = self.windows.remove(id) else { return true };
253        self.cdp.unsubscribe(&gone.session);
254        self.claims.release(&gone.target);
255        self.state.remove(&id);
256        if removed.was_active {
257            if let Some(next) = self.session_of(removed.now_active) {
258                let _ = self.cdp.call("Page.startScreencast", screencast(self.size.0, self.size.1), Some(&next)).await;
259            }
260        }
261        self.announce(out).await;
262        if removed.was_active {
263            if !chosen {
264                self.hold_keys(Instant::now());
265            }
266            self.say_moved(removed.now_active, out);
267        }
268        true
269    }
270
271    /// The browser's news of this pane's windows. `false` ends the pane.
272    pub(super) async fn on_target(&mut self, event: TargetEvent, out: &mut Vec<Out>) -> bool {
273        match event {
274            TargetEvent::Opened { target_id, opener_id, url } => {
275                self.opened(&target_id, &opener_id, &url, out).await;
276                true
277            }
278            TargetEvent::Gone { target_id } => match self.windows.by_target(&target_id) {
279                Some(id) => self.forget(id, false, out).await,
280                None => true,
281            },
282        }
283    }
284
285    async fn close_target(&self, target: &str) {
286        let _ = self.cdp.call("Target.closeTarget", json!({ "targetId": target }), None).await;
287    }
288
289    /// A page of this pane opened a window: it is shown, unless the pane already shows as many as it may.
290    async fn opened(&mut self, target: &str, opener_target: &str, url: &str, out: &mut Vec<Out>) {
291        let opener = self.windows.by_target(opener_target);
292        let opener_url = opener.and_then(|o| self.windows.get(o)).map(|w| w.url.clone()).unwrap_or_default();
293        if opener.is_none() || !self.windows.has_room() {
294            self.close_target(target).await;
295            let line = if opener.is_none() { windows::window_not_shown(url) } else { windows::too_many_windows(&opener_url) };
296            self.notice(line, out);
297            return;
298        }
299        let attached = self.cdp.call("Target.attachToTarget", json!({ "targetId": target, "flatten": true }), None).await;
300        let session = attached.ok().and_then(|a| a.get("sessionId").and_then(Value::as_str).map(str::to_string));
301        let (Some(session), Some(tx)) = (session, self.events.upgrade()) else {
302            self.close_target(target).await;
303            self.notice(windows::window_not_shown(&opener_url), out);
304            return;
305        };
306        let before = self.windows.active();
307        let Some(id) = self.windows.add(target.to_string(), session.clone(), opener) else {
308            self.close_target(target).await;
309            return;
310        };
311        listen(&self.cdp, &session, id, tx);
312        self.claims.claim(target, self.targets.clone());
313        self.state.insert(id, PageState { loading: false, resized_at: None });
314        if let Err(e) = self.prepare(id, None).await {
315            tracing::warn!(error = %e, "streamed browser: a window a page opened could not be shown");
316            self.windows.remove(id);
317            self.cdp.unsubscribe(&session);
318            self.claims.release(target);
319            self.state.remove(&id);
320            self.close_target(target).await;
321            // The shown window was never changed by the one that failed: say so, and carry on with it.
322            let _ = self.windows.focus(before);
323            self.notice(windows::window_not_shown(&opener_url), out);
324            return;
325        }
326        // The screencast moves to the new window: the one before it stops. The person did not choose this window, so for a moment
327        // their keys go to no window.
328        if let Some(old) = self.session_of(before) {
329            let _ = self.cdp.call("Page.stopScreencast", json!({}), Some(&old)).await;
330        }
331        self.hold_keys(Instant::now());
332        self.announce(out).await;
333    }
334
335    /// What a window's event means for the pane. `false` ends the pane.
336    pub(super) async fn on_event(&mut self, id: WindowId, event: Event, out: &mut Vec<Out>) -> bool {
337        match event.method.as_str() {
338            "Page.screencastFrame" => self.frame(id, &event.params, out),
339            "Page.frameStartedLoading" => {
340                self.state.entry(id).or_insert(PageState { loading: false, resized_at: None }).loading = true;
341                self.nav_update(id, out, true).await;
342            }
343            "Page.frameStoppedLoading" => {
344                self.state.entry(id).or_insert(PageState { loading: false, resized_at: None }).loading = false;
345                self.nav_update(id, out, true).await;
346            }
347            "Page.frameNavigated" if event.params.pointer("/frame/parentId").is_none() => self.nav_update(id, out, true).await,
348            // A dialog the page raised is dismissed (the pane has nowhere to show it), and the person is told which site raised it.
349            "Page.javascriptDialogOpening" => {
350                if let Some(session) = self.session_of(id) {
351                    self.cdp.send("Page.handleJavaScriptDialog", json!({ "accept": false }), Some(&session));
352                }
353                let page_url = event.params.get("url").and_then(Value::as_str).map(str::to_string).or_else(|| self.windows.get(id).map(|w| w.url.clone())).unwrap_or_default();
354                let kind = event.params.get("type").and_then(Value::as_str).unwrap_or("alert");
355                let message = event.params.get("message").and_then(Value::as_str).unwrap_or("");
356                self.notice(windows::dialog_dismissed(&page_url, kind, message), out);
357            }
358            "Inspector.targetCrashed" => {
359                if id == FIRST {
360                    out.push(Out::Text(json!({ "t": "error", "message": "the page crashed" })));
361                    return false;
362                }
363                if let Some(target) = self.windows.get(id).map(|w| w.target.clone()) {
364                    self.close_target(&target).await;
365                }
366                return self.forget(id, false, out).await;
367            }
368            _ => {}
369        }
370        true
371    }
372
373    /// A screencast frame: the shown window's goes to the pane; another window's is acknowledged and dropped.
374    fn frame(&mut self, id: WindowId, params: &Value, out: &mut Vec<Out>) {
375        let ack = params.get("sessionId").and_then(Value::as_i64);
376        let session = self.session_of(id);
377        let pair = session.clone().zip(ack);
378        if id != self.windows.active() {
379            if let Some((s, a)) = pair {
380                self.cdp.send("Page.screencastFrameAck", json!({ "sessionId": a }), Some(&s));
381            }
382            return;
383        }
384        let Some(data) = params.get("data").and_then(Value::as_str) else { return };
385        let Ok(jpeg) = base64::engine::general_purpose::STANDARD.decode(data) else { return };
386        let mut bytes = Vec::with_capacity(jpeg.len() + 1);
387        bytes.push(FRAME);
388        bytes.extend_from_slice(&jpeg);
389        if let Some(at) = self.state.get_mut(&id).and_then(|s| s.resized_at.take()) {
390            tracing::debug!(ms = at.elapsed().as_millis() as u64, "streamed browser: first frame after a resize");
391        }
392        // Acknowledged only once handed to the socket, so a slow client slows the page's own capture instead of queueing frames.
393        out.push(Out::Frame { bytes, ack: pair });
394    }
395
396    /// Resize every window and make the browser send a frame of the new size even when the page does not change: stopping and
397    /// starting the screencast does that.
398    async fn resize(&mut self, w: u32, h: u32) -> Result<(), String> {
399        self.size = (w, h);
400        let active = self.windows.active();
401        let ids: Vec<WindowId> = self.windows.entries().iter().map(|e| e.id).collect();
402        for id in ids {
403            let Some(session) = self.session_of(id) else { continue };
404            self.cdp.call("Emulation.setDeviceMetricsOverride", viewport(w, h), Some(&session)).await?;
405            if id == active {
406                self.cdp.call("Page.stopScreencast", json!({}), Some(&session)).await?;
407                self.cdp.call("Page.startScreencast", screencast(w, h), Some(&session)).await?;
408                if let Some(s) = self.state.get_mut(&id) {
409                    s.resized_at = Some(Instant::now());
410                }
411            }
412        }
413        Ok(())
414    }
415
416    /// What a message from the pane means. `false` ends the pane.
417    pub(super) async fn on_client(&mut self, text: &str, out: &mut Vec<Out>) -> bool {
418        self.on_client_at(text, out, Instant::now()).await
419    }
420
421    /// `on_client` at `now` (the clock is an argument so a test can say how long after a change a key arrives).
422    async fn on_client_at(&mut self, text: &str, out: &mut Vec<Out>, now: Instant) -> bool {
423        let msg = match protocol::parse(text) {
424            Ok(m) => m,
425            Err(e) => {
426                out.push(Out::Text(json!({ "t": "error", "message": e })));
427                return true;
428            }
429        };
430        if let Some((method, params)) = protocol::input_call(&msg) {
431            // Keys (typed or pasted) wait out the gap after a window changed on its own; the pointer does not.
432            let key = matches!(method, "Input.dispatchKeyEvent" | "Input.insertText");
433            if key && self.keys_held_until.is_some_and(|until| now < until) {
434                return true;
435            }
436            if let Some(session) = self.active_session() {
437                self.cdp.send(method, params, Some(&session));
438            }
439            return true;
440        }
441        match msg {
442            ClientMsg::Resize { w, h } => match self.resize(w, h).await {
443                Ok(()) => out.push(Out::Text(json!({ "t": "size", "w": w, "h": h }))),
444                Err(e) => out.push(Out::Text(json!({ "t": "error", "message": e }))),
445            },
446            ClientMsg::Nav { go, url } => {
447                if let Some(session) = self.active_session() {
448                    if let Err(e) = nav::go(&self.cdp, &session, go, &url).await {
449                        out.push(Out::Text(json!({ "t": "error", "message": e })));
450                    }
451                }
452            }
453            ClientMsg::Window { op: WindowOp::Focus, id } => self.show(id, out).await,
454            ClientMsg::Window { op: WindowOp::Close, id } => {
455                // The first window is the pane itself: it is not closed from here.
456                if id != FIRST {
457                    if let Some(target) = self.windows.get(id).map(|w| w.target.clone()) {
458                        self.close_target(&target).await;
459                        self.forget(id, true, out).await;
460                    }
461                }
462            }
463            _ => {}
464        }
465        true
466    }
467}
468
469async fn send_out(socket: &mut WebSocket, cdp: &Cdp, out: Vec<Out>) -> bool {
470    for item in out {
471        match item {
472            Out::Text(v) => {
473                if socket.send(Message::Text(v.to_string().into())).await.is_err() {
474                    return false;
475                }
476            }
477            Out::Frame { bytes, ack } => {
478                if socket.send(Message::Binary(bytes.into())).await.is_err() {
479                    return false;
480                }
481                if let Some((session, id)) = ack {
482                    cdp.send("Page.screencastFrameAck", json!({ "sessionId": id }), Some(&session));
483                }
484            }
485        }
486    }
487    true
488}
489
490/// Run a pane until its socket closes, its first page ends, or the sign-in behind it does.
491pub async fn run(mut socket: WebSocket, lease: Lease, start: Start, ended: impl std::future::Future<Output = ()>) {
492    let (mut pane, mut events, mut told) = match Pane::open(&lease.cdp, &start).await {
493        Ok(p) => p,
494        Err(e) => {
495            tracing::warn!(error = %e, "streamed browser: a pane could not be opened");
496            let _ = socket.send(Message::Text(json!({ "t": "error", "message": e }).to_string().into())).await;
497            return;
498        }
499    };
500    let _ = socket.send(Message::Text(json!({ "t": "size", "w": start.w, "h": start.h }).to_string().into())).await;
501    tokio::pin!(ended);
502    loop {
503        let mut out = Vec::new();
504        let keep = tokio::select! {
505            _ = &mut ended => false,
506            event = events.recv() => match event {
507                Some((id, e)) => pane.on_event(id, e, &mut out).await,
508                None => false,
509            },
510            news = told.recv() => match news {
511                Some(n) => pane.on_target(n, &mut out).await,
512                None => false,
513            },
514            incoming = socket.recv() => match incoming {
515                Some(Ok(Message::Text(t))) => pane.on_client(t.as_str(), &mut out).await,
516                Some(Ok(Message::Close(_))) | None | Some(Err(_)) => false,
517                Some(Ok(_)) => true,
518            },
519        };
520        if !send_out(&mut socket, &lease.cdp, out).await || !keep {
521            break;
522        }
523    }
524    pane.finish().await;
525    drop(lease);
526}
527
528#[cfg(test)]
529mod tests {
530    use super::*;
531    use crate::server::streamed_browser::fake_browser::FakeBrowser;
532
533    /// The registry of who owns which page is the process's: tests that use it take turns (`popups::serial`).
534    async fn serial() -> tokio::sync::MutexGuard<'static, ()> {
535        popups::serial().await
536    }
537
538    fn start() -> Start {
539        Start { url: "https://app.example/".into(), w: 800, h: 600 }
540    }
541
542    /// A pane over a stand-in browser, with `app.example` loaded in its first window.
543    async fn pane() -> (Pane, Events, UnboundedReceiver<TargetEvent>, FakeBrowser) {
544        let fake = FakeBrowser::start();
545        fake.set_address("S-T1", "https://app.example/", "App");
546        let (pane, events, told) = Pane::open(&fake.cdp, &start()).await.expect("the pane opens");
547        (pane, events, told, fake)
548    }
549
550    /// What the browser-level watcher does with a new page: the pane that owns the opener is told, else the page is closed (the pages to close).
551    fn browser_says(method: &str, params: Value) -> Vec<String> {
552        popups::route(method, &params)
553    }
554
555    fn created(target: &str, opener: &str) -> Value {
556        json!({ "targetInfo": { "targetId": target, "type": "page", "openerId": opener, "url": "https://idp.example/auth" } })
557    }
558
559    fn texts(out: &[Out]) -> Vec<Value> {
560        out.iter().filter_map(|o| if let Out::Text(v) = o { Some(v.clone()) } else { None }).collect()
561    }
562
563    fn of_kind(out: &[Out], kind: &str) -> Vec<Value> {
564        texts(out).into_iter().filter(|v| v["t"] == kind).collect()
565    }
566
567    /// A pane with a pop-up open (window 1, shown).
568    async fn with_popup() -> (Pane, Events, UnboundedReceiver<TargetEvent>, FakeBrowser, Vec<Out>) {
569        let (mut pane, events, mut told, fake) = pane().await;
570        fake.set_address("S-T2", "https://idp.example/auth", "Sign in");
571        assert!(browser_says("Target.targetCreated", created("T2", "T1")).is_empty(), "a page of the pane opened it: it is not closed");
572        let news = told.recv().await.unwrap();
573        let mut out = Vec::new();
574        assert!(pane.on_target(news, &mut out).await);
575        (pane, events, told, fake, out)
576    }
577
578    #[tokio::test]
579    async fn the_first_window_is_switched_on_with_the_blocked_addresses_and_sent_to_its_address() {
580        let _serial = serial().await;
581        let (pane, _events, _told, fake) = pane().await;
582        let calls = fake.calls();
583        let on = |m: &str| calls.iter().any(|c| c.method == m && c.session.as_deref() == Some("S-T1"));
584        for m in ["Page.enable", "Emulation.setDeviceMetricsOverride", "Network.enable", "Network.setBlockedURLs", "Page.startScreencast", "Page.navigate"] {
585            assert!(on(m), "{m}");
586        }
587        let blocked = calls.iter().find(|c| c.method == "Network.setBlockedURLs").unwrap();
588        assert_eq!(blocked.params["urls"], json!(BLOCKED_URLS));
589        pane.finish().await;
590    }
591
592    #[tokio::test]
593    async fn a_window_the_page_opens_is_shown_with_its_address_and_is_not_closed() {
594        let _serial = serial().await;
595        let (pane, _events, _told, fake, out) = with_popup().await;
596        let calls = fake.calls();
597        // It was attached and switched on exactly as the first one: the blocked addresses apply to it too.
598        for m in ["Page.enable", "Network.enable", "Network.setBlockedURLs", "Page.startScreencast"] {
599            assert!(calls.iter().any(|c| c.method == m && c.session.as_deref() == Some("S-T2")), "{m} on the pop-up");
600        }
601        let blocked = calls.iter().find(|c| c.method == "Network.setBlockedURLs" && c.session.as_deref() == Some("S-T2")).unwrap();
602        assert_eq!(blocked.params["urls"], json!(BLOCKED_URLS));
603        // The screencast moved to it, and nothing closed it.
604        assert!(calls.iter().any(|c| c.method == "Page.stopScreencast" && c.session.as_deref() == Some("S-T1")));
605        assert!(!calls.iter().any(|c| c.method == "Target.closeTarget" && c.params["targetId"] == "T2"));
606        let windows = of_kind(&out, "windows");
607        assert_eq!(windows.last().unwrap()["active"], 1);
608        assert_eq!(windows.last().unwrap()["windows"].as_array().unwrap().len(), 2);
609        assert_eq!(windows.last().unwrap()["windows"][1]["opener"], 0);
610        // The bar shows the pop-up's own address, so the person sees which site asks for the password.
611        let nav = of_kind(&out, "nav");
612        assert_eq!(nav.last().unwrap()["url"], "https://idp.example/auth");
613        pane.finish().await;
614    }
615
616    #[tokio::test]
617    async fn input_and_addresses_go_to_the_shown_window() {
618        let _serial = serial().await;
619        let (mut pane, _events, _told, fake, _) = with_popup().await;
620        let mut out = Vec::new();
621        assert!(pane.on_client(r#"{"t":"mouse","type":"down","x":5,"y":6,"button":"left","buttons":1,"clicks":1}"#, &mut out).await);
622        assert!(pane.on_client(r#"{"t":"nav","go":"url","url":"https://idp.example/next"}"#, &mut out).await);
623        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
624        let calls = fake.calls();
625        let mouse = calls.iter().rev().find(|c| c.method == "Input.dispatchMouseEvent").unwrap();
626        assert_eq!(mouse.session.as_deref(), Some("S-T2"));
627        let go = calls.iter().rev().find(|c| c.method == "Page.navigate").unwrap();
628        assert_eq!((go.session.as_deref(), go.params["url"].as_str()), (Some("S-T2"), Some("https://idp.example/next")));
629        pane.finish().await;
630    }
631
632    #[tokio::test]
633    async fn a_window_that_closes_itself_hands_the_pane_back_to_the_page_that_opened_it() {
634        let _serial = serial().await;
635        let (mut pane, _events, mut told, fake, _) = with_popup().await;
636        assert!(browser_says("Target.targetDestroyed", json!({ "targetId": "T2" })).is_empty());
637        let news = told.recv().await.unwrap();
638        assert_eq!(news, TargetEvent::Gone { target_id: "T2".into() });
639        let mut out = Vec::new();
640        assert!(pane.on_target(news, &mut out).await);
641        assert_eq!(of_kind(&out, "windows").last().unwrap()["active"], 0);
642        assert_eq!(of_kind(&out, "windows").last().unwrap()["windows"].as_array().unwrap().len(), 1);
643        assert_eq!(of_kind(&out, "nav").last().unwrap()["url"], "https://app.example/");
644        let calls = fake.calls();
645        assert!(calls.iter().rev().any(|c| c.method == "Page.startScreencast" && c.session.as_deref() == Some("S-T1")), "the page is streamed again");
646        // A late event from the closed window finds nothing.
647        assert!(pane.on_event(1, Event { method: "Page.frameStoppedLoading".into(), params: Value::Null }, &mut Vec::new()).await);
648        pane.finish().await;
649    }
650
651    #[tokio::test]
652    async fn the_first_window_going_ends_the_pane() {
653        let _serial = serial().await;
654        let (mut pane, _events, mut told, _fake) = pane().await;
655        browser_says("Target.targetDestroyed", json!({ "targetId": "T1" }));
656        let news = told.recv().await.unwrap();
657        assert!(!pane.on_target(news, &mut Vec::new()).await);
658        pane.finish().await;
659    }
660
661    #[tokio::test]
662    async fn a_page_cannot_open_more_windows_than_a_pane_shows_and_the_person_is_told_once() {
663        let _serial = serial().await;
664        let (mut pane, _events, mut told, fake) = pane().await;
665        for n in 2..=windows::MAX_WINDOWS as u32 {
666            fake.set_address(&format!("S-T{n}"), "https://idp.example/auth", "x");
667            browser_says("Target.targetCreated", created(&format!("T{n}"), "T1"));
668            let news = told.recv().await.unwrap();
669            assert!(pane.on_target(news, &mut Vec::new()).await);
670        }
671        let mut out = Vec::new();
672        for extra in ["T90", "T91"] {
673            browser_says("Target.targetCreated", created(extra, "T1"));
674            let news = told.recv().await.unwrap();
675            assert!(pane.on_target(news, &mut out).await);
676            assert!(fake.calls().iter().any(|c| c.method == "Target.closeTarget" && c.params["targetId"] == extra), "{extra} is closed");
677            assert!(!fake.calls().iter().any(|c| c.method == "Target.attachToTarget" && c.params["targetId"] == extra), "{extra} is never attached");
678        }
679        let notices = of_kind(&out, "notice");
680        assert_eq!(notices.len(), 1, "two refusals in a moment are one line");
681        let line = notices[0]["message"].as_str().unwrap();
682        assert!(line.contains("app.example") || line.contains("a page"), "{line}");
683        assert!(line.contains("another window"), "{line}");
684        pane.finish().await;
685    }
686
687    #[tokio::test]
688    async fn a_dialog_is_dismissed_and_the_person_is_told_which_site_raised_it() {
689        let _serial = serial().await;
690        let (mut pane, _events, _told, fake) = pane().await;
691        let mut out = Vec::new();
692        let event = Event { method: "Page.javascriptDialogOpening".into(), params: json!({ "url": "https://ads.example/x", "type": "confirm", "message": "Leave this page?" }) };
693        assert!(pane.on_event(FIRST, event, &mut out).await);
694        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
695        let dismissal = fake.calls().into_iter().find(|c| c.method == "Page.handleJavaScriptDialog").unwrap();
696        assert_eq!((dismissal.params["accept"].as_bool(), dismissal.session.as_deref()), (Some(false), Some("S-T1")));
697        let line = of_kind(&out, "notice")[0]["message"].as_str().unwrap().to_string();
698        assert_eq!(line, "ads.example opened a confirmation question (“Leave this page?”). It was dismissed.");
699        pane.finish().await;
700    }
701
702    #[tokio::test]
703    async fn a_page_that_is_googles_refusal_gets_a_line_that_says_so_and_nothing_more() {
704        let _serial = serial().await;
705        let (mut pane, _events, _told, fake) = pane().await;
706        fake.set_address("S-T1", "https://accounts.google.com/v3/signin/rejected?dsh=x", "Sign in - Google Accounts");
707        let mut out = Vec::new();
708        let navigated = Event { method: "Page.frameNavigated".into(), params: json!({ "frame": { "id": "f" } }) };
709        assert!(pane.on_event(FIRST, navigated, &mut out).await);
710        let line = of_kind(&out, "notice")[0]["message"].as_str().unwrap().to_string();
711        assert!(line.starts_with("Google refused to sign in with this browser"), "{line}");
712        // An ordinary page says nothing.
713        fake.set_address("S-T1", "https://example.com/", "Example");
714        let mut quiet = Vec::new();
715        pane.on_event(FIRST, Event { method: "Page.frameNavigated".into(), params: json!({ "frame": { "id": "f" } }) }, &mut quiet).await;
716        assert!(of_kind(&quiet, "notice").is_empty());
717        pane.finish().await;
718    }
719
720    #[tokio::test]
721    async fn the_person_can_show_another_window_and_close_a_pop_up_but_never_the_first_window() {
722        let _serial = serial().await;
723        let (mut pane, _events, _told, fake, _) = with_popup().await;
724        let mut out = Vec::new();
725        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":0}"#, &mut out).await);
726        assert_eq!(of_kind(&out, "windows").last().unwrap()["active"], 0);
727        assert_eq!(of_kind(&out, "nav").last().unwrap()["url"], "https://app.example/");
728        // closing the first window is refused: nothing is closed
729        let before = fake.calls().iter().filter(|c| c.method == "Target.closeTarget").count();
730        assert!(pane.on_client(r#"{"t":"window","op":"close","id":0}"#, &mut out).await);
731        assert_eq!(fake.calls().iter().filter(|c| c.method == "Target.closeTarget").count(), before);
732        // a window that is not there changes nothing
733        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":42}"#, &mut out).await);
734        assert_eq!(pane.windows.active(), 0);
735        // closing the pop-up closes it in the browser and leaves one window
736        let mut closing = Vec::new();
737        assert!(pane.on_client(r#"{"t":"window","op":"close","id":1}"#, &mut closing).await);
738        assert!(fake.calls().iter().any(|c| c.method == "Target.closeTarget" && c.params["targetId"] == "T2"));
739        assert_eq!(of_kind(&closing, "windows").last().unwrap()["windows"].as_array().unwrap().len(), 1);
740        pane.finish().await;
741    }
742
743    #[tokio::test]
744    async fn only_the_shown_windows_frames_reach_the_pane_and_the_others_are_acknowledged() {
745        let _serial = serial().await;
746        let (mut pane, _events, _told, fake, _) = with_popup().await;
747        let frame = |n: i64| Event { method: "Page.screencastFrame".into(), params: json!({ "data": "AQID", "sessionId": n }) };
748        let mut out = Vec::new();
749        assert!(pane.on_event(0, frame(7), &mut out).await);
750        assert!(out.is_empty(), "the first window is not shown now");
751        tokio::time::sleep(std::time::Duration::from_millis(50)).await;
752        assert!(fake.calls().iter().any(|c| c.method == "Page.screencastFrameAck" && c.params["sessionId"] == 7 && c.session.as_deref() == Some("S-T1")));
753        assert!(pane.on_event(1, frame(8), &mut out).await);
754        assert_eq!(out, vec![Out::Frame { bytes: vec![1, 1, 2, 3], ack: Some(("S-T2".to_string(), 8)) }]);
755        pane.finish().await;
756    }
757
758    #[tokio::test]
759    async fn a_resize_reaches_every_window_and_the_pane_ending_closes_them_all() {
760        let _serial = serial().await;
761        let (mut pane, _events, _told, fake, _) = with_popup().await;
762        let mut out = Vec::new();
763        assert!(pane.on_client(r#"{"t":"resize","w":900,"h":700}"#, &mut out).await);
764        let sized: Vec<_> = fake.calls().into_iter().filter(|c| c.method == "Emulation.setDeviceMetricsOverride" && c.params["width"] == 900).collect();
765        assert_eq!(sized.len(), 2);
766        pane.finish().await;
767        let closed: Vec<_> = fake.calls().into_iter().filter(|c| c.method == "Target.closeTarget").map(|c| c.params["targetId"].as_str().unwrap().to_string()).collect();
768        assert!(closed.contains(&"T1".to_string()) && closed.contains(&"T2".to_string()), "{closed:?}");
769        // Nothing of this pane is claimed any more: a window opened by one of its pages is nobody's and is closed.
770        assert_eq!(browser_says("Target.targetCreated", created("T77", "T2")), vec!["T77".to_string()]);
771    }
772
773    #[tokio::test]
774    async fn a_pane_dropped_without_finishing_claims_nothing_any_more() {
775        let _serial = serial().await;
776        let (pane, _events, _told, _fake) = pane().await;
777        // The pane ends by a panic or its task is dropped: `finish` never runs.
778        drop(pane);
779        assert_eq!(browser_says("Target.targetCreated", created("T78", "T1")), vec!["T78".to_string()], "its first page is still claimed");
780    }
781
782    #[tokio::test]
783    async fn a_window_the_browser_will_not_let_the_pane_attach_is_closed_and_the_person_told() {
784        let _serial = serial().await;
785        let (mut pane, _events, mut told, fake) = pane().await;
786        fake.refuse("Target.attachToTarget", "T2");
787        browser_says("Target.targetCreated", created("T2", "T1"));
788        let news = told.recv().await.unwrap();
789        let mut out = Vec::new();
790        assert!(pane.on_target(news, &mut out).await);
791        assert!(fake.calls().iter().any(|c| c.method == "Target.closeTarget" && c.params["targetId"] == "T2"));
792        assert!(of_kind(&out, "notice")[0]["message"].as_str().unwrap().contains("could not be shown"));
793        assert_eq!(pane.windows.len(), 1);
794        pane.finish().await;
795    }
796
797    #[tokio::test]
798    async fn the_pane_s_first_page_is_claimed_as_it_is_made_and_a_page_nobody_made_for_a_pane_is_closed() {
799        let _serial = serial().await;
800        let (pane, _events, _told, _fake) = pane().await;
801        // The news of its own page is no reason to close it; a page with no opener that no pane made is nobody's.
802        assert!(browser_says("Target.targetCreated", json!({ "targetInfo": { "targetId": "T1", "type": "page", "url": "about:blank" } })).is_empty());
803        assert_eq!(browser_says("Target.targetCreated", json!({ "targetInfo": { "targetId": "T9", "type": "page", "url": "about:blank" } })), vec!["T9".to_string()]);
804        pane.finish().await;
805    }
806
807    const KEY: &str = r#"{"t":"key","type":"down","key":"p","code":"KeyP","text":"p","vk":80}"#;
808    const PASTE: &str = r#"{"t":"paste","text":"secret"}"#;
809    const CLICK: &str = r#"{"t":"mouse","type":"down","x":5,"y":6,"button":"left","buttons":1,"clicks":1}"#;
810
811    /// The sessions a method was sent to, in order.
812    fn sent_to(fake: &FakeBrowser, method: &str) -> Vec<String> {
813        fake.calls().into_iter().filter(|c| c.method == method).filter_map(|c| c.session).collect()
814    }
815
816    #[tokio::test]
817    async fn keys_sent_just_after_a_page_opened_a_window_reach_no_window_but_the_pointer_does() {
818        let _serial = serial().await;
819        let ms = std::time::Duration::from_millis;
820        let t0 = Instant::now();
821        let (mut pane, _events, _told, fake, _) = with_popup().await;
822        let mut out = Vec::new();
823        // A typed key and a paste, inside the gap (half a second after the window appeared, at the latest).
824        assert!(pane.on_client_at(KEY, &mut out, t0 + ms(50)).await);
825        assert!(pane.on_client_at(PASTE, &mut out, t0 + ms(200)).await);
826        assert!(pane.on_client_at(KEY, &mut out, t0 + ms(450)).await);
827        // The pointer is not held.
828        assert!(pane.on_client_at(CLICK, &mut out, t0 + ms(100)).await);
829        tokio::time::sleep(ms(50)).await;
830        assert!(sent_to(&fake, "Input.dispatchKeyEvent").is_empty(), "a key reached a window in the gap");
831        assert!(sent_to(&fake, "Input.insertText").is_empty(), "a paste reached a window in the gap");
832        assert_eq!(sent_to(&fake, "Input.dispatchMouseEvent"), vec!["S-T2".to_string()]);
833        // Once the gap is over, a key goes to the shown window as before.
834        assert!(pane.on_client_at(KEY, &mut out, t0 + std::time::Duration::from_secs(60)).await);
835        tokio::time::sleep(ms(50)).await;
836        assert_eq!(sent_to(&fake, "Input.dispatchKeyEvent"), vec!["S-T2".to_string()]);
837        pane.finish().await;
838    }
839
840    #[tokio::test]
841    async fn keys_are_held_when_the_shown_window_closes_itself_but_not_when_the_person_closes_or_shows_one() {
842        let _serial = serial().await;
843        // It closes itself: the page behind it is shown again without the person choosing it.
844        let (mut pane, _events, mut told, _fake, _) = with_popup().await;
845        pane.keys_held_until = None;
846        browser_says("Target.targetDestroyed", json!({ "targetId": "T2" }));
847        let news = told.recv().await.unwrap();
848        assert!(pane.on_target(news, &mut Vec::new()).await);
849        assert!(pane.keys_held_until.is_some(), "the person did not choose to go back");
850        pane.finish().await;
851        // The person closes it from its tab, or shows another window: their choice, no gap.
852        let (mut pane, _events, _told, _fake, _) = with_popup().await;
853        pane.keys_held_until = None;
854        assert!(pane.on_client(r#"{"t":"window","op":"close","id":1}"#, &mut Vec::new()).await);
855        assert!(pane.keys_held_until.is_none());
856        pane.finish().await;
857        let (mut pane, _events, _told, _fake, _) = with_popup().await;
858        pane.keys_held_until = None;
859        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":0}"#, &mut Vec::new()).await);
860        assert!(pane.keys_held_until.is_none());
861        pane.finish().await;
862    }
863
864    #[tokio::test]
865    async fn a_window_that_changed_site_while_not_shown_is_told_to_the_person_when_they_come_back_to_it() {
866        let _serial = serial().await;
867        let moved = || Event { method: "Page.frameNavigated".into(), params: json!({ "frame": { "id": "f" } }) };
868        // The person goes back to it.
869        let (mut pane, _events, _told, fake, _) = with_popup().await;
870        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":0}"#, &mut Vec::new()).await);
871        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":1}"#, &mut Vec::new()).await);
872        fake.set_address("S-T1", "https://evil.example/pay", "Pay");
873        let mut behind = Vec::new();
874        assert!(pane.on_event(FIRST, moved(), &mut behind).await);
875        assert!(of_kind(&behind, "notice").is_empty(), "nothing is said while they look at another window");
876        let mut back = Vec::new();
877        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":0}"#, &mut back).await);
878        let notices = of_kind(&back, "notice");
879        assert_eq!(notices.len(), 1);
880        assert_eq!(notices[0]["message"], "This window went from app.example to evil.example while it was not shown.");
881        pane.finish().await;
882        // The window in front closes itself and the one behind, which moved, is shown again.
883        let (mut pane, _events, mut told, fake, _) = with_popup().await;
884        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":0}"#, &mut Vec::new()).await);
885        assert!(pane.on_client(r#"{"t":"window","op":"focus","id":1}"#, &mut Vec::new()).await);
886        fake.set_address("S-T1", "https://evil.example/pay", "Pay");
887        assert!(pane.on_event(FIRST, moved(), &mut Vec::new()).await);
888        browser_says("Target.targetDestroyed", json!({ "targetId": "T2" }));
889        let news = told.recv().await.unwrap();
890        let mut returned = Vec::new();
891        assert!(pane.on_target(news, &mut returned).await);
892        assert!(of_kind(&returned, "notice")[0]["message"].as_str().unwrap().contains("from app.example to evil.example"));
893        pane.finish().await;
894    }
895
896    #[tokio::test]
897    async fn a_window_has_no_lease_of_its_own_and_cannot_outlive_the_pane_that_holds_it() {
898        let _serial = serial().await;
899        let (pane, _events, _told, fake, _) = with_popup().await;
900        // Only the pane's first page was asked of the browser: a window a page opens is the browser's doing, not a second place held.
901        assert_eq!(fake.calls().iter().filter(|c| c.method == "Target.createTarget").count(), 1);
902        pane.finish().await;
903        // `run` holds the pane's one lease until `finish` has closed every window: nothing of the pane is open after it.
904        let closed: Vec<String> = fake.calls().into_iter().filter(|c| c.method == "Target.closeTarget").filter_map(|c| c.params["targetId"].as_str().map(str::to_string)).collect();
905        assert!(closed.contains(&"T1".to_string()) && closed.contains(&"T2".to_string()), "{closed:?}");
906        assert_eq!(browser_says("Target.targetCreated", created("T9", "T2")), vec!["T9".to_string()], "nothing of it is still claimed");
907    }
908
909    #[tokio::test]
910    async fn the_bar_shows_the_shown_window_s_top_level_address_and_a_frame_s_navigation_changes_nothing() {
911        let _serial = serial().await;
912        let (mut pane, _events, _told, _fake, _) = with_popup().await;
913        let mut out = Vec::new();
914        // A frame inside the pop-up goes to another address: not news for the bar.
915        let frame = Event { method: "Page.frameNavigated".into(), params: json!({ "frame": { "id": "f2", "parentId": "f1", "url": "https://ads.example/frame" } }) };
916        assert!(pane.on_event(1, frame, &mut out).await);
917        assert!(of_kind(&out, "nav").is_empty());
918        // The top-level navigation is: the bar shows the window's own address (read from its history, never from a frame).
919        let top = Event { method: "Page.frameNavigated".into(), params: json!({ "frame": { "id": "f1", "url": "https://idp.example/auth" } }) };
920        assert!(pane.on_event(1, top, &mut out).await);
921        assert_eq!(of_kind(&out, "nav").last().unwrap()["url"], "https://idp.example/auth");
922        pane.finish().await;
923    }
924
925    // ---- with a real Chromium (not run by default: `cargo test -p agentmux-srv real_chromium -- --ignored`) ----------------------------
926
927    /// A page server on a loopback port of its own: `/app` has a button that opens a sign-in window; `/popup` is that window, which
928    /// returns its result to the page that opened it and closes itself.
929    async fn sign_in_site() -> u16 {
930        use tokio::io::{AsyncReadExt, AsyncWriteExt};
931        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
932        let port = listener.local_addr().unwrap().port();
933        tokio::spawn(async move {
934            loop {
935                let Ok((mut socket, _)) = listener.accept().await else { return };
936                tokio::spawn(async move {
937                    let mut buf = [0u8; 2048];
938                    let n = socket.read(&mut buf).await.unwrap_or(0);
939                    let request = String::from_utf8_lossy(&buf[..n]).to_string();
940                    let path = request.split_whitespace().nth(1).unwrap_or("/").to_string();
941                    let body = if path.starts_with("/popup") {
942                        "<title>Sign in</title><p>the sign-in window</p><script>setTimeout(() => { opener.postMessage({ code: 'abc' }, '*'); window.close(); }, 600);</script>"
943                    } else {
944                        "<title>App</title><button id=b style='position:absolute;left:10px;top:10px;width:300px;height:80px' onclick='signIn()'>Sign in</button>\
945                         <script>window.result = { messages: [], closed: false, opened: false };\
946                         addEventListener('message', (e) => result.messages.push(e.data));\
947                         function signIn() { const w = open('/popup', 'idp', 'width=500,height=600'); result.opened = !!w; const t = setInterval(() => { if (w && w.closed) { result.closed = true; clearInterval(t); } }, 100); }</script>"
948                    };
949                    let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
950                    let _ = socket.write_all(reply.as_bytes()).await;
951                });
952            }
953        });
954        port
955    }
956
957    /// Feed the pane what the browser says for `ms`, collecting what it would send.
958    async fn pump(pane: &mut Pane, events: &mut Events, told: &mut UnboundedReceiver<TargetEvent>, out: &mut Vec<Out>, ms: u64) {
959        let end = tokio::time::Instant::now() + std::time::Duration::from_millis(ms);
960        loop {
961            tokio::select! {
962                _ = tokio::time::sleep_until(end) => return,
963                Some((id, e)) = events.recv() => { pane.on_event(id, e, out).await; }
964                Some(n) = told.recv() => { pane.on_target(n, out).await; }
965            }
966        }
967    }
968
969    async fn real_chromium_a_sign_in_window_returns_its_result_to_the_page_and_the_pane_goes_back() {
970        super::super::chromium::use_profile_root(std::env::temp_dir().join(format!("amx-pane-test-{}", std::process::id())));
971        let port = sign_in_site().await;
972        let lease = super::super::chromium::lease().await.expect("a browser for the pane");
973        let (mut pane, mut events, mut told) = Pane::open(&lease.cdp, &Start { url: format!("http://127.0.0.1:{port}/app"), w: 800, h: 600 }).await.expect("the pane opens");
974        let mut out = Vec::new();
975        pump(&mut pane, &mut events, &mut told, &mut out, 2000).await;
976
977        // A person's click on the button (a real input event, so the page may open a window).
978        for kind in ["down", "up"] {
979            let click = format!(r#"{{"t":"mouse","type":"{kind}","x":50,"y":40,"button":"left","buttons":1,"clicks":1}}"#);
980            assert!(pane.on_client(&click, &mut out).await);
981        }
982        // The window opens and is shown, with its own address.
983        let mut shown = false;
984        for _ in 0..20 {
985            pump(&mut pane, &mut events, &mut told, &mut out, 250).await;
986            if pane.windows.len() == 2 && pane.windows.active() != FIRST {
987                shown = true;
988                break;
989            }
990        }
991        assert!(shown, "the sign-in window was never shown: {:?}", of_kind(&out, "windows").last());
992        let popup_nav = of_kind(&out, "nav").into_iter().rev().find(|n| n["url"].as_str().is_some_and(|u| u.contains("/popup")));
993        assert!(popup_nav.is_some(), "the bar never showed the window's own address");
994
995        // It returns its result and closes itself; the pane goes back to the page.
996        let mut back = false;
997        for _ in 0..40 {
998            pump(&mut pane, &mut events, &mut told, &mut out, 250).await;
999            if pane.windows.len() == 1 && pane.windows.active() == FIRST {
1000                back = true;
1001                break;
1002            }
1003        }
1004        assert!(back, "the pane did not go back to the page");
1005        let session = pane.windows.get(FIRST).unwrap().session.clone();
1006        let result = pane.cdp.call("Runtime.evaluate", json!({ "expression": "JSON.stringify(window.result)", "returnByValue": true }), Some(&session)).await.unwrap();
1007        let seen: Value = serde_json::from_str(result["result"]["value"].as_str().expect("the page's result")).unwrap();
1008        assert_eq!(seen["opened"], true, "{seen}");
1009        assert_eq!(seen["messages"], json!([{ "code": "abc" }]), "the window's result reached the page that opened it: {seen}");
1010        assert_eq!(seen["closed"], true, "the page sees the window closed: {seen}");
1011
1012        pane.finish().await;
1013        drop(lease);
1014    }
1015
1016    // ---- real Chromium: a page that opens a window straight to an address that is refused ------------------------------------------
1017
1018    /// A page server on a loopback port of its own that answers every path with `body`.
1019    async fn static_site(body: String) -> u16 {
1020        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1021        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1022        let port = listener.local_addr().unwrap().port();
1023        tokio::spawn(async move {
1024            loop {
1025                let Ok((mut socket, _)) = listener.accept().await else { return };
1026                let body = body.clone();
1027                tokio::spawn(async move {
1028                    let mut buf = [0u8; 2048];
1029                    let _ = socket.read(&mut buf).await;
1030                    let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
1031                    let _ = socket.write_all(reply.as_bytes()).await;
1032                });
1033            }
1034        });
1035        port
1036    }
1037
1038    /// A server that stands for something the page must not reach: it counts the connections it gets.
1039    async fn secret_server() -> (u16, Arc<std::sync::atomic::AtomicUsize>) {
1040        let hits = Arc::new(std::sync::atomic::AtomicUsize::new(0));
1041        let counted = hits.clone();
1042        let port = static_site_counting("SECRET-MARKER-HTTP".to_string(), counted).await;
1043        (port, hits)
1044    }
1045
1046    async fn static_site_counting(body: String, hits: Arc<std::sync::atomic::AtomicUsize>) -> u16 {
1047        use tokio::io::AsyncWriteExt;
1048        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1049        let port = listener.local_addr().unwrap().port();
1050        tokio::spawn(async move {
1051            loop {
1052                let Ok((mut socket, _)) = listener.accept().await else { return };
1053                hits.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
1054                let body = body.clone();
1055                tokio::spawn(async move {
1056                    let reply = format!("HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", body.len());
1057                    let _ = socket.write_all(reply.as_bytes()).await;
1058                });
1059            }
1060        });
1061        port
1062    }
1063
1064    /// The pages the browser has, as (id, address).
1065    async fn pages(cdp: &Cdp) -> Vec<(String, String)> {
1066        let found = cdp.call("Target.getTargets", json!({}), None).await.unwrap();
1067        let list = found["targetInfos"].as_array().cloned().unwrap_or_default();
1068        list.iter().filter(|i| i["type"] == "page").map(|i| (i["targetId"].as_str().unwrap_or("").to_string(), i["url"].as_str().unwrap_or("").to_string())).collect()
1069    }
1070
1071    /// What a window shows: its scheme and the words on it. None when nothing was loaded in it at all.
1072    async fn what_it_shows(cdp: &Cdp, session: &str) -> Option<(String, String)> {
1073        let expression = "JSON.stringify({ p: location.protocol, t: (document.documentElement && document.documentElement.innerText) || '' })";
1074        let result = cdp.call("Runtime.evaluate", json!({ "expression": expression, "returnByValue": true }), Some(session)).await.ok()?;
1075        let seen: Value = serde_json::from_str(result["result"]["value"].as_str()?).ok()?;
1076        Some((seen["p"].as_str().unwrap_or("").to_string(), seen["t"].as_str().unwrap_or("").to_string()))
1077    }
1078
1079    async fn click(pane: &mut Pane, out: &mut Vec<Out>, x: f64, y: f64) {
1080        for kind in ["down", "up"] {
1081            let message = format!(r#"{{"t":"mouse","type":"{kind}","x":{x},"y":{y},"button":"left","buttons":1,"clicks":1}}"#);
1082            assert!(pane.on_client(&message, out).await);
1083        }
1084    }
1085
1086    async fn real_chromium_a_page_that_opens_a_window_straight_to_a_refused_address_gets_nothing_on_its_first_request() {
1087        super::super::chromium::use_profile_root(std::env::temp_dir().join(format!("amx-pane-test-{}", std::process::id())));
1088        // Something the policy refuses (a port of this server's own), a local file, and one of the browser's own pages.
1089        let (secret_port, hits) = secret_server().await;
1090        super::super::address_policy::note_own_port(secret_port);
1091        let marker = std::env::temp_dir().join(format!("amx-secret-{}.txt", std::process::id()));
1092        std::fs::write(&marker, "SECRET-MARKER-FILE").unwrap();
1093        let (refused, file, own) = (format!("http://127.0.0.1:{secret_port}/secret"), format!("file://{}", marker.display()), "chrome://version/".to_string());
1094        let button = |top: u32, address: &str| format!("<button style='position:absolute;left:10px;top:{top}px;width:300px;height:60px' onclick=\"window.open('{address}')\">open</button>");
1095        let site = static_site(format!("<title>App</title>{}{}{}", button(10, &refused), button(90, &file), button(170, &own))).await;
1096
1097        let lease = super::super::chromium::lease().await.expect("a browser for the pane");
1098        let (mut pane, mut events, mut told) = Pane::open(&lease.cdp, &Start { url: format!("http://127.0.0.1:{site}/app"), w: 800, h: 600 }).await.expect("the pane opens");
1099        let mut out = Vec::new();
1100        pump(&mut pane, &mut events, &mut told, &mut out, 2000).await;
1101
1102        for (what, y, must_open) in [("an address the policy refuses", 40.0, true), ("a file: address", 120.0, false), ("a chrome: address", 200.0, false)] {
1103            click(&mut pane, &mut out, 50.0, y).await;
1104            pump(&mut pane, &mut events, &mut told, &mut out, 1500).await;
1105            let windows: Vec<_> = pane.windows.entries().iter().filter(|e| e.id != FIRST).map(|e| (e.id, e.session.clone())).collect();
1106            eprintln!("{what}: {} window(s) opened; the browser has {:?}", windows.len(), pages(&pane.cdp).await);
1107            if must_open {
1108                assert!(!windows.is_empty(), "the click opened no window, so this test checked nothing");
1109            }
1110            for (_, session) in &windows {
1111                let shown = what_it_shows(&pane.cdp, session).await;
1112                eprintln!("{what}: the window shows {shown:?}");
1113                if let Some((scheme, words)) = shown {
1114                    assert!(scheme != "file:" && scheme != "chrome:", "{what}: the window loaded a {scheme} page");
1115                    assert!(!words.contains("SECRET-MARKER"), "{what}: the window shows what was refused: {words}");
1116                }
1117            }
1118            for (id, _) in &windows {
1119                assert!(pane.on_client(&format!(r#"{{"t":"window","op":"close","id":{id}}}"#), &mut out).await);
1120            }
1121            pump(&mut pane, &mut events, &mut told, &mut out, 300).await;
1122        }
1123        assert_eq!(hits.load(std::sync::atomic::Ordering::SeqCst), 0, "the refused address got a connection: its first request was not refused");
1124        let _ = std::fs::remove_file(&marker);
1125        pane.finish().await;
1126        drop(lease);
1127    }
1128
1129    /// A page of the browser the test owns, as a pane owns its first: claimed as it is made, at `url`, with a session.
1130    async fn own_page(cdp: &Arc<Cdp>, url: &str) -> (String, String, UnboundedReceiver<TargetEvent>) {
1131        let (tx, rx) = mpsc::unbounded_channel();
1132        let making = popups::making_a_page();
1133        let made = cdp.call("Target.createTarget", json!({ "url": "about:blank" }), None).await.expect("a page");
1134        let target = made["targetId"].as_str().expect("its id").to_string();
1135        popups::claim(&target, tx);
1136        for stray in making.done() {
1137            let _ = cdp.call("Target.closeTarget", json!({ "targetId": stray }), None).await;
1138        }
1139        let attached = cdp.call("Target.attachToTarget", json!({ "targetId": target, "flatten": true }), None).await.expect("attached");
1140        let session = attached["sessionId"].as_str().expect("its session").to_string();
1141        cdp.call("Page.enable", json!({}), Some(&session)).await.unwrap();
1142        cdp.call("Page.navigate", json!({ "url": url }), Some(&session)).await.unwrap();
1143        tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
1144        (target, session, rx)
1145    }
1146
1147    /// Run `expression` in the page, as a click would (`gesture`) or as a script on its own.
1148    async fn run_in(cdp: &Cdp, session: &str, expression: &str, gesture: bool) {
1149        let _ = cdp.call("Runtime.evaluate", json!({ "expression": expression, "userGesture": gesture }), Some(session)).await;
1150        tokio::time::sleep(std::time::Duration::from_millis(1500)).await;
1151    }
1152
1153    async fn real_chromium_the_engine_alone_refuses_a_page_s_window_to_every_address_the_blocked_list_names() {
1154        super::super::chromium::use_profile_root(std::env::temp_dir().join(format!("amx-pane-test-{}", std::process::id())));
1155        let marker = std::env::temp_dir().join(format!("amx-secret-engine-{}.txt", std::process::id()));
1156        std::fs::write(&marker, "SECRET-MARKER-FILE").unwrap();
1157        let site = static_site("<title>App</title>".to_string()).await;
1158        let lease = super::super::chromium::lease().await.expect("a browser");
1159        // No `Network.setBlockedURLs` anywhere here: only what the engine does with a page that opens a window to the address.
1160        let (opener, session, _rx) = own_page(&lease.cdp, &format!("http://127.0.0.1:{site}/app")).await;
1161        let addresses = [
1162            format!("file://{}", marker.display()),
1163            "chrome://version/".to_string(),
1164            "chrome-untrusted://terminal/".to_string(),
1165            "chrome-extension://abcdefghijklmnopabcdefghijklmnop/x.html".to_string(),
1166            "devtools://devtools/bundled/inspector.html".to_string(),
1167            format!("view-source:http://127.0.0.1:{site}/app"),
1168        ];
1169        let mut let_through = Vec::new();
1170        for address in &addresses {
1171            let before = pages(&lease.cdp).await;
1172            run_in(&lease.cdp, &session, &format!("window.open({address:?}, '_blank')"), true).await;
1173            let after = pages(&lease.cdp).await;
1174            let opened: Vec<_> = after.iter().filter(|(id, _)| !before.iter().any(|(b, _)| b == id)).cloned().collect();
1175            let scheme = format!("{}:", address.split(':').next().unwrap_or(""));
1176            eprintln!("{address}: the page opened {} window(s): {opened:?}", opened.len());
1177            for (id, url) in &opened {
1178                let attached = lease.cdp.call("Target.attachToTarget", json!({ "targetId": id, "flatten": true }), None).await;
1179                let shown = match attached.ok().and_then(|a| a["sessionId"].as_str().map(str::to_string)) {
1180                    Some(s) => what_it_shows(&lease.cdp, &s).await,
1181                    None => None,
1182                };
1183                eprintln!("{address}: the window is at {url} and shows {shown:?}");
1184                if shown.as_ref().is_some_and(|(p, words)| *p == scheme || words.contains("SECRET-MARKER")) {
1185                    let_through.push(address.clone());
1186                }
1187                let _ = lease.cdp.call("Target.closeTarget", json!({ "targetId": id }), None).await;
1188            }
1189        }
1190        assert!(let_through.is_empty(), "the engine let a page's window load: {let_through:?}, so the blocked list is the only thing refusing it");
1191        let _ = std::fs::remove_file(&marker);
1192        let _ = lease.cdp.call("Target.closeTarget", json!({ "targetId": opener }), None).await;
1193        popups::release(&opener);
1194        drop(lease);
1195    }
1196
1197    async fn real_chromium_a_page_can_open_a_window_only_on_a_gesture() {
1198        super::super::chromium::use_profile_root(std::env::temp_dir().join(format!("amx-pane-test-{}", std::process::id())));
1199        let site = static_site("<title>App</title>".to_string()).await;
1200        let lease = super::super::chromium::lease().await.expect("a browser");
1201        let (opener, session, _rx) = own_page(&lease.cdp, &format!("http://127.0.0.1:{site}/app")).await;
1202        let before = pages(&lease.cdp).await;
1203        // A script on its own (no click, no key): the engine's pop-up blocking refuses it, so no page exists that was not there.
1204        run_in(&lease.cdp, &session, "window.open('/popup', '_blank')", false).await;
1205        let without = pages(&lease.cdp).await;
1206        assert_eq!(without.len(), before.len(), "a window opened with no gesture: {without:?}");
1207        // The same call on a gesture opens one, so the check above is a check of something.
1208        run_in(&lease.cdp, &session, "window.open('/popup', '_blank')", true).await;
1209        let with = pages(&lease.cdp).await;
1210        assert_eq!(with.len(), before.len() + 1, "a window opened on a gesture was not made: {with:?}");
1211        for (id, _) in with.iter().filter(|(id, _)| !before.iter().any(|(b, _)| b == id)) {
1212            let _ = lease.cdp.call("Target.closeTarget", json!({ "targetId": id }), None).await;
1213        }
1214        let _ = lease.cdp.call("Target.closeTarget", json!({ "targetId": opener }), None).await;
1215        popups::release(&opener);
1216        drop(lease);
1217    }
1218
1219    /// The real-Chromium scenarios, one after the other in one test. The browser, its address proxy and its profile belong to the
1220    /// process and are started on the runtime that is running the first one: a test of its own would run on a runtime of its own, and
1221    /// find the browser the one before it started stopped with that runtime. A scenario that fails does not stop the ones after it.
1222    #[tokio::test]
1223    #[ignore = "needs a Chromium: AGENTMUX_STREAMED_BROWSER_BIN, or one on the PATH"]
1224    async fn real_chromium_scenarios() {
1225        let _serial = serial().await;
1226        let mut failed: Vec<String> = Vec::new();
1227        macro_rules! scenario {
1228            ($name:ident) => {{
1229                eprintln!("== {}", stringify!($name));
1230                if let Err(e) = tokio::spawn($name()).await {
1231                    failed.push(format!("{}: {e}", stringify!($name)));
1232                }
1233            }};
1234        }
1235        scenario!(real_chromium_a_sign_in_window_returns_its_result_to_the_page_and_the_pane_goes_back);
1236        scenario!(real_chromium_a_page_that_opens_a_window_straight_to_a_refused_address_gets_nothing_on_its_first_request);
1237        scenario!(real_chromium_the_engine_alone_refuses_a_page_s_window_to_every_address_the_blocked_list_names);
1238        scenario!(real_chromium_a_page_can_open_a_window_only_on_a_gesture);
1239        assert!(failed.is_empty(), "scenarios that failed: {failed:?}");
1240    }
1241}