car-browser 0.51.0

Browser automation and perception pipeline for Common Agent Runtime
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
//! Multi-tab page registry — the tab data model behind
//! [`crate::chromium::ChromiumBackend`].
//!
//! [`TabRegistry`] is generic over the page handle type (`ChromiumBackend` uses
//! `chromiumoxide::Page`) so the open/close/switch/list state machine — including
//! the neighbor-activation and empty-state rules a tab strip depends on — is unit
//! testable with a cheap synthetic handle (see `tests` below), no live Chrome
//! required. The CDP-specific glue (creating a real page, closing it, refreshing
//! its live nav state) lives in `chromium.rs`, which owns a `TabRegistry<Page>`
//! and drives it.
//!
//! Every mutation publishes a [`TabsSnapshot`] on a `tokio::sync::watch` channel —
//! the change-notification seam a later task's `browser.view.*` RPC surface needs
//! to keep a tab strip live, and the one a screencast pump owner needs to notice
//! the active tab changed and move capture to the new page (see
//! `crate::screencast`): subscribe, `changed().await`, react. No wire protocol
//! here — that's the later task's job.

use std::fmt;

use tokio::sync::watch;

/// Opaque identifier for one open tab. Assigned by [`TabRegistry::open`] from
/// an internal monotonic counter — ids are never reused, so a stale id from a
/// closed tab can never later alias a different tab.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct TabId(u64);

impl fmt::Display for TabId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "tab-{}", self.0)
    }
}

/// One tab's navigation state, as shown in a tab strip.
#[derive(Debug, Clone, PartialEq)]
pub struct TabInfo {
    pub id: TabId,
    pub url: String,
    pub title: String,
    /// Whether this is the currently active tab — every existing
    /// `BrowserBackend` method acts on the active tab's page.
    pub active: bool,
    pub can_go_back: bool,
    pub can_go_forward: bool,
}

/// One tab lifecycle or navigation event, carried alongside each
/// [`TabsSnapshot`] published to subscribers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabEvent {
    Opened(TabId),
    /// A BACKGROUND tab closed.
    ///
    /// Closing the ACTIVE tab publishes [`TabEvent::ActiveChanged`] instead,
    /// with `previous: Some(id)` naming the tab that went — see that variant.
    /// One mutation carries exactly one event, because this rides a `watch`,
    /// whose `send` overwrites: two publishes from inside a single `close()`
    /// would leave the first provably unobservable (nothing can be scheduled
    /// between them — `close` is synchronous and holds the registry's write
    /// lock throughout), so this is a contract to state rather than a second
    /// event to emit.
    ///
    /// A consumer that needs "which tab closed" for either case reads
    /// `previous` on `ActiveChanged` and this id here; one that needs to tell a
    /// close from a plain switch cannot, and that is the residual — stated
    /// here rather than left to be discovered.
    Closed(TabId),
    /// The active tab changed — by an explicit switch, or because the
    /// previously active tab was closed and a neighbor took over (`current:
    /// None` if it was the last tab — the well-defined empty state).
    ActiveChanged {
        previous: Option<TabId>,
        current: Option<TabId>,
    },
    NavStateChanged(TabId),
}

/// The full tab list plus which one is active, published to subscribers on
/// every mutation. `tabs`/`active` are always the resulting state, not a
/// diff; `event` names what just happened.
#[derive(Debug, Clone, PartialEq)]
pub struct TabsSnapshot {
    pub tabs: Vec<TabInfo>,
    pub active: Option<TabId>,
    /// `None` only for the very first value published by [`TabRegistry::new`],
    /// before anything has happened yet.
    pub event: Option<TabEvent>,
}

/// Error from an operation that names a tab id.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum TabError {
    #[error("no tab with id {0}")]
    NotFound(TabId),
}

struct TabEntry<P> {
    id: TabId,
    page: P,
    url: String,
    title: String,
    can_go_back: bool,
    can_go_forward: bool,
}

/// Ordered collection of open tabs plus which one is active. Generic over the
/// page handle type `P` so the state machine is unit testable without a live
/// CDP connection — the `tests` module below drives it with a plain `&str`
/// standing in for `chromiumoxide::Page`.
pub struct TabRegistry<P> {
    entries: Vec<TabEntry<P>>,
    active: Option<TabId>,
    next_id: u64,
    tx: watch::Sender<TabsSnapshot>,
    /// Kept alive so `tx.send()` never fails for lack of a receiver — a
    /// `watch::Sender` silently drops the value it was sending (does not
    /// update its stored state) when the receiver count is zero, which would
    /// otherwise mean a `subscribe()` that arrives after the FIRST mutation
    /// but before any consumer had subscribed would see stale (pre-mutation)
    /// state. See `tests::publish_persists_even_with_no_external_subscriber`.
    _anchor_rx: watch::Receiver<TabsSnapshot>,
}

impl<P: Clone> TabRegistry<P> {
    /// A registry with no tabs open and no active tab — the well-defined
    /// empty state.
    pub fn new() -> (Self, watch::Receiver<TabsSnapshot>) {
        let (tx, rx) = watch::channel(TabsSnapshot {
            tabs: Vec::new(),
            active: None,
            event: None,
        });
        let anchor = rx.clone();
        (
            Self {
                entries: Vec::new(),
                active: None,
                next_id: 1,
                tx,
                _anchor_rx: anchor,
            },
            rx,
        )
    }

    /// A new receiver tuned to the current state — `borrow()` sees the
    /// latest snapshot immediately; `changed()` waits for the next one.
    pub fn subscribe(&self) -> watch::Receiver<TabsSnapshot> {
        self.tx.subscribe()
    }

    /// Open a new tab wrapping `page`, and make it active. Returns the new
    /// tab's id.
    pub fn open(&mut self, page: P, url: impl Into<String>, title: impl Into<String>) -> TabId {
        let id = TabId(self.next_id);
        self.next_id += 1;
        self.entries.push(TabEntry {
            id,
            page,
            url: url.into(),
            title: title.into(),
            can_go_back: false,
            can_go_forward: false,
        });
        self.active = Some(id);
        self.publish(TabEvent::Opened(id));
        id
    }

    /// Close `id`. Returns its page handle (so the caller can drive the
    /// CDP-level close) if it existed — `None` if there was no such tab, a
    /// safe no-op rather than an error.
    ///
    /// Closing the active tab activates a neighbor: prefer the tab that
    /// slides into the closed one's position (the tab that was to its
    /// right), falling back to the tab now at the end (previously to its
    /// left) if it was the rightmost tab, falling back to `None` if it was
    /// the last tab open — the well-defined empty state.
    pub fn close(&mut self, id: TabId) -> Option<P> {
        let idx = self.entries.iter().position(|e| e.id == id)?;
        let removed = self.entries.remove(idx);
        if self.active == Some(id) {
            let neighbor = self
                .entries
                .get(idx)
                .or_else(|| idx.checked_sub(1).and_then(|i| self.entries.get(i)))
                .map(|e| e.id);
            self.active = neighbor;
            self.publish(TabEvent::ActiveChanged {
                previous: Some(id),
                current: neighbor,
            });
        } else {
            self.publish(TabEvent::Closed(id));
        }
        Some(removed.page)
    }

    /// Close every open tab. Returns their page handles in closing order, so
    /// the caller can drive a CDP-level close for each. Equivalent to
    /// calling [`Self::close`] on every currently-open id.
    pub fn close_all(&mut self) -> Vec<P> {
        let ids: Vec<TabId> = self.entries.iter().map(|e| e.id).collect();
        ids.into_iter().filter_map(|id| self.close(id)).collect()
    }

    /// Make `id` the active tab. Errors if no tab has that id. A no-op
    /// (still `Ok`, no event published) if `id` is already active.
    pub fn switch(&mut self, id: TabId) -> Result<(), TabError> {
        if !self.entries.iter().any(|e| e.id == id) {
            return Err(TabError::NotFound(id));
        }
        if self.active == Some(id) {
            return Ok(());
        }
        let previous = self.active;
        self.active = Some(id);
        self.publish(TabEvent::ActiveChanged {
            previous,
            current: Some(id),
        });
        Ok(())
    }

    /// The active tab's id, if any (`None` in the empty state).
    pub fn active_id(&self) -> Option<TabId> {
        self.active
    }

    /// The active tab's cached URL, if any. Used to keep a scalar
    /// "last known URL" cache in sync with whichever tab is active, without
    /// a live CDP round trip.
    pub fn active_url(&self) -> Option<String> {
        self.active
            .and_then(|id| self.entries.iter().find(|e| e.id == id))
            .map(|e| e.url.clone())
    }

    /// The active tab's page handle, if any.
    pub fn active_page(&self) -> Option<P> {
        self.active.and_then(|id| self.page(id))
    }

    /// `id`'s page handle, if it's an open tab.
    pub fn page(&self, id: TabId) -> Option<P> {
        self.entries
            .iter()
            .find(|e| e.id == id)
            .map(|e| e.page.clone())
    }

    /// Every open tab's id + page handle, in tab-strip order. Used to drive
    /// a live nav-state refresh across ALL tabs, not just the active one — a
    /// background tab can navigate on its own (a clicked link, a JS
    /// redirect) without ever going through `ChromiumBackend::navigate`.
    pub fn pages(&self) -> Vec<(TabId, P)> {
        self.entries
            .iter()
            .map(|e| (e.id, e.page.clone()))
            .collect()
    }

    /// Current tab list in strip order, each flagged with whether it's the
    /// active one.
    pub fn list(&self) -> Vec<TabInfo> {
        self.entries
            .iter()
            .map(|e| TabInfo {
                id: e.id,
                url: e.url.clone(),
                title: e.title.clone(),
                active: self.active == Some(e.id),
                can_go_back: e.can_go_back,
                can_go_forward: e.can_go_forward,
            })
            .collect()
    }

    /// Update `id`'s cached nav state. A no-op (including no published
    /// event) if none of the fields actually changed, or if `id` doesn't
    /// exist — keeps the watch channel free of churn from a caller that
    /// refreshes on every poll regardless of whether anything actually
    /// moved (see `ChromiumBackend::list_tabs`).
    pub fn update_nav_state(
        &mut self,
        id: TabId,
        url: impl Into<String>,
        title: impl Into<String>,
        can_go_back: bool,
        can_go_forward: bool,
    ) {
        let url = url.into();
        let title = title.into();
        let mut changed = false;
        if let Some(e) = self.entries.iter_mut().find(|e| e.id == id) {
            if e.url != url
                || e.title != title
                || e.can_go_back != can_go_back
                || e.can_go_forward != can_go_forward
            {
                e.url = url;
                e.title = title;
                e.can_go_back = can_go_back;
                e.can_go_forward = can_go_forward;
                changed = true;
            }
        }
        if changed {
            self.publish(TabEvent::NavStateChanged(id));
        }
    }

    fn publish(&self, event: TabEvent) {
        // `_anchor_rx` guarantees at least one receiver always exists, so
        // this send cannot fail for lack of a receiver — see its field doc.
        let _ = self.tx.send(TabsSnapshot {
            tabs: self.list(),
            active: self.active,
            event: Some(event),
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// A dummy page handle standing in for `chromiumoxide::Page` — cheap,
    /// `Clone`, and carries an identifying label so assertions can tell
    /// which tab's handle came back.
    type FakePage = &'static str;

    fn registry() -> (TabRegistry<FakePage>, watch::Receiver<TabsSnapshot>) {
        TabRegistry::new()
    }

    #[test]
    fn open_adds_a_tab_and_makes_it_active() {
        let (mut reg, _rx) = registry();
        let id = reg.open("page-a", "http://a", "A");
        assert_eq!(reg.active_id(), Some(id));
        let tabs = reg.list();
        assert_eq!(tabs.len(), 1);
        assert!(tabs[0].active);
        assert_eq!(tabs[0].url, "http://a");
        assert_eq!(tabs[0].title, "A");
        assert!(!tabs[0].can_go_back);
        assert!(!tabs[0].can_go_forward);
    }

    #[test]
    fn open_twice_makes_the_second_active_and_keeps_the_first() {
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        let second = reg.open("page-b", "http://b", "B");
        assert_eq!(reg.active_id(), Some(second));
        let tabs = reg.list();
        assert_eq!(tabs.len(), 2);
        assert_eq!(tabs[0].id, first);
        assert!(!tabs[0].active);
        assert_eq!(tabs[1].id, second);
        assert!(tabs[1].active);
    }

    #[test]
    fn active_page_routes_to_whichever_tab_is_active() {
        // This is the mechanism `ChromiumBackend::get_page()` — and through
        // it, every existing single-page BrowserBackend method — relies on
        // to "operate on the ACTIVE page" once more than one tab exists.
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        assert_eq!(reg.active_page(), Some("page-a"));

        let second = reg.open("page-b", "http://b", "B");
        assert_eq!(reg.active_page(), Some("page-b"));

        reg.switch(first).unwrap();
        assert_eq!(reg.active_page(), Some("page-a"));

        // Sanity: `second`'s handle is still resolvable directly by id even
        // while it isn't active.
        assert_eq!(reg.page(second), Some("page-b"));
    }

    #[test]
    fn close_non_active_tab_leaves_active_unchanged() {
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        let second = reg.open("page-b", "http://b", "B");
        assert_eq!(reg.active_id(), Some(second));

        let closed_page = reg.close(first);
        assert_eq!(closed_page, Some("page-a"));
        assert_eq!(
            reg.active_id(),
            Some(second),
            "closing a background tab must not move focus"
        );
        assert_eq!(reg.list().len(), 1);
    }

    #[test]
    fn close_active_tab_activates_the_right_neighbor() {
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        let second = reg.open("page-b", "http://b", "B");
        let third = reg.open("page-c", "http://c", "C");
        reg.switch(second).unwrap();
        assert_eq!(reg.active_id(), Some(second));

        reg.close(second);
        assert_eq!(
            reg.active_id(),
            Some(third),
            "closing the active middle tab should activate its right neighbor"
        );
        let ids: Vec<TabId> = reg.list().iter().map(|t| t.id).collect();
        assert_eq!(ids, vec![first, third]);
    }

    #[test]
    fn close_active_rightmost_tab_falls_back_to_left_neighbor() {
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        let second = reg.open("page-b", "http://b", "B");
        assert_eq!(reg.active_id(), Some(second));

        reg.close(second);
        assert_eq!(
            reg.active_id(),
            Some(first),
            "closing the rightmost active tab should fall back to the left neighbor"
        );
    }

    #[test]
    fn close_last_tab_leaves_the_empty_state() {
        let (mut reg, _rx) = registry();
        let only = reg.open("page-a", "http://a", "A");

        let page = reg.close(only);
        assert_eq!(page, Some("page-a"));
        assert_eq!(reg.active_id(), None);
        assert!(reg.list().is_empty());
        assert_eq!(
            reg.active_page(),
            None,
            "no dangling handle in the empty state"
        );
    }

    #[test]
    fn close_unknown_id_is_a_safe_noop() {
        let (mut reg, _rx) = registry();
        let real = reg.open("page-a", "http://a", "A");
        let bogus = TabId(9999);

        assert_eq!(reg.close(bogus), None);
        assert_eq!(
            reg.active_id(),
            Some(real),
            "closing a bogus id must not disturb state"
        );
        assert_eq!(reg.list().len(), 1);
    }

    #[test]
    fn close_all_closes_every_tab_and_returns_their_pages() {
        let (mut reg, _rx) = registry();
        reg.open("page-a", "http://a", "A");
        reg.open("page-b", "http://b", "B");
        reg.open("page-c", "http://c", "C");

        let mut closed = reg.close_all();
        closed.sort();
        assert_eq!(closed, vec!["page-a", "page-b", "page-c"]);
        assert!(reg.list().is_empty());
        assert_eq!(reg.active_id(), None);
    }

    #[test]
    fn switch_to_existing_tab_changes_active() {
        let (mut reg, _rx) = registry();
        let first = reg.open("page-a", "http://a", "A");
        let second = reg.open("page-b", "http://b", "B");
        assert_eq!(reg.active_id(), Some(second));

        reg.switch(first).unwrap();
        assert_eq!(reg.active_id(), Some(first));
        assert!(reg.list()[0].active);
        assert!(!reg.list()[1].active);
    }

    #[test]
    fn switch_to_unknown_id_errors() {
        let (mut reg, _rx) = registry();
        let real = reg.open("page-a", "http://a", "A");
        let bogus = TabId(9999);

        let err = reg.switch(bogus).unwrap_err();
        assert_eq!(err, TabError::NotFound(bogus));
        assert_eq!(
            reg.active_id(),
            Some(real),
            "a failed switch must not change active"
        );
    }

    #[test]
    fn switch_to_already_active_tab_is_a_noop_ok() {
        let (mut reg, mut rx) = registry();
        let only = reg.open("page-a", "http://a", "A");
        rx.mark_unchanged();

        reg.switch(only).unwrap();
        assert_eq!(reg.active_id(), Some(only));
        assert!(
            !rx.has_changed().unwrap(),
            "switching to the already-active tab must not publish a new snapshot"
        );
    }

    #[test]
    fn update_nav_state_updates_fields_and_is_reflected_in_list() {
        let (mut reg, _rx) = registry();
        let id = reg.open("page-a", "about:blank", "");

        reg.update_nav_state(id, "http://a/2", "Page A", true, false);

        let tab = &reg.list()[0];
        assert_eq!(tab.url, "http://a/2");
        assert_eq!(tab.title, "Page A");
        assert!(tab.can_go_back);
        assert!(!tab.can_go_forward);
    }

    #[test]
    fn update_nav_state_is_a_noop_when_nothing_changed() {
        let (mut reg, mut rx) = registry();
        let id = reg.open("page-a", "http://a", "A");
        rx.mark_unchanged();

        // Same values as at open() time.
        reg.update_nav_state(id, "http://a", "A", false, false);

        assert!(
            !rx.has_changed().unwrap(),
            "re-asserting identical nav state must not publish (avoids polling churn)"
        );
    }

    #[tokio::test]
    async fn subscribe_sees_open_close_switch_events_in_order() {
        let (mut reg, _initial_rx) = registry();
        let mut rx = reg.subscribe();
        rx.mark_unchanged();

        let first = reg.open("page-a", "http://a", "A");
        rx.changed().await.unwrap();
        assert_eq!(rx.borrow().event, Some(TabEvent::Opened(first)));

        let second = reg.open("page-b", "http://b", "B");
        rx.changed().await.unwrap();
        assert_eq!(rx.borrow().event, Some(TabEvent::Opened(second)));

        reg.switch(first).unwrap();
        rx.changed().await.unwrap();
        assert_eq!(
            rx.borrow().event,
            Some(TabEvent::ActiveChanged {
                previous: Some(second),
                current: Some(first)
            })
        );

        // Closing the active tab (`first`) with one neighbor left (`second`)
        // activates it.
        reg.close(first);
        rx.changed().await.unwrap();
        assert_eq!(
            rx.borrow().event,
            Some(TabEvent::ActiveChanged {
                previous: Some(first),
                current: Some(second)
            })
        );
    }

    #[test]
    fn publish_persists_even_with_no_external_subscriber() {
        // Regression test for the `_anchor_rx` field: without it, a
        // `watch::Sender::send()` with a receiver count of zero silently
        // drops the value (does not update the channel's stored state)
        // rather than merely failing to notify. Dropping the constructor's
        // receiver here simulates "nobody subscribed yet" — a real
        // ChromiumBackend discards it too, since `open()` at launch happens
        // before any caller has had a chance to call `subscribe_tabs()`.
        let (mut reg, initial_rx) = registry();
        drop(initial_rx);

        let id = reg.open("page-a", "http://a", "A");

        // A subscriber that arrives AFTER the mutation must still see it.
        let late_rx = reg.subscribe();
        let snapshot = late_rx.borrow();
        assert_eq!(snapshot.active, Some(id));
        assert_eq!(snapshot.tabs.len(), 1);
        assert_eq!(snapshot.event, Some(TabEvent::Opened(id)));
    }

    #[test]
    fn tab_id_display_is_stable_and_distinguishable() {
        let (mut reg, _rx) = registry();
        let a = reg.open("page-a", "http://a", "A");
        let b = reg.open("page-b", "http://b", "B");
        assert_ne!(a.to_string(), b.to_string());
    }

    #[test]
    fn closed_tab_ids_are_never_reused() {
        let (mut reg, _rx) = registry();
        let closed = reg.open("page-a", "http://a", "A");
        assert_eq!(reg.close(closed), Some("page-a"));

        let reopened = reg.open("page-b", "http://b", "B");

        assert_ne!(
            reopened, closed,
            "a stale tab id must never alias a new tab"
        );
        assert!(reopened > closed, "tab ids come from a monotonic counter");
    }
}