rho-coding-agent 1.40.0

A lightweight agent harness inspired by Pi
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
use std::borrow::Cow;
use std::time::Duration;

use pretty_assertions::assert_eq;
use rho_tools::tool_card::{
    DiffRow, DiffRowKind, ToolBody, ToolCard, ToolFact, ToolFamily, ToolHeader, ToolStatus,
};

use super::{card_is_toggleable, live_shell_elapsed, push_tool_card, with_live_shell_elapsed};
use crate::tui::{
    syntax::{reset_highlight_line_calls, take_highlight_line_calls, warm_syntax_set},
    theme::{SyntaxRole, Theme},
    ToolEntry,
};

fn line_text(line: &ratatui::text::Line<'_>) -> String {
    line.spans
        .iter()
        .map(|span| span.content.as_ref())
        .collect::<String>()
        .trim_end()
        .to_string()
}

fn render(card: &ToolCard, width: usize) -> Vec<String> {
    let mut lines = Vec::new();
    push_tool_card(
        &mut lines, card, width, /*max_tool_output_lines*/ 32, /*expanded*/ true,
    );
    lines.into_iter().map(|line| line_text(&line)).collect()
}

// Covers: wrapped fact rows keep a tree stem so long child text stays tied to the trunk.
// Owner: pure TUI layout
#[test]
fn mid_fact_wrap_keeps_box_stem_before_later_sibling() {
    let mut card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::Web,
        ToolHeader::call("x_search", None),
    );
    card.push_fact(ToolFact::Text {
        text: "Cerebras (5.6 OR o3) coming or release soon".into(),
    });
    card.push_fact(ToolFact::Meta {
        text: "finished".into(),
    });

    let lines = render(&card, 28);
    assert_eq!(lines[0], "✓ x_search");
    assert!(
        lines[1].starts_with(""),
        "first fact row should branch: {:?}",
        lines
    );
    assert!(
        lines.iter().any(|line| line.starts_with("")),
        "wrapped mid fact should extend with │: {:?}",
        lines
    );
    assert_eq!(lines.last().map(String::as_str), Some("  └ finished"));
}

// Covers: last fact wrap must not leave a dangling │ under └.
// Owner: pure TUI layout
#[test]
fn last_fact_wrap_uses_space_hang_not_stem() {
    let mut card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::Web,
        ToolHeader::call("x_search", None),
    );
    card.push_fact(ToolFact::Text {
        text: "only child query that needs several wraps at this width".into(),
    });

    let lines = render(&card, 24);
    assert!(
        lines[1].starts_with(""),
        "sole fact should be last branch: {:?}",
        lines
    );
    let continuations: Vec<_> = lines.iter().skip(2).collect();
    assert!(
        !continuations.is_empty(),
        "expected wrap continuations: {:?}",
        lines
    );
    for line in continuations {
        assert!(
            line.starts_with("    ") && !line.starts_with(""),
            "last-child wrap must hang with spaces: {:?}",
            lines
        );
    }
}

// Covers: multi-file File headers keep a continuous trunk through body rows so
// section branches read as one tree (│ under mid files, hang under the last).
// Owner: pure TUI layout
#[test]
fn multi_file_diff_connects_body_under_section_headers() {
    let card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileDiff,
        ToolHeader::call("edit", Some("2 files".into())),
    )
    .with_body(ToolBody::Diff(vec![
        DiffRow::file_header("a.txt", Some((1, 1))),
        DiffRow::new(DiffRowKind::Added, Some(1), "A"),
        DiffRow::file_header("b.txt", Some((0, 1))),
        DiffRow::new(DiffRowKind::Removed, Some(1), "B"),
    ]));

    let lines = render(&card, 40);
    assert_eq!(lines[0], "✓ edit(2 files)");
    assert!(
        lines[1].starts_with("")
            && lines[1].contains("+1 -1 lines")
            && lines[1].contains("a.txt"),
        "first file section should mid-branch: {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|line| line.starts_with("") && line.contains("A")),
        "body under first file must keep trunk stem: {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|line| line.starts_with("") && line.contains("b.txt")),
        "last file section should end-branch: {:?}",
        lines
    );
    assert!(
        lines.iter().any(|line| {
            line.contains("B") && line.starts_with("    ") && !line.starts_with("")
        }),
        "body under last file must hang without stem: {:?}",
        lines
    );
}

// Covers: fact wrap prefers whitespace over hard mid-word cuts (same as headers).
// Owner: pure TUI layout
#[test]
fn fact_wrap_breaks_on_whitespace() {
    let mut card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::Default,
        ToolHeader::call("tool", None),
    );
    card.push_fact(ToolFact::Text {
        text: "one two three four".into(),
    });

    // prefix "  └ " is 4 cols; content width 10.
    // Soft wrap: "one two" / "three four". Hard wrap would cut "three".
    let lines = render(&card, 14);
    let joined = lines.join("\n");
    assert!(
        !joined.contains("one two th"),
        "must not hard-split inside 'three': {:?}",
        lines
    );
    assert!(
        lines
            .iter()
            .any(|line| line.contains("three four") || line.ends_with("three")),
        "expected whitespace-bounded wrap rows: {:?}",
        lines
    );
}

// Covers: write/edit diff bodies syntax-highlight from the header path
// Owner: pure TUI (tool card diff highlighting)
#[test]
fn file_diff_body_highlights_rust_from_header_path() {
    // Theme is process-global; hold the lock so a parallel scheme test cannot
    // inject row-wash backgrounds into exact style comparisons.
    let _guard = crate::tui::theme::theme_test_lock();
    Theme::apply_committed("terminal");
    let card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileDiff,
        ToolHeader::call("write", Some("src/lib.rs".into())),
    )
    .with_body(ToolBody::Diff(vec![DiffRow::new(
        DiffRowKind::Added,
        Some(1),
        "let answer = 42; // note",
    )]));

    let mut lines = Vec::new();
    push_tool_card(
        &mut lines, &card, /*width*/ 80, /*max_tool_output_lines*/ 32,
        /*expanded*/ true,
    );
    let body = lines
        .iter()
        .find(|line| line.spans.iter().any(|span| span.content.contains("let")))
        .expect("diff body row");

    assert!(
        body.spans.iter().any(|span| {
            span.content.contains("let") && span.style == Theme::syntax(SyntaxRole::Keyword)
        }),
        "expected keyword highlight in spans: {:?}",
        body.spans
            .iter()
            .map(|s| (s.content.as_ref(), s.style))
            .collect::<Vec<_>>()
    );
    assert!(
        body.spans.iter().any(|span| {
            span.content.contains('+')
                && span.style == Theme::tool_diff_chrome(DiffRowKind::Added).sign
        }),
        "expected add sign style: {:?}",
        body.spans
            .iter()
            .map(|s| (s.content.as_ref(), s.style))
            .collect::<Vec<_>>()
    );
}

// Covers: wash reaches number/content/pad; sign uses chrome.sign; context clear
// Owner: pure TUI (tool card diff layout). Chrome mapping lives in theme_tests.
#[test]
fn file_diff_rows_apply_soft_wash_with_fg_signs() {
    let _guard = crate::tui::theme::theme_test_lock();
    Theme::apply_committed("terminal");
    Theme::apply_committed("one-half-dark");

    let card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileDiff,
        ToolHeader::call("edit", Some("notes.txt".into())),
    )
    .with_body(ToolBody::Diff(vec![
        DiffRow::new(DiffRowKind::Removed, Some(1), "old_line();"),
        DiffRow::new(DiffRowKind::Added, Some(1), "new_line();"),
        DiffRow::new(DiffRowKind::Context, Some(2), "keep();"),
    ]));

    let mut lines = Vec::new();
    push_tool_card(
        &mut lines, &card, /*width*/ 80, /*max_tool_output_lines*/ 32,
        /*expanded*/ true,
    );

    let removed = lines
        .iter()
        .find(|line| {
            line.spans
                .iter()
                .any(|span| span.content.contains("old_line"))
        })
        .expect("removed row");
    let added = lines
        .iter()
        .find(|line| {
            line.spans
                .iter()
                .any(|span| span.content.contains("new_line"))
        })
        .expect("added row");
    let context = lines
        .iter()
        .find(|line| line.spans.iter().any(|span| span.content.contains("keep")))
        .expect("context row");

    let add = Theme::tool_diff_chrome(DiffRowKind::Added);
    let del = Theme::tool_diff_chrome(DiffRowKind::Removed);
    let add_wash = add.sign.bg.expect("add wash");
    let del_wash = del.sign.bg.expect("del wash");

    assert!(
        removed
            .spans
            .iter()
            .any(|span| span.content.as_ref() == "-" && span.style == del.sign),
        "removed sign: {:?}",
        removed.spans
    );
    assert!(
        added
            .spans
            .iter()
            .any(|span| span.content.as_ref() == "+" && span.style == add.sign),
        "added sign: {:?}",
        added.spans
    );
    assert!(
        removed.spans.iter().any(|span| {
            span.content.contains("old_line")
                && span.style.bg == Some(del_wash)
                && span.style.fg == Theme::text().fg
        }),
        "removed content wash: {:?}",
        removed.spans
    );
    assert!(
        added.spans.iter().any(|span| {
            span.content.contains("new_line")
                && span.style.bg == Some(add_wash)
                && span.style.fg == Theme::text().fg
        }),
        "added content wash: {:?}",
        added.spans
    );
    assert!(
        removed
            .spans
            .iter()
            .any(|span| span.content.contains('1') && span.style.bg == Some(del_wash)),
        "removed number wash: {:?}",
        removed.spans
    );
    assert!(
        added
            .spans
            .iter()
            .any(|span| span.content.contains('1') && span.style.bg == Some(add_wash)),
        "added number wash: {:?}",
        added.spans
    );
    assert!(
        context.spans.iter().all(|span| span.style.bg.is_none()),
        "context must not wash: {:?}",
        context.spans
    );

    Theme::apply_committed("terminal");
}

fn large_rust_diff_card(lines: usize) -> ToolCard {
    let rows = (1..=lines)
        .map(|i| {
            DiffRow::new(
                DiffRowKind::Added,
                Some(i as u32),
                format!("let value_{i} = {i}; // line {i}"),
            )
        })
        .collect();
    ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileDiff,
        ToolHeader::call("write", Some("src/big.rs".into())),
    )
    .with_body(ToolBody::Diff(rows))
}

// Covers: collapsed paint must not language-highlight the whole write body
// Owner: pure unit (tool card highlight budget)
#[test]
fn collapsed_diff_paint_highlights_only_budget_rows() {
    warm_syntax_set();
    let card = large_rust_diff_card(200);
    let budget = 10usize;

    reset_highlight_line_calls();
    let mut collapsed = Vec::new();
    push_tool_card(
        &mut collapsed,
        &card,
        /*width*/ 100,
        budget,
        /*expanded*/ false,
    );
    let collapsed_calls = take_highlight_line_calls();

    reset_highlight_line_calls();
    let mut expanded = Vec::new();
    push_tool_card(
        &mut expanded,
        &card,
        /*width*/ 100,
        budget,
        /*expanded*/ true,
    );
    let expanded_calls = take_highlight_line_calls();

    assert!(
        collapsed_calls <= budget + 2,
        "collapsed should paint ~budget lines, got {collapsed_calls}"
    );
    assert!(
        expanded_calls >= 150,
        "expanded should paint most of the body, got {expanded_calls}"
    );
    assert!(
        collapsed_calls * 5 < expanded_calls,
        "collapsed ({collapsed_calls}) should be much cheaper than expanded ({expanded_calls})"
    );
}

// Covers: toggle check must not run syntect
// Owner: pure unit (tool card toggle estimate)
#[test]
fn toggle_check_does_not_highlight() {
    warm_syntax_set();
    let card = large_rust_diff_card(120);
    reset_highlight_line_calls();
    assert!(card_is_toggleable(
        &card, /*width*/ 100, /*max_tool_output_lines*/ 10, /*expanded*/ false,
    ));
    assert_eq!(
        take_highlight_line_calls(),
        0,
        "toggle check must stay highlight-free"
    );
}

// Covers: grep body gets language roles and match overlay from match_pattern
// Owner: pure TUI (grep search highlight)
#[test]
fn grep_body_highlights_language_and_match() {
    let card = ToolCard::new(
        ToolStatus::Ok,
        ToolFamily::FileCommand,
        ToolHeader::call("grep", Some("answer, src".into())),
    )
    .with_match_pattern("answer")
    .with_body(ToolBody::Lines(vec![
        "src/lib.rs".into(),
        "1 | let answer = 42;".into(),
        "1 matches in 1 file".into(),
    ]));

    let mut lines = Vec::new();
    push_tool_card(
        &mut lines, &card, /*width*/ 80, /*max_tool_output_lines*/ 32,
        /*expanded*/ true,
    );
    let body = lines
        .iter()
        .find(|line| line.spans.iter().any(|span| span.content.contains("let")))
        .expect("grep content row");
    assert!(
        body.spans.iter().any(|span| {
            span.content.contains("let") && span.style == Theme::syntax(SyntaxRole::Keyword)
        }),
        "expected rust keyword: {:?}",
        body.spans
            .iter()
            .map(|s| (s.content.as_ref(), s.style))
            .collect::<Vec<_>>()
    );
    assert!(
        body.spans.iter().any(|span| {
            span.content.as_ref() == "answer" && span.style == Theme::search_match(Theme::text())
        }),
        "expected match overlay: {:?}",
        body.spans
            .iter()
            .map(|s| (s.content.as_ref(), s.style))
            .collect::<Vec<_>>()
    );
}

// Covers: running shell cards fold the live elapsed clock into the timeout fact
// Owner: pure unit (tool card elapsed rewrite)
#[test]
fn with_live_shell_elapsed_folds_clock_into_timeout_fact() {
    let started = std::time::Instant::now() - Duration::from_millis(1_200);
    let mut entry = ToolEntry {
        card: ToolCard::new(
            ToolStatus::Running,
            ToolFamily::FileCommand,
            ToolHeader::shell("$", Some("sleep 1".into())),
        ),
        expanded: false,
        image: None,
        started_at: Some(started),
    };
    entry
        .card
        .push_fact(ToolFact::Timeout { seconds: Some(30) });
    entry.card.push_fact(ToolFact::Timeout { seconds: None });

    let rewritten = with_live_shell_elapsed(&entry);
    assert!(
        matches!(&rewritten, Cow::Owned(_)),
        "running shell must rewrite the card"
    );
    assert_eq!(
        rewritten.facts,
        vec![
            ToolFact::Meta {
                text: "timeout 30s · 1.2s".into()
            },
            ToolFact::Meta {
                text: "timeout none · 1.2s".into()
            },
        ]
    );
}

// Covers: finished, non-shell, and clockless entries keep their card untouched
// Owner: pure unit (tool card elapsed rewrite)
#[test]
fn with_live_shell_elapsed_borrows_when_no_live_clock() {
    let cases = [
        (
            "finished shell",
            ToolStatus::Ok,
            ToolHeader::shell("$", Some("true".into())),
            Some(std::time::Instant::now()),
        ),
        (
            "non-shell running",
            ToolStatus::Running,
            ToolHeader::call("read_file", Some("a.rs".into())),
            Some(std::time::Instant::now()),
        ),
        (
            "running shell without clock",
            ToolStatus::Running,
            ToolHeader::shell("$", Some("sleep 1".into())),
            None,
        ),
    ];
    for (label, status, header, started_at) in cases {
        let entry = ToolEntry {
            card: ToolCard::new(status, ToolFamily::FileCommand, header),
            expanded: false,
            image: None,
            started_at,
        };
        assert!(
            matches!(with_live_shell_elapsed(&entry), Cow::Borrowed(_)),
            "{label} must borrow the card unchanged"
        );
    }
}

// Covers: only running shell cards expose a live elapsed clock
// Owner: pure unit (tool entry elapsed gate)
#[test]
fn live_shell_elapsed_requires_shell_header_and_running_status() {
    let started = std::time::Instant::now() - Duration::from_millis(250);
    let mut entry = ToolEntry {
        card: ToolCard::new(
            ToolStatus::Running,
            ToolFamily::FileCommand,
            ToolHeader::shell("$", Some("sleep 1".into())),
        ),
        expanded: false,
        image: None,
        started_at: Some(started),
    };
    assert!(live_shell_elapsed(&entry).is_some());

    entry.card.status = ToolStatus::Ok;
    assert!(live_shell_elapsed(&entry).is_none());

    entry.card.status = ToolStatus::Error;
    assert!(live_shell_elapsed(&entry).is_none());

    entry.card.status = ToolStatus::Running;
    entry.card.header = ToolHeader::call("read_file", Some("a.rs".into()));
    assert!(live_shell_elapsed(&entry).is_none());
}