graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(tui): fold headers read like grok-build's — verb, count, tense
Rach Pradhan224f3dac12e2
diff --git a/AGENTS.md b/AGENTS.mdindex d4a9b5e8..ddcd04b1 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -27,8 +27,8 @@ defer term.deinit();_ = term.typeText("/help");_ = term.enter();const vis = try term.screen(); // glyphs a user would see (no SGR)-const rows = try term.annotated(); // " 12| ◆ Called 2 tools"-_ = try term.clickText("Called"); // click the first matching glyph+const rows = try term.annotated(); // " 12| › Ran bash"+_ = try term.clickText("Ran bash"); // click the first matching glyph_ = try term.hoverText("[Image #1]"); // hover an image chipconst lay = try term.layout(); // overlay / focus / origins / images / pending```diff --git a/TUI/anchor.zig b/TUI/anchor.zigindex 45db59b6..62973395 100644--- a/TUI/anchor.zig+++ b/TUI/anchor.zig@@ -254,7 +254,7 @@ test "a collapsed tool run anchors as one block" {// indexAtVisual maps anywhere in the run to its start — the anchored// block is the run, and the run is still what the top row shows.try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, w).?);- try testing.expect(std.mem.indexOf(u8, frame, "Called") != null);+ try testing.expect(std.mem.indexOf(u8, frame, "Ran bash") != null);}}diff --git a/TUI/app.zig b/TUI/app.zigindex 5fab4d09..5687df96 100644--- a/TUI/app.zig+++ b/TUI/app.zig@@ -42,6 +42,11 @@ pub const Entry = struct {/// those still render from `text` alone (see scrollback.zig), which is the/// whole reason this is optional rather than required.tool: ?ToolInfo = null,+ /// The loop clock when this row was appended — the only thing the fold+ /// header's settle flash needs (foldhdr.zig). Rows restored from a session+ /// are pushed before the loop ever sets `now_ms`, so they carry 0 against+ /// a boot-monotonic clock and a resumed transcript comes up quiet.+ at_ms: u64 = 0,};pub const Effect = enum { stay, quit, background };@@ -223,7 +228,7 @@ pub const Model = struct {pub fn push(self: *Model, kind: EntryKind, text: []const u8) !void {const owned = try sanitized(self.alloc, text);errdefer self.alloc.free(owned);- try self.history.append(.{ .kind = kind, .text = owned, .folded = kind == .tool });+ try self.history.append(.{ .kind = kind, .text = owned, .folded = kind == .tool, .at_ms = self.now_ms });if (kind == .user or kind == .assistant) {self.screen = .agent;self.follow = true;@@ -256,6 +261,7 @@ pub const Model = struct {.is_error = info.is_error,.denied = info.denied,},+ .at_ms = self.now_ms,});}diff --git a/TUI/foldhdr.zig b/TUI/foldhdr.zignew file mode 100644index 00000000..8dd938fd--- /dev/null+++ b/TUI/foldhdr.zig@@ -0,0 +1,396 @@+//! Fold headers for tool runs — grok-build's disclosure row.+//!+//! A collapsed run of `.tool` rows used to render a bare "Called N". This+//! derives a VERB and an object phrase from the run's typed tool events+//! instead: present-progressive with the live count while calls are still+//! landing ("Reading 2 files…"), past tense once the run settles ("Read 3+//! files").+//!+//! Nothing here parses a rendered line. Every fact comes off `Entry.tool` —+//! the engine's own ToolInvocation/ToolOutcome payload (#551) — so the header+//! is rebuilt from Model data on every frame and the count simply follows the+//! events in. A run whose calls disagree about what they are ("mixed") falls+//! back to the old "Called N tools" wording, which is the honest thing to say.++const std = @import("std");++const app = @import("app.zig");+const glyphs = @import("glyphs.zig");+const theme_mod = @import("theme.zig");+const Model = app.Model;++/// How long the accent tint sits on a header after its last call returns.+/// Two ticks of the same 500ms clock the pending blink runs on (glyphs.zig),+/// so the settle flash and the blink share one timebase rather than inventing+/// a second one.+pub const flash_ms: u64 = 1000;++/// The gutter an OPEN run's cards hang under, in columns. `│ ` — the same+/// light rail a tool card already uses for its result body.+pub const gutter = "\u{2502} ";+pub const gutter_cols: usize = 2;++// ── families ────────────────────────────────────────────────────────────────++pub const Family = enum { read, write, edit, bash, search, web, task, todo, mcp, other, mixed };++const Verb = struct {+ /// In flight.+ present: []const u8,+ /// Settled.+ past: []const u8,+ /// Countable object, singular. Pluralised with a bare "s".+ noun: []const u8,+ /// A run of exactly ONE call names the tool instead of counting a noun:+ /// "Running bash" reads the way grok-build's does; "Running 1 command"+ /// does not.+ solo_tool: bool = false,+};++fn verbOf(f: Family) Verb {+ return switch (f) {+ .read => .{ .present = "Reading", .past = "Read", .noun = "file" },+ .write => .{ .present = "Writing", .past = "Wrote", .noun = "file" },+ .edit => .{ .present = "Editing", .past = "Edited", .noun = "file" },+ .bash => .{ .present = "Running", .past = "Ran", .noun = "command", .solo_tool = true },+ .search => .{ .present = "Searching", .past = "Searched", .noun = "pattern" },+ .web => .{ .present = "Fetching", .past = "Fetched", .noun = "page" },+ .task => .{ .present = "Running", .past = "Ran", .noun = "task" },+ .todo => .{ .present = "Updating", .past = "Updated", .noun = "todo" },+ .mcp => .{ .present = "Calling", .past = "Called", .noun = "MCP tool" },+ .other => .{ .present = "Calling", .past = "Called", .noun = "tool", .solo_tool = true },+ .mixed => .{ .present = "Calling", .past = "Called", .noun = "tool" },+ };+}++fn eqAny(name: []const u8, set: []const []const u8) bool {+ for (set) |s| {+ if (std.mem.eql(u8, name, s)) return true;+ }+ return false;+}++fn has(hay: []const u8, needle: []const u8) bool {+ if (needle.len > hay.len) return false;+ var i: usize = 0;+ while (i + needle.len <= hay.len) : (i += 1) {+ if (std.ascii.eqlIgnoreCase(hay[i .. i + needle.len], needle)) return true;+ }+ return false;+}++pub fn isMcp(name: []const u8) bool {+ return std.mem.startsWith(u8, name, "mcp__");+}++/// The leaf of an MCP tool name (`mcp__server__leaf` → `leaf`), or the name+/// itself. Classification runs on the leaf so a server's `faster_search` is a+/// search and its `read` is a read, exactly as a first-party tool would be.+pub fn leafOf(name: []const u8) []const u8 {+ if (!isMcp(name)) return name;+ if (std.mem.lastIndexOf(u8, name, "__")) |u| {+ if (u + 2 < name.len) return name[u + 2 ..];+ }+ return name;+}++/// The display form of a tool NAME: the harness's internal names shortened,+/// an MCP tool shown by its leaf. Operates on the name alone.+pub fn displayName(name: []const u8) []const u8 {+ if (std.mem.eql(u8, name, "read_file")) return "read";+ if (std.mem.eql(u8, name, "write_file")) return "write";+ return leafOf(name);+}++/// Which verb family a tool name belongs to. Exact names first — they are what+/// this harness actually emits — then the looser substring tests the old+/// `isSearch` used, so an unfamiliar `*_search` / `*_grep` leaf still reads as+/// a search rather than falling all the way to "Called N tools".+pub fn familyOf(name: []const u8) Family {+ const leaf = leafOf(name);+ if (eqAny(leaf, &.{ "read_file", "read", "view", "cat", "open" })) return .read;+ if (eqAny(leaf, &.{ "write_file", "write", "create" })) return .write;+ if (eqAny(leaf, &.{ "edit_file", "edit", "patch", "replace", "apply_patch", "multiedit" })) return .edit;+ if (eqAny(leaf, &.{ "bash", "shell", "exec", "run_command", "bash_output", "bash_kill" })) return .bash;+ // Before the generic search test below: `web_search` is a fetch, not a+ // codebase search, and it would otherwise be swallowed by "search".+ if (eqAny(leaf, &.{ "webfetch", "web_fetch", "web_search", "fetch", "browse" })) return .web;+ if (eqAny(leaf, &.{ "task", "subagent", "workflow", "agent_output", "dispatch_agent" })) return .task;+ if (std.mem.startsWith(u8, leaf, "todo")) return .todo;+ if (eqAny(leaf, &.{ "grep", "glob", "search", "find", "ls", "list_dir", "codedb" })) return .search;+ if (has(leaf, "search") or has(leaf, "grep") or has(leaf, "glob") or has(leaf, "find")) return .search;+ if (has(leaf, "web")) return .web;+ if (isMcp(name)) return .mcp;+ return .other;+}++// ── run walk ────────────────────────────────────────────────────────────────++/// A tool row's start/done phase, straight off its typed payload. A legacy row+/// (tool == null) is neither: it has no phase to read, so it renders alone.+pub fn isStartTool(e: app.Entry) bool {+ const t = e.tool orelse return false;+ return !t.done;+}++pub fn isDoneTool(e: app.Entry) bool {+ const t = e.tool orelse return false;+ return t.done;+}++/// The index after the logical call at `t`: an announce and the outcome that+/// answers it are ONE call, so the header counts them once.+pub fn nextTool(self: *const Model, t: usize, end: usize) usize {+ if (t + 1 < end and isStartTool(self.history.items[t]) and isDoneTool(self.history.items[t + 1]))+ return t + 2;+ return t + 1;+}++/// Everything a header says, counted off the run's typed events.+pub const Run = struct {+ /// Logical calls: an announce plus its outcome is ONE.+ calls: usize = 0,+ family: Family = .other,+ /// Display name of the only call, when there is exactly one.+ solo: []const u8 = "",+ /// A call has been announced and has not come back yet.+ live: bool = false,+ /// `at_ms` of the last outcome in the run — when it settled.+ settled_ms: u64 = 0,+};++pub fn scan(self: *const Model, start: usize, end: usize) Run {+ var r: Run = .{};+ if (start >= end or end > self.history.items.len) return r;+ var fam: ?Family = null;+ var all_mcp = true;+ var t = start;+ while (t < end) {+ const e = self.history.items[t];+ const name = if (e.tool) |ti| ti.name else "";+ const f = if (name.len == 0) Family.other else familyOf(name);+ if (!isMcp(name)) all_mcp = false;+ if (fam) |prev| {+ if (prev != .mixed and prev != f) fam = .mixed;+ } else fam = f;+ r.calls += 1;+ if (r.calls == 1) r.solo = displayName(name);+ const nxt = nextTool(self, t, end);+ var k = t;+ while (k < nxt) : (k += 1) {+ if (isDoneTool(self.history.items[k])) r.settled_ms = @max(r.settled_ms, self.history.items[k].at_ms);+ }+ t = nxt;+ }+ r.family = fam orelse .other;+ // A run of MCP calls that disagree about their shape is still an MCP run —+ // "Called 2 MCP tools" beats the flat "Called 2 tools" it would otherwise+ // fall back to.+ if (r.family == .mixed and all_mcp) r.family = .mcp;+ if (r.calls != 1) r.solo = "";+ // The run is in flight exactly when its LAST row is an unanswered announce.+ r.live = isStartTool(self.history.items[end - 1]);+ return r;+}++// ── words ───────────────────────────────────────────────────────────────────++/// The header's words: verb, count, object. Present-progressive with a+/// trailing ellipsis while the run is live, past tense once it settles.+pub fn phrase(a: std.mem.Allocator, r: Run) ![]const u8 {+ if (r.calls == 0) return "";+ const v = verbOf(r.family);+ const verb = if (r.live) v.present else v.past;+ const tail: []const u8 = if (r.live) "\u{2026}" else "";+ if (r.calls == 1 and v.solo_tool and r.solo.len > 0)+ return std.fmt.allocPrint(a, "{s} {s}{s}", .{ verb, r.solo, tail });+ return std.fmt.allocPrint(a, "{s} {d} {s}{s}{s}", .{+ verb,+ r.calls,+ v.noun,+ if (r.calls == 1) "" else "s",+ tail,+ });+}++/// The disclosure mark: the accent chevron when the run is folded shut, a+/// down-pointing arrowhead when it is open. Both are ONE column in every+/// terminal — see glyphs.zig, which pins the pair.+pub fn chevron(open: bool) []const u8 {+ return if (open) glyphs.chev_open else glyphs.chev_closed;+}++/// Is this run inside its settle flash? False while it is live and false once+/// the window has passed, so the header row changes exactly twice per run.+///+/// A run restored from a session was pushed before the loop ever set+/// `now_ms`, so its rows carry `at_ms == 0` against a boot-monotonic clock —+/// far outside the window, and the transcript comes up quiet.+pub fn flashing(r: Run, now_ms: u64) bool {+ if (r.calls == 0 or r.live) return false;+ return now_ms -| r.settled_ms < flash_ms;+}++/// The settle tint. Accent-derived and deliberately shallow: a wash the eye+/// catches in passing, never a highlight that competes with the selection.+pub fn flashBg(th: theme_mod.Theme) []const u8 {+ return if (th.id == .day) "\x1b[48;2;231;227;246m" else "\x1b[48;2;42;36;58m";+}++// ── tests ───────────────────────────────────────────────────────────────────++const testing = std.testing;++fn oneRun(m: *Model) Run {+ return scan(m, 0, m.history.items.len);+}++test "a homogeneous run reads present-progressive live and past tense settled" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();++ try m.pushTool(.{ .name = "read_file", .detail = "a.zig" });+ try testing.expectEqualStrings("Reading 1 file\u{2026}", try phrase(a, oneRun(&m)));+ try m.pushTool(.{ .name = "read_file", .detail = "…", .done = true });+ try testing.expectEqualStrings("Read 1 file", try phrase(a, oneRun(&m)));++ // The count follows the events in, one logical call at a time.+ try m.pushTool(.{ .name = "read_file", .detail = "b.zig" });+ try testing.expectEqualStrings("Reading 2 files\u{2026}", try phrase(a, oneRun(&m)));+ try m.pushTool(.{ .name = "read_file", .detail = "…", .done = true });+ try m.pushTool(.{ .name = "read_file", .detail = "c.zig" });+ try m.pushTool(.{ .name = "read_file", .detail = "…", .done = true });+ try testing.expectEqualStrings("Read 3 files", try phrase(a, oneRun(&m)));+}++test "a single call names its tool where that is how it reads" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();++ try m.pushTool(.{ .name = "bash", .detail = "ls" });+ try testing.expectEqualStrings("Running bash\u{2026}", try phrase(a, oneRun(&m)));+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });+ try testing.expectEqualStrings("Ran bash", try phrase(a, oneRun(&m)));+ // ...but a run of them counts commands rather than repeating the name.+ try m.pushTool(.{ .name = "bash", .detail = "pwd" });+ try m.pushTool(.{ .name = "bash", .detail = "/", .done = true });+ try testing.expectEqualStrings("Ran 2 commands", try phrase(a, oneRun(&m)));+}++test "each family gets its own verb and object" {+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const cases = [_]struct { f: Family, n: usize, want: []const u8 }{+ .{ .f = .write, .n = 2, .want = "Wrote 2 files" },+ .{ .f = .edit, .n = 3, .want = "Edited 3 files" },+ .{ .f = .search, .n = 2, .want = "Searched 2 patterns" },+ .{ .f = .web, .n = 1, .want = "Fetched 1 page" },+ .{ .f = .task, .n = 2, .want = "Ran 2 tasks" },+ .{ .f = .todo, .n = 1, .want = "Updated 1 todo" },+ .{ .f = .mcp, .n = 2, .want = "Called 2 MCP tools" },+ .{ .f = .mixed, .n = 3, .want = "Called 3 tools" },+ };+ for (cases) |c| {+ try testing.expectEqualStrings(c.want, try phrase(a, .{ .calls = c.n, .family = c.f }));+ }+}++test "a heterogeneous run falls back to Called N tools" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ try m.pushTool(.{ .name = "bash", .detail = "ls" });+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });+ try m.pushTool(.{ .name = "read_file", .detail = "a.zig" });+ try m.pushTool(.{ .name = "read_file", .detail = "…", .done = true });+ const r = oneRun(&m);+ try testing.expectEqual(Family.mixed, r.family);+ try testing.expectEqualStrings("Called 2 tools", try phrase(arena.allocator(), r));+}++test "an all-MCP run keeps the MCP wording even when its leaves disagree" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "note" });+ try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "saved", .done = true });+ try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "needle" });+ try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "3 hits", .done = true });+ const r = oneRun(&m);+ try testing.expectEqual(Family.mcp, r.family);+ try testing.expectEqualStrings("Called 2 MCP tools", try phrase(arena.allocator(), r));+}++test "familyOf reads the name, and an MCP leaf classifies like a first-party tool" {+ try testing.expectEqual(Family.read, familyOf("read_file"));+ try testing.expectEqual(Family.write, familyOf("write_file"));+ try testing.expectEqual(Family.edit, familyOf("edit_file"));+ try testing.expectEqual(Family.bash, familyOf("bash"));+ try testing.expectEqual(Family.search, familyOf("grep"));+ try testing.expectEqual(Family.search, familyOf("glob"));+ try testing.expectEqual(Family.search, familyOf("mcp__codedbpro__faster_search"));+ try testing.expectEqual(Family.read, familyOf("mcp__codedbpro__read"));+ try testing.expectEqual(Family.web, familyOf("webfetch"));+ // web_search is a fetch, not a codebase search — the ordering that pins it.+ try testing.expectEqual(Family.web, familyOf("web_search"));+ try testing.expectEqual(Family.task, familyOf("subagent"));+ try testing.expectEqual(Family.todo, familyOf("todo_write"));+ try testing.expectEqual(Family.mcp, familyOf("mcp__github__create_issue"));+ try testing.expectEqual(Family.other, familyOf("imagegen"));+}++test "the settle flash opens when the last call lands and closes on its own" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ m.now_ms = 5_000;+ try m.pushTool(.{ .name = "bash", .detail = "ls" });+ // Live: never flashing, however long it runs.+ try testing.expect(!flashing(oneRun(&m), 5_000));+ try testing.expect(!flashing(oneRun(&m), 9_000));+ m.now_ms = 6_000;+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });+ const r = oneRun(&m);+ try testing.expectEqual(@as(u64, 6_000), r.settled_ms);+ try testing.expect(flashing(r, 6_000));+ try testing.expect(flashing(r, 6_999));+ try testing.expect(!flashing(r, 7_000));+ try testing.expect(!flashing(r, 30_000));+}++test "a legacy row with no typed payload still counts and never flashes" {+ var m: Model = undefined;+ m.setup(testing.allocator);+ defer m.deinit();+ var arena = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena.deinit();+ m.now_ms = 5_000;+ try m.push(.tool, "bash | ok");+ const r = oneRun(&m);+ try testing.expectEqual(@as(usize, 1), r.calls);+ try testing.expect(!r.live);+ try testing.expectEqualStrings("Called 1 tool", try phrase(arena.allocator(), r));+ // Nothing ever reported an outcome, so there is no settle to tint.+ try testing.expectEqual(@as(u64, 0), r.settled_ms);+ try testing.expect(!flashing(r, 5_000));+}++test "displayName shortens an mcp tool to its leaf, reading the NAME" {+ try testing.expectEqualStrings("memo", displayName("mcp__codedbpro__memo"));+ try testing.expectEqualStrings("faster_search", displayName("mcp__codedbpro__faster_search"));+ try testing.expectEqualStrings("bash", displayName("bash"));+ try testing.expectEqualStrings("read", displayName("read_file"));+}diff --git a/TUI/glyphs.zig b/TUI/glyphs.zigindex 5f770900..9338fe76 100644--- a/TUI/glyphs.zig+++ b/TUI/glyphs.zig@@ -33,7 +33,8 @@//!//! U+2759 ❙ N pending blink, frame 0 one column everywhere//! U+2758 ❘ N pending blink, frame 1 one column everywhere-//! U+203A › N selection mark, composer caret+//! U+203A › N selection mark, composer caret, folded-run chevron+//! U+2304 ⌄ N open-run chevron//! U+276F ❯ N sticky header prompt mark//! U+2298 ⊘ N denied tool//! U+2717 ✗ N failed tool@@ -42,7 +43,8 @@//! U+25C6 ◆ A tool mark static, box-class//! U+00B7 · A system mark, meter separator static, box-class//! U+258B ▋ A composer cursor static, box-class-//! U+25A0 ■ A stopped/interrupted row static, box-class+//! U+25A0 ■ A stopped/interrupted row static, box-class+//! U+2026 … A live-header ellipsis static, box-class//!//! The two blink frames were the suspect ones — they read like the ambiguous//! Geometric Shapes neighbours — but Dingbats U+2758..U+2767 are Neutral, so@@ -66,7 +68,8 @@ pub const Glyph = struct {pub const registry = [_]Glyph{.{ .cp = 0x2759, .cols = 1, .class = .narrow, .role = "pending blink, frame 0" },.{ .cp = 0x2758, .cols = 1, .class = .narrow, .role = "pending blink, frame 1" },- .{ .cp = 0x203A, .cols = 1, .class = .narrow, .role = "selection mark / composer caret" },+ .{ .cp = 0x203A, .cols = 1, .class = .narrow, .role = "selection mark / composer caret / folded-run chevron" },+ .{ .cp = 0x2304, .cols = 1, .class = .narrow, .role = "open-run chevron" },.{ .cp = 0x276F, .cols = 1, .class = .narrow, .role = "sticky header prompt mark" },.{ .cp = 0x2298, .cols = 1, .class = .narrow, .role = "denied tool" },.{ .cp = 0x2717, .cols = 1, .class = .narrow, .role = "failed tool" },@@ -76,6 +79,7 @@ pub const registry = [_]Glyph{.{ .cp = 0x00B7, .cols = 1, .class = .ambiguous, .role = "system mark / meter separator" },.{ .cp = 0x258B, .cols = 1, .class = .ambiguous, .role = "composer cursor" },.{ .cp = 0x25A0, .cols = 1, .class = .ambiguous, .role = "stopped / interrupted row" },+ .{ .cp = 0x2026, .cols = 1, .class = .ambiguous, .role = "live fold-header ellipsis" },};// ── animated ────────────────────────────────────────────────────────────────@@ -89,11 +93,18 @@ pub const thinking = [_][]const u8{ "\u{2759}", "\u{2758}" };/// row's body starts at the same column selected or not.pub const row_mark = [_][]const u8{ "\u{203A} ", " " };+/// The tool-run fold chevron, closed then open. Not a tick — it flips on a+/// click — but it is registered as a frame SET for exactly the same reason:+/// both states must measure one column, or opening a run steps its verb+/// sideways.+pub const chev_flip = [_][]const u8{ chev_closed, chev_open };+pub const Animation = struct { name: []const u8, frames: []const []const u8 };pub const animations = [_]Animation{.{ .name = "pending-blink", .frames = &thinking },.{ .name = "row-mark", .frames = &row_mark },+ .{ .name = "chev-flip", .frames = &chev_flip },};/// Frame `i` of an animation, wrapping — call sites index by time, never by a@@ -113,6 +124,14 @@ pub const denied = "\u{2298}";pub const failed = "\u{2717}";pub const cursor = "\u{258B}";+/// The tool-run disclosure pair. Both are EAW-Narrow — ONE column in every+/// terminal, ambiguous-wide setting included — so flipping a run open cannot+/// shift the verb beside it by a column. The `chev_flip` animation below is+/// what asserts that; the pair is a state change, not a tick, but the width+/// law it has to obey is the animated one.+pub const chev_closed = "\u{203A}";+pub const chev_open = "\u{2304}";+fn lookup(cp: u21) ?Glyph {for (registry) |g| {if (g.cp == cp) return g;diff --git a/TUI/layout_cache.zig b/TUI/layout_cache.zigindex be7c5eb8..5a9918f1 100644--- a/TUI/layout_cache.zig+++ b/TUI/layout_cache.zig@@ -29,6 +29,7 @@const std = @import("std");const app = @import("app.zig");+const foldhdr = @import("foldhdr.zig");const scrollback = @import("scrollback.zig");const theme_mod = @import("theme.zig");const Model = app.Model;@@ -211,20 +212,11 @@ fn steerText(m: *Model, a: std.mem.Allocator) ![]const u8 {/// tool run.fn blockText(m: *const Model, a: std.mem.Allocator, start: usize, end: usize, width: usize, users: u32) ![]const u8 {const e = m.history.items[start];- const sel = m.focus == .scrollback and m.selected >= start and m.selected < end;- if (e.kind != .tool) return scrollback.row(m, a, users, e, width, m.now_ms, sel);- if (e.folded) return scrollback.summary(m, a, start, end, sel);- var out = std.array_list.Managed(u8).init(a);- var first = true;- var t = start;- while (t < end) {- if (!first) try out.append('\n');- first = false;- const one = m.focus == .scrollback and t == m.selected;- try out.appendSlice(try scrollback.toolVisual(m, a, t, end, width, m.now_ms, one));- t = scrollback.nextTool(m, t, end);+ if (e.kind != .tool) {+ const sel = m.focus == .scrollback and m.selected >= start and m.selected < end;+ return scrollback.row(m, a, users, e, width, m.now_ms, sel);}- return out.items;+ return scrollback.runVisual(m, a, start, end, width, m.now_ms);}/// Everything the block's bytes are a function of. Entry identity is the@@ -239,6 +231,15 @@ fn blockKey(m: *const Model, start: usize, end: usize, width: usize, th: u8, useh.update(std.mem.asBytes(&users));const sel: usize = if (m.focus == .scrollback and m.selected >= start and m.selected < end) m.selected + 1 else 0;h.update(std.mem.asBytes(&sel));+ // A tool run's header carries a settle FLASH that turns itself off a+ // second after the last call lands (foldhdr.zig). Nothing else about the+ // block moves when it does, so without this the cache would keep serving+ // the tinted row forever — the one place where these bytes are a function+ // of the clock as well as of the entries.+ if (m.history.items[start].kind == .tool) {+ const flash = @intFromBool(foldhdr.flashing(foldhdr.scan(m, start, end), m.now_ms));+ h.update(std.mem.asBytes(&flash));+ }var i = start;while (i < end) : (i += 1) {const e = m.history.items[i];diff --git a/TUI/markdown.zig b/TUI/markdown.zigindex ce564cef..9be259c6 100644--- a/TUI/markdown.zig+++ b/TUI/markdown.zig@@ -3,6 +3,7 @@const std = @import("std");const diff = @import("diff.zig");const theme_mod = @import("theme.zig");+const mdtable = @import("mdtable.zig");const syntax = @import("syntax.zig");/// Headers, fences, bullets, `code`, **bold**, and `/slash` tokens.@@ -143,8 +144,8 @@ pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme,i += 1;continue;}- if (tableLen(lines.items[i..])) |n| {- try emitTable(&out, a, lines.items[i .. i + n], th.accent, th.muted, th.text, width);+ if (mdtable.tableLen(lines.items[i..])) |n| {+ try mdtable.emitTable(&out, a, lines.items[i .. i + n], th.accent, th.muted, th.text, width);i += n;continue;}@@ -206,8 +207,8 @@ pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, mi += 1;continue;}- if (tableLen(lines.items[i..])) |n| {- try emitTable(&out, a, lines.items[i .. i + n], accent, muted, text, 0);+ if (mdtable.tableLen(lines.items[i..])) |n| {+ try mdtable.emitTable(&out, a, lines.items[i .. i + n], accent, muted, text, 0);i += n;continue;}@@ -274,7 +275,7 @@ pub fn renderUser(a: std.mem.Allocator, src: []const u8, accent: []const u8, texreturn out.toOwnedSlice();}-fn inlineSpans(out: *std.array_list.Managed(u8), line: []const u8, accent: []const u8, text: []const u8) !void {+pub fn inlineSpans(out: *std.array_list.Managed(u8), line: []const u8, accent: []const u8, text: []const u8) !void {var i: usize = 0;while (i < line.len) {if (line[i] == '`') {@@ -300,161 +301,6 @@ fn inlineSpans(out: *std.array_list.Managed(u8), line: []const u8, accent: []con}}-const max_table_cols: usize = 8;--fn isTableRow(line: []const u8) bool {- const t = std.mem.trim(u8, line, " \t");- if (t.len < 3 or t[0] != '|') return false;- return std.mem.indexOfScalar(u8, t[1..], '|') != null;-}--fn isSepRow(line: []const u8) bool {- if (!isTableRow(line)) return false;- var buf: [max_table_cols][]const u8 = undefined;- const n = splitCells(line, &buf);- if (n == 0) return false;- for (buf[0..n]) |c| {- if (c.len == 0) return false;- for (c) |ch| {- if (ch != '-' and ch != ':' and ch != ' ') return false;- }- }- return true;-}--fn tableLen(lines: []const []const u8) ?usize {- if (lines.len < 2 or !isTableRow(lines[0]) or !isSepRow(lines[1])) return null;- var n: usize = 2;- while (n < lines.len and isTableRow(lines[n]) and !isSepRow(lines[n])) n += 1;- return n;-}--fn splitCells(line: []const u8, out: [][]const u8) usize {- var t = std.mem.trim(u8, line, " \t");- if (t.len > 0 and t[0] == '|') t = t[1..];- if (t.len > 0 and t[t.len - 1] == '|') t = t[0 .. t.len - 1];- var n: usize = 0;- var it = std.mem.splitScalar(u8, t, '|');- while (it.next()) |raw| {- if (n >= out.len) break;- out[n] = std.mem.trim(u8, raw, " \t");- n += 1;- }- return n;-}--/// Visible width of a cell AS RENDERED: run it through inlineSpans and count.-/// Guessing at markers went wrong on every unmatched ` or ** (the render kept-/// them, the measure dropped them, the pad math sheared the grid).-fn cellWidth(a: std.mem.Allocator, s: []const u8) usize {- var scratch = std.array_list.Managed(u8).init(a);- defer scratch.deinit();- inlineSpans(&scratch, s, "", "") catch return s.len;- return theme_mod.visibleLen(scratch.items);-}--fn emitRule(out: *std.array_list.Managed(u8), muted: []const u8, widths: []const usize, left: []const u8, mid: []const u8, right: []const u8) !void {- try out.appendSlice(muted);- try out.appendSlice(left);- for (widths, 0..) |w, i| {- if (i > 0) try out.appendSlice(mid);- var n: usize = 0;- while (n < w + 2) : (n += 1) try out.appendSlice("─");- }- try out.appendSlice(right);- try out.appendSlice(theme_mod.reset);-}--fn emitTable(- out: *std.array_list.Managed(u8),- a: std.mem.Allocator,- rows: []const []const u8,- accent: []const u8,- muted: []const u8,- text: []const u8,- width: usize,-) !void {- var widths: [max_table_cols]usize = @splat(0);- var ncol: usize = 0;- for (rows, 0..) |row, ri| {- if (ri == 1) continue;- var cells: [max_table_cols][]const u8 = undefined;- const n = splitCells(row, &cells);- if (n > ncol) ncol = n;- var c: usize = 0;- while (c < n) : (c += 1) {- const w = @min(cellWidth(a, cells[c]), @as(usize, 36));- if (w > widths[c]) widths[c] = w;- }- }- if (ncol == 0) return;- const cols = widths[0..ncol];- // Fit the grid into the terminal: every row costs ncol*3+1 border/pad- // columns on top of the content. Shave the widest column until it fits- // (floor 5), then clamp each CELL to its column so an over-long cell can- // never blow the grid — before this, content was emitted unclamped and- // the line-wrapper sheared tables apart at narrow widths.- const chrome_cost = ncol * 3 + 1;- const budget = if (width == 0) 76 else if (width > chrome_cost) width - chrome_cost else ncol * 5;- var total: usize = 0;- for (cols) |w| total += w;- while (total > budget) {- var widest: usize = 0;- for (cols, 0..) |w, ci| {- if (w > cols[widest]) widest = ci;- }- if (cols[widest] <= 5) break;- cols[widest] -= 1;- total -= 1;- }- try emitRule(out, muted, cols, "┌", "┬", "┐");- try out.append('\n');- for (rows, 0..) |row, ri| {- if (ri == 1) {- try emitRule(out, muted, cols, "├", "┼", "┤");- try out.append('\n');- continue;- }- var cells: [max_table_cols][]const u8 = undefined;- const n = splitCells(row, &cells);- var c: usize = 0;- while (c < ncol) : (c += 1) {- try out.appendSlice(muted);- try out.appendSlice("│");- try out.appendSlice(theme_mod.reset);- try out.append(' ');- const cell = if (c < n) cells[c] else "";- const want = cols[c];- var scratch = std.array_list.Managed(u8).init(a);- defer scratch.deinit();- if (ri == 0) {- try scratch.appendSlice(theme_mod.bold);- try scratch.appendSlice(accent);- try inlineSpans(&scratch, cell, accent, accent);- } else {- try scratch.appendSlice(text);- try inlineSpans(&scratch, cell, accent, text);- }- const vis = cellWidth(a, cell);- if (vis > want) {- try out.appendSlice(theme_mod.takeCols(scratch.items, if (want > 1) want - 1 else want));- if (want > 1) try out.appendSlice("\u{2026}");- } else {- try out.appendSlice(scratch.items);- var p: usize = 0;- while (p < want - vis) : (p += 1) try out.append(' ');- }- try out.appendSlice(theme_mod.reset);- try out.append(' ');- }- try out.appendSlice(muted);- try out.appendSlice("│");- try out.appendSlice(theme_mod.reset);- try out.append('\n');- }- try emitRule(out, muted, cols, "└", "┴", "┘");-}-fn isBreak(c: u8) bool {return c == ' ' or c == '\t' or c == '\n' or c == '(' or c == '[';}diff --git a/TUI/mdtable.zig b/TUI/mdtable.zignew file mode 100644index 00000000..72c7f7a4--- /dev/null+++ b/TUI/mdtable.zig@@ -0,0 +1,165 @@+//! The pipe-table half of the pager's markdown: detection, column fitting and+//! the box-drawing grid. Split out of markdown.zig to keep both files inside+//! the 600-line ceiling; the cell CONTENT still goes through markdown's own+//! inline renderer, so a table cell and a paragraph style identically.++const std = @import("std");+const markdown = @import("markdown.zig");+const theme_mod = @import("theme.zig");++const inlineSpans = markdown.inlineSpans;++pub const max_table_cols: usize = 8;++pub fn isTableRow(line: []const u8) bool {+ const t = std.mem.trim(u8, line, " \t");+ if (t.len < 3 or t[0] != '|') return false;+ return std.mem.indexOfScalar(u8, t[1..], '|') != null;+}++pub fn isSepRow(line: []const u8) bool {+ if (!isTableRow(line)) return false;+ var buf: [max_table_cols][]const u8 = undefined;+ const n = splitCells(line, &buf);+ if (n == 0) return false;+ for (buf[0..n]) |c| {+ if (c.len == 0) return false;+ for (c) |ch| {+ if (ch != '-' and ch != ':' and ch != ' ') return false;+ }+ }+ return true;+}++pub fn tableLen(lines: []const []const u8) ?usize {+ if (lines.len < 2 or !isTableRow(lines[0]) or !isSepRow(lines[1])) return null;+ var n: usize = 2;+ while (n < lines.len and isTableRow(lines[n]) and !isSepRow(lines[n])) n += 1;+ return n;+}++pub fn splitCells(line: []const u8, out: [][]const u8) usize {+ var t = std.mem.trim(u8, line, " \t");+ if (t.len > 0 and t[0] == '|') t = t[1..];+ if (t.len > 0 and t[t.len - 1] == '|') t = t[0 .. t.len - 1];+ var n: usize = 0;+ var it = std.mem.splitScalar(u8, t, '|');+ while (it.next()) |raw| {+ if (n >= out.len) break;+ out[n] = std.mem.trim(u8, raw, " \t");+ n += 1;+ }+ return n;+}++/// Visible width of a cell AS RENDERED: run it through inlineSpans and count.+/// Guessing at markers went wrong on every unmatched ` or ** (the render kept+/// them, the measure dropped them, the pad math sheared the grid).+pub fn cellWidth(a: std.mem.Allocator, s: []const u8) usize {+ var scratch = std.array_list.Managed(u8).init(a);+ defer scratch.deinit();+ inlineSpans(&scratch, s, "", "") catch return s.len;+ return theme_mod.visibleLen(scratch.items);+}++pub fn emitRule(out: *std.array_list.Managed(u8), muted: []const u8, widths: []const usize, left: []const u8, mid: []const u8, right: []const u8) !void {+ try out.appendSlice(muted);+ try out.appendSlice(left);+ for (widths, 0..) |w, i| {+ if (i > 0) try out.appendSlice(mid);+ var n: usize = 0;+ while (n < w + 2) : (n += 1) try out.appendSlice("─");+ }+ try out.appendSlice(right);+ try out.appendSlice(theme_mod.reset);+}++pub fn emitTable(+ out: *std.array_list.Managed(u8),+ a: std.mem.Allocator,+ rows: []const []const u8,+ accent: []const u8,+ muted: []const u8,+ text: []const u8,+ width: usize,+) !void {+ var widths: [max_table_cols]usize = @splat(0);+ var ncol: usize = 0;+ for (rows, 0..) |row, ri| {+ if (ri == 1) continue;+ var cells: [max_table_cols][]const u8 = undefined;+ const n = splitCells(row, &cells);+ if (n > ncol) ncol = n;+ var c: usize = 0;+ while (c < n) : (c += 1) {+ const w = @min(cellWidth(a, cells[c]), @as(usize, 36));+ if (w > widths[c]) widths[c] = w;+ }+ }+ if (ncol == 0) return;+ const cols = widths[0..ncol];+ // Fit the grid into the terminal: every row costs ncol*3+1 border/pad+ // columns on top of the content. Shave the widest column until it fits+ // (floor 5), then clamp each CELL to its column so an over-long cell can+ // never blow the grid — before this, content was emitted unclamped and+ // the line-wrapper sheared tables apart at narrow widths.+ const chrome_cost = ncol * 3 + 1;+ const budget = if (width == 0) 76 else if (width > chrome_cost) width - chrome_cost else ncol * 5;+ var total: usize = 0;+ for (cols) |w| total += w;+ while (total > budget) {+ var widest: usize = 0;+ for (cols, 0..) |w, ci| {+ if (w > cols[widest]) widest = ci;+ }+ if (cols[widest] <= 5) break;+ cols[widest] -= 1;+ total -= 1;+ }+ try emitRule(out, muted, cols, "┌", "┬", "┐");+ try out.append('\n');+ for (rows, 0..) |row, ri| {+ if (ri == 1) {+ try emitRule(out, muted, cols, "├", "┼", "┤");+ try out.append('\n');+ continue;+ }+ var cells: [max_table_cols][]const u8 = undefined;+ const n = splitCells(row, &cells);+ var c: usize = 0;+ while (c < ncol) : (c += 1) {+ try out.appendSlice(muted);+ try out.appendSlice("│");+ try out.appendSlice(theme_mod.reset);+ try out.append(' ');+ const cell = if (c < n) cells[c] else "";+ const want = cols[c];+ var scratch = std.array_list.Managed(u8).init(a);+ defer scratch.deinit();+ if (ri == 0) {+ try scratch.appendSlice(theme_mod.bold);+ try scratch.appendSlice(accent);+ try inlineSpans(&scratch, cell, accent, accent);+ } else {+ try scratch.appendSlice(text);+ try inlineSpans(&scratch, cell, accent, text);+ }+ const vis = cellWidth(a, cell);+ if (vis > want) {+ try out.appendSlice(theme_mod.takeCols(scratch.items, if (want > 1) want - 1 else want));+ if (want > 1) try out.appendSlice("\u{2026}");+ } else {+ try out.appendSlice(scratch.items);+ var p: usize = 0;+ while (p < want - vis) : (p += 1) try out.append(' ');+ }+ try out.appendSlice(theme_mod.reset);+ try out.append(' ');+ }+ try out.appendSlice(muted);+ try out.appendSlice("│");+ try out.appendSlice(theme_mod.reset);+ try out.append('\n');+ }+ try emitRule(out, muted, cols, "└", "┴", "┘");+}diff --git a/TUI/render.zig b/TUI/render.zigindex 54322b61..3f658a23 100644--- a/TUI/render.zig+++ b/TUI/render.zig@@ -339,7 +339,7 @@ test "welcome frame has chrome, prompt, and no offline stub" {try std.testing.expect(std.mem.indexOf(u8, frame, "click") == null);}-test "click on a painted Called row expands the tools" {+test "click on a painted fold header expands the tools" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();@@ -352,7 +352,7 @@ test "click on a painted Called row expands the tools" {var hit: ?usize = null;var it = std.mem.splitScalar(u8, frame, '\n');while (it.next()) |ln| : (row += 1) {- if (std.mem.indexOf(u8, ln, "Called") != null) {+ if (std.mem.indexOf(u8, ln, "Ran bash") != null) {hit = row;break;}@@ -379,7 +379,7 @@ test "image overlay keeps the conversation and paints the Grok card" {try std.testing.expect(std.mem.indexOf(u8, frame, "y copy path") != null);}-test "visible dump of a fixture frame shows chips, Called, composer, no CSI" {+test "visible dump of a fixture frame shows chips, the fold header, composer, no CSI" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();@@ -392,7 +392,7 @@ test "visible dump of a fixture frame shows chips, Called, composer, no CSI" {const vis = try dump_mod.visible(std.testing.allocator, frame);defer std.testing.allocator.free(vis);try std.testing.expect(std.mem.indexOf(u8, vis, "[Image #1]") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "Called") != null);+ try std.testing.expect(std.mem.indexOf(u8, vis, "Ran bash") != null);try std.testing.expect(std.mem.indexOf(u8, vis, "╭") != null);try std.testing.expect(std.mem.indexOf(u8, vis, "›") != null);try std.testing.expect(std.mem.indexOf(u8, vis, "\x1b") == null);diff --git a/TUI/root.zig b/TUI/root.zigindex 4a167a43..8aef266c 100644--- a/TUI/root.zig+++ b/TUI/root.zig@@ -60,6 +60,8 @@ test {_ = @import("bgop.zig");_ = @import("welcome.zig");_ = @import("glyphs.zig");+ _ = @import("foldhdr.zig");+ _ = @import("mdtable.zig");_ = @import("scrollback.zig");_ = @import("layout_cache.zig");_ = @import("selection.zig");diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigindex 015a190b..013125ce 100644--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@ -6,6 +6,7 @@ const std = @import("std");const app = @import("app.zig");const diff_mod = @import("diff.zig");+const foldhdr = @import("foldhdr.zig");const glyphs = @import("glyphs.zig");const theme_mod = @import("theme.zig");const Model = app.Model;@@ -19,23 +20,9 @@ pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u6const e = self.history.items[i];if (e.kind == .tool) {const run = self.toolRun(i);- const collapsed = self.history.items[run.start].folded;- if (collapsed) {- if (!first) try out.append('\n');- first = false;- const selected = self.focus == .scrollback and self.selected >= run.start and self.selected < run.end;- try out.appendSlice(try summary(self, a, run.start, run.end, selected));- i = run.end;- continue;- }- var t = run.start;- while (t < run.end) {- if (!first) try out.append('\n');- first = false;- const selected = self.focus == .scrollback and t == self.selected;- try out.appendSlice(try toolVisual(self, a, t, run.end, width, now_ms, selected));- t = nextTool(self, t, run.end);- }+ if (!first) try out.append('\n');+ first = false;+ try out.appendSlice(try runVisual(self, a, run.start, run.end, width, now_ms));i = run.end;continue;}@@ -71,19 +58,7 @@ pub fn indexAtVisual(self: *const Model, visual_row: usize, width: usize) ?usizewhile (i < self.history.items.len) {if (self.history.items[i].kind == .tool) {const run = self.toolRun(i);- const collapsed = self.history.items[run.start].folded;- var lines: usize = 0;- if (collapsed) {- const s = summary(self, a, run.start, run.end, false) catch "";- lines = lineCount(s);- } else {- var t = run.start;- while (t < run.end) {- const s = toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "";- lines += lineCount(s);- t = nextTool(self, t, run.end);- }- }+ const lines = lineCount(runVisual(self, a, run.start, run.end, width, self.now_ms) catch "");if (visual_row >= v and visual_row < v + lines) return run.start;v += lines;i = run.end;@@ -118,16 +93,7 @@ pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {if (self.history.items[i].kind == .tool) {const run = self.toolRun(i);if (idx >= run.start and idx < run.end) return v;- const collapsed = self.history.items[run.start].folded;- if (collapsed) {- v += lineCount(summary(self, a, run.start, run.end, false) catch "");- } else {- var t = run.start;- while (t < run.end) {- v += lineCount(toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "");- t = nextTool(self, t, run.end);- }- }+ v += lineCount(runVisual(self, a, run.start, run.end, width, self.now_ms) catch "");i = run.end;continue;}@@ -153,15 +119,7 @@ pub fn stickyUserAbove(self: *const Model, top_line: usize, width: usize) ?[]conconst e = self.history.items[i];if (e.kind == .tool) {const run = self.toolRun(i);- if (self.history.items[run.start].folded) {- v += lineCount(summary(self, a, run.start, run.end, false) catch "");- } else {- var t = run.start;- while (t < run.end) {- v += lineCount(toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "");- t = nextTool(self, t, run.end);- }- }+ v += lineCount(runVisual(self, a, run.start, run.end, width, self.now_ms) catch "");i = run.end;continue;}@@ -180,62 +138,73 @@ pub fn lineCount(s: []const u8) usize {/// Is this a search-shaped tool? Answered from the tool NAME (#551). It used/// to be answered from the whole rendered line, so `bash` running a command/// that merely mentioned "find" counted as a search.-fn isSearch(name: []const u8) bool {- return containsIgnoreCase(name, "search") or containsIgnoreCase(name, "grep") or containsIgnoreCase(name, "find");-}--fn isMcp(name: []const u8) bool {- return std.mem.startsWith(u8, name, "mcp__");-}--/// What a row's classification reads. A field-backed row answers with the-/// engine's tool name; a legacy row restored from an old session has only its-/// rendered text, and keeps the looser substring behavior it was written with.-fn classifyOn(e: app.Entry) []const u8 {- if (e.tool) |t| return t.name;- return e.text;-}--fn rowIsMcp(e: app.Entry) bool {- if (e.tool) |t| return isMcp(t.name);- return std.mem.indexOf(u8, e.text, "mcp__") != null or containsIgnoreCase(e.text, "mcp");-}--fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {- if (needle.len > hay.len) return false;- var i: usize = 0;- while (i + needle.len <= hay.len) : (i += 1) {- if (std.ascii.eqlIgnoreCase(hay[i .. i + needle.len], needle)) return true;+/// One whole tool run as the transcript shows it: grok's disclosure header,+/// and — when the run is open — the cards under it, hanging off a light+/// gutter. Every reader of the transcript's row math goes through here, so+/// the header can never be counted by one and missed by another.+pub fn runVisual(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, width: usize, now_ms: u64) ![]const u8 {+ if (start >= end) return "";+ const open = !self.history.items[start].folded;+ const in_run = self.focus == .scrollback and self.selected >= start and self.selected < end;+ var out = std.array_list.Managed(u8).init(a);+ try out.appendSlice(try header(self, a, start, end, width, now_ms, in_run));+ if (!open) return out.items;+ var t = start;+ while (t < end) {+ try out.append('\n');+ const one = self.focus == .scrollback and t == self.selected;+ const card = try toolVisual(self, a, t, end, width -| foldhdr.gutter_cols, now_ms, one);+ try out.appendSlice(try indent(a, self.theme(), card));+ t = nextTool(self, t, end);}- return false;+ return out.items;}-pub fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, selected: bool) ![]const u8 {+/// The run's own row: `[selection mark][chevron] [verb phrase]`. Always ONE+/// line — a menu entry's rule, and what keeps the click math a straight+/// screen-row → run mapping.+pub fn header(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, width: usize, now_ms: u64, selected: bool) ![]const u8 {const th = self.theme();- var searches: usize = 0;- var calls: usize = 0;- var mcp_n: usize = 0;- var i = start;- while (i < end) : (i += 1) {- const e = self.history.items[i];- if (rowIsMcp(e)) mcp_n += 1;- if (isSearch(classifyOn(e))) searches += 1 else calls += 1;- }+ const r = foldhdr.scan(self, start, end);+ if (r.calls == 0) return "";+ const open = !self.history.items[start].folded;const sel = glyphs.frame(&glyphs.row_mark, @intFromBool(!selected));// No live bar here: liveness belongs to the pending row alone. A bar on- // every summary made the whole transcript pulse and shift while thinking.+ // every header made the whole transcript pulse and shift while thinking —+ // the settle flash below is a single bounded change, not a tick.+ const plain = theme_mod.takeCols(+ try std.fmt.allocPrint(a, "{s}{s} {s}", .{ sel, foldhdr.chevron(open), try foldhdr.phrase(a, r) }),+ width,+ );+ const fg = if (selected or foldhdr.flashing(r, now_ms)) th.accent else th.muted;+ if (!foldhdr.flashing(r, now_ms)) return theme_mod.paint(a, fg, plain);+ // The settle tint is a FIELD, not a ribbon: padded out to the full width+ // and closed back onto the canvas bg, so the row under it inherits+ // nothing (the same rule diff.zig's bands follow).var out = std.array_list.Managed(u8).init(a);- if (calls > 0) {- const label = if (mcp_n == calls + searches)- try std.fmt.allocPrint(a, "{s}{s} Called {d} MCP tool{s}", .{ sel, glyphs.tool, calls, if (calls == 1) "" else "s" })- else- try std.fmt.allocPrint(a, "{s}{s} Called {d} tool{s}", .{ sel, glyphs.tool, calls, if (calls == 1) "" else "s" });- try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));- }- if (searches > 0) {- if (out.items.len > 0) try out.append('\n');- const label = try std.fmt.allocPrint(a, "{s}{s} Searched {d} MCP tool{s}", .{ sel, glyphs.tool, searches, if (searches == 1) "" else "s" });- try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));+ try out.appendSlice(foldhdr.flashBg(th));+ try out.appendSlice(fg);+ try out.appendSlice(plain);+ var pad = width -| theme_mod.visibleLen(plain);+ while (pad > 0) : (pad -= 1) try out.append(' ');+ try out.appendSlice(th.bg);+ try out.appendSlice(theme_mod.reset);+ return out.items;+}++/// Hang a card off the open run's gutter — every line of it, so a wrapped+/// title and a banded diff stay inside the same rail.+fn indent(a: std.mem.Allocator, th: theme_mod.Theme, card: []const u8) ![]const u8 {+ var out = std.array_list.Managed(u8).init(a);+ var it = std.mem.splitScalar(u8, card, '\n');+ var first = true;+ while (it.next()) |ln| {+ if (!first) try out.append('\n');+ first = false;+ try out.appendSlice(th.muted);+ try out.appendSlice(foldhdr.gutter);+ try out.appendSlice(theme_mod.reset);+ try out.appendSlice(ln);}return out.items;}@@ -294,37 +263,13 @@ fn userNo(self: *const Model, idx: usize) u32 {return if (n == 0) 1 else n;}-/// A tool row's start/done phase, straight off its typed payload. A legacy row-/// (tool == null) is neither: it has no phase to read, so it renders alone.-fn isStartTool(e: app.Entry) bool {- const t = e.tool orelse return false;- return !t.done;-}--fn isDoneTool(e: app.Entry) bool {- const t = e.tool orelse return false;- return t.done;-}--pub fn nextTool(self: *const Model, t: usize, end: usize) usize {- if (t + 1 < end and isStartTool(self.history.items[t]) and isDoneTool(self.history.items[t + 1]))- return t + 2;- return t + 1;-}--/// The display form of a tool NAME: the harness's internal names shortened,-/// and an MCP tool shown by its leaf. Operates on the name alone — the old-/// prettyTool did this by stripping a status glyph off a rendered line first.-fn displayName(name: []const u8) []const u8 {- if (std.mem.eql(u8, name, "read_file")) return "read";- if (std.mem.eql(u8, name, "write_file")) return "write";- if (std.mem.startsWith(u8, name, "mcp__")) {- if (std.mem.lastIndexOf(u8, name, "__")) |u| {- if (u + 2 < name.len) return name[u + 2 ..];- }- }- return name;-}+// The run-walk primitives live in foldhdr.zig, which needs them to COUNT a+// run before this file can draw one. Re-exported here so every caller (and+// every test written against them) keeps one name for one rule.+const isStartTool = foldhdr.isStartTool;+const isDoneTool = foldhdr.isDoneTool;+pub const nextTool = foldhdr.nextTool;+const displayName = foldhdr.displayName;/// The head of a tool row: `[status mark] name [argument preview]`, composed/// from FIELDS. On a paired card the name and its arguments come from the call@@ -446,6 +391,10 @@ test "a live turn never pulses or shifts historical rows" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();+ // Pushed against a clock well past the settle window, so the fold header's+ // one-second flash is already over and the only motion under test is the+ // pending blink. The flash itself is exercised below.+ m.now_ms = 100_000;try m.push(.user, "hi");try m.pushTool(.{ .name = "bash" });try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });@@ -463,12 +412,12 @@ test "a live turn never pulses or shifts historical rows" {defer m.pending = null;var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();- const t0 = try render(&m, arena.allocator(), 80, 0);- const t140 = try render(&m, arena.allocator(), 80, 140);+ const t0 = try render(&m, arena.allocator(), 80, 200_000);+ const t140 = try render(&m, arena.allocator(), 80, 200_140);var it = std.mem.splitScalar(u8, t0, '\n');var saw_summary = false;while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, "Called") != null) {+ if (std.mem.indexOf(u8, ln, "Ran bash") != null) {saw_summary = true;try std.testing.expect(std.mem.indexOf(u8, ln, glyphs.thinking[0]) == null);}@@ -479,7 +428,7 @@ test "a live turn never pulses or shifts historical rows" {// change; every historical row stays byte-identical. (Full staticness// went the other way into a paint freeze; full pulsing was the original// bug. The contract is: motion exists, and it is confined.)- const t500 = try render(&m, arena.allocator(), 80, 500);+ const t500 = try render(&m, arena.allocator(), 80, 200_500);var it0 = std.mem.splitScalar(u8, t0, '\n');var it5 = std.mem.splitScalar(u8, t500, '\n');var changed: usize = 0;@@ -493,6 +442,52 @@ test "a live turn never pulses or shifts historical rows" {try std.testing.expectEqual(@as(usize, 1), changed);}+test "the settle flash is the ONE extra moving row, and it stops on its own" {+ // A deliberate widening of the pin above. A tool run that has just settled+ // owns a second moving row for one second — its header, tinted — and that+ // is the whole of the allowance: the flash is a single on→off transition+ // on a single row, not a tick, so the transcript still cannot pulse.+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ m.now_ms = 10_000;+ try m.push(.user, "hi");+ try m.pushTool(.{ .name = "bash" });+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const lit = try render(&m, arena.allocator(), 80, 10_000);+ const mid = try render(&m, arena.allocator(), 80, 10_900);+ const off = try render(&m, arena.allocator(), 80, 11_000);+ const later = try render(&m, arena.allocator(), 80, 60_000);+ // Nothing moves WITHIN the window...+ try std.testing.expectEqualStrings(lit, mid);+ // ...the tint is real while it is up...+ try std.testing.expect(std.mem.indexOf(u8, lit, foldhdr.flashBg(m.theme())) != null);+ try std.testing.expect(std.mem.indexOf(u8, off, foldhdr.flashBg(m.theme())) == null);+ // ...it closes back onto the canvas so the row below inherits nothing...+ var it = std.mem.splitScalar(u8, lit, '\n');+ while (it.next()) |ln| {+ if (std.mem.indexOf(u8, ln, foldhdr.flashBg(m.theme())) == null) continue;+ try std.testing.expect(std.mem.endsWith(u8, ln, theme_mod.reset));+ try std.testing.expect(std.mem.indexOf(u8, ln, m.theme().bg) != null);+ }+ // ...and exactly ONE row differs across the on→off edge.+ var a0 = std.mem.splitScalar(u8, lit, '\n');+ var a1 = std.mem.splitScalar(u8, off, '\n');+ var changed: usize = 0;+ while (a0.next()) |x| {+ const y = a1.next() orelse "";+ if (!std.mem.eql(u8, x, y)) {+ changed += 1;+ try std.testing.expect(std.mem.indexOf(u8, y, "Ran bash") != null);+ }+ }+ try std.testing.expectEqual(@as(usize, 1), changed);+ // After that the row is done moving for good.+ try std.testing.expectEqualStrings(off, later);+}+test "displayName shortens an mcp tool to its leaf, reading the NAME" {// The old prettyTool took a rendered LINE and stripped a status glyph off// it first; this takes the engine's tool name, which is all it ever needed.@@ -506,7 +501,7 @@ test {_ = @import("scrollback_tests.zig");}-test "collapsed tool run is one Called summary" {+test "a collapsed tool run is one verb header, and it flips open" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();@@ -518,12 +513,18 @@ test "collapsed tool run is one Called summary" {defer arena.deinit();const text = try render(&m, arena.allocator(), 80, 0);try std.testing.expect(std.mem.indexOf(u8, text, "#1") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "Called 2") != null);+ // One logical call — the announce and its outcome — read in past tense,+ // behind a closed chevron.+ try std.testing.expect(std.mem.indexOf(u8, text, "Ran bash") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, glyphs.chev_closed ++ " Ran bash") != null);try std.testing.expect(std.mem.indexOf(u8, text, "⚙ bash") == null);m.toggleToolGroup(1);const open = try render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, open, "bash") != null);- try std.testing.expect(std.mem.indexOf(u8, open, "Called 2") == null);+ // Open: the same header, chevron flipped, cards under it on the gutter.+ try std.testing.expect(std.mem.indexOf(u8, open, glyphs.chev_open ++ " Ran bash") != null);+ try std.testing.expect(std.mem.indexOf(u8, open, glyphs.chev_closed ++ " Ran bash") == null);+ try std.testing.expect(std.mem.indexOf(u8, open, foldhdr.gutter) != null);+ try std.testing.expect(std.mem.indexOf(u8, open, "Called") == null);}test "long assistant lines wrap to the terminal width" {@@ -540,7 +541,7 @@ test "long assistant lines wrap to the terminal width" {}}-test "Called summary visual row maps back to the tool group" {+test "the header's visual row maps back to the tool group" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();@@ -554,7 +555,7 @@ test "Called summary visual row maps back to the tool group" {var hit: ?usize = null;var it = std.mem.splitScalar(u8, text, '\n');while (it.next()) |ln| : (vis += 1) {- if (std.mem.indexOf(u8, ln, "Called") != null) {+ if (std.mem.indexOf(u8, ln, "Ran bash") != null) {hit = vis;break;}@@ -563,7 +564,7 @@ test "Called summary visual row maps back to the tool group" {try std.testing.expectEqual(@as(usize, 1), indexAtVisual(&m, hit.?, 80).?);}-test "collapsed search run is one Searched summary" {+test "collapsed search run reads as a search, in past tense" {var m: Model = undefined;m.setup(std.testing.allocator);defer m.deinit();@@ -572,7 +573,7 @@ test "collapsed search run is one Searched summary" {var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();const text = try render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, text, "Searched 2") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "Searched 1 pattern") != null);try std.testing.expect(std.mem.indexOf(u8, text, "⚙ grep") == null);m.toggleToolGroup(0);const open = try render(&m, arena.allocator(), 80, 0);diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zigindex 3dd4cd45..4351ecec 100644--- a/TUI/scrollback_tests.zig+++ b/TUI/scrollback_tests.zig@@ -79,7 +79,7 @@ test "classification reads the tool name, not the whole row (#551)" {var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();const text = try scrollback.render(&m, arena.allocator(), 100, 0);- try std.testing.expect(std.mem.indexOf(u8, text, "Called 2") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "Ran bash") != null);try std.testing.expect(std.mem.indexOf(u8, text, "Searched") == null);// And the argument survives the " | " that used to truncate the title.m.toggleToolGroup(0);@@ -96,7 +96,9 @@ test "an mcp run summarises as MCP tools, off the name prefix" {var arena = std.heap.ArenaAllocator.init(std.testing.allocator);defer arena.deinit();const text = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, text, "Called 2 MCP tools") != null);+ // One logical call, and the MCP wording survives the verb map: an MCP+ // leaf with no family of its own has no better name to offer.+ try std.testing.expect(std.mem.indexOf(u8, text, "Called 1 MCP tool") != null);}test "an assistant line that starts with a status glyph is NOT a tool row (#551)" {diff --git a/TUI/sim.zig b/TUI/sim.zigindex 6e69a389..664e2602 100644--- a/TUI/sim.zig+++ b/TUI/sim.zig@@ -221,7 +221,7 @@ test "typeText lands in the composer dump" {try std.testing.expect(std.mem.indexOf(u8, vis, "›") != null);}-test "clickText on Called expands the folded tools" {+test "clickText on the verb header expands the folded tools" {var term: Term = undefined;term.init(std.testing.allocator, 80, 24);defer term.deinit();@@ -230,12 +230,15 @@ test "clickText on Called expands the folded tools" {try term.model.pushTool(.{ .name = "bash", .detail = "ok", .done = true });const before = try term.screen();defer std.testing.allocator.free(before);- try std.testing.expect(std.mem.indexOf(u8, before, "Called") != null);- try std.testing.expect(try term.clickText("Called"));+ // Closed: the chevron points right and the phrase is past tense.+ try std.testing.expect(std.mem.indexOf(u8, before, "› Ran bash") != null);+ try std.testing.expect(try term.clickText("Ran bash"));try std.testing.expect(!term.model.history.items[1].folded);const after = try term.screen();defer std.testing.allocator.free(after);- try std.testing.expect(std.mem.indexOf(u8, after, "Called") == null);+ // Open: the SAME header, chevron flipped down — it does not vanish.+ try std.testing.expect(std.mem.indexOf(u8, after, "⌄ Ran bash") != null);+ try std.testing.expect(std.mem.indexOf(u8, after, "› Ran bash") == null);}test "feed Ghostty SGR click matches clickAt" {@@ -245,7 +248,7 @@ test "feed Ghostty SGR click matches clickAt" {try term.model.push(.assistant, "working");try term.model.pushTool(.{ .name = "bash" });try term.model.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- const hit = try term.find("Called") orelse return error.NoCalled;+ const hit = try term.find("Ran bash") orelse return error.NoHeader;var buf: [40]u8 = undefined;const seq = try std.fmt.bufPrint(&buf, "\x1b[<0;{d};{d}M", .{ hit.x, hit.y });_ = term.feed(seq);diff --git a/TUI/turn.zig b/TUI/turn.zigindex 4729771d..107abc12 100644--- a/TUI/turn.zig+++ b/TUI/turn.zig@@ -421,7 +421,9 @@ test "a live tool row is visible mid-turn, straight off the event queue" {defer arena_state.deinit();drainEvents(&m);const harvested = try scrollback.render(&m, arena_state.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, harvested, "Called") != null);+ // Mid-turn: the call is announced and has not come back, so the header+ // reads present-progressive.+ try std.testing.expect(std.mem.indexOf(u8, harvested, "Running bash\u{2026}") != null);Hold.release.store(true, .release);spins = 0;diff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 85ce358a..68316b53 100644--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -293,6 +293,14 @@ if wanted tuiguard; thenif python3 scripts/test-tui-screenstate.py zig-out/bin/graff; then :; elserecord_fail tuiguardfi+ # A tool run's fold header reads like grok-build's: present-progressive+ # while the call is in flight, past tense on settle, tinted for a second.+ # Drives a real `sleep` tool loop against the codex mock and reads the+ # header row's TEXT and its cell BACKGROUNDS off a virtual screen. Both+ # halves fail on their own when either is removed (verified).+ if python3 scripts/test-tui-fold-headers.py zig-out/bin/graff; then :; else+ record_fail tuiguard+ fi# Streaming markdown: the answer arrives as 1-3 codepoint deltas whose# boundaries land mid-escape, mid-fence and mid-marker. Both the live tail# and the settled row must be free of the model's own CR/SGR bytes.diff --git a/scripts/test-tui-fold-headers.py b/scripts/test-tui-fold-headers.pynew file mode 100644index 00000000..02b9118c--- /dev/null+++ b/scripts/test-tui-fold-headers.py@@ -0,0 +1,269 @@+#!/usr/bin/env python3+"""Fold headers read like grok-build's: a verb, a count, and a tense.++Drives a REAL tool loop against the codex mock (no network, no model) on a+virtual screen (scripts/ptyharness.py), and reads the header row back at three+moments the user actually experiences:++ 1. mid-call — the run is announced and has not come back, so the header is+ present-progressive with an ellipsis: "Running bash…"+ 2. on settle — the last outcome lands and the header flips to past tense+ ("Ran bash") wearing the accent tint for about a second. The+ tint is read off CELL BACKGROUNDS, which is the one thing a+ raw-byte grep cannot do honestly.+ 3. after ~1s — the tint is gone and the row stops moving for good.++Then it clicks the header twice: open (chevron flips down, the card hangs off+the gutter) and shut again. The click path is the one #519/#551 pinned, so a+header that changed shape must not have moved the row→run mapping.++The tool is a `sleep`, so step 1 is a real window and not a race: with the+progressive/past split removed the very first assertion fails.++Usage: python3 scripts/test-tui-fold-headers.py [path/to/graff]+Exit 0 = pass. Skips (exit 0, notice) with no pty support.+"""++from __future__ import annotations++import json+import os+import sys+import tempfile+import time++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))++from codex_ws_mock import CodexMock, RecordedRequest # noqa: E402+from ptyharness import PtyHarness, PtyTimeout # noqa: E402++BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")+ROWS, COLS = 34, 110++# Long enough that the live header is a window, short enough that the probe+# stays quick. The turn's own timeout is far above this.+SLEEP_S = 3+FINAL = "FOLDHDR_OK"++CHEV_CLOSED = "›"+CHEV_OPEN = "⌄"+GUTTER = "│"+ELLIPSIS = "…"+++def message_item(text: str, item_id: str) -> dict:+ return {+ "type": "message",+ "id": item_id,+ "status": "completed",+ "role": "assistant",+ "content": [{"type": "output_text", "text": text, "annotations": []}],+ }+++def response_events(item: dict, response_id: str) -> list[dict]:+ return [+ {"type": "response.output_item.done", "item": item},+ {+ "type": "response.completed",+ "response": {+ "id": response_id,+ "usage": {+ "input_tokens": 100,+ "input_tokens_details": {"cached_tokens": 0},+ "output_tokens": 10,+ "total_tokens": 110,+ },+ },+ },+ ]+++def events(request: RecordedRequest) -> list[dict]:+ if request.ordinal == 1:+ return response_events(+ {+ "type": "function_call",+ "id": "fc_fold_bash",+ "call_id": "call_fold_bash",+ "name": "bash",+ "arguments": json.dumps({"command": f"sleep {SLEEP_S}; echo slept"}),+ "status": "completed",+ },+ "resp_fold_bash",+ )+ return response_events(message_item(FINAL, "msg_fold_done"), "resp_fold_done")+++def workspace(tmp: str, port: int):+ codex_home = os.path.join(tmp, "codex-home")+ os.makedirs(codex_home)+ with open(os.path.join(codex_home, "auth.json"), "w", encoding="utf-8") as fh:+ json.dump({"tokens": {"access_token": "fold-header-mock", "account_id": "acct-fold"}}, fh)+ harness = os.path.join(tmp, ".harness")+ os.makedirs(harness)+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:+ json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)+ empty_mcp = os.path.join(tmp, "empty-mcp.json")+ with open(empty_mcp, "w", encoding="utf-8") as fh:+ fh.write('{"mcpServers": {}}')+ env = {+ "HOME": tmp,+ "CODEX_HOME": codex_home,+ "GRAFF_CODEX_URL": f"http://127.0.0.1:{port}/backend-api/codex/responses",+ "GRAFF_CODEX_WS": "off",+ "GRAFF_FLEET": "off",+ "GRAFF_NO_TELEMETRY": "1",+ "GRAFF_MCP_CONFIG": empty_mcp,+ "GRAFF_LEARN_AUTO": "off",+ }+ for name in list(os.environ):+ if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR") and name not in env:+ env[name] = None+ return env+++def spawn_env(env):+ """PtyHarness merges into os.environ, so a None means 'unset'."""+ clean = {k: v for k, v in env.items() if v is not None}+ for k, v in env.items():+ if v is None:+ os.environ.pop(k, None)+ return clean+++def header_row(pty, chevron=None):+ """Index of the fold header row, by chevron state. None = either."""+ hits = []+ for y, ln in enumerate(pty.screen_lines()):+ if "bash" not in ln:+ continue+ if chevron is None:+ if f"{CHEV_CLOSED} R" in ln or f"{CHEV_OPEN} R" in ln:+ hits.append(y)+ elif f"{chevron} R" in ln:+ hits.append(y)+ return hits+++def row_bgs(pty, y):+ return {pty.cell(x, y).bg for x in range(pty.cols)}+++def click(pty, y):+ """SGR press+release on the header's text column, 1-based."""+ pty.inject_keys(f"\x1b[<0;6;{y + 1}M".encode())+ pty.pump(0.25)+ pty.inject_keys(f"\x1b[<0;6;{y + 1}m".encode())+ pty.pump(0.8)+++def run() -> str | None:+ mock = CodexMock(events_for_request=events)+ port = mock.start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-fold-headers-") as tmp:+ env = spawn_env(workspace(tmp, port))+ argv = [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"]+ with PtyHarness(argv, cols=COLS, rows=ROWS, cwd=tmp, env=env) as pty:+ if not pty.wait_for_boot():+ return "the TUI never took the alt screen"+ pty.inject_keys(b"run the sleep then report\r")++ # 1. IN FLIGHT: present-progressive, with the count of calls+ # that have been announced so far.+ try:+ pty.wait_for_text(f"Running bash{ELLIPSIS}", timeout=25.0)+ except PtyTimeout as exc:+ return f"the live header never read present-progressive: {exc}"+ live = header_row(pty, CHEV_CLOSED)+ if len(live) != 1:+ return f"expected one live header row, got {live!r}"+ if "Ran bash" in pty.screen_contents():+ return "the header was in past tense while the call was still running"++ # 2. SETTLED: past tense, and tinted for about a second.+ try:+ pty.wait_for_text("Ran bash", timeout=40.0)+ except PtyTimeout as exc:+ return f"the header never flipped to past tense: {exc}"+ settled_at = time.monotonic()+ if f"Running bash{ELLIPSIS}" in pty.screen_contents():+ return "the progressive header outlived the call"+ lit = header_row(pty, CHEV_CLOSED)+ if len(lit) != 1:+ return f"expected one settled header row, got {lit!r}"+ bgs = row_bgs(pty, lit[0])+ # The whole row is one field, so the tint is the only bg on it.+ if len(bgs) != 1:+ return f"the settle tint is a ribbon, not a field: {bgs!r}"+ tint = next(iter(bgs))+ canvas = row_bgs(pty, lit[0] - 1) if lit[0] else {None}+ if tint in canvas:+ return f"the settle tint is the canvas bg, so nothing flashed: {tint!r}"++ # 3. AFTER THE WINDOW: the tint is gone and stays gone.+ pty.pump(max(0.0, 1.4 - (time.monotonic() - settled_at)))+ pty.pump(0.6)+ after = header_row(pty, CHEV_CLOSED)+ if len(after) != 1:+ return f"the header moved after the flash: {after!r}"+ if row_bgs(pty, after[0]) == {tint}:+ return "the settle tint never turned itself off"+ if "Ran bash" not in pty.screen_contents():+ return "the settled header did not survive its own flash"++ # 4. The final answer still lands, outside the run.+ try:+ pty.wait_for_text(FINAL, timeout=30.0)+ except PtyTimeout as exc:+ return f"the turn never produced its answer: {exc}"++ # 5. CLICK: the chevron flips and the card hangs off the gutter.+ y = header_row(pty, CHEV_CLOSED)+ if len(y) != 1:+ return f"lost the header before the click: {y!r}"+ click(pty, y[0])+ if header_row(pty, CHEV_CLOSED):+ return "the click did not open the run"+ opened = header_row(pty, CHEV_OPEN)+ if len(opened) != 1:+ return f"the open run lost its header: {opened!r}"+ lines = pty.screen_lines()+ card = [ln for ln in lines[opened[0] + 1 : opened[0] + 4] if GUTTER in ln and "bash" in ln]+ if not card:+ return f"no card on the open run's gutter: {lines[opened[0]:opened[0] + 4]!r}"+ if "Ran bash" not in lines[opened[0]]:+ return f"the open header lost its verb: {lines[opened[0]]!r}"++ # 6. ...and clicking it again folds the run back up.+ click(pty, opened[0])+ if not header_row(pty, CHEV_CLOSED):+ return "the second click did not fold the run back"+ if header_row(pty, CHEV_OPEN):+ return "the run stayed open after being folded"+ pty.quit()+ finally:+ mock.stop()+ return None+++def main() -> int:+ if not os.path.exists(BIN):+ print(f" ! fold headers: no binary at {BIN}, skipping")+ return 0+ try:+ import pty as _pty # noqa: F401+ except Exception:+ print(" ! fold headers: no pty support, skipping")+ return 0+ err = run()+ if err:+ print(f" ✗ fold headers: {err}")+ return 1+ print(" ✓ fold headers: progressive → past tense, settle flash on and off, click opens and folds")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/test-tui-typed-events.py b/scripts/test-tui-typed-events.pyold mode 100755new mode 100644index 5717f9bc..eb712859--- a/scripts/test-tui-typed-events.py+++ b/scripts/test-tui-typed-events.py@@ -209,8 +209,15 @@ def workspace(tmp, port):return env, unset-def summary_rows(rows):- return [i for i, ln in enumerate(rows) if "Called" in ln and "tool" in ln]+CHEV_CLOSED = "›"+CHEV_OPEN = "⌄"+++def summary_rows(rows, chevron=CHEV_CLOSED):+ """Rows carrying a fold HEADER in the given disclosure state. The header+ survives expansion now — only its chevron flips — so the state has to be+ read off the glyph rather than off the header's presence."""+ return [i for i, ln in enumerate(rows) if f"{chevron} Read " in ln]def check_folded(rows):@@ -218,14 +225,19 @@ def check_folded(rows):if "TYPEDEV_OK" not in body:return "the final answer never rendered"# 1. The real tool run folded into exactly ONE summary row, counting the- # two typed rows of one call (invocation + outcome) and nothing else.- # The scraping path counted the answer's "✓ " line as a third row.+ # two typed rows of one call (invocation + outcome) as the ONE logical+ # call they are. The scraping path counted the answer's "✓ " line as a+ # third row; the pre-verb header counted the pair as two.hits = summary_rows(rows)if len(hits) != 1:return f"expected exactly one folded tool summary, got {[rows[i] for i in hits]!r}"summary = rows[hits[0]].strip()- if not re.search(r"Called 2 tools\b", summary):- return f"the summary counted something other than the one real call: {summary!r}"+ # Past tense: the run settled before the answer landed. `read_file` is the+ # read family, so the object is a file, not a bare "tool".+ if not re.search(r"Read 1 file\b", summary):+ return f"the header did not read as a settled single read: {summary!r}"+ if "Called" in summary:+ return f"the run was homogeneous and should not fall back: {summary!r}"# 2. The answer's status-glyph line is on screen exactly once...answers = [ln for ln in rows if GLYPH_LINE in ln]if len(answers) != 1:@@ -245,13 +257,19 @@ def check_expanded(rows):"""The card the fold opens onto is built from FIELDS: the engine's toolname, its argument, and the result preview — none of it recovered bysplitting a rendered line."""- if summary_rows(rows):+ if summary_rows(rows, CHEV_CLOSED):return "the click did not expand the tool group"+ # The header stays put and flips its chevron down; it does not vanish.+ if len(summary_rows(rows, CHEV_OPEN)) != 1:+ return f"the open run lost its header: {rows[:12]!r}"# The head is `◆ <displayName(name)> <compactArg(input)>`: read_file# shortened to "read", the path taken from the call's JSON argument.head = next((i for i, ln in enumerate(rows) if re.search(r"◆\s+read {2}note\.txt\s*$", ln)), None)if head is None:return f"no field-backed card head on screen: {rows[:8]!r}"+ # ...hanging off the open run's gutter.+ if "│" not in rows[head]:+ return f"the card head is not on the open run's gutter: {rows[head]!r}"# The body under it is the outcome's result preview, in the card gutter.if head + 1 >= len(rows) or "│" not in rows[head + 1] or NOTE_BODY not in rows[head + 1]:return f"the card body is not the result preview: {rows[head:head + 2]!r}"