Skip to main content

agentmux_srv/server/streamed_browser/
popups.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Who owns the pages of the browser. The browser tells everyone about every new page and every page that ends. Each pane claims
5//! the pages it shows, so a window opened by one of a pane's pages is told to that pane (which shows it). The rule is that no
6//! page exists in the browser that no pane lists: a new page nobody claims is closed as it appears, whether or not it has an
7//! opener. The pages srv makes for itself are known because srv made them, not because they lack an opener: a pane marks that it
8//! is making a page before it asks for it, and claims the page the moment it has its id; the browser's own first (blank) page is
9//! marked when the browser starts.
10
11use std::collections::HashMap;
12use std::sync::{Mutex, OnceLock};
13
14use serde_json::Value;
15use tokio::sync::mpsc::UnboundedSender;
16
17/// What a pane is told about its windows.
18#[derive(Debug, Clone, PartialEq, Eq)]
19pub enum TargetEvent {
20    /// A page of the pane opened a window (`target_id`); `opener_id` is the page that opened it.
21    Opened { target_id: String, opener_id: String, url: String },
22    /// A window of the pane ended (its page closed it, or it crashed).
23    Gone { target_id: String },
24}
25
26enum Owner {
27    /// A pane shows this page.
28    Pane(UnboundedSender<TargetEvent>),
29    /// srv made this page and no pane lists it: the browser's first, blank page, which keeps the browser from having none.
30    Srv,
31}
32
33#[derive(Default)]
34struct Registry {
35    owners: HashMap<String, Owner>,
36    /// How many pages srv is making for a pane right now (asked for, not yet claimed).
37    making: usize,
38    /// Pages that appeared with no opener while a page was being made: one of them is the page being made, which is claimed in a
39    /// moment; whatever is left when the last one is claimed is nobody's.
40    unclaimed: Vec<String>,
41}
42
43impl Registry {
44    /// The pages to close now: the unclaimed ones, once no page is being made.
45    fn strays(&mut self) -> Vec<String> {
46        if self.making > 0 {
47            return Vec::new();
48        }
49        std::mem::take(&mut self.unclaimed).into_iter().filter(|t| !self.owners.contains_key(t)).collect()
50    }
51}
52
53fn registry() -> &'static Mutex<Registry> {
54    static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
55    REGISTRY.get_or_init(|| Mutex::new(Registry::default()))
56}
57
58fn lock() -> std::sync::MutexGuard<'static, Registry> {
59    registry().lock().unwrap_or_else(|e| e.into_inner())
60}
61
62/// This pane shows `target_id`: windows it opens, and its end, are told to `tx`.
63pub fn claim(target_id: &str, tx: UnboundedSender<TargetEvent>) {
64    let mut r = lock();
65    r.unclaimed.retain(|t| t != target_id);
66    r.owners.insert(target_id.to_string(), Owner::Pane(tx));
67}
68
69/// srv made `target_id` for itself and no pane lists it (the browser's first page): it is not closed as unowned.
70pub fn claim_for_srv(target_id: &str) {
71    let mut r = lock();
72    r.unclaimed.retain(|t| t != target_id);
73    r.owners.insert(target_id.to_string(), Owner::Srv);
74}
75
76pub fn release(target_id: &str) {
77    lock().owners.remove(target_id);
78}
79
80/// The pages one pane has claimed, owned by the pane: they are all released when it is dropped, whether it ended through
81/// `Pane::finish`, by a panic or because its task was dropped before `finish` ran.
82#[derive(Default)]
83pub struct Claims(Vec<String>);
84
85impl Claims {
86    /// The pane shows `target_id` (as [`claim`]): released with the pane at the latest.
87    pub fn claim(&mut self, target_id: &str, tx: UnboundedSender<TargetEvent>) {
88        claim(target_id, tx);
89        if !self.0.iter().any(|t| t == target_id) {
90            self.0.push(target_id.to_string());
91        }
92    }
93
94    /// The pane no longer shows `target_id`.
95    pub fn release(&mut self, target_id: &str) {
96        release(target_id);
97        self.0.retain(|t| t != target_id);
98    }
99}
100
101impl Drop for Claims {
102    fn drop(&mut self) {
103        if self.0.is_empty() {
104            return;
105        }
106        let mut r = lock();
107        for t in self.0.drain(..) {
108            r.owners.remove(&t);
109        }
110    }
111}
112
113/// A pane is about to ask the browser for a page. Until it says it is done (`Making::done`), a new page that has no opener is
114/// held as maybe-the-one-being-made instead of being closed.
115pub struct Making(());
116
117pub fn making_a_page() -> Making {
118    lock().making += 1;
119    Making(())
120}
121
122impl Making {
123    /// The pane has the page's id and has claimed it (or the browser made none). The pages to close: any that appeared in
124    /// the meantime and nobody has claimed.
125    pub fn done(self) -> Vec<String> {
126        drop(self);
127        lock().strays()
128    }
129}
130
131impl Drop for Making {
132    fn drop(&mut self) {
133        let mut r = lock();
134        r.making = r.making.saturating_sub(1);
135    }
136}
137
138/// What to do with a browser-level event: the pages to close. A pane that owns a page is told what happened to it.
139pub fn route(method: &str, params: &Value) -> Vec<String> {
140    let mut r = lock();
141    let mut close = r.strays();
142    match method {
143        "Target.targetCreated" => {
144            let info = &params["targetInfo"];
145            if info["type"] != "page" {
146                return close;
147            }
148            let Some(target) = info["targetId"].as_str() else { return close };
149            if r.owners.contains_key(target) {
150                // srv's own page, or one a pane claimed before the browser's news of it came.
151                return close;
152            }
153            let opener = info.get("openerId").and_then(Value::as_str).filter(|o| !o.is_empty());
154            let url = info["url"].as_str().unwrap_or("").to_string();
155            match opener {
156                Some(opener) => match r.owners.get(opener) {
157                    Some(Owner::Pane(tx)) if tx.send(TargetEvent::Opened { target_id: target.to_string(), opener_id: opener.to_string(), url }).is_ok() => {}
158                    Some(Owner::Pane(_)) => {
159                        // The pane that owned the opener is gone.
160                        r.owners.remove(opener);
161                        close.push(target.to_string());
162                    }
163                    _ => close.push(target.to_string()),
164                },
165                // No opener: either a page srv is making (claimed in a moment), or nobody's.
166                None if r.making > 0 => r.unclaimed.push(target.to_string()),
167                None => close.push(target.to_string()),
168            }
169        }
170        "Target.targetDestroyed" => {
171            if let Some(target) = params["targetId"].as_str() {
172                r.unclaimed.retain(|t| t != target);
173                if let Some(Owner::Pane(tx)) = r.owners.get(target) {
174                    let _ = tx.send(TargetEvent::Gone { target_id: target.to_string() });
175                }
176            }
177        }
178        _ => {}
179    }
180    close
181}
182
183/// Takes a turn: the registry is the process's, so tests that use it one at a time.
184#[cfg(test)]
185pub(super) async fn serial() -> tokio::sync::MutexGuard<'static, ()> {
186    static TURN: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
187    TURN.lock().await
188}
189
190#[cfg(test)]
191mod tests {
192    use super::*;
193    use serde_json::json;
194    use tokio::sync::mpsc;
195
196    fn created(target: &str, opener: Option<&str>, kind: &str) -> Value {
197        let mut info = json!({ "targetId": target, "type": kind, "url": "https://idp.example/auth" });
198        if let Some(o) = opener {
199            info["openerId"] = json!(o);
200        }
201        json!({ "targetInfo": info })
202    }
203
204    fn only(closed: Vec<String>) -> Option<String> {
205        assert!(closed.len() <= 1, "{closed:?}");
206        closed.into_iter().next()
207    }
208
209    #[tokio::test]
210    async fn a_window_a_pane_s_page_opens_is_told_to_that_pane_and_is_not_closed() {
211        let _turn = serial().await;
212        let (tx, mut rx) = mpsc::unbounded_channel();
213        claim("t-owned-1", tx);
214        assert_eq!(route("Target.targetCreated", &created("t-pop-1", Some("t-owned-1"), "page")), Vec::<String>::new());
215        assert_eq!(rx.try_recv().unwrap(), TargetEvent::Opened { target_id: "t-pop-1".into(), opener_id: "t-owned-1".into(), url: "https://idp.example/auth".into() });
216        release("t-owned-1");
217    }
218
219    #[tokio::test]
220    async fn a_page_nobody_claims_is_closed_whether_or_not_it_has_an_opener() {
221        let _turn = serial().await;
222        // An opener that no pane owns.
223        assert_eq!(only(route("Target.targetCreated", &created("t-pop-2", Some("t-unowned"), "page"))).as_deref(), Some("t-pop-2"));
224        // No opener at all, with nothing being made: it is nobody's.
225        assert_eq!(only(route("Target.targetCreated", &created("t-new", None, "page"))).as_deref(), Some("t-new"));
226        // Not a page, or not news of a page: left alone.
227        assert!(route("Target.targetCreated", &created("t-w", Some("t-unowned"), "service_worker")).is_empty());
228        assert!(route("Target.targetCreated", &json!({})).is_empty());
229        assert!(route("Target.attachedToTarget", &json!({})).is_empty());
230    }
231
232    #[tokio::test]
233    async fn a_page_srv_is_making_is_not_closed_and_one_that_appears_beside_it_is() {
234        let _turn = serial().await;
235        let (tx, _rx) = mpsc::unbounded_channel();
236        let making = making_a_page();
237        // The browser's news of the page comes before the answer that gives its id.
238        assert!(route("Target.targetCreated", &created("t-own-6", None, "page")).is_empty(), "held, not closed: it may be the page being made");
239        assert!(route("Target.targetCreated", &created("t-stray-6", None, "page")).is_empty());
240        claim("t-own-6", tx);
241        // Once the pane has its page, what is left over is nobody's.
242        assert_eq!(making.done(), vec!["t-stray-6".to_string()]);
243        // And the claimed page stays: its own later news does not close it.
244        assert!(route("Target.targetCreated", &created("t-own-6", None, "page")).is_empty());
245        release("t-own-6");
246    }
247
248    #[tokio::test]
249    async fn a_page_that_no_answer_ever_claims_is_closed_when_the_making_ends() {
250        let _turn = serial().await;
251        let making = making_a_page();
252        route("Target.targetCreated", &created("t-lost-7", None, "page"));
253        // The pane never got an id (the browser refused, or the pane was dropped): nothing claims it.
254        drop(making);
255        assert_eq!(route("Target.targetDestroyed", &json!({ "targetId": "t-other" })), vec!["t-lost-7".to_string()], "the next news of the browser sweeps it");
256    }
257
258    #[tokio::test]
259    async fn the_page_srv_keeps_for_itself_is_not_closed_and_is_not_a_panes() {
260        let _turn = serial().await;
261        claim_for_srv("t-blank-8");
262        assert!(route("Target.targetCreated", &created("t-blank-8", None, "page")).is_empty());
263        // It opens nothing, but if it did, its window would be nobody's: srv's own page is not a pane.
264        assert_eq!(only(route("Target.targetCreated", &created("t-pop-8", Some("t-blank-8"), "page"))).as_deref(), Some("t-pop-8"));
265        release("t-blank-8");
266    }
267
268    #[tokio::test]
269    async fn a_pane_hears_only_of_its_own_windows() {
270        let _turn = serial().await;
271        let (a_tx, mut a_rx) = mpsc::unbounded_channel();
272        let (b_tx, mut b_rx) = mpsc::unbounded_channel();
273        claim("t-a-3", a_tx);
274        claim("t-b-3", b_tx);
275        route("Target.targetCreated", &created("t-pop-3", Some("t-b-3"), "page"));
276        assert!(a_rx.try_recv().is_err());
277        assert!(matches!(b_rx.try_recv(), Ok(TargetEvent::Opened { .. })));
278        route("Target.targetDestroyed", &json!({ "targetId": "t-a-3" }));
279        assert_eq!(a_rx.try_recv().unwrap(), TargetEvent::Gone { target_id: "t-a-3".into() });
280        assert!(b_rx.try_recv().is_err());
281        release("t-a-3");
282        release("t-b-3");
283    }
284
285    #[tokio::test]
286    async fn the_claims_of_a_pane_dropped_without_finishing_are_released() {
287        let _turn = serial().await;
288        let (tx, mut rx) = mpsc::unbounded_channel();
289        let mut claims = Claims::default();
290        claims.claim("t-held-6", tx.clone());
291        claims.claim("t-held-7", tx);
292        claims.release("t-held-7");
293        // While the pane lives its page is its own: a window it opens is told to it, not closed.
294        assert!(route("Target.targetCreated", &created("t-pop-6", Some("t-held-6"), "page")).is_empty());
295        assert!(matches!(rx.try_recv(), Ok(TargetEvent::Opened { .. })));
296        // Dropped with no finish (a panic, a task dropped): nothing of it is claimed, though its channel is still open.
297        drop(claims);
298        assert_eq!(only(route("Target.targetCreated", &created("t-pop-7", Some("t-held-6"), "page"))).as_deref(), Some("t-pop-7"));
299        assert!(rx.try_recv().is_err(), "a page of a dropped pane is still told its news");
300    }
301
302    #[tokio::test]
303    async fn a_window_whose_pane_has_gone_is_closed_and_the_claim_is_dropped() {
304        let _turn = serial().await;
305        let (tx, rx) = mpsc::unbounded_channel();
306        claim("t-gone-4", tx);
307        drop(rx);
308        assert_eq!(only(route("Target.targetCreated", &created("t-pop-4", Some("t-gone-4"), "page"))).as_deref(), Some("t-pop-4"));
309        assert_eq!(only(route("Target.targetCreated", &created("t-pop-5", Some("t-gone-4"), "page"))).as_deref(), Some("t-pop-5"));
310    }
311}