Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

perf(tui): lay the transcript out once and scroll a slice of it

Rach Pradhan3ce0c2d32b14
diff --git a/TUI/anchor.zig b/TUI/anchor.zig
index de3223e5..45db59b6 100644
--- a/TUI/anchor.zig
+++ b/TUI/anchor.zig
@@ -13,7 +13,7 @@
const std = @import("std");
const app = @import("app.zig");
-const scrollback = @import("scrollback.zig");
+const layout = @import("layout_cache.zig");
const Model = app.Model;
/// Where the viewport was parked, in transcript terms rather than screen rows:
@@ -25,20 +25,23 @@ pub const Anchor = struct { idx: usize, ordinal: usize };
/// `width`. Null when there is nothing to hold: an empty transcript, or a user
/// who is tailing — follow mode is already an anchor, and a better one (the
/// bottom), so a rewrap must not drag the viewport off it.
-pub fn capture(self: *const Model, width: usize) ?Anchor {
+pub fn capture(self: *Model, width: usize) ?Anchor {
if (self.follow or width == 0 or self.history.items.len == 0) return null;
+ // One layout pass, not two: at capture time the cache still holds the OLD
+ // width, so this is a validating walk and both reads come off it.
+ const c = layout.ensure(self, width);
const top = self.mid_skip;
- const idx = scrollback.indexAtVisual(self, top, width) orelse return null;
- const base = scrollback.visualOfIndex(self, idx, width) orelse return null;
+ const idx = layout.indexAt(c, top) orelse return null;
+ const base = layout.lineOf(c, idx) orelse return null;
return .{ .idx = idx, .ordinal = top -| base };
}
/// The transcript row that shows the anchored logical line at `width`. A block
/// that rewrapped SHORTER clamps to its own last line, so the anchor stays
/// inside the entry it was taken from instead of sliding into the next one.
-pub fn rowAt(self: *const Model, anc: Anchor, width: usize) usize {
- const base = scrollback.visualOfIndex(self, anc.idx, width) orelse return 0;
- const span = blockSpan(self, anc.idx, width, base);
+pub fn rowAt(self: *const Model, c: *const layout.Cache, anc: Anchor) usize {
+ const base = layout.lineOf(c, anc.idx) orelse return 0;
+ const span = blockSpan(self, c, anc.idx, base);
if (span == 0) return base;
return base + @min(anc.ordinal, span - 1);
}
@@ -47,10 +50,10 @@ pub fn rowAt(self: *const Model, anc: Anchor, width: usize) usize {
/// the gap to the next block rather than by re-rendering the entry, so a
/// collapsed or expanded tool RUN — which the row math treats as one unit —
/// is measured the same way the viewport lays it out.
-fn blockSpan(self: *const Model, idx: usize, width: usize, base: usize) usize {
+fn blockSpan(self: *const Model, c: *const layout.Cache, idx: usize, base: usize) usize {
const nxt = nextBlock(self, idx);
- if (nxt >= self.history.items.len) return scrollback.totalVisualLines(self, width) -| base;
- const nb = scrollback.visualOfIndex(self, nxt, width) orelse return 1;
+ if (nxt >= self.history.items.len) return c.total -| base;
+ const nb = layout.lineOf(c, nxt) orelse return 1;
return nb -| base;
}
@@ -63,6 +66,7 @@ fn nextBlock(self: *const Model, idx: usize) usize {
// ---------------------------------------------------------------------------
const render_mod = @import("render.zig");
+const scrollback = @import("scrollback.zig");
const testing = std.testing;
/// Park the viewport so entry `idx`'s first row is the top visible line, using
diff --git a/TUI/app.zig b/TUI/app.zig
index edbd4c6c..97b76ae6 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -123,6 +123,10 @@ pub const Model = struct {
preview_rows: usize = 0,
/// Drag-selection band over the composed frame (#529) — presentation only.
sel: @import("selection.zig").Sel = .{},
+ /// Wrapped-line layout of the transcript, keyed by width/theme/fold/entry
+ /// identity (layout_cache.zig). Presentation state: a pure memo of what the
+ /// row builders would produce, so scrolling is a slice and not a re-layout.
+ layout: @import("layout_cache.zig").Cache = .{},
/// Text the band currently covers, captured by the same pass that paints
/// it, so what the clipboard gets is exactly what the user saw highlighted.
sel_text: []const u8 = "",
@@ -156,6 +160,7 @@ pub const Model = struct {
if (self.bg) |op| {
if (!op.threaded or op.done.load(.acquire)) @import("bgop.zig").reap(self) else self.bg = null;
}
+ self.layout.deinit(self.alloc);
for (self.history.items) |e| self.freeEntry(e);
self.history.deinit();
for (self.prompt_hist.items) |s| self.alloc.free(s);
@@ -257,6 +262,9 @@ pub const Model = struct {
}
pub fn clearHistory(self: *Model) void {
+ // Before the entries go: the layout holds wrapped bytes for them and a
+ // back-pointer into their text.
+ self.layout.invalidate(self.alloc);
for (self.history.items) |e| self.freeEntry(e);
self.history.clearRetainingCapacity();
self.turns = 0;
diff --git a/TUI/image.zig b/TUI/image.zig
index bfdcf71a..e1af011a 100644
--- a/TUI/image.zig
+++ b/TUI/image.zig
@@ -199,13 +199,13 @@ pub fn mouse(self: *Model, ev: key_mod.Mouse) bool {
}
return false;
};
- const hist = if (y >= self.prompt_origin or y < self.mid_origin + self.sticky_rows) null else @import("scrollback.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, self.last_term_width);
+ const hist = if (y >= self.prompt_origin or y < self.mid_origin + self.sticky_rows) null else @import("layout_cache.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, self.last_term_width);
const path = pathForChip(self, n, hist);
show(self, path, n, click);
return true;
}
-fn chipAt(self: *const Model, x: usize, y: usize) ?u32 {
+fn chipAt(self: *Model, x: usize, y: usize) ?u32 {
if (self.images.items.len > 0 and y == self.prompt_origin + 1) {
const box_pad: usize = 4;
if (x < box_pad) return null;
@@ -222,7 +222,7 @@ fn chipAt(self: *const Model, x: usize, y: usize) ?u32 {
if (y < self.mid_origin) return null;
if (y < self.mid_origin + self.sticky_rows) return null; // sticky chrome is inert
const vis = y - self.mid_origin + self.mid_skip;
- const idx = @import("scrollback.zig").indexAtVisual(self, vis, self.last_term_width) orelse return null;
+ const idx = @import("layout_cache.zig").indexAtVisual(self, vis, self.last_term_width) orelse return null;
if (self.history.items[idx].kind != .user) return null;
if (pathInUserText(self.history.items[idx].text, 1) == null) return null;
return parseChipOnUser(self, idx, x);
diff --git a/TUI/keys.zig b/TUI/keys.zig
index ce698e54..a9014312 100644
--- a/TUI/keys.zig
+++ b/TUI/keys.zig
@@ -5,7 +5,7 @@ const std = @import("std");
const app = @import("app.zig");
const catalog = @import("catalog.zig");
const dispatch = @import("dispatch.zig");
-const scrollback = @import("scrollback.zig");
+const layout_cache = @import("layout_cache.zig");
const selection = @import("selection.zig");
const engine = @import("engine.zig");
const key_mod = @import("key.zig");
@@ -245,7 +245,7 @@ fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {
self.focus = .scrollback;
// A click on blank padding maps to no entry — it must not select or
// toggle anything (#519).
- const i = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse return .stay;
+ const i = layout_cache.indexAtVisual(self, vis, self.last_term_width) orelse return .stay;
self.selected = i;
if (self.history.items[i].kind == .tool) {
self.toggleToolGroup(i);
diff --git a/TUI/layout_cache.zig b/TUI/layout_cache.zig
new file mode 100644
index 00000000..be7c5eb8
--- /dev/null
+++ b/TUI/layout_cache.zig
@@ -0,0 +1,364 @@
+//! Virtual layout for the transcript viewport.
+//!
+//! scrollback.render lays the WHOLE history out on every call: every entry is
+//! re-wrapped through theme.wrapToWidth and the result concatenated into one
+//! string, which render.zig then splits back into lines and throws all but a
+//! screenful of away. That makes one wheel tick cost O(total transcript), and
+//! on a long session it is exactly why scrolling feels bad.
+//!
+//! grok-build's answer, and this one: lay each BLOCK out once, keep the wrapped
+//! bytes, and keep a prefix sum of where each block starts in virtual-Y. A
+//! scroll is then a viewport SLICE — binary search to the block holding the top
+//! line, walk forward a screenful — so a frame costs O(view height + log n)
+//! instead of O(history).
+//!
+//! A block is one history entry, or a whole consecutive tool RUN (collapsed or
+//! expanded), because that is the unit scrollback.render emits between '\n's.
+//! Everything a block's bytes depend on — its entries' identity and fold state,
+//! the width, the theme, whether the selection is inside it, and the user
+//! ordinal that numbers a prompt — is folded into a 64-bit key, and a block
+//! whose key still matches is reused verbatim. Appending to the transcript
+//! therefore reuses the entire cached prefix, and a streaming turn re-lays out
+//! only its own tail.
+//!
+//! Presentation state by construction: nothing here is engine state, and the
+//! cache is a pure memo — dropping it changes performance and nothing else.
+//! scrollback.render stays as the uncached reference that the property tests in
+//! layout_cache_tests.zig check this against, byte for byte.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const scrollback = @import("scrollback.zig");
+const theme_mod = @import("theme.zig");
+const Model = app.Model;
+
+/// A laid-out block: the bytes scrollback.render would have emitted for the
+/// history range [start, end), plus where they sit in virtual-Y.
+pub const Block = struct {
+ /// First history index of the block; `end` is exclusive. A live block — the
+ /// pending stream tail or the steer notice — is not history at all and
+ /// carries start >= history.len so it maps to no entry.
+ start: usize,
+ end: usize,
+ key: u64,
+ /// Owned by the cache's allocator. Empty only under OOM.
+ text: []u8,
+ lines: usize,
+ first_line: usize = 0,
+ /// Laid out fresh every frame and never reused: a `.pending` row animates
+ /// off now_ms, and the live rows below change with the stream.
+ vol: bool = false,
+ /// Not history: the streaming tail or the steer notice. Maps to no entry.
+ live: bool = false,
+ /// The nearest `.user` entry's text at or before this block — what the
+ /// sticky header pins. Refreshed on every walk, so it can never outlive the
+ /// entry it points at.
+ user_text: ?[]const u8 = null,
+};
+
+pub const Cache = struct {
+ blocks: std.ArrayList(Block) = .empty,
+ /// The width and theme the cached bytes were laid out at. A change in
+ /// either is a cold rebuild: every block rewraps.
+ width: usize = 0,
+ theme: u8 = 0xff,
+ total: usize = 0,
+ hits: u64 = 0,
+ misses: u64 = 0,
+ colds: u64 = 0,
+
+ pub fn deinit(self: *Cache, gpa: std.mem.Allocator) void {
+ self.invalidate(gpa);
+ self.blocks.deinit(gpa);
+ self.* = .{};
+ }
+
+ /// Drop every laid-out block, keeping the array's capacity. Callers that
+ /// free the entries themselves (clearHistory) must come through here: a
+ /// cached `user_text` points into entry storage.
+ pub fn invalidate(self: *Cache, gpa: std.mem.Allocator) void {
+ for (self.blocks.items) |b| if (b.text.len > 0) gpa.free(b.text);
+ self.blocks.clearRetainingCapacity();
+ self.total = 0;
+ }
+};
+
+/// Bring the cache up to date for `width` and return it. Cheap when nothing
+/// changed: one key per block, no wrapping and no allocation.
+pub fn ensure(m: *Model, width: usize) *Cache {
+ const c = &m.layout;
+ const th: u8 = @intFromEnum(m.theme_id);
+ if (c.width != width or c.theme != th) {
+ c.invalidate(m.alloc);
+ c.width = width;
+ c.theme = th;
+ c.colds += 1;
+ }
+ var arena = std.heap.ArenaAllocator.init(m.alloc);
+ defer arena.deinit();
+
+ var w: Walk = .{ .m = m, .c = c, .arena = &arena, .width = width, .th = th };
+ var i: usize = 0;
+ while (i < m.history.items.len) {
+ const e = m.history.items[i];
+ const end = if (e.kind == .tool) m.toolRun(i).end else i + 1;
+ if (e.kind == .user) {
+ w.users += 1;
+ w.user_text = e.text;
+ }
+ w.place(i, end, e.kind == .pending, false);
+ i = end;
+ }
+ w.placeLive();
+ // Whatever the walk did not claim describes a transcript that no longer
+ // exists — a cleared history, a removed pending row, a collapsed run.
+ for (c.blocks.items[w.pos..]) |b| if (b.text.len > 0) m.alloc.free(b.text);
+ c.blocks.shrinkRetainingCapacity(w.pos);
+ c.total = w.line;
+ return c;
+}
+
+const Walk = struct {
+ m: *Model,
+ c: *Cache,
+ arena: *std.heap.ArenaAllocator,
+ width: usize,
+ th: u8,
+ pos: usize = 0,
+ line: usize = 0,
+ users: u32 = 0,
+ user_text: ?[]const u8 = null,
+
+ fn place(self: *Walk, start: usize, end: usize, vol: bool, live: bool) void {
+ const key = if (vol) 0 else blockKey(self.m, start, end, self.width, self.th, self.users);
+ if (self.pos < self.c.blocks.items.len) {
+ const b = &self.c.blocks.items[self.pos];
+ if (!vol and !b.vol and b.key == key and b.start == start and b.end == end) {
+ b.first_line = self.line;
+ b.user_text = self.user_text;
+ self.line += b.lines;
+ self.pos += 1;
+ self.c.hits += 1;
+ return;
+ }
+ if (b.text.len > 0) self.m.alloc.free(b.text);
+ b.* = self.build(start, end, key, vol, live);
+ self.line += b.lines;
+ self.pos += 1;
+ self.c.misses += 1;
+ return;
+ }
+ const b = self.build(start, end, key, vol, live);
+ self.c.blocks.append(self.m.alloc, b) catch {
+ if (b.text.len > 0) self.m.alloc.free(b.text);
+ return;
+ };
+ self.line += b.lines;
+ self.pos += 1;
+ self.c.misses += 1;
+ }
+
+ fn build(self: *Walk, start: usize, end: usize, key: u64, vol: bool, live: bool) Block {
+ _ = self.arena.reset(.retain_capacity);
+ const a = self.arena.allocator();
+ const text = if (live)
+ liveText(self.m, a, start, end, self.width) catch ""
+ else
+ blockText(self.m, a, start, end, self.width, self.users) catch "";
+ const owned: []u8 = self.m.alloc.dupe(u8, text) catch &.{};
+ return .{
+ .start = start,
+ .end = end,
+ .key = key,
+ .text = owned,
+ .lines = scrollback.lineCount(owned),
+ .first_line = self.line,
+ .vol = vol,
+ .live = live,
+ .user_text = self.user_text,
+ };
+ }
+
+ /// The two rows a live turn owns: the streaming prose tail and the steer
+ /// notice. Both change every frame, so they are laid out fresh every time
+ /// and never claim a cached slot's identity.
+ fn placeLive(self: *Walk) void {
+ const m = self.m;
+ const job = m.pending orelse return;
+ if (m.cancel_requested) return;
+ const n = m.history.items.len;
+ if (job.stream.len.load(.acquire) > 0) self.place(n, n, true, true);
+ if (m.steer_queue.items.len > 0) self.place(n, n + 1, true, true);
+ }
+};
+
+/// Which live row this is: `end == start` is the stream tail, anything else is
+/// the steer notice. Keeps the two apart without a third field.
+fn liveText(m: *Model, a: std.mem.Allocator, start: usize, end: usize, width: usize) ![]const u8 {
+ if (end != start) return steerText(m, a);
+ const job = m.pending orelse return "";
+ const live = job.stream.snapshot(a) orelse return "";
+ return theme_mod.paint(a, m.theme().muted, try scrollback.tail(a, scrollback.strip(a, live), width, 4));
+}
+
+fn steerText(m: *Model, a: std.mem.Allocator) ![]const u8 {
+ return theme_mod.paint(a, m.theme().muted, try std.fmt.allocPrint(a, " ↳ {d} queued · empty Enter sends now", .{m.steer_queue.items.len}));
+}
+
+/// One block's bytes, composed exactly as scrollback.render composes them —
+/// same helpers, same selection rule, same '\n' between the rows of an expanded
+/// tool run.
+fn blockText(m: *const Model, a: std.mem.Allocator, start: usize, end: usize, width: usize, users: u32) ![]const u8 {
+ const e = m.history.items[start];
+ const sel = m.focus == .scrollback and m.selected >= start and m.selected < end;
+ if (e.kind != .tool) return scrollback.row(m, a, users, e, width, m.now_ms, sel);
+ if (e.folded) return scrollback.summary(m, a, start, end, sel);
+ var out = std.array_list.Managed(u8).init(a);
+ var first = true;
+ var t = start;
+ while (t < end) {
+ if (!first) try out.append('\n');
+ first = false;
+ const one = m.focus == .scrollback and t == m.selected;
+ try out.appendSlice(try scrollback.toolVisual(m, a, t, end, width, m.now_ms, one));
+ t = scrollback.nextTool(m, t, end);
+ }
+ return out.items;
+}
+
+/// Everything the block's bytes are a function of. Entry identity is the
+/// (pointer, length) of its owned strings — entries are immutable once pushed,
+/// and freed on replacement — with a bounded content sample mixed in so an
+/// allocator that hands the same address and length back for different bytes
+/// cannot fake a hit.
+fn blockKey(m: *const Model, start: usize, end: usize, width: usize, th: u8, users: u32) u64 {
+ var h = std.hash.Wyhash.init(0x1a70c0de);
+ h.update(std.mem.asBytes(&width));
+ h.update(std.mem.asBytes(&th));
+ h.update(std.mem.asBytes(&users));
+ const sel: usize = if (m.focus == .scrollback and m.selected >= start and m.selected < end) m.selected + 1 else 0;
+ h.update(std.mem.asBytes(&sel));
+ var i = start;
+ while (i < end) : (i += 1) {
+ const e = m.history.items[i];
+ var flags: u8 = @intFromEnum(e.kind);
+ flags |= @as(u8, @intFromBool(e.folded)) << 4;
+ h.update(std.mem.asBytes(&flags));
+ mixSlice(&h, e.text);
+ var tf: u8 = 0;
+ if (e.tool) |t| {
+ tf = 1;
+ tf |= @as(u8, @intFromBool(t.done)) << 1;
+ tf |= @as(u8, @intFromBool(t.is_error)) << 2;
+ tf |= @as(u8, @intFromBool(t.denied)) << 3;
+ h.update(std.mem.asBytes(&tf));
+ mixSlice(&h, t.name);
+ mixSlice(&h, t.detail);
+ } else h.update(std.mem.asBytes(&tf));
+ }
+ return h.final();
+}
+
+fn mixSlice(h: *std.hash.Wyhash, s: []const u8) void {
+ const p = @intFromPtr(s.ptr);
+ h.update(std.mem.asBytes(&p));
+ const n = s.len;
+ h.update(std.mem.asBytes(&n));
+ if (s.len <= 32) {
+ h.update(s);
+ return;
+ }
+ h.update(s[0..16]);
+ h.update(s[s.len - 16 ..]);
+}
+
+// --- viewport queries ------------------------------------------------------
+
+/// The `count` display lines starting at virtual row `from`. The slices point
+/// into the cache's own bytes, so this allocates only the index array.
+pub fn window(c: *const Cache, a: std.mem.Allocator, from: usize, count: usize) ![]const []const u8 {
+ var out = std.array_list.Managed([]const u8).init(a);
+ if (count == 0) return out.items;
+ var bi = blockOfLine(c, from) orelse return out.items;
+ while (bi < c.blocks.items.len and out.items.len < count) : (bi += 1) {
+ const b = c.blocks.items[bi];
+ var it = std.mem.splitScalar(u8, b.text, '\n');
+ var ord: usize = 0;
+ while (it.next()) |ln| : (ord += 1) {
+ if (b.first_line + ord < from) continue;
+ if (out.items.len >= count) break;
+ try out.append(ln);
+ }
+ }
+ return out.items;
+}
+
+/// History index shown on virtual row `y` — a tool run answers with its start,
+/// a live row with null. Mirrors scrollback.indexAtVisual.
+pub fn indexAt(c: *const Cache, y: usize) ?usize {
+ const bi = blockOfLine(c, y) orelse return null;
+ const b = c.blocks.items[bi];
+ if (b.live) return null;
+ return b.start;
+}
+
+/// First virtual row of entry `idx` (a tool run answers with its own first
+/// row). Mirrors scrollback.visualOfIndex.
+pub fn lineOf(c: *const Cache, idx: usize) ?usize {
+ const bs = c.blocks.items;
+ if (bs.len == 0) return null;
+ var lo: usize = 0;
+ var hi: usize = bs.len;
+ while (lo + 1 < hi) {
+ const mid = lo + (hi - lo) / 2;
+ if (bs[mid].start <= idx) lo = mid else hi = mid;
+ }
+ const b = bs[lo];
+ if (b.live or idx < b.start or idx >= b.end) return null;
+ return b.first_line;
+}
+
+/// The last user prompt whose first row sits strictly above `top` — the grok
+/// sticky-header candidate, in O(log n) off the per-block back-pointer.
+pub fn stickyUserAbove(c: *const Cache, top: usize) ?[]const u8 {
+ const bs = c.blocks.items;
+ if (bs.len == 0 or top == 0 or bs[0].first_line >= top) return null;
+ var lo: usize = 0;
+ var hi: usize = bs.len;
+ while (lo + 1 < hi) {
+ const mid = lo + (hi - lo) / 2;
+ if (bs[mid].first_line < top) lo = mid else hi = mid;
+ }
+ return bs[lo].user_text;
+}
+
+fn blockOfLine(c: *const Cache, y: usize) ?usize {
+ const bs = c.blocks.items;
+ if (bs.len == 0 or y >= c.total) return null;
+ var lo: usize = 0;
+ var hi: usize = bs.len;
+ while (lo + 1 < hi) {
+ const mid = lo + (hi - lo) / 2;
+ if (bs[mid].first_line <= y) lo = mid else hi = mid;
+ }
+ return lo;
+}
+
+// --- Model-level convenience (same shapes as the scrollback originals) ------
+
+pub fn totalVisualLines(m: *Model, width: usize) usize {
+ return ensure(m, width).total;
+}
+
+pub fn indexAtVisual(m: *Model, y: usize, width: usize) ?usize {
+ return indexAt(ensure(m, width), y);
+}
+
+pub fn visualOfIndex(m: *Model, idx: usize, width: usize) ?usize {
+ return lineOf(ensure(m, width), idx);
+}
+
+test {
+ _ = @import("layout_cache_tests.zig");
+}
diff --git a/TUI/layout_cache_tests.zig b/TUI/layout_cache_tests.zig
new file mode 100644
index 00000000..74531b01
--- /dev/null
+++ b/TUI/layout_cache_tests.zig
@@ -0,0 +1,333 @@
+//! The layout cache is only allowed to be faster — never different. Every test
+//! here pins it against scrollback.zig's uncached path, which stays in the tree
+//! precisely as the oracle: it re-wraps the whole history on every call, so if
+//! the two ever disagree the cache is wrong by definition.
+//!
+//! The last test is the benchmark. It runs a token-sized transcript by default
+//! (Debug timings are meaningless, so it asserts REUSE there, not speed) and
+//! the full 10k-display-line matrix with numbers when GRAFF_TUI_BENCH is set —
+//! see scripts/bench-tui-layout.sh, which builds it ReleaseFast.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const engine = @import("engine.zig");
+const layout = @import("layout_cache.zig");
+const render_mod = @import("render.zig");
+const scrollback = @import("scrollback.zig");
+const theme_mod = @import("theme.zig");
+const Model = app.Model;
+const testing = std.testing;
+
+/// The whole transcript, read back out of the cache one display line at a time
+/// and re-joined. Byte-identical to scrollback.render is the contract.
+fn cachedAll(m: *Model, a: std.mem.Allocator, width: usize) ![]const u8 {
+ const c = layout.ensure(m, width);
+ const lines = try layout.window(c, a, 0, c.total);
+ var out = std.array_list.Managed(u8).init(a);
+ for (lines, 0..) |ln, i| {
+ if (i > 0) try out.append('\n');
+ try out.appendSlice(ln);
+ }
+ return out.items;
+}
+
+const prose = "a long explanation line that fills the scrollback with content and keeps wrapping at every narrow width the matrix below tests";
+
+fn fixture(m: *Model) !void {
+ try m.push(.user, "how do I frobnicate the widget? and keep the question long enough to wrap");
+ try m.push(.assistant, prose);
+ try m.pushTool(.{ .name = "bash", .detail = "printf hello | wc -c" });
+ try m.pushTool(.{ .name = "bash", .detail = "6", .done = true });
+ try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "needle" });
+ try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "3 hits", .done = true });
+ try m.push(.assistant, "## heading\n\n- one\n- two\n\n`code` and **bold** " ++ prose);
+ try m.push(.system, "· a system notice");
+ try m.push(.err, "something went wrong while doing the thing that went wrong");
+ try m.push(.user, "second prompt");
+ try m.pushTool(.{ .name = "read_file", .detail = "src/foo.zig" });
+ try m.pushTool(.{ .name = "read_file", .detail = "const std = @import(\"std\");", .done = true });
+ try m.push(.assistant, "done");
+}
+
+const widths = [_]usize{ 28, 41, 60, 80, 100, 132 };
+
+test "cached layout is byte-identical to the uncached render over widths, themes and folds" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try fixture(&m);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+
+ // Every phase mutates something the cache keys on, WITHOUT clearing it:
+ // the point is that invalidation is derived, not announced.
+ for (theme_mod.all) |tid| {
+ m.theme_id = tid;
+ for (widths) |w| {
+ for (0..8) |phase| {
+ switch (phase) {
+ 1 => m.toggleToolGroup(2), // expand the bash run
+ 2 => m.toggleToolGroup(4), // expand the search run
+ 3 => {
+ m.focus = .scrollback;
+ m.selected = 5;
+ },
+ 4 => m.selected = 1,
+ 5 => m.toggleToolGroup(2), // fold it back under selection
+ 6 => m.focus = .prompt,
+ 7 => {
+ try m.push(.assistant, "an appended answer that arrives after everything was cached " ++ prose);
+ try m.push(.pending, "");
+ m.now_ms = 700; // past the ❙/❘ blink half-period
+ },
+ else => {},
+ }
+ _ = arena.reset(.retain_capacity);
+ const a = arena.allocator();
+ const want = try scrollback.render(&m, a, w, m.now_ms);
+ const got = try cachedAll(&m, a, w);
+ testing.expectEqualStrings(want, got) catch |e| {
+ std.debug.print("theme={s} width={d} phase={d}\n", .{ tid.label(), w, phase });
+ return e;
+ };
+ }
+ // The pending row is a history entry, not chrome: it maps back to
+ // its own index the way every other row does.
+ const c = layout.ensure(&m, w);
+ const last = m.history.items.len - 1;
+ try testing.expectEqual(last, layout.indexAt(c, c.total - 1).?);
+ // Unwind phase 7's pushes so the next width starts from the fixture.
+ m.freeEntry(m.history.pop().?);
+ m.freeEntry(m.history.pop().?);
+ m.now_ms = 0;
+ }
+ }
+}
+
+test "cached virtual-Y agrees with the uncached row math entry for entry" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try fixture(&m);
+ for (widths) |w| {
+ for (0..3) |phase| {
+ if (phase == 1) m.toggleToolGroup(2);
+ if (phase == 2) m.toggleToolGroup(4);
+ const c = layout.ensure(&m, w);
+ try testing.expectEqual(scrollback.totalVisualLines(&m, w), c.total);
+ var idx: usize = 0;
+ while (idx < m.history.items.len) : (idx += 1) {
+ try testing.expectEqual(scrollback.visualOfIndex(&m, idx, w), layout.lineOf(c, idx));
+ }
+ var y: usize = 0;
+ while (y < c.total + 3) : (y += 1) {
+ try testing.expectEqual(scrollback.indexAtVisual(&m, y, w), layout.indexAt(c, y));
+ try testing.expectEqual(scrollback.stickyUserAbove(&m, y, w), layout.stickyUserAbove(c, y));
+ }
+ }
+ m.toggleToolGroup(2);
+ m.toggleToolGroup(4);
+ }
+}
+
+test "the live turn's streaming tail and steer notice stay in the layout" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try fixture(&m);
+ var sbuf: [256]u8 = undefined;
+ var none: [0]engine.Turn = .{};
+ var job: engine.Job = .{
+ .gpa = testing.allocator,
+ .history = &none,
+ .params = .{},
+ .stream = .{ .buf = &sbuf },
+ };
+ m.pending = &job;
+ defer m.pending = null;
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+
+ // Nothing streamed yet, then prose arrives a chunk at a time: only the tail
+ // may move, and the whole frame must still match the oracle.
+ for ([_][]const u8{ "", "thinking about it", "\nand a second line", "\nthird" }) |chunk| {
+ if (chunk.len > 0) job.stream.appendBytes(chunk);
+ _ = arena.reset(.retain_capacity);
+ const a = arena.allocator();
+ try testing.expectEqualStrings(try scrollback.render(&m, a, 80, m.now_ms), try cachedAll(&m, a, 80));
+ }
+ const queued = try testing.allocator.dupe(u8, "next thing");
+ try m.steer_queue.append(queued);
+ _ = arena.reset(.retain_capacity);
+ const a = arena.allocator();
+ try testing.expectEqualStrings(try scrollback.render(&m, a, 80, m.now_ms), try cachedAll(&m, a, 80));
+ // A live row belongs to no history entry — clicking it must select nothing.
+ const c = layout.ensure(&m, 80);
+ try testing.expect(layout.indexAt(c, c.total - 1) == null);
+}
+
+test "appending reuses the whole cached prefix; a fold or a width change does not" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try fixture(&m);
+ var i: usize = 0;
+ while (i < 40) : (i += 1) try m.push(.assistant, prose);
+
+ const first = layout.ensure(&m, 80);
+ const blocks = first.blocks.items.len;
+ try testing.expect(blocks > 10);
+ try testing.expectEqual(blocks, first.misses);
+
+ // A frame with nothing changed lays NOTHING out again.
+ first.hits = 0;
+ first.misses = 0;
+ _ = layout.ensure(&m, 80);
+ try testing.expectEqual(@as(u64, 0), first.misses);
+ try testing.expectEqual(@as(u64, blocks), first.hits);
+
+ // An append re-lays out exactly one block, and the prefix is reused.
+ first.hits = 0;
+ first.misses = 0;
+ try m.push(.assistant, "one more");
+ _ = layout.ensure(&m, 80);
+ try testing.expectEqual(@as(u64, 1), first.misses);
+ try testing.expectEqual(@as(u64, blocks), first.hits);
+
+ // A fold touches its own block only.
+ first.hits = 0;
+ first.misses = 0;
+ m.toggleToolGroup(2);
+ _ = layout.ensure(&m, 80);
+ try testing.expectEqual(@as(u64, 1), first.misses);
+
+ // A width change is a cold rebuild; so is a theme change at the same width.
+ const colds = first.colds;
+ _ = layout.ensure(&m, 72);
+ try testing.expectEqual(colds + 1, first.colds);
+ m.theme_id = .day;
+ _ = layout.ensure(&m, 72);
+ try testing.expectEqual(colds + 2, first.colds);
+}
+
+test "a cleared history drops the layout with the entries it points into" {
+ var m: Model = undefined;
+ m.setup(testing.allocator);
+ defer m.deinit();
+ try fixture(&m);
+ const c = layout.ensure(&m, 80);
+ try testing.expect(c.total > 0);
+ m.clearHistory();
+ try testing.expectEqual(@as(usize, 0), m.layout.blocks.items.len);
+ try testing.expectEqual(@as(usize, 0), layout.ensure(&m, 80).total);
+ // And the transcript comes back correctly after the reset.
+ try fixture(&m);
+ var arena = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ try testing.expectEqualStrings(try scrollback.render(&m, a, 80, 0), try cachedAll(&m, a, 80));
+}
+
+// --- benchmark -------------------------------------------------------------
+
+fn p95(v: []u64) u64 {
+ std.mem.sort(u64, v, {}, std.sort.asc(u64));
+ return v[(v.len * 95) / 100];
+}
+
+fn grow(m: *Model, target: usize, width: usize) !void {
+ while (layout.totalVisualLines(m, width) < target) {
+ try m.push(.user, "a user prompt that is long enough to wrap at the narrower widths in the matrix");
+ try m.push(.assistant, prose ++ " " ++ prose);
+ try m.pushTool(.{ .name = "bash", .detail = "printf hello | wc -c" });
+ try m.pushTool(.{ .name = "bash", .detail = "6", .done = true });
+ try m.push(.system, "· a system notice");
+ }
+}
+
+test "layout cache benchmark: frame build while scrolling, and cold rebuild" {
+ const full = std.c.getenv("GRAFF_TUI_BENCH") != null;
+ const target: usize = if (full) 10_000 else 1_200;
+ const frames: usize = if (full) 400 else 40;
+ const gpa = testing.allocator;
+ var m: Model = undefined;
+ m.setup(gpa);
+ defer m.deinit();
+ try grow(&m, target, 100);
+ m.follow = false;
+ const total = layout.totalVisualLines(&m, 100);
+
+ const scroll_ns = try gpa.alloc(u64, frames);
+ defer gpa.free(scroll_ns);
+ const io = std.Io.Threaded.global_single_threaded.io();
+ // Warm the layout so the first sample is a scroll, not the cold build.
+ gpa.free(try render_mod.render(&m, gpa, 100, 40, 0));
+ m.layout.hits = 0;
+ m.layout.misses = 0;
+ for (scroll_ns, 0..) |*slot, i| {
+ m.scroll = (i * 3) % (total - 20);
+ const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;
+ const frame = try render_mod.render(&m, gpa, 100, 40, @intCast(i));
+ slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));
+ gpa.free(frame);
+ }
+ const scroll_p95 = p95(scroll_ns);
+ // Snapshot before the cold loop: those rebuilds are the thing being timed
+ // next, and folding them in here would hide the claim this makes.
+ const scroll_hits = m.layout.hits;
+ const scroll_misses = m.layout.misses;
+
+ var cold_ns: [6]u64 = undefined;
+ for (&cold_ns, 0..) |*slot, i| {
+ const w = widths[i % widths.len];
+ const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;
+ const frame = try render_mod.render(&m, gpa, w, 40, 0);
+ slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));
+ gpa.free(frame);
+ }
+ const cold_max = std.mem.max(u64, &cold_ns);
+ for (cold_ns, 0..) |ns, i| std.debug.print(
+ "[layout-bench] cold rebuild at width {d:>4} = {d:.3} ms\n",
+ .{ widths[i % widths.len], @as(f64, @floatFromInt(ns)) / 1e6 },
+ );
+
+ // The path this replaces, on the same transcript: one uncached full
+ // layout, which is what every wheel tick used to cost.
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ var before: [8]u64 = undefined;
+ for (&before) |*slot| {
+ _ = arena.reset(.retain_capacity);
+ const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;
+ const text = try scrollback.render(&m, arena.allocator(), 100, 0);
+ std.mem.doNotOptimizeAway(text.len);
+ slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));
+ }
+ const before_med = p95(before[0..4]);
+
+ std.debug.print(
+ "\n[layout-bench] mode={s} entries={d} display_lines={d} frames={d}\n" ++
+ " scroll frame build p95 = {d:.3} ms (max {d:.3} ms)\n" ++
+ " cold rebuild after width change, worst of {d} = {d:.3} ms\n" ++
+ " block layouts during the scroll run: {d} reused / {d} rebuilt\n" ++
+ " uncached full layout (the path this replaces) = {d:.3} ms\n",
+ .{
+ if (full) "full" else "smoke", m.history.items.len,
+ total, frames,
+ @as(f64, @floatFromInt(scroll_p95)) / 1e6, @as(f64, @floatFromInt(scroll_ns[scroll_ns.len - 1])) / 1e6,
+ cold_ns.len, @as(f64, @floatFromInt(cold_max)) / 1e6,
+ scroll_hits, scroll_misses,
+ @as(f64, @floatFromInt(before_med)) / 1e6,
+ },
+ );
+
+ // A scroll must never re-lay a block out: that is the whole claim.
+ try testing.expectEqual(@as(u64, 0), scroll_misses);
+ try testing.expect(scroll_hits > 0);
+ if (full) {
+ try testing.expect(total >= 10_000);
+ try testing.expect(scroll_p95 < 1_000_000); // < 1 ms
+ try testing.expect(cold_max < 10_000_000); // < 10 ms
+ }
+}
diff --git a/TUI/nav.zig b/TUI/nav.zig
index 361deba6..d28300e2 100644
--- a/TUI/nav.zig
+++ b/TUI/nav.zig
@@ -64,7 +64,7 @@ pub fn jumpTo(self: *Model, idx: usize) void {
self.selected = idx;
self.focus = .scrollback;
self.follow = false;
- const sb = @import("scrollback.zig");
+ const sb = @import("layout_cache.zig");
const width = if (self.last_term_width == 0) 80 else self.last_term_width;
const total = sb.totalVisualLines(self, width);
const at = sb.visualOfIndex(self, idx, width) orelse return;
diff --git a/TUI/render.zig b/TUI/render.zig
index 9610947f..375cfe71 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -8,7 +8,7 @@ const anchor = @import("anchor.zig");
const app = @import("app.zig");
const chrome = @import("chrome.zig");
const engine = @import("engine.zig");
-const scrollback = @import("scrollback.zig");
+const layout_cache = @import("layout_cache.zig");
const selection = @import("selection.zig");
const theme_mod = @import("theme.zig");
const welcome = @import("welcome.zig");
@@ -50,16 +50,20 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
// The image overlay is a card ABOVE the composer, so `mid` stays the
// transcript; every other overlay replaces it with its own body.
const overlay_body = self.overlay != .none and self.overlay != .image;
+ // Anything in the transcript — including a live background op's pending
+ // row — outranks the welcome pane: keeping it up hid a running `!cmd`/
+ // @-list entirely and froze the paint loop (the welcome frame is static,
+ // so the hash-diff suppressed every paint).
+ const welcome_pane = self.screen == .welcome and self.history.items.len == 0 and self.pending == null;
const mid = if (overlay_body)
try theme_mod.wrapToWidth(a, try chrome.overlay(self, a, width), width)
- else if (self.screen == .welcome and self.history.items.len == 0 and self.pending == null)
- // Anything in the transcript — including a live background op's
- // pending row — outranks the welcome pane: keeping it up hid a
- // running `!cmd`/@-list entirely and froze the paint loop (the
- // welcome frame is static, so the hash-diff suppressed every paint).
+ else if (welcome_pane)
try welcome.render(self, a, width)
else
- try scrollback.render(self, a, width, now_ms);
+ "";
+ // The transcript is never composed whole: the layout cache holds its
+ // wrapped lines and the frame takes a SLICE of them (layout_cache.zig).
+ const cache: ?*layout_cache.Cache = if (overlay_body or welcome_pane) null else layout_cache.ensure(self, width);
const slash = try chrome.slashMenu(self, a, width);
const prompt = try chrome.promptBox(self, a, width);
const status = try chrome.statusBar(self, a, width);
@@ -95,20 +99,22 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
const view_h: usize = if (height > used) height - used else 1;
var mid_lines = std.array_list.Managed([]const u8).init(a);
- var it = std.mem.splitScalar(u8, mid, '\n');
- while (it.next()) |ln| try mid_lines.append(ln);
- if (mid_lines.items.len > 0 and mid_lines.items[mid_lines.items.len - 1].len == 0) _ = mid_lines.pop();
+ if (cache == null) {
+ var it = std.mem.splitScalar(u8, mid, '\n');
+ while (it.next()) |ln| try mid_lines.append(ln);
+ if (mid_lines.items.len > 0 and mid_lines.items[mid_lines.items.len - 1].len == 0) _ = mid_lines.pop();
+ }
var out = std.array_list.Managed(u8).init(a);
try out.appendSlice(top);
if (top.len > 0 and top[top.len - 1] != '\n') try out.append('\n');
- const n = mid_lines.items.len;
+ const n = if (cache) |c| c.total else mid_lines.items.len;
self.sticky_rows = 0;
if (n <= view_h) {
self.scroll = 0;
self.mid_skip = 0;
- for (mid_lines.items) |ln| {
+ for (try midSlice(a, cache, mid_lines.items, 0, n)) |ln| {
try out.appendSlice(ln);
try out.append('\n');
}
@@ -120,7 +126,9 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
// Put the anchored logical line back on the top row. Saturating: when
// the rewrap pushed it past the last possible top line the viewport
// parks at the bottom, which still shows it.
- if (rewrap) |anc| self.scroll = max_scroll -| anchor.rowAt(self, anc, width);
+ if (rewrap) |anc| {
+ if (cache) |c| self.scroll = max_scroll -| anchor.rowAt(self, c, anc);
+ }
if (self.scroll > max_scroll) self.scroll = max_scroll;
const start = max_scroll - self.scroll;
self.mid_skip = start;
@@ -134,7 +142,7 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
// is the overlay's own body, and a long one (/help, /models) scrolls
// too — ungated, this pinned a user prompt over its first two rows.
if (!overlay_body and view_h >= 5) {
- if (scrollback.stickyUserAbove(self, start, width)) |utext| {
+ if (if (cache) |c| layout_cache.stickyUserAbove(c, start) else null) |utext| {
const th = self.theme();
var head = std.array_list.Managed(u8).init(a);
try head.appendSlice(th.accent);
@@ -152,7 +160,7 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
self.sticky_rows = 2;
}
}
- for (mid_lines.items[start + chrome_rows .. start + view_h]) |ln| {
+ for (try midSlice(a, cache, mid_lines.items, start + chrome_rows, view_h - chrome_rows)) |ln| {
try out.appendSlice(ln);
try out.append('\n');
}
@@ -168,6 +176,16 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
return gpa.dupe(u8, try selection.paint(self, a, out.items, width));
}
+/// `count` mid rows starting at `from`, taken from the layout cache when the
+/// mid IS the transcript and from the composed overlay/welcome lines otherwise.
+/// The cached path never materialises the rows outside the viewport, which is
+/// the whole point: a wheel tick copies a screenful, not a transcript.
+fn midSlice(a: std.mem.Allocator, cache: ?*layout_cache.Cache, lines: [][]const u8, from: usize, count: usize) ![]const []const u8 {
+ if (cache) |c| return layout_cache.window(c, a, from, count);
+ const end = @min(lines.len, from + count);
+ return lines[@min(from, end)..end];
+}
+
fn countLines(s: []const u8) usize {
if (s.len == 0) return 0;
return std.mem.count(u8, s, "\n") + 1;
diff --git a/TUI/root.zig b/TUI/root.zig
index 453e6273..0f24f9e0 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -60,6 +60,7 @@ test {
_ = @import("bgop.zig");
_ = @import("welcome.zig");
_ = @import("scrollback.zig");
+ _ = @import("layout_cache.zig");
_ = @import("selection.zig");
_ = @import("chrome.zig");
_ = @import("models.zig");
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index 1186e025..1b765a5a 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -1,4 +1,5 @@
-//! Conversation scrollback. ANSI only.
+//! Conversation scrollback. ANSI only. render() is the uncached full layout
+//! that layout_cache.zig memoizes per block and that its tests hold it to.
//! Consecutive tool rows collapse into a Grok-style summary until expanded.
const std = @import("std");
@@ -39,7 +40,7 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6
if (!first) try out.append('\n');
first = false;
const selected = self.focus == .scrollback and i == self.selected;
- try out.appendSlice(try row(self, a, i, e, width, now_ms, selected));
+ try out.appendSlice(try row(self, a, userNo(self, i), e, width, now_ms, selected));
i += 1;
}
if (self.pending) |job| {
@@ -86,7 +87,7 @@ pub fn indexAtVisual(self: *const Model, visual_row: usize, width: usize) ?usize
i = run.end;
continue;
}
- const s = row(self, a, i, self.history.items[i], width, self.now_ms, false) catch "";
+ const s = row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "";
const lines = lineCount(s);
if (visual_row >= v and visual_row < v + lines) return i;
v += lines;
@@ -129,7 +130,7 @@ pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {
continue;
}
if (i == idx) return v;
- v += lineCount(row(self, a, i, self.history.items[i], width, self.now_ms, false) catch "");
+ v += lineCount(row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "");
i += 1;
}
return null;
@@ -163,13 +164,13 @@ pub fn stickyUserAbove(self: *const Model, top_line: usize, width: usize) ?[]con
continue;
}
if (e.kind == .user and v < top_line) best = e.text;
- v += lineCount(row(self, a, i, e, width, self.now_ms, false) catch "");
+ v += lineCount(row(self, a, userNo(self, i), e, width, self.now_ms, false) catch "");
i += 1;
}
return best;
}
-fn lineCount(s: []const u8) usize {
+pub fn lineCount(s: []const u8) usize {
if (s.len == 0) return 1;
return std.mem.count(u8, s, "\n") + 1;
}
@@ -207,7 +208,7 @@ fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {
return false;
}
-fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, selected: bool) ![]const u8 {
+pub fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, selected: bool) ![]const u8 {
const th = self.theme();
var searches: usize = 0;
var calls: usize = 0;
@@ -237,7 +238,7 @@ fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, s
return out.items;
}
-fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width: usize, now_ms: u64, selected: bool) ![]const u8 {
+pub fn row(self: *const Model, a: std.mem.Allocator, user_no: u32, e: app.Entry, width: usize, now_ms: u64, selected: bool) ![]const u8 {
const th = self.theme();
const mark: []const u8 = switch (e.kind) {
.user => "",
@@ -270,7 +271,7 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width
};
const sel: []const u8 = if (selected) "› " else " ";
if (e.kind == .user) {
- const line = try std.fmt.allocPrint(a, "{s}{s}#{d}{s} {s}", .{ sel, th.muted, userNo(self, idx), theme_mod.reset, body });
+ const line = try std.fmt.allocPrint(a, "{s}{s}#{d}{s} {s}", .{ sel, th.muted, user_no, theme_mod.reset, body });
return theme_mod.wrapToWidth(a, line, width);
}
if (e.kind == .pending) {
@@ -303,7 +304,7 @@ fn isDoneTool(e: app.Entry) bool {
return t.done;
}
-fn nextTool(self: *const Model, t: usize, end: usize) usize {
+pub fn nextTool(self: *const Model, t: usize, end: usize) usize {
if (t + 1 < end and isStartTool(self.history.items[t]) and isDoneTool(self.history.items[t + 1]))
return t + 2;
return t + 1;
@@ -349,7 +350,7 @@ fn toolPreview(e: app.Entry) ?[]const u8 {
return t.detail;
}
-fn toolVisual(
+pub fn toolVisual(
self: *const Model,
a: std.mem.Allocator,
t: usize,
@@ -360,7 +361,7 @@ fn toolVisual(
) ![]const u8 {
const e = self.history.items[t];
const paired = t + 1 < end and isStartTool(e) and isDoneTool(self.history.items[t + 1]);
- if (!paired) return row(self, a, t, e, width, now_ms, selected);
+ if (!paired) return row(self, a, 0, e, width, now_ms, selected); // a tool row is never numbered
return toolCard(a, self.theme(), e, self.history.items[t + 1], selected, width);
}
@@ -395,7 +396,7 @@ fn firstLine(s: []const u8) []const u8 {
return s;
}
-fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
+pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
var out = std.array_list.Managed(u8).init(a);
var i: usize = 0;
while (i < s.len) {
@@ -409,7 +410,7 @@ fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
return out.items;
}
-fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {
+pub fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {
var lines = std.array_list.Managed([]const u8).init(a);
var it = std.mem.splitScalar(u8, s, '\n');
// No tool-line filter any more: the live buffer carries PROSE only —
diff --git a/build.zig b/build.zig
index 8ea7ff4b..c0442051 100644
--- a/build.zig
+++ b/build.zig
@@ -183,6 +183,9 @@ pub fn build(b: *std.Build) void {
.target = target,
.optimize = optimize,
}),
+ // Same -Dtest-filter as `zig build test`: the layout benchmark needs to
+ // be runnable on its own, ReleaseFast, without the rest of the suite.
+ .filters = test_filters,
});
tui_tests.root_module.addAnonymousImport("spec_terminal_modes", .{ .root_source_file = b.path("spec/kernels/terminal_modes.json") });