Skip to main content

agentmux_srv/server/streamed_browser/
windows.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The windows of one streamed pane: the page it started with, and the windows that page (or a window of it) opened. Only
5//! one is shown at a time. A window a page opens (a sign-in pop-up, a link to a new tab) becomes the shown one, so the person sees
6//! it and its address; it can return its result to the page that opened it; it ends when its page closes it, and the pane goes
7//! back to the window that opened it. A page cannot open windows without limit.
8//!
9//! Plain data and functions, so every rule is tested without a browser.
10
11use std::time::{Duration, Instant};
12
13use serde_json::{json, Value};
14
15/// At most this many windows in one pane, the first included.
16pub const MAX_WINDOWS: usize = 4;
17/// After the shown window changes without the person choosing it (a page opened one, or one closed itself), keys the person
18/// types are dropped for this long: a key meant for one window must not land in another (a password typed into a page the
19/// person had not yet seen). Pointer input is not held.
20pub const KEY_GAP: Duration = Duration::from_millis(500);
21/// The window id of the page a pane starts with. It is never closed by the person or by a page.
22pub const FIRST: WindowId = 0;
23
24pub type WindowId = u32;
25
26/// One window: where the browser keeps it and what the person sees of it.
27#[derive(Debug, Clone, PartialEq)]
28pub struct Entry {
29    pub id: WindowId,
30    /// The browser's id of the page and the session this pane talks to it through.
31    pub target: String,
32    pub session: String,
33    /// The window that opened this one.
34    pub opener: Option<WindowId>,
35    pub url: String,
36    pub title: String,
37    /// While the window was not shown it went from one site to another: (the site the person last saw, the site it is on now).
38    pub moved: Option<(String, String)>,
39}
40
41/// What `remove` changed.
42#[derive(Debug, PartialEq, Eq)]
43pub struct Removed {
44    pub was_active: bool,
45    pub now_active: WindowId,
46}
47
48#[derive(Debug)]
49pub struct Windows {
50    list: Vec<Entry>,
51    active: WindowId,
52    next: WindowId,
53}
54
55impl Windows {
56    /// The pane's first window, which is the shown one.
57    pub fn starting(target: String, session: String) -> Windows {
58        let first = Entry { id: FIRST, target, session, opener: None, url: String::new(), title: String::new(), moved: None };
59        Windows { list: vec![first], active: FIRST, next: FIRST + 1 }
60    }
61
62    pub fn len(&self) -> usize {
63        self.list.len()
64    }
65
66    pub fn has_room(&self) -> bool {
67        self.list.len() < MAX_WINDOWS
68    }
69
70    pub fn active(&self) -> WindowId {
71        self.active
72    }
73
74    pub fn entries(&self) -> &[Entry] {
75        &self.list
76    }
77
78    pub fn get(&self, id: WindowId) -> Option<&Entry> {
79        self.list.iter().find(|w| w.id == id)
80    }
81
82    pub fn by_session(&self, session: &str) -> Option<WindowId> {
83        self.list.iter().find(|w| w.session == session).map(|w| w.id)
84    }
85
86    pub fn by_target(&self, target: &str) -> Option<WindowId> {
87        self.list.iter().find(|w| w.target == target).map(|w| w.id)
88    }
89
90    /// A new window, opened by `opener`. It becomes the shown one. `None` when the pane is at its limit.
91    pub fn add(&mut self, target: String, session: String, opener: Option<WindowId>) -> Option<WindowId> {
92        if !self.has_room() {
93            return None;
94        }
95        let id = self.next;
96        self.next += 1;
97        self.list.push(Entry { id, target, session, opener: opener.filter(|o| self.get(*o).is_some()), url: String::new(), title: String::new(), moved: None });
98        self.active = id;
99        Some(id)
100    }
101
102    /// The window ends. When it was the shown one, the one that opened it is shown again (else the one before it in the list). The first
103    /// window is never removed here: when it ends the pane does.
104    pub fn remove(&mut self, id: WindowId) -> Option<Removed> {
105        if id == FIRST {
106            return None;
107        }
108        let at = self.list.iter().position(|w| w.id == id)?;
109        let gone = self.list.remove(at);
110        // Windows this one opened now have no opener left to go back to.
111        for w in &mut self.list {
112            if w.opener == Some(id) {
113                w.opener = gone.opener;
114            }
115        }
116        let was_active = self.active == id;
117        if was_active {
118            let back = gone.opener.filter(|o| self.get(*o).is_some());
119            self.active = back.or_else(|| self.list.get(at.saturating_sub(1)).map(|w| w.id)).unwrap_or(FIRST);
120        }
121        Some(Removed { was_active, now_active: self.active })
122    }
123
124    /// Show `id`. False when there is no such window.
125    pub fn focus(&mut self, id: WindowId) -> bool {
126        if self.get(id).is_none() {
127            return false;
128        }
129        self.active = id;
130        true
131    }
132
133    pub fn set_location(&mut self, id: WindowId, url: String, title: String) {
134        let shown = self.active == id;
135        if let Some(w) = self.list.iter_mut().find(|w| w.id == id) {
136            if !shown {
137                // A window the person is not looking at went to another site: remember where it was when they last saw it.
138                let (was, now) = (site_of(&w.url), site_of(&url));
139                if was != now && was != NO_SITE {
140                    let from = w.moved.take().map(|(from, _)| from).unwrap_or(was);
141                    w.moved = if from == now { None } else { Some((from, now)) };
142                }
143            }
144            w.url = url;
145            w.title = title;
146        }
147    }
148
149    /// What the person has not yet been told about `id`: it changed site while it was not shown. Said once.
150    pub fn take_moved(&mut self, id: WindowId) -> Option<(String, String)> {
151        self.list.iter_mut().find(|w| w.id == id).and_then(|w| w.moved.take())
152    }
153
154    /// The `windows` message: every window with its address, which is shown, and which the person may close.
155    pub fn message(&self) -> Value {
156        let list: Vec<Value> = self
157            .list
158            .iter()
159            .map(|w| json!({ "id": w.id, "url": w.url, "title": w.title, "opener": w.opener, "closable": w.id != FIRST }))
160            .collect();
161        json!({ "t": "windows", "active": self.active, "windows": list })
162    }
163}
164
165/// What a line says for an address that has no host.
166const NO_SITE: &str = "a page";
167
168/// The site an address belongs to, for a line the person reads: the host, or "a page" when there is none.
169pub fn site_of(url: &str) -> String {
170    url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string)).filter(|h| !h.is_empty()).unwrap_or_else(|| NO_SITE.to_string())
171}
172
173/// A character a person cannot see or that changes how the text around it reads: controls, the marks that reorder text
174/// (bidi), and the ones that have no width (zero-width, joiners, the byte-order mark, soft hyphen, tag characters).
175fn is_hidden(c: char) -> bool {
176    c.is_control()
177        || matches!(c as u32, 0x061C | 0x00AD | 0x180E | 0x200B..=0x200F | 0x202A..=0x202E | 0x2060..=0x206F | 0xFEFF | 0xE0000..=0xE007F)
178}
179
180/// Words a page wrote, made safe to show inside a line of ours: one line, nothing hidden, at most `max` characters.
181fn shorten(text: &str, max: usize) -> String {
182    // Line breaks and tabs become one space first, then every hidden character goes.
183    let one_line: String = text.split_whitespace().collect::<Vec<_>>().join(" ").chars().filter(|c| !is_hidden(*c)).collect();
184    let one_line = one_line.split_whitespace().collect::<Vec<_>>().join(" ");
185    if one_line.chars().count() <= max {
186        return one_line;
187    }
188    format!("{}…", one_line.chars().take(max).collect::<String>())
189}
190
191/// The line for a page that opened more windows than a pane shows.
192pub fn too_many_windows(opener_url: &str) -> String {
193    format!("{} tried to open another window. A pane shows at most {MAX_WINDOWS} windows, so it was closed.", site_of(opener_url))
194}
195
196/// The line for a message box a page raised (alert, confirm, prompt, leaving the page), which the pane dismisses.
197pub fn dialog_dismissed(page_url: &str, kind: &str, message: &str) -> String {
198    let what = match kind {
199        "confirm" => "a confirmation question",
200        "prompt" => "a question",
201        "beforeunload" => "a question about leaving the page",
202        _ => "a message box",
203    };
204    let said = shorten(message, 100);
205    if said.is_empty() {
206        format!("{} opened {what}. It was dismissed.", site_of(page_url))
207    } else {
208        format!("{} opened {what} (“{said}”). It was dismissed.", site_of(page_url))
209    }
210}
211
212/// The line for a window the pane could not show because the page opened it before the browser would let the pane see it.
213pub fn window_not_shown(opener_url: &str) -> String {
214    format!("{} opened a window that could not be shown, so it was closed.", site_of(opener_url))
215}
216
217/// The line for a window that went to another site while the person was not looking at it, said when they come back to it.
218pub fn window_changed_site(from: &str, to: &str) -> String {
219    format!("This window went from {from} to {to} while it was not shown.")
220}
221
222/// Google's page that says it will not sign in this browser. Matched on its address (host and path), never on what the page says.
223const GOOGLE_REFUSAL: (&str, &str) = ("accounts.google.com", "/v3/signin/rejected");
224
225/// A line for an address the pane knows a provider answers with a refusal to this browser, else none.
226pub fn provider_refusal(url: &str) -> Option<String> {
227    let u = url::Url::parse(url).ok()?;
228    if u.scheme() == "https" && u.host_str() == Some(GOOGLE_REFUSAL.0) && u.path() == GOOGLE_REFUSAL.1 {
229        return Some("Google refused to sign in with this browser. Other sign-in methods on the site, or a Microsoft or GitHub account, may work.".to_string());
230    }
231    None
232}
233
234/// Notices come at most this often: a page that raises a hundred dialogs is one line, not a hundred.
235const NOTICE_EVERY: Duration = Duration::from_secs(3);
236
237#[derive(Debug, Default)]
238pub struct NoticeLimiter {
239    last: Option<Instant>,
240}
241
242impl NoticeLimiter {
243    /// May a notice be shown at `now`?
244    pub fn allow(&mut self, now: Instant) -> bool {
245        if self.last.is_some_and(|t| now.saturating_duration_since(t) < NOTICE_EVERY) {
246            return false;
247        }
248        self.last = Some(now);
249        true
250    }
251}
252
253#[cfg(test)]
254mod tests {
255    use super::*;
256
257    fn pane() -> Windows {
258        Windows::starting("t0".into(), "s0".into())
259    }
260
261    fn open(w: &mut Windows, n: u32, opener: Option<WindowId>) -> WindowId {
262        w.add(format!("t{n}"), format!("s{n}"), opener).expect("room")
263    }
264
265    #[test]
266    fn a_pane_starts_with_one_window_which_is_shown_and_cannot_be_closed() {
267        let w = pane();
268        assert_eq!((w.len(), w.active()), (1, FIRST));
269        let m = w.message();
270        assert_eq!(m["t"], "windows");
271        assert_eq!(m["windows"][0]["closable"], false);
272        let mut w = pane();
273        assert_eq!(w.remove(FIRST), None);
274        assert_eq!(w.len(), 1);
275    }
276
277    #[test]
278    fn a_window_a_page_opens_is_shown_and_knows_who_opened_it() {
279        let mut w = pane();
280        let popup = open(&mut w, 1, Some(FIRST));
281        assert_eq!(w.active(), popup);
282        assert_eq!(w.get(popup).unwrap().opener, Some(FIRST));
283        assert_eq!(w.message()["windows"][1]["closable"], true);
284        assert_eq!(w.message()["active"], popup);
285    }
286
287    #[test]
288    fn a_page_cannot_open_windows_without_limit() {
289        let mut w = pane();
290        for n in 1..MAX_WINDOWS as u32 {
291            assert!(w.has_room());
292            open(&mut w, n, Some(FIRST));
293        }
294        assert_eq!(w.len(), MAX_WINDOWS);
295        assert!(!w.has_room());
296        assert_eq!(w.add("tx".into(), "sx".into(), Some(FIRST)), None);
297        assert_eq!(w.len(), MAX_WINDOWS);
298    }
299
300    #[test]
301    fn when_the_shown_window_ends_the_one_that_opened_it_is_shown_again() {
302        let mut w = pane();
303        let a = open(&mut w, 1, Some(FIRST));
304        let b = open(&mut w, 2, Some(a));
305        assert_eq!(w.remove(b), Some(Removed { was_active: true, now_active: a }));
306        assert_eq!(w.remove(a), Some(Removed { was_active: true, now_active: FIRST }));
307        assert_eq!(w.active(), FIRST);
308    }
309
310    #[test]
311    fn a_window_that_ends_while_not_shown_changes_nothing_on_screen() {
312        let mut w = pane();
313        let a = open(&mut w, 1, Some(FIRST));
314        let b = open(&mut w, 2, Some(FIRST));
315        assert_eq!(w.active(), b);
316        assert_eq!(w.remove(a), Some(Removed { was_active: false, now_active: b }));
317        assert_eq!(w.remove(a), None, "once");
318    }
319
320    #[test]
321    fn windows_a_closed_window_opened_go_back_to_its_opener() {
322        let mut w = pane();
323        let a = open(&mut w, 1, Some(FIRST));
324        let b = open(&mut w, 2, Some(a));
325        w.remove(a);
326        assert_eq!(w.get(b).unwrap().opener, Some(FIRST));
327        assert_eq!(w.remove(b), Some(Removed { was_active: true, now_active: FIRST }));
328    }
329
330    #[test]
331    fn the_person_can_show_any_window_and_a_window_that_is_not_there_is_refused() {
332        let mut w = pane();
333        let a = open(&mut w, 1, Some(FIRST));
334        assert!(w.focus(FIRST));
335        assert_eq!(w.active(), FIRST);
336        assert!(w.focus(a));
337        assert!(!w.focus(99));
338        assert_eq!(w.active(), a);
339    }
340
341    #[test]
342    fn windows_are_found_by_the_browsers_ids_and_a_closed_ids_number_is_not_reused() {
343        let mut w = pane();
344        let a = open(&mut w, 1, Some(FIRST));
345        assert_eq!(w.by_target("t1"), Some(a));
346        assert_eq!(w.by_session("s1"), Some(a));
347        assert_eq!(w.by_target("nope"), None);
348        w.remove(a);
349        let b = open(&mut w, 2, Some(FIRST));
350        assert_ne!(a, b, "a late message about the old window cannot land on the new one");
351    }
352
353    #[test]
354    fn an_address_is_kept_per_window_and_shown_in_the_message() {
355        let mut w = pane();
356        let a = open(&mut w, 1, Some(FIRST));
357        w.set_location(a, "https://accounts.example.com/login".into(), "Sign in".into());
358        let m = w.message();
359        assert_eq!(m["windows"][1]["url"], "https://accounts.example.com/login");
360        assert_eq!(m["windows"][1]["title"], "Sign in");
361        assert_eq!(m["windows"][0]["url"], "");
362    }
363
364    #[test]
365    fn a_line_names_the_site_and_says_what_was_done() {
366        assert_eq!(site_of("https://login.example.com/a?b=1"), "login.example.com");
367        assert_eq!(site_of("about:blank"), "a page");
368        assert_eq!(site_of(""), "a page");
369        let line = too_many_windows("https://spam.example/x");
370        assert!(line.starts_with("spam.example tried to open another window"), "{line}");
371        assert!(line.contains(&MAX_WINDOWS.to_string()));
372        let d = dialog_dismissed("https://a.example/", "confirm", "Leave   the\npage?");
373        assert_eq!(d, "a.example opened a confirmation question (“Leave the page?”). It was dismissed.");
374        assert_eq!(dialog_dismissed("https://a.example/", "alert", ""), "a.example opened a message box. It was dismissed.");
375        assert!(dialog_dismissed("https://a.example/", "alert", &"x".repeat(500)).contains('…'));
376        assert!(window_not_shown("https://a.example/").starts_with("a.example opened a window"));
377    }
378
379    #[test]
380    fn google_s_refusal_is_recognised_by_its_address_and_nothing_else_is() {
381        assert!(provider_refusal("https://accounts.google.com/v3/signin/rejected?dsh=x&flowName=GlifWebSignIn").is_some());
382        for other in [
383            "https://accounts.google.com/v3/signin/identifier",
384            "https://accounts.google.com/signin/rejected",
385            "http://accounts.google.com/v3/signin/rejected",
386            "https://evil.example/v3/signin/rejected",
387            "https://accounts.google.com.evil.example/v3/signin/rejected",
388            "about:blank",
389            "",
390        ] {
391            assert!(provider_refusal(other).is_none(), "{other}");
392        }
393        let line = provider_refusal("https://accounts.google.com/v3/signin/rejected").unwrap();
394        assert!(line.starts_with("Google refused"), "{line}");
395    }
396
397    #[test]
398    fn what_a_page_wrote_is_shown_with_nothing_hidden_in_it_and_after_the_site() {
399        // Control, bidi (right-to-left override and isolates), zero-width and tag characters are removed; the words stay.
400        let nasty = "Sign\u{202E}in\u{200B} to\u{2066} pay\u{FEFF}\u{7}\u{E0041} now\u{061C}\u{00AD}";
401        let line = dialog_dismissed("https://a.example/", "alert", nasty);
402        assert_eq!(line, "a.example opened a message box (“Signin to pay now”). It was dismissed.");
403        for c in line.chars() {
404            assert!(!is_hidden(c), "{:?} is still in the line", c);
405        }
406        // The site comes first, so the person reads who is speaking before what they say.
407        assert!(line.starts_with("a.example opened"), "{line}");
408        // A message of nothing but hidden characters says nothing, as an empty one does.
409        assert_eq!(dialog_dismissed("https://a.example/", "alert", "\u{200B}\u{202E}\n\t"), "a.example opened a message box. It was dismissed.");
410        // Text that looks like an address stays text: the line is words, with no markup for a link.
411        let link = dialog_dismissed("https://a.example/", "alert", "go to https://evil.example/login now");
412        assert!(link.contains("https://evil.example/login") && !link.contains('<') && !link.contains("]("), "{link}");
413    }
414
415    #[test]
416    fn a_window_that_changed_site_while_not_shown_is_told_once_on_return() {
417        let mut w = pane();
418        w.set_location(FIRST, "https://app.example/".into(), "App".into());
419        let a = open(&mut w, 1, Some(FIRST));
420        // The pop-up is shown, so the first window is the one not shown now.
421        w.set_location(a, "https://idp.example/auth".into(), "Sign in".into());
422        assert_eq!(w.take_moved(a), None, "the shown window changing site is not news");
423        w.set_location(FIRST, "https://app.example/other".into(), "App".into());
424        assert_eq!(w.take_moved(FIRST), None, "same site, nothing to say");
425        w.set_location(FIRST, "https://evil.example/".into(), "x".into());
426        w.set_location(FIRST, "https://evil.example/again".into(), "x".into());
427        assert_eq!(w.take_moved(FIRST), Some(("app.example".to_string(), "evil.example".to_string())));
428        assert_eq!(w.take_moved(FIRST), None, "said once");
429        // Back to the site the person last saw: nothing to say.
430        w.set_location(FIRST, "https://other.example/".into(), "x".into());
431        w.set_location(FIRST, "https://evil.example/".into(), "x".into());
432        w.take_moved(FIRST);
433        w.set_location(FIRST, "https://a2.example/".into(), "x".into());
434        w.set_location(FIRST, "https://evil.example/".into(), "x".into());
435        assert_eq!(w.take_moved(FIRST), None);
436        assert_eq!(window_changed_site("a.example", "b.example"), "This window went from a.example to b.example while it was not shown.");
437    }
438
439    #[test]
440    fn keys_are_held_for_half_a_second() {
441        assert_eq!(KEY_GAP, Duration::from_millis(500));
442    }
443
444    #[test]
445    fn notices_are_not_a_flood() {
446        let mut l = NoticeLimiter::default();
447        let t = Instant::now();
448        assert!(l.allow(t));
449        assert!(!l.allow(t + Duration::from_millis(500)));
450        assert!(!l.allow(t + Duration::from_millis(2900)));
451        assert!(l.allow(t + Duration::from_secs(3)));
452    }
453}