Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
perf(agent-tui): count fitting lines without wrapping, one trace scan, borrow the last row
Akarshan Biswas46193900de21
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 5f818c4f0..ac34372ee 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -1605,12 +1605,50 @@ fn tally(counter: &'static std::thread::LocalKey<std::cell::Cell<usize>>) {/// a run of rows equals measuring their concatenation -- which is what lets/// `draw` add up cached per-row heights instead of wrapping the whole session.fn wrapped_height(lines: Vec<Line<'static>>, width: u16) -> u16 {- Paragraph::new(lines)+ wrapped_height_of(&lines, width)+}++/// `wrapped_height` without taking ownership: the word wrapper is only run+/// (on a copy) when some line might wrap. Every other line is one row, which+/// is the common case for pre-wrapped markdown, panels and the streaming tail.+fn wrapped_height_of(lines: &[Line<'static>], width: u16) -> u16 {+ let width = width.max(1);+ if lines.iter().all(|line| fits_one_row(line, width)) {+ return lines.len().min(u16::MAX as usize) as u16;+ }+ Paragraph::new(lines.to_vec()).wrap(Wrap { trim: false })- .line_count(width.max(1))+ .line_count(width).min(u16::MAX as usize) as u16}+/// Whether ratatui's word wrapper (`trim: false`) is certain to emit `line`+/// as exactly one row at `width`. Cells are counted the way the wrapper counts+/// them: per grapheme, control characters dropped. Shorter than the width+/// never breaks. Exactly the width only stays one row when no grapheme is zero+/// cells wide, since the wrapper closes a full row before looking at a+/// zero-width grapheme that follows it. Anything else is left to the wrapper.+fn fits_one_row(line: &Line<'_>, width: u16) -> bool {+ use ratatui::buffer::CellWidth;+ use unicode_segmentation::UnicodeSegmentation;+ let mut cells: usize = 0;+ let mut zero_width = false;+ for span in &line.spans {+ for g in span.content.graphemes(true) {+ if g.contains(char::is_control) {+ continue;+ }+ let w = g.cell_width() as usize;+ zero_width |= w == 0;+ cells += w;+ if cells > width as usize {+ return false;+ }+ }+ }+ cells < width as usize || !zero_width+}+/// One committed transcript entry. Width-dependent entries keep their *source*/// rather than rendered lines, so a terminal resize re-lays them out at the new/// width instead of leaving tables, boxed diffs and truncated labels sized for@@ -1727,7 +1765,7 @@ impl Row {return;}let lines = self.kind.render(width);- let height = wrapped_height(lines.clone(), width);+ let height = wrapped_height_of(&lines, width);*self.cache.borrow_mut() = Some(RowRender {width,lines,@@ -19288,7 +19326,7 @@ impl Segment {fn eager(idx: Option<usize>, lines: Vec<Line<'static>>, width: u16) -> Segment {Segment {idx,- height: wrapped_height(lines.clone(), width),+ height: wrapped_height_of(&lines, width),lines: Some(lines),}}@@ -19301,9 +19339,15 @@ fn trailing_blank(tail: &[Line<'static>], transcript: &[Row], width: u16) -> boolet blank = |line: &Line<'static>| line.spans.iter().all(|s| s.content.trim().is_empty());match tail.last() {Some(line) => blank(line),- None => transcript- .last()- .is_none_or(|row| row.lines(width).last().is_none_or(blank)),+ // Read through the row cache rather than `lines`, which would copy the+ // whole last row (a long answer) every frame to look at one line.+ None => transcript.last().is_none_or(|row| {+ row.fill(width);+ row.cache+ .borrow()+ .as_ref()+ .is_none_or(|r| r.lines.last().is_none_or(blank))+ }),}}@@ -19459,8 +19503,10 @@ fn draw(f: &mut Frame, app: &mut App) {// open group on that same first prose token, so it is already a trace member.)let last_answer = app.last_answer_idx();let answer_started = app.answer_started();+ // Built once: it sorts every group and reasoning block in the session.+ let trace_runs = app.trace_runs();let mut collapsed_headers: HashMap<usize, TraceRun> = HashMap::new();- for run in app.trace_runs() {+ for run in trace_runs.iter().copied() {let finished = answer_started || last_answer.is_some_and(|a| run.end < a);if finished && !app.expanded_traces.contains(&run.start) {collapsed_headers.insert(run.start, run);@@ -19474,8 +19520,7 @@ fn draw(f: &mut Frame, app: &mut App) {// after its last row, keyed by that row's index. The live rail's terminal is// its current step, and a folded trace shows only its header, so neither gets// one.- let expanded_trace_ends: std::collections::HashSet<usize> = app- .trace_runs()+ let expanded_trace_ends: std::collections::HashSet<usize> = trace_runs.iter().filter(|r| {last_answer.is_some_and(|a| r.end < a) && app.expanded_traces.contains(&r.start)diff --git a/src-tauri/src/core/cli/tui/tests/perf.rs b/src-tauri/src/core/cli/tui/tests/perf.rsindex eeff57200..026a79fd0 100644--- a/src-tauri/src/core/cli/tui/tests/perf.rs+++ b/src-tauri/src/core/cli/tui/tests/perf.rs@@ -10,10 +10,12 @@//! timing.use super::super::{- ANSWER_SCANS, MD_PARSES, PATH_HINT_REFRESHES, THINK_SCANS,+ ANSWER_SCANS, MD_PARSES, PATH_HINT_REFRESHES, ROW_CLONES, THINK_SCANS, TRACE_RUN_SCANS,};use super::*;use ratatui::backend::TestBackend;+use ratatui::text::Span;+use ratatui::widgets::{Paragraph, Wrap};use ratatui::Terminal;/// Read and zero one of the work counters.@@ -354,3 +356,86 @@ fn an_unchanged_live_tail_is_not_reparsed() {render_rows(&mut app, 60, 24);assert!(take(&MD_PARSES) > 0, "a resize must re-render the tail");}++/// The wrapped-height fast path agrees with ratatui's own count on lines at,+/// under and over the width, with wide, zero-width and control graphemes.+#[test]+fn wrapped_height_fast_path_matches_line_count() {+ let samples = [+ "",+ " ",+ "plain words that may or may not wrap here",+ "exactly-ten",+ "abcdefghij",+ "abcdefghi\u{301}",+ "abcdefghij\u{301}",+ "\u{4e2d}\u{6587}\u{5b57}\u{7b26}\u{4e32}",+ "a\u{4e2d}\u{6587}\u{5b57}\u{7b26}\u{4e32}",+ "tab\there\r\nand\u{1b} esc",+ "trailing spaces ",+ "\u{200b}\u{200b}abcdefghij",+ "nbsp\u{a0}\u{a0}\u{a0}\u{a0}\u{a0}\u{a0}x",+ "\u{1f600}\u{1f600}\u{1f600}\u{1f600}\u{1f600}",+ "\u{ff9e}\u{ff9e}\u{ff9e}abcdefg",+ ];+ for width in [1u16, 2, 5, 9, 10, 11, 40] {+ for text in samples {+ for split in [false, true] {+ let line = if split && text.len() > 3 {+ let at = text.char_indices().nth(2).map_or(0, |(i, _)| i);+ Line::from(vec![+ Span::raw(text[..at].to_string()),+ Span::styled(text[at..].to_string(), Style::new().bold()),+ ])+ } else {+ Line::raw(text.to_string())+ };+ let want = Paragraph::new(vec![line.clone()])+ .wrap(Wrap { trim: false })+ .line_count(width) as u16;+ let got = super::super::wrapped_height_of(&[line], width);+ assert_eq!(got, want, "width {width}, {text:?}, split {split}");+ }+ }+ }+}++/// A frame builds the trace runs once, and checking whether the body ends on+/// a blank copies no row out of the cache beyond the visible ones.+#[test]+fn a_frame_builds_trace_runs_once() {+ let mut app = long_session(200);+ let mut term = terminal(100, 30);+ draw_on(&mut term, &mut app);+ take(&TRACE_RUN_SCANS);+ draw_on(&mut term, &mut app);+ assert_eq!(take(&TRACE_RUN_SCANS), 1);+}++/// The blank-separator check above a streaming tail reads the last row in+/// place: with the last row on screen anyway, a frame copies the same rows+/// whether or not a tail is streaming.+#[test]+fn the_tail_separator_check_copies_no_row() {+ let mut app = long_session(200);+ let mut term = terminal(100, 30);+ draw_on(&mut term, &mut app);+ take(&ROW_CLONES);+ draw_on(&mut term, &mut app);+ let idle = take(&ROW_CLONES);+ app.status = Status::Running;+ app.apply(StreamEvent::ToolCall {+ id: "z".into(),+ name: "grep".into(),+ args: json!({ "pattern": "x" }),+ });+ app.finalize_tool_group();+ app.apply(StreamEvent::Token {+ text: "<think>still".into(),+ });+ draw_on(&mut term, &mut app);+ take(&ROW_CLONES);+ draw_on(&mut term, &mut app);+ let streaming = take(&ROW_CLONES);+ assert!(streaming <= idle, "streaming frame copied {streaming} rows, idle {idle}");+}