rho-coding-agent 1.48.0

A lightweight agent harness inspired by Pi
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
use ratatui::{
    style::Style,
    text::{Line, Span},
};

mod code_fence;
mod heading;
mod inline;
mod math;
mod mermaid;
mod panel;
mod stream;
mod table;
mod txm;

#[cfg(test)]
pub(crate) use mermaid::PHASE_CHAIN_FLOWCHART;

use code_fence::mermaid_opening_fence;
pub(in crate::tui) use code_fence::{
    is_closing_fence, opening_fence_info_token, parse_opening_fence, update_code_block_state,
    CodeFence, CodeFenceState,
};

use super::markdown_image::standalone_markdown_image;
use super::syntax::BlockHighlighter;
use inline::{inline_markdown_stable_prefix_len, markdown_inline_segments, markdown_inline_text};
use panel::ClosedPanel;

pub(in crate::tui) use heading::HeadingLevel;
use heading::{heading_stream_state, parse_atx_heading, HeadingStreamState};
pub(super) use stream::{incremental_markdown_tail_start, markdown_stream_bounds};
pub(in crate::tui) use table::{streaming_table, streaming_table_bottom_border, StreamingTable};

#[cfg(test)]
#[path = "markdown/table_tests.rs"]
mod table_tests;

use super::{
    render::{
        char_display_width, display_width, hard_wrap_styled_spans, slice_spans_by_bytes,
        soft_wrap_visible_ranges, truncate_to_display_width,
        wrap_line_at_whitespace_ranges_with_protected_prefix,
    },
    theme::Theme,
};

pub(super) fn push_wrapped_markdown_without_copy_button_from_fence_state(
    lines: &mut Vec<Line<'static>>,
    text: &str,
    width: usize,
    state: &mut CodeFenceState,
) {
    lines.extend(
        render_markdown_from_fence_state(text, width, state, CodeBlockCopyButton::Hidden).lines,
    );
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum CodeBlockCopyButton {
    Visible,
    Hidden,
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub(super) struct MarkdownCodeBlock {
    pub(super) top_line: usize,
    pub(super) copy_columns: std::ops::Range<usize>,
    pub(super) text: String,
}

pub(super) struct RenderedMarkdown {
    pub(super) lines: Vec<Line<'static>>,
    pub(super) code_blocks: Vec<MarkdownCodeBlock>,
    /// Standalone `![alt](path)` references, in source order.
    pub(super) image_sources: Vec<super::markdown_image::MarkdownImageSource>,
    /// Rendered fallback rows corresponding to `image_sources`.
    pub(super) image_rows: Vec<usize>,
}

/// Render-local open fenced block: fence marker, optional highlighter, and
/// optional copy-button capture. Open/close is a single state transition.
struct ActiveBlock<'a> {
    fence: CodeFence,
    highlighter: Option<BlockHighlighter>,
    copy: Option<ActiveCopyCapture<'a>>,
}

struct ActiveCopyCapture<'a> {
    top_line: usize,
    copy_columns: std::ops::Range<usize>,
    content: Vec<&'a str>,
}

pub(super) fn markdown_lines(
    text: &str,
    width: usize,
    state: &mut CodeFenceState,
) -> Vec<Line<'static>> {
    render_markdown(text, width, state).lines
}

pub(super) fn render_markdown(
    text: &str,
    width: usize,
    state: &mut CodeFenceState,
) -> RenderedMarkdown {
    render_markdown_from_fence_state(text, width, state, CodeBlockCopyButton::Visible)
}

fn render_markdown_from_fence_state(
    text: &str,
    width: usize,
    state: &mut CodeFenceState,
    copy_button: CodeBlockCopyButton,
) -> RenderedMarkdown {
    let width = width.max(1);
    let mut lines = Vec::new();
    let mut code_blocks = Vec::new();
    let mut image_sources = Vec::new();
    let mut image_rows = Vec::new();
    // Continue an open fence from a prior chunk (live preview). No header row:
    // that belongs to the opening line already committed above. Reuse the
    // stored highlighter so multi-line tokens keep their lexical state.
    let mut active = state.active.map(|fence| ActiveBlock {
        fence,
        highlighter: state.highlighter.take(),
        copy: None,
    });

    let raw_lines = text.lines().collect::<Vec<_>>();
    let mut line_index = 0;
    while line_index < raw_lines.len() {
        let raw_line = raw_lines[line_index];
        if active.is_none() {
            if let Some(opening) = mermaid_opening_fence(raw_line) {
                if let Some(closing_offset) = raw_lines[line_index + 1..]
                    .iter()
                    .position(|line| is_closing_fence(line, opening.fence))
                {
                    let closing_index = line_index + 1 + closing_offset;
                    let source = raw_lines[line_index + 1..closing_index].join("\n");
                    let panel = mermaid::render_closed_fence(source, width);
                    push_closed_panel(&mut lines, &mut code_blocks, copy_button, width, panel);
                    line_index = closing_index + 1;
                    continue;
                }
            }
            if let Some((source, consumed_lines)) =
                math::take_closed_display_math(&raw_lines[line_index..])
            {
                let panel = math::render_closed_display_math(source, width);
                push_closed_panel(&mut lines, &mut code_blocks, copy_button, width, panel);
                line_index += consumed_lines;
                continue;
            }
        }
        let opening_fence = active
            .is_none()
            .then(|| parse_opening_fence(raw_line))
            .flatten();
        let closing_fence = active
            .as_ref()
            .is_some_and(|block| is_closing_fence(raw_line, block.fence));
        if opening_fence.is_some() || closing_fence {
            if closing_fence {
                if let Some(ActiveBlock {
                    copy: Some(capture),
                    ..
                }) = active.take()
                {
                    code_blocks.push(MarkdownCodeBlock {
                        top_line: capture.top_line,
                        copy_columns: capture.copy_columns,
                        text: capture.content.join("\n"),
                    });
                } else {
                    active = None;
                }
                state.clear_open();
            } else {
                let fence = opening_fence.expect("opening branch");
                let language = opening_fence_info_token(raw_line);
                let label = language.as_deref().map(str::to_ascii_uppercase);
                let top_line = lines.len();
                lines.push(code_block_header(width, label.as_deref(), copy_button));
                let copy = (copy_button == CodeBlockCopyButton::Visible)
                    .then(|| code_block_copy_columns(width))
                    .flatten()
                    .map(|copy_columns| ActiveCopyCapture {
                        top_line,
                        copy_columns,
                        content: Vec::new(),
                    });
                // Seed language/active; take the highlighter onto the render-local
                // block so body lines advance one shared ParseState.
                state.open_fence(fence, language);
                let highlighter = state.highlighter.take();
                active = Some(ActiveBlock {
                    fence,
                    highlighter,
                    copy,
                });
            }
            line_index += 1;
            continue;
        }

        if let Some(block) = &mut active {
            if let Some(capture) = &mut block.copy {
                capture.content.push(raw_line);
            }
            let plain = Theme::code_text();
            let segments = match &mut block.highlighter {
                Some(highlighter) => highlighter
                    .highlight_line(raw_line)
                    .into_iter()
                    .map(|segment| {
                        let style = segment.style(plain);
                        StyledSegment::new(segment.text, style)
                    })
                    .collect(),
                None => vec![StyledSegment::new(raw_line.to_string(), plain)],
            };
            lines.extend(wrap_styled_segments_hard(&segments, width));
            line_index += 1;
            continue;
        }

        if let Some((table_lines, consumed_lines)) =
            table::markdown_table_lines(&raw_lines[line_index..], width)
        {
            lines.extend(table_lines);
            line_index += consumed_lines;
            continue;
        }

        if let Some(heading) = parse_atx_heading(raw_line) {
            lines.extend(markdown_heading_lines(heading, width));
            line_index += 1;
            continue;
        }

        if is_markdown_divider(raw_line) {
            lines.push(markdown_divider(width));
            line_index += 1;
            continue;
        }

        if let Some(image) = standalone_markdown_image(raw_line) {
            image_rows.push(lines.len());
            let fallback = if image.alt.is_empty() {
                format!("[image: {}]", image.path)
            } else {
                format!("[image: {}]", image.alt)
            };
            lines.push(Line::styled(fallback, Theme::markdown_link()));
            image_sources.push(image);
            line_index += 1;
            continue;
        }

        lines.extend(wrap_styled_segments(
            &markdown_inline_segments(raw_line),
            width,
        ));
        line_index += 1;
    }

    // Persist highlighter lexical state when the fence stays open across chunks.
    match active {
        Some(ActiveBlock {
            highlighter,
            copy: Some(capture),
            ..
        }) => {
            state.highlighter = highlighter;
            code_blocks.push(MarkdownCodeBlock {
                top_line: capture.top_line,
                copy_columns: capture.copy_columns,
                text: capture.content.join("\n"),
            });
        }
        Some(ActiveBlock { highlighter, .. }) => {
            state.highlighter = highlighter;
        }
        None => {
            // Closed path already cleared state; leave highlighter unset.
        }
    }

    if lines.is_empty() && text.is_empty() {
        lines.push(Line::from(Span::styled(String::new(), Theme::text())));
    }

    RenderedMarkdown {
        lines,
        code_blocks,
        image_sources,
        image_rows,
    }
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct StyledSegment {
    text: String,
    style: Style,
}

impl StyledSegment {
    fn new(text: String, style: Style) -> Self {
        Self { text, style }
    }
}

fn is_markdown_divider(line: &str) -> bool {
    let trimmed = line.trim();
    let mut chars = trimmed.chars().filter(|ch| !ch.is_whitespace());
    let Some(marker) = chars.next() else {
        return false;
    };
    matches!(marker, '-' | '*' | '_')
        && trimmed.chars().filter(|ch| !ch.is_whitespace()).count() >= 3
        && chars.all(|ch| ch == marker)
}

fn markdown_divider(width: usize) -> Line<'static> {
    Line::from(Span::styled("─".repeat(width.max(1)), Theme::dim()))
}

/// Emit a closed art panel (mermaid, display math) with header and copy state.
fn push_closed_panel(
    lines: &mut Vec<Line<'static>>,
    code_blocks: &mut Vec<MarkdownCodeBlock>,
    copy_button: CodeBlockCopyButton,
    width: usize,
    panel: ClosedPanel,
) {
    let top_line = lines.len();
    let (title, body, source) = match panel {
        ClosedPanel::Art {
            title,
            lines: art,
            source,
        } => (title, panel::panel_lines(art, width), source),
        ClosedPanel::SourceFallback { title, source } => {
            let mut body = Vec::new();
            let plain = Theme::code_text();
            for content_line in source.lines() {
                let segments = vec![StyledSegment::new(content_line.to_string(), plain)];
                body.extend(wrap_styled_segments_hard(&segments, width));
            }
            if body.is_empty() {
                body.extend(wrap_styled_segments_hard(
                    &[StyledSegment::new(String::new(), plain)],
                    width,
                ));
            }
            (title, body, source)
        }
    };
    lines.push(code_block_header(width, Some(title), copy_button));
    lines.extend(body);
    push_copyable_code_block(code_blocks, copy_button, top_line, width, source);
}

fn push_copyable_code_block(
    code_blocks: &mut Vec<MarkdownCodeBlock>,
    copy_button: CodeBlockCopyButton,
    top_line: usize,
    width: usize,
    text: String,
) {
    if copy_button != CodeBlockCopyButton::Visible {
        return;
    }
    if let Some(copy_columns) = code_block_copy_columns(width) {
        code_blocks.push(MarkdownCodeBlock {
            top_line,
            copy_columns,
            text,
        });
    }
}

/// Slim header row above a code block or art panel: dim label on the left,
/// COPY right-aligned at the geometry [`code_block_copy_columns`] promises to
/// hit-testing. Always one row, even with no label and a hidden button, so
/// block line counts stay uniform.
fn code_block_header(
    width: usize,
    label: Option<&str>,
    copy_button: CodeBlockCopyButton,
) -> Line<'static> {
    let width = width.max(1);
    let copy_columns = (copy_button == CodeBlockCopyButton::Visible)
        .then(|| code_block_copy_columns(width))
        .flatten();
    let copy_label = copy_columns
        .as_ref()
        .and_then(|_| code_block_copy_label(width));
    // Keep at least one blank column between the label and COPY.
    let label_budget = copy_columns
        .as_ref()
        .map_or(width, |columns| columns.start.saturating_sub(1));
    let label = truncate_to_display_width(label.unwrap_or_default(), label_budget);
    let mut spans = Vec::new();
    if let Some(columns) = &copy_columns {
        let filler = columns.start.saturating_sub(display_width(&label));
        spans.push(Span::styled(
            format!("{label}{}", " ".repeat(filler)),
            Theme::dim(),
        ));
    } else {
        spans.push(Span::styled(label.into_owned(), Theme::dim()));
    }
    if let Some(copy_label) = copy_label {
        spans.push(Span::styled(
            copy_label,
            Theme::markdown_code_copy_button(/*hovered*/ false),
        ));
    }
    Line::from(spans)
}

fn code_block_copy_label(width: usize) -> Option<&'static str> {
    if width >= 9 {
        Some(" COPY ")
    } else if width >= 6 {
        Some("COPY")
    } else {
        None
    }
}

pub(in crate::tui) fn code_block_copy_columns(width: usize) -> Option<std::ops::Range<usize>> {
    let label_width = display_width(code_block_copy_label(width)?);
    let start = width.saturating_sub(label_width + 1);
    Some(start..start + label_width)
}

/// Hard-wrap highlighted segments at display-width columns, preserving span
/// styles across breaks. Code needs hard wrapping; [`wrap_styled_segments`]
/// soft-wraps at whitespace and would reflow source lines.
fn wrap_styled_segments_hard(segments: &[StyledSegment], width: usize) -> Vec<Line<'static>> {
    let text = segments
        .iter()
        .map(|segment| segment.text.as_str())
        .collect::<String>();
    let spans = segments
        .iter()
        .map(|segment| Span::styled(segment.text.clone(), segment.style))
        .collect::<Vec<_>>();
    let empty_style = segments
        .first()
        .map(|segment| segment.style)
        .unwrap_or_else(Theme::code_text);
    hard_wrap_styled_spans(&text, &spans, width, empty_style)
        .into_iter()
        .map(Line::from)
        .collect()
}

fn markdown_heading_lines(heading: heading::AtxHeading<'_>, width: usize) -> Vec<Line<'static>> {
    let heading_style = Theme::markdown_heading(heading.level);
    if heading.content.is_empty() {
        return vec![Line::from(Span::styled(String::new(), heading_style))];
    }

    let segments = markdown_inline_segments(heading.content)
        .into_iter()
        .map(|segment| StyledSegment::new(segment.text, heading_style.patch(segment.style)))
        .collect::<Vec<_>>();
    wrap_styled_segments(&segments, width)
}

fn wrap_markdown_line_ranges(line: &str, width: usize) -> Vec<std::ops::Range<usize>> {
    let protected_prefix_end = markdown_list_body_start(line).unwrap_or_default();
    wrap_line_at_whitespace_ranges_with_protected_prefix(line, width, protected_prefix_end)
}

fn markdown_list_body_start(line: &str) -> Option<usize> {
    let trimmed = line.trim_start_matches(char::is_whitespace);
    let leading_whitespace_len = line.len() - trimmed.len();
    let marker_len = trimmed.find(char::is_whitespace)?;
    let marker = &trimmed[..marker_len];
    let is_list_marker = matches!(marker, "-" | "+" | "*")
        || marker.strip_suffix(['.', ')']).is_some_and(|digits| {
            (1..=9).contains(&digits.len()) && digits.bytes().all(|byte| byte.is_ascii_digit())
        });
    if !is_list_marker {
        return None;
    }

    let separator_len = trimmed[marker_len..]
        .chars()
        .take_while(|ch| ch.is_whitespace())
        .map(char::len_utf8)
        .sum::<usize>();
    let body_start = leading_whitespace_len + marker_len + separator_len;
    (body_start < line.len()).then_some(body_start)
}

fn wrap_styled_segments(segments: &[StyledSegment], width: usize) -> Vec<Line<'static>> {
    let text = segments
        .iter()
        .map(|segment| segment.text.as_str())
        .collect::<String>();
    let spans = segments
        .iter()
        .map(|segment| Span::styled(segment.text.clone(), segment.style))
        .collect::<Vec<_>>();

    let lines = soft_wrap_visible_ranges(&text, wrap_markdown_line_ranges(&text, width))
        .map(|range| {
            let chunk = slice_spans_by_bytes(&spans, range.start, range.end);
            if chunk.is_empty() {
                // Preserve an empty content row so underline/style state does not
                // leak from adjacent lines when a wrap yields no visible glyphs.
                Line::from(Span::styled(
                    String::new(),
                    Style::default().remove_modifier(ratatui::style::Modifier::UNDERLINED),
                ))
            } else {
                Line::from(chunk)
            }
        })
        .collect::<Vec<_>>();

    if lines.is_empty() {
        vec![Line::from(Span::styled(
            String::new(),
            Style::default().remove_modifier(ratatui::style::Modifier::UNDERLINED),
        ))]
    } else {
        lines
    }
}

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