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
//! Minimal mode: the transcript scrolls into the terminal's own scrollback.
//!
//! Frames still fill the main screen, with history pinned to the bottom of
//! its pane. Before a frame scrolls committed rows off the top of the pane,
//! [`App::paint`] writes them into scrollback, oldest first, and repaints the
//! screen. From then on the terminal owns those rows: native wheel
//! scrolling, selection, and search reach them, and Rho never redraws them.
//! Live rows (stream previews, running tools) are never written. A committed
//! entry that changes later, such as a reasoning entry gaining its "Thought
//! for" line, changes only the rows still on screen.
//!
//! The feed remembers how far it wrote as a header or entry line rather than
//! a row number, so re-rendering an entry or changing width keeps its place.
//! The pane never starts above that mark, so rows already in scrollback do
//! not show twice. Wherever the feed cannot tell what the terminal holds, it
//! repeats rows rather than risk losing any.

use std::io;

use ratatui::{
    buffer::Buffer,
    layout::{Rect, Size},
    text::Line,
    widgets::{Paragraph, Widget},
};

use super::{
    history_cache::{HistoryLineCache, HistoryRenderSettings},
    render::entry_lines,
    screen_layout::terminal_meets_minimum,
    synced_backend::repaint_every_row,
    App, DefaultTerminal,
};

/// How much of the history document is in scrollback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FeedMark {
    /// The first `n` header rows; past the header's end means all of it.
    Header(usize),
    /// The header, every entry before `index`, and the first `line` rows of
    /// entry `index`. Past the entry's end means all of it, so rows the entry
    /// grows by land after the mark.
    Entry { index: usize, line: usize },
}

impl FeedMark {
    /// The mark after the transcript changed under rows already written.
    ///
    /// `left_surface` is the entry of a surface the keyboard just left: it
    /// may have changed in rows already written, so it is written again from
    /// its start. `removed_from` is the first entry removed or moved: indices
    /// from it on no longer mean what was written, so the mark steps back
    /// before it. What was written of either stays in scrollback.
    fn rewound(self, left_surface: Option<usize>, removed_from: Option<usize>) -> Self {
        let Self::Entry { index, .. } = self else {
            return self;
        };
        let mark = match left_surface {
            Some(surface) if surface <= index => Self::Entry {
                index: surface,
                line: 0,
            },
            Some(_) | None => self,
        };
        match (mark, removed_from) {
            (Self::Entry { index, .. }, Some(removed)) if index >= removed => {
                match removed.checked_sub(1) {
                    Some(kept) => Self::Entry {
                        index: kept,
                        line: usize::MAX,
                    },
                    None => Self::Header(usize::MAX),
                }
            }
            _ => mark,
        }
    }

    /// The mark after its entry, rendered as `old` rows at the last paint's
    /// width, is rendered as `new` rows.
    ///
    /// Rows do not map across widths, so the boundary is found by content:
    /// the unwritten rows' text, whitespace aside, must end the new rows, and
    /// the mark goes to the last row before it, then back over blank rows.
    /// When the entry renders other text at the new width, such as a table
    /// that switches layout, the whole entry is written again: a repeated
    /// row is better than a lost one. A whole written entry stays whole.
    fn rewrapped(self, old: &[Line<'_>], new: &[Line<'_>]) -> Self {
        let Self::Entry { index, line } = self else {
            return self;
        };
        if old.is_empty() || line >= old.len() {
            let line = if old.is_empty() { line } else { new.len() };
            return Self::Entry { index, line };
        }
        let unwritten = rows_text(&old[line..]);
        let rows: Vec<String> = new
            .iter()
            .map(|row| rows_text(std::slice::from_ref(row)))
            .collect();
        let text = rows.concat();
        let Some(written_text) = text.strip_suffix(unwritten.as_str()) else {
            return Self::Entry { index, line: 0 };
        };
        // Rows wholly within the written text, then back over blank rows.
        let mut end = 0;
        let mut row = 0;
        for row_text in &rows {
            end += row_text.len();
            if end > written_text.len() {
                break;
            }
            row += 1;
        }
        while row > 0 && rows[row - 1].is_empty() {
            row -= 1;
        }
        Self::Entry { index, line: row }
    }
}

/// Whether a paint writes rows to scrollback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum FeedRows {
    /// The session view is on screen, and rows leave it as it scrolls.
    Write,
    /// A screen that replaces the session (setup, attach, peek) is up: the
    /// session's rows are not on screen, and its layout under that screen
    /// would push rows the session view shows once it returns. A resize is
    /// still reconciled, so rows a reflowing terminal pulled back are not
    /// lost.
    Hold,
}

/// Minimal mode's link between the history pane and native scrollback.
#[derive(Debug)]
pub(super) struct ScrollbackFeed {
    mark: FeedMark,
    /// `mark` as a document row at the last paint. The pane starts no higher.
    mark_row: usize,
    /// Unwritten rows of a transcript replaced since the last paint, for it
    /// to write. `Some` until then, so a second replacement before it does
    /// not write the new header early.
    retired: Option<Vec<Line<'static>>>,
    /// `None` before the first paint.
    last_paint: Option<LastPaint>,
    /// The transcript entry of the surface the keyboard was on at the last
    /// paint. The pane shows all of it, rows in scrollback too, since the
    /// user must see what they operate.
    operated_surface: Option<usize>,
    /// Set by a resize, for the next paint to repaint every row once rows a
    /// reflowing terminal pulled back onto the screen are back in scrollback.
    repaint_pending: bool,
}

#[derive(Clone, Copy, Debug)]
struct LastPaint {
    size: Size,
    /// To render rows between paints.
    settings: HistoryRenderSettings,
}

/// What a resize does to the feed.
#[derive(Debug, PartialEq, Eq)]
struct ResizeRewind {
    /// The mark's row from now on.
    mark_row: usize,
    /// Rows at the top of the screen to push back into scrollback first.
    foreign_rows: u16,
}

impl ScrollbackFeed {
    pub(super) fn new() -> Self {
        Self {
            mark: FeedMark::Header(0),
            mark_row: 0,
            retired: None,
            last_paint: None,
            operated_surface: None,
            repaint_pending: false,
        }
    }

    /// `start`, the pane's first row of `history_len`, moved past rows the
    /// feed already wrote, so none shows twice, unless a surface has the
    /// keyboard.
    pub(super) fn clamp_start(&self, start: usize, history_len: usize) -> usize {
        match self.operated_surface {
            Some(_) => start,
            None => start.max(self.mark_row.min(history_len)),
        }
    }

    /// Defers the repaint a resize needs to the next paint. Erasing now
    /// would blank rows a reflowing terminal pulled back from scrollback
    /// before the paint pushes them back there.
    pub(super) fn repaint_after_resize(&mut self) {
        self.repaint_pending = true;
    }

    /// How the feed follows the screen going from `previous` to `size`.
    ///
    /// Terminals that reflow on resize pull scrollback rows back onto a
    /// taller screen, where the next frame would paint over them. The mark
    /// steps back over the document rows among them, so those show again and
    /// later scroll out as usual. With a new width the pulled-back rows no
    /// longer line up with the document's rows, so the mark steps back twice
    /// as far. Rows pulled back from before the document, the shell's or a
    /// replaced transcript's, go back into scrollback. A terminal that pulls
    /// nothing back repeats rows in scrollback instead: a repeated row is
    /// better than a lost one. A shorter screen keeps the mark, for the same
    /// reason.
    fn rewind_after_resize(mark_row: usize, previous: Size, size: Size) -> ResizeRewind {
        if size.height <= previous.height {
            return ResizeRewind {
                mark_row,
                foreign_rows: 0,
            };
        }
        let grown = size.height - previous.height;
        let pulled_back = mark_row.min(usize::from(grown));
        let rewound = if previous.width == size.width {
            pulled_back
        } else {
            mark_row.min(2 * usize::from(grown))
        };
        ResizeRewind {
            mark_row: mark_row - rewound,
            // `pulled_back` is at most `grown`, a `u16`.
            foreign_rows: grown - pulled_back as u16,
        }
    }

    /// The mark as a document row. Valid while `lines` is current.
    fn mark_row(&self, lines: &HistoryLineCache, document: FeedDocument) -> usize {
        match self.mark {
            FeedMark::Header(line) => line.min(document.header_len),
            // An entry the cache does not hold is past the measured end.
            FeedMark::Entry { index, line } => lines
                .entry_line_range(index)
                .map_or(document.committed_len, |range| {
                    document.header_len + range.start + line.min(range.len())
                }),
        }
    }

    /// Moves the mark to document row `row`, at most the committed length,
    /// naming the entry of the last row written so that entry's growth is
    /// written too. `entries` is the transcript's length.
    fn set_mark(
        &mut self,
        row: usize,
        lines: &HistoryLineCache,
        entries: usize,
        document: FeedDocument,
    ) {
        self.mark = if row <= document.header_len {
            FeedMark::Header(row)
        } else {
            let last = row - document.header_len - 1;
            match lines.entry_at_cached_line(last) {
                Some((index, start)) => FeedMark::Entry {
                    index,
                    line: last + 1 - start,
                },
                None => {
                    debug_assert!(false, "committed row {row} is not in the line cache");
                    // All of it: repeating nothing beats a mark that rewinds.
                    FeedMark::Entry {
                        index: entries.saturating_sub(1),
                        line: usize::MAX,
                    }
                }
            }
        };
        self.mark_row = row;
    }
}

/// Lengths of the parts of the history document Rho can write to scrollback.
#[derive(Clone, Copy, Debug)]
struct FeedDocument {
    header_len: usize,
    /// Header and transcript rows; live rows follow.
    committed_len: usize,
}

/// Rows [`App::take_unwritten_rows`] took, and screen rows to push back
/// into scrollback before them.
struct UnwrittenRows {
    rows: Vec<Line<'static>>,
    foreign_rows: u16,
}

/// The document and the mark's row in it, from [`App::settle_feed_mark`].
struct SettledFeed {
    document: FeedDocument,
    /// The mark's row, after any resize rewind.
    mark_row: usize,
    /// Rows at the top of the screen to push back into scrollback first.
    foreign_rows: u16,
    /// Whether entries were measured, which changes the frame's history.
    measured: bool,
}

impl App {
    /// Whether the terminal's own scrollback holds the transcript (minimal
    /// mode), which leaves scrolling and search to the terminal.
    pub(super) fn terminal_owns_scrollback(&self) -> bool {
        self.scrollback.is_some()
    }

    /// Writes to scrollback any committed rows the next frame would scroll
    /// off the top of the history pane, as `feed_rows` allows. See
    /// [`App::paint`].
    pub(super) fn feed_scrollback(
        &mut self,
        terminal: &mut DefaultTerminal,
        feed_rows: FeedRows,
    ) -> io::Result<()> {
        let size = terminal.size()?;
        let area = Rect::new(0, 0, size.width, size.height);
        if !terminal_meets_minimum(area) {
            // No layout to feed from, but a resize is still reconciled at the
            // last paint's settings, so the notice's repaint does not erase
            // rows a reflowing terminal pulled back.
            let foreign_rows = match self.feed_mut().last_paint {
                Some(last) => {
                    let settled = self.settle_feed_mark(last.settings, size);
                    self.set_feed_mark(settled.mark_row, settled.document);
                    settled.foreign_rows
                }
                None => 0,
            };
            let repaint = std::mem::take(&mut self.feed_mut().repaint_pending);
            if foreign_rows > 0 {
                terminal.backend_mut().push_screen_top(foreign_rows)?;
            }
            return if repaint || foreign_rows > 0 {
                repaint_every_row(terminal)
            } else {
                Ok(())
            };
        }
        // Rows above the mark are in scrollback; in-app scrolling is off.
        self.scroll_history_to_bottom();
        let mut ctx = self.frame_context(area);
        let settings = ctx.settings;
        let settled = self.settle_feed_mark(settings, size);
        if settled.measured {
            ctx = self.frame_context(area);
        }
        let document = settled.document;
        let (mut rows, end) = match feed_rows {
            FeedRows::Write => {
                let pane_height = usize::from(ctx.layout.history_content.height);
                let pane_start = ctx.history_len.saturating_sub(pane_height);
                let end = pane_start.min(document.committed_len).max(settled.mark_row);
                (self.feed_mut().retired.take().unwrap_or_default(), end)
            }
            FeedRows::Hold => (Vec::new(), settled.mark_row),
        };
        rows.extend(self.feed_rows(settings, settled.mark_row..end));
        self.set_feed_mark(end, document);
        let repaint = std::mem::take(&mut self.feed_mut().repaint_pending);
        if rows.is_empty() && settled.foreign_rows == 0 {
            return if repaint {
                repaint_every_row(terminal)
            } else {
                Ok(())
            };
        }
        terminal
            .backend_mut()
            .push_screen_top(settled.foreign_rows)?;
        write_to_scrollback(terminal, &rows, size)?;
        repaint_every_row(terminal)
    }

    /// Writes the rows still on screen as plain lines and leaves the cursor
    /// below them, so the transcript stays where the session ended. Called
    /// once, as the session view closes.
    pub(super) fn release_main_screen(&mut self, terminal: &mut DefaultTerminal) -> io::Result<()> {
        let Some(feed) = self.scrollback.as_mut() else {
            return Ok(());
        };
        let mut rows = feed.retired.take().unwrap_or_default();
        let last_settings = feed.last_paint.map(|last| last.settings);
        let size = terminal.size()?;
        let mut foreign_rows = 0;
        let area = Rect::new(0, 0, size.width, size.height);
        // Too small a screen lays out no frame; the last paint's settings
        // still render the rows.
        let settings = if terminal_meets_minimum(area) {
            Some(self.frame_context(area).settings)
        } else {
            last_settings
        };
        if let Some(settings) = settings {
            let unwritten = self.take_unwritten_rows(settings, size);
            rows.extend(unwritten.rows);
            foreign_rows = unwritten.foreign_rows;
        }
        // A resize since the last paint, such as during shutdown, is
        // reconciled as a paint would.
        terminal.backend_mut().push_screen_top(foreign_rows)?;
        let kept = rows.len().min(usize::from(size.height.saturating_sub(1)));
        let (head, tail) = rows.split_at(rows.len() - kept);
        write_to_scrollback(terminal, head, size)?;
        terminal
            .backend_mut()
            .finish_main_screen(&rows_buffer(tail, size.width))
    }

    /// Keeps the rows of the transcript about to be replaced that are not in
    /// scrollback yet, for the next paint to write, and starts the feed over
    /// at the new transcript's header. Call before replacing the transcript.
    pub(super) fn retire_scrollback_document(&mut self) {
        let Some(last) = self
            .scrollback
            .as_ref()
            .filter(|feed| feed.retired.is_none())
            .and_then(|feed| feed.last_paint)
        else {
            return;
        };
        // At the last paint's size, so there is no resize to reconcile.
        let unwritten = self.take_unwritten_rows(last.settings, last.size);
        let feed = self.feed_mut();
        feed.retired = Some(unwritten.rows);
        feed.mark = FeedMark::Header(0);
        feed.mark_row = 0;
    }

    /// Every committed row after the mark, which moves to the document's end.
    fn take_unwritten_rows(
        &mut self,
        settings: HistoryRenderSettings,
        size: Size,
    ) -> UnwrittenRows {
        let settled = self.settle_feed_mark(settings, size);
        let document = settled.document;
        let rows = self.feed_rows(settings, settled.mark_row..document.committed_len);
        self.set_feed_mark(document.committed_len, document);
        UnwrittenRows {
            rows,
            foreign_rows: settled.foreign_rows,
        }
    }

    /// Brings the mark up to date with the transcript ([`FeedMark::rewound`])
    /// and the last paint's width ([`FeedMark::rewrapped`]), measures every
    /// entry from it on, so its rows have numbers, then follows a resize
    /// since the last paint ([`ScrollbackFeed::rewind_after_resize`]). Takes
    /// `size` and `settings` as the last paint's from then on.
    fn settle_feed_mark(&mut self, settings: HistoryRenderSettings, size: Size) -> SettledFeed {
        let operated = self.surfaces.operated_entry(self.history.entries());
        let removed_from = self.history.take_removed_from();
        let feed = self.feed_mut();
        let left_surface = feed.operated_surface.filter(|&last| operated != Some(last));
        feed.operated_surface = operated;
        feed.mark = feed.mark.rewound(left_surface, removed_from);
        let last_paint = feed.last_paint.replace(LastPaint { size, settings });
        let rewrap_from = last_paint
            .map(|last| last.settings)
            .filter(|previous| previous.width != settings.width);
        if let (Some(previous), FeedMark::Entry { index, .. }) = (rewrap_from, feed.mark) {
            if let Some(entry) = self.history.get(index) {
                let rows = |settings: HistoryRenderSettings| {
                    entry_lines(
                        entry,
                        settings.width,
                        settings.max_tool_output_lines,
                        settings.max_image_height,
                    )
                };
                let (old, new) = (rows(previous), rows(settings));
                let feed = self.feed_mut();
                feed.mark = feed.mark.rewrapped(&old, &new);
            }
        }
        let first = match self.feed_mut().mark {
            FeedMark::Entry { index, .. } => index,
            FeedMark::Header(_) => 0,
        };
        let measured = self.history.measured_from() > first;
        if measured {
            // In one pass: each prepend rebuilds the cache's ranges.
            self.grow_measured_history_prefix(settings, /*extra_lines*/ usize::MAX);
        }
        let header_len = self.visible_session_header_len(settings.width);
        let document = FeedDocument {
            header_len,
            committed_len: header_len.saturating_add(self.cached_transcript_line_count(settings)),
        };
        let mark_row = self
            .scrollback
            .as_ref()
            .expect("minimal mode has a feed")
            .mark_row(self.history.lines(), document);
        let rewind = match last_paint.map(|last| last.size) {
            Some(previous) if previous != size => {
                ScrollbackFeed::rewind_after_resize(mark_row, previous, size)
            }
            Some(_) | None => ResizeRewind {
                mark_row,
                foreign_rows: 0,
            },
        };
        SettledFeed {
            document,
            mark_row: rewind.mark_row,
            foreign_rows: rewind.foreign_rows,
            measured,
        }
    }

    fn set_feed_mark(&mut self, row: usize, document: FeedDocument) {
        let feed = self.scrollback.as_mut().expect("minimal mode has a feed");
        feed.set_mark(row, self.history.lines(), self.history.len(), document);
    }

    fn feed_rows(
        &mut self,
        settings: HistoryRenderSettings,
        rows: std::ops::Range<usize>,
    ) -> Vec<Line<'static>> {
        self.visible_history_lines_with_live(settings.width, settings, rows.start, rows.len(), &[])
    }

    fn feed_mut(&mut self) -> &mut ScrollbackFeed {
        self.scrollback.as_mut().expect("minimal mode has a feed")
    }
}

/// The text of `rows` without whitespace, which wrapping adds and removes.
fn rows_text(rows: &[Line<'_>]) -> String {
    rows.iter()
        .flat_map(|row| row.spans.iter())
        .flat_map(|span| span.content.chars())
        .filter(|ch| !ch.is_whitespace())
        .collect()
}

/// Writes `rows` to scrollback a screen at a time.
fn write_to_scrollback(
    terminal: &mut DefaultTerminal,
    rows: &[Line<'static>],
    size: Size,
) -> io::Result<()> {
    for slice in rows.chunks(usize::from(size.height.max(1))) {
        terminal
            .backend_mut()
            .push_to_scrollback(&rows_buffer(slice, size.width))?;
    }
    Ok(())
}

/// `rows`, at most a screen of them, painted as the history pane paints
/// them, one buffer row each.
fn rows_buffer(rows: &[Line<'static>], width: u16) -> Buffer {
    let height = u16::try_from(rows.len()).expect("at most a screen of rows");
    let area = Rect::new(0, 0, width, height);
    let mut buffer = Buffer::empty(area);
    Paragraph::new(rows.to_vec()).render(area, &mut buffer);
    buffer
}

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