rho-coding-agent 3.12.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
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
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
//! A session's tabs: the browser context they live in, which one is
//! current, and each one's refs.
//!
//! The session's browser tools share one [`SessionTabs`]. Each call holds
//! the session's context for as long as it runs, so the browser does not
//! close under it, and lets go when it returns, so an idle session leaves
//! the browser free to close.

mod sizing;

use super::refs::{Refs, StaleRef};
use super::schema::NAVIGATION_LIMIT;
use super::text::TabLine;
use crate::browser::view::ViewTab;
use crate::browser::{SessionBrowser, VIEWPORT};
use rho_browser::cdp::dom::{ResolveNode, ScrollIntoViewIfNeeded};
use rho_browser::cdp::page::GetFrameTree;
use rho_browser::cdp::runtime::{
    CallArgument, CallFunctionOn, Evaluate, ExecutionContextId, ReleaseObject,
};
use rho_browser::cdp::target::{CloseTarget, GetTargets, TargetInfo};
use rho_browser::cdp::{page::CreateIsolatedWorld, Command};
use rho_browser::cdp::{BackendNodeId, BrowserContextId, TargetId};
use rho_browser::manager::Context;
use rho_browser::tab::{Dialogs, LoadError, Step, Tab, Viewport, Watch};
use rho_browser::CdpError;
use rho_sdk::tool::{ToolError, ToolErrorKind};
use serde_json::Value;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;
use std::time::Duration;

/// How many tabs a session may have open, a tripwire rather than a target.
/// Each heavy real page measured 23 to 153 MB of PSS in chrome-headless-shell
/// on Linux, so ten bound the worst case near 1.5 GB.
pub(super) const TAB_LIMIT: usize = 10;

/// Resolves after the page has drawn two frames, by when it has acted on an
/// input it was sent. A wheel scroll moved the page within 17 to 36 ms, and
/// this took 50. A click's handler had run, and a link's navigation had
/// started, within 2 to 15 ms, against 15 to 42 ms for this
/// (chrome-headless-shell 158, Linux).
const NEXT_FRAMES: &str =
    "new Promise(done => requestAnimationFrame(() => requestAnimationFrame(() => done(null))))";

/// How long one call to the browser may go unanswered before the tool gives
/// up on it. The slowest call the tools make, reading Wikipedia's 24,324-node
/// accessibility tree, took 481 ms (chrome-headless-shell 158, Linux).
pub(super) const CALL_LIMIT: Duration = Duration::from_secs(10);

/// The tabs of one session's browser context.
pub(super) struct SessionTabs {
    browser: SessionBrowser,
    tabs: tokio::sync::Mutex<Tabs>,
}

#[derive(Default)]
pub(super) struct Tabs {
    /// The browser context the tabs live in. A call that gets another one
    /// finds the tabs gone with the old one.
    context: Option<BrowserContextId>,
    open: Vec<OpenTab>,
    /// The tabs the session closed that the browser may still list for a
    /// moment: `Target.closeTarget` answers before the tab is gone.
    closing: Vec<TargetId>,
    current: Option<String>,
    /// The mouse button a person driving the browser holds down.
    pub(super) person_button: super::person::HeldButton,
    opened: usize,
    /// The tab list the model was last shown, so a call shows it again only
    /// when it changed.
    shown: Vec<TabLine>,
    /// How many times a person had taken the browser over when the
    /// session's last call held its tabs.
    takeovers: u64,
    /// The viewport the tabs render at.
    sizing: sizing::Sizing,
}

pub(super) struct OpenTab {
    pub(super) id: String,
    tab: Tab,
    pub(super) refs: Refs,
    /// The isolated world rho's own scripts run in, and the document it
    /// belongs to.
    world: Option<(String, ExecutionContextId)>,
    /// How many loads of the tab are under way, each held by a [`Loading`]:
    /// the tab shows loading until the last one ends.
    loads: Arc<AtomicUsize>,
    /// The viewport the tab was last asked to render at.
    size: Viewport,
}

/// What pages did to the session's tabs since the last look, as
/// [`Tabs::take_in`] found it.
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct PageTabs {
    /// The ids of the tabs pages opened that the session took in.
    pub(super) taken: Vec<String>,
    /// How many tabs pages opened the session closed, having no room for
    /// them.
    pub(super) refused: usize,
    /// The ids of the session's tabs that closed themselves, as a popup
    /// does with `window.close()`, which the session forgot.
    pub(super) gone: Vec<String>,
}

/// The pages among `listed` in `context` that are not `tracked`: tabs
/// pages there opened, which the session does not know yet.
fn opened_pages<'a>(
    listed: &'a [TargetInfo],
    context: &'a BrowserContextId,
    tracked: &'a [&TargetId],
) -> impl Iterator<Item = &'a TargetInfo> {
    listed.iter().filter(move |target| {
        target.kind == "page"
            && target.browser_context_id.as_ref() == Some(context)
            && !tracked.contains(&&target.target_id)
    })
}

/// A call's hold on the session's context and tabs.
pub(super) struct Held<'a> {
    pub(super) context: Context,
    pub(super) tabs: tokio::sync::MutexGuard<'a, Tabs>,
    /// Set when the browser closed since the session's last call, taking
    /// its tabs.
    pub(super) lost_tabs: bool,
    /// Set when a person drove the browser since the session's last call.
    pub(super) person_drove: bool,
    pub(super) browser: &'a SessionBrowser,
}

impl Held<'_> {
    /// Tells the session's clients its tabs as they are now, with their
    /// titles and URLs. A tab shown loading stays so: the load that showed
    /// it ends it.
    pub(super) async fn show_tabs(&self) {
        let lines = self.tabs.lines().await;
        let current = self.tabs.current().map(str::to_owned);
        let tabs = lines
            .into_iter()
            .zip(&self.tabs.open)
            .map(|(line, open)| ViewTab {
                id: line.id,
                target: open.tab.page().target_id().clone(),
                title: line.title,
                url: line.url,
                loading: false,
            })
            .collect::<Vec<_>>();
        self.browser.show_in(self.context.id(), |view| {
            let loading: Vec<String> = view
                .tabs
                .iter()
                .filter(|tab| tab.loading)
                .map(|tab| tab.id.clone())
                .collect();
            view.tabs = tabs
                .into_iter()
                .map(|tab: ViewTab| ViewTab {
                    loading: loading.contains(&tab.id),
                    ..tab
                })
                .collect();
            view.current = current;
        });
    }
}

/// Tells `browser`'s clients that tab `open` of `context` is loading,
/// `url` when it is a new one rather than the page again or a step through
/// its history, until the returned [`Loading`] drops, and any other load
/// of the tab with it.
pub(super) fn show_loading(
    browser: &SessionBrowser,
    context: &BrowserContextId,
    open: &OpenTab,
    url: Option<&str>,
) -> Loading {
    let mut counted = None;
    browser.show_in(context, |view| {
        // Under the view's lock, as the count's drop is.
        open.loads.fetch_add(1, Ordering::Relaxed);
        counted = Some(Arc::clone(&open.loads));
        match view.tabs.iter_mut().find(|tab| tab.id == open.id) {
            Some(tab) => {
                if let Some(url) = url {
                    url.clone_into(&mut tab.url);
                }
                tab.loading = true;
            }
            None => view.tabs.push(ViewTab {
                id: open.id.clone(),
                target: open.tab.page().target_id().clone(),
                title: String::new(),
                url: url.unwrap_or_default().to_owned(),
                loading: true,
            }),
        }
    });
    Loading {
        browser: browser.clone(),
        context: context.clone(),
        tab: open.id.clone(),
        loads: counted,
    }
}

/// A tab shown loading, until this drops: whatever ends its load, or the
/// call that started it being cancelled.
pub(super) struct Loading {
    browser: SessionBrowser,
    context: BrowserContextId,
    tab: String,
    /// The tab's count of loads, which this load is one of, unless the
    /// browser of `context` had closed when it started.
    loads: Option<Arc<AtomicUsize>>,
}

impl Drop for Loading {
    fn drop(&mut self) {
        let Some(loads) = &self.loads else {
            return;
        };
        self.browser.show_in(&self.context, |view| {
            if loads.fetch_sub(1, Ordering::Relaxed) > 1 {
                return;
            }
            if let Some(tab) = view.tabs.iter_mut().find(|tab| tab.id == self.tab) {
                tab.loading = false;
            }
        });
    }
}

impl SessionTabs {
    pub(super) fn browser(&self) -> &SessionBrowser {
        &self.browser
    }

    pub(super) fn new(browser: SessionBrowser) -> Self {
        Self {
            browser,
            tabs: tokio::sync::Mutex::default(),
        }
    }

    /// The session's context and tabs for an agent's call, starting the
    /// browser if it is not running, once no person drives it. A call that
    /// holds them when a person takes over finishes first.
    pub(super) async fn hold(&self) -> Result<Held<'_>, ToolError> {
        // Locked first, so calls get their contexts in the order they hold
        // the tabs, and an older context never replaces a newer one. A
        // person may take over while this call waits for the lock, so the
        // agent's turn is checked again once it has it.
        let (tabs, takeovers) = loop {
            self.browser.agent_turn().await;
            let tabs = self.tabs.lock().await;
            if let Some(takeovers) = self.browser.agent_drives() {
                break (tabs, takeovers);
            }
        };
        let mut held = self.held(tabs, Some(takeovers)).await?;
        // The agent acts at its own size, whatever a person who drove
        // before, or takes over while this call runs, views the tabs at.
        held.tabs.fit(VIEWPORT).await;
        Ok(held)
    }

    /// The session's context and tabs, starting the browser if it is not
    /// running, whoever drives it.
    pub(super) async fn hold_now(&self) -> Result<Held<'_>, ToolError> {
        // Locked first, as in `hold`.
        let tabs = self.tabs.lock().await;
        let mut held = self.held(tabs, /*takeovers*/ None).await?;
        held.tabs.fit(self.browser.viewport()).await;
        Ok(held)
    }

    /// `tabs` with the session's context, which it gets once it holds them.
    /// An agent's call passes the `takeovers` it saw.
    async fn held<'a>(
        &'a self,
        mut tabs: tokio::sync::MutexGuard<'a, Tabs>,
        takeovers: Option<u64>,
    ) -> Result<Held<'a>, ToolError> {
        let context = self.browser.context().await.map_err(execution)?;
        // Recorded only once the call can tell the model, so a call that
        // could not start the browser leaves the notice to the next one.
        let person_drove = takeovers.is_some_and(|takeovers| {
            std::mem::replace(&mut tabs.takeovers, takeovers) != takeovers
        });
        // A new context has none of the tabs the session had, which went
        // with the browser that closed, or with the context the session
        // released.
        let lost_tabs = tabs.follow(context.id());
        Ok(Held {
            context,
            tabs,
            lost_tabs,
            person_drove,
            browser: &self.browser,
        })
    }

    /// Closes the session's context and its tabs.
    pub(super) async fn release(&self) {
        self.tabs.lock().await.forget();
        self.browser.release().await;
        self.browser.show(|view| {
            view.tabs.clear();
            view.current = None;
        });
    }
}

impl Tabs {
    /// Moves to `context`, forgetting the tabs of any other, and returns
    /// whether there were any.
    fn follow(&mut self, context: &BrowserContextId) -> bool {
        if self.context.as_ref() == Some(context) {
            return false;
        }
        let had_tabs = self.forget();
        self.context = Some(context.clone());
        had_tabs
    }

    /// Forgets every tab, returning whether there were any. Numbering goes
    /// on while the session stays loaded, so a new tab does not take the id
    /// of one the model saw in this load of the session.
    fn forget(&mut self) -> bool {
        let had_tabs = !self.open.is_empty();
        *self = Self {
            opened: self.opened,
            takeovers: self.takeovers,
            sizing: self.sizing,
            ..Self::default()
        };
        had_tabs
    }

    /// The tab `id` names, or the current one.
    pub(super) fn get(&mut self, id: Option<&str>) -> Result<&mut OpenTab, ToolError> {
        let id = match id.or(self.current.as_deref()) {
            Some(id) => id.to_owned(),
            None => return Err(execution("No tab is open. Open a page with navigate.")),
        };
        let open = self.ids();
        self.open
            .iter_mut()
            .find(|tab| tab.id == id)
            .ok_or_else(|| {
                ToolError::new(
                    ToolErrorKind::InvalidArguments,
                    format!("There is no tab {id}. Open tabs: {open}."),
                )
            })
    }

    /// Opens a tab in `context` and makes it current.
    pub(super) async fn open(&mut self, context: &Context) -> Result<&mut OpenTab, ToolError> {
        if self.open.len() >= TAB_LIMIT {
            return Err(execution(format!(
                "This session has {TAB_LIMIT} tabs open, the most it may; close one with close_tab first."
            )));
        }
        let size = self.sizing.viewport();
        let tab = answer(Tab::open(context.connection(), context.id(), size))
            .await
            .map_err(|error| execution(format!("could not open a tab: {error}")))?;
        self.opened += 1;
        let id = format!("tab-{}", self.opened);
        self.current = Some(id.clone());
        self.open.push(OpenTab::new(id, tab, size));
        Ok(self.open.last_mut().expect("just pushed"))
    }

    /// Takes in the tabs pages in `context` opened since the last look, such
    /// as by a link with `target="_blank"`, a middle click or
    /// `window.open`, while the session has room for them, and closes the
    /// rest. Forgets the session's tabs that closed themselves; the last
    /// tab opened becomes current if the current one did. Otherwise the
    /// current tab stays current.
    pub(super) async fn take_in(&mut self, context: &Context) -> PageTabs {
        let mut found = PageTabs::default();
        // Nothing to take in is all a failed look can tell.
        let Ok(targets) = answer(context.connection().call(&GetTargets {})).await else {
            return found;
        };
        let listed = targets.target_infos;
        let is_listed = |id: &TargetId| listed.iter().any(|target| target.target_id == *id);
        self.closing.retain(|closing| is_listed(closing));
        let (kept, gone) = std::mem::take(&mut self.open)
            .into_iter()
            .partition(|open| is_listed(open.tab.page().target_id()));
        self.open = kept;
        found.gone = gone.into_iter().map(|open: OpenTab| open.id).collect();
        if self
            .current
            .as_ref()
            .is_some_and(|current| found.gone.contains(current))
        {
            self.current = self.open.last().map(|tab| tab.id.clone());
        }
        let tracked: Vec<&TargetId> = self
            .open
            .iter()
            .map(|open| open.tab.page().target_id())
            .chain(&self.closing)
            .collect();
        let new: Vec<TargetId> = opened_pages(&listed, context.id(), &tracked)
            .map(|target| target.target_id.clone())
            .collect();
        for target in new {
            if self.open.len() >= TAB_LIMIT {
                self.close_target(context, target).await;
                found.refused += 1;
                continue;
            }
            let size = self.sizing.viewport();
            match answer(Tab::adopt(context.connection(), &target, size)).await {
                Ok(tab) => {
                    self.opened += 1;
                    let id = format!("tab-{}", self.opened);
                    self.open.push(OpenTab::new(id.clone(), tab, size));
                    found.taken.push(id);
                }
                // Closed, so that a tab the session could not take in stays
                // neither open outside the limit nor tried again on every
                // look. One the page closed before it could be taken in is
                // gone already.
                Err(_) => self.close_target(context, target).await,
            }
        }
        found
    }

    /// Closes a tab the session does not track, remembering it until the
    /// browser stops listing it.
    async fn close_target(&mut self, context: &Context, target: TargetId) {
        // A tab the page closed itself is closed all the same.
        let _ = answer(context.connection().call(&CloseTarget {
            target_id: target.clone(),
        }))
        .await;
        self.closing.push(target);
    }

    /// Makes tab `id` current.
    pub(super) fn switch(&mut self, id: &str) -> Result<(), ToolError> {
        self.get(Some(id))?;
        self.current = Some(id.to_owned());
        Ok(())
    }

    /// Closes tab `id`. The last tab opened becomes current if it was.
    pub(super) async fn close(&mut self, id: &str) -> Result<(), ToolError> {
        self.get(Some(id))?;
        let index = self
            .open
            .iter()
            .position(|tab| tab.id == id)
            .expect("found above");
        let closed = self.open.remove(index);
        if self.current.as_deref() == Some(id) {
            self.current = self.open.last().map(|tab| tab.id.clone());
        }
        // A tab the browser already closed is closed all the same.
        let _ = answer(closed.tab.close()).await;
        self.closing.push(closed.tab.page().target_id().clone());
        Ok(())
    }

    pub(super) fn current(&self) -> Option<&str> {
        self.current.as_deref()
    }

    /// Whether the session has tab `id`.
    pub(super) fn has(&self, id: &str) -> bool {
        self.open.iter().any(|tab| tab.id == id)
    }

    /// The open tabs with their titles and URLs now, in the order of
    /// `open`.
    pub(super) async fn lines(&self) -> Vec<TabLine> {
        let mut lines = Vec::with_capacity(self.open.len());
        for open in &self.open {
            let (title, url) = match answer(open.tab.info()).await {
                Ok(info) => (info.title, info.url),
                Err(_) => (String::new(), String::new()),
            };
            lines.push(TabLine {
                id: open.id.clone(),
                title,
                url,
            });
        }
        lines
    }

    /// Records `lines` as the tab list the model has seen, returning
    /// whether it differs from the one before.
    pub(super) fn note_shown(&mut self, lines: &[TabLine]) -> bool {
        let changed = self.shown != lines;
        if changed {
            self.shown = lines.to_vec();
        }
        changed
    }

    fn ids(&self) -> String {
        let ids: Vec<&str> = self.open.iter().map(|tab| tab.id.as_str()).collect();
        if ids.is_empty() {
            "none".to_owned()
        } else {
            ids.join(", ")
        }
    }
}

impl OpenTab {
    /// `tab`, which renders at `size`, as tab `id`, with no refs yet.
    pub(super) fn new(id: String, tab: Tab, size: Viewport) -> Self {
        Self {
            id,
            tab,
            refs: Refs::default(),
            world: None,
            loads: Arc::default(),
            size,
        }
    }

    /// The loader of the tab's current document, after which its refs
    /// follow.
    pub(super) async fn document(&mut self) -> Result<String, ToolError> {
        let loader = self
            .call(&GetFrameTree {})
            .await?
            .frame_tree
            .frame
            .loader_id;
        self.refs.follow(&loader);
        Ok(loader)
    }

    /// The node `name`, a ref such as `ref_3`, names in the tab's current
    /// document.
    pub(super) async fn node<'a>(&mut self, name: &'a str) -> Result<Node<'a>, ToolError> {
        let loader = self.document().await?;
        let id = self
            .refs
            .node(name, &loader)
            .map_err(|error| execution(error.to_string()))?;
        Ok(Node { id, name })
    }

    /// Resolves after the page has drawn two frames since now.
    pub(super) async fn drawn(&mut self) -> Result<(), ToolError> {
        self.evaluate(NEXT_FRAMES).await.map(drop)
    }

    /// Starts watching for a navigation an input sets off.
    pub(super) fn watch(&self) -> Watch {
        self.tab.watch()
    }

    /// The browser's tab.
    pub(super) fn tab(&self) -> &Tab {
        &self.tab
    }

    /// Loads `url`; [`NAVIGATION_LIMIT`] bounds it.
    pub(super) async fn load(&self, url: &str) -> Result<(), LoadError> {
        self.tab.load(url, NAVIGATION_LIMIT).await
    }

    /// Takes `step` through the tab's history; [`NAVIGATION_LIMIT`] bounds it.
    pub(super) async fn go(&self, step: Step) -> Result<(), LoadError> {
        self.tab.go(step, NAVIGATION_LIMIT).await
    }

    /// The tab's URL, or empty if the browser did not say.
    pub(super) async fn url(&self) -> String {
        answer(self.tab.info())
            .await
            .map(|info| info.url)
            .unwrap_or_default()
    }

    /// The dialogs the page opened, and the tab dismissed, since the last
    /// call.
    pub(super) fn take_dialogs(&self) -> Dialogs {
        self.tab.take_dialogs()
    }

    /// Scrolls `node` into view.
    pub(super) async fn scroll_into_view(&self, node: &Node<'_>) -> Result<(), ToolError> {
        let command = ScrollIntoViewIfNeeded {
            backend_node_id: node.id,
        };
        match self.on_node(&command).await? {
            Some(_) => Ok(()),
            None => Err(node.stale()),
        }
    }

    /// Sends `command`, about a node, to the tab: `None` when the browser
    /// refuses it, as for a node the page removed, or for a node it does
    /// not draw when asked for its box.
    pub(super) async fn on_node<C: Command>(
        &self,
        command: &C,
    ) -> Result<Option<C::Response>, ToolError> {
        match within_limit(self.tab.page().call(command)).await {
            Ok(response) => Ok(Some(response)),
            Err(CallError::Browser(CdpError::Protocol { .. })) => Ok(None),
            Err(error) => Err(execution(format!("the browser could not do that: {error}"))),
        }
    }

    /// Sends `command` to the tab, failing when it goes unanswered for
    /// [`CALL_LIMIT`].
    pub(super) async fn call<C: Command>(&self, command: &C) -> Result<C::Response, ToolError> {
        answer(self.tab.page().call(command))
            .await
            .map_err(|error| execution(format!("the browser could not do that: {error}")))
    }

    /// rho's isolated world of the tab's document, where the page's own
    /// scripts cannot change what rho's scripts see.
    async fn world(&mut self) -> Result<ExecutionContextId, ToolError> {
        let loader = self.document().await?;
        if let Some((world_loader, world)) = &self.world {
            if *world_loader == loader {
                return Ok(*world);
            }
        }
        let world = self
            .call(&CreateIsolatedWorld {
                frame_id: self.tab.frame().clone(),
                world_name: "rho".to_owned(),
            })
            .await?
            .execution_context_id;
        self.world = Some((loader, world));
        Ok(world)
    }

    /// Runs `expression` in rho's isolated world and returns its value.
    pub(super) async fn evaluate(&mut self, expression: &str) -> Result<Value, ToolError> {
        let world = self.world().await?;
        let evaluated = self
            .call(&Evaluate {
                expression: expression.to_owned(),
                context_id: Some(world),
                return_by_value: true,
                await_promise: true,
                timeout: None,
            })
            .await?;
        if let Some(exception) = evaluated.exception_details {
            return Err(execution(format!(
                "the browser could not read the page: {}",
                exception.text
            )));
        }
        Ok(evaluated.result.value.unwrap_or(Value::Null))
    }

    /// Calls `function` in rho's isolated world with `node` as `this`, and
    /// returns its value.
    pub(super) async fn call_on(
        &mut self,
        node: &Node<'_>,
        function: &str,
        arguments: Vec<Value>,
    ) -> Result<Value, ToolError> {
        let world = self.world().await?;
        let resolve = ResolveNode {
            backend_node_id: node.id,
            execution_context_id: world,
        };
        let object = self
            .on_node(&resolve)
            .await?
            .and_then(|resolved| resolved.object.object_id)
            .ok_or_else(|| node.stale())?;
        let called = self
            .call(&CallFunctionOn {
                function_declaration: function.to_owned(),
                object_id: object.clone(),
                arguments: arguments
                    .into_iter()
                    .map(|value| CallArgument { value })
                    .collect(),
                return_by_value: true,
                await_promise: false,
            })
            .await;
        // Best effort: the handle goes with the document anyway.
        let _ = answer(self.tab.page().call(&ReleaseObject { object_id: object })).await;
        let called = called?;
        if let Some(exception) = called.exception_details {
            return Err(execution(format!(
                "the browser could not do that: {}",
                exception.text
            )));
        }
        Ok(called.result.value.unwrap_or(Value::Null))
    }
}

/// A node a ref names.
pub(super) struct Node<'a> {
    pub(super) id: BackendNodeId,
    /// The ref, such as `ref_3`.
    pub(super) name: &'a str,
}

impl Node<'_> {
    /// The error for a node the page no longer has.
    pub(super) fn stale(&self) -> ToolError {
        execution(StaleRef(self.name.to_owned()).to_string())
    }
}

/// `call`, or a timeout error when the browser does not answer within
/// [`CALL_LIMIT`].
pub(super) async fn answer<T>(
    call: impl std::future::Future<Output = Result<T, CdpError>>,
) -> Result<T, String> {
    within_limit(call).await.map_err(|error| error.to_string())
}

/// Why a call to the browser failed.
#[derive(Debug, thiserror::Error)]
enum CallError {
    #[error(transparent)]
    Browser(CdpError),
    #[error("the browser did not answer within {} s", CALL_LIMIT.as_secs())]
    Unanswered,
}

/// `call`, failing when the browser does not answer within [`CALL_LIMIT`].
async fn within_limit<T>(
    call: impl std::future::Future<Output = Result<T, CdpError>>,
) -> Result<T, CallError> {
    match tokio::time::timeout(CALL_LIMIT, call).await {
        Ok(result) => result.map_err(CallError::Browser),
        Err(_) => Err(CallError::Unanswered),
    }
}

pub(super) fn execution(message: impl Into<String>) -> ToolError {
    ToolError::new(ToolErrorKind::Execution, message)
}

#[cfg(test)]
#[path = "tabs_tests.rs"]
mod tests;

#[cfg(test)]
#[path = "tabs_live_tests.rs"]
mod live_tests;