rho-coding-agent 3.5.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
use std::path::Path;

use pretty_assertions::assert_eq;
use rho_protocol::{self as wire, Cursor, Replay, Seq};
use rho_sdk::model::Message;

use super::{Feed, REPLAY_BUFFER_BYTES, TURN_START_EVICTED};
use crate::{
    app::{
        session_events::{LiveEvents, SavedTurn},
        session_runtime::SessionTools,
    },
    session::tree::{DisplayRowOrigin, NodeId, ProjectedMessage},
    tools::sdk_registry::AppToolSet,
};

fn notice(text: &str) -> wire::SessionEvent {
    wire::SessionEvent::Notice { text: text.into() }
}

fn notices(texts: &[&str]) -> Vec<wire::SessionEvent> {
    texts.iter().map(|text| notice(text)).collect()
}

/// `texts` saved as one save's display rows, a user message each, saved in
/// a node named after its text.
fn saved(texts: &[&str]) -> SavedTurn {
    let rows: Vec<_> = texts
        .iter()
        .map(|text| ProjectedMessage {
            origin: Some(DisplayRowOrigin {
                node: NodeId::from_string(*text).unwrap(),
                row: 0,
            }),
            message: Message::user_text(*text),
        })
        .collect();
    let tool_set = AppToolSet::disabled();
    let tools = SessionTools::of_tool_set_for_tests(&tool_set);
    LiveEvents::new(Path::new("/work"), tools, /*configured_window*/ None)
        .replay(&rows, Path::new("/work"), tools)
        .unwrap()
}

/// The event a reset replays [`saved`]'s row of `text` as.
fn shown(text: &str) -> wire::SessionEvent {
    wire::SessionEvent::UserMessage {
        message: wire::MessageId::new(format!("saved-{text}-0-0")),
        content: vec![wire::ContentBlock::Text { text: text.into() }],
        steer: None,
    }
}

/// The agent [`idle_feed`]'s session runs as.
const AGENT: &str = "default";

fn agent(id: &str) -> wire::SessionEvent {
    wire::SessionEvent::Agent { id: id.into() }
}

/// The events an attach from `after` replays, and whether it resets; a
/// reset's after the agent and the started sessions' defaults it starts
/// with. Also checks the count the attach reports, which the client reads
/// before the lazily rendered events, and that a reset starts with those
/// two, the defaults as [`idle_feed`]'s session has none.
fn replay(feed: &Feed, after: Option<Cursor>) -> (Replay, Vec<(u64, wire::SessionEvent)>) {
    let (replay, events) = feed.state().replay_from(after.as_ref());
    let len = events.len;
    let mut events: Vec<_> = events.events.map(|(seq, event)| (seq.0, event)).collect();
    assert_eq!(len, events.len(), "the reported replay length");
    if replay == Replay::Reset {
        let head: Vec<_> = events.drain(..2).map(|(_, event)| event).collect();
        assert_eq!(
            head,
            [
                agent(AGENT),
                wire::SessionEvent::StartedSessionDefaults(Default::default()),
            ],
            "a reset starts with the agent and the started sessions' defaults"
        );
    }
    (replay, events)
}

/// Options that differ only in their permission mode.
fn options(mode: wire::PermissionMode) -> wire::SessionOptions {
    wire::SessionOptions {
        model: wire::ModelOptions {
            auth: "api-key".into(),
            current: wire::ModelRef {
                provider: "test".into(),
                model: "model".into(),
            },
            available: Vec::new(),
        },
        reasoning: None,
        fast_mode: None,
        permission_mode: wire::PermissionModeOptions {
            current: mode,
            available: vec![wire::PermissionMode::Bypass, wire::PermissionMode::Plan],
        },
        commands: Vec::new(),
        added_dirs: Vec::new(),
    }
}

fn idle_feed() -> Feed {
    Feed::new(
        wire::JobState::Idle,
        /*turn*/ None,
        /*title*/ None,
        options(wire::PermissionMode::Bypass),
        AGENT.into(),
    )
}

fn cursor(feed: &Feed, seq: u64) -> Option<Cursor> {
    Some(Cursor {
        stream: feed.state().stream.clone(),
        seq: Seq(seq),
    })
}

#[test]
fn attach_resumes_a_buffered_cursor_and_resets_anything_else() {
    // One saved turn, then a turn in progress.
    let feed = idle_feed();
    feed.publish(notices(&["live"]));
    feed.end_turn(saved(&["saved"]));
    feed.publish(notices(&["a", "b", "c"]));

    let other_stream = Some(Cursor {
        stream: rho_protocol::StreamId::new("an earlier daemon"),
        seq: Seq(1),
    });
    let reset = (
        Replay::Reset,
        vec![
            (1, shown("saved")),
            (2, notice("a")),
            (3, notice("b")),
            (4, notice("c")),
        ],
    );
    for (name, after, expected) in [
        ("no cursor", None, reset.clone()),
        ("another stream's cursor", other_stream, reset.clone()),
        ("a cursor past the stream", cursor(&feed, 5), reset.clone()),
        // What a client holds that left partway through a transcript.
        ("a cursor at 0", cursor(&feed, 0), reset.clone()),
        (
            "the transcript's end",
            cursor(&feed, 1),
            (
                Replay::Tail,
                vec![(2, notice("a")), (3, notice("b")), (4, notice("c"))],
            ),
        ),
        (
            "a buffered cursor",
            cursor(&feed, 2),
            (Replay::Tail, vec![(3, notice("b")), (4, notice("c"))]),
        ),
        (
            "the latest cursor",
            cursor(&feed, 4),
            (Replay::Tail, vec![]),
        ),
    ] {
        assert_eq!(replay(&feed, after), expected, "{name}");
    }
}

#[test]
fn a_saved_turn_moves_into_the_transcript_without_repeating_or_dropping_events() {
    let feed = idle_feed();
    feed.publish(notices(&["first live"]));
    feed.end_turn(saved(&["first turn"]));
    feed.publish(notices(&["live prompt", "live reply"]));
    // The turn's replay from its saved rows joins the transcript, and its
    // live events stop being part of a reset.
    feed.end_turn(saved(&["saved prompt", "saved reply"]));
    feed.publish(notices(&["next prompt"]));

    assert_eq!(
        replay(&feed, None),
        (
            Replay::Reset,
            vec![
                (0, shown("first turn")),
                (0, shown("saved prompt")),
                (3, shown("saved reply")),
                (4, notice("next prompt")),
            ]
        ),
    );
    // A client that saw the live turn still resumes from the buffer.
    assert_eq!(
        replay(&feed, cursor(&feed, 2)),
        (
            Replay::Tail,
            vec![(3, notice("live reply")), (4, notice("next prompt"))]
        ),
    );
}

// Covers: a turn whose saved rows could not be read must not vanish from
// resets once the next turn starts.
#[test]
fn a_turn_that_did_not_save_replays_live_until_a_later_turn_saves_it() {
    let feed = idle_feed();
    feed.publish(notices(&["unsaved turn"]));
    feed.publish(notices(&["next turn"]));
    assert_eq!(
        replay(&feed, None),
        (
            Replay::Reset,
            vec![(1, notice("unsaved turn")), (2, notice("next turn"))]
        ),
    );

    feed.end_turn(saved(&["both turns saved"]));
    assert_eq!(
        replay(&feed, None),
        (Replay::Reset, vec![(2, shown("both turns saved"))]),
    );
}

#[test]
fn a_turn_larger_than_the_buffer_resets_with_a_notice_instead_of_its_start() {
    let feed = idle_feed();
    let large = "x".repeat(REPLAY_BUFFER_BYTES / 4);
    feed.publish(std::iter::repeat_with(|| notice(&large)).take(5));
    feed.publish(notices(&["latest"]));

    let (kind, events) = replay(&feed, None);
    let seqs: Vec<_> = events.iter().map(|(seq, _)| *seq).collect();
    assert_eq!(kind, Replay::Reset);
    assert_eq!(events[0], (0, notice(TURN_START_EVICTED)));
    assert_eq!(events.last(), Some(&(6, notice("latest"))));
    assert!(
        seqs[1] > 1,
        "the turn's first events were evicted: {seqs:?}"
    );
    // The evicted start can no longer be resumed from.
    assert_eq!(replay(&feed, cursor(&feed, 1)).0, Replay::Reset);
}

// Covers: once a session's conversation moved to another node of its tree,
// the feed replays that conversation to everyone: a cursor from before the
// move resets instead of tailing the branch left behind, what is published
// after the move follows the new transcript, and the clients attached at
// the move are no longer subscribed, so they attach again.
// Owner: daemon session feed.
#[test]
fn a_restart_replays_the_moved_conversation_to_every_cursor() {
    let feed = idle_feed();
    feed.publish(notices(&["live"]));
    feed.end_turn(saved(&["first saved", "second saved"]));
    let before = cursor(&feed, 1);
    let _attached = feed.attach(before.as_ref());

    feed.restart(Some(saved(&["first saved"])));
    feed.publish(notices(&["told after"]));

    let moved = (
        Replay::Reset,
        vec![(0, shown("first saved")), (1, notice("told after"))],
    );
    assert_eq!(
        (replay(&feed, before), replay(&feed, None), feed.followed()),
        (moved.clone(), moved, false)
    );
}

#[test]
fn an_attach_reports_the_job_state_its_replay_ends_in_and_its_turn() {
    let feed = idle_feed();
    let idle = feed.attach(None);
    assert_eq!((idle.job, idle.turn), (wire::JobState::Idle, None));
    let turn = wire::TurnId::new("t1");
    feed.publish([wire::SessionEvent::State {
        state: wire::JobState::Running,
        turn: Some(turn.clone()),
    }]);
    feed.publish(notices(&["a reply"]));
    let running = feed.attach(None);
    assert_eq!(
        (running.job, running.turn),
        (wire::JobState::Running, Some(turn))
    );
}

// Covers: an attach reports the session's title, the saved one a reopened
// session starts with until a title change replaces it, since no saved
// transcript holds a title (#1670).
// Owner: daemon session feed.
#[test]
fn an_attach_reports_the_saved_title_until_a_title_change() {
    let feed = Feed::new(
        wire::JobState::Idle,
        /*turn*/ None,
        Some("Saved title".into()),
        options(wire::PermissionMode::Bypass),
        AGENT.into(),
    );
    assert_eq!(feed.attach(None).title, Some("Saved title".into()));
    feed.publish([wire::SessionEvent::TitleChanged {
        title: "New title".into(),
    }]);
    assert_eq!(feed.attach(None).title, Some("New title".into()));
}

// Covers: an attach reports the input requests open as they stand after
// its replay: resolved ones gone, and a held one without the timeout it
// opened with, so a late client neither shows a countdown nor misses one.
// Owner: daemon session feed.
#[test]
fn an_attach_reports_open_requests_as_they_stand() {
    let request = |id: u64| wire::InputRequest {
        id: wire::InputRequestId(id),
        ask: wire::Ask::PlanApproval(wire::PlanApprovalAsk {
            plan: "the plan".into(),
            modes: vec![wire::PermissionMode::Auto],
        }),
        tool_call: None,
        timeout: Some(wire::InputTimeout {
            deadline_ms: 1,
            answer: wire::InputAnswer::KeepPlanning { feedback: None },
            reason: "safe".into(),
        }),
        asker: Default::default(),
    };
    let feed = idle_feed();
    feed.publish([
        wire::SessionEvent::InputRequested {
            request: Box::new(request(0)),
        },
        wire::SessionEvent::InputRequested {
            request: Box::new(request(1)),
        },
        wire::SessionEvent::InputRequested {
            request: Box::new(request(2)),
        },
        wire::SessionEvent::InputHeld {
            id: wire::InputRequestId(0),
        },
        wire::SessionEvent::InputResolved {
            id: wire::InputRequestId(1),
            resolution: wire::Resolution::TimedOut,
        },
    ]);
    let held = wire::InputRequest {
        timeout: None,
        ..request(0)
    };
    assert_eq!(feed.attach(None).inputs, vec![held, request(2)]);
}

// Covers: clients hear of an options change once, and an attach reports the
// options as they stand, so a configure that changes nothing sends nothing.
// Owner: daemon session feed
#[test]
fn options_reach_clients_only_when_they_change() {
    let feed = idle_feed();
    feed.update_options(options(wire::PermissionMode::Bypass));
    feed.update_options(options(wire::PermissionMode::Plan));
    feed.update_options(options(wire::PermissionMode::Plan));

    let changed = wire::SessionEvent::OptionsChanged {
        options: Box::new(options(wire::PermissionMode::Plan)),
    };
    assert_eq!(replay(&feed, None), (Replay::Reset, vec![(1, changed)]));
    assert_eq!(
        feed.attach(None).options,
        options(wire::PermissionMode::Plan)
    );
}

// Covers: a reset starts with the agent the session runs as, which no saved
// row holds: the one it opened as until an `/agent:` rebind changes it, and
// clients hear of that change once.
// Owner: daemon session feed.
#[test]
fn a_reset_starts_with_the_agent_a_rebind_last_named() {
    let feed = idle_feed();
    let opened = feed.reset_replay_for_tests().first().cloned();
    feed.update_agent(AGENT);
    feed.update_agent("archivist");
    feed.update_agent("archivist");

    assert_eq!(
        (
            opened,
            feed.buffered_for_tests(),
            feed.reset_replay_for_tests().first().cloned(),
        ),
        (
            Some(agent(AGENT)),
            vec![agent("archivist")],
            Some(agent("archivist")),
        ),
    );
}

// Covers: an event JSON cannot hold, live or saved, never reaches a reset or
// a subscriber, whose forwarder relies on every event encoding.
#[cfg(unix)]
#[test]
fn events_json_cannot_hold_are_dropped_live_and_saved() {
    use std::{ffi::OsStr, os::unix::ffi::OsStrExt, path::PathBuf};

    let unencodable = || {
        wire::SessionEvent::tool_call(wire::ToolCallUpdate {
            id: wire::ToolCallId::new("call"),
            title: None,
            kind: None,
            status: None,
            raw_input: None,
            content: None,
            locations: Some(vec![wire::Location {
                path: PathBuf::from(OsStr::from_bytes(b"/work/\xff")),
                line: None,
            }]),
            display: None,
        })
    };
    let feed = idle_feed();
    feed.publish([unencodable(), notice("live")]);
    assert_eq!(
        replay(&feed, None),
        (Replay::Reset, vec![(1, notice("live"))])
    );

    // A saved read in a workspace whose path is not UTF-8 opens with a
    // location JSON cannot hold.
    let config = crate::config::Config::default();
    let tool_set = AppToolSet::new(
        &config,
        crate::diagnostics::RuntimeDiagnostics::new(&config),
        crate::tools::sdk_registry::ToolSetOptions::new(crate::agent::AgentCapabilities::new(
            [crate::agent::ToolCapability::ReadFile].into(),
        )),
    );
    let workspace = PathBuf::from(OsStr::from_bytes(b"/work/\xff"));
    let read = rho_sdk::model::ToolCall::new(
        "read".into(),
        "read_file".into(),
        serde_json::json!({ "path": "src/lib.rs" }),
    );
    let rows = [
        ProjectedMessage {
            origin: Some(DisplayRowOrigin {
                node: NodeId::from_string("saved").unwrap(),
                row: 0,
            }),
            message: Message::user_text("saved"),
        },
        ProjectedMessage {
            origin: None,
            message: Message::Assistant(vec![rho_sdk::model::ContentBlock::ToolCall(read)].into()),
        },
    ];
    let tools = SessionTools::of_tool_set_for_tests(&tool_set);
    let turn = LiveEvents::new(&workspace, tools, /*configured_window*/ None)
        .replay(&rows, &workspace, tools)
        .unwrap();
    feed.end_turn(turn);
    // The read opens with that location, so its opening is dropped; the
    // replay still closes the call it left without a result.
    let closed = wire::SessionEvent::tool_call(wire::ToolCallUpdate {
        id: wire::ToolCallId::new("read"),
        title: None,
        kind: None,
        status: Some(wire::ToolStatus::Failed),
        raw_input: None,
        content: None,
        locations: None,
        display: None,
    });
    assert_eq!(
        replay(&feed, None),
        (Replay::Reset, vec![(0, shown("saved")), (1, closed)])
    );
}

// Covers: the job list's usage starts as what a reopened session was
// seeded with, and a turn's usage, which holds the session's cost, replaces
// it.
// Owner: daemon session feed.
#[test]
fn the_listed_usage_is_the_seeded_one_until_a_turn_reports_it() {
    let usage = |used_tokens, cost_usd_micros| wire::SessionEvent::Usage {
        used_tokens,
        window_tokens: Some(1_000),
        cost_usd_micros,
    };
    let listed = |used_tokens, cost_usd_micros| {
        Some(wire::JobUsage {
            used_tokens,
            window_tokens: Some(1_000),
            cost_usd_micros,
        })
    };
    let feed = idle_feed();
    let new = feed.live().usage;
    feed.seed_usage(&usage(10, None));
    let reopened = feed.live().usage;
    feed.publish([usage(20, Some(5))]);
    let live = feed.live().usage;

    assert_eq!(
        (new, reopened, live, feed.buffered_for_tests().len()),
        (None, listed(10, None), listed(20, Some(5)), 1)
    );
}

// Covers: a client that attaches to a session, as `rho --resume` and
// `/jobs` do, shows its context and spend at once. Saved rows hold no usage,
// so a reset that replays only them left the gauges blank until the next
// turn. The replayed usage is the one as of the last save, a reopened
// session's seed included; the turn in progress replays its own after it.
// Owner: daemon session feed.
#[test]
fn a_reset_replays_the_usage_as_of_the_last_save() {
    let usage = |used_tokens| wire::SessionEvent::Usage {
        used_tokens,
        window_tokens: Some(1_000),
        cost_usd_micros: Some(5),
    };
    let reopened = idle_feed();
    reopened.seed_usage(&usage(10));
    reopened.end_turn(saved(&["saved prompt"]));
    let loaded = idle_feed();
    loaded.publish([notice("prompt"), usage(10), notice("reply"), usage(20)]);
    loaded.end_turn(saved(&["saved prompt", "saved reply"]));
    loaded.publish([notice("next prompt"), usage(30)]);

    assert_eq!(
        (replay(&reopened, None), replay(&loaded, None)),
        (
            (
                Replay::Reset,
                vec![(0, shown("saved prompt")), (0, usage(10))]
            ),
            (
                Replay::Reset,
                vec![
                    (0, shown("saved prompt")),
                    (0, shown("saved reply")),
                    (4, usage(20)),
                    (5, notice("next prompt")),
                    (6, usage(30)),
                ]
            ),
        ),
    );
}

// Covers: once the feed reports activity, every attach's replay, tail or
// reset, ends with the current level, counted in its length, said once
// when the replay already ends with the event that said it; and a turn
// starting on a settled session says `active` before its `running`. A
// late observer that missed the level would wait on a session that already
// settled, or return before a turn starts.
// Owner: daemon session feed.
#[test]
fn replays_end_with_the_activity_and_active_precedes_a_running_state() {
    let activity = |state| wire::SessionEvent::Activity { state };
    let state = |state| wire::SessionEvent::State {
        state,
        turn: Some(wire::TurnId::new("t1")),
    };
    let unreported = idle_feed();
    unreported.publish([state(wire::JobState::Running)]);
    let feed = idle_feed();
    feed.update_activity(|| false);
    feed.publish([state(wire::JobState::Running), notice("reply")]);
    let busy = replay(&feed, cursor(&feed, 1));
    feed.publish([state(wire::JobState::Completed)]);
    feed.update_activity(|| false);
    // Already settled: no second event.
    feed.update_activity(|| false);

    assert_eq!(
        (
            replay(&unreported, None),
            busy,
            replay(&feed, None),
            replay(&feed, cursor(&feed, 6)),
        ),
        (
            (Replay::Reset, vec![(1, state(wire::JobState::Running))]),
            (
                Replay::Tail,
                vec![
                    (2, activity(wire::SessionActivity::Active)),
                    (3, state(wire::JobState::Running)),
                    (4, notice("reply")),
                    (4, activity(wire::SessionActivity::Active)),
                ]
            ),
            (
                Replay::Reset,
                vec![
                    (1, activity(wire::SessionActivity::Settled)),
                    (2, activity(wire::SessionActivity::Active)),
                    (3, state(wire::JobState::Running)),
                    (4, notice("reply")),
                    (5, state(wire::JobState::Completed)),
                    (6, activity(wire::SessionActivity::Settled)),
                ]
            ),
            (
                Replay::Tail,
                vec![(6, activity(wire::SessionActivity::Settled))]
            ),
        )
    );
}