//! Built-in P1 components for the TUI (plan §6). //! //! Each component satisfies the `Component` vtable (`tui_component.zig`) and //! implements the cache-derived dirty model exactly as `RenderCache` defines //! it: any state mutation calls `markDirty`/`markDirtyFrom` (drops the cache), //! and a successful `render` calls `cache.store(lines)` (diffs the new lines //! against the prior cache, records the lowest differing index, re-populates //! the cache, and marks it clean). `firstLineChanged` is therefore derived //! purely from cache state and never a hand-managed integer that can drift. //! //! Data-in / lines-out: each component takes STRUCTURED DATA IN via setters or //! delta-appenders and produces LINES OUT from `render(width, alloc)`. Every //! returned line's visible width is <= `width` (we TRUNCATE; the engine treats //! overflow as a hard error per plan §3.1). //! //! Render storage convention: a component renders into a transient list, calls //! `cache.store(lines)` (which dupes the bytes into cache-owned storage), then //! returns `cache.lines` re-typed as `[]const []const u8`. The returned slices //! are owned by the cache and stay valid until the next `render`/`invalidate` //! — satisfying the vtable's lifetime contract. const std = @import("std"); const component = @import("tui_component.zig"); const theme = @import("tui_theme.zig"); const input = @import("tui_input.zig"); const key = @import("tui_key.zig"); const Component = component.Component; const Focusable = component.Focusable; const RenderCache = component.RenderCache; const CURSOR_MARKER = component.CURSOR_MARKER; const Style = theme.Style; const Key = key.Key; const KeyCode = key.KeyCode; // =========================================================================== // Shared helpers // =========================================================================== /// Number of display columns occupied by `text`, counted as one column per /// UTF-8 codepoint. `text` here is assumed to be PLAIN (no escape sequences); /// components wrap on plain text and only add styling escapes afterward, so /// this is a faithful visible width. Mirrors the engine's P1 approximation /// (1 col per codepoint; wide CJK/emoji width is a deferred refinement). pub fn displayWidth(text: []const u8) usize { var cols: usize = 0; var i: usize = 0; while (i < text.len) { const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; cols += 1; i += @min(seq_len, text.len - i); } return cols; } /// Truncate `text` to at most `max_cols` display columns, returning a byte /// slice of `text` that ends on a codepoint boundary. Never splits a multibyte /// codepoint. pub fn truncateToCols(text: []const u8, max_cols: usize) []const u8 { var cols: usize = 0; var i: usize = 0; while (i < text.len and cols < max_cols) { const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; const adv = @min(seq_len, text.len - i); i += adv; cols += 1; } return text[0..i]; } /// Wrap `text` (a single logical paragraph, no embedded newlines) into lines of /// at most `width` display columns, appending each produced line to `out`. /// Greedy word-wrap on ASCII spaces; a word longer than `width` is hard-split. /// An empty paragraph yields one empty line. Lines pushed to `out` are slices /// borrowed from `text` (no allocation of line bytes here; `out` only stores /// the slice headers). fn wrapParagraph(text: []const u8, width: usize, out: *std.ArrayList([]const u8), alloc: std.mem.Allocator) !void { if (width == 0) { try out.append(alloc, ""); return; } if (text.len == 0) { try out.append(alloc, ""); return; } // Greedy word-wrap. We accumulate a line by byte range [line_start, i); on // overflow we break at the last space that fits, or hard-split a word that // is wider than `width`. var line_start: usize = 0; var line_cols: usize = 0; var last_break: ?usize = null; // byte index of the last space on this line var i: usize = 0; while (i < text.len) { const seq_len = std.unicode.utf8ByteSequenceLength(text[i]) catch 1; const adv = @min(seq_len, text.len - i); const is_space = adv == 1 and text[i] == ' '; if (is_space and line_cols == width) { // The overflowing glyph is the inter-word space itself: break here // and consume the space (standard word-wrap discards it) so the // current word group fills the line exactly. try out.append(alloc, text[line_start..i]); line_start = i + adv; last_break = null; line_cols = 0; i += adv; continue; } if (line_cols + 1 > width) { // Adding this glyph would overflow; break the line first. if (last_break) |brk| { // Break at the last space: emit up to (not including) it, and // start the next line just after it. try out.append(alloc, text[line_start..brk]); line_start = brk + 1; last_break = null; line_cols = displayWidth(text[line_start..i]); } else { // No space on this line: hard-split before the current glyph. try out.append(alloc, text[line_start..i]); line_start = i; line_cols = 0; } } if (is_space) last_break = i; line_cols += 1; i += adv; } // Flush the final line (always emit, even if empty/trailing fragment). try out.append(alloc, text[line_start..]); } /// Split `buffer` on newlines into paragraphs and wrap each to `width`, /// appending all produced lines to `out`. A trailing newline produces a final /// empty line (so a freshly-typed "\n" shows a blank row). An empty buffer /// produces no lines. fn wrapBuffer(buffer: []const u8, width: usize, out: *std.ArrayList([]const u8), alloc: std.mem.Allocator) !void { if (buffer.len == 0) return; var it = std.mem.splitScalar(u8, buffer, '\n'); while (it.next()) |para| { try wrapParagraph(para, width, out, alloc); } } /// Build the cache-owned line set for a styled text block: each wrapped plain /// line is wrapped in `style.open()`/`style.close()` and stored via the cache. /// Returns the cache's owned lines re-typed for the vtable. /// /// `width` bounds the *visible* width: the plain text is truncated to `width` /// columns BEFORE styling escapes are added (escapes are zero visible width). fn renderStyledLines( cache: *RenderCache, buffer: []const u8, style: Style, width: usize, alloc: std.mem.Allocator, ) ![]const []const u8 { // 1. Wrap plain text into borrowed slices. var plain: std.ArrayList([]const u8) = .empty; defer plain.deinit(alloc); try wrapBuffer(buffer, width, &plain, alloc); // 2. Style each line into a transient owned buffer. var styled: std.ArrayList([]const u8) = .empty; defer { for (styled.items) |s| alloc.free(s); styled.deinit(alloc); } for (plain.items) |line| { // Defensive truncate (wrap already bounds it, but a hard contract). const vis = truncateToCols(line, width); const composed = try std.fmt.allocPrint(alloc, "{s}{s}{s}", .{ style.open(), vis, style.close() }); try styled.append(alloc, composed); } // 3. Commit to the cache (dupes), then return the cache's owned copy. try cache.store(styled.items); return cacheLines(cache); } /// Re-type the cache's owned `[][]u8` lines as `[]const []const u8` for the /// vtable return. The cache guarantees these outlive the call until the next /// render/invalidate. fn cacheLines(cache: *RenderCache) []const []const u8 { const owned = cache.lines orelse return &.{}; return @ptrCast(owned); } // =========================================================================== // AssistantText — streaming assistant message (plan §6, §8) // =========================================================================== /// Accumulates assistant content deltas into an internal buffer and renders /// the wrapped text with the theme's assistant style. /// /// Streaming-tail dirty model (plan §3.3): a delta is appended to the buffer /// and the cache is marked dirty; the engine then requests a render. Because /// appended text only changes the LAST wrapped line(s) and leaves earlier /// wrapped lines byte-identical, `RenderCache.store`'s diff naturally reports /// `firstLineChanged` near the TAIL, not line 0 — the cut stays near the end /// during streaming. (There is no per-delta render method on the interface; /// the delta just mutates state + dirties, per plan §8.) /// /// Markdown hosting (plan §8, DEFERRED): the buffer/render are structured so a /// later pass can cache finished blocks and only re-render the last open block. /// For P1 this is plain text + word wrap; the tail-near firstLineChanged /// property already holds via the cache diff, so the markdown upgrade slots in /// without changing the dirty model. pub const AssistantText = struct { alloc: std.mem.Allocator, buffer: std.ArrayList(u8) = .empty, cache: RenderCache, pub fn init(alloc: std.mem.Allocator) AssistantText { return .{ .alloc = alloc, .cache = RenderCache.init(alloc) }; } pub fn deinit(self: *AssistantText) void { self.buffer.deinit(self.alloc); self.cache.deinit(); } /// Append a streaming content delta. Mutates the buffer and marks the cache /// dirty (the engine will requestRender). The cache diff keeps /// firstLineChanged near the tail. pub fn appendDelta(self: *AssistantText, delta: []const u8) !void { try self.buffer.appendSlice(self.alloc, delta); // markDirtyAppend RETAINS the baseline so the post-render diff recovers // the true tail change point; while dirty it reports a tail hint, so // the engine's cut stays near the end during streaming (plan §3.3/§8). self.cache.markDirtyAppend(); } /// Replace the whole buffer (e.g. a non-streaming set). Marks dirty. pub fn setText(self: *AssistantText, 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: *AssistantText = @ptrCast(@alignCast(ptr)); return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.assistant), width, self.alloc); } fn firstLineChangedImpl(ptr: *anyopaque) ?usize { const self: *AssistantText = @ptrCast(@alignCast(ptr)); return self.cache.firstLineChanged(); } fn invalidateImpl(ptr: *anyopaque) void { const self: *AssistantText = @ptrCast(@alignCast(ptr)); self.cache.invalidate(); } const vtable = Component.VTable{ .render = renderImpl, .firstLineChanged = firstLineChangedImpl, .invalidate = invalidateImpl, }; pub fn comp(self: *AssistantText) Component { return .{ .ptr = self, .vtable = &vtable }; } }; // =========================================================================== // UserText — submitted user message (plan §6) // =========================================================================== /// A submitted user message, rendered with the theme's user style. Static once /// set; `setText` replaces it and marks dirty. pub const UserText = struct { alloc: std.mem.Allocator, buffer: std.ArrayList(u8) = .empty, cache: RenderCache, pub fn init(alloc: std.mem.Allocator) UserText { return .{ .alloc = alloc, .cache = RenderCache.init(alloc) }; } pub fn deinit(self: *UserText) void { self.buffer.deinit(self.alloc); self.cache.deinit(); } /// Set the (static) message text. Marks dirty. pub fn setText(self: *UserText, 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: *UserText = @ptrCast(@alignCast(ptr)); return renderStyledLines(&self.cache, self.buffer.items, theme.default.fg(.user), width, self.alloc); } fn firstLineChangedImpl(ptr: *anyopaque) ?usize { const self: *UserText = @ptrCast(@alignCast(ptr)); return self.cache.firstLineChanged(); } fn invalidateImpl(ptr: *anyopaque) void { const self: *UserText = @ptrCast(@alignCast(ptr)); self.cache.invalidate(); } const vtable = Component.VTable{ .render = renderImpl, .firstLineChanged = firstLineChangedImpl, .invalidate = invalidateImpl, }; pub fn comp(self: *UserText) Component { return .{ .ptr = self, .vtable = &vtable }; } }; // =========================================================================== // InputBox — editable single-row+ input (plan §6, §3.5) // =========================================================================== /// A `Focusable` editor. Single row by default; ENTER submits, SHIFT+ENTER /// inserts a newline (grows one row per line). Growth is UNBOUNDED in P1 (the /// cap + scroll-window is deferred to P2). /// /// Editing (raw keys via `handleInput`, decoded by `tui_input`): /// - printable chars (UTF-8) insert at the cursor /// - backspace deletes the codepoint before the cursor /// - delete removes the codepoint at the cursor /// - left/right move by one codepoint; home/end jump to start/end of the /// current visual buffer (P1: whole buffer, not per-line) /// - ENTER submits the whole buffer (see "Submit mechanism") /// - SHIFT+ENTER inserts a '\n' /// /// Cursor (plan §3.5): the box draws its OWN cursor as a reverse-video block /// (theme `.cursor` style) over the glyph at the cursor position. When focused /// it also emits `CURSOR_MARKER` (zero visible width) at the cursor location in /// its render output, so the engine can later position the hardware cursor. /// /// SHIFT+ENTER limitation: on terminals without the Kitty protocol, Enter and /// Shift+Enter send identical bytes (`\r`); the decoder cannot distinguish them /// and both arrive as `.enter` with no shift modifier, so only plain submit is /// possible there. When Kitty IS active, Shift+Enter arrives as CSI-u /// (`\x1b[13;2u`) with `mods.shift` set and this box inserts a newline. The /// logic works wherever the distinction is available. /// /// Submit mechanism: a POLLABLE buffer. On ENTER the current editor contents /// are moved into `submitted` and the editor is cleared. The app calls /// `takeSubmitted()` once per frame; it returns the submitted bytes (owned by /// the box, valid until the next `takeSubmitted`/edit) and clears the pending /// flag, or null if nothing was submitted. This avoids callback re-entrancy /// into the render loop. pub const InputBox = struct { alloc: std.mem.Allocator, focusable: Focusable = .{}, /// Editor contents (may contain '\n' for multi-line input). UTF-8. text: std.ArrayList(u8) = .empty, /// Cursor position as a BYTE offset into `text` (always on a codepoint /// boundary). cursor: usize = 0, /// Pending submitted line, owned by the box. Valid until the next submit /// 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) }; } pub fn deinit(self: *InputBox) void { self.text.deinit(self.alloc); self.submitted.deinit(self.alloc); self.cache.deinit(); } // -- focus ------------------------------------------------------------- /// Set focus. Re-dirties because the cursor block + marker only render when /// focused, so focus changes alter the output. pub fn setFocused(self: *InputBox, value: bool) void { if (self.focusable.focused != value) { self.focusable.setFocused(value); self.cache.markDirty(); } } pub fn isFocused(self: *const InputBox) bool { return self.focusable.focused; } // -- submit polling ---------------------------------------------------- /// Poll the submitted line. Returns the bytes (box-owned) and clears the /// pending flag, or null if nothing was submitted since the last poll. pub fn takeSubmitted(self: *InputBox) ?[]const u8 { if (!self.has_submitted) return null; self.has_submitted = false; 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 { try self.text.insertSlice(self.alloc, self.cursor, bytes); self.cursor += bytes.len; self.cache.markDirty(); } fn backspace(self: *InputBox) void { if (self.cursor == 0) return; const start = self.prevBoundary(self.cursor); 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 deleteForward(self: *InputBox) void { if (self.cursor >= self.text.items.len) return; const next = self.nextBoundary(self.cursor); const removed = next - self.cursor; std.mem.copyForwards(u8, self.text.items[self.cursor..], self.text.items[next..]); self.text.items.len -= removed; self.cache.markDirty(); } fn moveLeft(self: *InputBox) void { if (self.cursor == 0) return; self.cursor = self.prevBoundary(self.cursor); self.cache.markDirty(); } fn moveRight(self: *InputBox) void { if (self.cursor >= self.text.items.len) return; self.cursor = self.nextBoundary(self.cursor); self.cache.markDirty(); } fn moveHome(self: *InputBox) void { if (self.cursor == 0) return; self.cursor = 0; self.cache.markDirty(); } fn moveEnd(self: *InputBox) void { if (self.cursor == self.text.items.len) return; self.cursor = self.text.items.len; 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); self.has_submitted = true; self.text.clearRetainingCapacity(); self.cursor = 0; self.cache.markDirty(); } /// Byte index of the codepoint boundary before `i` (i > 0). fn prevBoundary(self: *const InputBox, i: usize) usize { var j = i - 1; while (j > 0 and isContinuation(self.text.items[j])) : (j -= 1) {} return j; } /// Byte index of the next codepoint boundary after `i` (i < len). fn nextBoundary(self: *const InputBox, i: usize) usize { const seq_len = std.unicode.utf8ByteSequenceLength(self.text.items[i]) catch 1; return @min(i + seq_len, self.text.items.len); } fn isContinuation(b: u8) bool { return (b & 0xc0) == 0x80; } // -- input handling ---------------------------------------------------- /// Apply one decoded key. Split out so tests can drive editing without raw /// byte sequences. pub fn applyKey(self: *InputBox, k: Key) !void { if (k.event == .release) return; switch (k.code) { .char => { // 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 { // Encode the codepoint ourselves when no text was carried. var buf: [4]u8 = undefined; const n = std.unicode.utf8Encode(k.code.char, &buf) catch return; try self.insertText(buf[0..n]); } }, .enter => { if (k.mods.shift) { try self.insertText("\n"); // shift+enter newline } else { try self.submit(); } }, // 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(), // 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 } } fn handleInputImpl(ptr: *anyopaque, data: []const u8) void { const self: *InputBox = @ptrCast(@alignCast(ptr)); var off: usize = 0; while (off < data.len) { const step = input.decodeOne(data[off..]) orelse break; // partial tail: drop in P1 off += step.consumed; switch (step.decoded) { .key => |k| self.applyKey(k) catch return, .paste => |p| self.insertText(p) catch return, // Negotiation replies are consumed by the app before input is // routed here; ignore defensively if one slips through. .negotiation => {}, } } } // -- render ------------------------------------------------------------ fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 { _ = alloc; const self: *InputBox = @ptrCast(@alignCast(ptr)); return self.renderLines(width); } /// 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; defer { for (rows.items) |r| a.free(r); rows.deinit(a); } const cursor_style = theme.default.fg(.cursor); // Locate the cursor's (row, byte-col-in-row). 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; const line_end = line_start + line.len; const cursor_in_line = focused and self.cursor >= line_start and self.cursor <= line_end and // The cursor belongs to the FIRST line whose range contains it // (at a '\n' boundary it stays on the line before the break, // i.e. == line_end). Disambiguate the boundary: if cursor == // line_end and there are more lines, it belongs to the NEXT // 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; line_byte_start = line_end + 1; // skip the '\n' } if (!produced_any) { // Empty buffer: a single (possibly cursor-bearing) row. const row = try self.renderRow("", if (focused) @as(?usize, 0) else null, cursor_style, width, focused); try rows.append(a, row); } // 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 /// cursor (or a space at end-of-line) and emits CURSOR_MARKER there. fn renderRow(self: *InputBox, line: []const u8, cursor_col: ?usize, cursor_style: Style, width: usize, focused: bool) ![]u8 { const a = self.alloc; // The cursor block consumes one visible column, so usable text width // is width-1 when the cursor sits at/after the truncated end and we // must show the block. To keep it simple and always-safe: truncate the // plain line to `width` columns; if a cursor block would push us to // width+1, the block replaces the last column instead. const vis = truncateToCols(line, width); var buf: std.ArrayList(u8) = .empty; errdefer buf.deinit(a); if (cursor_col == null or !focused) { try buf.appendSlice(a, vis); return buf.toOwnedSlice(a); } // Cursor is on this row. Find the byte position within `vis`. const cc = cursor_col.?; const before_cols = displayWidth(line[0..@min(cc, line.len)]); if (cc >= line.len) { // Cursor at end-of-line: block over a trailing space. Ensure room: // if the visible text already fills `width`, drop its last column. var head = vis; if (before_cols >= width) { head = truncateToCols(line, width - 1); } try buf.appendSlice(a, head); try buf.appendSlice(a, CURSOR_MARKER); try buf.appendSlice(a, cursor_style.open()); try buf.appendSlice(a, " "); try buf.appendSlice(a, cursor_style.close()); return buf.toOwnedSlice(a); } // Cursor over an interior glyph. Split: head | glyph | tail. const glyph_len = blk: { const sl = std.unicode.utf8ByteSequenceLength(line[cc]) catch 1; break :blk @min(sl, line.len - cc); }; const head = line[0..cc]; const glyph = line[cc .. cc + glyph_len]; const tail = line[cc + glyph_len ..]; // Compose head + marker + [reverse]glyph[/] + tail, then truncate the // whole visible width to `width` columns (escapes + marker are // zero-width, so truncation acts on glyphs). try buf.appendSlice(a, head); try buf.appendSlice(a, CURSOR_MARKER); try buf.appendSlice(a, cursor_style.open()); try buf.appendSlice(a, glyph); try buf.appendSlice(a, cursor_style.close()); try buf.appendSlice(a, tail); // The composed row's visible width == displayWidth(line). If that // exceeds `width`, rebuild with a width-bounded tail. (Rare: cursor // near a long line's start.) Simpler safe path: if over, truncate the // tail. if (displayWidth(line) > width) { buf.clearRetainingCapacity(); // Keep head+glyph; truncate tail to remaining columns. const used = before_cols + 1; // head cols + the glyph try buf.appendSlice(a, head); try buf.appendSlice(a, CURSOR_MARKER); try buf.appendSlice(a, cursor_style.open()); try buf.appendSlice(a, glyph); try buf.appendSlice(a, cursor_style.close()); if (used < width) { const remaining = width - used; try buf.appendSlice(a, truncateToCols(tail, remaining)); } } return buf.toOwnedSlice(a); } fn firstLineChangedImpl(ptr: *anyopaque) ?usize { const self: *InputBox = @ptrCast(@alignCast(ptr)); return self.cache.firstLineChanged(); } fn invalidateImpl(ptr: *anyopaque) void { const self: *InputBox = @ptrCast(@alignCast(ptr)); self.cache.invalidate(); } const vtable = Component.VTable{ .render = renderImpl, .firstLineChanged = firstLineChangedImpl, .invalidate = invalidateImpl, .handleInput = handleInputImpl, }; pub fn comp(self: *InputBox) Component { return .{ .ptr = self, .vtable = &vtable }; } }; // =========================================================================== // Footer — persistent bottom line with frame-timing element (plan §6) // =========================================================================== /// The persistent bottom line. For P1 it renders a FRAME-TIMING element: the /// last frame's render time as a theoretical-max fps (1000/ms), shown inverted /// (reverse-video). It optionally shows model info passed in by the app. The /// fps element is TEMPORARY (removed after perf validation) but REQUIRED for /// P1. /// /// Frame-time input: the app calls `setFrameTime(ms)` after each rendered frame /// with the measured render duration in milliseconds; this updates the fps and /// marks dirty so the footer repaints. `setModel(name)` sets the model info. pub const Footer = struct { alloc: std.mem.Allocator, cache: RenderCache, /// Last frame's render time in milliseconds (null = not measured yet). 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) }; } pub fn deinit(self: *Footer) void { self.model.deinit(self.alloc); self.cache.deinit(); } /// Feed the last frame's render time (milliseconds). Marks dirty so the /// footer's fps element repaints next frame. pub fn setFrameTime(self: *Footer, ms: f64) void { self.frame_ms = ms; self.cache.markDirty(); } /// Set the model info shown in the footer. pub fn setModel(self: *Footer, name: []const u8) !void { self.model.clearRetainingCapacity(); try self.model.appendSlice(self.alloc, name); 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. fn fpsText(self: *const Footer, buf: []u8) []const u8 { const ms = self.frame_ms orelse return std.fmt.bufPrint(buf, "fps: --", .{}) catch "fps: --"; if (ms <= 0.0) return std.fmt.bufPrint(buf, "fps: >9999", .{}) catch "fps: >9999"; const fps = 1000.0 / ms; if (fps > 9999.0) return std.fmt.bufPrint(buf, "fps: >9999", .{}) catch "fps: >9999"; return std.fmt.bufPrint(buf, "fps: {d:.0} ({d:.2}ms)", .{ fps, ms }) catch "fps: ?"; } fn renderImpl(ptr: *anyopaque, width: usize, alloc: std.mem.Allocator) anyerror![]const []const u8 { _ = alloc; const self: *Footer = @ptrCast(@alignCast(ptr)); const a = self.alloc; 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 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); // The fps element is shown INVERTED (reverse video). The whole footer // line uses reverse video so the timing element stands out; the model // rides along in the same inverted run. (Temporary perf chrome.) const cursor_style = theme.default.fg(.cursor); // reverse video const composed = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ cursor_style.open(), vis, cursor_style.close() }); defer a.free(composed); const lines = [_][]const u8{composed}; try self.cache.store(&lines); return cacheLines(&self.cache); } fn firstLineChangedImpl(ptr: *anyopaque) ?usize { const self: *Footer = @ptrCast(@alignCast(ptr)); return self.cache.firstLineChanged(); } fn invalidateImpl(ptr: *anyopaque) void { const self: *Footer = @ptrCast(@alignCast(ptr)); self.cache.invalidate(); } const vtable = Component.VTable{ .render = renderImpl, .firstLineChanged = firstLineChangedImpl, .invalidate = invalidateImpl, }; pub fn comp(self: *Footer) Component { return .{ .ptr = self, .vtable = &vtable }; } }; // =========================================================================== // 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" 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 () ` /// followed by a blank line and `(…)` as a result placeholder. /// 3. Once the result lands: `tool () ` /// 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 () ` ------------ 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 () `, 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 // =========================================================================== const testing = std.testing; const engine = @import("tui_engine.zig"); /// Visible width of a rendered (possibly styled, possibly marker-bearing) line, /// reusing the engine's authoritative measure. fn vw(line: []const u8) usize { return engine.visibleWidth(line); } // -- helpers --------------------------------------------------------------- test "displayWidth counts codepoints; truncateToCols respects boundaries" { try testing.expectEqual(@as(usize, 3), displayWidth("abc")); try testing.expectEqual(@as(usize, 3), displayWidth("aé✓")); try testing.expectEqualStrings("aé", truncateToCols("aé✓", 2)); try testing.expectEqualStrings("abc", truncateToCols("abcdef", 3)); // Never splits a multibyte codepoint. const t = truncateToCols("é", 1); try testing.expectEqualStrings("é", t); } test "wrapParagraph word-wraps and hard-splits long words" { var out: std.ArrayList([]const u8) = .empty; defer out.deinit(testing.allocator); try wrapParagraph("hello world foo", 7, &out, testing.allocator); try testing.expectEqual(@as(usize, 3), out.items.len); try testing.expectEqualStrings("hello", out.items[0]); try testing.expectEqualStrings("world", out.items[1]); try testing.expectEqualStrings("foo", out.items[2]); out.clearRetainingCapacity(); try wrapParagraph("abcdefghij", 4, &out, testing.allocator); try testing.expectEqual(@as(usize, 3), out.items.len); try testing.expectEqualStrings("abcd", out.items[0]); try testing.expectEqualStrings("efgh", out.items[1]); try testing.expectEqualStrings("ij", out.items[2]); } // -- AssistantText --------------------------------------------------------- test "AssistantText: renders wrapped text within width" { var at = AssistantText.init(testing.allocator); defer at.deinit(); try at.setText("hello world foo"); const lines = try at.comp().render(7, testing.allocator); try testing.expectEqual(@as(usize, 3), lines.len); for (lines) |l| try testing.expect(vw(l) <= 7); // First render after empty cache => changed from 0. try testing.expectEqual(@as(?usize, 0), at.comp().firstLineChanged()); } test "AssistantText: streaming keeps firstLineChanged near the tail, not 0" { var at = AssistantText.init(testing.allocator); defer at.deinit(); // Seed several wrapped lines. try at.setText("alpha beta gamma delta epsilon"); _ = try at.comp().render(11, testing.allocator); const lines1 = at.cache.lines.?.len; try testing.expect(lines1 >= 3); // Append a delta to the tail; earlier wrapped lines stay byte-identical. try at.appendDelta(" zeta"); // While dirty, firstLineChanged reports 0 (full markDirty). The KEY // property is what the cache reports AFTER the render: the lowest line that // actually changed must be near the tail, not 0. _ = try at.comp().render(11, testing.allocator); const fc = at.comp().firstLineChanged(); // The change landed on the last line(s); the cut must be > 0. try testing.expect(fc == null or fc.? > 0); // Stronger: the first changed line should be at the tail region. if (fc) |v| try testing.expect(v >= lines1 - 1); } test "AssistantText: width truncation on a long unbroken word" { var at = AssistantText.init(testing.allocator); defer at.deinit(); try at.setText("supercalifragilistic"); const lines = try at.comp().render(5, testing.allocator); for (lines) |l| try testing.expect(vw(l) <= 5); } // -- UserText --------------------------------------------------------------- test "UserText: renders user-styled lines within width" { var ut = UserText.init(testing.allocator); defer ut.deinit(); try ut.setText("a user message that wraps"); const lines = try ut.comp().render(10, testing.allocator); for (lines) |l| try testing.expect(vw(l) <= 10); // Static: re-render with no change => clean. _ = try ut.comp().render(10, testing.allocator); try testing.expectEqual(@as(?usize, null), ut.comp().firstLineChanged()); } // -- InputBox --------------------------------------------------------------- fn charKey(c: u21, text: []const u8) Key { return .{ .code = .{ .char = c }, .text = text }; } test "InputBox: insert printable chars and render with cursor block when focused" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); ib.setFocused(true); try ib.applyKey(charKey('h', "h")); try ib.applyKey(charKey('i', "i")); const lines = try ib.comp().render(20, testing.allocator); try testing.expectEqual(@as(usize, 1), lines.len); try testing.expect(vw(lines[0]) <= 20); // Focused => emits CURSOR_MARKER and reverse-video style. try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) != null); try testing.expect(std.mem.indexOf(u8, lines[0], "\x1b[7m") != null); try testing.expect(std.mem.indexOf(u8, lines[0], "hi") != null); } test "InputBox: not focused emits no cursor marker" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); try ib.applyKey(charKey('x', "x")); const lines = try ib.comp().render(20, testing.allocator); try testing.expect(std.mem.indexOf(u8, lines[0], CURSOR_MARKER) == null); } test "InputBox: backspace, delete, and cursor movement" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); for ("abc") |c| try ib.applyKey(charKey(c, &[_]u8{c})); try testing.expectEqual(@as(usize, 3), ib.cursor); ib.backspace(); // "ab" try testing.expectEqualStrings("ab", ib.text.items); try testing.expectEqual(@as(usize, 2), ib.cursor); ib.moveLeft(); // cursor at 1 try testing.expectEqual(@as(usize, 1), ib.cursor); ib.deleteForward(); // delete 'b' -> "a" try testing.expectEqualStrings("a", ib.text.items); ib.moveHome(); try testing.expectEqual(@as(usize, 0), ib.cursor); ib.moveEnd(); try testing.expectEqual(@as(usize, 1), ib.cursor); } test "InputBox: multibyte backspace removes a whole codepoint" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); try ib.applyKey(charKey('é', "é")); // 2 bytes try testing.expectEqual(@as(usize, 2), ib.cursor); ib.backspace(); try testing.expectEqual(@as(usize, 0), ib.text.items.len); } test "InputBox: shift+enter inserts newline, enter submits" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); for ("ab") |c| try ib.applyKey(charKey(c, &[_]u8{c})); // Shift+Enter => newline (grows a row). try ib.applyKey(.{ .code = .enter, .mods = .{ .shift = true } }); for ("cd") |c| try ib.applyKey(charKey(c, &[_]u8{c})); try testing.expectEqualStrings("ab\ncd", ib.text.items); const lines = try ib.comp().render(20, testing.allocator); try testing.expectEqual(@as(usize, 2), lines.len); // Plain Enter => submit, editor cleared, pollable buffer set. try ib.applyKey(.{ .code = .enter }); const got = ib.takeSubmitted(); try testing.expect(got != null); try testing.expectEqualStrings("ab\ncd", got.?); try testing.expectEqual(@as(usize, 0), ib.text.items.len); // Second poll returns null. try testing.expect(ib.takeSubmitted() == null); } test "InputBox: handleInput decodes raw bytes (typing + enter)" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); ib.comp().handleInput("hi\r"); // 'h' 'i' Enter const got = ib.takeSubmitted(); try testing.expect(got != null); try testing.expectEqualStrings("hi", got.?); } test "InputBox: handleInput kitty shift+enter inserts newline" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); ib.comp().handleInput("a\x1b[13;2ub"); // 'a', shift+enter, 'b' try testing.expectEqualStrings("a\nb", ib.text.items); try testing.expect(ib.takeSubmitted() == null); // no plain enter yet } test "InputBox: firstLineChanged is cache-derived (clean after stable render)" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); ib.setFocused(true); try ib.applyKey(charKey('x', "x")); _ = try ib.comp().render(20, testing.allocator); // Re-render with no state change => clean. _ = try ib.comp().render(20, testing.allocator); try testing.expectEqual(@as(?usize, null), ib.comp().firstLineChanged()); // Edit => dirty again. try ib.applyKey(charKey('y', "y")); try testing.expectEqual(@as(?usize, 0), ib.comp().firstLineChanged()); } test "InputBox: cursor block fits within width at end of a full line" { var ib = InputBox.init(testing.allocator); defer ib.deinit(); ib.setFocused(true); for ("abcde") |c| try ib.applyKey(charKey(c, &[_]u8{c})); // width 5, cursor at end: the block must not overflow. const lines = try ib.comp().render(5, testing.allocator); 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" { var ft = Footer.init(testing.allocator); defer ft.deinit(); ft.setFrameTime(8.0); // 1000/8 = 125 fps const lines = try ft.comp().render(80, testing.allocator); try testing.expectEqual(@as(usize, 1), lines.len); try testing.expect(vw(lines[0]) <= 80); // Inverted (reverse video) styling present. try testing.expect(std.mem.indexOf(u8, lines[0], "\x1b[7m") != null); // fps value 125 present. try testing.expect(std.mem.indexOf(u8, lines[0], "125") != null); } test "Footer: unmeasured frame shows placeholder; submillisecond capped" { var ft = Footer.init(testing.allocator); defer ft.deinit(); var buf: [48]u8 = undefined; try testing.expectEqualStrings("fps: --", ft.fpsText(&buf)); ft.setFrameTime(0.0); try testing.expectEqualStrings("fps: >9999", ft.fpsText(&buf)); ft.setFrameTime(0.05); // 20000 fps -> capped try testing.expectEqualStrings("fps: >9999", ft.fpsText(&buf)); } test "Footer: shows model info and truncates to width" { var ft = Footer.init(testing.allocator); defer ft.deinit(); ft.setFrameTime(10.0); try ft.setModel("gpt-test-model"); const lines = try ft.comp().render(12, testing.allocator); try testing.expect(vw(lines[0]) <= 12); } test "Footer: setFrameTime dirties; stable re-render is clean" { var ft = Footer.init(testing.allocator); defer ft.deinit(); ft.setFrameTime(8.0); _ = try ft.comp().render(80, testing.allocator); _ = try ft.comp().render(80, testing.allocator); try testing.expectEqual(@as(?usize, null), ft.comp().firstLineChanged()); ft.setFrameTime(16.0); 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" { var buf = std.Io.Writer.Allocating.init(testing.allocator); defer buf.deinit(); var eng = engine.Engine.init(testing.allocator, &buf.writer, 40, 24, false); defer eng.deinit(); var user = UserText.init(testing.allocator); defer user.deinit(); var assistant = AssistantText.init(testing.allocator); defer assistant.deinit(); var ib = InputBox.init(testing.allocator); defer ib.deinit(); var footer = Footer.init(testing.allocator); defer footer.deinit(); try user.setText("hi there"); try assistant.appendDelta("hello"); ib.setFocused(true); try ib.applyKey(charKey('q', "q")); footer.setFrameTime(8.0); try eng.addComponent(user.comp()); try eng.addComponent(assistant.comp()); try eng.addComponent(ib.comp()); try eng.addComponent(footer.comp()); try eng.render(); // first paint: must not error (width contract holds) const out = buf.written(); try testing.expect(std.mem.indexOf(u8, out, "hi there") != null); try testing.expect(std.mem.indexOf(u8, out, "hello") != null); // Cursor marker is consumed by the engine and recorded as a hint. try testing.expect(eng.cursor_hint != null); // Stream another delta -> only the assistant should re-render; the engine // stays on the differential path (no full clear after first paint). try assistant.appendDelta(" world"); footer.setFrameTime(9.0); buf.clearRetainingCapacity(); try eng.render(); 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); }