rho-coding-agent 1.18.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
//! Multi-span Call + Children rendering for structured tool cards.

use ratatui::{
    style::Style,
    text::{Line, Span},
};
use rho_tools::tool_card::{
    DiffRow, DiffRowKind, ToolBody, ToolCard, ToolFact, ToolHeader, ToolStatus,
};
use unicode_width::UnicodeWidthStr;

use super::{
    feed_image::reserve_optional_image_rows,
    render::{
        display_width, pad_entry_line, padded_inner_width, push_wrapped_text, slice_spans_by_bytes,
        spans_display_width, styled_blank_line, wrap_line_at_whitespace_ranges, wrap_line_hard,
        wrap_spans_hard, LineFill,
    },
    theme::Theme,
    tool_diff, ToolEntry,
};

const TREE_INDENT: &str = "  ";
const TREE_BRANCH_MID: &str = "├ ";
const TREE_BRANCH_END: &str = "â”” ";
const TREE_CONTINUE: &str = "  ";
/// Vertical stem on wrapped header rows; same box-drawing family as ├ / └.
const HEADER_WRAP_STEM: &str = "  │ ";
/// Content column after `  ├ ` / `  └ `.
const CHILD_CONTENT_INDENT: &str = "    ";

pub(super) fn tool_entry_lines(
    tool: &ToolEntry,
    width: usize,
    max_tool_output_lines: usize,
) -> Vec<Line<'static>> {
    let inner_width = padded_inner_width(width);
    let mut lines = Vec::new();
    push_tool_card(
        &mut lines,
        &tool.card,
        inner_width,
        max_tool_output_lines,
        tool.expanded,
    );
    reserve_optional_image_rows(&mut lines, tool.image.as_ref(), width);
    // One trailing spacer only. Prior entries own the blank above this card.
    let padding_style = Theme::tool_card_padding();
    let mut padded = Vec::with_capacity(lines.len() + 1);
    padded.extend(lines.into_iter().map(pad_entry_line));
    padded.push(styled_blank_line(width, padding_style));
    padded
}

pub(super) fn push_tool_card(
    lines: &mut Vec<Line<'static>>,
    card: &ToolCard,
    width: usize,
    max_tool_output_lines: usize,
    expanded: bool,
) {
    push_header_line(lines, card, card.status, width);

    let budget = max_tool_output_lines.max(1);
    let children = render_child_groups(card, width);
    let total_rows: usize = children.iter().map(Vec::len).sum();
    let show_collapse_prompt = expanded && total_rows > budget;
    let mut remaining = if expanded { usize::MAX } else { budget };
    let mut hidden_rows = 0usize;
    let mut emitted = Vec::new();

    for group in children {
        if remaining == 0 {
            hidden_rows = hidden_rows.saturating_add(group.len());
            continue;
        }
        if group.len() <= remaining {
            remaining = remaining.saturating_sub(group.len());
            emitted.push(group);
            continue;
        }
        // Clip a wrapping child to the remaining terminal-row budget.
        hidden_rows = hidden_rows.saturating_add(group.len() - remaining);
        let mut clipped = group;
        clipped.truncate(remaining);
        remaining = 0;
        if !clipped.is_empty() {
            emitted.push(clipped);
        }
    }

    let show_expand_prompt = !expanded && hidden_rows > 0;
    let has_prompt = show_expand_prompt || show_collapse_prompt;
    let last_child = emitted.len().saturating_sub(1);
    for (index, group) in emitted.into_iter().enumerate() {
        let is_last_child = index == last_child && !has_prompt;
        for (row_index, mut row) in group.into_iter().enumerate() {
            if row_index == 0 {
                rewrite_fact_branch(&mut row, is_last_child);
            }
            lines.push(row);
        }
    }

    if show_expand_prompt {
        let prompt = format!("... {hidden_rows} more lines, ctrl+o to expand");
        push_wrapped_text(lines, &prompt, width, Theme::dim(), LineFill::PadToWidth);
    } else if show_collapse_prompt {
        push_wrapped_text(
            lines,
            "ctrl+o to collapse",
            width,
            Theme::dim(),
            LineFill::PadToWidth,
        );
    }
}

/// Whether ctrl+o / click should toggle this tool at the given terminal width.
pub(super) fn card_is_toggleable(
    card: &ToolCard,
    width: usize,
    max_tool_output_lines: usize,
    _expanded: bool,
) -> bool {
    let budget = max_tool_output_lines.max(1);
    let total_rows: usize = render_child_groups(card, width).iter().map(Vec::len).sum();
    total_rows > budget
}

/// Render each fact/body item into its full terminal-row group at `width`.
fn render_child_groups(card: &ToolCard, width: usize) -> Vec<Vec<Line<'static>>> {
    let mut groups = Vec::new();
    for fact in &card.facts {
        // Branch glyph is rewritten after budget clipping once last-child is known.
        let mut lines = Vec::new();
        push_fact_line(&mut lines, fact, /*is_last*/ false, width);
        groups.push(lines);
    }
    match &card.body {
        ToolBody::None => {}
        ToolBody::Lines(body) => {
            for line in tool_diff::logical_lines(body) {
                let mut lines = Vec::new();
                push_body_line(&mut lines, &line, width, Theme::text());
                groups.push(lines);
            }
        }
        ToolBody::Diff(rows) => {
            let gutter = tool_diff::gutter_width(rows);
            for row in rows {
                let mut lines = Vec::new();
                push_diff_row(&mut lines, row, gutter, width);
                groups.push(lines);
            }
        }
    }
    groups
}

/// Facts draw ├ by default; the final visible fact becomes └ when it is last.
fn rewrite_fact_branch(line: &mut Line<'static>, is_last: bool) {
    let Some(first) = line.spans.first_mut() else {
        return;
    };
    let content = first.content.as_ref();
    let mid = format!("{TREE_INDENT}{TREE_BRANCH_MID}");
    let end = format!("{TREE_INDENT}{TREE_BRANCH_END}");
    if content.starts_with(&mid) || content.starts_with(&end) {
        let suffix = &content[mid.len().min(content.len())..];
        first.content = format!(
            "{}{suffix}",
            if is_last {
                format!("{TREE_INDENT}{TREE_BRANCH_END}")
            } else {
                format!("{TREE_INDENT}{TREE_BRANCH_MID}")
            }
        )
        .into();
    }
}

fn push_header_line(
    lines: &mut Vec<Line<'static>>,
    card: &ToolCard,
    status: ToolStatus,
    width: usize,
) {
    // Marker stays on the first row only. Primary/command/detail may wrap with a
    // hang under the fixed prefix so long streamed args stay visible (main used
    // to hard-wrap whole tool lines; a single clipped header hides the tail).
    let marker = Span::styled(format!("{} ", status.marker()), Theme::tool_marker(status));
    match &card.header {
        ToolHeader::Call { verb, primary } => {
            let mut prefix = vec![
                marker,
                Span::styled(verb.clone(), Theme::tool_verb(card.family)),
            ];
            match primary.as_ref().filter(|primary| !primary.is_empty()) {
                Some(primary) => {
                    prefix.push(Span::styled("(", Theme::tool_primary()));
                    let wrappable = vec![
                        Span::styled(primary.clone(), Theme::tool_primary()),
                        Span::styled(")", Theme::tool_primary()),
                    ];
                    push_wrapped_header(lines, prefix, wrappable, width);
                }
                None => lines.push(pad_spans_line(prefix, width)),
            }
        }
        ToolHeader::Shell { prompt, command } => {
            let mut prefix = vec![
                marker,
                Span::styled(prompt.clone(), Theme::tool_verb(card.family)),
            ];
            match command.as_ref().filter(|command| !command.is_empty()) {
                Some(command) => {
                    prefix.push(Span::raw(" "));
                    let wrappable = vec![Span::styled(command.clone(), Theme::tool_primary())];
                    push_wrapped_header(lines, prefix, wrappable, width);
                }
                None => lines.push(pad_spans_line(prefix, width)),
            }
        }
        ToolHeader::StatusFirst { identity, detail } => {
            let mut prefix = vec![
                marker,
                Span::styled(identity.clone(), Theme::tool_verb(card.family)),
            ];
            if detail.is_empty() {
                lines.push(pad_spans_line(prefix, width));
            } else {
                prefix.push(Span::raw("  "));
                let wrappable = vec![Span::styled(detail.clone(), Theme::text())];
                push_wrapped_header(lines, prefix, wrappable, width);
            }
        }
    }
}

/// Wrap header primary/command under a fixed first-line prefix.
///
/// Continuations draw a tree-column `|` elbow, then pad to the primary hang so
/// children (`├` / `└`) still read as a connected trunk under the call.
fn push_wrapped_header(
    lines: &mut Vec<Line<'static>>,
    prefix: Vec<Span<'static>>,
    wrappable: Vec<Span<'static>>,
    width: usize,
) {
    let hang = spans_display_width(&prefix);
    if hang >= width {
        // Pathological narrow width: fall back to a single padded row.
        let mut spans = prefix;
        spans.extend(wrappable);
        lines.push(pad_spans_line(spans, width));
        return;
    }
    let content_width = (width - hang).max(1);
    let text: String = wrappable.iter().map(|span| span.content.as_ref()).collect();
    if text.is_empty() {
        lines.push(pad_spans_line(prefix, width));
        return;
    }

    let ranges = wrap_line_at_whitespace_ranges(&text, content_width);
    for (index, range) in ranges.into_iter().enumerate() {
        let mut start = range.start;
        let end = range.end;
        if index > 0 {
            // Keep hang indent stable when a wrap boundary leaves leading spaces.
            while start < end {
                let ch = text[start..].chars().next().expect("start < end");
                if !ch.is_whitespace() {
                    break;
                }
                start += ch.len_utf8();
            }
            if start >= end {
                continue;
            }
        }
        let chunk_spans = slice_spans_by_bytes(&wrappable, start, end);
        let mut row = if index == 0 {
            prefix.clone()
        } else {
            header_wrap_continuation_prefix(hang)
        };
        row.extend(chunk_spans);
        lines.push(pad_spans_line(row, width));
    }
}

/// `  │ ` in the child elbow column, then spaces out to the primary hang.
fn header_wrap_continuation_prefix(hang: usize) -> Vec<Span<'static>> {
    let stem_width = display_width(HEADER_WRAP_STEM);
    let mut spans = vec![Span::styled(
        HEADER_WRAP_STEM.to_string(),
        Theme::tool_tree(),
    )];
    if hang > stem_width {
        spans.push(Span::styled(" ".repeat(hang - stem_width), Theme::text()));
    }
    spans
}

fn push_fact_line(lines: &mut Vec<Line<'static>>, fact: &ToolFact, is_last: bool, width: usize) {
    let branch = if is_last {
        TREE_BRANCH_END
    } else {
        TREE_BRANCH_MID
    };
    let prefix = format!("{TREE_INDENT}{branch}");
    let prefix_width = display_width(&prefix);
    let content_width = width.saturating_sub(prefix_width).max(1);
    let wrapped = wrap_spans_hard(&fact_spans(fact), content_width);

    // First line uses tree branch; continuations align to the content column.
    let mut first_line = vec![Span::styled(prefix, Theme::tool_tree())];
    first_line.extend(wrapped[0].clone());
    lines.push(pad_spans_line(first_line, width));

    for row in wrapped.iter().skip(1) {
        let mut continuation = vec![Span::styled(
            format!("{TREE_INDENT}{TREE_CONTINUE}"),
            Theme::tool_tree(),
        )];
        continuation.extend(row.clone());
        lines.push(pad_spans_line(continuation, width));
    }
}

fn fact_spans(fact: &ToolFact) -> Vec<Span<'static>> {
    match fact {
        ToolFact::DiffStat {
            added,
            removed,
            path,
        } => {
            let mut spans = vec![
                Span::styled(format!("+{added}"), Theme::tool_stat_add()),
                Span::raw(" "),
                Span::styled(format!("-{removed}"), Theme::tool_stat_del()),
                Span::styled(" lines", Theme::tool_meta()),
            ];
            if let Some(path) = path.as_ref().filter(|path| !path.is_empty()) {
                spans.push(Span::styled(" | ", Theme::tool_meta()));
                spans.push(Span::styled(path.clone(), Theme::tool_path()));
            }
            spans
        }
        ToolFact::Exit { code, duration_ms } => {
            let status = if *code == 0 {
                ToolStatus::Ok
            } else {
                ToolStatus::Error
            };
            let mut spans = vec![Span::styled(
                format!("exit {code}"),
                Theme::tool_exit(status),
            )];
            if let Some(ms) = duration_ms {
                let secs = *ms as f64 / 1000.0;
                spans.push(Span::styled(format!(" · {secs:.1}s"), Theme::tool_meta()));
            }
            spans
        }
        ToolFact::Count {
            label,
            value,
            detail,
        } => {
            let mut text = format!("{value} {label}");
            if let Some(detail) = detail.as_ref().filter(|detail| !detail.is_empty()) {
                text.push(' ');
                text.push_str(detail);
            }
            vec![Span::styled(text, Theme::text())]
        }
        ToolFact::Meta { text } => vec![Span::styled(text.clone(), Theme::tool_meta())],
        ToolFact::Error { text } => vec![Span::styled(text.clone(), Theme::tool_error_text())],
        ToolFact::Progress { completed, total } => {
            let text = match total {
                Some(total) => format!("{completed}/{total}"),
                None => format!("{completed}"),
            };
            vec![Span::styled(text, Theme::tool_meta())]
        }
        ToolFact::Text { text } => vec![Span::styled(text.clone(), Theme::text())],
    }
}

/// Draw one diff row as `<indent><line no> <sign> <text>`.
///
/// The number gutter and sign column are fixed, so wrapped text hangs under the
/// text column and added/removed rows stay distinguishable without color.
fn push_diff_row(lines: &mut Vec<Line<'static>>, row: &DiffRow, gutter: usize, width: usize) {
    if row.kind == DiffRowKind::File {
        push_body_line(lines, &row.text, width, Theme::tool_path());
        return;
    }

    // Unnumbered bodies (patch text without hunk headers) drop the gutter and
    // its separator so the sign column sits right under the tree indent.
    let number = match (gutter, row.line) {
        (0, _) => String::new(),
        (_, Some(line)) => format!("{line:>gutter$} "),
        (_, None) => " ".repeat(gutter + 1),
    };
    let sign = format!("{} ", row.kind.sign());
    let prefix_width = display_width(CHILD_CONTENT_INDENT) + display_width(&number) + sign.len();
    let content_width = width.saturating_sub(prefix_width).max(1);
    let text_style = Theme::tool_diff_text(row.kind);

    let mut chunks = wrap_line_hard(&row.text, content_width);
    if chunks.is_empty() {
        chunks.push(String::new());
    }
    for (index, chunk) in chunks.into_iter().enumerate() {
        let mut spans = if index == 0 {
            vec![
                Span::styled(
                    format!("{CHILD_CONTENT_INDENT}{number}"),
                    Theme::tool_diff_gutter(),
                ),
                Span::styled(sign.clone(), text_style),
            ]
        } else {
            vec![Span::styled(" ".repeat(prefix_width), Theme::tool_tree())]
        };
        spans.push(Span::styled(chunk, text_style));
        lines.push(pad_spans_line(spans, width));
    }
}

fn push_body_line(lines: &mut Vec<Line<'static>>, line: &str, width: usize, style: Style) {
    // Indent body under the tree content column.
    let prefix = CHILD_CONTENT_INDENT;
    let prefix_width = display_width(prefix);
    let content_width = width.saturating_sub(prefix_width).max(1);
    let chunks = wrap_line_hard(line, content_width);
    if chunks.is_empty() {
        lines.push(pad_spans_line(
            vec![
                Span::styled(prefix.to_string(), Theme::tool_tree()),
                Span::styled(String::new(), style),
            ],
            width,
        ));
        return;
    }
    for chunk in chunks {
        lines.push(pad_spans_line(
            vec![
                Span::styled(prefix.to_string(), Theme::tool_tree()),
                Span::styled(chunk, style),
            ],
            width,
        ));
    }
}

fn pad_spans_line(mut spans: Vec<Span<'static>>, width: usize) -> Line<'static> {
    let used = spans
        .iter()
        .map(|span| UnicodeWidthStr::width(span.content.as_ref()))
        .sum::<usize>();
    if used < width {
        spans.push(Span::styled(" ".repeat(width - used), Theme::text()));
    }
    Line::from(spans)
}

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