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
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
//! A person driving a real chrome-headless-shell. Set
//! `RHO_BROWSER_EXECUTABLE` to one and run with `--include-ignored`.

use super::super::tabs::SessionTabs;
use crate::browser::config::BrowserConfig;
use crate::browser::drive::PersonTabs;
use crate::browser::view::{BrowserState, BrowserView, Driver};
use crate::browser::{Browsers, SessionBrowser, VIEWPORT};
use pretty_assertions::assert_eq;
use rho_browser::cdp::runtime::Evaluate;
use rho_browser::screencast::Fit;
use rho_browser::tab::Viewport;
use rho_protocol::{
    BrowserCursor, BrowserDestination, BrowserInput, BrowserKeyAction, BrowserModifiers,
    BrowserMouseAction, BrowserMouseButton, BrowserTabAction, ConnectionId,
};
use rho_sdk::SessionId;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};

/// Bounds each wait on the browser; never the way the test syncs.
const BUDGET: Duration = Duration::from_secs(10);

/// A link that opens a popup across the page's top left, and a field whose
/// text the page makes its title.
const PAGE: &str = r#"<title>drive</title>
<a href="/popup" target="_blank" style="position:absolute;left:0;top:0;width:400px;height:200px">open</a>
<input id="field" oninput="document.title=this.value" style="position:absolute;left:500px;top:20px;width:200px;height:30px">"#;

/// Serves `page` at every path.
async fn serve(page: &'static str) -> std::net::SocketAddr {
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let address = listener.local_addr().unwrap();
    tokio::spawn(async move {
        while let Ok((mut stream, _)) = listener.accept().await {
            tokio::spawn(async move {
                let mut request = vec![0; 4096];
                let _ = stream.read(&mut request).await;
                let response = format!(
                    "HTTP/1.1 200 OK\r\ncontent-type: text/html\r\ncontent-length: {}\r\n\r\n{page}",
                    page.len()
                );
                let _ = stream.write_all(response.as_bytes()).await;
            });
        }
    });
    address
}

/// A click at `(x, y)` as a client sends one: the pointer moves there,
/// then the button goes down and up.
fn click(x: f64, y: f64) -> [BrowserInput; 3] {
    let mouse = |action, button, clicks| BrowserInput::Mouse {
        action,
        x,
        y,
        button,
        clicks,
        modifiers: BrowserModifiers::NONE,
    };
    let left = Some(BrowserMouseButton::Left);
    [
        mouse(BrowserMouseAction::Moved, None, 0),
        mouse(BrowserMouseAction::Pressed, left, 1),
        mouse(BrowserMouseAction::Released, left, 1),
    ]
}

fn key(action: BrowserKeyAction, text: Option<&str>) -> BrowserInput {
    BrowserInput::Key {
        action,
        key: "h".into(),
        code: Some("KeyH".into()),
        text: text.map(str::to_owned),
        modifiers: BrowserModifiers::NONE,
    }
}

async fn until(
    view: &mut tokio::sync::watch::Receiver<BrowserView>,
    what: &str,
    done: impl FnMut(&BrowserView) -> bool,
) {
    tokio::time::timeout(BUDGET, view.wait_for(done))
        .await
        .unwrap_or_else(|_| panic!("{what}"))
        .unwrap();
}

// Covers: a person who took a session's browser over opens a tab, loads a
// page in it, clicks and types into it, the title the page sets from it
// shows on the tab, and a popup their click opens joins the session's
// tabs, all in the tabs the agent uses; an agent's call meanwhile waits,
// and goes on once the person's connection leaves, seeing what the person
// typed and learning a person drove. Without it, a person's driving would
// act on tabs the agent never sees, or under the agent's hands, or a tab
// would keep a title its page replaced.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_person_drives_the_tabs_the_agent_uses_while_it_waits() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let config = BrowserConfig {
        executable: Some(executable.into()),
        ..BrowserConfig::default()
    };
    let browsers = Browsers::for_daemon(
        home.path(),
        Box::new(move || Box::pin(std::future::ready(config.clone()))),
    )
    .unwrap();
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let mut view = browser.view();
    let page = format!("http://{}/", serve(PAGE).await);
    let connection = ConnectionId::new(1);

    browser.control(Driver::Person, connection);
    let opened = browser.person_tab(BrowserTabAction::New).await.unwrap();
    browser
        .person_navigate(
            "tab-1".into(),
            BrowserDestination::Url { url: page.clone() },
        )
        .await
        .unwrap();
    until(&mut view, "the page should load", |view| {
        view.tabs
            .first()
            .is_some_and(|tab| tab.url == page && !tab.loading)
    })
    .await;
    let typing = click(600.0, 35.0).into_iter().chain([
        key(BrowserKeyAction::Down, Some("h")),
        key(BrowserKeyAction::Up, None),
        BrowserInput::Text { text: "i!".into() },
    ]);
    for input in typing {
        browser.person_input("tab-1".into(), input).await.unwrap();
    }
    until(
        &mut view,
        "the tab should show the title the page set",
        |view| {
            view.tabs
                .iter()
                .any(|tab| tab.id == "tab-1" && tab.title == "hi!")
        },
    )
    .await;
    let agent = tokio::spawn({
        let tabs = Arc::clone(&tabs);
        async move {
            let mut held = tabs.hold().await.unwrap();
            let typed = held
                .tabs
                .get(Some("tab-1"))
                .unwrap()
                .call(&Evaluate {
                    expression: "document.getElementById('field').value".into(),
                    context_id: None,
                    return_by_value: true,
                    await_promise: false,
                    timeout: None,
                })
                .await
                .unwrap()
                .result
                .value;
            (held.person_drove, typed)
        }
    });
    for input in click(100.0, 100.0) {
        browser.person_input("tab-1".into(), input).await.unwrap();
    }
    until(&mut view, "the popup should join the tabs", |view| {
        view.tabs.len() == 2
    })
    .await;
    let waited = !agent.is_finished();
    browser.connection_left(connection);
    let (person_drove, typed) = tokio::time::timeout(BUDGET, agent)
        .await
        .expect("the agent's call should go on")
        .unwrap();

    let ids: Vec<_> = view
        .borrow()
        .tabs
        .iter()
        .map(|tab| tab.id.clone())
        .collect();
    assert_eq!(
        (opened, ids, waited, person_drove, typed, browser.driver()),
        (
            Some("tab-1".to_owned()),
            vec!["tab-1".to_owned(), "tab-2".to_owned()],
            true,
            true,
            Some(serde_json::json!("hi!")),
            Driver::Agent,
        )
    );
    browsers.close().await;
}

/// Takes `browser` over for the person at `connection`, opens a tab and
/// loads `page` in it, then hands the browser back, answering the state
/// right after the take-over.
async fn take_over_and_load(
    browser: &SessionBrowser,
    view: &mut tokio::sync::watch::Receiver<BrowserView>,
    connection: ConnectionId,
    page: &str,
) -> BrowserState {
    browser.take_over(connection, None).await.unwrap();
    let taken = view.borrow().state;
    let opened = browser
        .person_tab(BrowserTabAction::New)
        .await
        .unwrap()
        .expect("a new tab has an id");
    browser
        .person_navigate(opened.clone(), BrowserDestination::Url { url: page.into() })
        .await
        .unwrap();
    until(view, "the page should load", |view| {
        view.tabs
            .iter()
            .any(|tab| tab.id == opened && tab.url == page && !tab.loading)
    })
    .await;
    browser.control(Driver::Agent, connection);
    taken
}

// Covers: a person who takes over a session's browser that is not running,
// as one that never started, went unused and unloaded, or crashed, starts
// it, and then opens a tab and loads a page in it, which the session's view
// shows. Otherwise a person could drive a browser only once the agent had
// started one.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn taking_over_a_browser_that_is_not_running_starts_it() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let browsers = Browsers::for_tests(
        home.path(),
        BrowserConfig {
            executable: Some(executable.into()),
            unload_idle_after: Some(Duration::from_millis(500)),
            ..BrowserConfig::default()
        },
    );
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let mut view = browser.view();
    let page = format!("http://{}/", serve(PAGE).await);
    let connection = ConnectionId::new(1);

    let never_started = view.borrow().state;
    let first = take_over_and_load(&browser, &mut view, connection, &page).await;
    until(&mut view, "the browser should unload", |view| {
        view.state == BrowserState::Unloaded
    })
    .await;
    let after_unload = take_over_and_load(&browser, &mut view, connection, &page).await;
    let context = browser.context().await.unwrap();
    // Answered or not, the browser dies.
    let _ = context
        .connection()
        .call_raw("Browser.crash", serde_json::json!({}))
        .await;
    drop(context);
    until(&mut view, "the browser should crash", |view| {
        view.state == BrowserState::Crashed
    })
    .await;
    let after_crash = take_over_and_load(&browser, &mut view, connection, &page).await;
    browsers.close().await;

    assert_eq!(
        (never_started, first, after_unload, after_crash),
        (
            BrowserState::NotStarted,
            BrowserState::Running,
            BrowserState::Running,
            BrowserState::Running
        )
    );
}

/// The size tab `tab` lays its page out at, as the page sees it.
async fn laid_out_at(tabs: &SessionTabs, tab: &str) -> Viewport {
    let mut held = tabs.hold_now().await.unwrap();
    let size = held
        .tabs
        .get(Some(tab))
        .unwrap()
        .call(&Evaluate {
            expression: "[innerWidth, innerHeight]".into(),
            context_id: None,
            return_by_value: true,
            await_promise: false,
            timeout: None,
        })
        .await
        .unwrap()
        .result
        .value;
    let size: (u32, u32) = serde_json::from_value(size.unwrap()).unwrap();
    Viewport {
        width: size.0,
        height: size.1,
    }
}

// Covers: a person who takes over a browser that is not running, naming
// the size they view it at, gets tabs that open and lay out at that size,
// and a watch starts at it; a resize while they drive lays the tabs out
// again; and once they hand back, the agent's next call finds its tabs at
// the agent's size. Otherwise the panel shows a page shrunk to its width
// with half of it empty, or the agent's screenshots and coordinates come
// at the person's size.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn a_persons_tabs_render_at_their_size_until_the_agent_gets_them_back() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let browsers = Browsers::for_tests(
        home.path(),
        BrowserConfig {
            executable: Some(executable.into()),
            ..BrowserConfig::default()
        },
    );
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let connection = ConnectionId::new(1);
    let panel = Viewport {
        width: 400,
        height: 700,
    };
    let wider = Viewport {
        width: 600,
        height: 900,
    };
    let fit = Fit {
        max_width: 800,
        max_height: 900,
    };

    let taken = browser.take_over(connection, Some(panel)).await.unwrap();
    let opened = browser.person_tab(BrowserTabAction::New).await.unwrap();
    let at_take_over = laid_out_at(&tabs, "tab-1").await;
    let (watched, _frames) = browser.watch("tab-1", fit).await.unwrap();
    browser.person_resize(wider).unwrap();
    // The person's next action holds the tabs after the resize's fit.
    let after_resize = laid_out_at(&tabs, "tab-1").await;
    browser.control(Driver::Agent, connection);
    let (person_drove, for_the_agent) = {
        let held = tabs.hold().await.unwrap();
        (held.person_drove, held.tabs.has("tab-1"))
    };
    let after_hand_back = laid_out_at(&tabs, "tab-1").await;
    browsers.close().await;

    assert_eq!(
        (
            taken,
            opened,
            at_take_over,
            watched.viewport,
            after_resize,
            (person_drove, for_the_agent),
            after_hand_back,
            browser.viewport(),
        ),
        (
            panel,
            Some("tab-1".to_owned()),
            panel,
            rho_protocol::BrowserViewport::new(400, 700),
            wider,
            (true, true),
            VIEWPORT,
            VIEWPORT,
        )
    );
}

/// A page with a cursor of each kind rho works out, in boxes down its left
/// edge, 40 px apart: a link, text, a field, an image cursor falling back
/// to `grab`, and a button's label, then the page's blank `auto`.
const CURSORS: &str = r##"<style>body{margin:0;font:16px sans-serif}
div,a,input,button{position:absolute;left:0;width:300px;height:30px;margin:0;padding:0;border:0;display:block}</style>
<a href="/" style="top:0">a link</a>
<div style="top:40px">some text to select</div>
<input style="top:80px">
<div style="top:120px;cursor:url(nowhere.png), grab"></div>
<button style="top:160px">a button</button>"##;

// Covers: after the person's mouse input, the tabs answer the cursor a
// browser shows there: a link's pointer, `auto` as text over every glyph
// of a line of text and over a field, and as default over a button's
// label and blank page, and an image cursor's fallback; a key answers
// none. Otherwise the client shows the wrong cursor over the frame, or
// none.
// Owner: person driving the session's tabs
#[tokio::test]
#[ignore = "needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE"]
async fn the_tabs_answer_the_cursor_under_the_persons_pointer() {
    let executable = std::env::var_os("RHO_BROWSER_EXECUTABLE")
        .expect("needs chrome-headless-shell in RHO_BROWSER_EXECUTABLE");
    let home = tempfile::tempdir().unwrap();
    let config = BrowserConfig {
        executable: Some(executable.into()),
        ..BrowserConfig::default()
    };
    let browsers = Browsers::for_daemon(
        home.path(),
        Box::new(move || Box::pin(std::future::ready(config.clone()))),
    )
    .unwrap();
    let browser = Browsers::session(Some(&browsers), &SessionId::new()).unwrap();
    let tabs = Arc::new(SessionTabs::new(browser.clone()));
    let person: Arc<dyn PersonTabs> = tabs.clone();
    browser.drive_with(Arc::downgrade(&person));
    let mut view = browser.view();
    let page = format!("http://{}/", serve(CURSORS).await);
    let connection = ConnectionId::new(1);
    take_over_and_load(&browser, &mut view, connection, &page).await;
    browser.control(Driver::Person, connection);

    let moved = |x, y| BrowserInput::Mouse {
        action: BrowserMouseAction::Moved,
        x,
        y,
        button: None,
        clicks: 0,
        modifiers: BrowserModifiers::NONE,
    };
    let mut cursors = Vec::new();
    for y in [15.0, 55.0, 95.0, 135.0, 175.0, 400.0] {
        cursors.push(person.input("tab-1".into(), moved(20.0, y)).await.unwrap());
    }
    // Across the line of text, a pixel at a time, up to its end.
    let mut across = Vec::new();
    for x in 1..100 {
        let cursor = person
            .input("tab-1".into(), moved(f64::from(x), 55.0))
            .await
            .unwrap();
        if cursor != Some(BrowserCursor::Text) {
            across.push((x, cursor));
        }
    }
    let key = person
        .input("tab-1".into(), key(BrowserKeyAction::Down, Some("h")))
        .await
        .unwrap();

    assert_eq!(
        (cursors, across, key),
        (
            [
                BrowserCursor::Pointer,
                BrowserCursor::Text,
                BrowserCursor::Text,
                BrowserCursor::Grab,
                BrowserCursor::Default,
                BrowserCursor::Default,
            ]
            .map(Some)
            .to_vec(),
            Vec::new(),
            None,
        )
    );
    browsers.close().await;
}