rho-coding-agent 3.13.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
//! A person driving the session's tabs from a client ([`PersonTabs`]):
//! their input, navigation and tab actions act on the same tabs the agent's
//! calls use, and the session's view follows what their driving does.

use super::cursor;
use super::tabs::{answer, Held, Loading, SessionTabs};
use super::text::{self, Destination};
use super::{keys, schema::NAVIGATION_LIMIT};
use crate::browser::drive::{PersonTabs, Refused};
use crate::browser::view::{BrowserState, BrowserView, Driver, ViewTab};
use crate::browser::{navigation, SessionBrowser};
use futures_util::future::BoxFuture;
use rho_browser::cdp::input::{
    DispatchKeyEvent, DispatchMouseEvent, InsertText, KeyEventKind, Modifiers, MouseButton,
    MouseEventKind,
};
use rho_browser::cdp::target::{
    GetTargets, SetDiscoverTargets, TargetCreated, TargetInfo, TargetInfoChanged,
};
use rho_browser::cdp::{BrowserContextId, TargetId};
use rho_browser::tab::{Step, Tab};
use rho_protocol::{
    BrowserCursor, BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers,
    BrowserMouseAction, BrowserMouseButton, BrowserTabAction,
};
use std::time::Duration;

/// How often the tabs' titles are read again while a person drives. The
/// browser tells of a new URL, but not of a title the page sets, as it does
/// once loaded or from a script: chrome-headless-shell 158 sends no
/// `Target.targetInfoChanged` for it (Linux). A read of five tabs' titles
/// took the browser p50 0.06 ms, p90 0.42 ms (n = 300), so a chip lags its
/// page's title by at most a quarter second for about 0.25 ms of the
/// browser's time a second.
const TITLES_EVERY: Duration = Duration::from_millis(250);

impl PersonTabs for SessionTabs {
    fn input(
        &self,
        tab: String,
        input: BrowserInput,
    ) -> BoxFuture<'_, Result<Option<BrowserCursor>, Refused>> {
        Box::pin(async move {
            let mut held = self.person_hold(&tab).await?;
            let takeovers = held.browser.takeovers();
            // Where the pointer went, after mouse input; the wheel, see
            // `cursor`.
            let at = match &input {
                BrowserInput::Mouse { x, y, .. } => Some((*x, *y)),
                _ => None,
            };
            let command = command(input, held.tabs.person_button.under(takeovers));
            let open = held.tabs.get(Some(&tab)).map_err(|_| Refused::NoTab(tab))?;
            let sent = match command {
                Command::Mouse(event) => open.call(&event).await.map(drop),
                Command::Key(event) => open.call(&event).await.map(drop),
                Command::Text(event) => open.call(&event).await.map(drop),
            };
            sent.map_err(|error| Refused::Browser(error.message().to_owned()))?;
            let Some((x, y)) = at else {
                return Ok(None);
            };
            Ok(cursor::under(open, x, y).await)
        })
    }

    fn navigate(&self, tab: String, to: BrowserDestination) -> BoxFuture<'_, Result<(), Refused>> {
        Box::pin(async move {
            let destination = match to {
                BrowserDestination::Url { url } => {
                    let destination = text::destination(&url).map_err(Refused::Invalid)?;
                    if let Destination::Url(url) = &destination {
                        navigation::allowed(url.as_str()).await.map_err(|reason| {
                            Refused::Invalid(format!("Navigation refused: {reason}."))
                        })?;
                    }
                    destination
                }
                BrowserDestination::Back => Destination::Back,
                BrowserDestination::Forward => Destination::Forward,
                BrowserDestination::Reload => Destination::Reload,
                _ => return Err(Refused::Invalid("an unknown destination".to_owned())),
            };
            let mut held = self.person_hold(&tab).await?;
            let open = held
                .tabs
                .get(Some(&tab))
                .map_err(|_| Refused::NoTab(tab.clone()))?;
            let new_url = match &destination {
                Destination::Url(url) => Some(url.as_str()),
                Destination::Back | Destination::Forward | Destination::Reload => None,
            };
            let loading = super::tabs::show_loading(held.browser, held.context.id(), open, new_url);
            tokio::spawn(load(
                held.browser.clone(),
                held.context.id().clone(),
                open.tab().clone(),
                destination,
                loading,
            ));
            Ok(())
        })
    }

    fn tab(&self, action: BrowserTabAction) -> BoxFuture<'_, Result<Option<String>, Refused>> {
        Box::pin(async move {
            let mut held = self.hold_now().await.map_err(browser_error)?;
            let opened = match action {
                BrowserTabAction::New => {
                    let opened = held
                        .tabs
                        .open(&held.context)
                        .await
                        .map_err(|error| Refused::Invalid(error.message().to_owned()))?;
                    Some(opened.id.clone())
                }
                BrowserTabAction::Close { tab } => {
                    if !held.tabs.has(&tab) {
                        return Err(Refused::NoTab(tab));
                    }
                    held.tabs.close(&tab).await.map_err(browser_error)?;
                    None
                }
                BrowserTabAction::Activate { tab } => {
                    held.tabs.switch(&tab).map_err(|_| Refused::NoTab(tab))?;
                    None
                }
                _ => return Err(Refused::Invalid("an unknown tab action".to_owned())),
            };
            held.show_tabs().await;
            Ok(opened)
        })
    }

    fn close(&self) -> BoxFuture<'_, ()> {
        Box::pin(self.release())
    }

    fn fit(&self) -> BoxFuture<'_, ()> {
        Box::pin(self.fit_running())
    }

    fn follow(&self) -> BoxFuture<'_, ()> {
        Box::pin(async move {
            let browser = self.browser();
            let mut view = browser.view();
            // A browser that is not running has nothing to follow; the
            // person's next action, which may start it, follows it then.
            if view.borrow_and_update().state != BrowserState::Running {
                return;
            }
            let (connection, context) = match self.hold_now().await {
                Ok(held) => (held.context.connection().clone(), held.context.id().clone()),
                Err(_) => return,
            };
            let mut events = connection.events();
            if connection
                .call(&SetDiscoverTargets { discover: true })
                .await
                .is_err()
            {
                return;
            }
            let mut titles = tokio::time::interval(TITLES_EVERY);
            titles.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
            loop {
                tokio::select! {
                    event = events.recv() => {
                        // The browser closed.
                        let Ok(event) = event else { return };
                        if let Some(Ok(changed)) = event.parse::<TargetInfoChanged>() {
                            let info = changed.target_info;
                            browser.show_in(&context, |view| {
                                if let Some(tab) = shown(view, &info.target_id) {
                                    tab.title = info.title;
                                    tab.url = info.url;
                                }
                            });
                        } else if let Some(Ok(created)) = event.parse::<TargetCreated>() {
                            let info = created.target_info;
                            if info.kind == "page" && info.browser_context_id.as_ref() == Some(&context) {
                                self.take_in_pages().await;
                            }
                        }
                    }
                    _ = titles.tick() => {
                        // A closed browser ends the events; a failed read
                        // tries again next tick.
                        if let Ok(targets) = answer(connection.call(&GetTargets {})).await {
                            show_titles(browser, &context, targets.target_infos);
                        }
                    }
                    () = agent_drives(&mut view) => return,
                }
            }
        })
    }
}

impl SessionTabs {
    /// The session's tabs for a person's action on tab `tab`, which the
    /// session's view lists, so an action on a tab of a browser that closed
    /// never starts it again.
    async fn person_hold(&self, tab: &str) -> Result<Held<'_>, Refused> {
        if !self.browser().shows_tab(tab) {
            return Err(Refused::NoTab(tab.to_owned()));
        }
        self.hold_now().await.map_err(browser_error)
    }

    /// Takes in the tabs pages opened, as a link a person clicked did, and
    /// shows them.
    async fn take_in_pages(&self) {
        if let Ok(mut held) = self.hold_now().await {
            held.tabs.take_in(&held.context).await;
            held.show_tabs().await;
        }
    }
}

/// Shows the titles of `targets` on the tabs of `context` that are them.
/// Not their URLs: a loading tab shows where it goes, while its target
/// still has the URL it leaves until the new page commits, which
/// [`TargetInfoChanged`] tells.
fn show_titles(browser: &SessionBrowser, context: &BrowserContextId, targets: Vec<TargetInfo>) {
    browser.show_in(context, |view| {
        for info in targets {
            if let Some(tab) = shown(view, &info.target_id) {
                tab.title = info.title;
            }
        }
    });
}

/// The tab of `view` that is `target`.
fn shown<'a>(view: &'a mut BrowserView, target: &TargetId) -> Option<&'a mut ViewTab> {
    view.tabs.iter_mut().find(|tab| tab.target == *target)
}

/// Resolves once the agent drives the browser again, or the session's
/// view is gone.
async fn agent_drives(view: &mut tokio::sync::watch::Receiver<crate::browser::view::BrowserView>) {
    let _ = view.wait_for(|view| view.driver == Driver::Agent).await;
}

fn browser_error(error: rho_sdk::tool::ToolError) -> Refused {
    Refused::Browser(error.message().to_owned())
}

/// Loads `destination` in `tab` of `context`, then shows the tab's title
/// and URL as loaded, or as far as it got, and no longer `loading`.
async fn load(
    browser: SessionBrowser,
    context: BrowserContextId,
    tab: Tab,
    destination: Destination,
    loading: Loading,
) {
    let loaded = match &destination {
        Destination::Url(url) => tab.load(url.as_str(), NAVIGATION_LIMIT).await,
        Destination::Back => tab.go(Step::Back, NAVIGATION_LIMIT).await,
        Destination::Forward => tab.go(Step::Forward, NAVIGATION_LIMIT).await,
        Destination::Reload => tab.go(Step::Reload, NAVIGATION_LIMIT).await,
    };
    if let Err(error) = loaded {
        tracing::debug!(%error, "a person's navigation did not finish");
    }
    let info = tab.info().await.ok();
    let target = tab.page().target_id().clone();
    browser.show_in(&context, |view| {
        if let Some(tab) = shown(view, &target) {
            if let Some(info) = info {
                tab.title = info.title;
                tab.url = info.url;
            }
        }
    });
    drop(loading);
}

/// The browser command a person's input sends.
#[derive(Debug, Clone)]
enum Command {
    Mouse(DispatchMouseEvent),
    Key(DispatchKeyEvent),
    Text(InsertText),
}

/// The command for `input`. `held` is the mouse button the person holds
/// down, which a move drags: a press holds it and a release lets go.
/// The mouse button a person driving the browser holds down, which their
/// moves drag. A button pressed under an earlier takeover was let go with
/// it, as when a client left between a press and its release.
#[derive(Debug, Default)]
pub(super) struct HeldButton {
    /// The takeover, as [`SessionBrowser::takeovers`] counts them, the
    /// button was pressed under.
    takeover: u64,
    button: Option<MouseButton>,
}

impl HeldButton {
    /// The button held under takeover `takeover`.
    pub(super) fn under(&mut self, takeover: u64) -> &mut Option<MouseButton> {
        if self.takeover != takeover {
            *self = Self {
                takeover,
                button: None,
            };
        }
        &mut self.button
    }
}

fn command(input: BrowserInput, held: &mut Option<MouseButton>) -> Command {
    match input {
        BrowserInput::Mouse {
            action,
            x,
            y,
            button,
            clicks,
            modifiers,
        } => {
            let button = button.map(mouse_button);
            let (kind, button, click_count) = match action {
                BrowserMouseAction::Moved => (MouseEventKind::Moved, *held, None),
                BrowserMouseAction::Pressed => {
                    *held = button;
                    (MouseEventKind::Pressed, button, Some(clicks.max(1)))
                }
                BrowserMouseAction::Released => {
                    *held = None;
                    (MouseEventKind::Released, button, Some(clicks.max(1)))
                }
                _ => (MouseEventKind::Moved, *held, None),
            };
            Command::Mouse(DispatchMouseEvent {
                kind,
                x,
                y,
                button,
                click_count,
                modifiers: modifiers_of(modifiers),
                delta_x: None,
                delta_y: None,
            })
        }
        BrowserInput::Wheel {
            x,
            y,
            dx,
            dy,
            modifiers,
        } => Command::Mouse(DispatchMouseEvent {
            kind: MouseEventKind::Wheel,
            x,
            y,
            button: None,
            click_count: None,
            modifiers: modifiers_of(modifiers),
            delta_x: Some(dx),
            delta_y: Some(dy),
        }),
        BrowserInput::Key {
            action,
            key,
            code,
            text,
            modifiers,
        } => {
            let modifiers = modifiers_of(modifiers);
            // As the agent's `key` does: a key types only with no modifier
            // but shift held.
            let text = text.filter(|text| {
                !text.is_empty() && modifiers.without(Modifiers::SHIFT) == Modifiers::NONE
            });
            let (kind, text) = match (action, text) {
                (BrowserKeyAction::Down, Some(text)) => (KeyEventKind::KeyDown, Some(text)),
                (BrowserKeyAction::Up, _) => (KeyEventKind::KeyUp, None),
                (_, _) => (KeyEventKind::RawKeyDown, None),
            };
            Command::Key(DispatchKeyEvent {
                kind,
                windows_virtual_key_code: keys::key_code(&key),
                key,
                code,
                text,
                modifiers,
            })
        }
        BrowserInput::Text { text } => Command::Text(InsertText { text }),
        // A newer client's input this daemon cannot send moves nothing.
        _ => Command::Text(InsertText {
            text: String::new(),
        }),
    }
}

fn mouse_button(button: BrowserMouseButton) -> MouseButton {
    match button {
        BrowserMouseButton::Left => MouseButton::Left,
        BrowserMouseButton::Middle => MouseButton::Middle,
        BrowserMouseButton::Right => MouseButton::Right,
        _ => MouseButton::Left,
    }
}

fn modifiers_of(held: BrowserModifiers) -> Modifiers {
    [
        (held.alt, Modifiers::ALT),
        (held.ctrl, Modifiers::CTRL),
        (held.meta, Modifiers::META),
        (held.shift, Modifiers::SHIFT),
    ]
    .into_iter()
    .filter(|(on, _)| *on)
    .fold(Modifiers::NONE, |all, (_, modifier)| all.with(modifier))
}

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

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