summaryrefslogtreecommitdiff
path: root/src/tui_components.zig
diff options
context:
space:
mode:
authort <t@tjp.lol>2026-06-08 14:48:33 -0600
committert <t@tjp.lol>2026-06-08 19:56:47 -0600
commit104001d25c9c8cb5ec45ced1678f7c7b70888808 (patch)
treee0fd9d5c89e953dd9db9253b87be8426e56d63f1 /src/tui_components.zig
parentb5eb3f1776a540a55d5675f786a4421c49a6283d (diff)
keybinding fixes
Diffstat (limited to 'src/tui_components.zig')
-rw-r--r--src/tui_components.zig1244
1 files changed, 1237 insertions, 7 deletions
diff --git a/src/tui_components.zig b/src/tui_components.zig
index 3dfe817..b2ed842 100644
--- a/src/tui_components.zig
+++ b/src/tui_components.zig
@@ -369,8 +369,20 @@ pub const InputBox = struct {
/// or `takeSubmitted`.
submitted: std.ArrayList(u8) = .empty,
has_submitted: bool = false,
+ /// Maximum number of VISUAL rows the box renders at once (plan §6 / P2).
+ /// When the wrapped/`\n`-split buffer exceeds this many rows, the box
+ /// renders only a `line_cap`-tall SCROLL-WINDOW that follows the cursor
+ /// (so the cursor row stays visible). The default is 8. A single-row
+ /// buffer still renders one row — the cap is a ceiling, not a floor, so
+ /// the existing "single-row default, grow one row per line" behavior is
+ /// preserved up to the cap.
+ line_cap: usize = default_line_cap,
cache: RenderCache,
+ /// Default visual-row cap (plan §6, P2): show at most the last 8 contiguous
+ /// lines once the buffer grows past the window.
+ pub const default_line_cap: usize = 8;
+
pub fn init(alloc: std.mem.Allocator) InputBox {
return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
}
@@ -406,6 +418,23 @@ pub const InputBox = struct {
return self.submitted.items;
}
+ // -- buffer access (for the Ctrl+G $EDITOR round-trip) -----------------
+
+ /// The current editor contents (box-owned; valid until the next edit).
+ /// Used by the app's Ctrl+G handler to seed the external-editor tempfile.
+ pub fn buffer(self: *const InputBox) []const u8 {
+ return self.text.items;
+ }
+
+ /// Replace the whole editor buffer (e.g. with text edited in `$EDITOR`).
+ /// Places the cursor at the end and marks dirty.
+ pub fn setBuffer(self: *InputBox, bytes: []const u8) !void {
+ self.text.clearRetainingCapacity();
+ try self.text.appendSlice(self.alloc, bytes);
+ self.cursor = self.text.items.len;
+ self.cache.markDirty();
+ }
+
// -- editing primitives (also directly unit-testable) ------------------
fn insertText(self: *InputBox, bytes: []const u8) !void {
@@ -457,6 +486,116 @@ pub const InputBox = struct {
self.cache.markDirty();
}
+ /// Byte index of the start of the current LOGICAL line (the byte just after
+ /// the previous '\n', or 0). "Logical line" = a run delimited by '\n' in
+ /// the buffer, independent of visual wrapping.
+ fn lineStart(self: *const InputBox, at: usize) usize {
+ if (at == 0) return 0;
+ if (std.mem.lastIndexOfScalar(u8, self.text.items[0..at], '\n')) |nl| return nl + 1;
+ return 0;
+ }
+
+ /// Byte index of the end of the current LOGICAL line (the next '\n' at or
+ /// after `at`, or the buffer end).
+ fn lineEnd(self: *const InputBox, at: usize) usize {
+ if (std.mem.indexOfScalarPos(u8, self.text.items, at, '\n')) |nl| return nl;
+ return self.text.items.len;
+ }
+
+ /// Move the cursor to the start of the current logical line (Ctrl+A).
+ fn moveLineStart(self: *InputBox) void {
+ const dest = self.lineStart(self.cursor);
+ if (dest == self.cursor) return;
+ self.cursor = dest;
+ self.cache.markDirty();
+ }
+
+ /// Move the cursor to the end of the current logical line (Ctrl+E).
+ fn moveLineEnd(self: *InputBox) void {
+ const dest = self.lineEnd(self.cursor);
+ if (dest == self.cursor) return;
+ self.cursor = dest;
+ self.cache.markDirty();
+ }
+
+ /// Whether the codepoint starting at byte `i` is "word" whitespace for
+ /// word-motion. We treat ASCII spaces, tabs, and newlines as separators.
+ fn isWordSep(self: *const InputBox, i: usize) bool {
+ const b = self.text.items[i];
+ return b == ' ' or b == '\t' or b == '\n';
+ }
+
+ /// Byte index one word to the LEFT of `from` (standard word-motion: skip a
+ /// run of separators, then a run of non-separators). Returns 0 at the
+ /// start. Operates on codepoint boundaries.
+ fn prevWord(self: *const InputBox, from: usize) usize {
+ var i = from;
+ // Skip separators immediately to the left.
+ while (i > 0) {
+ const p = self.prevBoundary(i);
+ if (!self.isWordSep(p)) break;
+ i = p;
+ }
+ // Skip the word (non-separators) to the left.
+ while (i > 0) {
+ const p = self.prevBoundary(i);
+ if (self.isWordSep(p)) break;
+ i = p;
+ }
+ return i;
+ }
+
+ /// Byte index one word to the RIGHT of `from` (skip a run of non-separators,
+ /// then a run of separators). Returns the buffer end at the end. Operates on
+ /// codepoint boundaries.
+ fn nextWord(self: *const InputBox, from: usize) usize {
+ var i = from;
+ const len = self.text.items.len;
+ // Skip the word (non-separators) to the right.
+ while (i < len and !self.isWordSep(i)) i = self.nextBoundary(i);
+ // Skip trailing separators.
+ while (i < len and self.isWordSep(i)) i = self.nextBoundary(i);
+ return i;
+ }
+
+ /// Move one word left (Alt+Left / Ctrl+Left).
+ fn moveWordLeft(self: *InputBox) void {
+ if (self.cursor == 0) return;
+ self.cursor = self.prevWord(self.cursor);
+ self.cache.markDirty();
+ }
+
+ /// Move one word right (Alt+Right / Ctrl+Right).
+ fn moveWordRight(self: *InputBox) void {
+ if (self.cursor >= self.text.items.len) return;
+ self.cursor = self.nextWord(self.cursor);
+ self.cache.markDirty();
+ }
+
+ /// Delete from the cursor back to the start of the current logical line
+ /// (Ctrl+U). A PLAIN delete — no kill-ring / yank buffer is kept.
+ fn deleteToLineStart(self: *InputBox) void {
+ const start = self.lineStart(self.cursor);
+ if (start == self.cursor) return;
+ const removed = self.cursor - start;
+ std.mem.copyForwards(u8, self.text.items[start..], self.text.items[self.cursor..]);
+ self.text.items.len -= removed;
+ self.cursor = start;
+ self.cache.markDirty();
+ }
+
+ /// Delete the previous word (Ctrl+W). A PLAIN delete — no kill-ring.
+ fn deletePrevWord(self: *InputBox) void {
+ if (self.cursor == 0) return;
+ const start = self.prevWord(self.cursor);
+ if (start == self.cursor) return;
+ const removed = self.cursor - start;
+ std.mem.copyForwards(u8, self.text.items[start..], self.text.items[self.cursor..]);
+ self.text.items.len -= removed;
+ self.cursor = start;
+ self.cache.markDirty();
+ }
+
fn submit(self: *InputBox) !void {
self.submitted.clearRetainingCapacity();
try self.submitted.appendSlice(self.alloc, self.text.items);
@@ -491,7 +630,52 @@ pub const InputBox = struct {
if (k.event == .release) return;
switch (k.code) {
.char => {
- if (k.mods.ctrl or k.mods.alt or k.mods.super) return; // not a printable insert
+ // Ctrl/Alt chord bindings (standard editing shortcuts). These
+ // are handled BEFORE the printable-insert path, which rejects
+ // modified chars. NONE of these keep a kill-ring / yank buffer
+ // — they are plain moves/deletes (plan P2: no kill-ring/undo).
+ if (k.mods.ctrl and !k.mods.alt and !k.mods.super) {
+ switch (std.ascii.toLower(@intCast(k.code.char & 0x7f))) {
+ 'u' => {
+ self.deleteToLineStart(); // delete to line start
+ return;
+ },
+ 'w' => {
+ self.deletePrevWord(); // delete previous word
+ return;
+ },
+ 'a' => {
+ self.moveLineStart(); // start of line
+ return;
+ },
+ 'e' => {
+ self.moveLineEnd(); // end of line
+ return;
+ },
+ else => return, // other ctrl chords: ignore (Ctrl+G
+ // handled at the app level, never reaches the box).
+ }
+ }
+ // Alt-chord word bindings. Many terminals (notably Ghostty
+ // and macOS terminals) send Alt+Left/Right as the classic
+ // readline `ESC b` / `ESC f` rather than a modified arrow CSI,
+ // so they arrive here as alt+b / alt+f char keys. Map them to
+ // the same word-motion as Alt/Ctrl+Arrow so word navigation
+ // works regardless of which form the terminal emits.
+ if (k.mods.alt and !k.mods.ctrl and !k.mods.super) {
+ switch (std.ascii.toLower(@intCast(k.code.char & 0x7f))) {
+ 'b' => {
+ self.moveWordLeft();
+ return;
+ },
+ 'f' => {
+ self.moveWordRight();
+ return;
+ },
+ else => return, // other alt chords: ignore (not text)
+ }
+ }
+ if (k.mods.alt or k.mods.super) return; // not a printable insert
if (k.text) |t| {
try self.insertText(t);
} else {
@@ -508,13 +692,18 @@ pub const InputBox = struct {
try self.submit();
}
},
- .backspace => self.backspace(),
+ // Alt/Ctrl+Backspace deletes the previous word (readline
+ // convention); plain Backspace deletes one codepoint.
+ .backspace => if (k.mods.alt or k.mods.ctrl) self.deletePrevWord() else self.backspace(),
.delete => self.deleteForward(),
- .left => self.moveLeft(),
- .right => self.moveRight(),
+ // Word-motion: Alt+Left/Right (xterm/kitty) and Ctrl+Left/Right
+ // (many terminals send `1;5D`/`1;5C`). Plain Left/Right move by one
+ // codepoint.
+ .left => if (k.mods.alt or k.mods.ctrl) self.moveWordLeft() else self.moveLeft(),
+ .right => if (k.mods.alt or k.mods.ctrl) self.moveWordRight() else self.moveRight(),
.home => self.moveHome(),
.end => self.moveEnd(),
- else => {}, // tab, arrows up/down, fkeys: ignored in P1
+ else => {}, // tab, arrows up/down, fkeys: ignored
}
}
@@ -545,6 +734,13 @@ pub const InputBox = struct {
/// Render the editor: split on '\n' into visual rows, place the styled
/// cursor block + CURSOR_MARKER at the cursor row/column when focused.
/// Truncates each row to `width` columns.
+ ///
+ /// Scroll-window (plan §6, P2): when the buffer produces more than
+ /// `line_cap` rows, only a `line_cap`-tall window is rendered. The window
+ /// FOLLOWS the cursor — it always contains the cursor's row — and defaults
+ /// to the LAST `line_cap` rows (so a freshly grown buffer shows its tail,
+ /// where the cursor usually is). A single-row buffer is unaffected: the cap
+ /// is a ceiling, not a floor.
fn renderLines(self: *InputBox, width: usize) ![]const []const u8 {
const a = self.alloc;
var rows: std.ArrayList([]const u8) = .empty;
@@ -558,8 +754,11 @@ pub const InputBox = struct {
const focused = self.focusable.focused;
// Walk lines, tracking byte offset so we know which row holds cursor.
+ // `cursor_row` records which produced row carries the cursor block, so
+ // the scroll-window below can keep it visible.
var line_byte_start: usize = 0;
var produced_any = false;
+ var cursor_row: usize = 0;
var it = std.mem.splitScalar(u8, self.text.items, '\n');
while (it.next()) |line| {
const line_start = line_byte_start;
@@ -572,6 +771,7 @@ pub const InputBox = struct {
// line's start unless this is the last line.
(self.cursor < line_end or it.peek() == null);
+ if (cursor_in_line) cursor_row = rows.items.len;
const row = try self.renderRow(line, if (cursor_in_line) self.cursor - line_start else null, cursor_style, width, focused);
try rows.append(a, row);
produced_any = true;
@@ -583,10 +783,38 @@ pub const InputBox = struct {
try rows.append(a, row);
}
- try self.cache.store(rows.items);
+ // Apply the scroll-window: store at most `line_cap` rows, the window
+ // defaulting to the tail and sliding up to keep the focused cursor row
+ // visible. When unfocused there is no live cursor, so we never slide
+ // up — the tail window stands.
+ const window = self.scrollWindow(rows.items.len, if (focused) cursor_row else null);
+ try self.cache.store(rows.items[window.start..window.end]);
return cacheLines(&self.cache);
}
+ /// Compute the visible `[start, end)` row range for the scroll-window given
+ /// the total produced rows and (optionally) the focused cursor's row.
+ /// Returns the whole range when `total <= line_cap` (or the cap is
+ /// 0/disabled). Otherwise returns a `line_cap`-tall window biased toward the
+ /// TAIL: the default window is the last `line_cap` rows, sliding UP only as
+ /// far as needed to keep `cursor_row` visible. A null `cursor_row` (no live
+ /// cursor / unfocused) leaves the tail window in place.
+ const Window = struct { start: usize, end: usize };
+ fn scrollWindow(self: *const InputBox, total: usize, cursor_row: ?usize) Window {
+ const cap = self.line_cap;
+ if (cap == 0 or total <= cap) return .{ .start = 0, .end = total };
+
+ // Default to the last `cap` rows.
+ var start = total - cap;
+ // Slide the window up if the focused cursor is above it (keep the cursor
+ // row in view). The cursor is never below the tail window, so no
+ // downward slide is needed.
+ if (cursor_row) |cr| {
+ if (cr < start) start = cr;
+ }
+ return .{ .start = start, .end = start + cap };
+ }
+
/// Render one visual row. `cursor_col` is the byte offset within `line`
/// where the cursor sits (null if the cursor isn't on this row). When
/// present and focused, draws a reverse-video block over the glyph at the
@@ -709,6 +937,11 @@ pub const Footer = struct {
frame_ms: ?f64 = null,
/// Model info string (borrowed; copied into a small owned buffer on set).
model: std.ArrayList(u8) = .empty,
+ /// Latest context-window size in tokens (null = no usage reported yet).
+ /// Overwritten on each `message_complete` with the most recent value, not
+ /// accumulated. Defined (plan §6) as
+ /// `usage.input + usage.cache_read + usage.cache_write`.
+ context_tokens: ?u64 = null,
pub fn init(alloc: std.mem.Allocator) Footer {
return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
@@ -733,6 +966,24 @@ pub const Footer = struct {
self.cache.markDirty();
}
+ /// Set the latest context-window token count (plan §6). The caller passes
+ /// the already-summed `input + cache_read + cache_write`. Overwrites the
+ /// previous value (latest-wins) and marks dirty so the footer repaints.
+ pub fn setContextTokens(self: *Footer, tokens: u64) void {
+ self.context_tokens = tokens;
+ self.cache.markDirty();
+ }
+
+ /// Format the context-window element: e.g. "12.3k ctx" for large counts,
+ /// "845 ctx" for small ones. "" (empty) when no usage reported yet, so the
+ /// element is simply absent until the first `message_complete`.
+ fn contextText(self: *const Footer, buf: []u8) []const u8 {
+ const n = self.context_tokens orelse return "";
+ if (n < 1000) return std.fmt.bufPrint(buf, "{d} ctx", .{n}) catch "";
+ const k = @as(f64, @floatFromInt(n)) / 1000.0;
+ return std.fmt.bufPrint(buf, "{d:.1}k ctx", .{k}) catch "";
+ }
+
/// Format the theoretical-max fps element from the last frame time.
/// `fps = 1000 / ms`; a zero/sub-millisecond frame is reported as a capped
/// ">9999" sentinel rather than infinity. "--" when unmeasured.
@@ -751,14 +1002,21 @@ pub const Footer = struct {
var fps_buf: [48]u8 = undefined;
const fps = self.fpsText(&fps_buf);
+ var ctx_buf: [32]u8 = undefined;
+ const ctx = self.contextText(&ctx_buf);
- // Build the PLAIN content: "<model> <fps>" (model only if set).
+ // Build the PLAIN content: "<model> <ctx> <fps>" (model and ctx
+ // only when present).
var plain: std.ArrayList(u8) = .empty;
defer plain.deinit(a);
if (self.model.items.len != 0) {
try plain.appendSlice(a, self.model.items);
try plain.appendSlice(a, " ");
}
+ if (ctx.len != 0) {
+ try plain.appendSlice(a, ctx);
+ try plain.appendSlice(a, " ");
+ }
try plain.appendSlice(a, fps);
const vis = truncateToCols(plain.items, width);
@@ -797,6 +1055,448 @@ pub const Footer = struct {
};
// ===========================================================================
+// Welcome — session-start banner (plan §6: "version, cwd, model info")
+// ===========================================================================
+
+/// A static banner shown as the first transcript entry at session start.
+/// Structured data in (version / cwd / model label via setters), lines out.
+/// Re-rendered only when one of the fields changes (markDirty), which in
+/// practice is once during bring-up.
+pub const Welcome = struct {
+ alloc: std.mem.Allocator,
+ cache: RenderCache,
+ version: std.ArrayList(u8) = .empty,
+ cwd: std.ArrayList(u8) = .empty,
+ model: std.ArrayList(u8) = .empty,
+
+ pub fn init(alloc: std.mem.Allocator) Welcome {
+ return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
+ }
+
+ pub fn deinit(self: *Welcome) void {
+ self.version.deinit(self.alloc);
+ self.cwd.deinit(self.alloc);
+ self.model.deinit(self.alloc);
+ self.cache.deinit();
+ }
+
+ fn setField(self: *Welcome, field: *std.ArrayList(u8), value: []const u8) !void {
+ field.clearRetainingCapacity();
+ try field.appendSlice(self.alloc, value);
+ self.cache.markDirty();
+ }
+
+ /// Set the panto version string (e.g. "0.1.0").
+ pub fn setVersion(self: *Welcome, value: []const u8) !void {
+ try self.setField(&self.version, value);
+ }
+
+ /// Set the working directory shown in the banner.
+ pub fn setCwd(self: *Welcome, value: []const u8) !void {
+ try self.setField(&self.cwd, value);
+ }
+
+ /// Set the model label shown in the banner.
+ pub fn setModel(self: *Welcome, value: []const u8) !void {
+ try self.setField(&self.model, value);
+ }
+
+ fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
+ _ = alloc;
+ const self: *Welcome = @ptrCast(@alignCast(ptr));
+ const a = self.alloc;
+ const accent = theme.default.fg(.welcome);
+ const dim = theme.default.fg(.dim);
+
+ // Transient owned lines; freed after the cache dupes them.
+ var lines: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (lines.items) |l| a.free(l);
+ lines.deinit(a);
+ }
+
+ // Title line: "panto v<version>" in the accent color.
+ {
+ const title_plain = if (self.version.items.len != 0)
+ try std.fmt.allocPrint(a, "panto v{s}", .{self.version.items})
+ else
+ try std.fmt.allocPrint(a, "panto", .{});
+ defer a.free(title_plain);
+ const vis = truncateToCols(title_plain, width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ accent.open(), vis, accent.close() }));
+ }
+
+ // Detail lines (dim): cwd and model, only when set.
+ if (self.cwd.items.len != 0) {
+ const plain = try std.fmt.allocPrint(a, "cwd: {s}", .{self.cwd.items});
+ defer a.free(plain);
+ const vis = truncateToCols(plain, width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
+ }
+ if (self.model.items.len != 0) {
+ const plain = try std.fmt.allocPrint(a, "model: {s}", .{self.model.items});
+ defer a.free(plain);
+ const vis = truncateToCols(plain, width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
+ }
+
+ try self.cache.store(lines.items);
+ return cacheLines(&self.cache);
+ }
+
+ fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
+ const self: *Welcome = @ptrCast(@alignCast(ptr));
+ return self.cache.firstLineChanged();
+ }
+
+ fn invalidateImpl(ptr: *anyopaque) void {
+ const self: *Welcome = @ptrCast(@alignCast(ptr));
+ self.cache.invalidate();
+ }
+
+ const vtable = Component.VTable{
+ .render = renderImpl,
+ .firstLineChanged = firstLineChangedImpl,
+ .invalidate = invalidateImpl,
+ };
+
+ pub fn comp(self: *Welcome) Component {
+ return .{ .ptr = self, .vtable = &vtable };
+ }
+};
+
+// ===========================================================================
+// Thinking — streaming thinking deltas (plan §6: dimmed; streams)
+// ===========================================================================
+
+/// Accumulates thinking content deltas into an internal buffer and renders the
+/// wrapped text with the theme's `thinking` (dim) style. Shares AssistantText's
+/// streaming-tail dirty model (`appendDelta` + `markDirtyAppend`), so the cut
+/// stays near the tail while reasoning streams. It is its OWN component type
+/// (not a styled AssistantText) so the component taxonomy is honest: the engine
+/// and any future event/handler logic can distinguish a thinking block from an
+/// assistant body.
+pub const Thinking = struct {
+ alloc: std.mem.Allocator,
+ buffer: std.ArrayList(u8) = .empty,
+ cache: RenderCache,
+
+ pub fn init(alloc: std.mem.Allocator) Thinking {
+ return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
+ }
+
+ pub fn deinit(self: *Thinking) void {
+ self.buffer.deinit(self.alloc);
+ self.cache.deinit();
+ }
+
+ /// Append a streaming thinking delta. Retains the baseline so the cache
+ /// diff recovers the true tail change point (firstLineChanged near the end).
+ pub fn appendDelta(self: *Thinking, delta: []const u8) !void {
+ try self.buffer.appendSlice(self.alloc, delta);
+ self.cache.markDirtyAppend();
+ }
+
+ /// Replace the whole buffer. Marks dirty.
+ pub fn setText(self: *Thinking, text: []const u8) !void {
+ self.buffer.clearRetainingCapacity();
+ try self.buffer.appendSlice(self.alloc, text);
+ self.cache.markDirty();
+ }
+
+ fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
+ _ = alloc;
+ const self: *Thinking = @ptrCast(@alignCast(ptr));
+ return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.thinking), width, self.alloc);
+ }
+
+ fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
+ const self: *Thinking = @ptrCast(@alignCast(ptr));
+ return self.cache.firstLineChanged();
+ }
+
+ fn invalidateImpl(ptr: *anyopaque) void {
+ const self: *Thinking = @ptrCast(@alignCast(ptr));
+ self.cache.invalidate();
+ }
+
+ const vtable = Component.VTable{
+ .render = renderImpl,
+ .firstLineChanged = firstLineChangedImpl,
+ .invalidate = invalidateImpl,
+ };
+
+ pub fn comp(self: *Thinking) Component {
+ return .{ .ptr = self, .vtable = &vtable };
+ }
+};
+
+// ===========================================================================
+// CompactionSummary — shown when context is compacted (plan §6)
+// ===========================================================================
+
+/// Renders a compaction summary (the synthetic seed text that replaces a
+/// compacted conversation prefix). Structured data in (the summary string via
+/// `setSummary`), lines out. Styled as dim chrome with a short prefix so it
+/// reads as a system event rather than assistant prose.
+pub const CompactionSummary = struct {
+ alloc: std.mem.Allocator,
+ buffer: std.ArrayList(u8) = .empty,
+ cache: RenderCache,
+
+ pub fn init(alloc: std.mem.Allocator) CompactionSummary {
+ return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
+ }
+
+ pub fn deinit(self: *CompactionSummary) void {
+ self.buffer.deinit(self.alloc);
+ self.cache.deinit();
+ }
+
+ /// Set the compaction summary text. Marks dirty.
+ pub fn setSummary(self: *CompactionSummary, text: []const u8) !void {
+ self.buffer.clearRetainingCapacity();
+ try self.buffer.appendSlice(self.alloc, text);
+ self.cache.markDirty();
+ }
+
+ fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
+ _ = alloc;
+ const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
+ const a = self.alloc;
+ const style = theme.default.fg(.compaction);
+
+ // Wrap a header line plus the summary body, all styled as compaction
+ // chrome. The header makes the event legible even when the summary is
+ // empty.
+ var plain: std.ArrayList([]const u8) = .empty;
+ defer plain.deinit(a);
+ try plain.append(a, "[context compacted]");
+ try wrapBuffer(self.buffer.items, width, &plain, a);
+
+ var styled: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (styled.items) |s| a.free(s);
+ styled.deinit(a);
+ }
+ for (plain.items) |line| {
+ const vis = truncateToCols(line, width);
+ try styled.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ style.open(), vis, style.close() }));
+ }
+
+ try self.cache.store(styled.items);
+ return cacheLines(&self.cache);
+ }
+
+ fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
+ const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
+ return self.cache.firstLineChanged();
+ }
+
+ fn invalidateImpl(ptr: *anyopaque) void {
+ const self: *CompactionSummary = @ptrCast(@alignCast(ptr));
+ self.cache.invalidate();
+ }
+
+ const vtable = Component.VTable{
+ .render = renderImpl,
+ .firstLineChanged = firstLineChangedImpl,
+ .invalidate = invalidateImpl,
+ };
+
+ pub fn comp(self: *CompactionSummary) Component {
+ return .{ .ptr = self, .vtable = &vtable };
+ }
+};
+
+// ===========================================================================
+// ToolUse — one component owns the whole call + result (plan §6, P2)
+// ===========================================================================
+
+/// A single component that owns an entire tool call: its name, its streamed
+/// input (verbatim JSON args), and its result output. Render progression
+/// (plan §6 / P2 table):
+///
+/// 1. At creation (block_start), name unknown: `tool (?)…`
+/// 2. Once args finish streaming (name known): `tool (<name>) <input json>`
+/// followed by a blank line and `(…)` as a result placeholder.
+/// 3. Once the result lands: `tool (<name>) <input json>`
+/// followed by a blank line and the result output text.
+///
+/// The input JSON is rendered VERBATIM (no pretty-print), terminal-wrapped to
+/// width. It accumulates from the ToolUse block's `content_delta`s (the deltas
+/// ARE the streaming JSON args), or is set wholesale from the completed block.
+///
+/// Collapsing (ctrl+o) is a GLOBAL toggle driven by the app: it calls
+/// `setCollapsed(bool)` on every ToolUse component. Default is COLLAPSED. When
+/// collapsed, only the LAST 5 lines of the wrapped output are shown (with a
+/// leading `…` marker line when output was truncated); expanded shows all of
+/// it. Collapsing is a length change — the RenderCache diff and the engine's
+/// line-diff backstop handle the shrink; the component just re-renders fewer
+/// lines and marks dirty.
+///
+/// No "active component" (plan §6): the app keys each ToolUse instance by the
+/// libpanto block index AND by tool-call id (for result correlation). This
+/// component holds no global state.
+pub const ToolUse = struct {
+ /// Number of trailing output lines shown when collapsed.
+ pub const collapsed_tail_lines: usize = 5;
+
+ alloc: std.mem.Allocator,
+ cache: RenderCache,
+ /// Resolved tool name, or null until `tool_details`/completion.
+ name: ?std.ArrayList(u8) = null,
+ /// Accumulated verbatim input JSON (streamed args).
+ input: std.ArrayList(u8) = .empty,
+ /// Result output text, or null until the result lands.
+ output: ?std.ArrayList(u8) = null,
+ /// Whether the output is collapsed to its tail. Default true.
+ collapsed: bool = true,
+
+ pub fn init(alloc: std.mem.Allocator) ToolUse {
+ return .{ .alloc = alloc, .cache = RenderCache.init(alloc) };
+ }
+
+ pub fn deinit(self: *ToolUse) void {
+ if (self.name) |*n| n.deinit(self.alloc);
+ self.input.deinit(self.alloc);
+ if (self.output) |*o| o.deinit(self.alloc);
+ self.cache.deinit();
+ }
+
+ /// Resolve the tool name (from `tool_details` or the completed block).
+ pub fn setName(self: *ToolUse, name: []const u8) !void {
+ if (self.name == null) self.name = .empty;
+ self.name.?.clearRetainingCapacity();
+ try self.name.?.appendSlice(self.alloc, name);
+ self.cache.markDirty();
+ }
+
+ /// Append a streaming args delta (verbatim JSON bytes).
+ pub fn appendInput(self: *ToolUse, delta: []const u8) !void {
+ try self.input.appendSlice(self.alloc, delta);
+ self.cache.markDirty();
+ }
+
+ /// Replace the input verbatim (e.g. from the completed block's `input`).
+ pub fn setInput(self: *ToolUse, value: []const u8) !void {
+ self.input.clearRetainingCapacity();
+ try self.input.appendSlice(self.alloc, value);
+ self.cache.markDirty();
+ }
+
+ /// Set the result output text. Transitions render stage 2 -> 3.
+ pub fn setOutput(self: *ToolUse, value: []const u8) !void {
+ if (self.output == null) self.output = .empty;
+ self.output.?.clearRetainingCapacity();
+ try self.output.?.appendSlice(self.alloc, value);
+ self.cache.markDirty();
+ }
+
+ /// Global collapse toggle target. The app calls this on every ToolUse
+ /// component when ctrl+o is pressed. A no-op state change skips the dirty.
+ pub fn setCollapsed(self: *ToolUse, value: bool) void {
+ if (self.collapsed == value) return;
+ self.collapsed = value;
+ self.cache.markDirty();
+ }
+
+ fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 {
+ _ = alloc;
+ const self: *ToolUse = @ptrCast(@alignCast(ptr));
+ const a = self.alloc;
+ const tool_style = theme.default.fg(.tool);
+ const dim = theme.default.fg(.dim);
+
+ // Transient owned lines; the cache dupes them and we free here.
+ var lines: std.ArrayList([]const u8) = .empty;
+ defer {
+ for (lines.items) |l| a.free(l);
+ lines.deinit(a);
+ }
+
+ // -- Header: `tool (?)…` or `tool (<name>) <input json>` ------------
+ if (self.name == null) {
+ const plain = "tool (?)…";
+ const vis = truncateToCols(plain, width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ tool_style.open(), vis, tool_style.close() }));
+ try self.cache.store(lines.items);
+ return cacheLines(&self.cache);
+ }
+
+ // Name known: header is `tool (<name>) <input json>`, wrapped to width.
+ // The whole header (including verbatim JSON) is one logical paragraph
+ // that we wrap; it is styled with the tool accent.
+ {
+ const header_plain = try std.fmt.allocPrint(a, "tool ({s}) {s}", .{ self.name.?.items, self.input.items });
+ defer a.free(header_plain);
+ var wrapped: std.ArrayList([]const u8) = .empty;
+ defer wrapped.deinit(a);
+ try wrapParagraph(header_plain, width, &wrapped, a);
+ for (wrapped.items) |line| {
+ const vis = truncateToCols(line, width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ tool_style.open(), vis, tool_style.close() }));
+ }
+ }
+
+ // -- Blank separator line ------------------------------------------
+ try lines.append(a, try a.dupe(u8, ""));
+
+ // -- Result region: `(…)` placeholder or the output text -----------
+ if (self.output == null) {
+ const vis = truncateToCols("(…)", width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
+ } else {
+ // Wrap the full output, then optionally collapse to the tail.
+ var out_lines: std.ArrayList([]const u8) = .empty;
+ defer out_lines.deinit(a);
+ try wrapBuffer(self.output.?.items, width, &out_lines, a);
+
+ var start: usize = 0;
+ var truncated = false;
+ if (self.collapsed and out_lines.items.len > collapsed_tail_lines) {
+ start = out_lines.items.len - collapsed_tail_lines;
+ truncated = true;
+ }
+ if (truncated) {
+ // A leading marker so the user knows output was elided.
+ const vis = truncateToCols("…", width);
+ try lines.append(a, try std.fmt.allocPrint(a, "{s}{s}{s}", .{ dim.open(), vis, dim.close() }));
+ }
+ for (out_lines.items[start..]) |line| {
+ const vis = truncateToCols(line, width);
+ // Output uses plain assistant style (no escape) so it reads as
+ // content; truncate enforces the width contract.
+ try lines.append(a, try a.dupe(u8, vis));
+ }
+ }
+
+ try self.cache.store(lines.items);
+ return cacheLines(&self.cache);
+ }
+
+ fn firstLineChangedImpl(ptr: *anyopaque) ?usize {
+ const self: *ToolUse = @ptrCast(@alignCast(ptr));
+ return self.cache.firstLineChanged();
+ }
+
+ fn invalidateImpl(ptr: *anyopaque) void {
+ const self: *ToolUse = @ptrCast(@alignCast(ptr));
+ self.cache.invalidate();
+ }
+
+ const vtable = Component.VTable{
+ .render = renderImpl,
+ .firstLineChanged = firstLineChangedImpl,
+ .invalidate = invalidateImpl,
+ };
+
+ pub fn comp(self: *ToolUse) Component {
+ return .{ .ptr = self, .vtable = &vtable };
+ }
+};
+
+// ===========================================================================
// Tests
// ===========================================================================
@@ -1012,6 +1712,270 @@ test "InputBox: cursor block fits within width at end of a full line" {
try testing.expect(vw(lines[0]) <= 5);
}
+fn ctrlKey(letter: u8) Key {
+ return .{ .code = .{ .char = letter }, .mods = .{ .ctrl = true } };
+}
+
+fn typeStr(ib: *InputBox, s: []const u8) !void {
+ for (s) |c| try ib.applyKey(charKey(c, &[_]u8{c}));
+}
+
+test "InputBox: alt+left / alt+right move by word" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "foo bar baz"); // cursor at 11 (end)
+ try testing.expectEqual(@as(usize, 11), ib.cursor);
+ // Alt+Left: jump to start of "baz" (byte 8).
+ try ib.applyKey(.{ .code = .left, .mods = .{ .alt = true } });
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+ // Again: start of "bar" (byte 4).
+ try ib.applyKey(.{ .code = .left, .mods = .{ .alt = true } });
+ try testing.expectEqual(@as(usize, 4), ib.cursor);
+ // Alt+Right: skip "bar" + the trailing space -> start of "baz" (byte 8).
+ try ib.applyKey(.{ .code = .right, .mods = .{ .alt = true } });
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+ // Ctrl+Left also performs word-motion (many terminals send 1;5D).
+ try ib.applyKey(.{ .code = .left, .mods = .{ .ctrl = true } });
+ try testing.expectEqual(@as(usize, 4), ib.cursor);
+}
+
+test "InputBox: alt+arrow via RAW BYTES moves by word (handleInput pipeline)" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "foo bar baz"); // cursor at 11
+ try testing.expectEqual(@as(usize, 11), ib.cursor);
+
+ // Kitty functional alt+left: CSI 57350 ; 3 u -> word-left to byte 8.
+ ib.comp().handleInput("\x1b[57350;3u");
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+
+ // Legacy CSI alt+left: 1;3D -> word-left to byte 4.
+ ib.comp().handleInput("\x1b[1;3D");
+ try testing.expectEqual(@as(usize, 4), ib.cursor);
+
+ // Alt+right via raw bytes -> back to byte 8.
+ ib.comp().handleInput("\x1b[1;3C");
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+}
+
+test "InputBox: ESC b / ESC f (readline alt-word form) moves by word" {
+ // Ghostty and most macOS terminals send Alt+Left/Right as the classic
+ // readline `ESC b` / `ESC f`, which decode to alt+b / alt+f CHAR keys
+ // rather than modified-arrow CSIs. These must move by word (and must NOT
+ // be inserted as literal text).
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "foo bar baz"); // cursor at 11
+ try testing.expectEqual(@as(usize, 11), ib.cursor);
+
+ ib.comp().handleInput("\x1bb"); // alt+b -> word-left to byte 8
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+ ib.comp().handleInput("\x1bb"); // -> byte 4
+ try testing.expectEqual(@as(usize, 4), ib.cursor);
+ ib.comp().handleInput("\x1bf"); // alt+f -> word-right to byte 8
+ try testing.expectEqual(@as(usize, 8), ib.cursor);
+
+ // The alt-char must not have inserted any literal 'b'/'f' bytes.
+ try testing.expectEqualStrings("foo bar baz", ib.text.items);
+}
+
+test "InputBox: alt/ctrl+backspace deletes the previous word" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "foo bar baz"); // cursor at 11
+ try ib.applyKey(.{ .code = .backspace, .mods = .{ .alt = true } });
+ try testing.expectEqualStrings("foo bar ", ib.text.items);
+ try ib.applyKey(.{ .code = .backspace, .mods = .{ .ctrl = true } });
+ try testing.expectEqualStrings("foo ", ib.text.items);
+ // Plain backspace still deletes a single codepoint.
+ try ib.applyKey(.{ .code = .backspace });
+ try testing.expectEqualStrings("foo", ib.text.items);
+}
+
+test "InputBox: arrow press+release moves ONCE, not twice (no key-up double-move)" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "abcdef"); // cursor at 6
+ try testing.expectEqual(@as(usize, 6), ib.cursor);
+
+ // A physical left-arrow press under the Kitty protocol would, with event
+ // reporting on, arrive as a PRESS then a RELEASE. Feeding both must move
+ // the cursor only once (the release is dropped). This guards the
+ // double-move regression at the raw-bytes pipeline level even if a
+ // terminal still emits releases.
+ ib.comp().handleInput("\x1b[57350u"); // functional left press
+ try testing.expectEqual(@as(usize, 5), ib.cursor);
+ ib.comp().handleInput("\x1b[57350;1:3u"); // functional left RELEASE
+ try testing.expectEqual(@as(usize, 5), ib.cursor); // unchanged
+
+ // Same property for the legacy CSI release form via applyKey directly.
+ try ib.applyKey(.{ .code = .left, .event = .release });
+ try testing.expectEqual(@as(usize, 5), ib.cursor);
+}
+
+test "InputBox: word-nav boundary cases (multiple spaces, newlines, buffer ends)" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ // Multiple spaces between words and a newline-separated logical line.
+ try typeStr(&ib, "foo bar");
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } }); // '\n' at byte 9
+ try typeStr(&ib, "baz"); // cursor at end (byte 13)
+ try testing.expectEqual(@as(usize, 13), ib.cursor);
+
+ // Word-left from end: start of "baz" (byte 10, just after the '\n').
+ ib.moveWordLeft();
+ try testing.expectEqual(@as(usize, 10), ib.cursor);
+ // Again: crosses the newline and the multi-space run to the start of "bar"
+ // (byte 6).
+ ib.moveWordLeft();
+ try testing.expectEqual(@as(usize, 6), ib.cursor);
+ // Again: start of "foo" (byte 0).
+ ib.moveWordLeft();
+ try testing.expectEqual(@as(usize, 0), ib.cursor);
+ // At the start, word-left is a clamped no-op.
+ ib.moveWordLeft();
+ try testing.expectEqual(@as(usize, 0), ib.cursor);
+
+ // Word-right skips "foo" + the multi-space run -> start of "bar" (byte 6).
+ ib.moveWordRight();
+ try testing.expectEqual(@as(usize, 6), ib.cursor);
+ // Jump to end, then word-right is a clamped no-op.
+ ib.moveEnd();
+ const end = ib.cursor;
+ ib.moveWordRight();
+ try testing.expectEqual(end, ib.cursor);
+}
+
+test "InputBox: ctrl+u on the FIRST logical line clears to byte 0" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ // Single logical line; ctrl+u from the end clears the whole line to 0
+ // (the first-line case, complementing the later-line case below).
+ try typeStr(&ib, "hello world");
+ try ib.applyKey(ctrlKey('u'));
+ try testing.expectEqualStrings("", ib.text.items);
+ try testing.expectEqual(@as(usize, 0), ib.cursor);
+}
+
+test "InputBox: focused render emits CURSOR_MARKER exactly once" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ ib.setFocused(true);
+ // Multi-row buffer so we exercise the per-row cursor placement: the marker
+ // must appear on exactly ONE row, once.
+ try typeStr(&ib, "alpha");
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
+ try typeStr(&ib, "beta");
+ const lines = try ib.comp().render(20, testing.allocator);
+ var count: usize = 0;
+ for (lines) |l| {
+ var idx: usize = 0;
+ while (std.mem.indexOfPos(u8, l, idx, CURSOR_MARKER)) |at| {
+ count += 1;
+ idx = at + CURSOR_MARKER.len;
+ }
+ }
+ try testing.expectEqual(@as(usize, 1), count);
+}
+
+test "InputBox: ctrl+u deletes to start of the current logical line" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ // Two logical lines; cursor mid-second-line.
+ try typeStr(&ib, "first");
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } }); // newline
+ try typeStr(&ib, "second");
+ // Cursor at end of "second"; ctrl+u clears just "second", keeping "first\n".
+ try ib.applyKey(ctrlKey('u'));
+ try testing.expectEqualStrings("first\n", ib.text.items);
+ try testing.expectEqual(@as(usize, 6), ib.cursor); // just after the '\n'
+}
+
+test "InputBox: ctrl+w deletes the previous word (plain, no kill-ring)" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "hello world");
+ try ib.applyKey(ctrlKey('w')); // delete "world"
+ try testing.expectEqualStrings("hello ", ib.text.items);
+ try ib.applyKey(ctrlKey('w')); // delete "hello "
+ try testing.expectEqualStrings("", ib.text.items);
+}
+
+test "InputBox: ctrl+a / ctrl+e move to line start / end" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "abc");
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
+ try typeStr(&ib, "defg"); // second line, cursor at end (byte 8)
+ try ib.applyKey(ctrlKey('a'));
+ try testing.expectEqual(@as(usize, 4), ib.cursor); // start of "defg"
+ try ib.applyKey(ctrlKey('e'));
+ try testing.expectEqual(@as(usize, 8), ib.cursor); // end of "defg"
+}
+
+test "InputBox: line cap renders only the last cap rows by default" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ ib.line_cap = 3;
+ // 5 logical lines: L0..L4. Cursor ends on L4.
+ try typeStr(&ib, "L0");
+ for (0..4) |i| {
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
+ var b: [2]u8 = .{ 'L', @intCast('1' + i) };
+ try typeStr(&ib, &b);
+ }
+ const lines = try ib.comp().render(20, testing.allocator);
+ // Only `cap` rows rendered (the tail window: L2, L3, L4).
+ try testing.expectEqual(@as(usize, 3), lines.len);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "L2") != null);
+ try testing.expect(std.mem.indexOf(u8, lines[2], "L4") != null);
+ for (lines) |ln| try testing.expect(vw(ln) <= 20);
+}
+
+test "InputBox: scroll-window slides up to keep the cursor visible" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ ib.setFocused(true);
+ ib.line_cap = 3;
+ try typeStr(&ib, "L0");
+ for (0..4) |i| {
+ try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } });
+ var b: [2]u8 = .{ 'L', @intCast('1' + i) };
+ try typeStr(&ib, &b);
+ }
+ // Move the cursor up to the top (L0) via Home then re-anchor: move cursor
+ // to byte 0 so cursor_row == 0, above the default tail window.
+ ib.moveHome();
+ const lines = try ib.comp().render(20, testing.allocator);
+ try testing.expectEqual(@as(usize, 3), lines.len);
+ // Window slid up so the cursor row (L0) is visible at the TOP: the cursor
+ // block + marker render on row 0 (the cursor splits "L0", so the marker is
+ // the reliable signal), and the rows below are L1, L2 — proving the window
+ // is [0, 3) not the default tail [2, 5).
+ try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) != null);
+ try testing.expect(std.mem.indexOf(u8, lines[1], "L1") != null);
+ try testing.expect(std.mem.indexOf(u8, lines[2], "L2") != null);
+}
+
+test "InputBox: single-row default is unaffected by the cap" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try testing.expectEqual(InputBox.default_line_cap, ib.line_cap);
+ try typeStr(&ib, "just one line");
+ const lines = try ib.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 1), lines.len);
+}
+
+test "InputBox: setBuffer/buffer round-trip for the $EDITOR hook" {
+ var ib = InputBox.init(testing.allocator);
+ defer ib.deinit();
+ try typeStr(&ib, "old");
+ try ib.setBuffer("new multi\nline text");
+ try testing.expectEqualStrings("new multi\nline text", ib.buffer());
+ // Cursor lands at the end.
+ try testing.expectEqual(ib.text.items.len, ib.cursor);
+}
+
// -- Footer -----------------------------------------------------------------
test "Footer: renders fps from frame time, inverted, within width" {
@@ -1058,6 +2022,67 @@ test "Footer: setFrameTime dirties; stable re-render is clean" {
try testing.expectEqual(@as(?usize, 0), ft.comp().firstLineChanged());
}
+test "Footer: context tokens absent until set, then shown alongside fps" {
+ var ft = Footer.init(testing.allocator);
+ defer ft.deinit();
+ var buf: [32]u8 = undefined;
+ // Absent until usage is reported.
+ try testing.expectEqualStrings("", ft.contextText(&buf));
+ ft.setFrameTime(8.0);
+ {
+ const lines = try ft.comp().render(80, testing.allocator);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "ctx") == null);
+ }
+ // Small count rendered verbatim.
+ ft.setContextTokens(845);
+ try testing.expectEqualStrings("845 ctx", ft.contextText(&buf));
+ {
+ const lines = try ft.comp().render(80, testing.allocator);
+ try testing.expect(vw(lines[0]) <= 80);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "845 ctx") != null);
+ // fps element still present alongside.
+ try testing.expect(std.mem.indexOf(u8, lines[0], "fps:") != null);
+ }
+}
+
+test "Footer: contextText formatting boundaries (0, 999, 1000 -> k)" {
+ var ft = Footer.init(testing.allocator);
+ defer ft.deinit();
+ var buf: [32]u8 = undefined;
+ // Zero is a real measured value (not "absent") -> "0 ctx".
+ ft.setContextTokens(0);
+ try testing.expectEqualStrings("0 ctx", ft.contextText(&buf));
+ // Just below the k threshold stays verbatim.
+ ft.setContextTokens(999);
+ try testing.expectEqualStrings("999 ctx", ft.contextText(&buf));
+ // Exactly 1000 crosses into the k suffix.
+ ft.setContextTokens(1000);
+ try testing.expectEqualStrings("1.0k ctx", ft.contextText(&buf));
+}
+
+test "Footer: large context token counts format as k; latest wins" {
+ var ft = Footer.init(testing.allocator);
+ defer ft.deinit();
+ var buf: [32]u8 = undefined;
+ ft.setContextTokens(12345);
+ try testing.expectEqualStrings("12.3k ctx", ft.contextText(&buf));
+ // Overwritten (latest-wins), not accumulated.
+ ft.setContextTokens(2000);
+ try testing.expectEqualStrings("2.0k ctx", ft.contextText(&buf));
+}
+
+test "Footer: setContextTokens dirties; stable re-render is clean" {
+ var ft = Footer.init(testing.allocator);
+ defer ft.deinit();
+ ft.setFrameTime(8.0);
+ ft.setContextTokens(1000);
+ _ = try ft.comp().render(80, testing.allocator);
+ _ = try ft.comp().render(80, testing.allocator);
+ try testing.expectEqual(@as(?usize, null), ft.comp().firstLineChanged());
+ ft.setContextTokens(2000);
+ try testing.expectEqual(@as(?usize, 0), ft.comp().firstLineChanged());
+}
+
// -- Integration with the real Engine (no TTY) ------------------------------
test "components drive the real engine without a TTY" {
@@ -1102,3 +2127,208 @@ test "components drive the real engine without a TTY" {
const out2 = buf.written();
try testing.expect(std.mem.indexOf(u8, out2, "world") != null);
}
+
+// -- Welcome / Thinking / CompactionSummary / ToolUse (P2) ------------------
+
+test "Welcome: renders title + cwd + model, all within width" {
+ var w = Welcome.init(testing.allocator);
+ defer w.deinit();
+ try w.setVersion("0.1.0");
+ try w.setCwd("/tmp/project");
+ try w.setModel("anthropic:claude");
+ const lines = try w.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 3), lines.len);
+ for (lines) |l| try testing.expect(vw(l) <= 40);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "panto v0.1.0") != null);
+ try testing.expect(std.mem.indexOf(u8, lines[1], "/tmp/project") != null);
+ try testing.expect(std.mem.indexOf(u8, lines[2], "anthropic:claude") != null);
+}
+
+test "Welcome: title only when cwd/model unset" {
+ var w = Welcome.init(testing.allocator);
+ defer w.deinit();
+ const lines = try w.comp().render(20, testing.allocator);
+ try testing.expectEqual(@as(usize, 1), lines.len);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "panto") != null);
+}
+
+test "Welcome: honors the width contract at a tiny width" {
+ var w = Welcome.init(testing.allocator);
+ defer w.deinit();
+ try w.setVersion("0.1.0");
+ try w.setCwd("/a/very/long/working/directory/path/that/overflows");
+ try w.setModel("anthropic:claude-some-very-long-model-id");
+ // Width 6: every banner row (title + cwd + model) must truncate to fit.
+ const lines = try w.comp().render(6, testing.allocator);
+ try testing.expectEqual(@as(usize, 3), lines.len);
+ for (lines) |l| try testing.expect(vw(l) <= 6);
+}
+
+test "Thinking: streams dim, firstLineChanged stays near the tail" {
+ var t = Thinking.init(testing.allocator);
+ defer t.deinit();
+ try t.appendDelta("line one is fairly long so it wraps across");
+ _ = try t.comp().render(20, testing.allocator);
+ // A clean re-render reports no change.
+ _ = try t.comp().render(20, testing.allocator);
+ try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());
+ // Appending a delta should dirty near the tail (not line 0).
+ try t.appendDelta(" more");
+ const flc = t.comp().firstLineChanged();
+ try testing.expect(flc != null and flc.? > 0);
+ const lines = try t.comp().render(20, testing.allocator);
+ for (lines) |l| try testing.expect(vw(l) <= 20);
+}
+
+test "CompactionSummary: header + wrapped summary within width" {
+ var c = CompactionSummary.init(testing.allocator);
+ defer c.deinit();
+ try c.setSummary("summarized prior turns here");
+ const lines = try c.comp().render(20, testing.allocator);
+ try testing.expect(lines.len >= 2);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "compacted") != null);
+ for (lines) |l| try testing.expect(vw(l) <= 20);
+}
+
+test "ToolUse: stage 1 renders tool (?) before the name resolves" {
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ const lines = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 1), lines.len);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "tool (?)") != null);
+}
+
+test "ToolUse: stage 2 shows name + verbatim json + placeholder" {
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("read");
+ try t.appendInput("{\"path\":\"a\"}");
+ const lines = try t.comp().render(60, testing.allocator);
+ // header line, blank, placeholder
+ try testing.expect(lines.len >= 3);
+ try testing.expect(std.mem.indexOf(u8, lines[0], "tool (read) {\"path\":\"a\"}") != null);
+ try testing.expectEqualStrings("", lines[lines.len - 2]);
+ try testing.expect(std.mem.indexOf(u8, lines[lines.len - 1], "(…)") != null);
+ for (lines) |l| try testing.expect(vw(l) <= 60);
+}
+
+test "ToolUse: collapsed shows only the last 5 output lines (default)" {
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("read");
+ try t.setInput("{}");
+ // 8 short output lines -> collapsed shows the marker + last 5.
+ try t.setOutput("l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8");
+ const collapsed = try t.comp().render(40, testing.allocator);
+ // header, blank, marker, l4..l8 = 3 + 5
+ try testing.expect(std.mem.indexOf(u8, collapsed[collapsed.len - 1], "l8") != null);
+ try testing.expect(std.mem.indexOf(u8, collapsed[collapsed.len - 5], "l4") != null);
+ // The earliest output lines are elided when collapsed.
+ var has_l1 = false;
+ for (collapsed) |l| {
+ if (std.mem.indexOf(u8, l, "l1") != null) has_l1 = true;
+ }
+ try testing.expect(!has_l1);
+
+ // Expanding shows everything.
+ t.setCollapsed(false);
+ const expanded = try t.comp().render(40, testing.allocator);
+ try testing.expect(expanded.len > collapsed.len);
+ var has_l1_exp = false;
+ for (expanded) |l| {
+ if (std.mem.indexOf(u8, l, "l1") != null) has_l1_exp = true;
+ }
+ try testing.expect(has_l1_exp);
+}
+
+test "ToolUse: short output is shown whole even when collapsed" {
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("ls");
+ try t.setInput("{}");
+ try t.setOutput("only\ntwo");
+ const lines = try t.comp().render(40, testing.allocator);
+ var seen_only = false;
+ var seen_two = false;
+ for (lines) |l| {
+ if (std.mem.indexOf(u8, l, "only") != null) seen_only = true;
+ if (std.mem.indexOf(u8, l, "two") != null) seen_two = true;
+ }
+ try testing.expect(seen_only and seen_two);
+}
+
+test "ToolUse: collapse/expand is a length change with a cache-derived firstLineChanged" {
+ // Expanding/collapsing changes the rendered LINE COUNT (plan §3.3). A
+ // collapse toggle is a structural change (the whole output region shifts),
+ // so `setCollapsed` re-dirties via `markDirty` — dropping the baseline — and
+ // the post-render `firstLineChanged` is therefore 0 (cache-derived: a full
+ // drop reports from the top). That is correct and cheap for a small tool
+ // component; the engine's line-diff backstop (plan §3.3) still handles the
+ // length delta. The KEY guarantees this test pins: the line COUNT changes
+ // across the toggle, the signal is cache-derived (0 after a full drop, null
+ // after a stable render), and there is no hand-managed drift.
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("read");
+ try t.setInput("{}");
+ try t.setOutput("l1\nl2\nl3\nl4\nl5\nl6\nl7\nl8");
+
+ // Default collapsed: header + blank + marker + last 5 = 8 rows.
+ const collapsed = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 8), collapsed.len);
+ // A stable re-render is clean (cache-derived, no drift).
+ _ = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());
+
+ // Expand: header + blank + all 8 output rows = 10 rows (a length GROWTH).
+ t.setCollapsed(false);
+ // While dirty (full drop), the signal is the cache-derived 0.
+ try testing.expectEqual(@as(?usize, 0), t.comp().firstLineChanged());
+ const expanded = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 10), expanded.len);
+ // After the render the baseline was dropped on the toggle, so the diff
+ // reports from 0 — cache-derived, not a hand-managed value.
+ try testing.expectEqual(@as(?usize, 0), t.comp().firstLineChanged());
+ // Stable re-render is clean again.
+ _ = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(?usize, null), t.comp().firstLineChanged());
+
+ // Collapse again: shrink back to 8 rows (the length-change shrink path).
+ t.setCollapsed(true);
+ const recollapsed = try t.comp().render(40, testing.allocator);
+ try testing.expectEqual(@as(usize, 8), recollapsed.len);
+}
+
+test "ToolUse: args are rendered VERBATIM (no pretty-print) and within width" {
+ // The input JSON must pass through byte-for-byte (no reflow of the JSON
+ // structure), only terminal-wrapped. We use a compact object with no spaces
+ // and assert the exact substring survives in the joined header.
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("search");
+ try t.appendInput("{\"q\":\"a b\",");
+ try t.appendInput("\"n\":10}");
+ const verbatim = "{\"q\":\"a b\",\"n\":10}";
+ try testing.expectEqualStrings(verbatim, t.input.items);
+
+ // Wide render: the verbatim args appear unmodified on the header line.
+ const wide = try t.comp().render(80, testing.allocator);
+ try testing.expect(std.mem.indexOf(u8, wide[0], verbatim) != null);
+
+ // Narrow render: header wraps across rows but every row honors the width
+ // contract (no pretty-print expansion, just wrapping).
+ const narrow = try t.comp().render(12, testing.allocator);
+ for (narrow) |l| try testing.expect(vw(l) <= 12);
+}
+
+test "ToolUse: long output lines honor the width contract" {
+ var t = ToolUse.init(testing.allocator);
+ defer t.deinit();
+ try t.setName("read");
+ try t.setInput("{}");
+ t.setCollapsed(false);
+ try t.setOutput("a very long single output line that must be wrapped to fit the narrow width");
+ const lines = try t.comp().render(10, testing.allocator);
+ for (lines) |l| try testing.expect(vw(l) <= 10);
+}
+