graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Remove embedded TUI and launch the separate client
justrach2fc6fe0aedab
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 5bf5be3d..d0eb6817 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -24,8 +24,8 @@ jobs:- name: Zig source-size guard integrity testsrun: python3 scripts/test-zig-lines.py- - name: Tuiguard pool deadline integrity (#704)- run: python3 scripts/eval/test_tier1_tuiguard.py+ - name: PTY cleanup integrity+ run: python3 scripts/eval/test_pty_cleanup.py- name: Behavioral outcome verifier integrityrun: python3 scripts/eval/test_tier2_outcomes.py@@ -226,11 +226,8 @@ jobs:- name: PTY a follow-up typed mid-reply supersedes it (line REPL)run: python3 scripts/test-pty-steer-mid-reply.py zig-out/bin/graff- - name: TUI a follow-up typed mid-reply joins the running turn- run: python3 scripts/test-tui-steer-mid-reply.py zig-out/bin/graff-- - name: TUI GPT-6 follow-ups steer the running reply (ADR 0222)- run: python3 scripts/test-tui-steer-gpt6.py zig-out/bin/graff+ - name: Line-REPL prompt reflow+ run: python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-repl-prompt-reflow.py zig-out/bin/graff- name: PTY peer-channel delivery smoke test (#469)run: python3 scripts/test-pty-peer-channel.py zig-out/bin/graffdiff --git a/AGENTS.md b/AGENTS.mdindex ea9e87bb..071e7f4c 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -45,42 +45,12 @@ new load-bearing decision, add a record in the same branch.- **The font is not ours.** The terminal emulator owns the typeface — it loads the font, measures the cell grid, and rasterizes glyphs itself; the wire protocol has no sequence for an app to request a font. (xterm's legacy `OSC 50` is unimplemented by modern emulators and would hijack the user's whole terminal — do not emit it.) If a user asks to "change the REPL font," the answer is their terminal's config, e.g. `font-family = Geist Mono` (the site's typeface) in Ghostty — never a code change here.- **HDR/wide-gamut color is not ours either.** Truecolor SGR is 8-bit sRGB per channel — the protocol's ceiling; no sequence expresses Display P3 or EDR headroom, and macOS terminals clip app colors to SDR regardless of the panel. Pick values that look right on both P3 and sRGB displays (as `#059669` does); that's the whole lever.-## Driving the pager (no PTY, no Ghostty window)--Do not spawn `graff tui` or a terminal emulator to inspect or click the pager.-The headless session is `TUI/sim.zig` (`Term`): the same `key.next` → `keys.handle`-→ `render` → `dump.visible` path Ghostty uses on a real TTY.--```zig-var term: @import("sim.zig").Term = undefined;-term.init(alloc, 80, 24);-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| › Ran bash"-_ = try term.clickText("Ran bash"); // click the first matching glyph-_ = try term.hoverText("[Image #1]"); // hover an image chip-const lay = try term.layout(); // overlay / focus / origins / images / pending-```--High-level helpers (`typeText`, `enter`, `clickText`, `hoverText`, `clickAt`,-`hoverAt`) are enough for most work. When you must speak Ghostty's wire:--| input | bytes |-|---|---|-| printable | the UTF-8 itself |-| Enter | `\r` |-| click at (col, row) | `ESC [ < 0 ; COL ; ROW M` (1-based cells) |-| hover | `ESC [ < 35 ; COL ; ROW M` |-| bracketed paste | `ESC [ 200 ~` … body … `ESC [ 201 ~` |-| CSI-u (Ctrl+P) | `ESC [ 112 ; 5 u` |--Feed those with `term.feed(bytes)`. Coordinates are 1-based screen cells, same-as SGR mouse. Read `term.annotated()` to pick a row, then `clickAt(x, y)`.+## Separate terminal UI-`/debug` stays the observability HUD; `term.layout()` is how you see why a-click missed (overlay, prompt-origin, mid-origin).+The fullscreen terminal UI is maintained separately. `graff tui` launches an+installed `graff-tui` executable (beside graff first, then on `PATH`); it does+not download one. Keep UI rendering tests in that project. This repository+owns the engine, line REPL, ACP protocol, and external-launcher boundary.## File size@@ -89,13 +59,14 @@ click missed (overlay, prompt-origin, mid-origin).- If a touched file is already over 600 LOC, do not grow it; move it toward the limit before adding more behavior.- Generated files, vendored dependencies, lockfiles, and machine-produced artifacts are exempt; change their generator or source instead of hand-editing them.-## Engine features are the same on REPL, TUI, and ACP+## Engine features are the same on REPL and ACPMessaging (`peer_message`, idle peer mail, Accord live wake) and otherengine-side behavior (turns, tools, compaction, goals) must work the same on-the line REPL, the fullscreen TUI, and ACP clients such as Harness (`graff acp`). Surface+the line REPL and ACP clients such as Harness (`graff acp`) and the separate+terminal UI. Surfacechrome can differ; the engine path cannot. If you add a wake, a latch, or a-delivery rule, wire it on all three in the same change.+delivery rule, wire it through the REPL and ACP engine paths in the same change.The desktop app is Harness, which lives in its own repository and drivesgraff over ACP. A new-chat folder rule, a worktree handoff, or a session cwd@@ -143,12 +114,12 @@ Install the tracked hooks once, and the checks run themselves:scripts/install-hooks.sh```-That points `core.hooksPath` at `.githooks/`, whose `pre-push` runs **tier 1** of the internal eval set: `zig fmt`, the 600-line ceiling, test reachability, `zig build`, the unit suite plus a count that may grow and never shrink, the named goal/loop/todo invariants, SDK drift, plus the TUI / tuiguard legs. It is deterministic and offline (no provider calls, no network, no spend). A warm `fmt`/`reach`/`sdk` subset is seconds; a post-`src` change rebuilds zig and runs the PTY probes, which is minutes (see #641). Prefer `scripts/eval-tier1.sh --only <check>` for a local edit. A push that only touches docs skips it.+That points `core.hooksPath` at `.githooks/`, whose `pre-push` runs **tier 1** of the internal eval set: `zig fmt`, the 600-line ceiling, test reachability, `zig build`, the unit suite plus a count that may grow and never shrink, the named goal/loop/todo invariants, SDK drift, plus the terminal regression checks. It is deterministic and offline (no provider calls, no network, no spend). A warm `fmt`/`reach`/`sdk` subset is seconds; a post-`src` change rebuilds zig and runs the PTY probes, which is minutes (see #641). Prefer `scripts/eval-tier1.sh --only <check>` for a local edit. A push that only touches docs skips it.```bashscripts/eval-tier1.sh # run it by handscripts/eval-tier1.sh --only sdk # rerun one check-scripts/eval-tier1.sh --only tui,tuiguard # a comma-separated list (#641)+scripts/eval-tier1.sh --only fmt,reach # a comma-separated list (#641)scripts/eval-tier1.sh --list # the check namesgit push --no-verify # emergency skip (GRAFF_SKIP_PREPUSH=1 also works)```diff --git a/README.md b/README.mdindex cd59da9c..e5c558ef 100644--- a/README.md+++ b/README.md@@ -387,7 +387,7 @@ container.| path | what it is ||---|---|-| `src/`, `TUI/` | agent engine and terminal UI |+| `src/` | agent engine, line REPL, and ACP || `apps/` | Chrome native-messaging extension || `graff-evals/` | live, in-house, FrontierHarness || `docs/` | ADRs, architecture, images, install, embedding |@@ -395,7 +395,9 @@ container.| `scripts/` | tier-1/2, PTY probes, release |The desktop app has its own repository,-[justrach/harness](https://github.com/justrach/harness).+[justrach/harness](https://github.com/justrach/harness). The fullscreen terminal+UI is also maintained separately: `graff tui` launches an installed `graff-tui`+beside the graff executable, or otherwise from `PATH`. It does not download it.```bashscripts/install-hooks.sh # oncediff --git a/TUI/anchor.zig b/TUI/anchor.zigdeleted file mode 100644index 95194be3..00000000--- a/TUI/anchor.zig+++ /dev/null@@ -1,289 +0,0 @@-//! Logical scroll anchor across a width rewrap.-//!-//! `Model.scroll` is a distance from the BOTTOM of the transcript in visual-//! rows, so a width change — which rewraps every line under the viewport —-//! keeps the number and loses the content: the row that was on top becomes a-//! different row of a different entry, and the transcript jumps under the-//! user's eyes. grok-build fixes this by holding a LOGICAL position across the-//! rebuild instead of a row count, and so do we: before the rewrap, record-//! which history entry owned the top visible line and how far into that-//! entry's block the line sat; after it, put that same logical line back on-//! top. Presentation only — nothing here is engine state.--const std = @import("std");--const app = @import("app.zig");-const layout = @import("layout_cache.zig");-const Model = app.Model;--/// Where the viewport was parked, in transcript terms rather than screen rows:-/// the history entry whose block the top visible line belonged to, plus that-/// line's ordinal WITHIN the block. Both survive a rewrap; a row index cannot.-pub const Anchor = struct { idx: usize, ordinal: usize };--/// The anchor for the top visible transcript line of the frame last painted at-/// `width`. Null when there is nothing to hold: an empty transcript, or a user-/// who is tailing — follow mode is already an anchor, and a better one (the-/// bottom), so a rewrap must not drag the viewport off it.-pub fn capture(self: *Model, width: usize) ?Anchor {- if (self.follow or width == 0 or self.history.items.len == 0) return null;- // One layout pass, not two: at capture time the cache still holds the OLD- // width, so this is a validating walk and both reads come off it.- const c = layout.ensure(self, width);- const top = self.mid_skip;- const idx = layout.indexAt(c, top) orelse return null;- const base = layout.lineOf(c, idx) orelse return null;- return .{ .idx = idx, .ordinal = top -| base };-}--/// The transcript row that shows the anchored logical line at `width`. A block-/// that rewrapped SHORTER clamps to its own last line, so the anchor stays-/// inside the entry it was taken from instead of sliding into the next one.-pub fn rowAt(self: *const Model, c: *const layout.Cache, anc: Anchor) usize {- const base = layout.lineOf(c, anc.idx) orelse return 0;- const span = blockSpan(self, c, anc.idx, base);- if (span == 0) return base;- return base + @min(anc.ordinal, span - 1);-}--/// How many visual rows entry `idx`'s block occupies at `width`. Measured as-/// the gap to the next block rather than by re-rendering the entry, so a-/// collapsed or expanded tool RUN — which the row math treats as one unit —-/// is measured the same way the viewport lays it out.-fn blockSpan(self: *const Model, c: *const layout.Cache, idx: usize, base: usize) usize {- const nxt = nextBlock(self, idx);- if (nxt >= self.history.items.len) return c.total -| base;- const nb = layout.lineOf(c, nxt) orelse return 1;- return nb -| base;-}--fn nextBlock(self: *const Model, idx: usize) usize {- if (idx < self.history.items.len and self.history.items[idx].kind == .tool)- return self.toolRun(idx).end;- return idx + 1;-}--// -----------------------------------------------------------------------------const inset = @import("inset.zig");-const render_mod = @import("render.zig");-const scrollback = @import("scrollback.zig");-const testing = std.testing;--fn wrap(m: *const Model) usize {- return inset.wrapWidth(m);-}--/// Park the viewport so entry `idx`'s first row is the top visible line, using-/// only what a real frame leaves on the Model: after a render with scroll = 0-/// and follow off, `mid_skip` IS max_scroll. Fails loudly when the entry sits-/// too near the end to ever BE a top line — a silently mis-parked viewport-/// would make every assertion below vacuous.-fn park(m: *Model, width: usize, height: usize, idx: usize) !usize {- m.follow = false;- // Sync `last_term_width` FIRST so neither probe below is itself a rewrap —- // parking is setup, not the behaviour under test.- const sync = try render_mod.render(m, testing.allocator, width, height, 0);- testing.allocator.free(sync);- m.scroll = 0;- const probe = try render_mod.render(m, testing.allocator, width, height, 0);- testing.allocator.free(probe);- const max_scroll = m.mid_skip;- const want = scrollback.visualOfIndex(m, idx, wrap(m)) orelse return error.NoSuchEntry;- if (want > max_scroll) return error.EntryCannotBeTopLine;- m.scroll = max_scroll - want;- const frame = try render_mod.render(m, testing.allocator, width, height, 0);- testing.allocator.free(frame);- try testing.expectEqual(want, m.mid_skip);- return want;-}--fn rewrap(m: *Model, width: usize, height: usize) ![]const u8 {- return render_mod.render(m, testing.allocator, width, height, 0);-}--// `**` is avoided on purpose: this zig fmt mangles it. Ten words a line,-// seven lines — long enough that the entry spans several rows at 100 cols.-const wrapme = " wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme wrapme";-const wrap_tail = wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme ++ wrapme;--fn fill(m: *Model, n: usize) !void {- var i: usize = 0;- while (i < n) : (i += 1) {- try m.push(.assistant, "a long explanation line that fills the scrollback with content and wraps at every narrow width we test");- }-}--test "a width rewrap keeps the anchored entry on the top row" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 30);- try m.push(.user, "MARKERONE");- try fill(&m, 30);-- const idx: usize = 30;- _ = try park(&m, 100, 24, idx);- try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).?);-- // Every one of these widths rewraps the filler above the marker into a- // different number of rows. Row-count scrolling drifts further on each- // step; the logical anchor must not move at all. There is transcript to- // spare above and below at every width here, so no edge clamp applies.- for ([_]usize{ 72, 55, 41, 120, 64, 100 }) |w| {- const frame = try rewrap(&m, w, 24);- defer testing.allocator.free(frame);- try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).?);- try testing.expect(std.mem.indexOf(u8, frame, "MARKERONE") != null);- }-}--test "an anchor inside a wrapped entry stays inside that entry" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 25);- try m.push(.assistant, "WRAPME" ++ wrap_tail);- try fill(&m, 25);-- const idx: usize = 25;- const base = try park(&m, 100, 24, idx);- // Park three rows INTO the long entry: the anchor now carries an ordinal.- m.scroll -= 3;- const at = try rewrap(&m, 100, 24);- testing.allocator.free(at);- try testing.expectEqual(base + 3, m.mid_skip);-- for ([_]usize{ 60, 44, 90, 40 }) |w| {- const frame = try rewrap(&m, w, 24);- defer testing.allocator.free(frame);- // The row on top still belongs to the same logical entry — the ordinal- // clamps into the rewrapped block rather than spilling past its end.- try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).?);- // Its head word is three rows above the viewport by construction; what- // must be on screen is the block's own body.- try testing.expect(std.mem.indexOf(u8, frame, "wrapme") != null);- }-}--test "the top edge clamps: entry 0 stays pinned to row 0 when it widens" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try m.push(.user, "FIRSTENTRY");- try fill(&m, 24);-- _ = try park(&m, 50, 24, 0);- try testing.expectEqual(@as(usize, 0), m.mid_skip);- // Widening shortens the transcript; the anchor is row 0, so the viewport- // must stay at the top rather than being flung to the bottom.- for ([_]usize{ 80, 110, 46 }) |w| {- const frame = try rewrap(&m, w, 24);- defer testing.allocator.free(frame);- try testing.expectEqual(@as(usize, 0), m.mid_skip);- try testing.expect(std.mem.indexOf(u8, frame, "FIRSTENTRY") != null);- }-}--test "the bottom edge clamps: a widened rewrap still shows the anchor" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 20);- try m.push(.user, "TAILMARK");- try fill(&m, 8);-- const idx: usize = 20;- _ = try park(&m, 42, 24, idx);- // Widening collapses the whole transcript into far fewer rows, so the- // anchored row can no longer BE the top line: max_scroll saturates and the- // viewport parks at the bottom. The anchor must still be on screen — the- // failure this guards against is scrolling past it entirely.- const frame = try rewrap(&m, 120, 24);- defer testing.allocator.free(frame);- try testing.expectEqual(@as(usize, 0), m.scroll);- try testing.expect(std.mem.indexOf(u8, frame, "TAILMARK") != null);- try testing.expect(scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).? <= idx);-}--test "a vertical-only resize keeps bottom-follow and never anchors" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 30);- try m.push(.assistant, "TAILROW");-- for ([_]usize{ 24, 12, 40, 18 }) |h| {- const frame = try rewrap(&m, 80, h);- defer testing.allocator.free(frame);- try testing.expect(m.follow);- try testing.expectEqual(@as(usize, 0), m.scroll);- try testing.expect(std.mem.indexOf(u8, frame, "TAILROW") != null);- }- // Height-only changes leave a SCROLLED viewport's distance-from-bottom- // alone: nothing rewrapped, so there is nothing to re-anchor.- _ = try park(&m, 80, 24, 8);- const kept = m.scroll;- const frame = try rewrap(&m, 80, 20);- defer testing.allocator.free(frame);- try testing.expectEqual(kept, m.scroll);-}--test "capture declines when the user is tailing or the transcript is empty" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try testing.expect(capture(&m, 80) == null);- try fill(&m, 4);- m.follow = true;- try testing.expect(capture(&m, 80) == null);- m.follow = false;- try testing.expect(capture(&m, 80) != null);-}--test "a collapsed tool run anchors as one block" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 25);- try m.pushTool(.{ .name = "bash", .detail = "printf hello" });- try m.pushTool(.{ .name = "bash", .detail = "hello", .done = true });- try fill(&m, 25);-- const idx: usize = 25;- _ = try park(&m, 100, 24, idx);- try testing.expectEqual(idx, scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).?);- for ([_]usize{ 62, 48, 96 }) |w| {- const frame = try rewrap(&m, w, 24);- defer testing.allocator.free(frame);- // 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, wrap(&m)).?);- try testing.expect(std.mem.indexOf(u8, frame, "Ran bash") != null);- }-}--test "without the anchor a width rewrap moves the top line" {- // The bug this module exists for, pinned as a fact about the OLD policy:- // holding `scroll` (a distance from the bottom) across a rewrap lands on a- // different entry. If a future change makes plain row-count scrolling- // width-stable on its own, this test says so out loud.- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fill(&m, 30);- try m.push(.user, "MARKERONE");- try fill(&m, 30);-- const idx: usize = 30;- _ = try park(&m, 100, 24, idx);- const kept = m.scroll;- // Rewrap with the anchor bypassed: same width change, scroll restored to- // exactly what the old code would have carried over.- const frame = try rewrap(&m, 44, 24);- testing.allocator.free(frame);- m.scroll = kept;- const naive = try rewrap(&m, 44, 24);- defer testing.allocator.free(naive);- try testing.expect(scrollback.indexAtVisual(&m, m.mid_skip, wrap(&m)).? != idx);-}diff --git a/TUI/app.zig b/TUI/app.zigdeleted file mode 100644index 1273a932..00000000--- a/TUI/app.zig+++ /dev/null@@ -1,576 +0,0 @@-//! Application model: screens, focus, overlays, conversation entries.-//! No zigzag — input is TUI/input.zig.--const std = @import("std");--const engine = @import("engine.zig");-const input_mod = @import("input.zig");-const theme_mod = @import("theme.zig");-const sanitize = @import("sanitize.zig");--pub const Screen = enum { welcome, agent };-pub const Focus = enum { prompt, scrollback };-pub const Overlay = enum { none, palette, help, theme, model, effort, settings, rewind, slash, debug, image, file, jump, sessions };-/// One vocabulary with the engine (#551): the Model does not keep a private-/// copy of the permission policy, it holds the engine's own enum and hands it-/// straight to the turn backend.-pub const AgentMode = engine.Mode;-pub const EscArm = enum { none, clear, rewind };-pub const EntryKind = enum { user, assistant, tool, system, err, pending };--/// A tool row's payload, straight off the engine's ToolInvocation /-/// ToolOutcome / ToolRejection (#551). Rendering reads these FIELDS; nothing-/// re-derives them by splitting a rendered line on a glyph or on " | ".-pub const ToolInfo = struct {- /// The engine's tool name, verbatim. Classification (mcp / search) tests- /// this, never the whole row.- name: []const u8,- /// Tier 1: One-line decision summary (via interpret).- summary: []const u8 = "",- /// Tier 2: High-signal facts (via usefulPreview).- detail: []const u8 = "",- /// Tier 3: The raw output from the engine.- raw: []const u8 = "",- /// false = the call was announced, true = it returned (or was refused).- done: bool = false,- is_error: bool = false,- /// Refused by the harness before it ran.- denied: bool = false,- /// Engine-measured duration on a finished row. 0 while the call is live.- ms: u64 = 0,-};--pub const Entry = struct {- kind: EntryKind,- notification: bool = false,- text: []const u8,- folded: bool = false,- /// Non-null on every `.tool` row a live turn produces. Null on a legacy- /// `.tool` row restored from a session written before the typed contract —- /// 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 };--/// The rows of a composed frame that a scroll actually MOVES: content only, no-/// chrome. `off` is the transcript line the first of them shows, so comparing-/// two consecutive frames' bands says whether the viewport merely slid — which-/// is the one thing a row-against-row diff can never see (perf/tui-scroll-paint).-/// `live` is false whenever there is nothing scrollable: the welcome pane, a-/// transcript shorter than the viewport.-pub const Band = struct {- live: bool = false,- /// First screen row of the band, 0-based.- top: usize = 0,- len: usize = 0,- /// Index, in the composed mid-lines, of the line on `top`.- off: usize = 0,- /// Visual lines the band is a window ONTO — the whole wrapped transcript,- /// not the screenful of it. The scrollbar's proportions come from here.- total: usize = 0,-};--pub const ESC_MS: u64 = 800;--pub const Model = struct {- alloc: std.mem.Allocator,- input: input_mod.Input,- history: std.array_list.Managed(Entry),- prompt_hist: std.array_list.Managed([]const u8),- /// Image paths index-aligned with `prompt_hist` (#577). Empty slice = text-only.- prompt_hist_images: std.array_list.Managed([]const []const u8),- draft_input: ?input_mod.State = null,- draft_images: ?[]const []const u8 = null,- steer_queue: std.array_list.Managed([]const u8),- images: std.array_list.Managed([]const u8),- owned_images: std.array_list.Managed(@import("owned_images.zig").Owned),- pending: ?*engine.Job = null,- /// A background engine op (/compact, !cmd, @-file list) — same thread +- /// done-flag contract as `pending`, so neither can freeze the loop (#533).- bg: ?*engine.BgOp = null,-- screen: Screen = .welcome,- focus: Focus = .prompt,- overlay: Overlay = .none,- overlay_sel: usize = 0,- overlay_filter: []const u8 = "",- slash_sel: usize = 0,-- theme_id: theme_mod.Id = .night,- /// Set once the user picks a theme; blocks the OSC-11 auto polarity.- theme_explicit: bool = false,- /// Rows of sticky-header chrome at the top of the viewport this frame —- /// keys.zig must treat them as inert instead of clicking what they occlude.- sticky_rows: usize = 0,- mode: AgentMode = .normal,- effort: engine.Effort = .medium,- fast: bool = false,- thinking_show: bool = false,- ultracode: bool = false,- strict: bool = false,- title: bool = true,- multiline: bool = false,- compact_mode: bool = false,- vim_mode: bool = false,- follow: bool = true,- running: bool = true,-- goal: ?[]const u8 = null,- session_name: ?[]const u8 = null,- /// Owns the string `engine.g_model_name` points at after a mid-turn- /// provider failover (#551): the event that carried it is freed as soon as- /// the drain that delivered it returns.- model_override: ?[]const u8 = null,- scroll: usize = 0,- /// An overlay body is a DOCUMENT, not a transcript: it opens at its FIRST- /// row and scrolls downward, where the transcript is pinned to its tail.- /// Kept apart from `scroll` on purpose — sharing the field meant paging- /// /help left the transcript underneath parked mid-history the moment the- /// overlay closed. Presentation state, reset whenever an overlay opens.- overlay_scroll: usize = 0,- selected: usize = 0,- turns: usize = 0,- /// The engine's last reported meters (#551). Null until a turn has run —- /// there is nothing honest to say about a context nobody has measured.- /// Its strings are owned here; setStatus and deinit are the only writers.- status: ?engine.Status = null,- last_term_width: usize = 80,- last_term_height: usize = 24,- /// Screen row (0-based) where scrollback/welcome starts — for mouse hits.- mid_origin: usize = 0,- /// First screen row (0-based) of the composer — clicks here focus the prompt.- prompt_origin: usize = 20,- /// How many mid-lines were clipped above the viewport.- mid_skip: usize = 0,- /// Composed mid-lines this frame: the transcript's wrapped total, or an- /// overlay body's own line count. A press past it landed on the BACKDROP- /// under a short panel and dismisses it, rather than on the panel itself.- mid_total: usize = 0,- /// Rows of the slash completion menu on screen, at the top of the bottom- /// block. A press there picks a command instead of merely focusing the- /// composer (click.zig); zero whenever the menu is closed.- slash_rows: usize = 0,- /// The scrollable band of the frame just composed, and the painter hint- /// derived from how it moved since the frame before it. Presentation state- /// for the diff painter's scroll fast path: render.zig is the only writer,- /// paint.zig the only reader, and both treat it as a claim to verify.- band: Band = .{},- paint_hint: ?@import("scrollpaint.zig").Hint = null,- now_ms: u64 = 0,- /// When the viewport last MOVED. The scrollbar fades out of a tail-parked- /// viewport this many milliseconds later (scrollbar.zig); zero means the- /// session has never scrolled, so no gutter has ever been earned.- scroll_seen_ms: u64 = 0,- /// Did the frame just composed carry the scroll gutter? Two consecutive- /// frames that both did are shaped the same way, which is what lets the- /// painter scroll the band and patch the gutter cell (scrollpaint.zig)- /// instead of refusing the fast path outright.- gutter_on: bool = false,- /// A one-shot byte string the run loop owes the TERMINAL, not the screen:- /// the OSC 52 clipboard write a copy just produced. Deliberately not part- /// of the frame — a frame is re-painted (the self-heal rewrites it every- /// few seconds), and a clipboard write must happen exactly once.- osc_pending: []const u8 = "",- hist_idx: ?usize = null,- /// Newline-joined paths for the @-file picker, loaded once per session.- files_cache: ?[]const u8 = null,- sessions_cache: ?[]const u8 = null,-- toast: []const u8 = "",- toast_until_ms: u64 = 0,- esc_arm: EscArm = .none,- esc_until_ms: u64 = 0,- new_arm_until_ms: u64 = 0,- preview_path: []const u8 = "",- preview_n: u32 = 0,- preview_pin: bool = false,- preview_rows: usize = 0,- /// Drag-selection band over the composed frame (#529) — presentation only.- sel: @import("selection.zig").Sel = .{},- /// Row under the pointer and the double-click window (hover.zig). Screen- /// state: which row is hovered is never an engine fact, and the affordance- /// it paints is derived from the typed entries the Model already holds.- hover: @import("hover.zig").State = .{},- /// Single-click gesture state (click.zig) - whether the scroll gutter- /// currently owns the pointer. Presentation only, like `sel` and `hover`.- click: @import("click.zig").State = .{},- /// Wrapped-line layout of the transcript, keyed by width/theme/fold/entry- /// identity (layout_cache.zig). Presentation state: a pure memo of what the- /// row builders would produce, so scrolling is a slice and not a re-layout.- layout: @import("layout_cache.zig").Cache = .{},- /// Text the band currently covers, captured by the same pass that paints- /// it, so what the clipboard gets is exactly what the user saw highlighted.- sel_text: []const u8 = "",- cancel_requested: bool = false,- quit_requested: bool = false,- chat: bool = false,- pasting: bool = false,-- pub fn setup(self: *Model, alloc: std.mem.Allocator) void {- self.* = .{- .alloc = alloc,- .input = input_mod.Input.init(alloc),- .history = std.array_list.Managed(Entry).init(alloc),- .prompt_hist = std.array_list.Managed([]const u8).init(alloc),- .prompt_hist_images = std.array_list.Managed([]const []const u8).init(alloc),- .steer_queue = std.array_list.Managed([]const u8).init(alloc),- .images = std.array_list.Managed([]const u8).init(alloc),- .owned_images = std.array_list.Managed(@import("owned_images.zig").Owned).init(alloc),- .chat = engine.g_turn_fn != null,- };- self.input.setPlaceholder("");- }-- pub fn deinit(self: *Model) void {- const settled = (if (self.pending) |job| !job.threaded or job.done.load(.acquire) else true) and- (if (self.bg) |op| !op.threaded or op.done.load(.acquire) else true);- // Never an unbounded join in a destructor (#534): by the time deinit- // runs, run.zig's terminal defers have already handed the shell back,- // so joining a stalled provider call here hangs invisibly. run.zig- // settles the job while the alt screen is still up; a thread still- // running at this point is abandoned, leak and all.- if (self.pending) |job| {- if (!job.threaded or job.done.load(.acquire)) self.destroyJob(job) else self.pending = null;- }- if (self.bg) |op| {- if (!op.threaded or op.done.load(.acquire)) @import("bgop.zig").reap(self) else self.bg = null;- }- @import("owned_images.zig").deinit(self, settled);- self.layout.deinit(self.alloc);- for (self.history.items) |e| self.freeEntry(e);- self.history.deinit();- for (self.prompt_hist.items) |s| self.alloc.free(s);- self.prompt_hist.deinit();- @import("prompt_history.zig").deinit(self);- for (self.steer_queue.items) |s| self.alloc.free(s);- self.steer_queue.deinit();- for (self.images.items) |s| self.alloc.free(s);- self.images.deinit();- if (self.goal) |g| self.alloc.free(g);- if (self.session_name) |s| self.alloc.free(s);- self.dropStatus();- if (self.model_override) |m| {- // The global points into this buffer; drop it before the free so a- // late reader cannot follow a dangling slice.- if (engine.g_model_name.ptr == m.ptr) engine.g_model_name = "";- self.alloc.free(m);- }- if (self.overlay_filter.len > 0) self.alloc.free(self.overlay_filter);- if (self.files_cache) |f| self.alloc.free(f);- if (self.sessions_cache) |s| self.alloc.free(s);- if (self.sel_text.len > 0) self.alloc.free(self.sel_text);- if (self.osc_pending.len > 0) self.alloc.free(self.osc_pending);- self.input.deinit();- }-- pub fn destroyJob(self: *Model, job: *engine.Job) void {- engine.joinJob(job);- if (job.result) |r| self.alloc.free(r);- for (job.history) |t| self.alloc.free(t.text);- self.alloc.free(job.history);- if (engine.g_raw == &job.raw) engine.g_raw = null;- if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);- if (job.raw.buf.len > 0) self.alloc.free(job.raw.buf);- job.events.deinit();- self.alloc.destroy(job);- self.pending = null;- @import("owned_images.zig").collect(self);- }-- pub fn theme(self: *const Model) theme_mod.Theme {- return theme_mod.of(self.theme_id);- }-- pub fn push(self: *Model, kind: EntryKind, text: []const u8) !void {- const owned = try sanitize.sanitized(self.alloc, text);- errdefer self.alloc.free(owned);- if (kind == .user) try @import("owned_images.zig").retain(self, owned);- 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;- self.scroll = 0;- }- }-- /// Append a FIELD-BACKED tool row (#551). `name`/`detail` come from the- /// engine's typed event and are copied here; `text` is kept only as the- /// plain fallback the non-rendering readers use (sticky header, selection- /// copy, session persistence), never as the thing rendering parses.- pub fn pushTool(self: *Model, info: ToolInfo) !void {- const name = try self.alloc.dupe(u8, info.name);- errdefer self.alloc.free(name);- const summary = try sanitize.sanitized(self.alloc, info.summary);- errdefer self.alloc.free(summary);- const detail = try sanitize.sanitized(self.alloc, info.detail);- errdefer self.alloc.free(detail);- const raw = try sanitize.sanitized(self.alloc, info.raw);- errdefer self.alloc.free(raw);-- const text = try self.alloc.dupe(u8, summary);- errdefer self.alloc.free(text);-- try self.history.append(.{- .kind = .tool,- .text = text,- .folded = true,- .tool = .{- .name = name,- .summary = summary,- .detail = detail,- .raw = raw,- .done = info.done,- .is_error = info.is_error,- .denied = info.denied,- .ms = info.ms,- },- .at_ms = self.now_ms,- });- }-- /// Release everything an entry owns. Tool rows own two extra strings, so- /// freeing `text` alone leaks them.- pub fn freeEntry(self: *Model, e: Entry) void {- self.alloc.free(e.text);- if (e.tool) |t| {- self.alloc.free(t.name);- self.alloc.free(t.summary);- self.alloc.free(t.detail);- self.alloc.free(t.raw);- }- }-- pub fn pushFmt(self: *Model, kind: EntryKind, comptime fmt: []const u8, args: anytype) !void {- const raw = try std.fmt.allocPrint(self.alloc, fmt, args);- defer self.alloc.free(raw);- const text = try sanitize.sanitized(self.alloc, raw);- errdefer self.alloc.free(text);- if (kind == .user) try @import("owned_images.zig").retain(self, text);- try self.history.append(.{ .kind = kind, .text = text });- }-- /// Take ownership of what the engine says a model switch landed on. The- /// name is allocated by the callback out of THIS Model's allocator and the- /// globals point into it, so the Model holds exactly one such buffer and- /// deinit already knows how to drop it. The provider id is a static spec- /// literal and is not owned.- pub fn adoptModel(self: *Model, picked: engine.Picked) void {- if (self.model_override) |old| self.alloc.free(old);- self.model_override = picked.model;- engine.g_model_name = picked.model;- engine.g_model_provider = picked.provider;- }-- /// A mid-turn failover changed the seat behind the frontend's back (#551).- /// Unlike `adoptModel` the model string dies with the drain that delivered- /// the event, so it is copied here; the provider id is a static spec- /// literal and is not owned, exactly as above.- ///- /// Both globals must move TOGETHER. The failover path used to set only the- /// name, which left the new model paired with the OLD provider id — a seat- /// that serves nothing — and `models.isCurrent` compares the provider too,- /// so the picker marked the wrong row, or none at all.- pub fn adoptFailover(self: *Model, changed: engine.ModelChanged) void {- const owned = self.alloc.dupe(u8, changed.model) catch return;- if (self.model_override) |old| self.alloc.free(old);- self.model_override = owned;- engine.g_model_name = owned;- engine.g_model_provider = changed.provider;- self.pushFmt(.system, "model \u{2192} {s}", .{owned}) catch {};- }-- pub fn setToast(self: *Model, text: []const u8) void {- self.toast = text;- self.toast_until_ms = self.now_ms + 1500;- }-- pub fn clearHistory(self: *Model) void {- // Before the entries go: the layout holds wrapped bytes for them and a- // back-pointer into their text.- self.layout.invalidate(self.alloc);- for (self.history.items) |e| self.freeEntry(e);- self.history.clearRetainingCapacity();- self.turns = 0;- // The meters describe a conversation that no longer exists. Compaction- // replays through here too and re-reports its own on the next turn.- self.dropStatus();- self.selected = 0;- self.scroll = 0;- self.screen = .welcome;- }-- /// Adopt the engine's meters. The event's copy dies with the drain that- /// delivered it, so the two strings are re-owned here.- pub fn setStatus(self: *Model, st: engine.Status) void {- const model = self.alloc.dupe(u8, st.model) catch return;- const provider = self.alloc.dupe(u8, st.provider_id) catch {- self.alloc.free(model);- return;- };- self.dropStatus();- var owned = st;- owned.model = model;- owned.provider_id = provider;- self.status = owned;- }-- pub fn dropStatus(self: *Model) void {- const st = self.status orelse return;- self.alloc.free(st.model);- self.alloc.free(st.provider_id);- self.status = null;- }-- /// Percent of the model's context window in use, or null while nothing has- /// been measured — a "0%" drawn before the first response is a lie.- pub fn contextPercent(self: *const Model) ?u64 {- const st = self.status orelse return null;- if (!st.has_context) return null;- return st.percent();- }-- /// /new, /clear, Ctrl+N twice: start over. Distinct from clearHistory,- /// which the compaction replay also uses — that one REPLACES the visible- /// transcript for a conversation the engine has just rewritten and must- /// keep, while this one throws the conversation away too (#551).- ///- /// Returns false while an engine call is in flight, and does nothing: the- /// reset frees the arena that call is allocating its history from, so- /// "clear the screen" would be a use-after-free on the turn thread. /new- /// already refused mid-turn (#521); Ctrl+N did not, and only became- /// dangerous once the reset reached past the transcript.- pub fn newSession(self: *Model) bool {- if (self.pending != null or self.bg != null) return false;- self.clearHistory();- engine.historyChanged(.reset);- return true;- }-- pub fn userTurnCount(self: *const Model) usize {- var n: usize = 0;- for (self.history.items) |e| {- if (e.kind == .user) n += 1;- }- return n;- }-- pub fn modeLabel(self: *const Model) []const u8 {- return switch (self.mode) {- .normal => "Normal",- .plan => "Plan",- .always_approve => "Always-approve",- };- }-- pub fn modeSlug(self: *const Model) []const u8 {- return switch (self.mode) {- .normal => "normal",- .plan => "plan",- .always_approve => "auto-accept",- };- }-- /// Inclusive-exclusive run of consecutive `.tool` rows containing `idx`.- pub fn toolRun(self: *const Model, idx: usize) struct { start: usize, end: usize } {- if (idx >= self.history.items.len or self.history.items[idx].kind != .tool)- return .{ .start = idx, .end = idx };- var start = idx;- while (start > 0 and self.history.items[start - 1].kind == .tool) start -= 1;- var end = idx + 1;- while (end < self.history.items.len and self.history.items[end].kind == .tool) end += 1;- return .{ .start = start, .end = end };- }-- pub fn toggleToolGroup(self: *Model, idx: usize) void {- const run = self.toolRun(idx);- if (run.start >= run.end) return;- const open = !self.history.items[run.start].folded;- var i = run.start;- while (i < run.end) : (i += 1) self.history.items[i].folded = open;- }-- pub fn cycleMode(self: *Model) void {- self.mode = switch (self.mode) {- .normal => .plan,- .plan => .always_approve,- .always_approve => .normal,- };- self.setToast(self.modeLabel());- }-- pub fn closeOverlay(self: *Model) void {- self.overlay = .none;- self.overlay_sel = 0;- self.overlay_scroll = 0;- self.preview_path = "";- self.preview_n = 0;- self.preview_pin = false;- if (self.overlay_filter.len > 0) {- self.alloc.free(self.overlay_filter);- self.overlay_filter = "";- }- }-- pub fn openOverlay(self: *Model, which: Overlay) void {- self.overlay = which;- self.overlay_sel = 0;- self.overlay_scroll = 0;- if (self.overlay_filter.len > 0) {- self.alloc.free(self.overlay_filter);- self.overlay_filter = "";- }- }-- pub fn typeOverlayFilter(self: *Model, c: u8) void {- const old = self.overlay_filter;- const buf = self.alloc.alloc(u8, old.len + 1) catch return;- if (old.len > 0) @memcpy(buf[0..old.len], old);- buf[old.len] = c;- if (old.len > 0) self.alloc.free(old);- self.overlay_filter = buf;- self.overlay_sel = 0;- }-- pub fn attachImage(self: *Model, path: []const u8) void {- const owned = self.alloc.dupe(u8, path) catch return;- self.images.append(owned) catch {- self.alloc.free(owned);- return;- };- self.setToast(if (self.images.items.len == 1) "[Image #1] attached" else "image attached");- }-- pub fn takeImagesPrefix(self: *Model, a: std.mem.Allocator) []const u8 {- if (self.images.items.len == 0) return "";- var out = std.array_list.Managed(u8).init(a);- for (self.images.items) |p| {- out.appendSlice("@[") catch {};- out.appendSlice(p) catch {};- out.appendSlice("] ") catch {};- }- for (self.images.items) |p| self.alloc.free(p);- self.images.clearRetainingCapacity();- return out.toOwnedSlice() catch "";- }-- pub fn backspaceOverlayFilter(self: *Model) void {- const old = self.overlay_filter;- if (old.len == 0) return;- if (old.len == 1) {- self.alloc.free(old);- self.overlay_filter = "";- } else {- const buf = self.alloc.dupe(u8, old[0 .. old.len - 1]) catch return;- self.alloc.free(old);- self.overlay_filter = buf;- }- self.overlay_sel = 0;- }-};diff --git a/TUI/app_tests.zig b/TUI/app_tests.zigdeleted file mode 100644index 9037d73c..00000000--- a/TUI/app_tests.zig+++ /dev/null@@ -1,38 +0,0 @@-//! Tests for TUI/app.zig, split out so app.zig stays under 600 lines.--const std = @import("std");-const app = @import("app.zig");-const Model = app.Model;-const AgentMode = app.AgentMode;-const Screen = app.Screen;--test "cycleMode walks Normal → Plan → Always-approve" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(AgentMode.normal, m.mode);- m.cycleMode();- try std.testing.expectEqual(AgentMode.plan, m.mode);- m.cycleMode();- try std.testing.expectEqual(AgentMode.always_approve, m.mode);-}--test "push user flips welcome to agent" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(Screen.welcome, m.screen);- try m.push(.user, "hi");- try std.testing.expectEqual(Screen.agent, m.screen);-}--test "push strips raw ANSI, OSC, and CR from tool text" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.tool, "⚙ bash | \x1b[31mred\x1b[0m\x1b]0;title\x07 done\r");- try std.testing.expectEqualStrings("⚙ bash | red done", m.history.items[0].text);- // No ESC and no CR — the old fast path would have kept these.- try m.push(.assistant, "beep\x07back\x08null\x00done");- try std.testing.expectEqualStrings("beepbacknulldone", m.history.items[1].text);-}diff --git a/TUI/bgop.zig b/TUI/bgop.zigdeleted file mode 100644index fb07d637..00000000--- a/TUI/bgop.zig+++ /dev/null@@ -1,372 +0,0 @@-//! Background engine ops. `/compact`, `/version`, `/update`, `!cmd` and the @-file list used to call-//! straight into the engine from keys.handle, i.e. from inside run.zig's byte-//! parse loop: no render, no poll, no key handling, no cancel for the whole-//! round trip — a 5-60 s freeze indistinguishable from a hang (#533).-//!-//! They now take the same route a model turn takes (turn.zig): one thread, one-//! done flag, polled from the top of the loop. Nothing here reimplements-//! engine behavior — each op is exactly one engine callback, moved off the-//! render+input thread, with the result applied on the main thread.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const turn = @import("turn.zig");-const Model = app.Model;-const Op = engine.BgOp;--const SpawnFn = *const fn (*Op) anyerror!std.Thread;--fn spawnOp(op: *Op) anyerror!std.Thread {- return std.Thread.spawn(.{}, engine.bgRun, .{op});-}--/// Spawn `kind` in the background, taking ownership of `turns` and `cmd`.-/// A non-empty `label` pushes a live row so the wait is visible. Returns false-/// when a turn or another op already holds the engine — the caller still owns-/// its inputs then.-pub fn start(self: *Model, kind: Op.Kind, turns: []engine.Turn, cmd: []const u8, label: []const u8) bool {- return startWithSpawn(self, kind, turns, cmd, label, spawnOp);-}--fn startWithSpawn(self: *Model, kind: Op.Kind, turns: []engine.Turn, cmd: []const u8, label: []const u8, spawn_fn: SpawnFn) bool {- if (self.bg != null or self.pending != null) return false;- const op = self.alloc.create(Op) catch return false;- // The op carries the same policy a turn does: `!cmd` goes through the- // engine's gate now, and /plan has to reach it (#551).- op.* = .{ .kind = kind, .gpa = self.alloc, .turns = turns, .cmd = cmd, .params = turn.paramsOf(self) };- if (label.len > 0) self.push(.pending, label) catch {};- self.bg = op;- if (spawn_fn(op)) |th| {- op.thread = th;- } else |_| {- // Running inline would freeze paint, input and cancellation — report- // the failed start through finish() without invoking engine work.- op.threaded = false;- op.start_failed = true;- op.done.store(true, .release);- }- return true;-}--/// Esc / Ctrl+C during an op. The engine-side cancel is the same one a turn-/// uses: process_runner kills a running `!cmd` child within 200 ms, and the-/// compaction request's stall watchdogs abort between polls.-pub fn cancel(self: *Model) void {- const op = self.bg orelse return;- if (op.cancelled) return;- op.cancelled = true;- if (engine.g_cancel_fn) |f| f(engine.g_turn_ctx);-}--/// Apply a finished op on the main thread. No-op while it is still running.-pub fn finish(self: *Model) void {- const op = self.bg orelse return;- if (!op.done.load(.acquire)) return;- if (op.threaded) op.thread.join();- op.threaded = false; // release() must not join a second time- _ = turn.removePendingRows(self);- if (op.start_failed) {- self.push(.err, switch (op.kind) {- .compact => "compaction failed to start",- .bash => "command failed to start",- .files => "file list failed to start",- .version => "version check failed to start",- .update => "update failed to start",- }) catch {};- } else switch (op.kind) {- .compact => applyCompact(self, op),- .bash => applyBash(self, op),- .files => applyFiles(self, op),- .version => applyVersion(self, op),- .update => applyUpdate(self, op),- }- release(self, op);- self.scroll = 0;- self.follow = true;-}--/// Free a finished op without applying it — Model.deinit's path.-pub fn reap(self: *Model) void {- const op = self.bg orelse return;- release(self, op);-}--/// Give up on an op whose thread ignored the cancel. Everything it owns is-/// leaked on purpose: the detached worker still writes into it. Callers exit-/// the process straight after (same contract as turn.abandonJob).-pub fn abandon(self: *Model) void {- self.bg = null;-}--/// One step of the quit-time settle, mirroring turn.quitStep so run.zig can-/// wait for a turn and an op with a single deadline.-pub fn quitStep(self: *Model, elapsed_ms: u64) turn.QuitStep {- const op = self.bg orelse return .reap;- if (!op.threaded or op.done.load(.acquire)) return .reap;- return if (elapsed_ms >= turn.quit_drain_ms) .abandon else .wait;-}--/// True while the @-file list is still loading, so the picker can say so-/// instead of claiming there is no file list.-pub fn loadingFiles(self: *const Model) bool {- const op = self.bg orelse return false;- return op.kind == .files;-}--fn release(self: *Model, op: *Op) void {- if (op.threaded) op.thread.join();- for (op.turns) |t| self.alloc.free(t.text);- if (op.turns.len > 0) self.alloc.free(op.turns);- if (op.cmd.len > 0) self.alloc.free(op.cmd);- if (op.compact.note.len > 0) self.alloc.free(op.compact.note);- for (op.compact.turns) |t| self.alloc.free(t.text);- if (op.compact.turns.len > 0) self.alloc.free(op.compact.turns);- if (op.text) |t| self.alloc.free(t);- self.alloc.destroy(op);- self.bg = null;- @import("owned_images.zig").collect(self);-}--fn applyCompact(self: *Model, op: *Op) void {- if (!op.ok) {- const why: []const u8 = if (op.cancelled)- "compaction cancelled, history unchanged"- else if (op.compact.note.len > 0)- op.compact.note- else- "compaction failed, history unchanged";- self.push(.system, why) catch {};- return;- }- self.clearHistory();- if (op.compact.note.len > 0) self.push(.system, op.compact.note) catch {};- for (op.compact.turns) |t| {- self.push(if (t.notification) .system else switch (t.role) {- .user => .user,- .assistant => .assistant,- }, t.text) catch continue;- self.history.items[self.history.items.len - 1].notification = t.notification;- }-}--fn applyBash(self: *Model, op: *Op) void {- if (op.text) |out| {- self.push(.system, @import("dispatch.zig").lastLines(out, 40)) catch {};- } else if (op.cancelled) {- self.push(.system, "■ interrupted") catch {};- } else {- self.push(.err, "command failed to start") catch {};- }-}--fn applyFiles(self: *Model, op: *Op) void {- if (self.files_cache != null) return;- const t = op.text orelse return;- self.files_cache = self.alloc.dupe(u8, t) catch null;-}--fn applyVersion(self: *Model, op: *Op) void {- if (op.text) |text| {- self.push(.system, text) catch {};- } else if (op.cancelled) {- self.push(.system, "version check cancelled") catch {};- } else {- self.push(.err, "version check unavailable") catch {};- }-}--fn applyUpdate(self: *Model, op: *Op) void {- if (op.text) |text| {- self.push(.system, text) catch {};- } else if (op.cancelled) {- self.push(.system, "update cancelled — the existing install is unchanged") catch {};- } else {- self.push(.err, "update check unavailable") catch {};- }-}--const testing = std.testing;--fn drain(m: *Model) !void {- var spins: usize = 0;- while (m.bg) |op| {- if (op.done.load(.acquire)) break;- spins += 1;- if (spins > 1_000_000) return error.OpNeverFinished;- std.Thread.yield() catch {};- }- finish(m);-}--test "a bash op runs off the render thread and its output lands in the scrollback (#533)" {- engine.g_bash_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, _: engine.Params) ?[]const u8 {- return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;- }- }.f;- defer engine.g_bash_fn = null;- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- const cmd = try testing.allocator.dupe(u8, "git status");- try testing.expect(start(&m, .bash, &.{}, cmd, "running"));- // The op is in flight: the model is usable and a live row is showing.- try testing.expect(m.bg != null);- try testing.expectEqual(app.EntryKind.pending, m.history.items[0].kind);- try drain(&m);- try testing.expect(m.bg == null);- for (m.history.items) |e| try testing.expect(e.kind != .pending);- try testing.expectEqualStrings("ran: git status", m.history.items[m.history.items.len - 1].text);-}--test "a compact op replaces the history only when the engine says it worked (#533)" {- engine.g_compact_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, history: []const engine.Turn, out: *engine.CompactOut) bool {- if (history.len == 0) return false;- var turns = gpa.alloc(engine.Turn, 1) catch return false;- turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "summary") catch return false };- out.turns = turns;- out.note = gpa.dupe(u8, "history compacted") catch "";- return true;- }- }.f;- defer engine.g_compact_fn = null;- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try m.push(.user, "one");- try m.push(.assistant, "two");- const turns = try testing.allocator.alloc(engine.Turn, 1);- turns[0] = .{ .role = .user, .text = try testing.allocator.dupe(u8, "one") };- try testing.expect(start(&m, .compact, turns, "", "compacting"));- try drain(&m);- try testing.expect(m.bg == null);- try testing.expectEqualStrings("history compacted", m.history.items[0].text);- try testing.expectEqualStrings("summary", m.history.items[1].text);- try testing.expectEqual(@as(usize, 2), m.history.items.len);-}--test "a second op is refused while one is in flight, and Esc cancels the live one" {- const Gate = struct {- var go: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- var entered: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- var saw_cancel: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- fn bash(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const u8, _: engine.Params) ?[]const u8 {- entered.store(true, .release);- while (!go.load(.acquire)) std.Thread.yield() catch {};- return gpa.dupe(u8, "done") catch null;- }- fn cancelled(_: ?*anyopaque) void {- saw_cancel.store(true, .release);- go.store(true, .release);- }- };- Gate.go.store(false, .release);- Gate.entered.store(false, .release);- Gate.saw_cancel.store(false, .release);- engine.g_bash_fn = Gate.bash;- engine.g_cancel_fn = Gate.cancelled;- defer {- Gate.go.store(true, .release);- engine.g_bash_fn = null;- engine.g_cancel_fn = null;- }- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- const cmd = try testing.allocator.dupe(u8, "sleep 30");- try testing.expect(start(&m, .bash, &.{}, cmd, "running"));- var spins: usize = 0;- while (!Gate.entered.load(.acquire)) : (spins += 1) {- if (spins > 1_000_000) return error.OpNeverStarted;- std.Thread.yield() catch {};- }- // The engine is busy: a second op must not stack on top of it.- try testing.expect(!start(&m, .bash, &.{}, "", "running"));- // Esc reaches the engine — which is the whole point of the thread.- cancel(&m);- try testing.expect(Gate.saw_cancel.load(.acquire));- try drain(&m);- try testing.expect(m.bg == null);-}--test "thread spawn failure completes through finish without inline engine work (#537)" {- const Fake = struct {- var calls: usize = 0;- fn spawn(_: *Op) anyerror!std.Thread {- return error.InjectedSpawnFailure;- }- fn compact(_: ?*anyopaque, _: std.mem.Allocator, _: []const engine.Turn, _: *engine.CompactOut) bool {- calls += 1;- return false;- }- fn bash(_: ?*anyopaque, _: std.mem.Allocator, _: []const u8, _: engine.Params) ?[]const u8 {- calls += 1;- return null;- }- fn files(_: ?*anyopaque, _: std.mem.Allocator) ?[]const u8 {- calls += 1;- return null;- }- fn version(_: ?*anyopaque, _: std.mem.Allocator) ?[]const u8 {- calls += 1;- return null;- }- fn update(_: ?*anyopaque, _: std.mem.Allocator, _: []const u8) ?[]const u8 {- calls += 1;- return null;- }- };- Fake.calls = 0;- engine.g_compact_fn = Fake.compact;- engine.g_bash_fn = Fake.bash;- engine.g_files_fn = Fake.files;- engine.g_version_fn = Fake.version;- engine.g_update_fn = Fake.update;- defer {- engine.g_compact_fn = null;- engine.g_bash_fn = null;- engine.g_files_fn = null;- engine.g_version_fn = null;- engine.g_update_fn = null;- }- const cases = [_]struct { kind: Op.Kind, message: []const u8 }{- .{ .kind = .compact, .message = "compaction failed to start" },- .{ .kind = .bash, .message = "command failed to start" },- .{ .kind = .files, .message = "file list failed to start" },- .{ .kind = .version, .message = "version check failed to start" },- .{ .kind = .update, .message = "update failed to start" },- };- for (cases) |case| {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try testing.expect(startWithSpawn(&m, case.kind, &.{}, "", "running", Fake.spawn));- const op = m.bg.?;- try testing.expect(op.start_failed and !op.threaded and op.done.load(.acquire));- try testing.expectEqual(@as(usize, 0), Fake.calls);- finish(&m);- try testing.expect(m.bg == null);- try testing.expectEqual(app.EntryKind.err, m.history.items[0].kind);- try testing.expectEqualStrings(case.message, m.history.items[0].text);- }- try testing.expectEqual(@as(usize, 0), Fake.calls);-}--test "quit gives a stuck op a bounded wait, then abandons it (#533/#534)" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- const op = try testing.allocator.create(Op);- defer testing.allocator.destroy(op); // the real path leaks it on purpose- op.* = .{ .kind = .bash, .gpa = testing.allocator, .threaded = true };- m.bg = op;- try testing.expectEqual(turn.QuitStep.wait, quitStep(&m, 0));- try testing.expectEqual(turn.QuitStep.abandon, quitStep(&m, turn.quit_drain_ms));- op.done.store(true, .release);- try testing.expectEqual(turn.QuitStep.reap, quitStep(&m, turn.quit_drain_ms));- abandon(&m);- try testing.expect(m.bg == null);-}diff --git a/TUI/catalog.zig b/TUI/catalog.zigdeleted file mode 100644index c0443c1b..00000000--- a/TUI/catalog.zig+++ /dev/null@@ -1,152 +0,0 @@-//! Slash / palette catalog: Grok Build's pager commands plus the harness-//! session set, so `/` and Ctrl+P feel like grok and still drive codegraff.--const std = @import("std");--pub const Item = struct {- name: []const u8,- desc: []const u8,- aliases: []const []const u8 = &.{},-};--pub const items = [_]Item{- .{ .name = "/new", .desc = "Start a fresh session", .aliases = &.{"/clear"} },- .{ .name = "/resume", .desc = "Resume or branch a saved session" },- .{ .name = "/home", .desc = "Return to the welcome screen", .aliases = &.{"/welcome"} },- .{ .name = "/compact", .desc = "Engine-compact model-visible history" },- .{ .name = "/context", .desc = "Show context-window use" },- .{ .name = "/session-info", .desc = "Session details", .aliases = &.{ "/status", "/info" } },- .{ .name = "/version", .desc = "Running binary and latest release status" },- .{ .name = "/usage", .desc = "Token usage and cost", .aliases = &.{"/cost"} },- .{ .name = "/update", .desc = "Install a release for the next launch (this session keeps running)" },- .{ .name = "/debug", .desc = "Live observability HUD" },- .{ .name = "/cache", .desc = "Prompt-cache posture and remaining max levers" },- .{ .name = "/rewind", .desc = "Undo the last turn", .aliases = &.{"/undo"} },- .{ .name = "/quit", .desc = "Quit", .aliases = &.{ "/exit", "/q" } },- .{ .name = "/rename", .desc = "Rename this session", .aliases = &.{"/title"} },- .{ .name = "/model", .desc = "Switch model", .aliases = &.{ "/m", "/models" } },- .{ .name = "/settings", .desc = "Model, effort, mode, theme", .aliases = &.{ "/set", "/config" } },- .{ .name = "/effort", .desc = "Reasoning depth (menu or low|medium|…)", .aliases = &.{"/reasoning"} },- .{ .name = "/always-approve", .desc = "Skip permission prompts", .aliases = &.{ "/yolo", "/auto" } },- .{ .name = "/multiline", .desc = "Toggle multiline input", .aliases = &.{"/ml"} },- .{ .name = "/history", .desc = "Search prompt history" },- .{ .name = "/compact-mode", .desc = "Tighter padding" },- .{ .name = "/plan", .desc = "Toggle plan mode" },- .{ .name = "/theme", .desc = "Switch color theme", .aliases = &.{"/t"} },- .{ .name = "/goal", .desc = "Set, pause, resume, or clear a goal" },- .{ .name = "/goals", .desc = "Show the current goal without changing it" },- .{ .name = "/never", .desc = "Review, add, or retire project constraints", .aliases = &.{"/constraint"} },- .{ .name = "/schedule", .desc = "Fire a prompt later (30s/5m/2h)" },- .{ .name = "/adapter", .desc = "Channel-worker send / inbox" },- .{ .name = "/thinking", .desc = "Show live reasoning" },- .{ .name = "/fast", .desc = "Priority service tier" },- .{ .name = "/ultracode", .desc = "Persistent workflow mode", .aliases = &.{"/ult"} },- .{ .name = "/strict", .desc = "Every message is a tool" },- .{ .name = "/image", .desc = "Attach an image to the next message" },- .{ .name = "/paste", .desc = "Attach the clipboard image (Ctrl+V)" },- .{ .name = "/import-claude", .desc = "Adopt Claude and Cursor MCP + skills into graff folders" },- .{ .name = "/jump", .desc = "Jump to a previous turn" },- .{ .name = "/copy", .desc = "Copy the last reply to the clipboard" },- .{ .name = "/btw", .desc = "Queue an aside without interrupting" },- .{ .name = "/tell", .desc = "Message a running graff (/tell all broadcasts)" },- .{ .name = "/peek", .desc = "See what a live session is doing" },- .{ .name = "/vim-mode", .desc = "Vim keys in the scrollback", .aliases = &.{"/vim"} },- .{ .name = "/help", .desc = "List commands" },- .{ .name = "/doctor", .desc = "Health check: goal, jobs, budget" },- .{ .name = "/shortcuts", .desc = "Keyboard shortcuts", .aliases = &.{"/keys"} },-};--pub fn matches(item: Item, needle: []const u8) bool {- if (needle.len == 0) return true;- if (containsIgnoreCase(item.name, needle) or containsIgnoreCase(item.desc, needle)) return true;- for (item.aliases) |a| {- if (containsIgnoreCase(a, needle)) return true;- }- return false;-}--pub fn lookup(token: []const u8) ?Item {- for (items) |it| {- if (eqlIgnoreCase(it.name, token)) return it;- for (it.aliases) |a| {- if (eqlIgnoreCase(a, token)) return it;- }- }- return null;-}--pub fn filter(needle: []const u8, out: []usize) usize {- var n: usize = 0;- for (items, 0..) |it, i| {- if (!matches(it, needle)) continue;- if (n >= out.len) break;- out[n] = i;- n += 1;- }- return n;-}--/// Every spelling lookup() accepts, names first, for suggest().-const spellings = blk: {- var n: usize = 0;- for (items) |it| n += 1 + it.aliases.len;- var arr: [n][]const u8 = undefined;- var i: usize = 0;- for (items) |it| {- arr[i] = it.name;- i += 1;- }- for (items) |it| for (it.aliases) |a| {- arr[i] = a;- i += 1;- };- break :blk arr;-};--/// The command a mistyped `token` most likely meant (#1275), from the same-/// speller the REPL/ACP catalog uses, so `/resuem` gets one answer everywhere.-pub fn suggest(token: []const u8) ?[]const u8 {- return @import("slash_suggest").nearest(token, &spellings);-}--fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {- return std.ascii.eqlIgnoreCase(a, b);-}--fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {- if (needle.len == 0) return true;- 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;-}--test "filter: slash prefix and alias" {- var buf: [items.len]usize = undefined;- try std.testing.expect(filter("rew", &buf) >= 1);- try std.testing.expect(lookup("/undo") != null);- try std.testing.expect(lookup("/yolo") != null);- try std.testing.expect(lookup("/debug") != null);- try std.testing.expect(lookup("/cache") != null);- try std.testing.expect(lookup("/cost") != null);- try std.testing.expect(lookup("/version") != null);- try std.testing.expect(lookup("/update") != null);- try std.testing.expect(lookup("/tell") != null);- try std.testing.expect(lookup("/peek") != null);- try std.testing.expect(lookup("/constraint") != null);- try std.testing.expect(lookup("/not-a-cmd") == null);-}--test "catalog names start with slash" {- for (items) |it| try std.testing.expect(it.name.len > 1 and it.name[0] == '/');-}--test "suggest (#1275): a typo names the command; paths and noise do not" {- try std.testing.expectEqualStrings("/resume", suggest("/resuem").?);- try std.testing.expectEqualStrings("/help", suggest("/hlep").?);- try std.testing.expectEqualStrings("/settings", suggest("/setings").?);- try std.testing.expect(suggest("/banana") == null);- try std.testing.expect(suggest("/usr/bin/foo") == null);-}diff --git a/TUI/chrome.zig b/TUI/chrome.zigdeleted file mode 100644index 474a832f..00000000--- a/TUI/chrome.zig+++ /dev/null@@ -1,465 +0,0 @@-//! Top bar, prompt box, status, overlays. ANSI only.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const composer_links = @import("composer_links.zig");-const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--pub fn topBar(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- _ = width;- if (self.goal) |g| {- const clip = if (g.len > 48) g[0..48] else g;- return theme_mod.paint(a, self.theme().muted, try std.fmt.allocPrint(a, " :: Goal {s}", .{clip}));- }- if (self.session_name) |name| {- if (self.userTurnCount() == 0) return "";- return theme_mod.paint(a, self.theme().muted, try std.fmt.allocPrint(a, " {s}", .{name}));- }- return "";-}--pub fn promptBox(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- const th = self.theme();- const cols = if (width < 24) @as(usize, 80) else width;- // Between the │ │. Top/footer use the same inner so corners line up.- const inner = if (cols > 2) cols - 2 else cols;- const focused = self.focus == .prompt and self.overlay == .none;- const border = if (focused) th.focus else th.border;- var out = std.array_list.Managed(u8).init(a);- // No standing row above the composer. The one that used to sit here read- // "Image in clipboard · ctrl+v to paste" whenever a paste hook was wired at- // all — which is always — so it announced an image nobody had copied, on- // every idle frame, at the cost of a row. The affordance belongs with the- // other keys, in the footer hint (statusBar).- try out.appendSlice(border);- try out.appendSlice("╭");- var n: usize = 0;- while (n < inner) : (n += 1) try out.appendSlice("─");- try out.appendSlice("╮");- try out.appendSlice(theme_mod.reset);- try out.append('\n');- var body = std.array_list.Managed(u8).init(a);- try body.appendSlice(glyphs.caret ++ " ");- if (self.images.items.len > 0) {- try body.appendSlice(try imageChips(self, a, th.accent, th.text));- try body.appendSlice(" ");- }- // Paste/file spans get styled emphasis; otherwise allowlisted web links- // become OSC 8 targets. Both paths wrap with balanced link state per row.- if (self.input.semanticSpans().len > 0) {- try body.appendSlice(try self.input.viewStyled(a, th.accent, th.text));- } else {- const value = self.input.getValue();- if (value.len == 0) {- try body.appendSlice(try self.input.view(a));- } else {- try body.appendSlice(try composer_links.inputView(a, value, self.input.cursor));- }- }- const max_body: usize = 8;- const wrapped = try composer_links.wrap(a, body.items, inner, max_body);- var lines = std.array_list.Managed([]const u8).init(a);- var it = std.mem.splitScalar(u8, wrapped, '\n');- while (it.next()) |ln| try lines.append(ln);- for (lines.items) |ln| {- try out.appendSlice(try rowInner(a, border, th.text, ln, inner));- try out.append('\n');- }- const model = if (engine.g_model_name.len > 0) engine.g_model_name else "offline";- const provider = if (engine.g_model_provider.len > 0)- engine.g_model_provider- else if (self.status) |st|- st.provider_id- else- "";- const seat = if (provider.len > 0)- try std.fmt.allocPrint(a, "{s}/{s}", .{ provider, model })- else- model;- // The context share comes from the engine's meter and appears only once a- // turn has reported usage — a "0%" before the first response would be the- // char-counter's old habit of showing a number it had not measured (#551).- // Both fields are labeled and right-aligned to THREE columns. The footer is- // centred, so a meter ticking 9% → 10% must not slide its other labels.- var pct_buf: [64]u8 = undefined;- const pct: []const u8 = if (self.contextPercent()) |p| blk: {- const cache = if (self.status) |st| st.cachePercent() else null;- break :blk (std.fmt.bufPrint(&pct_buf, " · ctx {d: >3}% · cache {d: >3}%", .{ p, cache orelse 0 }) catch "");- } else "";- const label = try std.fmt.allocPrint(a, " {s} · {s} · {s}{s} ", .{ seat, @tagName(self.effort), self.modeSlug(), pct });- try out.appendSlice(try footer(a, border, th.muted, label, inner));- return out.items;-}--fn imageChips(self: *const Model, a: std.mem.Allocator, accent: []const u8, text: []const u8) ![]const u8 {- var chips = std.array_list.Managed(u8).init(a);- for (self.images.items, 0..) |path, i| {- if (i > 0) try chips.append(' ');- var buf: [24]u8 = undefined;- const label = try std.fmt.bufPrint(&buf, "[Image #{d}]", .{i + 1});- if (@import("image.zig").pathBacked(path)) {- try chips.appendSlice(accent);- try chips.appendSlice(label);- try chips.appendSlice(text);- } else {- try chips.appendSlice(label);- }- }- return chips.items;-}--fn rowInner(a: std.mem.Allocator, border: []const u8, fg: []const u8, text: []const u8, inner: usize) ![]const u8 {- const shown = theme_mod.takeCols(text, inner);- var pad = std.array_list.Managed(u8).init(a);- try pad.appendSlice(fg);- try pad.appendSlice(shown);- try pad.appendSlice(theme_mod.reset);- const cols = theme_mod.visibleLen(shown);- if (cols < inner) try pad.appendNTimes(' ', inner - cols);- return std.fmt.allocPrint(a, "{s}│{s}{s}{s}│{s}", .{ border, theme_mod.reset, pad.items, border, theme_mod.reset });-}--fn footer(a: std.mem.Allocator, border: []const u8, muted: []const u8, label: []const u8, inner: usize) ![]const u8 {- const shown = theme_mod.takeCols(label, inner);- const vis = theme_mod.visibleLen(shown);- const rest = if (inner > vis) inner - vis else 0;- const left = rest / 2;- const right = rest - left;- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(border);- try out.appendSlice("╰");- var i: usize = 0;- while (i < left) : (i += 1) try out.appendSlice("─");- try out.appendSlice(muted);- try out.appendSlice(shown);- try out.appendSlice(theme_mod.reset);- try out.appendSlice(border);- i = 0;- while (i < right) : (i += 1) try out.appendSlice("─");- try out.appendSlice("╯");- try out.appendSlice(theme_mod.reset);- return out.items;-}--pub fn statusBar(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- const th = self.theme();- if (self.now_ms < self.toast_until_ms and self.toast.len > 0) {- return theme_mod.paint(a, th.accent, theme_mod.takeCols(try std.fmt.allocPrint(a, " {s}", .{self.toast}), fitWidth(width)));- }- if (self.pending != null or self.bg != null) {- return hintLine(self, a, width, &.{- .{ .text = "Enter:queue" },- .{ .text = "Shift+Tab:mode" },- .{ .text = "Esc:cancel" },- .{ .text = "[stop]", .sgr = th.error_fg, .pin = true },- });- }- return hintLine(self, a, width, &.{- .{ .text = "Enter:send" },- .{ .text = "Shift+Enter:newline" },- .{ .text = "Shift+Tab:mode" },- .{ .text = "Ctrl+V:image", .want = engine.g_paste_fn != null },- .{ .text = "Ctrl+X:help" },- });-}--fn fitWidth(width: usize) usize {- return if (width == 0) 80 else width;-}--const Hint = struct {- text: []const u8,- /// Defaults to the muted token at paint time — a hint is never the accent.- sgr: []const u8 = "",- /// Reserved before anything else is measured, and painted last: the stop- /// control is the one segment a narrow terminal may not drop.- pin: bool = false,- /// False leaves the segment out entirely (an affordance that is not wired).- want: bool = true,-};--const hint_sep = " · ";--/// The footer hint, assembled from the segments that FIT.-///-/// grok-build's footer is one line that never wraps and never runs off the-/// edge. graff's was a fixed string handed to takeCols, so an 44-column-/// terminal read "Enter:send · Shift+Enter:newl" — a key name cut in half.-/// Segments are whole or absent, dropped from the right, and a pinned one keeps-/// its room reserved before the walk begins.-fn hintLine(self: *const Model, a: std.mem.Allocator, width: usize, segs: []const Hint) ![]const u8 {- const th = self.theme();- const room = fitWidth(width);- var reserved: usize = 0;- for (segs) |s| {- if (s.pin and s.want) reserved += theme_mod.visibleLen(s.text) + theme_mod.visibleLen(hint_sep);- }- var out = std.array_list.Managed(u8).init(a);- try out.append(' ');- var used: usize = 1;- var any = false;- for (segs) |s| {- if (s.pin or !s.want) continue;- const cost = theme_mod.visibleLen(s.text) + (if (any) theme_mod.visibleLen(hint_sep) else 0);- if (used + cost + reserved > room) break;- if (any) try out.appendSlice(hint_sep);- try out.appendSlice(try theme_mod.paint(a, if (s.sgr.len > 0) s.sgr else th.muted, s.text));- used += cost;- any = true;- }- for (segs) |s| {- if (!s.pin or !s.want) continue;- if (any) try out.appendSlice(hint_sep);- try out.appendSlice(try theme_mod.paint(a, if (s.sgr.len > 0) s.sgr else th.muted, s.text));- any = true;- }- // The separators are painted outside any span, so the row would otherwise- // wear whatever pen the previous paint left on it.- return theme_mod.paint(a, th.muted, out.items);-}--/// The completion menu's geometry, published so the renderer below and the-/// click map (click.zig) share ONE set of numbers instead of each deriving-/// its own. `line0` and `lines` describe the COMPOSED block, frame included:-/// the menu is a panel now, so its first row is a border and an item no-/// longer sits at the block's top line.-pub const SlashGeom = struct {- /// First item shown - the window follows the highlight.- first: usize,- /// Item rows drawn.- show: usize,- /// Items in the filtered catalogue.- n: usize,- /// Block line the first item row sits on: 1 inside a frame, else 0.- line0: usize,- /// Lines the whole block composes to, edges and window row included.- lines: usize,-};--pub fn slashWindow(self: *const Model) ?SlashGeom {- const v = self.input.getValue();- if (self.focus != .prompt or v.len == 0 or v[0] != '/') return null;- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(v, &idx);- if (n == 0) return null;- const show = @min(n, @as(usize, 8));- const sel = @min(self.slash_sel, n - 1);- // A panel too narrow to frame is returned as bare rows (panel.min_width),- // and then the first item IS the first line.- const framed = self.last_term_width >= panel.min_width;- const edges: usize = if (framed) 2 else 0;- return .{- .first = if (sel >= show) sel + 1 - show else 0,- .show = show,- .n = n,- .line0 = if (framed) 1 else 0,- .lines = show + @intFromBool(n > show) + edges,- };-}--pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- const w = slashWindow(self) orelse return "";- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- const th = self.theme();- var out = std.array_list.Managed(u8).init(a);- // Clamped selection + a window that follows it, so the highlighted row is- // always visible and always the row Enter fires (#522).- const show = w.show;- const sel = @min(self.slash_sel, n - 1);- const first = w.first;- var i: usize = first;- while (i < first + show) : (i += 1) {- const it = catalog.items[idx[i]];- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));- // One menu entry is one ROW: a click maps a screen row straight back to- // an item, so a long description is CUT, never wrapped — wrapping- // would slide every entry below it off its own row.- const line = theme_mod.takeCols(try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, it.name, it.desc }), width);- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- if (n > show) try out.appendSlice(try panel.windowRow(a, th, first, show, n));- // The same box the palette wears (overlaypane.zig). The completion menu and- // Ctrl+P show the SAME catalogue; before this one was a framed panel and- // the other bare text hanging over the transcript, which read as two- // unrelated features rather than one list reached two ways.- return panel.wrap(a, th, width, .{- .title = "Commands",- .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, catalog.items.len }),- .footer = "↑↓ move · Enter run · Esc",- .body = out.items,- });-}--test "composer footer shows the live agent mode" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- try std.testing.expect(std.mem.indexOf(u8, try promptBox(&m, a, 80), "normal") != null);- m.mode = .plan;- try std.testing.expect(std.mem.indexOf(u8, try promptBox(&m, a, 80), "plan") != null);- m.mode = .always_approve;- try std.testing.expect(std.mem.indexOf(u8, try promptBox(&m, a, 80), "auto-accept") != null);- try std.testing.expect(std.mem.indexOf(u8, try statusBar(&m, a, 80), "Enter:send") != null);- try std.testing.expect(std.mem.indexOf(u8, try statusBar(&m, a, 80), "Shift+Tab") != null);-}--test "status paints coral [stop] while a turn is pending" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(@import("engine.zig").Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- m.pending = job;- defer {- m.pending = null;- std.testing.allocator.destroy(job);- }- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try statusBar(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, text, "[stop]") != null);- try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.coral) != null);- try std.testing.expect(std.mem.indexOf(u8, text, "Esc:cancel") != null);-}--/// The overlay bodies live in overlaypane.zig — they are the panel's business,-/// not the composer's, and keeping both here put this file over its ceiling.-/// Re-exported so the frame composer still has one door to the chrome.-pub const overlay = @import("overlaypane.zig").overlay;--test "model overlay lists engine.g_model_entries with their providers" {- engine.g_model_entries = &.{- .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },- };- engine.g_model_name = "grok-4";- engine.g_model_provider = "xai";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, text, "grok-4") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") != null);- // The name and the tally ride in the panel's TOP EDGE now, not in a body row.- try std.testing.expect(std.mem.indexOf(u8, text, "Model \u{203A}") != null);- // The blind spot this fixes: the provider was nowhere on the surface.- try std.testing.expect(std.mem.indexOf(u8, text, "xai \u{B7} plan") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "openai \u{B7} api") != null);-}--test "the composer footer holds its columns as the context meter ticks" {- // The footer label is CENTRED, so a share that widened from 9% to 10%- // shifted every character of it one column mid-turn. Same class of defect- // as a two-column animation frame, same rule: the field is fixed-width.- engine.g_model_name = "grok-4";- defer engine.g_model_name = "";- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- var col: ?usize = null;- for ([_]u64{ 5, 9, 10, 99, 100 }) |pct| {- m.setStatus(.{- .model = "grok-4",- .provider_id = "xai",- .has_context = true,- .tokens = pct,- .window = 100,- .cache_read = pct / 2,- });- const box = try promptBox(&m, arena.allocator(), 80);- var it = std.mem.splitScalar(u8, box, '\n');- var footer_row: []const u8 = "";- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, "╰") != null) footer_row = ln;- }- const at = std.mem.indexOf(u8, footer_row, "grok-4") orelse return error.NoFooterLabel;- const start = theme_mod.visibleLen(footer_row[0..at]);- if (col) |want| try std.testing.expectEqual(want, start) else col = start;- try std.testing.expectEqual(@as(usize, 80), theme_mod.visibleLen(footer_row));- try std.testing.expect(std.mem.indexOf(u8, footer_row, "ctx") != null);- try std.testing.expect(std.mem.indexOf(u8, footer_row, "cache") != null);- }-}--test "composer footer prints last-turn cache hit next to context share" {- engine.g_model_name = "grok-4";- defer engine.g_model_name = "";- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- m.setStatus(.{- .model = "grok-4",- .provider_id = "xai",- .has_context = true,- .tokens = 12_345,- .window = 200_000,- .cache_read = 2048,- });- const box = try promptBox(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, box, "ctx 6%") != null);- try std.testing.expect(std.mem.indexOf(u8, box, "cache 16%") != null);-}--test "prompt box wraps a long draft onto several rows" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const long = "can we make it fit in things better if that makes sense and showcase how that looks";- try m.input.setValue(long);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const box = try promptBox(&m, arena.allocator(), 40);- try std.testing.expect(std.mem.count(u8, box, "│") >= 6);- try std.testing.expect(std.mem.indexOf(u8, box, "can we make") != null);-}--test "the composer's right border holds its column for ambiguous and wide glyphs" {- // rowInner pads from visibleLen, so a mis-measured glyph moves the wall.- // ✓/⚙ draw one cell (they used to claim two, pulling the border in); emoji- // and CJK draw two and must not push it out.- const drafts = [_][]const u8{- "✓ done ⚙ running ✗ failed ❯ next",- "🚀 ship it 🚀🚀 and keep typing until this wraps onto another row 🚀",- "你好世界你好世界你好世界你好世界你好世界你好世界你好世界你好世界",- "mixed ✓ 🚀 漢字 tail",- };- for (drafts) |draft| {- for ([_]usize{ 40, 41, 57, 80 }) |w| {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.input.setValue(draft);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const box = try promptBox(&m, arena.allocator(), w);- var it = std.mem.splitScalar(u8, box, '\n');- while (it.next()) |ln| {- if (ln.len == 0) continue;- try std.testing.expectEqual(w, theme_mod.visibleLen(ln));- }- }- }-}diff --git a/TUI/click.zig b/TUI/click.zigdeleted file mode 100644index 0c15e3b4..00000000--- a/TUI/click.zig+++ /dev/null@@ -1,204 +0,0 @@-//! Single click as an ACTION.-//!-//! Everything AROUND the press was already wired: hover.zig tints the row-//! under the pointer, the wheel scrolls, a drag paints a band and copies it,-//! and scrollbar.zig draws a thumb on the right edge. The press itself still-//! only ever did three things - focus the composer, toggle a fold, or dismiss-//! whatever overlay was up - so every list on screen looked clickable and was-//! not. This file is the missing half.-//!-//! THREE TARGETS, ONE RULE. A press answers the thing it LANDED on:-//!-//! * the scroll gutter (the last column of the band) seeks the viewport, and-//! keeps seeking while the button is held,-//! * a row of an open list picks it,-//! * a row of the slash completion menu picks that command,-//!-//! and a press that lands on none of them falls through to exactly what it did-//! before, byte for byte.-//!-//! SELECT, THEN CONFIRM. A click on a list row moves the highlight to it; a-//! click on the row that ALREADY carries the highlight fires it, like Enter.-//! That is one rule, not two, and it is also why a double click confirms-//! without a second copy of the double-click window: the first press makes the-//! row current and the second one lands on a current row. hover.zig's press-//! counter stays out of it - a list has no "one net toggle" problem to solve.-//!-//! CLICK IS NOT DRAG. A gutter press never reaches selection.zig, so it can-//! never anchor a band (a scrollbar that fought the copy gesture would be-//! worse than no scrollbar). Everywhere else the boundary is the one-//! selection.zig already owns: a press only ARMS the transcript's fold toggle-//! and records an anchor, and the instant motion proves the gesture was a-//! drag, `selection.extend` puts the fold back. So a motionless press+release-//! is a click, a press that moved is a selection, and neither ever does both.-//!-//! PRESENTATION ONLY. Which row a list highlights, where the viewport sits and-//! which command the menu offers are all screen state. What a picked row DOES-//! is not re-implemented here: a list row goes through `overlays.activate` and-//! a menu row through `dispatch.runCommand`, which are the two calls Enter-//! already makes.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const chrome = @import("chrome.zig");-const dispatch = @import("dispatch.zig");-const key_mod = @import("key.zig");-const overlays = @import("overlays.zig");-const scrollbar = @import("scrollbar.zig");-const Model = app.Model;-const Effect = app.Effect;--/// Gesture state. One flag: whether the gutter currently owns the pointer.-pub const State = struct {- /// A press landed on the scroll gutter and the button has not come up.- /// Every report until it does is a seek, and none of them is a selection.- gutter: bool = false,-};--// -------------------------------------------------------------- the gutter--/// The gutter gesture, run BEFORE selection.zig sees the report. Returns true-/// when the gutter owns this event.-///-/// A press on the track jumps toward it; the motion reports that follow keep-/// seeking, which is what makes the thumb draggable. The release ends it. A-/// motion report with NO button held (35) can only mean the release went-/// missing - a terminal that lost focus mid-drag - so it ends the gesture-/// rather than leaving the pointer captured forever.-pub fn gutterGesture(self: *Model, ev: key_mod.Mouse) bool {- if (self.click.gutter) {- if (ev.btn == 35) {- self.click.gutter = false;- return false;- }- if (!ev.down) {- self.click.gutter = false;- return true;- }- if (ev.btn == 32 or ev.btn == 0) {- seek(self, ev.y);- return true;- }- return false;- }- if (!ev.down or ev.btn != 0) return false;- if (!onGutter(self, ev)) return false;- self.click.gutter = true;- seek(self, ev.y);- return true;-}--/// Is this press on the gutter? Only while a thumb is actually SHOWING: the-/// gutter fades out of a tail-parked viewport (scrollbar.zig), and a column-/// the user cannot see must not swallow a click on the text under it.-fn onGutter(self: *const Model, ev: key_mod.Mouse) bool {- if (self.last_term_width < 2) return false;- const x: usize = if (ev.x > 0) ev.x - 1 else 0;- if (x != self.last_term_width - 1) return false;- const y: usize = if (ev.y > 0) ev.y - 1 else 0;- if (y < self.band.top or y >= self.band.top + self.band.len) return false;- return scrollbar.current(self) != null;-}--/// Put the viewport where the pointer is pointing.-///-/// The thumb is CENTRED on the row under the pointer, the way a browser's is:-/// grabbing it anywhere and dragging then moves it by the number of rows the-/// pointer moved, instead of snapping its top edge under the cursor.-///-/// The arithmetic runs in the scrollbar's own coordinates - `band.off` lines-/// above the viewport, out of `band.total` - and comes back through the one-/// door every other scroll uses (`keys.scrollBy`), so the fade clock, the-/// follow latch and the hover drop are wound exactly once, here as anywhere.-fn seek(self: *Model, row1: u16) void {- const b = self.band;- if (!b.live or b.len == 0 or b.total <= b.len) return;- const t = scrollbar.current(self) orelse return;- const y: usize = if (row1 > 0) row1 - 1 else 0;- const in_track = std.math.clamp(y, b.top, b.top + b.len - 1) - b.top;- const span = b.len - t.len; // rows the thumb's TOP can take- const max_off = b.total - b.len;- const want_top = @min(in_track -| t.len / 2, span);- const off = if (span == 0) max_off else (want_top * max_off + span / 2) / span;- // `scroll` counts from the BOTTOM, `off` from the top; the sticky header- // occludes rows the scroll never reaches, so the achievable maximum falls- // short of `max_off` by exactly those rows (render.zig).- const target = @min(max_off - off, b.total -| (b.len + self.sticky_rows));- if (target == self.scroll) return;- const d: i64 = @as(i64, @intCast(target)) - @as(i64, @intCast(self.scroll));- @import("keys.zig").scrollBy(self, std.math.lossyCast(i32, d));-}--// ---------------------------------------------------------------- the lists--/// A press that reached the click layer: the wheel, the drag and the image-/// card have all already declined it, and it is a left-button DOWN report.-/// Returns the effect when a list answered it, else null - and null is what-/// keeps every pre-existing meaning of a press intact.-pub fn press(self: *Model, ev: key_mod.Mouse) ?Effect {- const y: usize = if (ev.y > 0) ev.y - 1 else 0;- if (self.overlay == .none) return slashPress(self, y);- if (self.overlay == .image) return null; // a card, not a panel- return overlayPress(self, y);-}--/// The list item on screen row `y` of an open overlay, or null. Shared with-/// hover.zig so the tint and the click cannot disagree about what a row is.-pub fn overlayRowAt(self: *const Model, y: usize) ?usize {- const span = overlays.rowSpan(self) orelse return null;- if (y < self.mid_origin or y >= self.prompt_origin) return null;- const line = (y - self.mid_origin) + self.mid_skip;- if (line < span.line0 or line >= span.line0 + span.rows) return null;- return span.first + (line - span.line0);-}--/// A press with a list overlay up. Inside the panel it picks a row or does-/// nothing; OUTSIDE it - the backdrop under a short panel, the top bar, the-/// composer - it declines, and the press closes the overlay exactly as it-/// always has (keys.zig), which is the click-outside-to-dismiss half.-fn overlayPress(self: *Model, y: usize) ?Effect {- // An overlay with no list (help, the observability HUD, the rewind- // prompt) has no rows to pick and keeps its click-anywhere dismissal.- _ = overlays.rowSpan(self) orelse return null;- if (y < self.mid_origin or y >= self.prompt_origin) return null;- const line = (y - self.mid_origin) + self.mid_skip;- if (line >= self.mid_total) return null; // padding below a short panel- const item = overlayRowAt(self, y) orelse return .stay; // title, footer: inert- return overlays.clickRow(self, item);-}--/// A press on the slash completion menu, which sits at the TOP of the bottom-/// block - the rows `prompt_origin` names before the composer box starts. Same-/// select-then-confirm rule as an overlay list.-fn slashPress(self: *Model, y: usize) ?Effect {- if (self.slash_rows == 0) return null;- if (y < self.prompt_origin or y >= self.prompt_origin + self.slash_rows) return null;- const w = chrome.slashWindow(self) orelse return null;- // The menu is a PANEL: its first line is a border, its last is another,- // and a windowed list spends one more on the "N below" row. Work in block- // lines, not screen rows. A short terminal trims the bottom block from the- // TOP (render.zig), so the first line still on screen is not line 0.- const trimmed = w.lines -| self.slash_rows;- const line = (y - self.prompt_origin) + trimmed;- if (line < w.line0 or line >= w.line0 + w.show) return null; // an edge- const item = w.first + (line - w.line0);- if (item >= w.n) return null;- if (@min(self.slash_sel, w.n - 1) != item) {- self.slash_sel = item;- return .stay;- }- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- if (n == 0 or item >= n) return .stay;- const pick = catalog.items[idx[item]];- self.input.setValue("") catch {};- return dispatch.runCommand(self, pick.name);-}--test {- // The tests live next door so this file stays under the ceiling. Without- // this reference they compile for nobody and silently never run.- _ = @import("click_tests.zig");-}diff --git a/TUI/click_tests.zig b/TUI/click_tests.zigdeleted file mode 100644index 5a7cec24..00000000--- a/TUI/click_tests.zig+++ /dev/null@@ -1,537 +0,0 @@-//! Single-click semantics (click.zig), pinned.-//!-//! Four boundaries live here, and every one of them is a place the gesture-//! could quietly do the wrong thing:-//!-//! * a fold header answers a click with EXACTLY one net toggle, however fast-//! the second click arrives,-//! * a press that MOVED is a selection and never a fold toggle; a press that-//! did not is a click and never touches the clipboard,-//! * the scroll gutter owns its column before the selection can anchor in-//! it, and gives the pointer back on the button-up,-//! * a list row picks, the row that already carries the highlight confirms,-//! and the backdrop around the panel dismisses it.-//!-//! The overlay cases drive a REAL composed frame and find their row by reading-//! it back, so the click map (overlays.rowSpan) is checked against the bytes-//! the renderer actually produced rather than against a second opinion.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const chrome = @import("chrome.zig");-const engine = @import("engine.zig");-const hover = @import("hover.zig");-const keys = @import("keys.zig");-const overlays = @import("overlays.zig");-const render_mod = @import("render.zig");-const scrollbar = @import("scrollbar.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--const alloc = std.testing.allocator;-const expect = std.testing.expect;-const expectEqual = std.testing.expectEqual;--fn press(m: *Model, x: u16, y: u16) app.Effect {- return keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = true } });-}--fn release(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = false } });-}--fn motion(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 32, .x = x, .y = y, .down = true } });-}--/// A click: press and release on the SAME cell with nothing in between.-fn clickAt(m: *Model, x: u16, y: u16) app.Effect {- const e = press(m, x, y);- release(m, x, y);- return e;-}--fn frame(m: *Model, w: usize, h: usize) ![]const u8 {- return render_mod.render(m, alloc, w, h, m.now_ms);-}--/// The text of screen row `y1` (1-based, as a mouse report numbers it).-fn rowText(f: []const u8, y1: u16) ?[]const u8 {- var r: usize = 0;- var it = std.mem.splitScalar(u8, f, '\n');- while (it.next()) |ln| : (r += 1) {- if (r == @as(usize, y1) - 1) return ln;- }- return null;-}--/// The `/command` printed on a menu row, SGR and row mark stripped off.-fn commandOn(line: []const u8) ?[]const u8 {- const at = std.mem.indexOfScalar(u8, line, '/') orelse return null;- var end = at;- while (end < line.len and line[end] != ' ' and line[end] != 0x1b) end += 1;- return line[at..end];-}--/// 0-based screen row of the first frame line carrying `needle`.-fn rowOf(f: []const u8, needle: []const u8) ?usize {- var r: usize = 0;- var it = std.mem.splitScalar(u8, f, '\n');- while (it.next()) |ln| : (r += 1) {- if (std.mem.indexOf(u8, ln, needle) != null) return r;- }- return null;-}--/// A transcript with one collapsed tool group, laid out by hand so the row a-/// press lands on is arithmetic rather than a search through the frame.-fn foldModel(m: *Model) !void {- m.setup(alloc);- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.last_term_width = 80;- m.last_term_height = 24;- m.mid_origin = 1;- m.mid_skip = 0;- m.prompt_origin = 20;-}--// ------------------------------------------------------------------- folds--test "a motionless click on a fold header is exactly one net toggle" {- var m: Model = undefined;- try foldModel(&m);- defer m.deinit();- try expect(m.history.items[1].folded);- _ = clickAt(&m, 4, 3);- try expect(!m.history.items[1].folded);- // A click is not a selection: no band, no capture, no toast claiming one.- try expect(!m.sel.active);- try expect(!m.sel.pressed);- try expectEqual(@as(usize, 0), m.sel_text.len);- try std.testing.expectEqualStrings("", m.toast);- // ...and the next click, outside the double-click window, puts it back.- m.now_ms += hover.double_ms + 1;- _ = clickAt(&m, 4, 3);- try expect(m.history.items[1].folded);-}--test "two clicks inside the double-click window are ONE net toggle" {- // The pinned semantics: the first press toggles, the second REPLACES that- // action rather than repeating it, so the pair opens the group and leaves- // it open. Toggling twice would look like the gesture did nothing at all.- var m: Model = undefined;- try foldModel(&m);- defer m.deinit();- try expect(m.history.items[1].folded);- _ = clickAt(&m, 4, 3);- _ = clickAt(&m, 4, 3); // same cell, same millisecond- try expect(!m.history.items[1].folded);- // A third press, still inside the window, opens a fresh single click: the- // completed double disarmed, so the counter cannot fire twice in a row.- _ = clickAt(&m, 4, 3);- try expect(m.history.items[1].folded);-}--test "a press that MOVES is a selection, and leaves the fold as it was" {- var m: Model = undefined;- try foldModel(&m);- defer m.deinit();- try expect(m.history.items[1].folded);- _ = press(&m, 4, 3);- motion(&m, 30, 5);- // The optimistic expand is reverted the instant motion proves the drag.- try expect(m.history.items[1].folded);- try expect(m.sel.active);- // A gesture that moved can never be half of a double click either.- try expect(!m.hover.armed);- release(&m, 30, 5);- try expect(m.history.items[1].folded);-}--// --------------------------------------------------------------- the gutter--/// A transcript long enough to scroll, composed for real so the band, the-/// thumb and the viewport all agree with each other.-fn scrolledModel(m: *Model) !void {- m.setup(alloc);- var i: usize = 0;- while (i < 200) : (i += 1) {- var buf: [32]u8 = undefined;- try m.push(.assistant, try std.fmt.bufPrint(&buf, "line {d:0>3}", .{i}));- }- const first = try frame(m, 80, 24);- alloc.free(first);- keys.scrollBy(m, 40);- const second = try frame(m, 80, 24);- alloc.free(second);-}--test "a press on the gutter seeks the viewport and never anchors a band" {- var m: Model = undefined;- try scrolledModel(&m);- defer m.deinit();- try expect(m.band.live);- try expect(scrollbar.current(&m) != null);- const track_top: u16 = @intCast(m.band.top + 1);- const track_bottom: u16 = @intCast(m.band.top + m.band.len);- // The bottom of the track is the tail of the transcript.- _ = press(&m, 80, track_bottom);- try expect(m.click.gutter);- try expectEqual(@as(usize, 0), m.scroll);- try expect(m.follow);- // A scrollbar gesture is never a drag-copy, and never a fold toggle.- try expect(!m.sel.pressed);- try expect(!m.sel.active);- try expectEqual(app.Focus.prompt, m.focus);- release(&m, 80, track_bottom);- try expect(!m.click.gutter);- // ...and the top of the track is the top of the transcript.- _ = press(&m, 80, track_top);- const f = try frame(&m, 80, 24);- defer alloc.free(f);- try expectEqual(@as(usize, 0), m.band.off -| m.sticky_rows);- try expect(rowOf(f, "line 000") != null);- release(&m, 80, track_top);-}--test "a drag down the gutter walks the viewport, one report at a time" {- var m: Model = undefined;- try scrolledModel(&m);- defer m.deinit();- const track_top: u16 = @intCast(m.band.top + 1);- _ = press(&m, 80, track_top);- try expect(m.click.gutter);- const at_top = m.scroll;- var y = track_top;- var last = at_top;- while (y < @as(u16, @intCast(m.band.top + m.band.len))) : (y += 1) {- motion(&m, 80, y + 1);- // Monotone: dragging DOWN the track only ever moves toward the tail.- try expect(m.scroll <= last);- last = m.scroll;- // Still the gutter's pointer — the motion never became a selection.- try expect(!m.sel.active);- }- try expect(last < at_top);- release(&m, 80, @intCast(m.band.top + m.band.len));- try expect(!m.click.gutter);-}--test "a faded gutter is not a target: the press means what it always meant" {- var m: Model = undefined;- try scrolledModel(&m);- defer m.deinit();- keys.scrollBy(&m, -1000); // back to the tail- const f = try frame(&m, 80, 24);- alloc.free(f);- m.now_ms += scrollbar.fade_ms + 1;- try expect(scrollbar.current(&m) == null);- const row: u16 = @intCast(m.band.top + 2);- _ = press(&m, 80, row);- try expect(!m.click.gutter);- try expectEqual(@as(usize, 0), m.scroll);- // The ordinary transcript press ran instead.- try expectEqual(app.Focus.scrollback, m.focus);- release(&m, 80, row);-}--test "a key hands the pointer back when the gutter's release goes missing" {- var m: Model = undefined;- try scrolledModel(&m);- defer m.deinit();- _ = press(&m, 80, @intCast(m.band.top + 1));- try expect(m.click.gutter);- _ = keys.handle(&m, .{ .char = 'x' });- try expect(!m.click.gutter);-}--// -------------------------------------------------------------- list rows--fn modelOverlay(m: *Model) !void {- m.setup(alloc);- m.openOverlay(.model);-}--/// The catalog the click tests pick through. Entries now, not a joined string:-/// the picker reads `engine.g_model_entries` (the provider column lives there).-const click_catalog = [_]engine.ModelEntry{- .{ .name = "alpha-one", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "beta-two", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "gamma-three", .provider = "openai", .has_key = true, .cost = .api },-};--test "a click on a model row highlights it, and a second click picks it" {- engine.g_model_entries = &click_catalog;- engine.g_model_name = "alpha-one";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- }- var m: Model = undefined;- try modelOverlay(&m);- defer m.deinit();- const f = try frame(&m, 80, 24);- defer alloc.free(f);- const row = rowOf(f, "gamma-three") orelse return error.NoModelRow;- _ = press(&m, 3, @intCast(row + 1));- try expectEqual(app.Overlay.model, m.overlay); // selecting is not picking- try expectEqual(@as(usize, 2), m.overlay_sel);- _ = press(&m, 3, @intCast(row + 1));- try expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqualStrings("gamma-three", engine.g_model_name);-}--test "the panel keeps a press, and the backdrop around it dismisses" {- engine.g_model_entries = &click_catalog;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- try modelOverlay(&m);- defer m.deinit();- const f = try frame(&m, 80, 24);- defer alloc.free(f);- // The title is inside the panel: inert, and the overlay stays up.- const title = rowOf(f, "Model ›") orelse return error.NoTitle;- _ = press(&m, 3, @intCast(title + 1));- try expectEqual(app.Overlay.model, m.overlay);- try expectEqual(@as(usize, 0), m.overlay_sel);- // The panel DOCKS to the composer (render.zig), so the backdrop is the- // empty band ABOVE it - and a press up there closes it exactly like Esc.- try expect(m.mid_origin > 0);- const above: u16 = @intCast(m.mid_origin - 1);- _ = press(&m, 3, above);- try expectEqual(app.Overlay.none, m.overlay);-}--test "an overlay with no rows to pick still closes on any press" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.help);- const f = try frame(&m, 80, 24);- alloc.free(f);- try expect(overlays.rowSpan(&m) == null);- _ = press(&m, 10, @intCast(m.mid_origin + 3));- try expectEqual(app.Overlay.none, m.overlay);-}--test "a settings row opens the picker it names" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.settings);- const f = try frame(&m, 80, 24);- defer alloc.free(f);- const row = rowOf(f, "Theme") orelse return error.NoSettingsRow;- _ = press(&m, 3, @intCast(row + 1)); // highlight- try expectEqual(@as(usize, 3), m.overlay_sel);- _ = press(&m, 3, @intCast(row + 1)); // confirm- try expectEqual(app.Overlay.theme, m.overlay);-}--test "hover announces a list row, so the tint and the click agree" {- engine.g_model_entries = &click_catalog;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- try modelOverlay(&m);- defer m.deinit();- const f = try frame(&m, 80, 24);- defer alloc.free(f);- const row = rowOf(f, "beta-two") orelse return error.NoModelRow;- const hit = hover.hitTest(&m, row);- try expectEqual(hover.Target.row, hit.target);- try expectEqual(@as(?usize, 1), hit.idx);- // The title is not a target — an affordance on a row a press ignores- // would be worse than none.- const title = rowOf(f, "Model ›") orelse return error.NoTitle;- try expectEqual(hover.Target.none, hover.hitTest(&m, title).target);-}--// ------------------------------------------------------------ slash menu--test "a click on a completion row highlights it, and on the current one runs it" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.focus = .prompt;- try m.input.setValue("/");- const f = try frame(&m, 80, 24);- defer alloc.free(f);- try expect(m.slash_rows > 2);- try expectEqual(@as(usize, 0), m.slash_sel);- // Round-trip against the BYTES: read the command printed on the row that- // is about to be clicked, then check the highlight landed on that same- // command. The menu is a framed panel, so a click map that forgot the- // border would select a neighbour and still look arithmetically tidy.- const target_row: u16 = @intCast(m.prompt_origin + 3);- const printed = rowText(f, target_row) orelse return error.NoMenuRow;- const name = commandOn(printed) orelse return error.NoCommandOnRow;- _ = press(&m, 3, target_row);- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(m.input.getValue(), &idx);- try expect(m.slash_sel < n);- try std.testing.expectEqualStrings(name, catalog.items[idx[m.slash_sel]].name);- // ...and the draft is untouched: highlighting is not running.- try std.testing.expectEqualStrings("/", m.input.getValue());-}--test "a click on the highlighted completion row runs that command" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.focus = .prompt;- try m.input.setValue("/plan");- const f = try frame(&m, 80, 24);- defer alloc.free(f);- const w = chrome.slashWindow(&m) orelse return error.NoMenu;- try expectEqual(@as(usize, 1), w.n);- // One item, and the two panel edges around it.- try expectEqual(@as(usize, 1), w.show);- try expectEqual(w.lines, m.slash_rows);- try expectEqual(app.AgentMode.normal, m.mode);- // +2, not +1: the row under the panel's TOP EDGE is the item.- _ = press(&m, 3, @intCast(m.prompt_origin + 2));- try expectEqual(app.AgentMode.plan, m.mode);- try std.testing.expectEqualStrings("", m.input.getValue());-}--// ------------------------------------------------------- the map vs the bytes--/// Every body line fits the width, and the span's rows carry `want` in order.-/// This is the drift guard: `rowSpan` states each renderer's header shape as-/// arithmetic, and the day a renderer grows a line the arithmetic is a lie —-/// clicks would land one row off, silently, on the wrong item.-fn checkSpan(m: *Model, width: usize, want: []const []const u8) !void {- var arena = std.heap.ArenaAllocator.init(alloc);- defer arena.deinit();- const body = try chrome.overlay(m, arena.allocator(), width);- var lines = std.array_list.Managed([]const u8).init(arena.allocator());- var it = std.mem.splitScalar(u8, body, '\n');- while (it.next()) |ln| try lines.append(ln);- // A list row is CUT, never wrapped: one item is one line, or the map that- // turns a screen row into an item index cannot be arithmetic at all.- for (lines.items) |ln| try expect(theme_mod.visibleLen(ln) <= width);- const span = overlays.rowSpan(m) orelse return error.NoSpan;- try expectEqual(want.len, span.rows);- for (want, 0..) |text, k| {- const ln = lines.items[span.line0 + k];- if (std.mem.indexOf(u8, ln, text) == null) {- std.debug.print("row {d} (body line {d}) = {s}\n", .{ k, span.line0 + k, ln });- return error.RowDrifted;- }- }-}--test "the click map names the rows the model picker drew" {- engine.g_model_entries = &click_catalog;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.model);- try checkSpan(&m, 80, &.{ "alpha-one", "beta-two", "gamma-three" });-}--test "the click map names the rows the effort picker drew" {- const saved_p = engine.g_model_provider;- const saved_m = engine.g_model_name;- defer {- engine.g_model_provider = saved_p;- engine.g_model_name = saved_m;- }- engine.g_model_provider = "openai";- engine.g_model_name = "gpt-6-astra";- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.effort);- try checkSpan(&m, 80, &.{ "low", "medium", "high", "xhigh", "ultra" });-}--test "the click map names the rows the file picker drew, however long the path" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.files_cache = try alloc.dupe(u8, "src/a.zig\n" ++- "a/very/deeply/nested/directory/tree/that/runs/past/the/screen/edge/file.zig\n" ++- "docs/b.md");- m.openOverlay(.file);- try checkSpan(&m, 80, &.{ "src/a.zig", "a/very/deeply", "docs/b.md" });- // ...and at a width where the long path can only be a cut row.- try checkSpan(&m, 40, &.{ "src/a.zig", "a/very/deeply", "docs/b.md" });-}--test "the click map names the rows the settings, theme and jump panels drew" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.settings);- try checkSpan(&m, 80, &.{ "Model", "Effort", "Mode", "Theme" });- m.openOverlay(.theme);- var want: [theme_mod.all.len][]const u8 = undefined;- for (theme_mod.all, 0..) |id, i| want[i] = id.label();- try checkSpan(&m, 80, &want);- try m.push(.user, "first turn");- try m.push(.assistant, "ok");- try m.push(.user, "second turn");- m.openOverlay(.jump);- try checkSpan(&m, 80, &.{ "first turn", "second turn" });-}--test "the click map names the rows the resume picker drew" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.sessions_cache = try alloc.dupe(u8, "alpha\tAlpha title\t2h ago\nbeta\tbeta\tjust now");- m.openOverlay(.sessions);- try checkSpan(&m, 80, &.{ "Alpha title", "beta" });-}--test "the click map names the rows the command palette drew" {- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.palette);- try m.input.setValue("/th");- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter("/th", &idx);- try expect(n > 0 and n <= 12);- var want = std.array_list.Managed([]const u8).init(alloc);- defer want.deinit();- for (idx[0..n]) |i| try want.append(catalog.items[i].name);- try checkSpan(&m, 80, want.items);-}--test "a click on a SCROLLED overlay body still names the row under it" {- // The picker's window follows the highlight and the body itself scrolls- // once it outgrows the viewport, so both offsets have to be in the map.- var arena = std.heap.ArenaAllocator.init(alloc);- defer arena.deinit();- var list = std.array_list.Managed(engine.ModelEntry).init(arena.allocator());- for (0..40) |i| {- try list.append(.{- .name = try std.fmt.allocPrint(arena.allocator(), "mdl-{d:0>2}", .{i}),- .provider = "openai",- .has_key = true,- .cost = .api,- });- }- engine.g_model_entries = list.items;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- m.setup(alloc);- defer m.deinit();- m.openOverlay(.model);- m.overlay_sel = 30; // window scrolled well down the list- m.overlay_scroll = 3; // ...and the panel is taller than this viewport- const f = try frame(&m, 80, 12);- defer alloc.free(f);- try expect(m.mid_skip > 0); // the body scrolled too- const row = rowOf(f, "mdl-25") orelse return error.NoModelRow;- _ = press(&m, 3, @intCast(row + 1));- try expectEqual(@as(usize, 25), m.overlay_sel);- try expectEqual(app.Overlay.model, m.overlay);-}diff --git a/TUI/clipboard_recovery.zig b/TUI/clipboard_recovery.zigdeleted file mode 100644index 643b0331..00000000--- a/TUI/clipboard_recovery.zig+++ /dev/null@@ -1,122 +0,0 @@-//! Pending clipboard exports carry a locked recovery record until release/send.-const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;-const private_dir: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) .fromMode(0o700) else .default_dir;-const private_file: Io.File.Permissions = if (Io.File.Permissions.has_executable_bit) .fromMode(0o600) else .default_file;--const Record = struct {- version: u8 = 1,- path: []const u8,- // File identifiers are signed on Windows and unsigned on POSIX.- inode: i128,- size: u64,- mtime: i96,- ctime: i96,-};--pub const Lease = struct {- file: Io.File,- name: [40]u8,-};--pub const Store = struct {- dir: Io.Dir,- cursor: Io.Dir.Iterator,- io: Io,- alloc: Allocator,-- pub fn init(io: Io, alloc: Allocator, root: []const u8) !Store {- try Io.Dir.cwd().createDirPath(io, root);- const dir = try Io.Dir.cwd().openDir(io, root, .{ .iterate = true, .follow_symlinks = false });- errdefer dir.close(io);- try dir.setPermissions(io, private_dir);- return .{ .dir = dir, .cursor = dir.iterate(), .io = io, .alloc = alloc };- }-- pub fn deinit(self: *Store) void {- self.dir.close(self.io);- }-- pub fn record(self: *Store, file_path: []const u8, stat: Io.File.Stat) !Lease {- if (!std.fs.path.isAbsolute(file_path) or stat.kind != .file) return error.InvalidExport;- var raw: [16]u8 = undefined;- self.io.random(&raw);- const hex = std.fmt.bytesToHex(raw, .lower);- var name: [40]u8 = undefined;- @memcpy(name[0..32], &hex);- @memcpy(name[32..], ".pending");- const file = try self.dir.createFile(self.io, &name, .{- .read = true,- .exclusive = true,- .permissions = private_file,- .lock = .exclusive,- .lock_nonblocking = true,- });- errdefer file.close(self.io);- errdefer self.dir.deleteFile(self.io, &name) catch {};- const bytes = try std.json.Stringify.valueAlloc(self.alloc, Record{- .path = file_path,- .inode = stat.inode,- .size = stat.size,- .mtime = stat.mtime.nanoseconds,- .ctime = stat.ctime.nanoseconds,- }, .{});- defer self.alloc.free(bytes);- try file.writeStreamingAll(self.io, bytes);- try file.sync(self.io);- return .{ .file = file, .name = name };- }-- /// Remove recovery authority before a submitted image can reach a worker.- /// Failure must prevent the handoff; closing a still-pending lease is unsafe.- pub fn retain(self: *Store, lease: *?Lease) !void {- const held = lease.* orelse return;- try self.dir.deleteFile(self.io, &held.name);- held.file.close(self.io);- lease.* = null;- }-- pub fn release(self: *Store, lease: *?Lease) void {- const held = lease.* orelse return;- self.dir.deleteFile(self.io, &held.name) catch {};- held.file.close(self.io);- lease.* = null;- }-- /// A rolling cursor bounds directory work too, including invalid records.- pub fn sweep(self: *Store, limit: usize) usize {- var removed: usize = 0;- for (0..limit) |_| {- const entry = (self.cursor.next(self.io) catch return removed) orelse {- self.cursor = self.dir.iterate();- break;- };- if (entry.kind != .file or entry.name.len != 40 or !std.mem.endsWith(u8, entry.name, ".pending")) continue;- const file = self.dir.openFile(self.io, entry.name, .{- .mode = .read_write,- .follow_symlinks = false,- .lock = .exclusive,- .lock_nonblocking = true,- }) catch continue;- defer file.close(self.io);- var buffer: [8192]u8 = undefined;- const n = file.readPositionalAll(self.io, &buffer, 0) catch continue;- if (n == buffer.len) continue;- const parsed = std.json.parseFromSlice(Record, self.alloc, buffer[0..n], .{}) catch continue;- defer parsed.deinit();- const r = parsed.value;- if (r.version != 1 or !std.fs.path.isAbsolute(r.path)) continue;- const stat = Io.Dir.cwd().statFile(self.io, r.path, .{ .follow_symlinks = false }) catch |err| {- if (err == error.FileNotFound) self.dir.deleteFile(self.io, entry.name) catch {};- continue;- };- if (stat.kind != .file or stat.inode != r.inode or stat.size != r.size or- stat.mtime.nanoseconds != r.mtime or stat.ctime.nanoseconds != r.ctime) continue;- Io.Dir.cwd().deleteFile(self.io, r.path) catch continue;- self.dir.deleteFile(self.io, entry.name) catch {};- removed += 1;- }- return removed;- }-};diff --git a/TUI/composer_links.zig b/TUI/composer_links.zigdeleted file mode 100644index 6cd4c3d4..00000000--- a/TUI/composer_links.zig+++ /dev/null@@ -1,445 +0,0 @@-//! Safe OSC 8 links for the editable composer.-//!-//! The transcript has its own Markdown renderer. The composer must preserve the-//! draft byte-for-byte, including cursor position, while making supported web-//! addresses clickable across application-inserted row breaks.--const std = @import("std");-const glyphs = @import("glyphs.zig");-const theme = @import("theme.zig");--const osc_open_prefix = "\x1b]8;id=graff-composer-";-const osc_close = "\x1b]8;;\x07";--const Link = struct {- end: usize,- www: bool,-};--const Found = struct {- start: usize,- link: Link,-};--/// Render the raw draft with its cursor and allowlisted OSC 8 spans. The cursor-/// is never part of the destination; when it bisects a link, the same link is-/// closed around the glyph and reopened on the other side.-pub fn inputView(a: std.mem.Allocator, value: []const u8, cursor: usize) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- errdefer out.deinit();- const cur = cursorBoundary(value, cursor);- var cursor_drawn = false;- var i: usize = 0;- while (nextLink(value, i)) |found| {- try appendPlain(&out, value[i..found.start], i, cur, &cursor_drawn);- try appendLinked(&out, value, found.start, found.link, cur, &cursor_drawn);- i = found.link.end;- }- try appendPlain(&out, value[i..], i, cur, &cursor_drawn);- if (!cursor_drawn) try out.appendSlice(glyphs.cursor);- return out.toOwnedSlice();-}--const Row = struct {- bytes: []const u8,- active_at_start: ?[]const u8,-};--/// Word-wrap a composer body and retain only its visible tail. Generated links-/// are balanced on every retained row, so padding, borders, and independently-/// painted frames cannot inherit hyperlink state. Bounding before serialization-/// also keeps a pasted N-byte URL O(N): its full target is repeated at most-/// `max_rows` times, never once for every discarded continuation row.-pub fn wrap(a: std.mem.Allocator, body: []const u8, width: usize, max_rows: usize) ![]const u8 {- if (max_rows == 0) return a.dupe(u8, "");- const wrapped = try theme.wrapPreferWords(a, body, width);- defer a.free(wrapped);- var rows = std.array_list.Managed(Row).init(a);- defer rows.deinit();- var active: ?[]const u8 = null;- var active_at_start: ?[]const u8 = null;- var row_start: usize = 0;- var i: usize = 0;- while (i < wrapped.len) {- if (wrapped[i] == '\n') {- try keepRow(&rows, max_rows, .{ .bytes = wrapped[row_start..i], .active_at_start = active_at_start });- row_start = i + 1;- active_at_start = active;- i += 1;- continue;- }- if (wrapped[i] == 0x1b) {- const end = theme.skipEsc(wrapped, i);- noteLink(wrapped[i..end], &active);- i = end;- continue;- }- i += 1;- }- try keepRow(&rows, max_rows, .{ .bytes = wrapped[row_start..], .active_at_start = active_at_start });-- var out = std.array_list.Managed(u8).init(a);- errdefer out.deinit();- for (rows.items, 0..) |row, row_no| {- var row_active = row.active_at_start;- if (row_active) |open| try out.appendSlice(open);- i = 0;- while (i < row.bytes.len) {- if (row.bytes[i] == 0x1b) {- const end = theme.skipEsc(row.bytes, i);- const seq = row.bytes[i..end];- try out.appendSlice(seq);- noteLink(seq, &row_active);- i = end;- continue;- }- try out.append(row.bytes[i]);- i += 1;- }- if (row_active != null) try out.appendSlice(osc_close);- if (row_no + 1 < rows.items.len) try out.append('\n');- }- return out.toOwnedSlice();-}--fn keepRow(rows: *std.array_list.Managed(Row), max_rows: usize, row: Row) !void {- if (rows.items.len == max_rows) _ = rows.orderedRemove(0);- try rows.append(row);-}--fn noteLink(seq: []const u8, active: *?[]const u8) void {- if (std.mem.startsWith(u8, seq, osc_open_prefix)) {- active.* = seq;- } else if (active.* != null and std.mem.eql(u8, seq, osc_close)) {- active.* = null;- }-}--fn cursorBoundary(value: []const u8, cursor: usize) usize {- var cur = @min(cursor, value.len);- while (cur > 0 and cur < value.len and value[cur] & 0xc0 == 0x80) cur -= 1;- return cur;-}--fn appendPlain(out: *std.array_list.Managed(u8), text: []const u8, base: usize, cursor: usize, drawn: *bool) !void {- if (!drawn.* and cursor >= base and cursor < base + text.len) {- const at = cursor - base;- try out.appendSlice(text[0..at]);- try out.appendSlice(glyphs.cursor);- try out.appendSlice(text[at..]);- drawn.* = true;- } else {- try out.appendSlice(text);- }-}--fn appendLinked(out: *std.array_list.Managed(u8), value: []const u8, start: usize, link: Link, cursor: usize, drawn: *bool) !void {- const split = !drawn.* and cursor >= start and cursor < link.end;- if (!split or cursor > start) {- try appendOpen(out, value[start..link.end], start, link.www);- try out.appendSlice(value[start..if (split) cursor else link.end]);- try out.appendSlice(osc_close);- }- if (split) {- try out.appendSlice(glyphs.cursor);- drawn.* = true;- if (cursor < link.end) {- try appendOpen(out, value[start..link.end], start, link.www);- try out.appendSlice(value[cursor..link.end]);- try out.appendSlice(osc_close);- }- }-}--fn appendOpen(out: *std.array_list.Managed(u8), visible: []const u8, id: usize, www: bool) !void {- var id_buf: [32]u8 = undefined;- const number = try std.fmt.bufPrint(&id_buf, "{d};", .{id});- try out.appendSlice(osc_open_prefix);- try out.appendSlice(number);- if (www) try out.appendSlice("https://");- try out.appendSlice(visible);- try out.append(0x07);-}--fn nextLink(s: []const u8, from: usize) ?Found {- var i = from;- while (i < s.len) {- const candidate = leftBoundary(s, i) and (startsIgnoreCase(s[i..], "http://") or startsIgnoreCase(s[i..], "https://") or startsIgnoreCase(s[i..], "www."));- if (candidate) {- if (linkAt(s, i)) |link| return .{ .start = i, .link = link };- i = tokenEnd(s, i);- continue;- }- i += 1;- }- return null;-}--fn linkAt(s: []const u8, start: usize) ?Link {- if (!leftBoundary(s, start)) return null;- const http_len: usize = if (startsIgnoreCase(s[start..], "https://")) 8 else if (startsIgnoreCase(s[start..], "http://")) 7 else 0;- const www = http_len == 0 and startsIgnoreCase(s[start..], "www.");- if (http_len == 0 and !www) return null;- var end = tokenEnd(s, start);- end = trimOuterDelimiters(s, start, end);- if (end <= start + if (www) @as(usize, 4) else http_len) return null;- if (www) {- if (!validWwwHost(s[start + 4 .. authorityEnd(s, start + 4, end)])) return null;- } else if (!validAuthority(s[start + http_len .. authorityEnd(s, start + http_len, end)])) {- return null;- }- return .{ .end = end, .www = www };-}--fn leftBoundary(s: []const u8, start: usize) bool {- if (start == 0) return true;- const c = s[start - 1];- if (c == '_') {- var run = start - 1;- while (run > 0 and s[run - 1] == '_') run -= 1;- return run == 0 or !std.ascii.isAlphanumeric(s[run - 1]);- }- if (c >= 0x80 or std.ascii.isAlphanumeric(c)) return false;- return std.mem.indexOfScalar(u8, ".-/:@%", c) == null;-}--fn tokenEnd(s: []const u8, start: usize) usize {- var i = start;- while (i < s.len) {- const c = s[i];- if (c < 0x20 or c == 0x7f or std.ascii.isWhitespace(c)) break;- const len = std.unicode.utf8ByteSequenceLength(c) catch 1;- const step = @min(@as(usize, len), s.len - i);- const cp = std.unicode.utf8Decode(s[i .. i + step]) catch {- i += step;- continue;- };- if (unicodeSpace(cp)) break;- i += step;- }- return i;-}--fn unicodeSpace(cp: u21) bool {- return cp == 0x00a0 or cp == 0x1680 or cp == 0x2028 or cp == 0x2029 or cp == 0x202f or cp == 0x205f or cp == 0x3000 or (cp >= 0x2000 and cp <= 0x200a);-}--fn trimOuterDelimiters(s: []const u8, start: usize, initial_end: usize) usize {- var structural_end = initial_end;- while (structural_end > start and std.mem.indexOfScalar(u8, ".,", s[structural_end - 1]) != null) structural_end -= 1;-- var wrapper_end = trimMatchingWrapper(s, start, structural_end);- if (wrapper_end != structural_end) {- while (wrapper_end > start and std.mem.indexOfScalar(u8, ".,", s[wrapper_end - 1]) != null) wrapper_end -= 1;- return wrapper_end;- }-- var end = structural_end;- for ([_]struct { open: u8, close: u8 }{- .{ .open = '(', .close = ')' },- .{ .open = '[', .close = ']' },- .{ .open = '{', .close = '}' },- }) |pair| {- const opens = countByte(s[start..end], pair.open);- var closes = countByte(s[start..end], pair.close);- while (end > start and s[end - 1] == pair.close and closes > opens) {- end -= 1;- closes -= 1;- }- }- if (end != structural_end) return end;-- if (start > 0 and end > start) {- const before = s[start - 1];- if ((before == '<' and s[end - 1] == '>') or- (before == '\'' and s[end - 1] == '\'') or- (before == '"' and s[end - 1] == '"')) return end - 1;- }- return structural_end;-}--fn trimMatchingWrapper(s: []const u8, start: usize, initial_end: usize) usize {- if (start == 0 or initial_end <= start) return initial_end;- const mark = s[start - 1];- if (std.mem.indexOfScalar(u8, "*_~`", mark) == null) return initial_end;- var opens: usize = 0;- var i = start;- while (i > 0 and s[i - 1] == mark) : (i -= 1) opens += 1;- var closes: usize = 0;- i = initial_end;- while (i > start and s[i - 1] == mark and closes < opens) : (i -= 1) closes += 1;- return initial_end - closes;-}--fn authorityEnd(s: []const u8, start: usize, end: usize) usize {- var i = start;- while (i < end and std.mem.indexOfScalar(u8, "/?#", s[i]) == null) : (i += 1) {}- return i;-}--fn validAuthority(authority: []const u8) bool {- if (authority.len == 0) return false;- for (authority) |c| if (c < 0x21 or c == 0x7f or std.mem.indexOfScalar(u8, "<>\"'", c) != null) return false;- const host_port = if (std.mem.lastIndexOfScalar(u8, authority, '@')) |at| authority[at + 1 ..] else authority;- return validHostPort(host_port, false);-}--fn validWwwHost(host_port: []const u8) bool {- return validHostPort(host_port, true);-}--fn validHostPort(host_port: []const u8, require_dot: bool) bool {- if (host_port.len == 0) return false;- if (host_port[0] == '[') {- const close = std.mem.indexOfScalar(u8, host_port, ']') orelse return false;- if (close == 1 or !validIpv6(host_port[1..close])) return false;- return close + 1 == host_port.len or (host_port[close + 1] == ':' and validPort(host_port[close + 2 ..]));- }- const colon = std.mem.lastIndexOfScalar(u8, host_port, ':');- const host = if (colon) |at| host_port[0..at] else host_port;- if (std.mem.indexOfScalar(u8, host, ':') != null or !validHost(host, require_dot)) return false;- return if (colon) |at| validPort(host_port[at + 1 ..]) else true;-}--fn validHost(host: []const u8, require_dot: bool) bool {- if (host.len == 0 or host.len > 253) return false;- var labels = std.mem.splitScalar(u8, host, '.');- var count: usize = 0;- while (labels.next()) |label| {- if (label.len == 0 or label.len > 63 or label[0] == '-' or label[label.len - 1] == '-') return false;- for (label) |c| if (!std.ascii.isAlphanumeric(c) and c != '-') return false;- count += 1;- }- return !require_dot or count > 1;-}--fn validIpv6(host: []const u8) bool {- _ = std.Io.net.IpAddress.parseIp6(host, 0) catch return false;- return true;-}--fn validPort(port: []const u8) bool {- if (port.len == 0) return false;- for (port) |c| if (!std.ascii.isDigit(c)) return false;- _ = std.fmt.parseInt(u16, port, 10) catch return false;- return true;-}--fn startsIgnoreCase(s: []const u8, prefix: []const u8) bool {- return s.len >= prefix.len and std.ascii.eqlIgnoreCase(s[0..prefix.len], prefix);-}--fn countByte(s: []const u8, needle: u8) usize {- var n: usize = 0;- for (s) |c| {- if (c == needle) n += 1;- }- return n;-}--test "composer links allowlist web targets and preserve visible text" {- const dump = @import("dump.zig");- const cases = [_]struct { source: []const u8, target: ?[]const u8 }{- .{ .source = "http://example.test/path", .target = "http://example.test/path" },- .{ .source = "HTTPS://example.test/path", .target = "HTTPS://example.test/path" },- .{ .source = "www.example.test/path", .target = "https://www.example.test/path" },- .{ .source = "https://example.test/path.", .target = "https://example.test/path" },- .{ .source = "**http://localhost:3003.**", .target = "http://localhost:3003" },- .{ .source = "_https://example.test/path_", .target = "https://example.test/path" },- .{ .source = "snake_case https://example.test/a_", .target = "https://example.test/a_" },- .{ .source = "https://example.test/path(a)", .target = "https://example.test/path(a)" },- .{ .source = "https://en.wikipedia.org/wiki/Yahoo!", .target = "https://en.wikipedia.org/wiki/Yahoo!" },- .{ .source = "javascript:https://example.test", .target = null },- .{ .source = "[email protected]", .target = null },- .{ .source = "file:///tmp/a", .target = null },- .{ .source = "https://:80/path", .target = null },- .{ .source = "https://a.-b.example/path", .target = null },- .{ .source = "https://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.example/path", .target = null },- .{ .source = "https://[:::]/path", .target = null },- .{ .source = "www.example.test:bad/path", .target = null },- .{ .source = "www.", .target = null },- };- for (cases) |case| {- const got = try inputView(std.testing.allocator, case.source, case.source.len);- defer std.testing.allocator.free(got);- const visible = try dump.visible(std.testing.allocator, got);- defer std.testing.allocator.free(visible);- try std.testing.expectEqual(case.source.len + glyphs.cursor.len, visible.len);- try std.testing.expect(std.mem.startsWith(u8, visible, case.source));- try std.testing.expect(std.mem.endsWith(u8, visible, glyphs.cursor));- if (case.target) |target| {- const needle = try std.fmt.allocPrint(std.testing.allocator, ";{s}\x07", .{target});- defer std.testing.allocator.free(needle);- try std.testing.expect(std.mem.indexOf(u8, got, needle) != null);- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, got, osc_open_prefix));- } else {- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, got, osc_open_prefix));- }- }-}--test "composer link cursor keeps the complete target and stays outside it" {- const value = "https://example.test/a/long/path";- const cursor = std.mem.indexOf(u8, value, "example").? + 3;- const got = try inputView(std.testing.allocator, value, cursor);- defer std.testing.allocator.free(got);- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, got, osc_open_prefix));- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, got, value));- try std.testing.expect(std.mem.indexOf(u8, got, osc_close ++ glyphs.cursor ++ osc_open_prefix) != null);-}--test "composer cursor snaps away from a UTF-8 continuation byte" {- const dump = @import("dump.zig");- const value = "https://example.test/é";- const got = try inputView(std.testing.allocator, value, value.len - 1);- defer std.testing.allocator.free(got);- const visible = try dump.visible(std.testing.allocator, got);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings("https://example.test/" ++ glyphs.cursor ++ "é", visible);- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, got, osc_open_prefix));- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, got, osc_close));-}--test "wrapped composer links are balanced on every retained physical row" {- const value = "https://example.test/one/two/three/four/five/six/seven";- const linked = try inputView(std.testing.allocator, value, value.len);- defer std.testing.allocator.free(linked);- const got = try wrap(std.testing.allocator, linked, 12, 8);- defer std.testing.allocator.free(got);- var rows: usize = 0;- var it = std.mem.splitScalar(u8, got, '\n');- while (it.next()) |row| {- if (std.mem.indexOf(u8, row, osc_open_prefix) == null) continue;- rows += 1;- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, row, osc_open_prefix));- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, row, osc_close));- try std.testing.expect(theme.visibleLen(row) <= 12);- }- try std.testing.expect(rows > 2);-}--test "long composer links stay linear before the eight-row window" {- var value_buf = std.array_list.Managed(u8).init(std.testing.allocator);- defer value_buf.deinit();- try value_buf.appendSlice("https://example.test/");- try value_buf.appendNTimes('a', 10_000);- const value = value_buf.items;- const linked = try inputView(std.testing.allocator, value, value.len);- defer std.testing.allocator.free(linked);- const got = try wrap(std.testing.allocator, linked, 38, 8);- defer std.testing.allocator.free(got);- try std.testing.expect(got.len < value.len * 10);- try std.testing.expectEqual(@as(usize, 8), std.mem.count(u8, got, osc_open_prefix));- try std.testing.expectEqual(@as(usize, 8), std.mem.count(u8, got, osc_close));-}--test "malformed repeated link candidates are scanned once" {- var value_buf = std.array_list.Managed(u8).init(std.testing.allocator);- defer value_buf.deinit();- for (0..2_000) |_| try value_buf.appendSlice("(www.");- const value = value_buf.items;- const got = try inputView(std.testing.allocator, value, value.len);- defer std.testing.allocator.free(got);- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, got, osc_open_prefix));- try std.testing.expectEqual(value.len + glyphs.cursor.len, got.len);-}diff --git a/TUI/composer_paste.zig b/TUI/composer_paste.zigdeleted file mode 100644index 009647c2..00000000--- a/TUI/composer_paste.zig+++ /dev/null@@ -1,237 +0,0 @@-//! Origin-aware bracketed-paste finalization for the TUI composer (#792).-//!-//! The decoder owns paste framing. This module owns the exact inserted range:-//! text receives a removable trailing separator, pasted file paths become-//! semantic spans, and an image consumes only its own pasted bytes.--const std = @import("std");-const app = @import("app.zig");-const dispatch = @import("dispatch.zig");-const image = @import("image.zig");-const Model = app.Model;--pub fn begin(self: *Model) void {- self.input.beginPaste();-}--pub fn finish(self: *Model) void {- const range = self.input.pasteRange() orelse {- self.input.endPaste();- return;- };- defer self.input.endPaste();- const raw = self.input.getValue()[range.start..range.end];- // Rich clipboard selections can reach the terminal as only blank lines,- // NBSP, or object/format markers. They are not a usable text attachment.- if (!hasContent(raw)) {- if (range.start != range.end and !self.input.replacePaste(range, "", false)) return;- recoverImage(self);- return;- }- const path = normalizePath(self.alloc, raw) orelse {- self.input.ensurePasteSeparator();- return;- };- defer self.alloc.free(path);-- if (dispatch.looksLikeImagePath(path) and image.attachDropped(self, path)) {- _ = self.input.replacePaste(range, "", false);- return;- }- if (!pathExists(path)) {- self.input.ensurePasteSeparator();- return;- }- if (self.input.replacePaste(range, path, true)) self.input.ensurePasteSeparator();-}--fn recoverImage(self: *Model) void {- const engine = @import("engine.zig");- if (engine.g_paste_fn) |f| {- var buf: [1024]u8 = undefined;- var owned = false;- const n = f(engine.g_turn_ctx, &buf, &owned);- if (n > 0) {- const before = self.images.items.len;- @import("owned_images.zig").attach(self, buf[0..@intCast(n)], owned);- if (self.images.items.len > before) return;- } else if (n < 0) {- self.setToast(buf[0..@intCast(-n)]);- return;- }- }- self.setToast("paste contained no usable text or image — copy the image itself or use /image <path>");-}--fn hasContent(raw: []const u8) bool {- const view = std.unicode.Utf8View.init(raw) catch return true;- var it = view.iterator();- while (it.nextCodepoint()) |cp| {- switch (cp) {- 0...0x20,- 0x7f...0xa0,- 0xad,- 0x61c,- 0x1680,- 0x180e,- 0x2000...0x200f,- 0x2028...0x202f,- 0x205f...0x206f,- 0x3000,- 0xfeff,- 0xfff9...0xfffc,- => {},- else => return true,- }- }- return false;-}--fn pathExists(path: []const u8) bool {- const io = std.Io.Threaded.global_single_threaded.io();- _ = std.Io.Dir.cwd().statFile(io, path, .{}) catch return false;- return true;-}--/// Normalize the one-path forms terminals emit for Finder paste/drop. Mixed-/// prose and multiline payloads remain ordinary pasted text.-fn normalizePath(alloc: std.mem.Allocator, raw: []const u8) ?[]u8 {- var src = std.mem.trim(u8, raw, " \t\r\n");- if (src.len < 2 or std.mem.indexOfAny(u8, src, "\r\n") != null) return null;- if ((src[0] == '\'' and src[src.len - 1] == '\'') or (src[0] == '"' and src[src.len - 1] == '"')) {- src = src[1 .. src.len - 1];- }- if (std.mem.startsWith(u8, src, "file://")) src = src["file://".len..];-- var out = std.array_list.Managed(u8).init(alloc);- defer out.deinit();- var i: usize = 0;- while (i < src.len) {- const c = src[i];- if (c == 0 or (c < 0x20 and c != '\t')) return null;- if (c == '%' and i + 2 < src.len) {- const hi = hexNibble(src[i + 1]);- const lo = hexNibble(src[i + 2]);- if (hi != null and lo != null) {- const decoded = (hi.? << 4) | lo.?;- if (decoded == 0 or decoded < 0x20) return null;- out.append(decoded) catch return null;- i += 3;- continue;- }- }- if (c == '\\' and i + 1 < src.len) {- out.append(src[i + 1]) catch return null;- i += 2;- continue;- }- out.append(c) catch return null;- i += 1;- }- if (out.items.len == 0 or out.items[0] != '/') return null;- return out.toOwnedSlice() catch null;-}--const TestPaste = struct {- payload: []const u8 = "",- failed: bool = false,- calls: usize = 0,-- fn call(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {- const self: *TestPaste = @ptrCast(@alignCast(ctx.?));- self.calls += 1;- owned.* = false;- @memcpy(dest[0..self.payload.len], self.payload);- const n: isize = @intCast(self.payload.len);- return if (self.failed) -n else n;- }-};--test "#1468 empty and format-only terminal pastes warn without a false text chip" {- const engine = @import("engine.zig");- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- var callback = TestPaste{};- engine.g_paste_fn = TestPaste.call;- engine.g_turn_ctx = &callback;- for ([_][]const u8{ "", "\n\n\n", " \t\r\n", "\u{a0}\u{200b}\u{feff}\u{fffc}\n\n\n" }) |payload| {- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 120, 24);- defer term.deinit();- _ = term.typeText("beforeafter");- term.model.input.cursor = "before".len;- _ = term.feed("\x1b[200~");- _ = term.feed(payload);- _ = term.feed("\x1b[201~");- try std.testing.expectEqualStrings("beforeafter", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 6), term.model.input.cursor);- try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);- const screen = try term.screen();- defer term.alloc.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, "paste contained no usable text or image") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "[Pasted text") == null);- }- try std.testing.expectEqual(@as(usize, 4), callback.calls);-}--test "#1468 format-only paste recovers an image through the live callback" {- const engine = @import("engine.zig");- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- var callback = TestPaste{ .payload = "/synthetic/clipboard.png" };- engine.g_paste_fn = TestPaste.call;- engine.g_turn_ctx = &callback;- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 120, 24);- defer term.deinit();- _ = term.typeText("describe this");- _ = term.feed("\x1b[200~\n\n\n\x1b[201~");- try std.testing.expectEqualStrings("describe this", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), callback.calls);- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);- try std.testing.expectEqualStrings(callback.payload, term.model.images.items[0]);-}--test "#1468 recovery keeps actionable errors and never probes the clipboard for real text" {- const engine = @import("engine.zig");- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- var callback = TestPaste{ .payload = "clipboard image export failed", .failed = true };- engine.g_paste_fn = TestPaste.call;- engine.g_turn_ctx = &callback;- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 120, 24);- defer term.deinit();- _ = term.feed("\x1b[200~\n\n\n\x1b[201~");- const screen = try term.screen();- defer term.alloc.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, callback.payload) != null);- try std.testing.expectEqualStrings("", term.model.input.getValue());- const text = "\n\u{200d}hello\u{a0}\nworld\n";- _ = term.feed("\x1b[200~");- _ = term.feed(text);- _ = term.feed("\x1b[201~");- try std.testing.expectEqualStrings(text, term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), callback.calls);-}--fn hexNibble(c: u8) ?u8 {- return switch (c) {- '0'...'9' => c - '0',- 'a'...'f' => c - 'a' + 10,- 'A'...'F' => c - 'A' + 10,- else => null,- };-}diff --git a/TUI/diff.zig b/TUI/diff.zigdeleted file mode 100644index 5bce87c4..00000000--- a/TUI/diff.zig+++ /dev/null@@ -1,386 +0,0 @@-//! Unified diffs in the pager: detection, per-line banding, and a wrap that-//! preserves the band.-//!-//! grok-build bands a hunk by LINE — insertions on a green-tinted canvas,-//! deletions on a red one, the hunk header on a dim rail — and carries that-//! canvas across every continuation row a narrow terminal forces. Two rules-//! make that safe here:-//!-//! * a wrapped row re-opens the band itself and marks the fold with a-//! continuation gutter, so a reader never reads a fold as a new diff line;-//! * every row CLOSES with the theme canvas plus a foreground reset. The-//! wrappers in theme.zig re-emit whatever SGR is still active at a line-//! break, so leaving a band open at EOL is exactly how a red deletion ends-//! up painting the unrelated line underneath it.-//!-//! Presentation only. The bytes come from the typed tool events and message-//! bodies the Model already holds; nothing here asks the engine for anything.--const std = @import("std");--const markdown = @import("markdown.zig");-const syntax = @import("syntax.zig");-const theme_mod = @import("theme.zig");--/// What one diff line is. `meta` is the file/index header block, `ctx` an-/// unchanged line.-pub const Kind = enum { add, del, hunk, meta, ctx };--/// The fold marker a continuation row opens with (one column, like ↳).-pub const gutter = "\u{21AA} ";--/// Insertion band — tinted toward the theme's `ok` green, one value per-/// polarity so a light theme gets a wash rather than a hole.-pub fn addBg(light: bool) []const u8 {- return if (light) "\x1b[48;2;214;240;218m" else "\x1b[48;2;28;48;32m";-}--/// Deletion band, tinted toward `error_fg`.-pub fn delBg(light: bool) []const u8 {- return if (light) "\x1b[48;2;250;220;224m" else "\x1b[48;2;56;28;34m";-}--/// Hunk header: a dim neutral rail, never either edit color.-pub fn hunkBg(light: bool) []const u8 {- return if (light) "\x1b[48;2;232;232;236m" else "\x1b[48;2;34;34;40m";-}--/// Classify one line. The `+++`/`---` file headers are tested BEFORE the bare-/// `+`/`-` markers — otherwise every patch opens with a green and a red row-/// that are not edits at all.-pub fn classify(line: []const u8) Kind {- const s = std.mem.trimEnd(u8, line, "\r");- if (std.mem.startsWith(u8, s, "@@")) return .hunk;- if (std.mem.startsWith(u8, s, "+++") or std.mem.startsWith(u8, s, "---")) return .meta;- for ([_][]const u8{ "diff --git", "index ", "new file", "deleted file", "rename ", "similarity index", "Binary files" }) |p| {- if (std.mem.startsWith(u8, s, p)) return .meta;- }- if (s.len == 0) return .ctx;- return switch (s[0]) {- '+' => .add,- '-' => .del,- else => .ctx,- };-}--/// Evidence accumulator behind both detectors.-const Scan = struct {- hunk: bool = false,- minus_hdr: bool = false,- plus_hdr: bool = false,- edits: usize = 0,-- fn feed(s: *Scan, line: []const u8) void {- switch (classify(line)) {- .hunk => s.hunk = true,- .add, .del => s.edits += 1,- .meta => {- if (std.mem.startsWith(u8, line, "---")) s.minus_hdr = true;- if (std.mem.startsWith(u8, line, "+++")) s.plus_hdr = true;- if (std.mem.startsWith(u8, line, "diff --git")) {- s.minus_hdr = true;- s.plus_hdr = true;- }- },- .ctx => {},- }- }-- fn verdict(s: Scan) bool {- return s.edits > 0 and (s.hunk or (s.minus_hdr and s.plus_hdr));- }-};--/// Does this body read as a unified diff? A hunk header (or a `---`/`+++`-/// file pair) AND at least one edit line. Both halves matter: markdown bullet-/// lists are full of lines that open with `-`, and a lone `@@` is not a patch.-pub fn looksLikeUnified(src: []const u8) bool {- var s: Scan = .{};- var it = std.mem.splitScalar(u8, src, '\n');- while (it.next()) |ln| s.feed(ln);- return s.verdict();-}--/// The same verdict over an already-split fence body, stopping at the closing-/// fence so the prose after it never votes.-pub fn looksLikeLines(lines: []const []const u8) bool {- var s: Scan = .{};- for (lines) |ln| {- if (std.mem.startsWith(u8, std.mem.trimStart(u8, ln, " "), "```")) break;- s.feed(ln);- }- return s.verdict();-}--/// A fence info string that DECLARES a diff, whatever its body looks like.-pub fn isDiffInfo(info: []const u8) bool {- const t = std.mem.trim(u8, info, " \t\r");- return std.mem.eql(u8, t, "diff") or std.mem.eql(u8, t, "patch") or std.mem.eql(u8, t, "udiff");-}--fn bandBg(k: Kind, light: bool) ?[]const u8 {- return switch (k) {- .add => addBg(light),- .del => delBg(light),- .hunk => hunkBg(light),- .meta, .ctx => null,- };-}--fn fgOf(k: Kind, th: theme_mod.Theme) []const u8 {- return switch (k) {- .add => th.ok,- .del => th.error_fg,- .hunk, .meta => th.muted,- .ctx => th.text,- };-}--/// One diff line, banded and wrapped to `width` (0 = do not wrap).-pub fn lineThemed(a: std.mem.Allocator, line: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- try appendLine(&out, line, th, width);- return out.toOwnedSlice();-}--/// A whole diff body, one banded block. Already wrapped: the wrappers in-/// theme.zig find every row inside `width` and leave it alone.-pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- var it = std.mem.splitScalar(u8, src, '\n');- var first = true;- while (it.next()) |ln| {- if (!first) try out.append('\n');- first = false;- try appendLine(&out, ln, th, width);- }- return out.toOwnedSlice();-}--/// Append one banded line straight into a caller's buffer — the allocation-free-/// form markdown.zig uses while it walks a fence.-pub fn appendLine(out: *std.array_list.Managed(u8), line: []const u8, th: theme_mod.Theme, width: usize) !void {- const light = th.id == .day;- const k = classify(line);- const band = bandBg(k, light);- const bg = band orelse th.bg;- const fg = fgOf(k, th);- const cols = if (width == 0) std.math.maxInt(usize) else width;- var rest = std.mem.trimEnd(u8, line, "\r");- var row: usize = 0;- while (true) {- const lead: []const u8 = if (row == 0) "" else gutter;- const lead_cols = theme_mod.visibleLen(lead);- const chunk = take(rest, cols -| lead_cols);- if (row > 0) try out.append('\n');- try out.appendSlice(bg);- if (k == .hunk) try out.appendSlice(theme_mod.dim);- try out.appendSlice(fg);- try out.appendSlice(lead);- try out.appendSlice(chunk);- // A band is a FIELD: pad it out so the row is one solid stripe rather- // than a coloured ribbon that stops at the last glyph.- if (band != null and width > 0) {- var pad = width -| (lead_cols + theme_mod.visibleLen(chunk));- while (pad > 0) : (pad -= 1) try out.append(' ');- }- try out.appendSlice(th.bg); // canvas back before the row ends- try out.appendSlice(theme_mod.reset); // fg/weight/italic/underline off- rest = rest[chunk.len..];- row += 1;- if (rest.len == 0) break;- }-}--/// The next `cols` columns of `s`, never empty while bytes remain — a glyph-/// wider than the whole row still has to advance or the wrap spins forever.-fn take(s: []const u8, cols: usize) []const u8 {- if (s.len == 0) return s;- if (cols > 0) {- const got = theme_mod.takeCols(s, cols);- if (got.len > 0) return got;- }- return s[0..@min(s.len, std.unicode.utf8ByteSequenceLength(s[0]) catch 1)];-}--const patch =- "diff --git a/TUI/run.zig b/TUI/run.zig\n" ++- "--- a/TUI/run.zig\n" ++- "+++ b/TUI/run.zig\n" ++- "@@ -1,4 +1,4 @@\n" ++- " const std = @import(\"std\");\n" ++- "-const old = 1;\n" ++- "+const new = 2;\n";--test "classify separates file headers from the edits under them" {- try std.testing.expectEqual(Kind.meta, classify("--- a/TUI/run.zig"));- try std.testing.expectEqual(Kind.meta, classify("+++ b/TUI/run.zig"));- try std.testing.expectEqual(Kind.meta, classify("diff --git a/x b/x"));- try std.testing.expectEqual(Kind.hunk, classify("@@ -1,4 +1,4 @@"));- try std.testing.expectEqual(Kind.add, classify("+const new = 2;"));- try std.testing.expectEqual(Kind.del, classify("-const old = 1;"));- try std.testing.expectEqual(Kind.ctx, classify(" const std = @import(\"std\");"));- try std.testing.expectEqual(Kind.ctx, classify(""));-}--test "the detector wants a hunk header AND an edit, so prose never bands" {- try std.testing.expect(looksLikeUnified(patch));- try std.testing.expect(looksLikeUnified("@@ -1 +1 @@\n-a\n+b"));- // A markdown bullet list is nothing but lines that start with `-`.- try std.testing.expect(!looksLikeUnified("- one\n- two\n- three"));- // A lone hunk-shaped line with no edits under it is prose about diffs.- try std.testing.expect(!looksLikeUnified("the @@ marker names a hunk"));- try std.testing.expect(!looksLikeUnified(""));- try std.testing.expect(!looksLikeUnified("+1 more\n"));- // A `---`/`+++` pair stands in for the hunk header (git shows both).- try std.testing.expect(looksLikeUnified("--- a/x\n+++ b/x\n+added\n"));-}--test "looksLikeLines stops at the closing fence" {- const body = [_][]const u8{ "@@ -1 +1 @@", "-a", "+b", "```", "- a bullet", "- another" };- try std.testing.expect(looksLikeLines(&body));- const prose = [_][]const u8{ "```", "@@ -1 +1 @@", "-a", "+b" };- try std.testing.expect(!looksLikeLines(&prose));- try std.testing.expect(isDiffInfo("diff"));- try std.testing.expect(isDiffInfo(" patch \t"));- try std.testing.expect(!isDiffInfo("zig"));-}--/// Every row of a banded block must close its band, or theme.zig's wrap-/// re-opens it on whatever comes next.-fn expectClosed(row: []const u8, th: theme_mod.Theme) !void {- try std.testing.expect(std.mem.endsWith(u8, row, theme_mod.reset));- try std.testing.expect(std.mem.endsWith(u8, row[0 .. row.len - theme_mod.reset.len], th.bg));-}--test "golden: bands, boundaries and reset bytes at 40/80/120" {- const th = theme_mod.of(.night);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- for ([_]usize{ 40, 80, 120 }) |w| {- const out = try renderThemed(a, patch, th, w);- var it = std.mem.splitScalar(u8, out, '\n');- var adds: usize = 0;- var dels: usize = 0;- var hunks: usize = 0;- while (it.next()) |ln| {- try std.testing.expect(theme_mod.visibleLen(ln) <= w);- try expectClosed(ln, th);- const is_add = std.mem.startsWith(u8, ln, addBg(false));- const is_del = std.mem.startsWith(u8, ln, delBg(false));- const is_hunk = std.mem.startsWith(u8, ln, hunkBg(false));- // A banded row is a full-width field; exactly one band per row.- if (is_add or is_del or is_hunk) {- try std.testing.expectEqual(w, theme_mod.visibleLen(ln));- try std.testing.expectEqual(@as(usize, 1), @as(usize, @intFromBool(is_add)) + @intFromBool(is_del) + @intFromBool(is_hunk));- }- // The `---`/`+++` file headers are meta: they never band as edits.- if (is_add) try std.testing.expect(std.mem.indexOf(u8, ln, "+++") == null);- if (is_del) try std.testing.expect(std.mem.indexOf(u8, ln, "---") == null);- adds += @intFromBool(is_add);- dels += @intFromBool(is_del);- hunks += @intFromBool(is_hunk);- }- try std.testing.expectEqual(@as(usize, 1), adds);- try std.testing.expectEqual(@as(usize, 1), dels);- try std.testing.expectEqual(@as(usize, 1), hunks);- }-}--test "wrap-bleed regression: a long deletion never paints the line under it" {- const th = theme_mod.of(.night);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const src = "@@ -1,2 +1,2 @@\n" ++- "-const message = try std.fmt.allocPrint(gpa, \"a very long deleted line that has to wrap\", .{});\n" ++- " const equal = 1;\n";- const out = try renderThemed(a, src, th, 40);- var it = std.mem.splitScalar(u8, out, '\n');- var del_rows: usize = 0;- var saw_equal = false;- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, "const equal = 1;") != null) {- saw_equal = true;- // The equal line inherits nothing: no red band anywhere on it.- try std.testing.expect(std.mem.indexOf(u8, ln, delBg(false)) == null);- try std.testing.expect(std.mem.startsWith(u8, ln, th.bg));- continue;- }- if (std.mem.startsWith(u8, ln, delBg(false))) {- del_rows += 1;- try expectClosed(ln, th);- // The band survives the fold, and the fold is marked.- if (del_rows > 1) try std.testing.expect(std.mem.indexOf(u8, ln, gutter) != null);- }- }- try std.testing.expect(saw_equal);- try std.testing.expect(del_rows > 1); // it really did wrap-}--test "both polarities band, and a day theme never uses the night wash" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const day = try renderThemed(a, patch, theme_mod.of(.day), 60);- try std.testing.expect(std.mem.indexOf(u8, day, addBg(true)) != null);- try std.testing.expect(std.mem.indexOf(u8, day, delBg(true)) != null);- try std.testing.expect(std.mem.indexOf(u8, day, addBg(false)) == null);- try std.testing.expect(std.mem.indexOf(u8, day, delBg(false)) == null);- const night = try renderThemed(a, patch, theme_mod.of(.night), 60);- try std.testing.expect(std.mem.indexOf(u8, night, addBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, night, addBg(true)) == null);-}--test "a glyph wider than the row still advances, and width 0 does not wrap" {- const th = theme_mod.of(.night);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const wide = try lineThemed(a, "+\u{1F680}\u{1F680}", th, 1);- try std.testing.expect(std.mem.count(u8, wide, "\n") >= 2);- try std.testing.expect(std.mem.indexOf(u8, wide, "\u{1F680}") != null);- const unwrapped = try lineThemed(a, "+xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", th, 0);- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, unwrapped, "\n"));- try expectClosed(unwrapped, th);-}--// The markdown side of the same contract: a fence that IS a patch is banded-// by this module instead of taking the code canvas. Lives here for the-// 600-line ceiling on markdown.zig.--test "a diff fence bands its edits instead of taking the code canvas" {- const th = theme_mod.of(.night);- const src = "before\n```diff\n@@ -1,2 +1,2 @@\n const keep = 0;\n-const old = 1;\n+const new = 2;\n```\nafter";- const out = try markdown.renderThemed(std.testing.allocator, src, th, 40);- defer std.testing.allocator.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, addBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, out, delBg(false)) != null);- // A patch is not code: it never picks up the fence's own background.- try std.testing.expect(std.mem.indexOf(u8, out, syntax.codeBg(false)) == null);- var it = std.mem.splitScalar(u8, out, '\n');- while (it.next()) |ln| {- try std.testing.expect(theme_mod.visibleLen(ln) <= 40);- if (std.mem.indexOf(u8, ln, "after") == null) continue;- // The prose under the fence inherits neither band.- try std.testing.expect(std.mem.indexOf(u8, ln, addBg(false)) == null);- try std.testing.expect(std.mem.indexOf(u8, ln, delBg(false)) == null);- }-}--test "an undeclared fence that IS a patch bands; a bullet list never does" {- const th = theme_mod.of(.night);- const banded = try markdown.renderThemed(std.testing.allocator, "```\n--- a/x\n+++ b/x\n-gone\n+here\n```", th, 40);- defer std.testing.allocator.free(banded);- try std.testing.expect(std.mem.indexOf(u8, banded, addBg(false)) != null);- // Lines that merely START with `-` are a list, not a diff (#diff).- const list = try markdown.renderThemed(std.testing.allocator, "- one\n- two\n- three", th, 40);- defer std.testing.allocator.free(list);- try std.testing.expect(std.mem.indexOf(u8, list, delBg(false)) == null);- // …and a zig fence still gets syntax colors on the code canvas.- const code = try markdown.renderThemed(std.testing.allocator, "```zig\nconst x = 1;\n```", th, 40);- defer std.testing.allocator.free(code);- try std.testing.expect(std.mem.indexOf(u8, code, syntax.codeBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, code, addBg(false)) == null);-}diff --git a/TUI/dispatch.zig b/TUI/dispatch.zigdeleted file mode 100644index eed59ab9..00000000--- a/TUI/dispatch.zig+++ /dev/null@@ -1,517 +0,0 @@-//! Slash-command execution and line submit. UI-only commands live here;-//! model turns spawn a Job through turn.zig.--const std = @import("std");--const app = @import("app.zig");-const bgop = @import("bgop.zig");-const catalog = @import("catalog.zig");-const engine = @import("engine.zig");-const peer_cmd = @import("peer_cmd.zig");-const resume_mod = @import("resume.zig");-const meters = @import("meters.zig");-const theme_mod = @import("theme.zig");-const turn = @import("turn.zig");-const Model = app.Model;-const Effect = app.Effect;--/// Shown whenever an engine call is already in flight — /compact, `!cmd` and-/// a model turn all use the one engine, so they queue behind each other.-pub const busy_note = "an engine call is still running — press Esc to cancel it";--/// A production model switch replaces ReplCtx.provider and clears its fallback-/// flags. Turns and background ops borrow that same context, so the mutation-/// waits for the existing one-engine policy even within one input batch.-/// Browsing the picker remains UI-only; callers use this at confirmation.-pub fn refuseProviderMutation(self: *Model) bool {- if (self.pending == null and self.bg == null) return false;- self.push(.system, busy_note) catch {};- return true;-}--pub fn applyLine(self: *Model, raw: []const u8) Effect {- const line = std.mem.trim(u8, raw, " \t\r\n");- if (line.len == 0 and self.images.items.len == 0) return .stay;- if (line.len > 0 or self.images.items.len > 0) rememberPrompt(self, line);- if (line.len > 0 and line[0] == '/') return runCommand(self, line);- if (line.len > 1 and line[0] == '!') return bang(self, std.mem.trim(u8, line[1..], " \t"));- if (self.bg != null) {- // /compact rewrites the history the next turn would send — never race- // a turn against it.- self.push(.system, busy_note) catch {};- return .stay;- }- const payload = withImages(self, line);- defer if (payload.ptr != line.ptr) self.alloc.free(payload);- self.push(.user, payload) catch {- self.push(.err, "could not preserve the submitted attachment; recall the prompt and retry") catch {};- return .stay;- };- if (self.chat) {- self.turns += 1;- turn.startJob(self);- return .stay;- }- self.pushFmt(.system, "offline — no model wired. Use `graff` with a key, or /help.", .{}) catch {};- return .stay;-}--fn rememberPrompt(self: *Model, line: []const u8) void {- @import("prompt_history.zig").remember(self, line);-}--/// Bake live composer chips onto `line` as `@[path]` markers (same shape-/// applyLine sends). Clears the chips. Returns `line` when there are none.-fn withImages(self: *Model, line: []const u8) []const u8 {- const prefix = self.takeImagesPrefix(self.alloc);- if (prefix.len == 0) return line;- defer self.alloc.free(prefix);- return std.fmt.allocPrint(self.alloc, "{s}{s}", .{ prefix, line }) catch line;-}--/// Queue a mid-turn follow-up, including any attached chips. Idle applyLine-/// already prefixes `@[path]`; steer used to copy only the typed text, so the-/// pixels never left the composer.-/// A follow-up typed with Enter mid-turn. Plain text joins the running turn-/// (a streaming reply restarts with it); commands and image chips wait for-/// the turn to end, as a /btw aside does.-pub fn steerLine(self: *Model, text: []const u8) void {- const line = std.mem.trim(u8, text, " \t\r\n");- if (self.images.items.len == 0 and line.len > 0 and line[0] != '/') if (engine.g_steer_send_fn) |send| if (send(line)) {- if (engine.g_followup_fn) |f| f();- self.input.setValue("") catch {};- self.push(.system, "↳ sent to the running turn") catch {};- return;- };- queueSteerLine(self, text);-}--pub fn queueSteerLine(self: *Model, text: []const u8) void {- const line = std.mem.trim(u8, text, " \t\r\n");- if (line.len == 0 and self.images.items.len == 0) return;- const payload = withImages(self, line);- const dup = if (payload.ptr == line.ptr) self.alloc.dupe(u8, line) catch return else payload;- self.steer_queue.append(dup) catch {- if (dup.ptr != line.ptr) self.alloc.free(dup);- return;- };- if (engine.g_followup_fn) |f| f();- self.input.setValue("") catch {};- self.pushFmt(.system, "↳ queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};-}--pub fn runCommand(self: *Model, line: []const u8) Effect {- const sp = std.mem.indexOfScalar(u8, line, ' ');- const cmd = if (sp) |i| line[0..i] else line;- const arg = std.mem.trim(u8, if (sp) |i| line[i + 1 ..] else "", " \t");- const item = catalog.lookup(cmd);- const canon = if (item) |it| it.name else cmd;-- // #521: history-destroying commands must not run under a live job — the- // steer guard in promptKey only covers plain text, and the slash menu,- // palette, and steer drain all land here.- const destroys = std.mem.eql(u8, canon, "/new") or std.mem.eql(u8, canon, "/compact") or std.mem.eql(u8, canon, "/rewind") or std.mem.eql(u8, canon, "/resume");- if (self.pending != null and destroys) {- self.push(.system, "a turn is still running — press Esc to cancel it first") catch {};- return .stay;- }- // Same for a background engine op: /compact is itself one of them.- if (self.bg != null and destroys) {- self.push(.system, busy_note) catch {};- return .stay;- }- // Constraint mutation refreshes the live root prompt. Never race that- // against a turn or background engine operation; refuse without cancelling.- if (std.mem.eql(u8, canon, "/never") and (self.pending != null or self.bg != null)) {- self.push(.system, busy_note) catch {};- return .stay;- }-- if (std.mem.eql(u8, canon, "/quit")) {- self.quit_requested = true;- return .quit;- } else if (std.mem.eql(u8, canon, "/new")) {- _ = self.newSession(); // the `destroys` guard above already refused a live call- self.push(.system, "started a new conversation") catch {};- self.screen = .welcome;- } else if (std.mem.eql(u8, canon, "/resume")) {- if (arg.len == 0) resume_mod.open(self) else resume_mod.run(self, arg);- } else if (std.mem.eql(u8, canon, "/home")) {- self.screen = .welcome;- self.focus = .prompt;- } else if (std.mem.eql(u8, canon, "/rewind")) {- rewind(self);- } else if (std.mem.eql(u8, canon, "/compact")) {- compact(self);- } else if (std.mem.eql(u8, canon, "/help")) {- self.openOverlay(.help);- } else if (std.mem.eql(u8, canon, "/shortcuts")) {- self.openOverlay(.help);- } else if (std.mem.eql(u8, canon, "/theme")) {- if (arg.len == 0) {- self.openOverlay(.theme);- } else if (theme_mod.parse(arg)) |id| {- self.theme_id = id;- self.theme_explicit = true;- self.pushFmt(.system, "theme: {s}", .{id.label()}) catch {};- } else {- self.pushFmt(.err, "unknown theme '{s}' — night|day|tokyo|rose|oscura", .{arg}) catch {};- }- } else if (std.mem.eql(u8, canon, "/settings")) {- self.openOverlay(.settings);- } else if (std.mem.eql(u8, canon, "/model")) {- if (arg.len == 0) {- self.openOverlay(.model);- } else if (refuseProviderMutation(self)) {- return .stay;- } else if (engine.g_model_fn) |f| {- // A hand-typed name names no provider, so the engine routes it —- // the picker is the surface that knows which seat was meant.- const previous: engine.Picked = .{ .model = engine.g_model_name, .provider = engine.g_model_provider };- if (f(engine.g_turn_ctx, self.alloc, "", arg)) |got| {- const same = std.mem.eql(u8, previous.model, got.model) and std.mem.eql(u8, previous.provider, got.provider);- self.adoptModel(got);- self.pushFmt(.system, "{s} {s} · {s}", .{ if (same) "already using" else "switched to", got.model, got.provider }) catch {};- } else self.pushFmt(.err, "couldn't switch to '{s}'", .{arg}) catch {};- } else self.push(.system, "model switching isn't available (offline)") catch {};- } else if (std.mem.eql(u8, canon, "/effort")) {- if (arg.len == 0) {- const p = engine.g_model_provider;- const m = engine.g_model_name;- if ((std.mem.eql(u8, p, "xai") or std.mem.startsWith(u8, m, "grok")) and (self.effort == .max or self.effort == .ultra))- self.effort = .high;- self.openOverlay(.effort);- self.overlay_sel = @intFromEnum(self.effort);- return .stay;- }- const normalized = if (std.mem.eql(u8, arg, "med")) "medium" else arg;- self.effort = std.meta.stringToEnum(engine.Effort, normalized) orelse {- self.push(.system, "usage: /effort low|medium|high|xhigh|max|ultra") catch {};- return .stay;- };- const p = engine.g_model_provider;- const m = engine.g_model_name;- if ((std.mem.eql(u8, p, "xai") or std.mem.startsWith(u8, m, "grok")) and (self.effort == .max or self.effort == .ultra))- self.effort = .high;- self.pushFmt(.system, "reasoning effort: {s}", .{@tagName(self.effort)}) catch {};- } else if (std.mem.eql(u8, canon, "/always-approve")) {- self.mode = if (self.mode == .always_approve) .normal else .always_approve;- self.pushFmt(.system, "mode: {s}", .{self.modeLabel()}) catch {};- } else if (std.mem.eql(u8, canon, "/plan")) {- self.mode = if (self.mode == .plan) .normal else .plan;- self.pushFmt(.system, "mode: {s}", .{self.modeLabel()}) catch {};- } else if (std.mem.eql(u8, canon, "/multiline")) {- self.multiline = !self.multiline;- self.pushFmt(.system, "multiline: {s}", .{onOff(self.multiline)}) catch {};- } else if (std.mem.eql(u8, canon, "/compact-mode")) {- self.compact_mode = !self.compact_mode;- self.pushFmt(.system, "compact mode: {s}", .{onOff(self.compact_mode)}) catch {};- } else if (std.mem.eql(u8, canon, "/thinking")) {- self.thinking_show = !self.thinking_show;- self.pushFmt(.system, "show thinking: {s}", .{onOff(self.thinking_show)}) catch {};- } else if (std.mem.eql(u8, canon, "/fast")) {- self.fast = !self.fast;- self.pushFmt(.system, "fast: {s}", .{onOff(self.fast)}) catch {};- } else if (std.mem.eql(u8, canon, "/ultracode")) {- self.ultracode = !self.ultracode;- publishState(self);- self.pushFmt(.system, "ultracode: {s}", .{onOff(self.ultracode)}) catch {};- } else if (std.mem.eql(u8, canon, "/strict")) {- self.strict = !self.strict;- publishState(self);- self.pushFmt(.system, "strict: {s}", .{onOff(self.strict)}) catch {};- } else if (std.mem.eql(u8, canon, "/goals")) {- applyGoal(self, "status");- } else if (std.mem.eql(u8, canon, "/goal")) {- applyGoal(self, arg);- } else if (std.mem.eql(u8, canon, "/never")) {- if (engine.g_constraint_fn) |f| {- if (f(engine.g_turn_ctx, self.alloc, line)) |text| {- defer self.alloc.free(text);- self.push(.system, text) catch {};- } else self.push(.err, "constraint command failed; ledger unchanged") catch {};- } else self.push(.system, "constraint review unavailable (no live session)") catch {};- } else if (std.mem.eql(u8, canon, "/rename")) {- if (self.session_name) |s| self.alloc.free(s);- self.session_name = if (arg.len > 0) (self.alloc.dupe(u8, arg) catch null) else null;- publishState(self);- self.pushFmt(.system, "session: {s}", .{self.session_name orelse "untitled"}) catch {};- } else if (std.mem.eql(u8, canon, "/session-info")) {- meters.sessionInfo(self);- } else if (std.mem.eql(u8, canon, "/version")) {- if (!bgop.start(self, .version, &.{}, "", "checking version")) self.push(.system, busy_note) catch {};- } else if (std.mem.eql(u8, canon, "/debug") or std.mem.eql(u8, canon, "/cache")) {- self.openOverlay(.debug);- } else if (std.mem.eql(u8, canon, "/update")) {- startUpdate(self, arg);- } else if (std.mem.eql(u8, canon, "/usage")) {- var buf: [512]u8 = undefined;- if (engine.g_hud_fn) |f| {- const n = f(.usage, &buf);- if (n > 0) self.push(.system, buf[0..n]) catch {};- } else {- self.push(.system, "usage unavailable (no session sink)") catch {};- }- } else if (std.mem.eql(u8, canon, "/context")) {- meters.contextInfo(self);- } else if (std.mem.eql(u8, canon, "/history")) {- recallPrev(self);- } else if (std.mem.eql(u8, canon, "/image")) {- if (arg.len == 0) {- self.push(.system, "usage: /image <path.png|jpg|gif|webp>") catch {};- } else self.attachImage(arg);- } else if (std.mem.eql(u8, canon, "/paste")) {- pasteClipboard(self);- } else if (std.mem.eql(u8, canon, "/doctor")) {- var buf: [4096]u8 = undefined;- if (engine.g_hud_fn) |f| {- const n = f(.doctor, &buf);- if (n > 0) self.push(.system, buf[0..n]) catch {};- } else {- self.push(.system, "doctor unavailable (no session sink)") catch {};- }- } else if (std.mem.eql(u8, canon, "/import-claude")) {- self.push(.system, "adopting Claude/Cursor MCP writes ~/.codegraff — run `graff mcp import` from this repo") catch {};- } else if (std.mem.eql(u8, canon, "/jump")) {- if (self.userTurnCount() == 0) {- self.push(.system, "nothing to jump to yet") catch {};- } else self.openOverlay(.jump);- } else if (std.mem.eql(u8, canon, "/vim-mode")) {- self.vim_mode = !self.vim_mode;- self.pushFmt(.system, "vim scrollback: {s}", .{onOff(self.vim_mode)}) catch {};- } else if (std.mem.eql(u8, canon, "/copy")) {- copyLastReply(self);- } else if (std.mem.eql(u8, canon, "/tell") or std.mem.eql(u8, canon, "/peek")) {- peer_cmd.run(self, canon, arg);- } else if (std.mem.eql(u8, canon, "/btw")) {- if (arg.len == 0) {- self.push(.system, "usage: /btw <aside> — queue a note without interrupting") catch {};- } else if (self.pending != null) {- queueSteerLine(self, arg);- } else {- return applyLine(self, arg);- }- } else if (catalog.suggest(cmd)) |near| {- self.pushFmt(.err, "unknown command: {s} — did you mean {s}?", .{ cmd, near }) catch {};- } else {- self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};- }- return if (self.quit_requested) .quit else .stay;-}--fn publishState(self: *Model) void {- publishStateOp(self, .none);-}--fn publishStateOp(self: *Model, op: engine.GoalOp) void {- if (engine.g_state_fn) |f| f(engine.g_turn_ctx, .{- .session_name = self.session_name orelse "",- .goal = self.goal orelse "",- .strict = self.strict,- .ultracode = self.ultracode,- .goal_op = op,- });-}--/// Line-REPL `/goal` verbs (`status`/`pause`/`resume`/`clear`), not a raw-/// objective string. `/goal pause` used to mint a standing goal named "pause".-fn applyGoal(self: *Model, raw: []const u8) void {- const verb = std.mem.trim(u8, raw, " \t\r\n");- if (verb.len == 0 or std.ascii.eqlIgnoreCase(verb, "status")) {- if (self.goal) |g|- self.pushFmt(.system, "Goal: {s}. Commands: /goal pause | resume | clear.", .{g}) catch {}- else- self.push(.system, "No active goal. Set one with /goal <objective>.") catch {};- return;- }- if (std.ascii.eqlIgnoreCase(verb, "clear") or std.ascii.eqlIgnoreCase(verb, "off")) {- if (self.goal) |g| self.alloc.free(g);- self.goal = null;- publishStateOp(self, .clear);- self.push(.system, "goal cleared") catch {};- return;- }- if (std.ascii.eqlIgnoreCase(verb, "pause")) {- publishStateOp(self, .pause);- if (self.goal) |g|- self.pushFmt(.system, "goal paused: {s}", .{g}) catch {}- else- self.push(.system, "No active goal to pause. Set one with /goal <objective>.") catch {};- return;- }- if (std.ascii.eqlIgnoreCase(verb, "resume")) {- publishStateOp(self, .unpause);- if (self.goal) |g|- self.pushFmt(.system, "goal resumed: {s}", .{g}) catch {}- else- self.push(.system, "No goal to resume. Set one with /goal <objective>.") catch {};- return;- }- if (self.goal) |g| self.alloc.free(g);- self.goal = self.alloc.dupe(u8, verb) catch null;- publishStateOp(self, .set);- if (self.goal) |g| self.pushFmt(.system, "goal set: {s}", .{g}) catch {};-}--/// `!cmd` — run a shell line locally (grok-style bash mode) on a background-/// thread, so a slow command no longer freezes the frame for its whole 20s-/// cap (#533). Output stays out of the model history: EntryKind.system never-/// reaches startJob.-fn bang(self: *Model, cmd: []const u8) Effect {- if (cmd.len == 0) return .stay;- self.pushFmt(.system, "$ {s}", .{cmd}) catch {};- if (engine.g_bash_fn == null) {- self.push(.err, "! needs a live session (offline)") catch {};- return .stay;- }- const owned = self.alloc.dupe(u8, cmd) catch return .stay;- if (!bgop.start(self, .bash, &.{}, owned, "running")) {- self.alloc.free(owned);- self.push(.system, busy_note) catch {};- }- return .stay;-}--/// Tail of `s` capped to `max` lines, for `!` output in the scrollback.-pub fn lastLines(s: []const u8, max: usize) []const u8 {- var count: usize = 0;- var i = s.len;- while (i > 0) {- i -= 1;- if (s[i] == '\n') {- count += 1;- if (count == max) return s[i + 1 ..];- }- }- return s;-}--fn copyLastReply(self: *Model) void {- var i = self.history.items.len;- const text: ?[]const u8 = while (i > 0) {- i -= 1;- if (self.history.items[i].kind == .assistant) break self.history.items[i].text;- } else null;- if (text == null) {- self.push(.system, "nothing to copy yet") catch {};- } else if (engine.g_copy_fn) |f| {- self.setToast(if (f(engine.g_turn_ctx, text.?)) "copied last reply" else "copy failed");- } else self.setToast("clipboard needs a live session");-}--pub fn rewind(self: *Model) void {- // Same reason newSession refuses: the rewind reaches the engine's history,- // and the rewind overlay's Enter does not go through runCommand's guard.- if (self.pending != null or self.bg != null) {- self.push(.system, busy_note) catch {};- return;- }- var i = self.history.items.len;- while (i > 0) : (i -= 1) {- if (self.history.items[i - 1].kind == .user) break;- }- if (i == 0) {- self.push(.system, "nothing to rewind") catch {};- return;- }- var j = self.history.items.len;- while (j > i - 1) : (j -= 1) self.freeEntry(self.history.items[j - 1]);- self.history.shrinkRetainingCapacity(i - 1);- // The engine holds the conversation, so taking the turn back has to reach- // it too — otherwise the next request still carries the prompt the user- // just withdrew (#551).- engine.historyChanged(.rewind);- self.push(.system, "rewound the last turn") catch {};-}--/// `/compact` — hand the history to the engine on a background thread. Running-/// it inline froze the render+input loop for the whole summarization round-/// trip, with no paint, no key handling and no way to cancel (#533).-pub fn compact(self: *Model) void {- if (engine.g_compact_fn == null) {- self.push(.system, "compaction needs a live session") catch {};- return;- }- var turns = std.array_list.Managed(engine.Turn).init(self.alloc);- for (self.history.items) |e| {- const role: ?engine.Turn.Role = switch (e.kind) {- .user => .user,- .assistant => .assistant,- else => null,- };- if (role) |r| {- const t = self.alloc.dupe(u8, e.text) catch continue;- turns.append(.{ .role = r, .text = t }) catch self.alloc.free(t);- }- }- const owned: []engine.Turn = turns.toOwnedSlice() catch &.{};- if (!bgop.start(self, .compact, owned, "", "compacting")) {- for (owned) |t| self.alloc.free(t.text);- if (owned.len > 0) self.alloc.free(owned);- self.push(.system, busy_note) catch {};- }-}--pub fn recallPrev(self: *Model) void {- @import("prompt_history.zig").recallPrev(self);-}--pub fn recallNext(self: *Model) void {- @import("prompt_history.zig").recallNext(self);-}--pub fn pasteClipboard(self: *Model) void {- if (engine.g_paste_fn) |f| {- var buf: [1024]u8 = undefined;- var owned = false;- const n = f(engine.g_turn_ctx, &buf, &owned);- if (n > 0) {- @import("owned_images.zig").attach(self, buf[0..@intCast(n)], owned);- } else if (n < 0) {- self.setToast(buf[0..@intCast(-n)]);- } else self.setToast("no image on the clipboard — Ctrl+V (⌘V can't be captured)");- } else self.setToast("image paste needs a live session");-}--pub fn looksLikeImagePath(s: []const u8) bool {- var t = std.mem.trim(u8, s, " \t\r\n\"'");- if (std.mem.startsWith(u8, t, "file://")) t = t["file://".len..];- const exts = [_][]const u8{ ".png", ".jpg", ".jpeg", ".gif", ".webp" };- var ok = false;- for (exts) |e| {- if (t.len >= e.len and std.ascii.eqlIgnoreCase(t[t.len - e.len ..], e)) {- ok = true;- break;- }- }- if (!ok) return false;- if (std.mem.indexOfAny(u8, t, " \t") != null) {- return t[0] == '/' or t[0] == '~' or t[0] == '.';- }- return true;-}--fn startUpdate(self: *Model, arg: []const u8) void {- const action = if (std.mem.eql(u8, arg, "install")) "install" else "check";- if (engine.g_update_fn == null) {- self.push(.system, "check for a release with /update; install it for the next launch only after you confirm. This session keeps running.") catch {};- return;- }- const cmd = self.alloc.dupe(u8, action) catch {- self.push(.err, "update check unavailable") catch {};- return;- };- if (!bgop.start(self, .update, &.{}, cmd, if (std.mem.eql(u8, action, "install")) "installing update" else "checking for update")) {- self.alloc.free(cmd);- self.push(.system, busy_note) catch {};- }-}--fn onOff(v: bool) []const u8 {- return if (v) "on" else "off";-}--test {- _ = @import("dispatch_tests.zig"); // overflow tests (600-line cap)- _ = @import("dispatch_command_tests.zig");-}diff --git a/TUI/dispatch_command_tests.zig b/TUI/dispatch_command_tests.zigdeleted file mode 100644index 32f5fb7a..00000000--- a/TUI/dispatch_command_tests.zig+++ /dev/null@@ -1,526 +0,0 @@-//! dispatch.zig command-path tests.--const std = @import("std");--const app = @import("app.zig");-const dispatch = @import("dispatch.zig");-const bgop = @import("bgop.zig");-const engine = @import("engine.zig");-const turn = @import("turn.zig");-const Effect = app.Effect;-const Model = app.Model;-const applyLine = dispatch.applyLine;-const lastLines = dispatch.lastLines;-const looksLikeImagePath = dispatch.looksLikeImagePath;-const rewind = dispatch.rewind;--test "applyLine /quit and /new" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(Effect.quit, applyLine(&m, "/quit"));- m.quit_requested = false;- try m.push(.user, "keep me");- _ = applyLine(&m, "/new");- try std.testing.expectEqual(app.Screen.welcome, m.screen);- try std.testing.expectEqual(@as(usize, 1), m.history.items.len); // system notice-}--test "/debug opens the observability overlay" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/debug");- try std.testing.expectEqual(app.Overlay.debug, m.overlay);-}--test "/update checks in the background and does not activate via /new" {- engine.g_update_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, action: []const u8) ?[]const u8 {- return std.fmt.allocPrint(gpa, "running: v0.0.289 (this process)\ninstalled: v0.0.292\nlatest: v0.0.292\n{s}\n/new and /resume keep this process and do not activate the update.\n", .{action}) catch null;- }- }.f;- defer engine.g_update_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "keep talking");- _ = applyLine(&m, "/update");- try std.testing.expect(m.bg != null);- try std.testing.expectEqual(engine.BgOp.Kind.update, m.bg.?.kind);- var spins: usize = 0;- while (!m.bg.?.done.load(.acquire)) : (spins += 1) {- if (spins > 1_000_000) return error.UpdateCheckNeverFinished;- std.Thread.yield() catch {};- }- bgop.finish(&m);- const text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, text, "running:") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "do not activate") != null);- const before = m.history.items.len;- _ = applyLine(&m, "/new");- const new_text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, new_text, "update") == null);- try std.testing.expect(std.mem.indexOf(u8, new_text, "activate") == null);- try std.testing.expect(m.history.items.len < before + 3);-}--test "/cache opens the same observability overlay" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/cache");- try std.testing.expectEqual(app.Overlay.debug, m.overlay);-}--test "/version checks in the background and reports the running executable boundary" {- engine.g_version_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8 {- return gpa.dupe(u8, "graff v0.0.291 (running process)\nlatest release: v0.0.292 — update available\n/new and /resume do not reload the executable.\n") catch null;- }- }.f;- defer engine.g_version_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/version");- try std.testing.expect(m.bg != null);- try std.testing.expectEqual(engine.BgOp.Kind.version, m.bg.?.kind);- try std.testing.expectEqual(app.EntryKind.pending, m.history.items[0].kind);- var spins: usize = 0;- while (!m.bg.?.done.load(.acquire)) : (spins += 1) {- if (spins > 1_000_000) return error.VersionCheckNeverFinished;- std.Thread.yield() catch {};- }- bgop.finish(&m);- const text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, text, "running process") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "/new and /resume") != null);-}--test "/usage is not a char-count view" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/usage");- const text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, text, "chars sent") == null);- try std.testing.expect(std.mem.indexOf(u8, text, "no session sink") != null);-}--test "rewind drops the last user turn" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "one");- try m.push(.assistant, "two");- rewind(&m);- try std.testing.expectEqual(@as(usize, 1), m.history.items.len); // rewind notice-}--test "core pager commands change shipped model state" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(Effect.quit, applyLine(&m, "/exit"));- m.quit_requested = false;- try std.testing.expectEqual(Effect.quit, applyLine(&m, "/q"));- m.quit_requested = false;-- _ = applyLine(&m, "/help");- try std.testing.expectEqual(app.Overlay.help, m.overlay);- m.closeOverlay();-- try m.push(.user, "stay");- _ = applyLine(&m, "/home");- try std.testing.expectEqual(app.Screen.welcome, m.screen);- try std.testing.expectEqual(app.Focus.prompt, m.focus);-- try std.testing.expectEqual(app.AgentMode.normal, m.mode);- _ = applyLine(&m, "/plan");- try std.testing.expectEqual(app.AgentMode.plan, m.mode);- _ = applyLine(&m, "/plan");- try std.testing.expectEqual(app.AgentMode.normal, m.mode);- _ = applyLine(&m, "/always-approve");- try std.testing.expectEqual(app.AgentMode.always_approve, m.mode);- _ = applyLine(&m, "/yolo");- try std.testing.expectEqual(app.AgentMode.normal, m.mode);-- _ = applyLine(&m, "/settings");- try std.testing.expectEqual(app.Overlay.settings, m.overlay);- m.closeOverlay();-- _ = applyLine(&m, "/model");- try std.testing.expectEqual(app.Overlay.model, m.overlay);- m.closeOverlay();-- _ = applyLine(&m, "/clear");- try std.testing.expectEqual(app.Screen.welcome, m.screen);-}--test "/usage with a session HUD is the cost line, not chars" {- engine.g_hud_fn = struct {- fn f(kind: engine.HudKind, buf: []u8) usize {- if (kind != .usage) return 0;- const s = "1 api call(s) · 1200 in (200 cached) + 50 out tokens · $0.0123\n";- const n = @min(s.len, buf.len);- @memcpy(buf[0..n], s[0..n]);- return n;- }- }.f;- defer engine.g_hud_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/cost");- const text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, text, "api call(s)") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "$0.0123") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "chars sent") == null);- try std.testing.expect(std.mem.indexOf(u8, text, "offline") == null);-}--test "/doctor uses the session HUD, not a chrome-only status line (#321)" {- engine.g_hud_fn = struct {- fn f(kind: engine.HudKind, buf: []u8) usize {- if (kind != .doctor) return 0;- const s = "info GOAL_STATE no standing goal\n no goal is set.\ninfo JOB_STATE no background jobs\n";- const n = @min(s.len, buf.len);- @memcpy(buf[0..n], s[0..n]);- return n;- }- }.f;- defer engine.g_hud_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/doctor");- const text = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, text, "GOAL_STATE") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "ok · model=") == null);-}--test "/doctor via Term paints GOAL_STATE, not a chrome ok line (#321)" {- engine.g_hud_fn = struct {- fn f(kind: engine.HudKind, buf: []u8) usize {- if (kind != .doctor) return 0;- const s = "info GOAL_STATE no standing goal\n no goal is set.\n";- const n = @min(s.len, buf.len);- @memcpy(buf[0..n], s[0..n]);- return n;- }- }.f;- defer engine.g_hud_fn = null;- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("/doctor");- _ = term.enter();- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "GOAL_STATE") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "ok · model=") == null);-}--test "every slash name printed in /help dispatches" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.help);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try @import("chrome.zig").overlay(&m, arena.allocator(), 80);- m.closeOverlay();-- var seen: usize = 0;- var i: usize = 0;- while (i < text.len) {- if (text[i] != '/') {- i += 1;- continue;- }- var j = i + 1;- while (j < text.len and (std.ascii.isAlphanumeric(text[j]) or text[j] == '-')) j += 1;- if (j == i + 1) {- i += 1;- continue;- }- const name = text[i..j];- const before = m.history.items.len;- const effect = applyLine(&m, name);- if (std.mem.eql(u8, name, "/quit") or std.mem.eql(u8, name, "/exit") or std.mem.eql(u8, name, "/q")) {- try std.testing.expectEqual(Effect.quit, effect);- m.quit_requested = false;- } else {- try std.testing.expectEqual(Effect.stay, effect);- }- if (m.history.items.len > before) {- const last = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, last, "unknown command") == null);- }- seen += 1;- i = j;- }- try std.testing.expect(seen >= 9);-}--test "a mistyped command is refused locally with the nearest spelling (#1275)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(Effect.stay, applyLine(&m, "/resuem"));- try std.testing.expect(m.pending == null); // no model turn- try std.testing.expectEqualStrings("unknown command: /resuem — did you mean /resume?", m.history.items[m.history.items.len - 1].text);- _ = applyLine(&m, "/xyzzy");- try std.testing.expectEqualStrings("unknown command: /xyzzy — try /help", m.history.items[m.history.items.len - 1].text);-}--test "/image attaches a path the next send carries as @[path]" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = applyLine(&m, "/image /tmp/shot.png");- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- _ = applyLine(&m, "what is this");- var user_text: []const u8 = "";- for (m.history.items) |e| {- if (e.kind == .user) user_text = e.text;- }- try std.testing.expect(std.mem.indexOf(u8, user_text, "@[/tmp/shot.png]") != null);- try std.testing.expect(std.mem.indexOf(u8, user_text, "what is this") != null);- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);-}--test "looksLikeImagePath accepts file URLs and extensions" {- try std.testing.expect(looksLikeImagePath("/tmp/a.png"));- try std.testing.expect(looksLikeImagePath("file:///Users/me/x.JPEG"));- try std.testing.expect(!looksLikeImagePath("hello.png is a format"));- try std.testing.expect(!looksLikeImagePath("readme.md"));- try std.testing.expect(looksLikeImagePath("/Users/me/My Shot.png"));- try std.testing.expect(!looksLikeImagePath("see /tmp/a.png"));-}--test "/effort with no arg opens the effort menu" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.effort = .high;- try std.testing.expectEqual(app.Effect.stay, applyLine(&m, "/effort"));- try std.testing.expectEqual(app.Overlay.effort, m.overlay);- try std.testing.expectEqual(@as(usize, @intFromEnum(engine.Effort.high)), m.overlay_sel);- try std.testing.expectEqual(app.Effect.stay, applyLine(&m, "/effort low"));- try std.testing.expectEqual(engine.Effort.low, m.effort);-}--test "/vim-mode toggles and /jump without turns explains" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expect(!m.vim_mode);- _ = applyLine(&m, "/vim-mode");- try std.testing.expect(m.vim_mode);- _ = applyLine(&m, "/vim");- try std.testing.expect(!m.vim_mode);- _ = applyLine(&m, "/jump");- const last = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, last, "nothing to jump") != null);- try m.push(.user, "hi");- _ = applyLine(&m, "/jump");- try std.testing.expectEqual(app.Overlay.jump, m.overlay);-}--test "/btw queues an aside while a turn is pending" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- m.pending = job;- defer {- m.pending = null;- std.testing.allocator.destroy(job);- }- _ = applyLine(&m, "/btw remember the tests");- try std.testing.expectEqual(@as(usize, 1), m.steer_queue.items.len);- try std.testing.expectEqualStrings("remember the tests", m.steer_queue.items[0]);-}--test "steer queues @[path] with the text so drain sends pixels" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- m.pending = job;- defer {- m.pending = null;- std.testing.allocator.destroy(job);- }- m.attachImage("/tmp/shot.png");- try m.input.setValue("look at this");- turn.steerEnter(&m);- try std.testing.expectEqual(@as(usize, 1), m.steer_queue.items.len);- try std.testing.expect(std.mem.indexOf(u8, m.steer_queue.items[0], "@[/tmp/shot.png]") != null);- try std.testing.expect(std.mem.indexOf(u8, m.steer_queue.items[0], "look at this") != null);- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);- try std.testing.expectEqualStrings("", m.input.getValue());-- m.pending = null;- _ = turn.drainSteer(&m);- var user_text: []const u8 = "";- for (m.history.items) |e| {- if (e.kind == .user) user_text = e.text;- }- try std.testing.expect(std.mem.indexOf(u8, user_text, "@[/tmp/shot.png]") != null);- try std.testing.expect(std.mem.indexOf(u8, user_text, "look at this") != null);- try std.testing.expectEqual(@as(usize, 0), m.steer_queue.items.len);-}--test "image-only steer queues the chip, empty Enter does not cancel" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- m.pending = job;- defer {- m.pending = null;- std.testing.allocator.destroy(job);- }- m.attachImage("/tmp/only.png");- turn.steerEnter(&m);- try std.testing.expectEqual(@as(usize, 1), m.steer_queue.items.len);- try std.testing.expect(std.mem.indexOf(u8, m.steer_queue.items[0], "@[/tmp/only.png]") != null);- try std.testing.expect(!m.cancel_requested);- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);-}--var captured_op: engine.GoalOp = .none;-var captured_goal: []const u8 = "";-var publish_count: u32 = 0;--fn captureGoal(_: ?*anyopaque, state: engine.SessionState) void {- captured_op = state.goal_op;- captured_goal = state.goal;- publish_count += 1;-}--test "/goal pause and clear are lifecycle verbs, not objectives (#716)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- engine.g_state_fn = captureGoal;- defer engine.g_state_fn = null;- publish_count = 0;-- _ = applyLine(&m, "/goal ship it");- try std.testing.expectEqualStrings("ship it", m.goal.?);- try std.testing.expectEqual(engine.GoalOp.set, captured_op);- try std.testing.expectEqualStrings("ship it", captured_goal);-- _ = applyLine(&m, "/goal pause");- try std.testing.expectEqualStrings("ship it", m.goal.?);- try std.testing.expectEqual(engine.GoalOp.pause, captured_op);- const paused = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, paused, "paused") != null);-- _ = applyLine(&m, "/goal clear");- try std.testing.expect(m.goal == null);- try std.testing.expectEqual(engine.GoalOp.clear, captured_op);- try std.testing.expectEqualStrings("", captured_goal);-}--test "/goal status and bare /goal do not publish an objective (#716)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- engine.g_state_fn = captureGoal;- defer engine.g_state_fn = null;- publish_count = 0;-- _ = applyLine(&m, "/goal");- try std.testing.expectEqual(@as(u32, 0), publish_count);- try std.testing.expect(m.goal == null);- const bare = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, bare, "No active goal") != null);-- _ = applyLine(&m, "/goal ship it");- const after_set = publish_count;- _ = applyLine(&m, "/goal status");- _ = applyLine(&m, "/goals");- _ = applyLine(&m, "/goals pause");- try std.testing.expectEqual(after_set, publish_count);- try std.testing.expectEqualStrings("ship it", m.goal.?);- const status = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, status, "ship it") != null);-}--test "lastLines caps ! output to the tail" {- try std.testing.expectEqualStrings("c\nd", lastLines("a\nb\nc\nd", 2));- try std.testing.expectEqualStrings("a\nb", lastLines("a\nb", 5));-}--var handed_buf: [128]u8 = undefined;-var handed_len: usize = 0;-var hand_accepts = true;-fn fakeSteerSend(text: []const u8) bool {- if (!hand_accepts) return false;- handed_len = @min(text.len, handed_buf.len);- @memcpy(handed_buf[0..handed_len], text[0..handed_len]);- return true;-}--fn pendingModel(m: *Model) !*engine.Job {- m.setup(std.testing.allocator);- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- m.pending = job;- return job;-}--test "Enter mid-turn hands plain text to the running turn" {- var m: Model = undefined;- const job = try pendingModel(&m);- defer {- m.pending = null;- std.testing.allocator.destroy(job);- m.deinit();- }- engine.g_steer_send_fn = fakeSteerSend;- defer engine.g_steer_send_fn = null;- hand_accepts = true;- handed_len = 0;- try m.input.setValue("also run the tests");- turn.steerEnter(&m);- try std.testing.expectEqualStrings("also run the tests", handed_buf[0..handed_len]);- try std.testing.expectEqual(@as(usize, 0), m.steer_queue.items.len);- try std.testing.expectEqualStrings("", m.input.getValue());- try std.testing.expect(std.mem.indexOf(u8, m.history.items[m.history.items.len - 1].text, "sent to the running turn") != null);-}--test "commands, images, /btw and a refused hand-off still wait for the turn" {- var m: Model = undefined;- const job = try pendingModel(&m);- defer {- m.pending = null;- std.testing.allocator.destroy(job);- m.deinit();- }- engine.g_steer_send_fn = fakeSteerSend;- defer engine.g_steer_send_fn = null;- hand_accepts = true;- handed_len = 0;- try m.input.setValue("/model gpt-6");- turn.steerEnter(&m);- m.attachImage("/tmp/shot.png");- try m.input.setValue("look at this");- turn.steerEnter(&m);- _ = applyLine(&m, "/btw remember the tests");- hand_accepts = false;- try m.input.setValue("plain but refused");- turn.steerEnter(&m);- try std.testing.expectEqual(@as(usize, 0), handed_len); // nothing was handed over- try std.testing.expectEqual(@as(usize, 4), m.steer_queue.items.len);- try std.testing.expectEqualStrings("remember the tests", m.steer_queue.items[2]);- try std.testing.expectEqualStrings("plain but refused", m.steer_queue.items[3]);-}diff --git a/TUI/dispatch_tests.zig b/TUI/dispatch_tests.zigdeleted file mode 100644index 49438656..00000000--- a/TUI/dispatch_tests.zig+++ /dev/null@@ -1,381 +0,0 @@-//! dispatch.zig tests that outgrew the 600-line source cap.--const std = @import("std");--const app = @import("app.zig");-const bgop = @import("bgop.zig");-const dispatch = @import("dispatch.zig");-const engine = @import("engine.zig");-const overlays = @import("overlays.zig");-const Model = app.Model;--/// Spin until the background op finishes, then apply it — what run.zig's loop-/// does every frame while the frame keeps painting.-fn settle(m: *Model) !void {- var spins: usize = 0;- while (m.bg) |op| {- if (op.done.load(.acquire)) break;- spins += 1;- if (spins > 1_000_000) return error.OpNeverFinished;- std.Thread.yield() catch {};- }- bgop.finish(m);-}--test "! runs through the bash callback in the background and lands in the scrollback (#533)" {- engine.g_bash_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, _: engine.Params) ?[]const u8 {- return std.fmt.allocPrint(gpa, "ran: {s}", .{cmd}) catch null;- }- }.f;- defer engine.g_bash_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = dispatch.applyLine(&m, "!git status");- // The command is OFF the render thread: applyLine already returned.- try std.testing.expect(m.bg != null);- try settle(&m);- try std.testing.expectEqual(@as(usize, 2), m.history.items.len);- try std.testing.expectEqualStrings("$ git status", m.history.items[0].text);- try std.testing.expectEqualStrings("ran: git status", m.history.items[1].text);- try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);-}--test "a model turn cannot start while /compact is rewriting the history (#533)" {- engine.g_compact_fn = struct {- fn f(_: ?*anyopaque, _: std.mem.Allocator, _: []const engine.Turn, _: *engine.CompactOut) bool {- return false;- }- }.f;- defer engine.g_compact_fn = null;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.chat = true;- try m.push(.user, "one");- dispatch.compact(&m);- try std.testing.expect(m.bg != null);- try std.testing.expectEqual(app.Effect.stay, dispatch.applyLine(&m, "next question"));- try std.testing.expect(m.pending == null);- const last = m.history.items[m.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, last, "still running") != null);- try settle(&m);- try std.testing.expect(m.bg == null);-}--test "rapid same-batch /compact then /model cannot mutate the shared engine context" {- const Fake = struct {- var model_calls: usize = 0;- var release = std.atomic.Value(bool).init(false);- fn compact(_: ?*anyopaque, _: std.mem.Allocator, _: []const engine.Turn, _: *engine.CompactOut) bool {- while (!release.load(.acquire)) std.Thread.yield() catch {};- return false;- }- fn model(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const u8, name: []const u8) ?engine.Picked {- model_calls += 1;- return .{ .model = gpa.dupe(u8, name) catch return null, .provider = "next-provider" };- }- };- Fake.model_calls = 0;- Fake.release.store(false, .release);- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- engine.g_compact_fn = Fake.compact;- engine.g_model_fn = Fake.model;- engine.g_model_name = "old-model";- engine.g_model_provider = "old-provider";- const entries = [_]engine.ModelEntry{.{ .name = "next", .provider = "next-provider", .has_key = true }};- engine.g_model_entries = &entries;- defer {- Fake.release.store(true, .release);- engine.g_compact_fn = null;- engine.g_model_fn = null;- engine.g_model_name = "";- engine.g_model_provider = "";- engine.g_model_entries = &.{};- }-- var batch: pacing.Batch = .{};- for ("/compact") |c| try std.testing.expectEqual(pacing.Push.ok, batch.push(.{ .char = c }));- try std.testing.expectEqual(pacing.Push.ok, batch.push(.enter));- for ("/model next") |c| try std.testing.expectEqual(pacing.Push.ok, batch.push(.{ .char = c }));- try std.testing.expectEqual(pacing.Push.ok, batch.push(.enter));- for (batch.items()) |item| try std.testing.expectEqual(app.Effect.stay, keys.handleBatchItem(&m, item));-- try std.testing.expect(m.bg != null);- try std.testing.expect(!m.bg.?.done.load(.acquire));- try std.testing.expectEqual(@as(usize, 0), Fake.model_calls);- try std.testing.expectEqualStrings("old-model", engine.g_model_name);- _ = dispatch.runCommand(&m, "/model"); // browsing is UI-only and remains available- try std.testing.expectEqual(app.Overlay.model, m.overlay);- try std.testing.expectEqual(app.Effect.stay, overlays.activate(&m));- try std.testing.expectEqual(@as(usize, 0), Fake.model_calls);-- Fake.release.store(true, .release);- try settle(&m);- _ = dispatch.runCommand(&m, "/model next");- try std.testing.expectEqual(@as(usize, 1), Fake.model_calls);- try std.testing.expectEqualStrings("next", engine.g_model_name);-}--test "/new /compact /rewind are blocked while a job is pending (#521)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .threaded = false,- .gpa = std.testing.allocator,- .history = try std.testing.allocator.alloc(engine.Turn, 0),- .params = .{},- .stream = .{},- };- m.pending = job;- _ = dispatch.runCommand(&m, "/new");- try std.testing.expect(m.pending != null);- try std.testing.expectEqualStrings("hi", m.history.items[0].text);- try std.testing.expect(std.mem.indexOf(u8, m.history.items[1].text, "still running") != null);- _ = dispatch.runCommand(&m, "/rewind");- _ = dispatch.runCommand(&m, "/compact");- try std.testing.expectEqualStrings("hi", m.history.items[0].text);-}--test "cutting the transcript reaches the engine's conversation (#551)" {- // The model's history lives in the engine now, so a TUI-local truncation- // that never told it left the discarded turns in the next request body.- const Seen = struct {- var ops: std.ArrayList(engine.HistoryOp) = .empty;- fn f(_: ?*anyopaque, op: engine.HistoryOp) void {- ops.append(std.testing.allocator, op) catch {};- }- };- Seen.ops = .empty;- defer Seen.ops.deinit(std.testing.allocator);- engine.g_history_fn = Seen.f;- defer engine.g_history_fn = null;-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "alpha");- try m.push(.assistant, "beta");-- _ = dispatch.applyLine(&m, "/rewind");- try std.testing.expectEqual(@as(usize, 1), Seen.ops.items.len);- try std.testing.expectEqual(engine.HistoryOp.rewind, Seen.ops.items[0]);-- _ = dispatch.applyLine(&m, "/new");- try std.testing.expectEqual(@as(usize, 2), Seen.ops.items.len);- try std.testing.expectEqual(engine.HistoryOp.reset, Seen.ops.items[1]);-- // /clear is the same command under another name, and Ctrl+N (twice) is the- // same session reset from the keyboard.- _ = dispatch.applyLine(&m, "/clear");- try std.testing.expectEqual(engine.HistoryOp.reset, Seen.ops.items[Seen.ops.items.len - 1]);- const before = Seen.ops.items.len;-- // Compaction must NOT come through here: it REWROTE the conversation, and- // resetting on the replay would throw away the summary it just produced.- engine.g_compact_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, out: *engine.CompactOut) bool {- out.note = gpa.dupe(u8, "history compacted") catch "";- const turns = gpa.alloc(engine.Turn, 1) catch return false;- turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "Context: earlier work") catch "" };- out.turns = turns;- return true;- }- }.f;- defer engine.g_compact_fn = null;- try m.push(.user, "gamma");- _ = dispatch.applyLine(&m, "/compact");- try settle(&m);- try std.testing.expectEqual(before, Seen.ops.items.len);-}--test "a live engine call blocks every path that would free its history (#551)" {- // The reset/rewind seam frees the arena the running turn allocates its- // history from, so "just clear the screen" would be a use-after-free on- // the turn thread. Ctrl+N never went through runCommand's #521 guard.- const Seen = struct {- var n: usize = 0;- fn f(_: ?*anyopaque, _: engine.HistoryOp) void {- n += 1;- }- };- Seen.n = 0;- engine.g_history_fn = Seen.f;- defer engine.g_history_fn = null;-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "alpha");- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .threaded = false,- .gpa = std.testing.allocator,- .history = try std.testing.allocator.alloc(engine.Turn, 0),- .params = .{},- .stream = .{},- };- m.pending = job;-- try std.testing.expect(!m.newSession());- dispatch.rewind(&m);- try std.testing.expectEqual(@as(usize, 0), Seen.n);- try std.testing.expectEqualStrings("alpha", m.history.items[0].text);-- m.pending = null;- std.testing.allocator.free(job.history);- std.testing.allocator.destroy(job);-- // With the engine idle both reach it again.- try std.testing.expect(m.newSession());- try std.testing.expectEqual(@as(usize, 1), Seen.n);-}--test "/compact never crops locally; engine stub rewrites history" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "alpha");- try m.push(.assistant, "beta");- try m.push(.user, "gamma");- _ = dispatch.applyLine(&m, "/compact");- try std.testing.expectEqual(@as(usize, 4), m.history.items.len); // 3 + notice- try std.testing.expect(std.mem.indexOf(u8, m.history.items[3].text, "live session") != null);-- engine.g_compact_fn = struct {- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, out: *engine.CompactOut) bool {- out.note = gpa.dupe(u8, "history compacted to a 12-char summary") catch "";- const turns = gpa.alloc(engine.Turn, 1) catch return false;- turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "Context: earlier work") catch "" };- out.turns = turns;- return true;- }- }.f;- defer engine.g_compact_fn = null;- _ = dispatch.applyLine(&m, "/compact");- try settle(&m); // the engine call runs off the render thread now (#533)- try std.testing.expectEqual(@as(usize, 2), m.history.items.len);- try std.testing.expectEqual(app.EntryKind.system, m.history.items[0].kind);- try std.testing.expectEqual(app.EntryKind.user, m.history.items[1].kind);- try std.testing.expectEqualStrings("Context: earlier work", m.history.items[1].text);-}--// --- input pacing: what one tick of a wheel storm dispatches ----------------// The batch is built exactly as run.zig builds it and applied through the real-// keys.zig door, so these pin the DISPATCHED behaviour, not just the struct.--const key_mod = @import("key.zig");-const keys = @import("keys.zig");-const pacing = @import("pacing.zig");--fn wheelUp() key_mod.Key {- return .{ .mouse = .{ .btn = 64, .x = 4, .y = 4, .down = true } };-}--fn wheelDown() key_mod.Key {- return .{ .mouse = .{ .btn = 65, .x = 4, .y = 4, .down = true } };-}--/// Feed a tick's worth of events through the coalescer and apply the batch the-/// way run.zig does.-fn tick(m: *Model, evs: []const key_mod.Key) void {- var b: pacing.Batch = .{};- for (evs) |k| std.debug.assert(b.push(k) == .ok);- for (b.items()) |item| {- _ = keys.handleBatchItem(m, item);- }-}--test "5 wheel-up + a key + 3 wheel-down coalesce to +5, the key, then -3" {- var b: pacing.Batch = .{};- for (0..5) |_| _ = b.push(wheelUp());- _ = b.push(.{ .char = 'z' });- for (0..3) |_| _ = b.push(wheelDown());-- const it = b.items();- try std.testing.expectEqual(@as(usize, 3), it.len);- try std.testing.expectEqual(@as(i32, 5), it[0].wheel);- try std.testing.expectEqual(@as(u8, 'z'), it[1].key.char);- try std.testing.expectEqual(@as(i32, -3), it[2].wheel);-}--test "a coalesced tick lands on the same scroll a report-at-a-time tick would" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- var evs: [9]key_mod.Key = undefined;- for (0..5) |k| evs[k] = wheelUp();- evs[5] = .{ .char = 'z' };- for (6..9) |k| evs[k] = wheelDown();- tick(&m, &evs);- // 5 notches back, 3 forward, 3 lines a notch: +6 lines, and the keystroke- // reached the composer in its own place in the stream.- try std.testing.expectEqual(@as(usize, 6), m.scroll);- try std.testing.expect(!m.follow);- try std.testing.expectEqualStrings("z", m.input.getValue());-}--test "typing is never starved behind a wheel flood" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- // 400 reports with three keystrokes buried in the middle of them — one- // tick, and every character still arrives, in order.- var b: pacing.Batch = .{};- for (0..200) |_| _ = b.push(wheelUp());- _ = b.push(.{ .char = 'h' });- for (0..100) |_| _ = b.push(wheelUp());- _ = b.push(.{ .char = 'i' });- for (0..100) |_| _ = b.push(wheelDown());- _ = b.push(.{ .char = '!' });- // 400 wheel reports collapse into 3 units of scroll work.- try std.testing.expectEqual(@as(usize, 6), b.len);- for (b.items()) |item| {- _ = keys.handleBatchItem(&m, item);- }- try std.testing.expectEqualStrings("hi!", m.input.getValue());- try std.testing.expectEqual(@as(usize, 600), m.scroll); // (200+100-100)*3-}--test "a mixed run at the bottom edge does not re-latch follow mid-tick" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- // Two notches from the bottom, then down-down-up: a net notch back. Applied- // report by report the second down clamps at 0 and turns `follow` on, and- // the trailing up then scrolls away from where the fingers stopped.- keys.scrollBy(&m, 6);- tick(&m, &.{ wheelDown(), wheelDown(), wheelUp() });- try std.testing.expectEqual(@as(usize, 3), m.scroll);- try std.testing.expect(!m.follow);-}--test "the same run reaching the bottom still lands there and follows" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- keys.scrollBy(&m, 3);- tick(&m, &.{ wheelDown(), wheelDown() });- try std.testing.expectEqual(@as(usize, 0), m.scroll);- try std.testing.expect(m.follow);-}--test "a single wheel report is unchanged by the coalescer" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- tick(&m, &.{wheelUp()});- try std.testing.expectEqual(@as(usize, 3), m.scroll);- var direct: Model = undefined;- direct.setup(std.testing.allocator);- defer direct.deinit();- _ = keys.handle(&direct, wheelUp());- try std.testing.expectEqual(m.scroll, direct.scroll);- try std.testing.expectEqual(m.follow, direct.follow);-}diff --git a/TUI/dump.zig b/TUI/dump.zigdeleted file mode 100644index 58fbd4ce..00000000--- a/TUI/dump.zig+++ /dev/null@@ -1,104 +0,0 @@-//! Visible-terminal dump and layout debug for the pager frame.-//! Strips SGR / Kitty APC so a reader sees the same glyphs as a user.-//! Agents that need to type or click use TUI/sim.zig (`Term`), not a PTY.--const std = @import("std");-const app = @import("app.zig");-const Model = app.Model;--/// SGR/APC/OSC stripped; one screen row per line. Caller owns the slice.-pub fn visible(a: std.mem.Allocator, frame: []const u8) ![]u8 {- var out = std.array_list.Managed(u8).init(a);- var i: usize = 0;- while (i < frame.len) {- if (frame[i] == 0x1b) {- i = skipEsc(frame, i);- continue;- }- if (frame[i] == '\r') {- i += 1;- continue;- }- try out.append(frame[i]);- i += 1;- }- return out.toOwnedSlice();-}--fn skipEsc(s: []const u8, start: usize) usize {- var i = start + 1;- if (i >= s.len) return s.len;- const c = s[i];- if (c == '[') {- i += 1;- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) i += 1;- if (i < s.len) i += 1;- return i;- }- // OSC ] DCS P SOS X PM ^ APC _ (Kitty graphics is APC _G)- if (c == ']' or c == 'P' or c == 'X' or c == '^' or c == '_') {- i += 1;- while (i < s.len) {- if (s[i] == 0x07) return i + 1;- if (s[i] == 0x1b and i + 1 < s.len and s[i + 1] == '\\') return i + 2;- i += 1;- }- return i;- }- return i + 1;-}--/// Layout the cost HUD does not show. Stack buffer; no allocation.-pub fn layoutBuf(buf: []u8, self: *const Model) []const u8 {- return std.fmt.bufPrint(buf,- \\layout- \\ overlay {s}- \\ focus {s}- \\ prompt-origin {d}- \\ mid-origin {d}- \\ images {d}- \\ pending {s}- \\- , .{- @tagName(self.overlay),- @tagName(self.focus),- self.prompt_origin,- self.mid_origin,- self.images.items.len,- if (self.pending != null) "yes" else "no",- }) catch "";-}--pub fn layout(a: std.mem.Allocator, self: *const Model) ![]u8 {- var buf: [256]u8 = undefined;- return a.dupe(u8, layoutBuf(&buf, self));-}--test "visible strips SGR and Kitty APC and keeps row breaks" {- const raw = "\x1b[32mhi\x1b[0m\n\x1b_Ga=T,f=100,t=f;abc\x1b\\there\n";- const got = try visible(std.testing.allocator, raw);- defer std.testing.allocator.free(got);- try std.testing.expectEqualStrings("hi\nthere\n", got);- try std.testing.expect(std.mem.indexOf(u8, got, "\x1b") == null);-}--test "layout names overlay focus origins images pending" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.prompt_origin = 18;- m.mid_origin = 1;- m.attachImage("/tmp/a.png");- const text = try layout(std.testing.allocator, &m);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "overlay none") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "focus prompt") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "prompt-origin 18") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "mid-origin 1") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "images 1") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "pending no") != null);- m.openOverlay(.debug);- const after = try layout(std.testing.allocator, &m);- defer std.testing.allocator.free(after);- try std.testing.expect(std.mem.indexOf(u8, after, "overlay debug") != null);-}diff --git a/TUI/effort.zig b/TUI/effort.zigdeleted file mode 100644index a4d08e11..00000000--- a/TUI/effort.zig+++ /dev/null@@ -1,144 +0,0 @@-//! Searchable reasoning-effort picker — same shape as the model overlay.--const std = @import("std");-const app = @import("app.zig");-const engine = @import("engine.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--pub const all = std.meta.tags(engine.Effort);--fn blurb(e: engine.Effort) []const u8 {- return switch (e) {- .low => "faster, shorter thoughts",- .medium => "default",- .high => "deeper reasoning",- .xhigh => "extra-deep",- .max => "maximum",- .ultra => "ultra + workflow",- };-}--fn hides(e: engine.Effort) bool {- const p = engine.g_model_provider;- const m = engine.g_model_name;- if (std.mem.eql(u8, p, "xai") or std.mem.startsWith(u8, m, "grok"))- return e == .max or e == .ultra;- if (std.mem.eql(u8, p, "openai") or std.mem.eql(u8, p, "codex") or- std.mem.startsWith(u8, m, "gpt-") or std.mem.startsWith(u8, m, "openai/gpt-"))- return e == .max;- return false;-}--pub fn filter(query: []const u8, out: []engine.Effort) usize {- var n: usize = 0;- for (all) |e| {- if (hides(e)) continue;- const name = @tagName(e);- if (query.len > 0 and std.mem.indexOf(u8, name, query) == null) continue;- if (n >= out.len) break;- out[n] = e;- n += 1;- }- return n;-}--pub fn pick(self: *const Model) ?engine.Effort {- var buf: [all.len]engine.Effort = undefined;- const n = filter(self.overlay_filter, &buf);- if (n == 0) return null;- return buf[self.overlay_sel % n];-}--/// The panel's top-edge slots (overlaypane.zig places them).-pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {- var names: [all.len]engine.Effort = undefined;- return .{- .title = try std.fmt.allocPrint(a, "Effort › {s}\u{258B}", .{self.overlay_filter}),- .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ filter(self.overlay_filter, &names), all.len }),- };-}--pub const hint = "type to filter · ↑↓ move · click or Enter picks · Esc";--/// The ROWS only — the frame carries the rest.-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var names: [all.len]engine.Effort = undefined;- const n = filter(self.overlay_filter, &names);- var out = std.array_list.Managed(u8).init(a);- if (n == 0) {- try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches\n"));- return out.items;- }- const sel = self.overlay_sel % n;- for (names[0..n], 0..) |e, i| {- const mark: []const u8 = if (i == sel) "› " else " ";- const cur: []const u8 = if (e == self.effort) " (current)" else "";- const line = try std.fmt.allocPrint(a, "{s}{s:<8} {s}{s}", .{ mark, @tagName(e), blurb(e), cur });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- return out.items;-}--test "filter matches effort names" {- var buf: [8]engine.Effort = undefined;- try std.testing.expectEqual(@as(usize, 1), filter("low", &buf));- try std.testing.expectEqual(engine.Effort.low, buf[0]);- try std.testing.expectEqual(@as(usize, all.len), filter("", &buf));-}--test "seat effort lists and last-row keyboard selection" {- const saved_p = engine.g_model_provider;- const saved_m = engine.g_model_name;- defer {- engine.g_model_provider = saved_p;- engine.g_model_name = saved_m;- }- const openai_levels = [_]engine.Effort{ .low, .medium, .high, .xhigh, .ultra };- const grok_levels = [_]engine.Effort{ .low, .medium, .high, .xhigh };- const cases = [_]struct { provider: []const u8, model: []const u8, levels: []const engine.Effort }{- .{ .provider = "openai", .model = "o3", .levels = &openai_levels },- .{ .provider = "codex", .model = "codex", .levels = &openai_levels },- .{ .provider = "proxy", .model = "gpt-5", .levels = &openai_levels },- .{ .provider = "proxy", .model = "openai/gpt-5", .levels = &openai_levels },- .{ .provider = "xai", .model = "gpt-5", .levels = &grok_levels },- .{ .provider = "openai", .model = "grok-4.6", .levels = &grok_levels },- .{ .provider = "other", .model = "other", .levels = all },- };- for (cases) |case| {- engine.g_model_provider = case.provider;- engine.g_model_name = case.model;- var buf: [8]engine.Effort = undefined;- const n = filter("", &buf);- try std.testing.expectEqualSlices(engine.Effort, case.levels, buf[0..n]);-- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- term.model.openOverlay(.effort);- term.model.overlay_sel = 0;- for (1..n) |_| _ = term.feed("\x1b[B");- try std.testing.expectEqual(case.levels[n - 1], pick(&term.model).?);- _ = term.enter();- try std.testing.expectEqual(case.levels[n - 1], term.model.effort);- }-}--test "effort overlay lists levels and marks current" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.effort = .high;- m.openOverlay(.effort);- m.overlay_sel = @intFromEnum(m.effort);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- try std.testing.expect(std.mem.indexOf(u8, (try head(&m, arena.allocator())).title, "Effort ›") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "low") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "high") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "(current)") != null);-}diff --git a/TUI/engine.zig b/TUI/engine.zigdeleted file mode 100644index 6c113923..00000000--- a/TUI/engine.zig+++ /dev/null@@ -1,240 +0,0 @@-//! Frontend-agnostic types the TUI uses to talk to a turn backend.-//! The package never imports the harness: session glue supplies callbacks.--const std = @import("std");-const builtin = @import("builtin");-const types = @import("engine_types.zig");--const events_mod = @import("events.zig");--pub const Event = events_mod.Event;-pub const EventQueue = events_mod.Queue;-pub const ToolEvent = events_mod.Tool;-pub const Status = events_mod.Status;-pub const ModelChanged = events_mod.ModelChanged;-pub const Cost = events_mod.Cost;--pub const Effort = types.Effort;-pub const Mode = types.Mode;-pub const Turn = types.Turn;-pub const Params = types.Params;-pub const StreamBuf = types.StreamBuf;-pub const TurnFn = types.TurnFn;-pub const CostClass = types.CostClass;-pub const ModelEntry = types.ModelEntry;-pub const Picked = types.Picked;-pub const ModelFn = types.ModelFn;-pub const CancelFn = types.CancelFn;-pub const PasteFn = types.PasteFn;-pub const BashFn = types.BashFn;-pub const FilesFn = types.FilesFn;-pub const CopyFn = types.CopyFn;-pub const CompactOut = types.CompactOut;-pub const CompactFn = types.CompactFn;-pub const HistoryOp = types.HistoryOp;-pub const HistoryFn = types.HistoryFn;-pub const GoalOp = types.GoalOp;-pub const SessionState = types.SessionState;-pub const StateFn = types.StateFn;-pub const ResumeOut = types.ResumeOut;-pub const ResumeFn = types.ResumeFn;-pub const SessionsFn = types.SessionsFn;--pub const Job = struct {- thread: std.Thread = undefined,- threaded: bool = true,- done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),- /// Thread creation failed; finish still owns reporting and cleanup.- start_failed: bool = false,- result: ?[]const u8 = null,- gpa: std.mem.Allocator,- history: []Turn,- params: Params,- stream: StreamBuf,- /// grok-build RawTerminal tail: live bash_output_chunk bytes, not prose.- raw: StreamBuf = .{},- /// Typed engine events for this turn (#551). Attached to the model's- /// allocator by startJob; a Job literal that leaves it unattached simply- /// carries no events.- events: events_mod.Queue = .{},-};--/// The live job's raw bash tail. tui_sink writes here from the tool pool.-pub var g_raw: ?*StreamBuf = null;--/// Host sets this so a TUI steer can unstick a foreground shell wait.-pub const FollowupFn = *const fn () void;-pub var g_followup_fn: ?FollowupFn = null;--/// Host sets these so a plain-text follow-up typed mid-turn joins the running-/// turn: `send` hands it over (a streaming reply restarts with it), and-/// `reclaim` takes back any the turn ended before delivering, to run next.-pub const SteerSendFn = *const fn (text: []const u8) bool;-pub var g_steer_send_fn: ?SteerSendFn = null;-pub const SteerReclaimFn = *const fn (gpa: std.mem.Allocator, out: *std.array_list.Managed([]const u8)) void;-pub var g_steer_reclaim_fn: ?SteerReclaimFn = null;--/// Idle auto-wake: a finished background job wants a turn (grok-build notify).-pub const IdleWakeFn = *const fn (turn_ctx: ?*anyopaque, buf: []u8) ?[]const u8;-pub var g_idle_wake_fn: ?IdleWakeFn = null;--/// Run a peer-talk slash (`/tell`, `/peek`) on the live agent. The TUI does-/// not post to the room itself — the host implements this with the existing-/// mailbox (`tellCommand` / `peekCommand`). Caller frees the returned text.-pub const PeerFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, line: []const u8) ?[]const u8;-pub var g_peer_fn: ?PeerFn = null;-pub const ConstraintFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, line: []const u8) ?[]const u8;-pub var g_constraint_fn: ?ConstraintFn = null;-pub const VersionFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;-pub var g_version_fn: ?VersionFn = null;-pub const UpdateFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, action: []const u8) ?[]const u8;-pub var g_update_fn: ?UpdateFn = null;--/// A background engine op: `/compact`, `/version`, `/update`, `!cmd`, or the @-file list. Same-/// thread + done-flag contract as Job, so the render+input loop keeps painting-/// and Esc keeps reaching keys.handle while the engine works (#533). Every-/// field the worker writes is read only after `done`.-pub const BgOp = struct {- pub const Kind = enum { compact, bash, files, version, update };-- kind: Kind,- gpa: std.mem.Allocator,- thread: std.Thread = undefined,- threaded: bool = true,- done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),- /// Thread creation failed; finish still owns reporting and cleanup.- start_failed: bool = false,- /// Esc/Ctrl+C asked the engine to stop; the callbacks observe it through- /// the same cancel signal a turn uses.- cancelled: bool = false,- /// compact input — gpa-owned turns.- turns: []Turn = &.{},- /// bash input — gpa-owned command line.- cmd: []const u8 = "",- /// The session policy this op runs under, same as a turn's (#551).- params: Params = .{},- /// compact output — gpa-owned.- compact: CompactOut = .{},- ok: bool = false,- /// bash / files / version / update output — gpa-owned.- text: ?[]const u8 = null,-};--pub fn bgRun(op: *BgOp) void {- switch (op.kind) {- .compact => if (g_compact_fn) |f| {- op.ok = f(g_turn_ctx, op.gpa, op.turns, &op.compact);- },- .bash => if (g_bash_fn) |f| {- op.text = f(g_turn_ctx, op.gpa, op.cmd, op.params);- },- .files => if (g_files_fn) |f| {- op.text = f(g_turn_ctx, op.gpa);- },- .version => if (g_version_fn) |f| {- op.text = f(g_turn_ctx, op.gpa);- },- .update => if (g_update_fn) |f| {- op.text = f(g_turn_ctx, op.gpa, op.cmd);- },- }- op.done.store(true, .release);-}--pub const HudKind = enum { debug, usage, doctor };-pub const HudFn = *const fn (kind: HudKind, buf: []u8) usize;--/// Everything the host frontend hands the loop at startup: the callbacks that-/// reach the real agent and the facts the chrome renders from. Lives with the-/// seam it describes; `run.zig` re-exports it as `run.RunOpts`.-pub const RunOpts = struct {- turn_ctx: ?*anyopaque = null,- turn_fn: ?TurnFn = null,- model_fn: ?ModelFn = null,- cancel_fn: ?CancelFn = null,- model_name: []const u8 = "",- model_provider: []const u8 = "",- initial_history: []const Turn = &.{},- session_name: []const u8 = "",- initial_goal: []const u8 = "",- initial_strict: bool = false,- initial_ultracode: bool = false,- /// The model catalog with its provider column (see ModelEntry).- model_entries: []const ModelEntry = &.{},- cwd: []const u8 = ".",- yolo: bool = false,- hud_fn: ?HudFn = null,- paste_fn: ?PasteFn = null,- bash_fn: ?BashFn = null,- files_fn: ?FilesFn = null,- copy_fn: ?CopyFn = null,- compact_fn: ?CompactFn = null,- history_fn: ?HistoryFn = null,- resume_fn: ?ResumeFn = null,- sessions_fn: ?SessionsFn = null,- state_fn: ?StateFn = null,- emergency_fn: ?*const fn (turn_ctx: ?*anyopaque) void = null,- idle_wake_fn: ?IdleWakeFn = null,- peer_fn: ?PeerFn = null,- constraint_fn: ?ConstraintFn = null,- version_fn: ?VersionFn = null,- update_fn: ?UpdateFn = null,-};--pub var g_turn_fn: ?TurnFn = null;-pub var g_turn_ctx: ?*anyopaque = null;-pub var g_model_fn: ?ModelFn = null;-pub var g_cancel_fn: ?CancelFn = null;-pub var g_hud_fn: ?HudFn = null;-pub var g_paste_fn: ?PasteFn = null;-pub var g_bash_fn: ?BashFn = null;-pub var g_files_fn: ?FilesFn = null;-pub var g_copy_fn: ?CopyFn = null;-pub var g_compact_fn: ?CompactFn = null;-pub var g_history_fn: ?HistoryFn = null;-pub var g_resume_fn: ?ResumeFn = null;-pub var g_sessions_fn: ?SessionsFn = null;-pub var g_state_fn: ?StateFn = null;--/// Tell the engine the transcript was cut. Silent when nothing is wired-/// (offline TUI, unit tests).-pub fn historyChanged(op: HistoryOp) void {- if (g_history_fn) |f| f(g_turn_ctx, op);-}-pub var g_model_name: []const u8 = "";-/// Provider id serving `g_model_name`. Empty offline.-pub var g_model_provider: []const u8 = "";-/// The model catalog, provider column and all. Single source of truth for-/// every model surface in the TUI — there is no flat name-only string left.-pub var g_model_entries: []const ModelEntry = &.{};-pub var g_cwd: []const u8 = ".";--pub const JobSpawnFn = *const fn (*Job) anyerror!std.Thread;-pub const JobJoinObserver = *const fn () void;-var job_spawn_override: ?JobSpawnFn = null;-var job_join_observer: ?JobJoinObserver = null;--/// Deterministic test seam for thread creation and join accounting. Production-/// always takes the direct std.Thread paths below.-pub fn setJobThreadHooksForTesting(spawn: ?JobSpawnFn, join_observer: ?JobJoinObserver) void {- std.debug.assert(builtin.is_test);- job_spawn_override = spawn;- job_join_observer = join_observer;-}--pub fn spawnJob(job: *Job) !std.Thread {- if (builtin.is_test) if (job_spawn_override) |spawn| return spawn(job);- return std.Thread.spawn(.{}, jobRun, .{job});-}--pub fn joinJob(job: *Job) void {- if (!job.threaded) return;- if (builtin.is_test) if (job_join_observer) |observe| observe();- job.thread.join();-}--pub fn jobRun(job: *Job) void {- const reply = if (g_turn_fn) |f| f(g_turn_ctx, job.gpa, job.history, job.params, &job.stream, &job.events) else null;- job.result = reply;- job.done.store(true, .release);-}diff --git a/TUI/engine_types.zig b/TUI/engine_types.zigdeleted file mode 100644index 4eb1721f..00000000--- a/TUI/engine_types.zig+++ /dev/null@@ -1,200 +0,0 @@-//! Turn-backend value types and streaming buffer; no mutable frontend callbacks.-const std = @import("std");-const events_mod = @import("events.zig");--pub const Effort = enum { low, medium, high, xhigh, max, ultra };--/// The session's permission policy. This is ENGINE state, not a badge: the-/// turn backend maps it onto the harness's plan gate and approval policy-/// (repl_glue.replTurnCb). Before #551 round 2 the TUI kept its own copy and-/// the engine was never told, so a footer reading "Plan" sat over a turn that-/// was writing files.-pub const Mode = enum { normal, plan, always_approve };--pub const Turn = struct {- role: Role,- text: []const u8,- notification: bool = false,- pub const Role = enum { user, assistant };-};--pub const Params = struct {- effort: Effort = .medium,- fast: bool = false,- thinking: bool = false,- ultracode: bool = false,- /// Permission policy for this turn (Shift+Tab, Ctrl+O, /plan).- mode: Mode = .normal,- /// /strict — selects the strict system prompt on the turn's agent.- strict: bool = false,- goal: []const u8 = "",-};--/// Lock-free single-writer / single-reader preview buffer (same contract as-/// the scripted REPL stream). Overflow drops live bytes only.-pub const StreamBuf = struct {- buf: []u8 = &.{},- len: std.atomic.Value(usize) = std.atomic.Value(usize).init(0),-- pub fn appendBytes(self: *StreamBuf, bytes: []const u8) void {- const cur = self.len.load(.monotonic);- if (cur >= self.buf.len) return;- var n = @min(bytes.len, self.buf.len - cur);- // Overflow drops the tail for good, so a clip must not land INSIDE a- // codepoint: the missing bytes never arrive and the live row would- // paint replacement garbage that persists for the rest of the turn.- if (n < bytes.len) n = utf8Floor(bytes, n);- if (n == 0) return;- @memcpy(self.buf[cur .. cur + n], bytes[0..n]);- self.len.store(cur + n, .release);- }-- /// Largest k <= n where `s[0..k]` ends on a whole UTF-8 codepoint.- fn utf8Floor(s: []const u8, n: usize) usize {- if (n == 0 or n >= s.len) return n;- var k = n;- while (k > 0) : (k -= 1) {- const b = s[k - 1];- if (b < 0x80) return k; // ASCII byte ends a codepoint- if (b >= 0xc0) { // lead byte: does its whole sequence fit?- const len = std.unicode.utf8ByteSequenceLength(b) catch return k - 1;- return if (k - 1 + len <= n) n else k - 1;- }- }- return 0; // all continuation bytes: nothing whole to keep- }-- pub fn snapshot(self: *StreamBuf, gpa: std.mem.Allocator) ?[]u8 {- const n = self.len.load(.acquire);- if (n == 0) return null;- return gpa.dupe(u8, self.buf[0..n]) catch null;- }-};--/// A turn backend gets the live text buffer AND the typed event queue (#551):-/// prose streams into `stream` for the pending row's tail view, while every-/// structured moment (tool call, outcome, refusal, notice, failover) is PUSHED-/// as an event. The TUI used to recover the second kind by parsing the first,-/// which is the defect this seam removes.-pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf, events: *events_mod.Queue) ?[]const u8;-/// How a seat is PAID FOR. The TUI never derives this — src/billing.zig owns-/// the rule and the engine hands the answer over with the catalog, the same-/// way it hands over the model names themselves.-pub const CostClass = enum {- plan,- credits,- api,- local,-- pub fn badge(self: CostClass) []const u8 {- return switch (self) {- .plan => "plan",- .credits => "credits",- .api => "api",- .local => "local",- };- }-};--/// One row of the model catalog. A bare name was ambiguous: the same model-/// served by codex (a ChatGPT plan), codegraff (gateway credits) and openai (a-/// metered key) drew three identical rows, and picking one resolved the-/// provider by first-name-match rather than by the row the user chose.-pub const ModelEntry = struct {- name: []const u8,- provider: []const u8 = "",- /// False when this provider has no credential in this session. The row- /// stays — knowing the seat EXISTS is the point — but it is dimmed.- has_key: bool = false,- cost: CostClass = .api,-};--/// What a switch actually landed on. The provider travels back with the model-/// so the current-row marker can tell two same-named seats apart.-pub const Picked = struct { model: []const u8, provider: []const u8 = "" };--/// Switch to `name` ON `provider`. An empty `provider` means "the caller does-/// not know one" (a hand-typed `/model <name>`) and asks the engine to route-/// by name, which is what the picker used to be stuck doing for every pick.-pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?Picked;-pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;-/// Fill dest with an image path (>0) and its ownership, or an error line (<0).-pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8, owned: *bool) isize;-/// Run a user-typed `!` shell line; return combined output (caller frees), the-/// gate's refusal, or null when the harness could not produce either. `params`-/// carries the session's policy because `!` goes through the same gate the-/// model's bash tool does — a `!` under /plan must be refused (#551).-pub const BashFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, cmd: []const u8, params: Params) ?[]const u8;-/// Newline-joined repo-relative paths for @-search (caller frees), or null.-pub const FilesFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;-/// Copy text to the system clipboard; true on success.-pub const CopyFn = *const fn (turn_ctx: ?*anyopaque, text: []const u8) bool;-/// Engine-owned history compaction. Fills `out` with gpa-owned note + turns-/// (caller frees). Returns false when history is unchanged.-pub const CompactOut = struct {- note: []const u8 = "",- turns: []Turn = &.{},-};-pub const CompactFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, out: *CompactOut) bool;--/// The frontend just discarded part of its transcript. The engine owns the-/// conversation the model actually sees (#551), so it has to be told: without-/// this, /new left the whole old session in the request body and /rewind left-/// a prompt the user had taken back.-pub const HistoryOp = enum { reset, rewind };-pub const HistoryFn = *const fn (turn_ctx: ?*anyopaque, op: HistoryOp) void;--/// Host-side `/goal` verb. `.none` is a snapshot (strict/ultracode/rename):-/// the host must not re-apply or mint a goal. Typed TUI `/goal` is the same-/// retirable lifecycle as the line REPL — never a standing `--goal` (#716).-pub const GoalOp = enum { none, set, clear, pause, unpause };--pub const SessionState = struct {- session_name: []const u8 = "",- goal: []const u8 = "",- strict: bool = false,- ultracode: bool = false,- goal_op: GoalOp = .none,-};-pub const StateFn = *const fn (turn_ctx: ?*anyopaque, state: SessionState) void;--pub const ResumeOut = struct {- turns: []Turn = &.{},- session_name: []const u8 = "",- goal: []const u8 = "",- strict: bool = false,- ultracode: bool = false,- note: []const u8 = "",-};-pub const ResumeFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, spec: []const u8, out: *ResumeOut) bool;-/// Newline-joined saved-session rows (`base\tlabel\tdesc`) for `/resume` (caller frees), or null.-pub const SessionsFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8;--test "StreamBuf: append then snapshot, overflow is silent" {- var buf: [8]u8 = undefined;- var s: StreamBuf = .{ .buf = &buf };- s.appendBytes("hello");- const snap = s.snapshot(std.testing.allocator).?;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("hello", snap);- s.appendBytes(" world!!!!");- try std.testing.expectEqual(@as(usize, 8), s.len.load(.acquire));-}--test "StreamBuf: an overflow clip lands on a codepoint boundary" {- // The dropped tail never arrives, so a clip inside 🚀 would leave the live- // row painting replacement garbage for the rest of the turn.- var buf: [8]u8 = undefined;- var s: StreamBuf = .{ .buf = &buf };- s.appendBytes("ab");- s.appendBytes("🚀🚀"); // 8 bytes: only the first fits whole- const snap = s.snapshot(std.testing.allocator).?;- defer std.testing.allocator.free(snap);- try std.testing.expect(std.unicode.utf8ValidateSlice(snap));- try std.testing.expectEqualStrings("ab🚀", snap);- // A chunk that cannot contribute even one whole glyph writes nothing.- var tiny: [2]u8 = undefined;- var t: StreamBuf = .{ .buf = &tiny };- t.appendBytes("日");- try std.testing.expectEqual(@as(usize, 0), t.len.load(.acquire));-}diff --git a/TUI/events.zig b/TUI/events.zigdeleted file mode 100644index 35cad030..00000000--- a/TUI/events.zig+++ /dev/null@@ -1,310 +0,0 @@-//! The typed engine-event channel the TUI consumes (#551, the #422 epic).-//!-//! Before this file the TUI learned what the engine did by SCANNING the sink's-//! own rendered bytes: turn.zig matched "⚙ /✓ /✗ /⊘ " line prefixes out of the-//! live stream and scrollback.zig re-derived the tool's name, status, argument-//! and preview by splitting that line on the glyph, ' ' and ' | '. Both were-//! guesses about formatting rather than knowledge about the run, and both were-//! wrong in the obvious ways: an assistant answer whose line began "✓ " became-//! a phantom tool row, and a command containing " | " was mis-titled.-//!-//! Now the engine hands over typed events and this queue carries them across-//! the turn thread. Growth rule: a new engine moment becomes a new variant with-//! the FIELDS a frontend needs, never a pre-rendered string that a reader has-//! to take apart again.-//!-//! The package stays frontend-agnostic (it never imports the harness), so this-//! is a projection of src/engine_events.zig, not that union itself; the-//! translation lives in src/tui_sink.zig, which is the only place that knows-//! both vocabularies.--const std = @import("std");--/// One tool moment, as a row can render it without parsing anything.-pub const Tool = struct {- /// The engine's tool name, verbatim ("bash", "read_file",- /// "mcp__codedbpro__read"). Classification reads THIS, never a rendered- /// line: `isMcp` is a prefix test on the name, and a bash command that- /// happens to mention "search" is not a search.- name: []const u8,- /// A one-line argument preview (on a call) or result preview (on an- /// outcome). Already first-lined and capped by the emitter.- detail: []const u8 = "",- is_error: bool = false,- /// The harness refused the call before it ran (tool_rejected).- denied: bool = false,- /// Wall-clock ms the engine measured (tool_finished). 0 while running.- ms: u64 = 0,-};--/// What the cost meter can say. Three of the four are STATES, not numbers, so-/// a pre-formatted string would have had to invent figures for them.-pub const Cost = union(enum) {- /// --no-cost: the segment does not exist.- hidden,- /// Flat-rate provider: spend is not per-turn.- subscription,- /// No price-table row for this model.- unpriced,- usd: f64,-};--/// The engine's view of the session after a turn (engine_events.PromptStatus).-/// The TUI used to answer /context and /session-info from characters it had-/// counted itself, which measured the transcript rather than the request and-/// went further wrong every time the engine compacted or a tool result landed.-pub const Status = struct {- model: []const u8,- provider_id: []const u8 = "",- /// Context figures are meaningful only once a response has reported usage.- has_context: bool = false,- tokens: u64 = 0,- window: u64 = 0,- compact_at: u64 = 0,- cache_read: u64 = 0,- cost: Cost = .hidden,- fast: bool = false,- fallback: bool = false,- plan: bool = false,- strict: bool = false,- ultracode: bool = false,-- /// Percent of the window in use, 0 when nothing has been measured.- pub fn percent(self: Status) u64 {- if (!self.has_context or self.window == 0) return 0;- return @min((self.tokens *| 100) / self.window, 100);- }-- /// Last-turn prompt-cache hit: cached tokens over the prompt that- /// produced them. Null until a turn has reported a context size.- pub fn cachePercent(self: Status) ?u64 {- if (!self.has_context or self.tokens == 0) return null;- return @min((self.cache_read *| 100) / self.tokens, 100);- }-};--/// What a mid-turn failover landed on. The provider travels with the model for-/// the same reason it travels with `Picked`: the picker's current-row marker-/// compares BOTH, so a name alone cannot tell two same-named seats apart.-pub const ModelChanged = struct { model: []const u8, provider: []const u8 = "" };--pub const Event = union(enum) {- /// A tool call cleared the gates and is running (ToolInvocation).- tool_started: Tool,- /// It returned (ToolOutcome). `is_error` is the engine's verdict.- tool_finished: Tool,- /// The harness refused it before it ran (ToolRejection) — a moment the- /// TUI had no way to see at all before this file existed.- tool_rejected: Tool,- /// One operational line about the session (session_notice) -> system row.- notice: []const u8,- /// The active provider failed over mid-turn (provider_fallback).- model_changed: ModelChanged,- /// The engine's own context/cost meters (prompt_ready). The TUI renders- /// /context, /session-info and the footer from THIS, instead of counting- /// characters and calling the result a context meter.- status: Status,-};--/// Lock-guarded SPSC-shaped hand-off: the turn thread (and the parallel tool-/// pool behind it) pushes, the render loop drains at its existing poll points.-///-/// Allocation discipline: engine payloads point into the per-turn arena that-/// dies with the turn, so `push` COPIES every string into this queue's own-/// gpa and `drain` hands that ownership to the caller. The queue is bounded —-/// a turn that outruns the render loop drops events and counts them rather-/// than growing without limit.-pub const Queue = struct {- /// Bounded so a runaway turn cannot grow the queue without limit. ~4k- /// events is far more tool activity than one turn produces.- pub const cap: usize = 4096;-- /// Spin lock rather than a mutex: this zig's std has no io-less Thread- /// mutex, and the TUI package deliberately never takes an Io handle. The- /// critical sections are a dupe and an append — microseconds, never a- /// syscall — so it stays uncontended (the same choice repl_glue's- /// steerLock made for its queue).- lock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),- /// Set by the owner (turn.zig) before the turn thread starts. A queue that- /// was never attached drops silently — which is exactly what a Job literal- /// in a test that does not care about events wants.- gpa: ?std.mem.Allocator = null,- items: std.ArrayList(Event) = .empty,- /// Events refused because the queue was full or a copy failed. Surfaced- /// rather than swallowed: silent loss here is how a tool row goes missing.- dropped: usize = 0,- permission: @import("permission.zig").Mailbox = .{},-- fn acquire(self: *Queue) void {- while (self.lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();- }-- fn release(self: *Queue) void {- self.lock.store(false, .release);- }-- pub fn attach(self: *Queue, gpa: std.mem.Allocator) void {- self.acquire();- defer self.release();- self.gpa = gpa;- }-- pub fn push(self: *Queue, ev: Event) void {- self.acquire();- defer self.release();- const gpa = self.gpa orelse return;- if (self.items.items.len >= cap) {- self.dropped += 1;- return;- }- const owned = dupeEvent(gpa, ev) orelse {- self.dropped += 1;- return;- };- self.items.append(gpa, owned) catch {- freeEvent(gpa, owned);- self.dropped += 1;- };- }-- /// Everything queued so far. The caller owns the slice AND every string in- /// it until it calls `free`.- pub fn drain(self: *Queue) []Event {- self.acquire();- defer self.release();- const gpa = self.gpa orelse return &.{};- return self.items.toOwnedSlice(gpa) catch &.{};- }-- pub fn free(self: *Queue, evs: []Event) void {- const gpa = self.gpa orelse return;- for (evs) |e| freeEvent(gpa, e);- gpa.free(evs);- }-- pub fn deinit(self: *Queue) void {- self.acquire();- defer self.release();- const gpa = self.gpa orelse return;- for (self.items.items) |e| freeEvent(gpa, e);- self.items.deinit(gpa);- self.items = .empty;- }-};--fn dupeEvent(gpa: std.mem.Allocator, ev: Event) ?Event {- return switch (ev) {- .tool_started => |t| .{ .tool_started = dupeTool(gpa, t) orelse return null },- .tool_finished => |t| .{ .tool_finished = dupeTool(gpa, t) orelse return null },- .tool_rejected => |t| .{ .tool_rejected = dupeTool(gpa, t) orelse return null },- .notice => |s| .{ .notice = gpa.dupe(u8, s) catch return null },- // Only the model name is copied: a provider id is a static spec literal- // (see app.Model.adoptModel), so it outlives the drain on its own.- .model_changed => |m| .{ .model_changed = .{ .model = gpa.dupe(u8, m.model) catch return null, .provider = m.provider } },- .status => |st| .{ .status = dupeStatus(gpa, st) orelse return null },- };-}--fn dupeStatus(gpa: std.mem.Allocator, st: Status) ?Status {- var out = st;- out.model = gpa.dupe(u8, st.model) catch return null;- out.provider_id = gpa.dupe(u8, st.provider_id) catch {- gpa.free(out.model);- return null;- };- return out;-}--fn freeEvent(gpa: std.mem.Allocator, ev: Event) void {- switch (ev) {- .tool_started, .tool_finished, .tool_rejected => |t| {- gpa.free(t.name);- gpa.free(t.detail);- },- .notice => |s| gpa.free(s),- .model_changed => |m| gpa.free(m.model),- .status => |st| {- gpa.free(st.model);- gpa.free(st.provider_id);- },- }-}--fn dupeTool(gpa: std.mem.Allocator, t: Tool) ?Tool {- const name = gpa.dupe(u8, t.name) catch return null;- const detail = gpa.dupe(u8, t.detail) catch {- gpa.free(name);- return null;- };- return .{ .name = name, .detail = detail, .is_error = t.is_error, .denied = t.denied, .ms = t.ms };-}--test "queue copies payloads, so an arena that dies with the turn cannot dangle" {- var q: Queue = .{};- q.attach(std.testing.allocator);- defer q.deinit();-- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- const arena = arena_state.allocator();- const name = try arena.dupe(u8, "mcp__codedbpro__read");- const detail = try arena.dupe(u8, "src/main.zig");- q.push(.{ .tool_started = .{ .name = name, .detail = detail } });- // The engine's arena is gone; the queued copy must still be readable.- arena_state.deinit();-- const evs = q.drain();- defer q.free(evs);- try std.testing.expectEqual(@as(usize, 1), evs.len);- try std.testing.expectEqualStrings("mcp__codedbpro__read", evs[0].tool_started.name);- try std.testing.expectEqualStrings("src/main.zig", evs[0].tool_started.detail);-}--test "drain empties the queue and hands ownership over exactly once" {- var q: Queue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- q.push(.{ .tool_started = .{ .name = "bash", .detail = "ls" } });- q.push(.{ .tool_finished = .{ .name = "bash", .detail = "ok", .is_error = false } });- const first = q.drain();- try std.testing.expectEqual(@as(usize, 2), first.len);- q.free(first);- const second = q.drain();- defer q.free(second);- try std.testing.expectEqual(@as(usize, 0), second.len);-}--test "an unattached queue drops instead of crashing, and never hands out memory" {- var q: Queue = .{};- q.push(.{ .notice = "loaded 2 saved approval(s)" });- const evs = q.drain();- defer q.free(evs);- try std.testing.expectEqual(@as(usize, 0), evs.len);-}--test "the queue is bounded: past cap it drops and counts instead of growing" {- var q: Queue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var i: usize = 0;- while (i < Queue.cap + 8) : (i += 1) q.push(.{ .notice = "x" });- try std.testing.expectEqual(Queue.cap, q.items.items.len);- try std.testing.expectEqual(@as(usize, 8), q.dropped);-}--test "pushes from another thread arrive intact" {- var q: Queue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- const Writer = struct {- fn f(target: *Queue) void {- var i: usize = 0;- while (i < 200) : (i += 1) target.push(.{ .tool_finished = .{ .name = "bash", .detail = "done" } });- }- };- const th = try std.Thread.spawn(.{}, Writer.f, .{&q});- th.join();- const evs = q.drain();- defer q.free(evs);- try std.testing.expectEqual(@as(usize, 200), evs.len);- for (evs) |e| try std.testing.expectEqualStrings("bash", e.tool_finished.name);-}diff --git a/TUI/files.zig b/TUI/files.zigdeleted file mode 100644index dee795f1..00000000--- a/TUI/files.zig+++ /dev/null@@ -1,100 +0,0 @@-//! @-mention file picker: fuzzy filter over the session file list.--const std = @import("std");--const app = @import("app.zig");-const models = @import("models.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--pub const max_files = 512;-/// Rows the picker draws at once - the click map (overlays.rowSpan) reads this-/// same window instead of keeping a second copy of it.-pub const visible_rows = 10;--/// Newline-joined `list` filtered by substring-or-subsequence `query`.-pub fn filterList(list: []const u8, query: []const u8, out: [][]const u8) usize {- var n: usize = 0;- var it = std.mem.splitScalar(u8, list, '\n');- while (it.next()) |raw| {- const name = std.mem.trim(u8, raw, " \t\r");- if (name.len == 0) continue;- if (!models.modelMatch(name, query)) continue;- if (n >= out.len) break;- out[n] = name;- n += 1;- }- return n;-}--/// The panel's top-edge slots (overlaypane.zig places them).-pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {- var names: [max_files][]const u8 = undefined;- const list = self.files_cache orelse "";- const total = filterList(list, "", &names);- const n = filterList(list, self.overlay_filter, &names);- return .{- .title = try std.fmt.allocPrint(a, "File › {s}\u{258B}", .{self.overlay_filter}),- .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total }),- };-}--pub const hint = "type to search · ↑↓ move · click or Enter inserts · Esc";--/// The ROWS only — the frame carries the rest.-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var names: [max_files][]const u8 = undefined;- const list = self.files_cache orelse "";- const n = filterList(list, self.overlay_filter, &names);- var out = std.array_list.Managed(u8).init(a);- if (n == 0) {- const why = if (@import("bgop.zig").loadingFiles(self))- " loading files…"- else if (list.len == 0)- " no file list (offline?)"- else- " no matches — type to filter";- try out.appendSlice(try theme_mod.paint(a, th.muted, why));- try out.append('\n');- return out.items;- }- const sel = self.overlay_sel % n;- const vis = @min(visible_rows, n);- const off = if (sel >= vis) sel - vis + 1 else 0;- var i = off;- while (i < n and i < off + vis) : (i += 1) {- const mark: []const u8 = if (i == sel) "› " else " ";- const line = try std.fmt.allocPrint(a, "{s}{s}", .{ mark, names[i] });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- if (n > vis) try out.appendSlice(try panel.windowRow(a, th, off, vis, n));- return out.items;-}--test "filterList matches substring and subsequence" {- var buf: [8][]const u8 = undefined;- const list = "src/main.zig\nTUI/key.zig\nREADME.md";- try std.testing.expectEqual(@as(usize, 3), filterList(list, "", &buf));- try std.testing.expectEqual(@as(usize, 1), filterList(list, "tuikey", &buf));- try std.testing.expectEqualStrings("TUI/key.zig", buf[0]);- try std.testing.expectEqual(@as(usize, 1), filterList(list, "readme", &buf));-}--test "render shows the filtered file rows" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.files_cache = try std.testing.allocator.dupe(u8, "src/a.zig\ndocs/b.md");- m.openOverlay(.file);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- try std.testing.expect(std.mem.indexOf(u8, text, "src/a.zig") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "docs/b.md") != null);- const hd = try head(&m, arena.allocator());- try std.testing.expect(std.mem.indexOf(u8, hd.title, "File ›") != null);- try std.testing.expectEqualStrings("2/2", hd.note);-}diff --git a/TUI/foldhdr.zig b/TUI/foldhdr.zigdeleted file mode 100644index a4484dea..00000000--- a/TUI/foldhdr.zig+++ /dev/null@@ -1,418 +0,0 @@-//! 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, lookup, 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" },- .lookup => .{ .present = "Looking up", .past = "Looked up", .noun = "item" },- .web => .{ .present = "Fetching", .past = "Fetched", .noun = "page" },- .task => .{ .present = "Scouting", .past = "Scouted", .noun = "scout" },- .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";- if (std.mem.eql(u8, name, "read_tool_result")) return "inspect";- const leaf = leafOf(name);- if (std.mem.eql(u8, leaf, "batch")) return "inspect";- if (std.mem.eql(u8, name, "subagent") or std.mem.eql(u8, name, "workflow")) return "scout";- return leaf;-}--/// 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, &.{ "codedb" })) return .lookup;- if (eqAny(leaf, &.{ "grep", "glob", "search", "find", "ls", "list_dir" })) 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 "codedb is a lookup, not a search-for-patterns" {- 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 = "codedb", .detail = "context how auth works" });- try testing.expectEqualStrings("Looking up 1 item\u{2026}", try phrase(a, oneRun(&m)));- try m.pushTool(.{ .name = "codedb", .detail = "ok", .done = true });- try m.pushTool(.{ .name = "codedb", .detail = "around Agent" });- try m.pushTool(.{ .name = "codedb", .detail = "ok", .done = true });- try testing.expectEqualStrings("Looked up 2 items", 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 = "Scouted 2 scouts" },- .{ .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.lookup, familyOf("codedb"));- 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.zigdeleted file mode 100644index 0ce694bf..00000000--- a/TUI/glyphs.zig+++ /dev/null@@ -1,220 +0,0 @@-//! The chrome glyph registry — presentation only, no engine facts.-//!-//! Every non-text glyph the chrome paints is named here ONCE, with the terminal-//! width class it belongs to, and every animation is a frame SET rather than a-//! pair of literals at a call site. Scattered literals are how an animation-//! acquires a frame that measures two columns: the label beside it then steps-//! sideways on every tick, which is exactly what grok-build's one-column-//! discipline exists to prevent.-//!-//! Width classes. A terminal decides a glyph's cell count from a width table-//! built on Unicode's East_Asian_Width property, never from the font — a glyph-//! drawn from a fallback face still advances the cells its class says it does.-//!-//! narrow EAW N or Na. ONE column in every terminal, including one-//! configured to draw East-Asian-Ambiguous glyphs double-width.-//! ambiguous EAW A. One column by default — what theme.charWidth returns, and-//! what every western terminal does — but TWO under the CJK-//! ambiguous-wide setting (xterm -cjk_width, iTerm2's-//! "ambiguous characters are double-width", Terminal.app's).-//!-//! LAW: an ANIMATED glyph is narrow-class, and every frame of one animation-//! renders the same number of columns. Both halves are asserted below.-//!-//! The static chrome keeps its ambiguous members on purpose. The composer's-//! own walls (╭ ─ ╮ │ ╰ ╯), the meter separators and the block cursor are all-//! EAW A, so a terminal that widens ● has already widened the box around it —-//! ambiguous-wide is unsupported wholesale, and swapping three marks would buy-//! no alignment while changing the transcript's look. What must never happen is-//! an animation that shifts its neighbours in a NORMAL terminal, and that is-//! what the registry pins.-//!-//! Audit (Unicode 15 EastAsianWidth, 2026-08). Animated and gutter glyphs:-//!-//! 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, 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-//! U+21B3 ↳ N queued/nested row-//! U+275A ❚ N scrollbar thumb one column everywhere-//! U+25CF ● A assistant / error mark static, box-class-//! 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+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-//! the pair is genuinely pad-stable and needed no substitution.--const std = @import("std");-const theme = @import("theme.zig");--pub const Class = enum { narrow, ambiguous };--pub const Glyph = struct {- cp: u21,- cols: u2,- class: Class,- /// What it means, so the registry doubles as the audit table.- role: []const u8,-};--/// Every chrome codepoint the TUI paints. Anything animated must appear here-/// as `.narrow` — `animations` is checked against this list.-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 / 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" },- .{ .cp = 0x21B3, .cols = 1, .class = .narrow, .role = "queued / nested row" },- .{ .cp = 0x275A, .cols = 1, .class = .narrow, .role = "scrollbar thumb" },- .{ .cp = 0x25CF, .cols = 1, .class = .ambiguous, .role = "assistant / error mark" },- .{ .cp = 0x25C6, .cols = 1, .class = .ambiguous, .role = "tool mark" },- .{ .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 ────────────────────────────────────────────────────────────────--/// The pending row's blink. A fully static frame let run.zig's hash-diff-/// suppress every paint for a background op's whole duration, so the row has to-/// change — but only in ways that keep the label's column fixed.-pub const thinking = [_][]const u8{ "\u{2759}", "\u{2758}" };--/// The scrollback's selection mark. Both frames are a TWO-column field, so a-/// 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-/// literal.-pub fn frame(anim: []const []const u8, i: usize) []const u8 {- return anim[i % anim.len];-}--// ── static ──────────────────────────────────────────────────────────────────--pub const caret = "\u{203A}"; // composer prompt-/// Swapped in for `tool` on a COLLAPSED row under the pointer (hover.zig).-/// Same codepoint as `caret` on purpose — one chevron means "this opens" —-/// but named for its own role so the two call sites cannot drift.-pub const expand = "\u{203A}";-pub const prompt_mark = "\u{276F}"; // sticky header-pub const assistant = "\u{25CF}";-pub const tool = "\u{25C6}";-pub const system = "\u{00B7}";-pub const denied = "\u{2298}";-pub const failed = "\u{2717}";-pub const cursor = "\u{258B}";-/// The transcript scrollbar's thumb (scrollbar.zig). Narrow-class on purpose:-/// it is painted ON the last column, so a glyph a terminal draws two cells wide-/// would push itself off the row. The Block Elements (▐, █) read better and are-/// EAW-Ambiguous, which is exactly the trade this registry exists to refuse.-pub const scroll_thumb = "\u{275A}";--/// 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;- }- return null;-}--const testing = std.testing;--test "every registered glyph measures the columns it claims" {- var buf: [4]u8 = undefined;- for (registry) |g| {- try testing.expectEqual(@as(u2, 1), g.cols); // chrome is single-cell, always- try testing.expectEqual(g.cols, theme.charWidth(g.cp));- const n = try std.unicode.utf8Encode(g.cp, &buf);- try testing.expectEqual(@as(usize, g.cols), theme.visibleLen(buf[0..n]));- }-}--test "every frame of every animation renders the same visibleLen" {- // The whole point of the registry: a frame that measured differently would- // move the label or timer beside it on every tick.- for (animations) |anim| {- try testing.expect(anim.frames.len >= 2); // an animation that cannot change is a still- const want = theme.visibleLen(anim.frames[0]);- try testing.expect(want > 0);- for (anim.frames) |f| {- try testing.expectEqual(want, theme.visibleLen(f));- // ...and no two frames may be identical, or the paint loop stalls.- }- for (anim.frames, 0..) |f, i| {- for (anim.frames[i + 1 ..]) |other| {- try testing.expect(!std.mem.eql(u8, f, other));- }- }- }-}--test "every animated glyph is narrow-class — one column in EVERY terminal" {- for (animations) |anim| {- for (anim.frames) |f| {- var i: usize = 0;- while (i < f.len) {- const len = try std.unicode.utf8ByteSequenceLength(f[i]);- const cp = try std.unicode.utf8Decode(f[i .. i + len]);- i += len;- if (cp == ' ') continue; // padding, always one column- const g = lookup(cp) orelse {- std.debug.print("unregistered animated glyph U+{X:0>4}\n", .{cp});- return error.UnregisteredGlyph;- };- try testing.expectEqual(Class.narrow, g.class);- }- }- }-}--test "the blink frames live in the registry and nowhere else" {- // A second copy of the pair at a call site is how the frame set drifts:- // one gets replaced, the other does not, and the animation starts stepping.- for ([_][]const u8{- @embedFile("scrollback.zig"),- @embedFile("chrome.zig"),- @embedFile("render.zig"),- @embedFile("input.zig"),- }) |src| {- for (thinking) |f| try testing.expect(std.mem.indexOf(u8, src, f) == null);- }-}--test "frame() indexes by time and wraps" {- try testing.expectEqualStrings(thinking[0], frame(&thinking, 0));- try testing.expectEqualStrings(thinking[1], frame(&thinking, 1));- try testing.expectEqualStrings(thinking[0], frame(&thinking, 2));-}diff --git a/TUI/hover.zig b/TUI/hover.zigdeleted file mode 100644index 5274d805..00000000--- a/TUI/hover.zig+++ /dev/null@@ -1,247 +0,0 @@-//! Hover affordance: make a clickable row LOOK clickable before the click.-//!-//! ?1003h (any-event tracking) is already on for the image-chip preview, so-//! the pointer's position reaches keys.mouseKey as a mouse report with button-//! 35 on every motion. Until now every one of those that did not land on an-//! image chip was DROPPED — the TUI knew where the pointer was and said-//! nothing. This is the other half: the row under the pointer is looked up in-//! the same map a click uses, and if it is a target it is painted with a-//! background one step off the canvas. The tint is the whole affordance: fold-//! headers already carry their ›/⌄ disclosure chevron in both states-//! (foldhdr.zig), so hover changes a row's colour and NEVER its text.-//!-//! ONE HIT TEST. `hitTest` is the single answer to "what is on screen row y",-//! and keys.mouseKey routes its click through the same function. Hover and-//! click cannot disagree about what is clickable, because there is only one-//! opinion in the codebase.-//!-//! PRESENTATION ONLY. The hovered row, the click counter and the tint are all-//! screen state. What is FOLDABLE, and which entry a row belongs to, come from-//! the Model's typed entries (`kind == .tool`, `Entry.folded`) and from the-//! layout cache — never from reading the rendered text back.-//!-//! DOUBLE CLICK. Two presses on the same cell inside `double_ms`. The first-//! press always does exactly what a press does today (the existing tests pin-//! that); the SECOND suppresses the single-click action and runs the-//! double-click one instead, so a double click on a fold header is one net-//! toggle rather than an expand followed by a collapse. A press that MOVED is-//! a drag, never a click: selection.zig owns that distinction and calls-//! `dragged` the instant motion proves it, so the counter is not a second,-//! divergent copy of the same state machine.-//!-//! COST. Hover repaints ride the ordinary frame path. A sweep across N rows is-//! N motion reports, which pacing.zig's storm window folds into a bounded-//! number of composed frames exactly as it folds a momentum flick — see the-//! pacing lane's budget, and `scripts/test-tui-hover.py` for the pty proof.--const std = @import("std");--const app = @import("app.zig");-const key_mod = @import("key.zig");-const layout_cache = @import("layout_cache.zig");-const theme_mod = @import("theme.zig");-const tint = @import("theme_tint.zig");-const Model = app.Model;--/// Two presses inside this window, on the same cell, are one double click.-pub const double_ms: u64 = 400;--/// SGR button for motion with no button held, under ?1003h. Motion WITH the-/// left button down is 32 and belongs to the drag, not to hover.-pub const motion_btn: u8 = 35;--/// What sits on a screen row. Only rows a press actually does something to are-/// targets: an affordance that announced a click which does nothing would be-/// worse than no affordance at all.-pub const Target = enum {- /// Nothing clickable (blank padding, an overlay body, chrome).- none,- /// A row belonging to a tool run — a press toggles the whole group.- tool,- /// The sticky-header pin: a scrolled-past user prompt. A press does- /// nothing today; a DOUBLE press jumps the viewport back to it.- sticky,- /// The composer. A press focuses it.- composer,- /// A row of an open list overlay. A press moves the highlight there, and a- /// press on the row that already has it confirms (click.zig).- row,-};--pub const Hit = struct {- target: Target = .none,- /// What the row maps to: a history index for `.tool`, the list item for- /// `.row`. Null for every target that names no element.- idx: ?usize = null,- /// The group is folded, so its mark should announce that it opens.- collapsed: bool = false,-};--/// Presentation state. Lives on the Model beside `sel` and `layout`.-pub const State = struct {- /// 0-based screen row under the pointer, or null when nothing is hovered.- row: ?usize = null,- hit: Hit = .{},- /// Cell and time of the last press, for the double-click window.- last_ms: u64 = 0,- last_row: usize = 0,- last_col: usize = 0,- /// A press is banked here; the next one on the same cell inside the window- /// completes a double. Zeroed by a drag and by every scroll.- armed: bool = false,-};--// --------------------------------------------------------------- hit test--/// What screen row `y` (0-based) is, this frame. The row→entry map is the-/// layout cache's, which is the same one keys.mouseKey clicks through.-pub fn hitTest(m: *Model, y: usize) Hit {- // An overlay owns the whole screen. Its LIST rows are clickable now, so- // they announce themselves through the same one hit test; its title,- // footer and backdrop are not, and stay quiet.- if (m.overlay != .none) {- if (m.overlay == .image or y >= m.prompt_origin) return .{};- const item = @import("click.zig").overlayRowAt(m, y) orelse return .{};- return .{ .target = .row, .idx = item };- }- if (y >= m.prompt_origin) return .{ .target = .composer };- if (y < m.mid_origin) return .{};- // Sticky chrome OCCLUDES the top content rows: the blank separator row- // under the pin is chrome too, and neither maps to what is beneath them.- if (y < m.mid_origin + m.sticky_rows) {- return if (m.sticky_rows > 0 and y == m.mid_origin) .{ .target = .sticky } else .{};- }- const vis = y - m.mid_origin + m.mid_skip;- const i = layout_cache.indexAtVisual(m, vis, @import("inset.zig").wrapWidth(m)) orelse return .{};- if (m.history.items[i].kind != .tool) return .{};- const run = m.toolRun(i);- return .{ .target = .tool, .idx = i, .collapsed = m.history.items[run.start].folded };-}--// ----------------------------------------------------------------- motion--/// A mouse report. Returns true when it was pure hover motion and nothing else-/// should see it. A drag in progress owns the pointer, so hover stands down.-pub fn mouse(m: *Model, ev: key_mod.Mouse) bool {- if (ev.btn != motion_btn) return false;- if (m.sel.active or m.sel.pressed) {- clear(m);- return false; // image.zig still wants the report for its chip preview- }- const y: usize = if (ev.y > 0) ev.y - 1 else 0;- const hit = hitTest(m, y);- if (hit.target == .none) {- clear(m);- return false;- }- m.hover.row = y;- m.hover.hit = hit;- return false; // never consumed: the image chip preview reads it too-}--/// Drop the highlight. Called when the pointer leaves a target, when the-/// screen scrolls under it (the row no longer means what it meant), and on-/// every teardown of the frame's geometry.-pub fn clear(m: *Model) void {- m.hover.row = null;- m.hover.hit = .{};-}--/// A scroll moved the content out from under the pointer, and the pointer did-/// not move: the highlight would now be announcing a different row than the-/// one the user is actually over. Drop it and let the next motion re-arm.-pub fn scrolled(m: *Model) void {- clear(m);- m.hover.armed = false;-}--// ----------------------------------------------------------- click counting--/// Record a press. True when it COMPLETES a double click, in which case the-/// caller must run the double-click action INSTEAD of the single-click one:-/// the first press already did today's thing, and repeating it would undo it.-pub fn press(m: *Model, y: usize, x: usize) bool {- const same = m.hover.armed and- m.hover.last_row == y and m.hover.last_col == x and- m.now_ms -| m.hover.last_ms <= double_ms;- m.hover.last_row = y;- m.hover.last_col = x;- m.hover.last_ms = m.now_ms;- // A completed double disarms, so a third press opens a fresh single rather- // than firing the double action again on every press that follows.- m.hover.armed = !same;- return same;-}--/// selection.zig calls this the instant motion turns a press into a drag. A-/// gesture that moved is not a click, so it can never be half of a double one.-pub fn dragged(m: *Model) void {- m.hover.armed = false;- clear(m);-}--/// Double click on the sticky pin: put the prompt it is pinning back on the-/// top row of the viewport. No-op when there is nothing pinned or nothing to-/// scroll — the same numbers render.zig used to lay the frame out.-pub fn jumpToSticky(m: *Model) void {- const c = layout_cache.ensure(m, @import("inset.zig").wrapWidth(m));- if (layout_cache.stickyUserAbove(c, m.mid_skip) == null) return;- var i = layout_cache.indexAt(c, m.mid_skip) orelse m.history.items.len;- const line = while (i > 0) {- i -= 1;- if (m.history.items[i].kind == .user) break layout_cache.lineOf(c, i) orelse return;- } else return;- const view_h = m.prompt_origin -| m.mid_origin -| m.preview_rows;- if (view_h == 0 or c.total <= view_h) return;- // `scroll` counts lines from the BOTTOM (render.zig: start = max - scroll).- m.scroll = (c.total - view_h) -| line;- m.follow = m.scroll == 0;- scrolled(m);-}--// ------------------------------------------------------------------ paint--/// Post-pass over the COMPOSED frame, exactly like selection.paint: the row-/// builders stay unaware of hover, and the row lands on the screen row the-/// mouse reported.-///-/// The theme background is written per ROW by the painter, BEFORE the row's-/// bytes (paint.zig), so opening the row with a different background is all it-/// takes to retint it — including the padding the painter adds after it, which-/// inherits whatever the row left active.-pub fn paint(m: *Model, a: std.mem.Allocator, frame: []const u8, width: usize) ![]const u8 {- _ = width;- const row = m.hover.row orelse return frame;- if (m.hover.hit.target == .none) return frame;- // Re-ask, every frame. An explicit scroll drops the hover outright- // (`scrolled`), but content can also arrive under a pointer that never- // moved — a streaming answer, a tool card opening above. The remembered- // hit is then a claim about a row that has changed hands, so it is- // verified rather than trusted, and a stale one clears itself instead of- // announcing a click that would land somewhere else.- const now = hitTest(m, row);- if (now.target != m.hover.hit.target or now.idx != m.hover.hit.idx) {- clear(m);- return frame;- }- m.hover.hit = now; // the group may have folded or opened under the pointer- const bg = tint.hoverBg(m.theme_id);- var out = std.array_list.Managed(u8).init(a);- var r: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- var found = false;- while (it.next()) |ln| : (r += 1) {- if (r > 0) try out.append('\n');- if (r != row) {- try out.appendSlice(ln);- continue;- }- found = true;- try out.appendSlice(bg);- try out.appendSlice(ln);- }- // The pointer is parked on a row the frame no longer reaches (the transcript- // shrank under it). Nothing to tint, and the stale row must not paint.- if (!found) return frame;- return out.items;-}diff --git a/TUI/hover_tests.zig b/TUI/hover_tests.zigdeleted file mode 100644index 9b2cbf65..00000000--- a/TUI/hover_tests.zig+++ /dev/null@@ -1,336 +0,0 @@-//! Dispatch-level tests for the hover affordance: what a motion report does to-//! the Model, what the post-pass does to the frame, and where the double-click-//! window opens and closes. Reached from root.zig — a test module nobody-//! references compiles for nobody and silently never runs.--const std = @import("std");--const app = @import("app.zig");-const glyphs = @import("glyphs.zig");-const hover = @import("hover.zig");-const keys = @import("keys.zig");-const render_mod = @import("render.zig");-const tint = @import("theme_tint.zig");-const Model = app.Model;--const testing = std.testing;--/// The mouse reports the TUI actually receives. `y`/`x` are 1-based, as a-/// terminal sends them; every handler converts on the way in.-fn motion(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = hover.motion_btn, .x = x, .y = y, .down = true } });-}--fn press(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = true } });-}--fn drag(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 32, .x = x, .y = y, .down = true } });-}--/// A model with one collapsed tool run in a fixed, hand-placed geometry — the-/// same shape selection.zig's tests use, so the two agree about the viewport.-fn folded(m: *Model) !void {- m.setup(testing.allocator);- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.last_term_height = 24;- m.last_term_width = 80;- m.mid_origin = 1;- m.mid_skip = 0;- m.prompt_origin = 20;-}--test "motion over a collapsed tool row arms the hover; leaving it clears" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- try testing.expect(m.history.items[1].folded);-- motion(&m, 4, 3); // screen row 2 — the folded group's summary- try testing.expectEqual(@as(?usize, 2), m.hover.row);- try testing.expectEqual(hover.Target.tool, m.hover.hit.target);- try testing.expect(m.hover.hit.collapsed);- // Hover NEVER folds, selects or focuses anything: it only says a click- // would do something.- try testing.expect(m.history.items[1].folded);-- motion(&m, 4, 15); // blank padding below the transcript- try testing.expectEqual(@as(?usize, null), m.hover.row);- try testing.expectEqual(hover.Target.none, m.hover.hit.target);-}--test "the composer is a hover target; a row above the viewport is not" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- motion(&m, 5, 21); // inside the composer- try testing.expectEqual(hover.Target.composer, m.hover.hit.target);- try testing.expectEqual(@as(?usize, 20), m.hover.row);- motion(&m, 5, 1); // the top bar, above mid_origin- try testing.expectEqual(hover.Target.none, m.hover.hit.target);-}--test "an expanded group hovers as a target but never claims to expand" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- m.toggleToolGroup(1);- try testing.expect(!m.history.items[1].folded);- motion(&m, 4, 3);- try testing.expectEqual(hover.Target.tool, m.hover.hit.target);- // Already open: the chevron would be a lie, so the mark stays put.- try testing.expect(!m.hover.hit.collapsed);-}--/// Screen row (0-based) of the first composed line containing `needle`. The-/// frame decides its own geometry, so a test that wants to point at a row has-/// to ask the frame where it is rather than assume.-fn rowOf(frame: []const u8, needle: []const u8) ?usize {- var r: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (r += 1) {- if (std.mem.indexOf(u8, ln, needle) != null) return r;- }- return null;-}--test "the hovered row is repainted with the theme's hover background" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- const bg = tint.hoverBg(m.theme_id);-- const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(cold);- try testing.expect(std.mem.indexOf(u8, cold, bg) == null);- const summary: u16 = @intCast(rowOf(cold, "Ran bash").? + 1);-- motion(&m, 4, summary);- const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(warm);- // Exactly one row carries it: hover highlights a row, not a region.- var rows: usize = 0;- var it = std.mem.splitScalar(u8, warm, '\n');- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, bg) != null) rows += 1;- }- try testing.expectEqual(@as(usize, 1), rows);-- // ...and moving off restores the frame byte for byte.- motion(&m, 4, 15);- const cooled = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(cooled);- try testing.expectEqualStrings(cold, cooled);-}--/// Screen row `want` of the composed frame, verbatim.-fn nthRow(frame: []const u8, want: usize) []const u8 {- var r: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (r += 1) if (r == want) return ln;- return "";-}--test "hover tints a collapsed row and never edits its text" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(cold);- const row = rowOf(cold, "Ran bash").?;- // Disclosure is not a hover reveal: the closed chevron is already on the- // cold header (foldhdr.zig owns it), so hover has nothing to swap.- try testing.expect(std.mem.indexOf(u8, nthRow(cold, row), glyphs.expand) != null);-- motion(&m, 4, @intCast(row + 1));- const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(warm);- // The tint opens the row; every byte after it is the untouched cold row.- const bg = tint.hoverBg(m.theme_id);- const warm_row = nthRow(warm, row);- try testing.expect(std.mem.startsWith(u8, warm_row, bg));- try testing.expectEqualStrings(nthRow(cold, row), warm_row[bg.len..]);-}--test "an expanded row keeps its tool mark under the pointer" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- m.toggleToolGroup(1);- const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(cold);- motion(&m, 4, @intCast(rowOf(cold, "bash").? + 1));- const warm = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(warm);- try testing.expect(std.mem.indexOf(u8, warm, glyphs.tool) != null);-}--test "a scroll drops the hover: the row under a still pointer now means something else" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- motion(&m, 4, 3);- try testing.expectEqual(hover.Target.tool, m.hover.hit.target);- _ = keys.handle(&m, .{ .mouse = .{ .btn = 64, .x = 4, .y = 3, .down = true } });- try testing.expectEqual(@as(?usize, null), m.hover.row);- try testing.expectEqual(hover.Target.none, m.hover.hit.target);-}--test "a drag stands the hover down and disarms the click counter" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- motion(&m, 4, 3);- press(&m, 4, 3);- drag(&m, 30, 6); // motion with the button held: this is a selection now- try testing.expect(m.sel.active);- try testing.expectEqual(@as(?usize, null), m.hover.row);- // The press that turned into a drag cannot be half of a double click, so- // the press that ends the drag opens a fresh single.- try testing.expect(!m.hover.armed);- // Motion WITH the button down is the drag's, never hover's.- try testing.expectEqual(hover.Target.none, m.hover.hit.target);-}--// ------------------------------------------------------- double-click window--test "two presses on one cell inside the window are one double click" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- m.now_ms = 1000;- try testing.expect(!hover.press(&m, 5, 5));- m.now_ms = 1000 + hover.double_ms;- try testing.expect(hover.press(&m, 5, 5));- // A third press is a fresh single, not another double.- m.now_ms += 10;- try testing.expect(!hover.press(&m, 5, 5));-}--test "the window closes on time and on distance" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- // One millisecond past the window is a single click.- m.now_ms = 1000;- try testing.expect(!hover.press(&m, 5, 5));- m.now_ms = 1001 + hover.double_ms;- try testing.expect(!hover.press(&m, 5, 5));- // A different cell inside the window is a single click too — a double is- // two presses on ONE cell, not two presses anywhere.- m.now_ms += 10;- try testing.expect(!hover.press(&m, 6, 5));- m.now_ms += 10;- try testing.expect(!hover.press(&m, 5, 6));-}--test "a single click still expands, and a double click is one net toggle" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- m.now_ms = 5000;- try testing.expect(m.history.items[1].folded);-- // Today's behaviour, unchanged: one press expands the group.- press(&m, 4, 3);- try testing.expect(!m.history.items[1].folded);-- // A second press inside the window would have collapsed it again, leaving- // a double click looking like it did nothing. It is one net toggle now.- m.now_ms += 100;- press(&m, 4, 3);- try testing.expect(!m.history.items[1].folded);-- // ...and two presses far enough apart are still two independent clicks.- m.now_ms += 10 * hover.double_ms;- press(&m, 4, 3);- try testing.expect(m.history.items[1].folded);-}--test "a double click on the sticky pin scrolls its prompt back onto the screen" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try m.push(.user, "FINDME the pinned prompt");- var i: usize = 0;- while (i < 60) : (i += 1) try m.push(.assistant, "a filler answer line");- // Compose once so the viewport, the sticky pin and the layout cache exist.- const first = try render_mod.render(&m, testing.allocator, 80, 24, 0);- testing.allocator.free(first);- try testing.expect(m.sticky_rows > 0); // the prompt HAS scrolled past- try testing.expect(m.mid_skip > 0);-- m.now_ms = 9000;- const pin: u16 = @intCast(m.mid_origin + 1); // 1-based row of the pin- press(&m, 3, pin);- const after_single = m.mid_skip;- // A single press on the pin is inert, exactly as before.- const mid = try render_mod.render(&m, testing.allocator, 80, 24, 0);- testing.allocator.free(mid);- try testing.expectEqual(after_single, m.mid_skip);-- m.now_ms += 100;- press(&m, 3, pin);- const jumped = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(jumped);- // The prompt is on screen again, and the viewport is no longer following.- try testing.expect(std.mem.indexOf(u8, jumped, "FINDME") != null);- try testing.expect(!m.follow);- try testing.expect(m.mid_skip < after_single);-}--test "content arriving under a still pointer clears the hover instead of lying" {- // The pointer never moves; the transcript grows under it. The remembered- // row now names a different entry, so an unverified highlight would be- // announcing a click that lands somewhere else entirely.- var m: Model = undefined;- try folded(&m);- defer m.deinit();- const cold = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(cold);- motion(&m, 4, @intCast(rowOf(cold, "Ran bash").? + 1));- try testing.expectEqual(hover.Target.tool, m.hover.hit.target);-- // Enough answer to overflow the viewport: following the tail slides the- // group off the row the pointer is parked on, without the pointer moving.- var i: usize = 0;- while (i < 40) : (i += 1) try m.push(.assistant, "a streamed answer line");- const moved = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(moved);- try testing.expectEqual(@as(?usize, null), m.hover.row);- try testing.expect(std.mem.indexOf(u8, moved, tint.hoverBg(m.theme_id)) == null);-}--test "a group that folds under the pointer starts announcing that it opens" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- m.toggleToolGroup(1); // open it first- const open = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(open);- motion(&m, 4, @intCast(rowOf(open, "bash").? + 1));- try testing.expect(!m.hover.hit.collapsed);-- // Folded by the keyboard, with the pointer still parked on the row: the- // mark has to start announcing the expansion without a new motion report.- m.toggleToolGroup(1);- const shut = try render_mod.render(&m, testing.allocator, 80, 24, 0);- defer testing.allocator.free(shut);- try testing.expect(m.hover.hit.collapsed);- try testing.expect(std.mem.indexOf(u8, shut, glyphs.expand) != null);-}--test "hover clears when the pointer is over an overlay, which has no row targets" {- var m: Model = undefined;- try folded(&m);- defer m.deinit();- motion(&m, 4, 3);- try testing.expectEqual(hover.Target.tool, m.hover.hit.target);- m.openOverlay(.help);- motion(&m, 4, 3);- try testing.expectEqual(hover.Target.none, m.hover.hit.target);- try testing.expectEqual(@as(?usize, null), m.hover.row);-}diff --git a/TUI/image.zig b/TUI/image.zigdeleted file mode 100644index 546caa14..00000000--- a/TUI/image.zig+++ /dev/null@@ -1,590 +0,0 @@-//! [Image #N] chips: hover preview, click to pin, drop/paste paths, copy/open.--const std = @import("std");-const app = @import("app.zig");-const theme_mod = @import("theme.zig");-const key_mod = @import("key.zig");-const Model = app.Model;--/// A path still has bytes behind it. Used to decide whether a chip is a real-/// attachment (#577) or just the letters `[Image]`.-pub fn pathBacked(path: []const u8) bool {- if (path.len == 0) return false;- const io = ioHandle();- const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return false;- file.close(io);- return true;-}--pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- const th = self.theme();- const path = self.preview_path;- const meta = inspect(path);- const title = try std.fmt.allocPrint(a, " Image #{d} — {s} · {s} · {s} ", .{- if (self.preview_n == 0) 1 else self.preview_n,- meta.kind,- meta.dims,- meta.size,- });- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(try theme_mod.paint(a, th.accent, title));- try out.append('\n');- if (path.len > 0) {- try out.appendSlice(try theme_mod.paint(a, th.muted, path));- try out.append('\n');- }- // Blank rows the Kitty/iTerm2 pixels cover (imgproto.zig, after paint).- // APC stays out of this cell stream so scroll cannot leave a gray slab.- const gfx = @import("imgproto.zig");- if (gfx.supported()) {- var i: usize = 0;- const rows = gfx.pixelBox(path, width).rows;- while (i < rows) : (i += 1) try out.append('\n');- }- try out.appendSlice(try theme_mod.paint(a, th.muted, " backspace detach · y copy path · Enter open · Esc"));- try out.append('\n');- return out.toOwnedSlice();-}--const Meta = struct { kind: []const u8, dims: []const u8, size: []const u8, px_w: u32 = 0, px_h: u32 = 0 };--fn inspect(path: []const u8) Meta {- if (path.len == 0) return .{ .kind = "image", .dims = "?", .size = "?" };- const io = ioHandle();- const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch- return .{ .kind = kindFromExt(path), .dims = "?", .size = "?" };- defer file.close(io);- const st = file.stat(io) catch- return .{ .kind = kindFromExt(path), .dims = "?", .size = "?" };- var hdr: [8192]u8 = undefined;- const n = file.readPositionalAll(io, &hdr, 0) catch 0;- const px = pixelsFromHeader(hdr[0..n]);- return .{- .kind = kindFromHeader(hdr[0..n], path),- .dims = if (px) |p| (std.fmt.bufPrint(&dims_buf, "{d}×{d}", .{ p.w, p.h }) catch "?") else "?",- .size = fmtSize(st.size),- .px_w = if (px) |p| p.w else 0,- .px_h = if (px) |p| p.h else 0,- };-}--fn kindFromExt(path: []const u8) []const u8 {- if (std.ascii.endsWithIgnoreCase(path, ".png")) return "PNG";- if (std.ascii.endsWithIgnoreCase(path, ".jpg") or std.ascii.endsWithIgnoreCase(path, ".jpeg")) return "JPEG";- if (std.ascii.endsWithIgnoreCase(path, ".gif")) return "GIF";- if (std.ascii.endsWithIgnoreCase(path, ".webp")) return "WEBP";- return "image";-}--fn kindFromHeader(h: []const u8, path: []const u8) []const u8 {- if (h.len >= 8 and std.mem.eql(u8, h[0..8], "\x89PNG\r\n\x1a\n")) return "PNG";- if (h.len >= 3 and h[0] == 0xff and h[1] == 0xd8 and h[2] == 0xff) return "JPEG";- if (h.len >= 6 and (std.mem.eql(u8, h[0..6], "GIF87a") or std.mem.eql(u8, h[0..6], "GIF89a"))) return "GIF";- if (h.len >= 12 and std.mem.eql(u8, h[0..4], "RIFF") and std.mem.eql(u8, h[8..12], "WEBP")) return "WEBP";- return kindFromExt(path);-}--var dims_buf: [32]u8 = undefined;--const Px = struct { w: u32, h: u32 };--fn dimsFromHeader(h: []const u8) []const u8 {- const px = pixelsFromHeader(h) orelse return "?";- return std.fmt.bufPrint(&dims_buf, "{d}×{d}", .{ px.w, px.h }) catch "?";-}--fn pixelsFromHeader(h: []const u8) ?Px {- if (h.len >= 24 and std.mem.eql(u8, h[0..8], "\x89PNG\r\n\x1a\n"))- return .{ .w = std.mem.readInt(u32, h[16..20], .big), .h = std.mem.readInt(u32, h[20..24], .big) };- if (h.len >= 10 and (std.mem.eql(u8, h[0..6], "GIF89a") or std.mem.eql(u8, h[0..6], "GIF87a")))- return .{ .w = std.mem.readInt(u16, h[6..8], .little), .h = std.mem.readInt(u16, h[8..10], .little) };- if (jpegPx(h)) |p| return p;- if (webpPx(h)) |p| return p;- return null;-}--fn jpegPx(h: []const u8) ?Px {- if (h.len < 4 or h[0] != 0xff or h[1] != 0xd8) return null;- var i: usize = 2;- while (i + 8 < h.len) {- if (h[i] != 0xff) return null;- const marker = h[i + 1];- if (marker == 0xd8 or marker == 0xd9 or (marker >= 0xd0 and marker <= 0xd7)) {- i += 2;- continue;- }- if (i + 4 > h.len) return null;- const seglen = std.mem.readInt(u16, h[i + 2 .. i + 4][0..2], .big);- if (marker >= 0xc0 and marker <= 0xc3 and i + 8 < h.len) {- return .{- .h = std.mem.readInt(u16, h[i + 5 .. i + 7][0..2], .big),- .w = std.mem.readInt(u16, h[i + 7 .. i + 9][0..2], .big),- };- }- if (seglen < 2) return null;- i += 2 + @as(usize, seglen);- }- return null;-}--fn webpPx(h: []const u8) ?Px {- if (h.len < 30 or !std.mem.eql(u8, h[0..4], "RIFF") or !std.mem.eql(u8, h[8..12], "WEBP")) return null;- const tag = h[12..16];- if (std.mem.eql(u8, tag, "VP8 "))- return .{- .w = std.mem.readInt(u16, h[26..28][0..2], .little) & 0x3fff,- .h = std.mem.readInt(u16, h[28..30][0..2], .little) & 0x3fff,- };- if (std.mem.eql(u8, tag, "VP8X"))- return .{- .w = 1 + (@as(u32, h[24]) | (@as(u32, h[25]) << 8) | (@as(u32, h[26]) << 16)),- .h = 1 + (@as(u32, h[27]) | (@as(u32, h[28]) << 8) | (@as(u32, h[29]) << 16)),- };- return null;-}--var size_buf: [24]u8 = undefined;--fn fmtSize(n: u64) []const u8 {- if (n >= 1024 * 1024) return std.fmt.bufPrint(&size_buf, "{d:.1} MB", .{@as(f64, @floatFromInt(n)) / (1024.0 * 1024.0)}) catch "?";- if (n >= 1024) return std.fmt.bufPrint(&size_buf, "{d:.1} KB", .{@as(f64, @floatFromInt(n)) / 1024.0}) catch "?";- return std.fmt.bufPrint(&size_buf, "{d} B", .{n}) catch "?";-}--pub fn pathInUserText(src: []const u8, n: u32) ?[]const u8 {- var i: usize = 0;- var k: u32 = 0;- while (i < src.len) {- if (std.mem.startsWith(u8, src[i..], "@[")) {- if (std.mem.indexOfScalarPos(u8, src, i + 2, ']')) |close| {- k += 1;- if (k == n) return src[i + 2 .. close];- i = close + 1;- continue;- }- }- i += 1;- }- return null;-}--fn parseChip(line: []const u8, x: usize) ?u32 {- const at = std.mem.indexOf(u8, line, "[Image #") orelse return null;- const vis = theme_mod.visibleLen(line[0..at]);- var p = at + "[Image #".len;- var n: u32 = 0;- while (p < line.len and line[p] >= '0' and line[p] <= '9') : (p += 1) n = n * 10 + (line[p] - '0');- if (n == 0 or p >= line.len or line[p] != ']') return null;- const w = theme_mod.visibleLen(line[at .. p + 1]);- if (x < vis or x >= vis + w) return null;- return n;-}--fn pathForChip(self: *const Model, n: u32, hist_idx: ?usize) []const u8 {- if (hist_idx) |i| {- if (i < self.history.items.len and self.history.items[i].kind == .user) {- if (pathInUserText(self.history.items[i].text, n)) |p| return p;- }- }- if (n > 0 and n <= self.images.items.len) return self.images.items[n - 1];- return "";-}--fn show(self: *Model, path: []const u8, n: u32, pin: bool) void {- if (path.len == 0) return;- self.preview_path = path;- self.preview_n = n;- if (pin) self.preview_pin = true;- if (self.preview_rows == 0) self.preview_rows = 16;- self.openOverlay(.image);-}--/// Hover (btn 35) opens the card; click pins it. Returns true when consumed.-pub fn mouse(self: *Model, ev: key_mod.Mouse) bool {- const hover = ev.btn == 35;- const click = ev.down and ev.btn == 0;- if (!hover and !click) return false;- const y: usize = if (ev.y > 0) ev.y - 1 else 0;- const x: usize = if (ev.x > 0) ev.x - 1 else 0;- const n = chipAt(self, x, y) orelse {- if (hover and self.overlay == .image) {- const top = self.prompt_origin -| self.preview_rows;- if (y >= top and y < self.prompt_origin) return true;- if (!self.preview_pin) self.closeOverlay();- }- return false;- };- const hist = if (y >= self.prompt_origin or y < self.mid_origin + self.sticky_rows) null else @import("layout_cache.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, @import("inset.zig").wrapWidth(self));- const path = pathForChip(self, n, hist);- show(self, path, n, click);- return true;-}--fn chipAt(self: *Model, x: usize, y: usize) ?u32 {- if (self.images.items.len > 0 and y == self.prompt_origin + 1) {- const box_pad: usize = 4 + @import("inset.zig").of(self).left;- if (x < box_pad) return null;- var buf: [128]u8 = undefined;- var n: usize = 0;- var i: usize = 0;- while (i < self.images.items.len) : (i += 1) {- const s = std.fmt.bufPrint(buf[n..], "[Image #{d}] ", .{i + 1}) catch break;- n += s.len;- }- return parseChip(buf[0..n], x - box_pad);- }- if (y >= self.prompt_origin) return null;- if (y < self.mid_origin) return null;- if (y < self.mid_origin + self.sticky_rows) return null; // sticky chrome is inert- const vis = y - self.mid_origin + self.mid_skip;- const idx = @import("layout_cache.zig").indexAtVisual(self, vis, @import("inset.zig").wrapWidth(self)) orelse return null;- if (self.history.items[idx].kind != .user) return null;- if (pathInUserText(self.history.items[idx].text, 1) == null) return null;- return parseChipOnUser(self, idx, @import("inset.zig").screenToInner(self, x));-}--fn parseChipOnUser(self: *const Model, idx: usize, x: usize) ?u32 {- var no: u32 = 0;- var i: usize = 0;- while (i <= idx and i < self.history.items.len) : (i += 1) {- if (self.history.items[i].kind == .user) no += 1;- }- if (no == 0) no = 1;- var digits: usize = 1;- var t = no;- while (t >= 10) : (t /= 10) digits += 1;- // " " + "#" + digits + " "- var col: usize = 2 + 1 + digits + 2;- var n: u32 = 0;- const src = self.history.items[idx].text;- var p: usize = 0;- while (p < src.len) {- if (std.mem.startsWith(u8, src[p..], "@[")) {- if (std.mem.indexOfScalarPos(u8, src, p + 2, ']')) |close| {- n += 1;- var chip: [24]u8 = undefined;- const label = std.fmt.bufPrint(&chip, "[Image #{d}]", .{n}) catch "[Image]";- if (x >= col and x < col + label.len) return n;- col += label.len;- p = close + 1;- if (p < src.len and src[p] == ' ') p += 1;- continue;- }- }- col += 1;- p += 1;- }- return null;-}--pub fn lineChip(line: []const u8, x: usize) ?u32 {- return parseChip(line, x);-}--pub fn key(self: *Model, k: @import("key.zig").Key) bool {- if (self.overlay != .image) return false;- if (k == .escape) {- self.preview_pin = false;- self.closeOverlay();- return true;- }- if (k == .enter) {- openPath(self.preview_path);- return true;- }- if (k == .char and (k.char == 'y' or k.char == 'c')) {- copyPath(self.preview_path);- self.setToast("path copied");- return true;- }- if (k == .backspace or k == .delete or (k == .char and (k.char == 'x' or k.char == 'd'))) {- if (dropPreviewed(self)) {- self.setToast("image detached");- return true;- }- }- return false;-}--/// Backspace on an empty composer drops the last chip (#634).-pub fn dropLast(self: *Model) bool {- if (self.images.items.len == 0) return false;- const last = self.images.pop() orelse return false;- forgetPreview(self, last);- self.alloc.free(last);- @import("owned_images.zig").collect(self);- return true;-}--pub fn clearAll(self: *Model) void {- for (self.images.items) |p| {- forgetPreview(self, p);- self.alloc.free(p);- }- self.images.clearRetainingCapacity();- @import("owned_images.zig").collect(self);-}--pub fn dropPreviewed(self: *Model) bool {- if (self.preview_n == 0 or self.preview_n > self.images.items.len) return false;- const path = self.images.orderedRemove(self.preview_n - 1);- forgetPreview(self, path);- self.alloc.free(path);- @import("owned_images.zig").collect(self);- return true;-}--fn forgetPreview(self: *Model, path: []const u8) void {- if (!std.mem.eql(u8, self.preview_path, path)) return;- self.preview_path = "";- self.preview_n = 0;- self.preview_pin = false;- if (self.overlay == .image) self.closeOverlay();-}--fn ioHandle() std.Io {- return std.Io.Threaded.global_single_threaded.io();-}--fn openPath(path: []const u8) void {- if (path.len == 0) return;- const io = ioHandle();- var child = std.process.spawn(io, .{- .argv = &.{ "open", path },- .stdin = .ignore,- .stdout = .ignore,- .stderr = .ignore,- }) catch return;- _ = child.wait(io) catch {};-}--fn copyPath(path: []const u8) void {- _ = @import("selection.zig").copyText(path);-}--pub fn attachDropped(self: *Model, raw: []const u8) bool {- var any = false;- var decoded: [4096]u8 = undefined;- const whole = normalizePath(&decoded, raw);- if (@import("dispatch.zig").looksLikeImagePath(whole)) {- if (!alreadyHas(self, whole)) self.attachImage(whole);- return true;- }- var i: usize = 0;- while (nextToken(raw, &i)) |tok| {- var buf: [4096]u8 = undefined;- const p = normalizePath(&buf, tok);- if (!@import("dispatch.zig").looksLikeImagePath(p)) continue;- if (alreadyHas(self, p)) continue;- self.attachImage(p);- any = true;- }- return any;-}--fn alreadyHas(self: *const Model, p: []const u8) bool {- for (self.images.items) |q| {- if (std.mem.eql(u8, q, p)) return true;- }- return false;-}--fn nextToken(src: []const u8, i: *usize) ?[]const u8 {- while (i.* < src.len and std.ascii.isWhitespace(src[i.*])) i.* += 1;- if (i.* >= src.len) return null;- const q = src[i.*];- if (q == '\'' or q == '"') {- i.* += 1;- const start = i.*;- while (i.* < src.len and src[i.*] != q) i.* += 1;- const tok = src[start..i.*];- if (i.* < src.len) i.* += 1;- return tok;- }- const start = i.*;- while (i.* < src.len and !std.ascii.isWhitespace(src[i.*])) i.* += 1;- return src[start..i.*];-}--pub fn stripPath(s: []const u8) []const u8 {- var t = std.mem.trim(u8, s, " \t\r\n");- if (t.len >= 2 and ((t[0] == '\'' and t[t.len - 1] == '\'') or (t[0] == '"' and t[t.len - 1] == '"'))) {- t = t[1 .. t.len - 1];- }- if (std.mem.startsWith(u8, t, "file://")) t = t["file://".len..];- return t;-}--fn hexNibble(c: u8) ?u8 {- return switch (c) {- '0'...'9' => c - '0',- 'a'...'f' => c - 'a' + 10,- 'A'...'F' => c - 'A' + 10,- else => null,- };-}--fn normalizePath(dest: []u8, raw: []const u8) []const u8 {- const src = stripPath(raw);- var i: usize = 0;- var o: usize = 0;- while (i < src.len and o < dest.len) {- if (src[i] == '%' and i + 2 < src.len) {- if (hexNibble(src[i + 1])) |hi| {- if (hexNibble(src[i + 2])) |lo| {- dest[o] = (hi << 4) | lo;- o += 1;- i += 3;- continue;- }- }- }- if (src[i] == '\\' and i + 1 < src.len) {- dest[o] = src[i + 1];- o += 1;- i += 2;- continue;- }- dest[o] = src[i];- o += 1;- i += 1;- }- return dest[0..o];-}--pub const fitImageToCells = @import("imgproto.zig").fitImageToCells;--test "pathInUserText finds the nth @[path]" {- try std.testing.expectEqualStrings("/tmp/a.png", pathInUserText("@[/tmp/a.png] hi", 1).?);- try std.testing.expectEqualStrings("/tmp/b.jpg", pathInUserText("@[/tmp/a.png] @[/tmp/b.jpg]", 2).?);- try std.testing.expect(pathInUserText("nope", 1) == null);-}--test "parseChip hits only the chip columns" {- const line = " #4 [Image #1] hello";- const at = std.mem.indexOf(u8, line, "[Image #1]").?;- try std.testing.expectEqual(@as(u32, 1), parseChip(line, at).?);- try std.testing.expect(parseChip(line, 0) == null);-}--test "dimsFromHeader reads PNG IHDR" {- var h: [24]u8 = undefined;- @memcpy(h[0..8], "\x89PNG\r\n\x1a\n");- std.mem.writeInt(u32, h[16..20], 1402, .big);- std.mem.writeInt(u32, h[20..24], 394, .big);- try std.testing.expectEqualStrings("1402×394", dimsFromHeader(&h));-}--test "image overlay stays in the cell grid — no Kitty APC" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.preview_path = "/tmp/a.png";- m.preview_n = 1;- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, text, "\x1b_G") == null);- try std.testing.expect(std.mem.indexOf(u8, text, "Image #1") != null);-}--test "image overlay reserves pixel rows when graphics are on" {- const gfx = @import("imgproto.zig");- gfx.setSupportedForTest(true);- defer gfx.setSupportedForTest(false);- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.preview_path = "/tmp/a.png";- m.preview_n = 1;- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, text, "\x1b_G") == null);- var n: usize = 0;- for (text) |c| {- if (c == '\n') n += 1;- }- try std.testing.expect(n >= 10);-}--test "fmtSize matches the Grok card" {- try std.testing.expectEqualStrings("74.0 KB", fmtSize(74 * 1024));- try std.testing.expectEqualStrings("12 B", fmtSize(12));-}--test "stripPath unwraps quotes and file URLs" {- try std.testing.expectEqualStrings("/tmp/a.png", stripPath("'/tmp/a.png'"));- try std.testing.expectEqualStrings("/tmp/a.png", stripPath("file:///tmp/a.png"));- try std.testing.expectEqualStrings("/tmp/a.png", stripPath(" \"/tmp/a.png\" "));-}--test "attachDropped accepts quoted paths with spaces" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expect(attachDropped(&m, "'/Users/me/My Shot.png'"));- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings("/Users/me/My Shot.png", m.images.items[0]);- try std.testing.expect(attachDropped(&m, "file:///Users/me/My%20Shot.png"));- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);-}--test "click on a user image chip opens the preview overlay" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "@[/tmp/shot.png] can you see this");- m.last_term_width = 80;- m.last_term_height = 24;- m.mid_origin = 0;- m.mid_skip = 0;- m.prompt_origin = 20;- try std.testing.expect(mouse(&m, .{ .btn = 0, .x = 10, .y = 1, .down = true }));- try std.testing.expectEqual(app.Overlay.image, m.overlay);- try std.testing.expectEqualStrings("/tmp/shot.png", m.preview_path);- try std.testing.expect(m.preview_pin);-}--test "pathBacked is true only when the file is there (#577)" {- try std.testing.expect(!pathBacked(""));- try std.testing.expect(!pathBacked("/no/such/image-577.png"));- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = "y.png", .data = "y" });- var dir_buf: [std.fs.max_path_bytes]u8 = undefined;- const dir_n = try tmp.dir.realPath(io, &dir_buf);- var buf: [std.fs.max_path_bytes]u8 = undefined;- const live = try std.fmt.bufPrint(&buf, "{s}/y.png", .{dir_buf[0..dir_n]});- try std.testing.expect(pathBacked(live));-}--test "hover on a composer chip opens an unpinned preview" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage("/tmp/shot.png");- m.last_term_width = 80;- m.prompt_origin = 10;- // 1-based: left gutter (2) + box pad (4) + into "[Image #1]"- try std.testing.expect(mouse(&m, .{ .btn = 35, .x = 12, .y = 12, .down = false }));- try std.testing.expectEqual(app.Overlay.image, m.overlay);- try std.testing.expectEqualStrings("/tmp/shot.png", m.preview_path);- try std.testing.expect(!m.preview_pin);-}--test "overlay backspace detaches the previewed composer chip (#634)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage("/tmp/a.png");- m.attachImage("/tmp/b.png");- m.preview_path = m.images.items[0];- m.preview_n = 1;- m.openOverlay(.image);- try std.testing.expect(key(&m, .backspace));- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings("/tmp/b.png", m.images.items[0]);- try std.testing.expectEqual(app.Overlay.none, m.overlay);-}diff --git a/TUI/imgproto.zig b/TUI/imgproto.zigdeleted file mode 100644index 2cdae758..00000000--- a/TUI/imgproto.zig+++ /dev/null@@ -1,466 +0,0 @@-//! Kitty / iTerm2 pixels for the image overlay, after the cell paint.-//!-//! Grok-build's rule: the frame stays a cell grid (no APC in overlay text).-//! After paint() flushes, we place the image at the reserved blank rows with-//! `C=1` (cursor stays put) and `z=1` (above cells). Closing the overlay, a-//! geometry change, or a full wipe deletes the placement so it cannot survive-//! as a gray slab on scroll. Unit tests force this off (`builtin.is_test`).--const std = @import("std");-const builtin = @import("builtin");-const Io = std.Io;--const app = @import("app.zig");-const Model = app.Model;--pub const max_bytes: usize = 2 * 1024 * 1024;-pub const max_pixel_rows: usize = 12;-const chunk_b64: usize = 4096;-const kitty_id: u32 = 1;--pub const Protocol = enum { none, kitty, iterm2 };--pub const Place = struct {- x: u16,- y: u16,- cols: u16,- rows: u16,-};--pub const Slot = struct {- on: bool = false,- path_hash: u64 = 0,- x: u16 = 0,- y: u16 = 0,- cols: u16 = 0,- rows: u16 = 0,-- fn matches(self: Slot, path: []const u8, p: Place) bool {- if (!self.on) return false;- if (self.x != p.x or self.y != p.y or self.cols != p.cols or self.rows != p.rows) return false;- return self.path_hash == std.hash.Wyhash.hash(0, path);- }-- fn remember(self: *Slot, path: []const u8, p: Place) void {- self.on = true;- self.path_hash = std.hash.Wyhash.hash(0, path);- self.x = p.x;- self.y = p.y;- self.cols = p.cols;- self.rows = p.rows;- }-};--pub const clear_all = "\x1b_Ga=d,d=A,q=2\x1b\\";--var test_on: bool = false;--pub fn setSupportedForTest(on: bool) void {- test_on = on;-}--pub fn supported() bool {- if (builtin.is_test) return test_on;- return protocol() != .none;-}--pub fn protocol() Protocol {- if (builtin.os.tag == .windows) return .none;- if (std.c.getenv("TMUX") != null) return .none;- const program = if (std.c.getenv("TERM_PROGRAM")) |z| std.mem.span(z) else "";- const term = if (std.c.getenv("TERM")) |z| std.mem.span(z) else "";- return protocolFor(program, term);-}--pub fn protocolFor(term_program: []const u8, term: []const u8) Protocol {- if (eq(term_program, "ghostty") or eq(term_program, "kitty") or- eq(term_program, "WezTerm") or eq(term_program, "WarpTerminal") or- eq(term, "xterm-ghostty") or eq(term, "xterm-kitty"))- return .kitty;- if (eq(term_program, "iTerm.app")) return .iterm2;- return .none;-}--fn eq(a: []const u8, b: []const u8) bool {- return std.ascii.eqlIgnoreCase(a, b);-}--const Box = struct { cols: usize, rows: usize };--pub fn pixelBox(path: []const u8, width: usize) Box {- const max_cols = if (width > 4) width - 2 else 1;- const px = pixelsAt(path) orelse return .{ .cols = max_cols, .rows = @min(max_pixel_rows, 8) };- return fitImageToCells(px.w, px.h, max_cols, max_pixel_rows);-}--/// Grok Build `fit_image_to_cells`: monospace cells are ~0.5 as wide as tall.-pub fn fitImageToCells(img_w: u32, img_h: u32, max_cols: usize, max_rows: usize) Box {- if (img_w == 0 or img_h == 0 or max_cols == 0 or max_rows == 0)- return .{ .cols = @max(max_cols, 1), .rows = @max(max_rows, 1) };- const cols_per_row = (@as(f64, @floatFromInt(img_w)) / @as(f64, @floatFromInt(img_h))) / 0.5;- const rows_by_width: usize = @intFromFloat(@round(@as(f64, @floatFromInt(max_cols)) / cols_per_row));- if (rows_by_width <= max_rows) return .{ .cols = max_cols, .rows = @max(rows_by_width, 1) };- const cols_by_height: usize = @intFromFloat(@round(@as(f64, @floatFromInt(max_rows)) * cols_per_row));- return .{ .cols = @min(@max(cols_by_height, 1), max_cols), .rows = max_rows };-}--pub fn place(m: *const Model, term_cols: usize) ?Place {- if (!supported()) return null;- if (m.overlay != .image or m.preview_path.len == 0) return null;- const box = pixelBox(m.preview_path, term_cols);- if (box.cols == 0 or box.rows == 0) return null;- var headers: usize = 1;- if (m.preview_path.len > 0) headers += 1;- const y0 = m.prompt_origin -| m.preview_rows + headers;- return .{- .x = 1,- .y = @intCast(@min(y0 + 1, 9999)),- .cols = @intCast(@min(box.cols, 9999)),- .rows = @intCast(@min(box.rows, 9999)),- };-}--/// After the cell paint, inside ?2026. `wiping` means the screen was cleared-/// or every row rewritten — re-place even if geometry matches.-pub fn sync(- w: *Io.Writer,- alloc: std.mem.Allocator,- slot: *Slot,- m: *const Model,- term_cols: usize,- wiping: bool,-) void {- const p = place(m, term_cols);- const keep = if (p) |pl| slot.matches(m.preview_path, pl) and !wiping else false;- if (slot.on and !keep) {- w.writeAll(clear_all) catch {};- slot.on = false;- }- if (keep) return;- const pl = p orelse return;- if (draw(w, alloc, m.preview_path, pl, protocol())) slot.remember(m.preview_path, pl);-}--fn draw(w: *Io.Writer, alloc: std.mem.Allocator, path: []const u8, p: Place, proto: Protocol) bool {- if (proto == .none) return false;- const png = loadPng(alloc, path) orelse return false;- defer alloc.free(png);- w.print("\x1b[{d};{d}H", .{ p.y, p.x }) catch return false;- switch (proto) {- .kitty => kittyPlace(w, alloc, png, p.cols, p.rows) catch return false,- .iterm2 => itermPlace(w, alloc, png, p.cols, p.rows) catch return false,- .none => return false,- }- return true;-}--fn loadPng(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {- const io = ioHandle();- const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null;- defer file.close(io);- const st = file.stat(io) catch return null;- if (st.size == 0 or st.size > max_bytes) return null;- const buf = alloc.alloc(u8, @intCast(st.size)) catch return null;- const n = file.readPositionalAll(io, buf, 0) catch {- alloc.free(buf);- return null;- };- if (n < buf.len) {- alloc.free(buf);- return null;- }- if (isPng(buf)) return buf;- alloc.free(buf);- return convertToPng(alloc, path);-}--fn convertToPng(alloc: std.mem.Allocator, path: []const u8) ?[]u8 {- if (builtin.os.tag != .macos) return null;- const io = ioHandle();- var random: [16]u8 = undefined;- io.random(&random);- const hex = std.fmt.bytesToHex(random, .lower);- var dst_buf: [100]u8 = undefined;- const dst = std.fmt.bufPrint(&dst_buf, "/tmp/graff-img-{d}-{s}.png", .{ std.c.getpid(), hex }) catch return null;- return convertToPngAt(alloc, path, dst);-}--fn convertToPngAt(alloc: std.mem.Allocator, path: []const u8, dst: []const u8) ?[]u8 {- var threaded = Io.Threaded.init(alloc, .{});- defer threaded.deinit();- const io = threaded.io();- // Claim our output before the converter runs; never overwrite or clean up- // an existing file, including one belonging to another conversion.- const claim = Io.Dir.cwd().createFile(io, dst, .{ .exclusive = true, .permissions = .fromMode(0o600) }) catch return null;- claim.close(io);- defer Io.Dir.cwd().deleteFile(io, dst) catch {};- var child = std.process.spawn(io, .{- .argv = &.{ "/usr/bin/sips", "-s", "format", "png", path, "--out", dst },- .stdin = .ignore,- .stdout = .ignore,- .stderr = .ignore,- }) catch return null;- const term = child.wait(io) catch return null;- if (term != .exited or term.exited != 0) return null;- const file = std.Io.Dir.cwd().openFile(io, dst, .{}) catch return null;- defer file.close(io);- const info = file.stat(io) catch return null;- if (info.size == 0 or info.size > max_bytes) return null;- const buf = alloc.alloc(u8, @intCast(info.size)) catch return null;- const n = file.readPositionalAll(io, buf, 0) catch {- alloc.free(buf);- return null;- };- if (n < buf.len or !isPng(buf)) {- alloc.free(buf);- return null;- }- return buf;-}--fn isPng(h: []const u8) bool {- return h.len >= 8 and std.mem.eql(u8, h[0..8], "\x89PNG\r\n\x1a\n");-}--const Px = struct { w: u32, h: u32 };--fn pixelsAt(path: []const u8) ?Px {- if (path.len == 0) return null;- const io = ioHandle();- const file = std.Io.Dir.cwd().openFile(io, path, .{}) catch return null;- defer file.close(io);- var hdr: [8192]u8 = undefined;- const n = file.readPositionalAll(io, &hdr, 0) catch 0;- return pixelsFromHeader(hdr[0..n]);-}--fn pixelsFromHeader(h: []const u8) ?Px {- if (h.len >= 24 and isPng(h))- return .{ .w = std.mem.readInt(u32, h[16..20], .big), .h = std.mem.readInt(u32, h[20..24], .big) };- if (h.len >= 10 and (std.mem.eql(u8, h[0..6], "GIF89a") or std.mem.eql(u8, h[0..6], "GIF87a")))- return .{ .w = std.mem.readInt(u16, h[6..8], .little), .h = std.mem.readInt(u16, h[8..10], .little) };- return jpegPx(h) orelse webpPx(h);-}--fn jpegPx(h: []const u8) ?Px {- if (h.len < 4 or h[0] != 0xff or h[1] != 0xd8) return null;- var i: usize = 2;- while (i + 8 < h.len) {- if (h[i] != 0xff) return null;- const marker = h[i + 1];- if (marker == 0xd8 or marker == 0xd9 or (marker >= 0xd0 and marker <= 0xd7)) {- i += 2;- continue;- }- if (i + 4 > h.len) return null;- const seglen = std.mem.readInt(u16, h[i + 2 .. i + 4][0..2], .big);- if (marker >= 0xc0 and marker <= 0xc3 and i + 8 < h.len) {- return .{- .h = std.mem.readInt(u16, h[i + 5 .. i + 7][0..2], .big),- .w = std.mem.readInt(u16, h[i + 7 .. i + 9][0..2], .big),- };- }- if (seglen < 2) return null;- i += 2 + @as(usize, seglen);- }- return null;-}--fn webpPx(h: []const u8) ?Px {- if (h.len < 30 or !std.mem.eql(u8, h[0..4], "RIFF") or !std.mem.eql(u8, h[8..12], "WEBP")) return null;- const tag = h[12..16];- if (std.mem.eql(u8, tag, "VP8 "))- return .{- .w = std.mem.readInt(u16, h[26..28][0..2], .little) & 0x3fff,- .h = std.mem.readInt(u16, h[28..30][0..2], .little) & 0x3fff,- };- if (std.mem.eql(u8, tag, "VP8X"))- return .{- .w = 1 + (@as(u32, h[24]) | (@as(u32, h[25]) << 8) | (@as(u32, h[26]) << 16)),- .h = 1 + (@as(u32, h[27]) | (@as(u32, h[28]) << 8) | (@as(u32, h[29]) << 16)),- };- return null;-}--pub fn kittyPlace(w: *Io.Writer, alloc: std.mem.Allocator, png: []const u8, cols: u16, rows: u16) !void {- const enc = std.base64.standard.Encoder;- const total = enc.calcSize(png.len);- const b64 = try alloc.alloc(u8, total);- defer alloc.free(b64);- _ = enc.encode(b64, png);- var off: usize = 0;- var first = true;- while (off < b64.len) {- const n = @min(chunk_b64, b64.len - off);- const last = off + n == b64.len;- const m: u8 = if (last) 0 else 1;- if (first) {- try w.print("\x1b_Ga=T,f=100,t=d,q=2,C=1,z=1,i={d},p={d},c={d},r={d},m={d};", .{- kitty_id, kitty_id, cols, rows, m,- });- first = false;- } else {- try w.print("\x1b_Gq=2,m={d};", .{m});- }- try w.writeAll(b64[off .. off + n]);- try w.writeAll("\x1b\\");- off += n;- }-}--fn itermPlace(w: *Io.Writer, alloc: std.mem.Allocator, bytes: []const u8, cols: u16, rows: u16) !void {- const enc = std.base64.standard.Encoder;- const total = enc.calcSize(bytes.len);- const b64 = try alloc.alloc(u8, total);- defer alloc.free(b64);- _ = enc.encode(b64, bytes);- try w.print("\x1b]1337;File=inline=1;doNotMoveCursor=1;width={d};height={d};preserveAspectRatio=1:", .{ cols, rows });- try w.writeAll(b64);- try w.writeAll("\x07");-}--fn ioHandle() std.Io {- return std.Io.Threaded.global_single_threaded.io();-}--test "protocolFor matches Grok brands" {- try std.testing.expectEqual(Protocol.kitty, protocolFor("ghostty", "xterm-256color"));- try std.testing.expectEqual(Protocol.kitty, protocolFor("kitty", "xterm-kitty"));- try std.testing.expectEqual(Protocol.kitty, protocolFor("", "xterm-ghostty"));- try std.testing.expectEqual(Protocol.iterm2, protocolFor("iTerm.app", "xterm-256color"));- try std.testing.expectEqual(Protocol.none, protocolFor("Apple_Terminal", "xterm-256color"));-}--test "supported is off under zig test" {- try std.testing.expect(!supported());- setSupportedForTest(true);- defer setSupportedForTest(false);- try std.testing.expect(supported());-}--test "kittyPlace is APC, PNG, cursor-preserving, not in a text row" {- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- const png = "\x89PNG\r\n\x1a\n" ++ "xxxx";- try kittyPlace(&aw.writer, std.testing.allocator, png, 20, 8);- const s = aw.writer.buffered();- try std.testing.expect(std.mem.startsWith(u8, s, "\x1b_Ga=T,f=100,t=d,q=2,C=1,z=1"));- try std.testing.expect(std.mem.indexOf(u8, s, "c=20,r=8") != null);- try std.testing.expect(std.mem.indexOf(u8, s, "\x1b\\") != null);-}--test "sync keep-path does not retransmit" {- setSupportedForTest(true);- defer setSupportedForTest(false);- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.overlay = .image;- m.preview_path = "/tmp/missing-imgproto.png";- m.preview_rows = 12;- m.prompt_origin = 20;- var slot: Slot = .{};- slot.remember("/tmp/missing-imgproto.png", place(&m, 80).?);- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- sync(&aw.writer, std.testing.allocator, &slot, &m, 80, false);- try std.testing.expectEqual(@as(usize, 0), aw.writer.buffered().len);- try std.testing.expect(slot.on);-}--test "sync wipe deletes even when geometry matches" {- setSupportedForTest(true);- defer setSupportedForTest(false);- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.overlay = .image;- m.preview_path = "/tmp/missing-imgproto.png";- m.preview_rows = 12;- m.prompt_origin = 20;- var slot: Slot = .{};- slot.remember("/tmp/missing-imgproto.png", place(&m, 80).?);- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- sync(&aw.writer, std.testing.allocator, &slot, &m, 80, true);- const s = aw.writer.buffered();- try std.testing.expect(std.mem.indexOf(u8, s, clear_all) != null);-}--test "sync close overlay deletes" {- setSupportedForTest(true);- defer setSupportedForTest(false);- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.overlay = .none;- var slot: Slot = .{ .on = true };- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- sync(&aw.writer, std.testing.allocator, &slot, &m, 80, false);- try std.testing.expectEqualStrings(clear_all, aw.writer.buffered());- try std.testing.expect(!slot.on);-}--test "fitImageToCells matches Grok cell-aspect 0.5" {- const wide = fitImageToCells(1512, 644, 72, 10);- try std.testing.expectEqual(@as(usize, 47), wide.cols);- try std.testing.expectEqual(@as(usize, 10), wide.rows);- const sq = fitImageToCells(100, 100, 40, 10);- try std.testing.expectEqual(@as(usize, 20), sq.cols);- try std.testing.expectEqual(@as(usize, 10), sq.rows);-}--test "preview conversion removes its scratch output after reading valid pixels" {- if (builtin.os.tag != .macos) return error.SkipZigTest;- const alloc = std.testing.allocator;- const io = ioHandle();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- // A one-pixel 24-bit BMP, so the real converter must produce PNG bytes.- var bmp: [58]u8 = @splat(0);- @memcpy(bmp[0..2], "BM");- std.mem.writeInt(u32, bmp[2..6], 58, .little);- std.mem.writeInt(u32, bmp[10..14], 54, .little);- std.mem.writeInt(u32, bmp[14..18], 40, .little);- std.mem.writeInt(u32, bmp[18..22], 1, .little);- std.mem.writeInt(u32, bmp[22..26], 1, .little);- std.mem.writeInt(u16, bmp[26..28], 1, .little);- std.mem.writeInt(u16, bmp[28..30], 24, .little);- std.mem.writeInt(u32, bmp[34..38], 4, .little);- bmp[56] = 255;- try tmp.dir.writeFile(io, .{ .sub_path = "input.bmp", .data = &bmp });- const root = try tmp.dir.realPathFileAlloc(io, ".", alloc);- defer alloc.free(root);- const input = try std.fs.path.join(alloc, &.{ root, "input.bmp" });- defer alloc.free(input);- const output = try std.fs.path.join(alloc, &.{ root, "scratch.png" });- defer alloc.free(output);- const bytes = convertToPngAt(alloc, input, output) orelse return error.ConversionFailed;- defer alloc.free(bytes);- try std.testing.expect(isPng(bytes));- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "scratch.png", .{}));- const original = try tmp.dir.openFile(io, "input.bmp", .{});- original.close(io);-}--test "failed preview conversion removes only its claimed scratch output" {- if (builtin.os.tag != .macos) return error.SkipZigTest;- const alloc = std.testing.allocator;- const io = ioHandle();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", alloc);- defer alloc.free(root);- const output = try std.fs.path.join(alloc, &.{ root, "scratch.png" });- defer alloc.free(output);- try std.testing.expect(convertToPngAt(alloc, "/missing-preview-input", output) == null);- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "scratch.png", .{}));- try tmp.dir.writeFile(io, .{ .sub_path = "scratch.png", .data = "existing original" });- try std.testing.expect(convertToPngAt(alloc, "/missing-preview-input", output) == null);- const original = try tmp.dir.openFile(io, "scratch.png", .{});- defer original.close(io);- var bytes: [32]u8 = undefined;- const count = try original.readPositionalAll(io, &bytes, 0);- try std.testing.expectEqualStrings("existing original", bytes[0..count]);-}diff --git a/TUI/input.zig b/TUI/input.zigdeleted file mode 100644index 0131749c..00000000--- a/TUI/input.zig+++ /dev/null@@ -1,450 +0,0 @@-//! Composer buffer. Soft-wrap lives in chrome; undo is Ctrl/Cmd+Z.--const std = @import("std");-const glyphs = @import("glyphs.zig");-const Key = @import("key.zig").Key;--pub const Span = struct {- start: usize,- end: usize,-};--pub const State = struct {- text: []u8,- cursor: usize,- spans: []Span,-};--const Snap = State;-pub const Range = struct { start: usize, end: usize };--pub const Input = struct {- alloc: std.mem.Allocator,- buf: std.array_list.Managed(u8),- spans: std.array_list.Managed(Span),- undo_stack: std.array_list.Managed(Snap),- cursor: usize = 0,- placeholder: []const u8 = "",- paste_start: ?usize = null,- compound_edit: bool = false,- compound_snapshot: bool = false,-- pub fn init(alloc: std.mem.Allocator) Input {- return .{- .alloc = alloc,- .buf = std.array_list.Managed(u8).init(alloc),- .spans = std.array_list.Managed(Span).init(alloc),- .undo_stack = std.array_list.Managed(Snap).init(alloc),- };- }-- pub fn deinit(self: *Input) void {- for (self.undo_stack.items) |sn| freeState(self.alloc, sn);- self.undo_stack.deinit();- self.spans.deinit();- self.buf.deinit();- }-- pub fn snapshot(self: *const Input) !State {- const text = try self.alloc.dupe(u8, self.buf.items);- errdefer self.alloc.free(text);- return .{- .text = text,- .cursor = self.cursor,- .spans = try self.alloc.dupe(Span, self.spans.items),- };- }-- pub fn freeSnapshot(self: *const Input, state: State) void {- freeState(self.alloc, state);- }-- pub fn setState(self: *Input, state: State) !void {- self.pushUndo();- try self.buf.ensureTotalCapacity(state.text.len);- try self.spans.ensureTotalCapacity(state.spans.len);- self.buf.clearRetainingCapacity();- self.spans.clearRetainingCapacity();- try self.buf.appendSlice(state.text);- try self.spans.appendSlice(state.spans);- self.cursor = @min(state.cursor, self.buf.items.len);- self.paste_start = null;- self.compound_edit = false;- self.compound_snapshot = false;- }-- fn pushUndo(self: *Input) void {- const snap = self.snapshot() catch return;- self.undo_stack.append(snap) catch {- freeState(self.alloc, snap);- return;- };- if (self.undo_stack.items.len > 64) {- freeState(self.alloc, self.undo_stack.orderedRemove(0));- }- }-- fn maybePushUndo(self: *Input) void {- if (!self.compound_edit) {- self.pushUndo();- } else if (!self.compound_snapshot) {- self.pushUndo();- self.compound_snapshot = true;- }- }-- /// Restore the previous snapshot. False when the stack is empty.- pub fn undo(self: *Input) bool {- const snap = self.undo_stack.pop() orelse return false;- defer freeState(self.alloc, snap);- self.buf.ensureTotalCapacity(snap.text.len) catch return false;- self.spans.ensureTotalCapacity(snap.spans.len) catch return false;- self.buf.clearRetainingCapacity();- self.spans.clearRetainingCapacity();- self.buf.appendSlice(snap.text) catch return false;- self.spans.appendSlice(snap.spans) catch return false;- self.cursor = @min(snap.cursor, self.buf.items.len);- self.paste_start = null;- self.compound_edit = false;- self.compound_snapshot = false;- return true;- }-- pub fn getValue(self: *const Input) []const u8 {- return self.buf.items;- }-- pub fn semanticSpans(self: *const Input) []const Span {- return self.spans.items;- }-- pub fn spanEndAt(self: *const Input, at: usize) ?usize {- for (self.spans.items) |span| {- if (span.start == at and span.end <= self.buf.items.len) return span.end;- }- return null;- }-- pub fn setValue(self: *Input, text: []const u8) !void {- if (!std.mem.eql(u8, self.buf.items, text) or self.spans.items.len > 0) self.pushUndo();- self.buf.clearRetainingCapacity();- self.spans.clearRetainingCapacity();- try self.buf.appendSlice(text);- self.cursor = self.buf.items.len;- self.paste_start = null;- self.compound_edit = false;- self.compound_snapshot = false;- }-- pub fn insertSlice(self: *Input, text: []const u8) void {- if (text.len == 0) return;- if (!self.replaceRange(self.cursor, self.cursor, text)) return;- self.cursor += text.len;- }-- pub fn beginPaste(self: *Input) void {- if (self.paste_start != null) return;- self.paste_start = self.cursor;- self.compound_edit = true;- self.compound_snapshot = false;- }-- pub fn pasteRange(self: *const Input) ?Range {- const start = self.paste_start orelse return null;- if (self.cursor < start) return null;- return .{ .start = start, .end = self.cursor };- }-- pub fn endPaste(self: *Input) void {- self.paste_start = null;- self.compound_edit = false;- self.compound_snapshot = false;- }-- pub fn replacePaste(self: *Input, range: Range, text: []const u8, atomic: bool) bool {- if (atomic) self.spans.ensureUnusedCapacity(1) catch return false;- if (!self.replaceRange(range.start, range.end, text)) return false;- self.cursor = range.start + text.len;- if (atomic and text.len > 0) {- self.spans.appendAssumeCapacity(.{ .start = range.start, .end = self.cursor });- std.mem.sort(Span, self.spans.items, {}, spanLessThan);- }- return true;- }-- /// The separator is ordinary text outside a semantic span: one Backspace- /// removes it, and the next Backspace removes the whole pasted file.- pub fn ensurePasteSeparator(self: *Input) void {- if (self.cursor == 0) return;- if (std.ascii.isWhitespace(self.buf.items[self.cursor - 1])) return;- if (self.cursor < self.buf.items.len and std.ascii.isWhitespace(self.buf.items[self.cursor])) return;- if (!self.replaceRange(self.cursor, self.cursor, " ")) return;- self.cursor += 1;- }-- pub fn setPlaceholder(self: *Input, text: []const u8) void {- self.placeholder = text;- }-- pub fn handle(self: *Input, k: Key) void {- switch (k) {- .char => |c| {- var one = [_]u8{c};- self.insertSlice(&one);- },- .codepoint => |cp| {- var b: [4]u8 = undefined;- const n = std.unicode.utf8Encode(cp, &b) catch return;- self.insertSlice(b[0..n]);- },- .backspace => {- if (self.cursor == 0) return;- self.deleteAndLand(self.cursor - 1, self.cursor);- },- .left => self.cursor = self.left(self.cursor),- .right => self.cursor = self.right(self.cursor),- .home => self.cursor = 0,- .end => self.cursor = self.buf.items.len,- .word_left => self.cursor = self.prevWord(self.cursor),- .word_right => self.cursor = self.nextWord(self.cursor),- .delete_word => self.killTo(self.prevWord(self.cursor)),- .delete_to_start => self.killTo(0),- .delete_to_end => self.deleteAndLand(self.cursor, self.buf.items.len),- .delete => self.deleteAndLand(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),- .ctrl => |c| switch (c) {- 'a' => self.cursor = 0,- 'e' => self.cursor = self.buf.items.len,- 'k' => self.deleteAndLand(self.cursor, self.buf.items.len),- 'u' => self.killTo(0),- 'w' => self.killTo(self.prevWord(self.cursor)),- 'd' => self.deleteAndLand(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),- else => {},- },- else => {},- }- }-- fn left(self: *const Input, cursor: usize) usize {- for (self.spans.items) |span| {- if (cursor > span.start and cursor <= span.end) return span.start;- }- // Land on a scalar start, never inside a multi-byte sequence (#788).- var c = cursor -| 1;- while (c > 0 and c < self.buf.items.len and self.buf.items[c] & 0xc0 == 0x80) c -= 1;- return c;- }-- fn right(self: *const Input, cursor: usize) usize {- for (self.spans.items) |span| {- if (cursor >= span.start and cursor < span.end) return span.end;- }- var c = @min(cursor + 1, self.buf.items.len);- while (c < self.buf.items.len and self.buf.items[c] & 0xc0 == 0x80) c += 1;- return c;- }-- fn prevWord(self: *const Input, cursor: usize) usize {- for (self.spans.items) |span| {- if (cursor > span.start and cursor <= span.end) return span.start;- }- const plain = plainPrevWord(self.buf.items, cursor);- for (self.spans.items) |span| {- if (plain > span.start and plain < span.end) return span.start;- }- return plain;- }-- fn nextWord(self: *const Input, cursor: usize) usize {- for (self.spans.items) |span| {- if (cursor >= span.start and cursor < span.end) return span.end;- }- const plain = plainNextWord(self.buf.items, cursor);- for (self.spans.items) |span| {- if (plain > span.start and plain < span.end) return span.end;- }- return plain;- }-- fn killTo(self: *Input, at: usize) void {- self.deleteAndLand(at, self.cursor);- }-- fn deleteAndLand(self: *Input, from: usize, to: usize) void {- if (from >= to or to > self.buf.items.len) return;- const expanded = self.expandRange(from, to);- if (!self.replaceRange(expanded.start, expanded.end, "")) return;- self.cursor = expanded.start;- }-- fn expandRange(self: *const Input, from: usize, to: usize) Range {- var out = Range{ .start = from, .end = to };- var changed = true;- while (changed) {- changed = false;- for (self.spans.items) |span| {- if (out.start >= span.end or out.end <= span.start) continue;- const start = @min(out.start, span.start);- const end = @max(out.end, span.end);- if (start != out.start or end != out.end) changed = true;- out = .{ .start = start, .end = end };- }- }- return out;- }-- fn replaceRange(self: *Input, from: usize, to: usize, text: []const u8) bool {- if (from > to or to > self.buf.items.len) return false;- self.buf.ensureUnusedCapacity(text.len) catch return false;- self.maybePushUndo();- self.updateSpans(from, to, text.len);- var i = to;- while (i > from) {- i -= 1;- _ = self.buf.orderedRemove(i);- }- self.buf.insertSlice(from, text) catch unreachable;- return true;- }-- fn updateSpans(self: *Input, from: usize, to: usize, inserted_len: usize) void {- const removed_len = to - from;- var i: usize = 0;- while (i < self.spans.items.len) {- const span = &self.spans.items[i];- if (to <= span.start) {- shiftSpan(span, removed_len, inserted_len);- i += 1;- } else if (from >= span.end) {- i += 1;- } else {- _ = self.spans.orderedRemove(i);- }- }- }-- pub fn view(self: *const Input, a: std.mem.Allocator) ![]const u8 {- return self.viewStyled(a, "", "");- }-- pub fn viewStyled(self: *const Input, a: std.mem.Allocator, accent: []const u8, base: []const u8) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- errdefer out.deinit();- if (self.buf.items.len == 0) {- try out.appendSlice(self.placeholder);- try out.appendSlice(glyphs.cursor);- return out.toOwnedSlice();- }- var source: usize = 0;- var cursor_drawn = false;- for (self.spans.items) |span| {- if (span.start < source or span.end > self.buf.items.len) continue;- try appendCursorSlice(&out, self.buf.items[source..span.start], source, self.cursor, &cursor_drawn);- if (!cursor_drawn and self.cursor == span.start) {- try out.appendSlice(glyphs.cursor);- cursor_drawn = true;- }- try out.appendSlice(accent);- try appendCursorSlice(&out, self.buf.items[span.start..span.end], span.start, self.cursor, &cursor_drawn);- try out.appendSlice(base);- source = span.end;- }- try appendCursorSlice(&out, self.buf.items[source..], source, self.cursor, &cursor_drawn);- if (!cursor_drawn) try out.appendSlice(glyphs.cursor);- return out.toOwnedSlice();- }-};--fn appendCursorSlice(- out: *std.array_list.Managed(u8),- text: []const u8,- base: usize,- cursor: usize,- drawn: *bool,-) !void {- if (!drawn.* and cursor >= base and cursor < base + text.len) {- const at = cursor - base;- try out.appendSlice(text[0..at]);- try out.appendSlice(glyphs.cursor);- try out.appendSlice(text[at..]);- drawn.* = true;- } else {- try out.appendSlice(text);- }-}--fn freeState(alloc: std.mem.Allocator, state: State) void {- alloc.free(state.text);- alloc.free(state.spans);-}--fn spanLessThan(_: void, a: Span, b: Span) bool {- return a.start < b.start;-}--fn shiftSpan(span: *Span, removed_len: usize, inserted_len: usize) void {- if (inserted_len >= removed_len) {- const delta = inserted_len - removed_len;- span.start += delta;- span.end += delta;- } else {- const delta = removed_len - inserted_len;- span.start -= delta;- span.end -= delta;- }-}--fn plainPrevWord(s: []const u8, cur: usize) usize {- var i = cur;- while (i > 0 and s[i - 1] == ' ') i -= 1;- while (i > 0 and s[i - 1] != ' ') i -= 1;- return i;-}--fn plainNextWord(s: []const u8, cur: usize) usize {- var i = cur;- while (i < s.len and s[i] != ' ') i += 1;- while (i < s.len and s[i] == ' ') i += 1;- return i;-}--test "insert and backspace" {- var in = Input.init(std.testing.allocator);- defer in.deinit();- in.handle(.{ .char = 'h' });- in.handle(.{ .char = 'i' });- try std.testing.expectEqualStrings("hi", in.getValue());- in.handle(.backspace);- try std.testing.expectEqualStrings("h", in.getValue());- in.insertSlice("éllo");- try std.testing.expectEqualStrings("héllo", in.getValue());-}--test "cmd-delete and alt-backspace kill the line and the word" {- var in = Input.init(std.testing.allocator);- defer in.deinit();- try in.setValue("one two three");- in.cursor = in.buf.items.len;- in.handle(.delete_word);- try std.testing.expectEqualStrings("one two ", in.getValue());- in.handle(.delete_to_start);- try std.testing.expectEqualStrings("", in.getValue());-}--test "ctrl-z undoes the last edit" {- var in = Input.init(std.testing.allocator);- defer in.deinit();- in.handle(.{ .char = 'h' });- in.handle(.{ .char = 'i' });- try std.testing.expect(in.undo());- try std.testing.expectEqualStrings("h", in.getValue());- try std.testing.expect(in.undo());- try std.testing.expectEqualStrings("", in.getValue());- try std.testing.expect(!in.undo());-}--test "kitty codepoint inserts UTF-8" {- var in = Input.init(std.testing.allocator);- defer in.deinit();- in.handle(.{ .codepoint = 0xe9 });- try std.testing.expectEqualStrings("é", in.getValue());-}diff --git a/TUI/input_batch.zig b/TUI/input_batch.zigdeleted file mode 100644index f8014b58..00000000--- a/TUI/input_batch.zig+++ /dev/null@@ -1,28 +0,0 @@-//! Shared terminal-read decoder/batcher for the live loop and headless composer.-const key = @import("key.zig");-const pacing = @import("pacing.zig");--pub const Decoder = struct {- batch: pacing.Batch = .{},- carried: ?key.Key = null,- done: bool = false,-- pub fn next(self: *Decoder, bytes: []const u8, i: *usize) ?[]const pacing.Item {- if (self.done) return null;- self.batch.reset();- if (self.carried) |k| {- _ = self.batch.push(k);- self.carried = null;- }- while (key.next(bytes, i)) |k| {- pacing.events += 1;- if (pacing.wheelNotch(k) != null) pacing.wheel_events += 1;- if (self.batch.push(k) == .full) {- self.carried = k;- return self.batch.items();- }- }- self.done = true;- return if (self.batch.len > 0) self.batch.items() else null;- }-};diff --git a/TUI/inset.zig b/TUI/inset.zigdeleted file mode 100644index 1d595574..00000000--- a/TUI/inset.zig+++ /dev/null@@ -1,206 +0,0 @@-//! grok-build's default pager inset (xai-org/grok-build `LayoutConfig`).-//!-//! Measured from `crates/codegen/xai-grok-pager-render/src/appearance/config.rs`-//! and the pager.toml docs (`[scrollback.layout]`):-//!-//! outer_vpad = 1 // top/bottom of the scrollback viewport-//! outer_hpad_left = 2 // left gutter (minimum 1)-//! outer_hpad_right = 2 // right gutter (minimum 1)-//! block_pad_left = 2 // inside a block, after the accent rail-//! block_pad_right = 2-//!-//! Compact mode (their `eff_*`): horizontal pad drops to `MIN_HPAD` (1) and-//! vertical pad drops to 0. `/compact-mode` is the same switch here.-//!-//! Presentation only — colours stay in `theme.zig` / `ansi.zig`. No OSC 50.--const std = @import("std");--const app = @import("app.zig");-const Model = app.Model;--/// grok-build `LayoutConfig::outer_hpad_left`.-pub const outer_hpad_left: usize = 2;-/// grok-build `LayoutConfig::outer_hpad_right`.-pub const outer_hpad_right: usize = 2;-/// grok-build `LayoutConfig::outer_vpad`.-pub const outer_vpad: usize = 1;-/// grok-build `LayoutConfig::MIN_HPAD` — compact mode, and the clamp floor.-pub const min_hpad: usize = 1;--pub const Pads = struct {- left: usize,- right: usize,- vpad: usize,- /// Columns the chrome and transcript wrap to (`term - left - right`).- inner: usize,-};--pub fn hpadLeft(compact: bool) usize {- return if (compact) min_hpad else outer_hpad_left;-}--pub fn hpadRight(compact: bool) usize {- return if (compact) min_hpad else outer_hpad_right;-}--pub fn vpad(compact: bool) usize {- return if (compact) 0 else outer_vpad;-}--/// Effective pads for a terminal `width`. Narrow screens drop to `min_hpad`-/// rather than crush the composer below the panel minimum.-pub fn forTerm(width: usize, compact: bool) Pads {- var left = hpadLeft(compact);- var right = hpadRight(compact);- const floor: usize = 24;- if (width < left + right + floor) {- left = @min(left, min_hpad);- right = @min(right, min_hpad);- }- if (width < left + right + 16) {- left = 0;- right = 0;- }- const inner = width -| (left + right);- return .{- .left = left,- .right = right,- .vpad = vpad(compact),- .inner = if (inner == 0) width else inner,- };-}--pub fn of(m: *const Model) Pads {- return forTerm(if (m.last_term_width == 0) 80 else m.last_term_width, m.compact_mode);-}--/// Wrap / layout width — what `layout_cache.ensure` and `indexAtVisual` share.-pub fn wrapWidth(m: *const Model) usize {- return of(m).inner;-}--/// Screen column → content column (drops the left gutter).-pub fn screenToInner(m: *const Model, x: usize) usize {- return x -| of(m).left;-}--/// Prefix every row of `text` with `left` spaces. Trailing newline shape is-/// preserved so `render.zig`'s `countLines` stays honest.-pub fn appendPadded(out: *std.array_list.Managed(u8), text: []const u8, left: usize) !void {- if (text.len == 0) return;- var it = std.mem.splitScalar(u8, text, '\n');- var first = true;- while (it.next()) |ln| {- // A trailing empty segment is the final newline, not a row to pad —- // prefixing it (or emitting an extra `\n` both here and below) grew- // the frame by one and broke the height invariant.- if (ln.len == 0 and it.rest().len == 0) break;- if (!first) try out.append('\n');- first = false;- try out.appendNTimes(' ', left);- try out.appendSlice(ln);- }- if (text[text.len - 1] == '\n') try out.append('\n');-}--test "grok-build default inset is 2 / 2 / 1" {- const p = forTerm(80, false);- try std.testing.expectEqual(@as(usize, 2), p.left);- try std.testing.expectEqual(@as(usize, 2), p.right);- try std.testing.expectEqual(@as(usize, 1), p.vpad);- try std.testing.expectEqual(@as(usize, 76), p.inner);- try std.testing.expectEqual(outer_hpad_left, p.left);- try std.testing.expectEqual(outer_vpad, p.vpad);-}--test "compact mode uses MIN_HPAD and drops outer_vpad" {- const p = forTerm(80, true);- try std.testing.expectEqual(min_hpad, p.left);- try std.testing.expectEqual(min_hpad, p.right);- try std.testing.expectEqual(@as(usize, 0), p.vpad);- try std.testing.expectEqual(@as(usize, 78), p.inner);-}--test "appendPadded prefixes every row and keeps a trailing newline" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- try appendPadded(&out, "ab\ncd\n", 2);- try std.testing.expectEqualStrings(" ab\n cd\n", out.items);-}--fn firstGlyphCol(line: []const u8) usize {- var n: usize = 0;- for (line) |c| {- if (c != ' ') return n;- n += 1;- }- return n;-}--fn rowWith(vis: []const u8, needle: []const u8) ?[]const u8 {- var it = std.mem.splitScalar(u8, vis, '\n');- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, needle) != null) return ln;- }- return null;-}--test "Term screen insets transcript, composer, and footer like grok-build" {- const sim = @import("sim.zig");- var term: sim.Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.assistant, "INSETPROBE unique breathing room");- const vis = try term.screen();- defer std.testing.allocator.free(vis);- const probe = rowWith(vis, "INSETPROBE") orelse return error.NoTranscript;- // Outer gutter plus the unselected row mark: never flush to column 0.- try std.testing.expect(firstGlyphCol(probe) >= outer_hpad_left);- try std.testing.expect(probe.len >= 2 and probe[0] == ' ' and probe[1] == ' ');-- const box = rowWith(vis, "╭") orelse return error.NoComposer;- try std.testing.expectEqual(outer_hpad_left, firstGlyphCol(box));- try std.testing.expect(box[0] == ' ');-- const hints = rowWith(vis, "Enter:send") orelse return error.NoFooter;- try std.testing.expect(firstGlyphCol(hints) >= outer_hpad_left);-- const lay = try term.layout();- defer std.testing.allocator.free(lay);- try std.testing.expect(std.mem.indexOf(u8, lay, "prompt-origin") != null);- // Composer sits above the hint row, not on the last cell of the screen.- try std.testing.expect(term.model.prompt_origin + 1 < 24);- // outer_vpad: the row immediately above the box is blank, not transcript.- const ann = try term.annotated();- defer std.testing.allocator.free(ann);- var prev: []const u8 = "";- var it = std.mem.splitScalar(u8, ann, '\n');- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, "╭") != null) break;- prev = ln;- }- const prev_bar = std.mem.indexOfScalar(u8, prev, '|') orelse return error.NoPrevBar;- try std.testing.expectEqual(firstGlyphCol(prev[prev_bar + 1 ..]), prev[prev_bar + 1 ..].len);-}--test "Term annotated rows carry the left gutter; compact drops vpad" {- const sim = @import("sim.zig");- var term: sim.Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.user, "gutter-check prompt");- const ann = try term.annotated();- defer std.testing.allocator.free(ann);- const line = rowWith(ann, "gutter-check") orelse return error.NoAnnotated;- // " 12| › #1 gutter-check" — the dump prefix is 4 cols, then the gutter.- const bar = std.mem.indexOfScalar(u8, line, '|') orelse return error.NoBar;- try std.testing.expectEqual(@as(u8, ' '), line[bar + 1]);- try std.testing.expectEqual(@as(u8, ' '), line[bar + 2]);-- term.model.compact_mode = true;- const vis = try term.screen();- defer std.testing.allocator.free(vis);- const box = rowWith(vis, "╭") orelse return error.NoComposer;- try std.testing.expectEqual(min_hpad, firstGlyphCol(box));-}diff --git a/TUI/issue_524_tests.zig b/TUI/issue_524_tests.zigdeleted file mode 100644index 62e0b4a9..00000000--- a/TUI/issue_524_tests.zig+++ /dev/null@@ -1,239 +0,0 @@-//! Reachable fullscreen TUI regressions for legacy ESC ESC CSI navigation.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const key = @import("key.zig");-const recover = @import("key_recover.zig");-const stall = @import("run_stall.zig");-const Term = @import("sim.zig").Term;--const Trajectory = enum { idle, live_turn, compact, bash, files };-const trajectories = [_]Trajectory{ .idle, .live_turn, .compact, .bash, .files };--const Fixture = struct {- term: Term,- bg: ?*engine.BgOp = null,-- fn init(trajectory: Trajectory) !Fixture {- var fixture: Fixture = undefined;- fixture.bg = null;- fixture.term.init(std.testing.allocator, 80, 24);- errdefer fixture.term.deinit();- try fixture.term.model.push(.user, "existing turn");- switch (trajectory) {- .idle => {},- .live_turn => {- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- try fixture.term.model.push(.pending, "");- fixture.term.model.pending = job;- },- .compact, .bash, .files => {- const op = try std.testing.allocator.create(engine.BgOp);- op.* = .{ .kind = switch (trajectory) {- .compact => .compact,- .bash => .bash,- .files => .files,- else => unreachable,- }, .gpa = std.testing.allocator, .threaded = false };- try fixture.term.model.push(.pending, "background operation");- fixture.term.model.bg = op;- fixture.bg = op;- },- }- return fixture;- }-- fn deinit(self: *Fixture) void {- if (self.bg) |op| {- self.term.model.bg = null;- std.testing.allocator.destroy(op);- }- if (self.term.model.pending) |job| {- self.term.model.pending = null;- std.testing.allocator.destroy(job);- }- self.term.deinit();- }-};--fn expectAlive(fixture: *Fixture, trajectory: Trajectory) !void {- try std.testing.expect(!fixture.term.model.cancel_requested);- try std.testing.expect(fixture.term.last_effect == .stay);- if (trajectory == .live_turn) try std.testing.expect(fixture.term.model.pending != null);- if (trajectory != .idle and trajectory != .live_turn)- try std.testing.expect(fixture.bg != null and !fixture.bg.?.cancelled);-}--test "legacy Alt CSI decodes to the underlying navigation keys" {- const cases = [_]struct { bytes: []const u8, expected: key.Key }{- .{ .bytes = "\x1b\x1b[D", .expected = .left },- .{ .bytes = "\x1b\x1b[C", .expected = .right },- .{ .bytes = "\x1b\x1b[A", .expected = .up },- .{ .bytes = "\x1b\x1b[1;3A", .expected = .up },- .{ .bytes = "\x1b\x1b[1;3C", .expected = .word_right },- .{ .bytes = "\x1b\x1b[1;3D", .expected = .word_left },- };- key.resetInputState();- defer key.resetInputState();- for (cases) |case| {- var i: usize = 0;- try std.testing.expectEqual(case.expected, key.next(case.bytes, &i).?);- try std.testing.expectEqual(case.bytes.len, i);- try std.testing.expect(key.next(case.bytes, &i) == null);- }-}--test "legacy Alt CSI navigation accepts a coalesced printable key" {- const sequences = [_][]const u8{- "\x1b\x1b[Ax",- "\x1b\x1b[Cx",- "\x1b\x1b[Dx",- "\x1b\x1b[1;3Ax",- "\x1b\x1b[1;3Cx",- "\x1b\x1b[1;3Dx",- };- for (trajectories) |trajectory| for (sequences) |sequence| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.feed(sequence);- try std.testing.expectEqualStrings("x", fixture.term.model.input.getValue());- try expectAlive(&fixture, trajectory);- };-}--test "legacy Alt CSI boundary preserves printable prose on every TUI trajectory" {- const prose = [_]struct { sequence: []const u8, expected: []const u8 }{- .{ .sequence = "\x1b\x1b[Alice]", .expected = "seed:[Alice]" },- .{ .sequence = "\x1b\x1b[1;3Alice]", .expected = "seed:[1;3Alice]" },- };- for (trajectories) |trajectory| for (prose) |case| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed:");- fixture.term.model.scroll = 7;- fixture.term.model.follow = false;- _ = fixture.term.feed(case.sequence);- try std.testing.expectEqualStrings(case.expected, fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 7), fixture.term.model.scroll);- try std.testing.expectEqual(app.Overlay.none, fixture.term.model.overlay);- };-}--test "legacy Alt CSI navigation never emits Escape on any TUI trajectory" {- const sequences = [_][]const u8{- "\x1b\x1b[D",- "\x1b\x1b[C",- "\x1b\x1b[A",- "\x1b\x1b[1;3A",- "\x1b\x1b[1;3C",- "\x1b\x1b[1;3D",- };- for (trajectories) |trajectory| {- for (sequences) |sequence| {- for (0..sequence.len + 1) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.feed(sequence[0..cut]);- _ = fixture.term.feed(sequence[cut..]);- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectAlive(&fixture, trajectory);- }- }- }-}--test "legacy Alt CSI stays safe across the bounded stall window" {- const sequences = [_][]const u8{- "\x1b\x1b[A",- "\x1b\x1b[C",- "\x1b\x1b[D",- "\x1b\x1b[1;3A",- "\x1b\x1b[1;3C",- "\x1b\x1b[1;3D",- };- for (trajectories) |trajectory| for (sequences) |sequence| {- const grace: u8 = if (trajectory == .idle) 12 else stall.live_escape_stalls;- for (0..sequence.len) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.feed(sequence[0..cut]);- for (0..grace - 1) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- _ = fixture.term.feed(sequence[cut..]);- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectAlive(&fixture, trajectory);- }- };-}--test "legacy Alt CSI rejoins after a dropped head and a full read" {- const cases = [_]struct { tail: []const u8, expected: key.Key }{- .{ .tail = "A", .expected = .up },- .{ .tail = "C", .expected = .right },- .{ .tail = "D", .expected = .left },- .{ .tail = "1;3A", .expected = .up },- .{ .tail = "1;3C", .expected = .word_right },- .{ .tail = "1;3D", .expected = .word_left },- };- for (cases) |case| {- key.resetInputState();- key.abandonSequence("\x1b\x1b[", .dropped);- var buf: [16 * 1024]u8 = @splat('x');- @memcpy(buf[0..case.tail.len], case.tail);- const n = key.joinOrphanHead(&buf, buf.len);- var i: usize = 0;- try std.testing.expectEqual(case.expected, key.next(buf[0..n], &i).?);- try std.testing.expectEqual(key.Key{ .char = 'x' }, key.next(buf[0..n], &i).?);- }- key.resetInputState();- key.abandonSequence("\x1b\x1b[", .dropped);- var prose: [16]u8 = @splat(0);- @memcpy(prose[0..6], "Alice]");- try std.testing.expectEqual(@as(?usize, 1), recover.legacyCsiProse("\x1b\x1b[", "Alice]", 9));- const prose_n = key.joinOrphanHead(&prose, 6);- try std.testing.expectEqual(@as(usize, 7), prose_n);- var prose_i: usize = 0;- for ("[Alice]") |expected| try std.testing.expectEqual(key.Key{ .char = expected }, key.next(prose[0..prose_n], &prose_i).?);- try std.testing.expectEqual(prose_n, prose_i);- key.resetInputState();-}--test "legacy Alt CSI survives the runtime dropped-head seam" {- var fixture = try Fixture.init(.live_turn);- defer fixture.deinit();- _ = fixture.term.feed("\x1b\x1b[");- fixture.term.stallDropPending();- _ = fixture.term.feed("1;3D");- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectAlive(&fixture, .live_turn);-}--test "genuine double Escape still arms rewind after legacy Alt ambiguity expires" {- var fixture = try Fixture.init(.idle);- defer fixture.deinit();- _ = fixture.term.feed("\x1b\x1b");- for (0..11) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.escape_pair, fixture.term.stallTimeout());- try std.testing.expectEqual(app.Overlay.rewind, fixture.term.model.overlay);-}--test "legacy Alt CSI does not close a paste or move through an overlay" {- var paste = try Fixture.init(.idle);- defer paste.deinit();- _ = paste.term.feed("\x1b[200~");- _ = paste.term.feed("\x1b\x1b[1;3D");- try std.testing.expect(key.inPaste());- try std.testing.expectEqualStrings("", paste.term.model.input.getValue());- _ = paste.term.feed("\x1b[201~");- try std.testing.expect(!key.inPaste());-- var overlay = try Fixture.init(.idle);- defer overlay.deinit();- overlay.term.model.openOverlay(.palette);- overlay.term.model.overlay_sel = 1;- _ = overlay.term.feed("\x1b\x1b[A");- try std.testing.expectEqual(app.Overlay.palette, overlay.term.model.overlay);- try std.testing.expectEqual(@as(usize, 0), overlay.term.model.overlay_sel);-}diff --git a/TUI/issue_537_reviewer_tests.zig b/TUI/issue_537_reviewer_tests.zigdeleted file mode 100644index 3d054cf7..00000000--- a/TUI/issue_537_reviewer_tests.zig+++ /dev/null@@ -1,593 +0,0 @@-//! Reviewer-W regressions for #537's bounded dropped-head recovery.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const keys = @import("keys.zig");-const pacing = @import("pacing.zig");-const stall = @import("run_stall.zig");-const Term = @import("sim.zig").Term;-const Effect = app.Effect;--const Trajectory = enum { idle, live_turn, compact, bash, files };-const trajectories = [_]Trajectory{ .idle, .live_turn, .compact, .bash, .files };--fn isBackground(trajectory: Trajectory) bool {- return switch (trajectory) {- .compact, .bash, .files => true,- .idle, .live_turn => false,- };-}--fn installPending(term: *Term) !void {- const job = try std.testing.allocator.create(engine.Job);- errdefer std.testing.allocator.destroy(job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- };- try term.model.push(.pending, "");- term.model.pending = job;-}--fn installBackground(term: *Term, kind: engine.BgOp.Kind) !*engine.BgOp {- const op = try std.testing.allocator.create(engine.BgOp);- errdefer std.testing.allocator.destroy(op);- op.* = .{ .kind = kind, .gpa = std.testing.allocator, .threaded = false };- try term.model.push(.pending, "background operation");- term.model.bg = op;- return op;-}--const Fixture = struct {- term: Term,- bg: ?*engine.BgOp = null,-- fn init(trajectory: Trajectory) !Fixture {- var fixture: Fixture = undefined;- fixture.bg = null;- fixture.term.init(std.testing.allocator, 80, 24);- errdefer fixture.term.deinit();- try fixture.term.model.push(.user, "existing turn");- switch (trajectory) {- .idle => {},- .live_turn => try installPending(&fixture.term),- .compact => fixture.bg = try installBackground(&fixture.term, .compact),- .bash => fixture.bg = try installBackground(&fixture.term, .bash),- .files => fixture.bg = try installBackground(&fixture.term, .files),- }- fixture.term.now_ms = 100;- fixture.term.model.now_ms = 100;- return fixture;- }-- fn deinit(self: *Fixture) void {- if (self.bg) |op| {- self.term.model.bg = null;- std.testing.allocator.destroy(op);- }- if (self.term.model.pending) |job| {- self.term.model.pending = null;- std.testing.allocator.destroy(job);- }- self.term.deinit();- }-};--fn expectAlive(fixture: *Fixture, trajectory: Trajectory) !void {- try std.testing.expect(!fixture.term.model.cancel_requested);- if (trajectory == .live_turn) try std.testing.expect(fixture.term.model.pending != null);- if (isBackground(trajectory)) try std.testing.expect(fixture.term.model.bg != null and !fixture.bg.?.cancelled);-}--fn abandonedAt401(head: []const u8, recovery: key_mod.SequenceRecovery, close_paste: bool, fresh: []const u8, buf: []u8) usize {- key_mod.abandonSequence(head, recovery);- if (close_paste) key_mod.endPaste();- // At 401ms the short genuine-Escape carry is gone, but the one-second- // dropped-head recovery interval is still live.- std.debug.assert(stall.escapeCarryExpired(401, 0));- std.debug.assert(!stall.armExpired(401, 0));- key_mod.expireOrphanHead();- @memcpy(buf[0..fresh.len], fresh);- return key_mod.joinOrphanHead(buf, fresh.len);-}--test "every internal paste-marker split reconstructs a real event at 401ms" {- const cases = [_]struct { marker: []const u8, start: bool }{- .{ .marker = "\x1b[200~", .start = true },- .{ .marker = "\x1b[201~", .start = false },- };- for (cases) |case| for (1..case.marker.len) |cut| {- errdefer std.debug.print("marker recovery failure: {s} split {d}\n", .{ case.marker, cut });- key_mod.resetInputState();- if (!case.start) {- var open_i: usize = 0;- try std.testing.expectEqual(key_mod.Key.paste_start, key_mod.next("\x1b[200~", &open_i).?);- }- const ctx: stall.StallCtx = .{ .in_paste = !case.start };- const budget: u8 = if (cut == 1) 12 else if (case.start) 20 else 80;- const verdict: stall.StallVerdict = if (cut == 1) .escape_key else .drop;- try std.testing.expectEqual(stall.StallVerdict.wait, stall.stallVerdict(case.marker[0..cut], budget - 1, ctx));- try std.testing.expectEqual(verdict, stall.stallVerdict(case.marker[0..cut], budget, ctx));-- var fresh: [32]u8 = undefined;- const tail = case.marker[cut..];- @memcpy(fresh[0..tail.len], tail);- fresh[tail.len] = 0x11; // same-read Ctrl-Q: ordering is observable- var joined: [64]u8 = undefined;- const recovery: key_mod.SequenceRecovery = if (cut == 1) .escape else .dropped;- const n = abandonedAt401(case.marker[0..cut], recovery, !case.start, fresh[0 .. tail.len + 1], &joined);- var i: usize = 0;- const marker = key_mod.next(joined[0..n], &i).?;- if (case.start) {- try std.testing.expectEqual(key_mod.Key.paste_start, marker);- try std.testing.expect(key_mod.inPaste());- } else {- try std.testing.expectEqual(key_mod.Key.paste_end, marker);- try std.testing.expect(!key_mod.inPaste());- }- try std.testing.expectEqual(key_mod.Key{ .ctrl = 'q' }, key_mod.next(joined[0..n], &i).?);- try std.testing.expectEqual(n, i);- };- key_mod.resetInputState();-}--test "every dropped paste-start split latches before controls on every trajectory" {- const marker = "\x1b[200~";- const payload = "left\x11\x03\nright";- for (trajectories) |trajectory| for (2..marker.len) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- errdefer std.debug.print("paste-start trajectory failure: {s} split {d}\n", .{ @tagName(trajectory), cut });- try fixture.term.model.input.setValue("seed:");- const history_len = fixture.term.model.history.items.len;- _ = fixture.term.feed(marker[0..cut]);- for (0..19) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.drop, fixture.term.stallTimeout());- fixture.term.now_ms += 401;- var fresh: [64]u8 = undefined;- const tail = marker[cut..];- @memcpy(fresh[0..tail.len], tail);- @memcpy(fresh[tail.len .. tail.len + payload.len], payload);- try std.testing.expectEqual(Effect.stay, fixture.term.feed(fresh[0 .. tail.len + payload.len]));- try std.testing.expect(fixture.term.model.pasting and key_mod.inPaste());- try std.testing.expectEqualStrings("seed:left\nright", fixture.term.model.input.getValue());- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- _ = fixture.term.feed("\x1b[201~");- };-}--const FramedKind = enum { sgr, x10, kitty, osc };--fn expectFramed(kind: FramedKind, k: key_mod.Key) !void {- switch (kind) {- .sgr => {- try std.testing.expect(k == .mouse);- try std.testing.expectEqual(@as(u8, 65), k.mouse.btn);- try std.testing.expectEqual(@as(u16, 20), k.mouse.x);- try std.testing.expectEqual(@as(u16, 10), k.mouse.y);- },- .x10 => {- try std.testing.expect(k == .mouse);- try std.testing.expectEqual(@as(u8, 64), k.mouse.btn);- try std.testing.expectEqual(@as(u16, 4), k.mouse.x);- try std.testing.expectEqual(@as(u16, 4), k.mouse.y);- },- .kitty => try std.testing.expectEqual(key_mod.Key.left, k),- .osc => try std.testing.expect(k == .bg_report),- }-}--test "dropped SGR X10 kitty and OSC retain exact framing at 401ms" {- const cases = [_]struct { bytes: []const u8, kind: FramedKind }{- .{ .bytes = "\x1b[<65;20;10M", .kind = .sgr },- .{ .bytes = "\x1b[M`$$", .kind = .x10 },- .{ .bytes = "\x1b[57350;1u", .kind = .kitty },- .{ .bytes = "\x1b]11;rgb:14/14/14\x07", .kind = .osc },- };- for (cases) |case| for (2..case.bytes.len) |cut| {- key_mod.resetInputState();- try std.testing.expectEqual(stall.StallVerdict.drop, stall.stallVerdict(case.bytes[0..cut], 20, .{}));- var fresh: [128]u8 = undefined;- const tail = case.bytes[cut..];- @memcpy(fresh[0..tail.len], tail);- fresh[tail.len] = 'X';- var joined: [192]u8 = undefined;- const n = abandonedAt401(case.bytes[0..cut], .dropped, false, fresh[0 .. tail.len + 1], &joined);- var i: usize = 0;- try expectFramed(case.kind, key_mod.next(joined[0..n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .char = 'X' }, key_mod.next(joined[0..n], &i).?);- try std.testing.expectEqual(n, i);- };- key_mod.resetInputState();-}--test "every SGR separator split preserves button and coordinate alignment" {- const report = "\x1b[<65;20;10M";- for (report, 0..) |c, at| {- if (c != ';') continue;- for ([_]usize{ at, at + 1 }) |cut| {- key_mod.resetInputState();- var joined: [64]u8 = undefined;- const n = abandonedAt401(report[0..cut], .dropped, false, report[cut..], &joined);- var i: usize = 0;- const k = key_mod.next(joined[0..n], &i).?;- try expectFramed(.sgr, k);- try std.testing.expectEqual(@as(?i32, -1), pacing.wheelNotch(k));- try std.testing.expectEqual(n, i);- }- }- key_mod.resetInputState();-}--test "unaligned mouse tails fail closed instead of fabricating mouse or wheel" {- const tails = [_][]const u8{- "65;20;10M", // may start at button, x, or y- "20;10M",- "10M",- ";10M",- "65;20;10m",- "<65;20M", // field-zero marker, but a missing coordinate- };- for (tails) |tail| {- key_mod.resetInputState();- key_mod.armOrphan(true);- var i: usize = 0;- const k = key_mod.next(tail, &i).?;- try std.testing.expect(k != .mouse);- try std.testing.expectEqual(@as(?i32, null), pacing.wheelNotch(k));- try std.testing.expectEqual(tail.len, i);- }- // With field zero and all three fields proven, recovery remains exact.- key_mod.resetInputState();- key_mod.armOrphan(true);- var i: usize = 0;- const framed = key_mod.next("<65;20;10M", &i).?;- try std.testing.expectEqual(@as(?i32, -1), pacing.wheelNotch(framed));- // Full ESC framing still cannot invent a missing SGR coordinate.- key_mod.resetInputState();- i = 0;- const malformed = key_mod.next("\x1b[<65;20M", &i).?;- try std.testing.expect(malformed != .mouse);- try std.testing.expectEqual(@as(?i32, null), pacing.wheelNotch(malformed));- key_mod.resetInputState();-}--test "a mismatched dropped head disarms before byte-at-a-time prose on every trajectory" {- for (trajectories) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed:");- fixture.term.model.scroll = 7;- fixture.term.model.follow = false;- _ = fixture.term.feed("\x1b[<65;20");- for (0..19) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.drop, fixture.term.stallTimeout());- fixture.term.now_ms += 401;- for ("[Alice]") |c| {- _ = fixture.term.feed(&[_]u8{c});- fixture.term.now_ms += 50;- }- try std.testing.expectEqualStrings("seed:[Alice]", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try std.testing.expectEqual(@as(usize, 7), fixture.term.model.scroll);- try std.testing.expect(!fixture.term.model.follow);- try expectAlive(&fixture, trajectory);- }-}--fn dispatchProductionBatch(m: *app.Model, bytes: []const u8) !Effect {- var batch: pacing.Batch = .{};- var i: usize = 0;- while (key_mod.next(bytes, &i)) |k| try std.testing.expectEqual(pacing.Push.ok, batch.push(k));- // Both reports are consecutive and must reach run.zig as one folded item.- try std.testing.expectEqual(@as(usize, 2), batch.folded);- var wheel_items: usize = 0;- var effect: Effect = .stay;- for (batch.items()) |item| {- if (item == .wheel) {- wheel_items += 1;- try std.testing.expectEqual(@as(i32, 2), item.wheel);- }- effect = keys.handleBatchItem(m, item);- if (effect != .stay) break;- }- try std.testing.expectEqual(@as(usize, 1), wheel_items);- return effect;-}--test "production folded SGR and X10 wheels are paste-aware on every trajectory" {- const reads = [_][]const u8{- "\x1b[200~left\x1b[<64;4;4M\x1b[<64;4;4Mright\x1b[201~",- "\x1b[200~left\x1b[M`$$\x1b[M`$$right\x1b[201~",- };- for (trajectories) |trajectory| for (reads) |bytes| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- fixture.term.model.scroll = 7;- fixture.term.model.follow = false;- fixture.term.model.sel.active = true;- fixture.term.model.sel.pressed = true;- try std.testing.expectEqual(Effect.stay, try dispatchProductionBatch(&fixture.term.model, bytes));- try std.testing.expectEqualStrings("leftright ", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 7), fixture.term.model.scroll);- try std.testing.expect(!fixture.term.model.follow);- try std.testing.expect(fixture.term.model.sel.active and fixture.term.model.sel.pressed);- try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());- try expectAlive(&fixture, trajectory);- };-}--test "every paste marker cut is safe on every runtime trajectory" {- const start = "\x1b[200~";- const end = "\x1b[201~";- for (trajectories) |trajectory| for (1..start.len) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- const history_len = fixture.term.model.history.items.len;- _ = fixture.term.feed(start[0..cut]);- try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- const payload = "left\x11\x03\nright";- var fresh: [32]u8 = undefined;- const tail = start[cut..];- @memcpy(fresh[0..tail.len], tail);- @memcpy(fresh[tail.len .. tail.len + payload.len], payload);- _ = fixture.term.feed(fresh[0 .. tail.len + payload.len]);- try std.testing.expectEqualStrings("left\nright", fixture.term.model.input.getValue());- try std.testing.expect(fixture.term.model.pasting and key_mod.inPaste());- _ = fixture.term.feed(end[0..cut]);- try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- _ = fixture.term.feed(end[cut..]);- try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- };-}--test "dropped paste heads accumulate secondary late reads on every trajectory" {- for (trajectories) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed:");- const history_len = fixture.term.model.history.items.len;-- _ = fixture.term.feed("\x1b[20");- for (0..19) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.drop, fixture.term.stallTimeout());- fixture.term.now_ms += 401;- try std.testing.expectEqual(Effect.stay, fixture.term.feed("0"));- try std.testing.expectEqualStrings("seed:", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);-- try std.testing.expectEqual(Effect.stay, fixture.term.feed("~left\x11\x03\nright"));- try std.testing.expect(fixture.term.model.pasting and key_mod.inPaste());- try std.testing.expectEqualStrings("seed:left\nright", fixture.term.model.input.getValue());- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- _ = fixture.term.feed("\x1b[201~");- }-}--test "every paste marker cut permits a second bounded partial tail" {- const cases = [_]struct { marker: []const u8, start: bool }{- .{ .marker = "\x1b[200~", .start = true },- .{ .marker = "\x1b[201~", .start = false },- };- for (cases) |case| for (2..case.marker.len - 1) |cut| {- const tail = case.marker[cut..];- for (1..tail.len) |second_cut| {- key_mod.resetInputState();- if (!case.start) {- var open_i: usize = 0;- try std.testing.expectEqual(key_mod.Key.paste_start, key_mod.next("\x1b[200~", &open_i).?);- }- key_mod.abandonSequence(case.marker[0..cut], .dropped);- var buf: [64]u8 = undefined;- @memcpy(buf[0..second_cut], tail[0..second_cut]);- try std.testing.expectEqual(@as(usize, 0), key_mod.joinOrphanHead(&buf, second_cut));- const rest = tail[second_cut..];- @memcpy(buf[0..rest.len], rest);- buf[rest.len] = 0x11;- const n = key_mod.joinOrphanHead(&buf, rest.len + 1);- var i: usize = 0;- const expected: key_mod.Key = if (case.start) .paste_start else .paste_end;- try std.testing.expectEqual(expected, key_mod.next(buf[0..n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .ctrl = 'q' }, key_mod.next(buf[0..n], &i).?);- try std.testing.expectEqual(n, i);- }- };- key_mod.resetInputState();-}--test "full input buffer recovers paste start before every payload byte" {- key_mod.resetInputState();- defer key_mod.resetInputState();- key_mod.abandonSequence("\x1b[20", .dropped);- var buf: [16 * 1024]u8 = undefined;- @memset(&buf, 'x');- @memcpy(buf[0..2], "0~");- buf[2] = 0x11;- buf[3] = 0x03;- buf[4] = '\n';- const n = key_mod.joinOrphanHead(&buf, buf.len);- try std.testing.expectEqual(buf.len - 2, n);- var i: usize = 0;- try std.testing.expectEqual(key_mod.Key.paste_start, key_mod.next(buf[0..n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .ctrl = 'q' }, key_mod.next(buf[0..n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .ctrl = 'c' }, key_mod.next(buf[0..n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .char = '\n' }, key_mod.next(buf[0..n], &i).?);- var xs: usize = 0;- while (key_mod.next(buf[0..n], &i)) |k| {- try std.testing.expectEqual(key_mod.Key{ .char = 'x' }, k);- xs += 1;- }- try std.testing.expectEqual(buf.len - 5, xs);- try std.testing.expectEqual(n, i);-}--test "invalid and oversized late tails fail closed and disarm" {- key_mod.resetInputState();- defer key_mod.resetInputState();- key_mod.abandonSequence("\x1b[20", .dropped);- var bad = [_]u8{ 'x', 0x11 };- const bad_n = key_mod.joinOrphanHead(&bad, bad.len);- var i: usize = 0;- try std.testing.expectEqual(key_mod.Key{ .char = 'x' }, key_mod.next(bad[0..bad_n], &i).?);- try std.testing.expectEqual(key_mod.Key{ .ctrl = 'q' }, key_mod.next(bad[0..bad_n], &i).?);- try std.testing.expect(!key_mod.inPaste());-- key_mod.abandonSequence("\x1b[", .dropped);- var oversized: [65]u8 = @splat('2');- try std.testing.expectEqual(oversized.len, key_mod.joinOrphanHead(&oversized, oversized.len));- i = 0;- try std.testing.expectEqual(key_mod.Key{ .char = '2' }, key_mod.next(&oversized, &i).?);- try std.testing.expect(!key_mod.inPaste());-}--test "a possible paste-start ESC cannot cancel live work before one second" {- for (trajectories[1..]) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- const history_len = fixture.term.model.history.items.len;- _ = fixture.term.feed("\x1b");- for (1..stall.live_escape_stalls) |_| {- try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try expectAlive(&fixture, trajectory);- }- try std.testing.expectEqual(Effect.stay, fixture.term.feed("[200~left\x11\x03\nright"));- try std.testing.expectEqualStrings("left\nright", fixture.term.model.input.getValue());- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- _ = fixture.term.feed("\x1b[201~");- }-}--test "live lone Escape is bounded while Ctrl-C and CSI-u Escape stay immediate" {- for (trajectories[1..]) |trajectory| {- var bounded = try Fixture.init(trajectory);- defer bounded.deinit();- _ = bounded.term.feed("\x1b");- for (1..stall.live_escape_stalls) |_| try std.testing.expectEqual(stall.StallVerdict.wait, bounded.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.escape_key, bounded.term.stallTimeout());- if (trajectory == .live_turn) try std.testing.expect(bounded.term.model.cancel_requested);- if (isBackground(trajectory)) try std.testing.expect(bounded.bg.?.cancelled);-- var ctrl_c = try Fixture.init(trajectory);- defer ctrl_c.deinit();- _ = ctrl_c.term.feed("\x03");- if (trajectory == .live_turn) try std.testing.expect(ctrl_c.term.model.cancel_requested);- if (isBackground(trajectory)) try std.testing.expect(ctrl_c.bg.?.cancelled);-- var kitty = try Fixture.init(trajectory);- defer kitty.deinit();- _ = kitty.term.feed("\x1b[27u");- if (trajectory == .live_turn) try std.testing.expect(kitty.term.model.cancel_requested);- if (isBackground(trajectory)) try std.testing.expect(kitty.bg.?.cancelled);- }-}--const FullEventKind = enum { sgr, x10, kitty, osc };-const full_event_cases = [_]struct { head: []const u8, tail: []const u8, kind: FullEventKind }{- .{ .head = "\x1b[<65;20", .tail = ";10M", .kind = .sgr },- .{ .head = "\x1b[M", .tail = "`$$", .kind = .x10 },- .{ .head = "\x1b[57350;", .tail = "1u", .kind = .kitty },- .{ .head = "\x1b]11;rgb:f6", .tail = "/f6/f6\x07", .kind = .osc },-};--test "full reads recover framed events before remaining bytes on every trajectory" {- for (trajectories) |trajectory| for (full_event_cases) |case| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- errdefer std.debug.print("full event failure: {s} / {s}\n", .{ @tagName(trajectory), @tagName(case.kind) });- try fixture.term.model.input.setValue(if (case.kind == .kitty) "ab" else "seed:");- fixture.term.model.scroll = 7;- fixture.term.model.follow = false;- fixture.term.model.theme_explicit = false;- fixture.term.model.theme_id = .night;- const history_len = fixture.term.model.history.items.len;- _ = fixture.term.feed(case.head);- try std.testing.expectEqual(case.head.len, fixture.term.pending);- fixture.term.stallDropPending();-- var full: [16 * 1024]u8 = @splat(0x07);- @memcpy(full[0..case.tail.len], case.tail);- full[full.len - 1] = 'X';- try std.testing.expectEqual(Effect.stay, fixture.term.feed(&full));- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- switch (case.kind) {- .sgr => {- try std.testing.expectEqualStrings("seed:X", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 4), fixture.term.model.scroll);- },- .x10 => {- try std.testing.expectEqualStrings("seed:X", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 10), fixture.term.model.scroll);- },- .kitty => try std.testing.expectEqualStrings("aXb", fixture.term.model.input.getValue()),- .osc => {- try std.testing.expectEqualStrings("seed:X", fixture.term.model.input.getValue());- try std.testing.expectEqual(.day, fixture.term.model.theme_id);- },- }- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- };-}--test "one feed carries a 16KiB paste payload through its later terminator" {- const start = "\x1b[200~";- const end = "\x1b[201~";- const payload: [16 * 1024]u8 = @splat('p');- var wire: [payload.len + start.len + end.len]u8 = undefined;- @memcpy(wire[0..start.len], start);- @memcpy(wire[start.len .. start.len + payload.len], &payload);- @memcpy(wire[start.len + payload.len ..], end);- for (trajectories) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- const history_len = fixture.term.model.history.items.len;- try std.testing.expectEqual(Effect.stay, fixture.term.feed(&wire));- const got = fixture.term.model.input.getValue();- try std.testing.expectEqual(payload.len + 1, got.len);- try std.testing.expectEqualStrings(&payload, got[0..payload.len]);- try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);- try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectAlive(&fixture, trajectory);- }-}--test "feed stops at Ctrl-Q across a 16KiB+1 paste-start/paste-end wire" {- const start = "\x1b[200~";- const end = "\x1b[201~";- const total = 16 * 1024 + 1;- const payload_len = total - start.len - end.len - 2;- var wire: [total]u8 = undefined;- var at: usize = 0;- @memcpy(wire[at .. at + start.len], start);- at += start.len;- @memset(wire[at .. at + payload_len], 'p');- at += payload_len;- @memcpy(wire[at .. at + end.len], end);- at += end.len;- wire[at] = 0x11; // Ctrl-Q: the last byte of the first 16KiB chunk- wire[at + 1] = 'x'; // supplied after the effect; no tty queue exists here-- for (trajectories) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try std.testing.expectEqual(Effect.quit, fixture.term.feed(&wire));- const got = fixture.term.model.input.getValue();- try std.testing.expectEqual(payload_len + 1, got.len);- try std.testing.expectEqualStrings(wire[start.len .. start.len + payload_len], got[0..payload_len]);- try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);- try std.testing.expect(!fixture.term.model.pasting and !key_mod.inPaste());- }-}diff --git a/TUI/issue_537_tests.zig b/TUI/issue_537_tests.zigdeleted file mode 100644index cdb85bae..00000000--- a/TUI/issue_537_tests.zig+++ /dev/null@@ -1,598 +0,0 @@-//! Adversarial bracketed-paste and nested-sequence coverage for #537.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const stall = @import("run_stall.zig");-const theme_mod = @import("theme.zig");-const Term = @import("sim.zig").Term;-const Effect = app.Effect;--const PasteTrajectory = enum { idle, live_turn, background_compact, background_bash, background_files };--const all_trajectories = [_]PasteTrajectory{ .idle, .live_turn, .background_compact, .background_bash, .background_files };--fn isBackground(trajectory: PasteTrajectory) bool {- return switch (trajectory) {- .background_compact, .background_bash, .background_files => true,- .idle, .live_turn => false,- };-}--fn installPending(term: *Term) !void {- const job = try std.testing.allocator.create(engine.Job);- errdefer std.testing.allocator.destroy(job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- };- try term.model.push(.pending, "");- term.model.pending = job;-}--fn installBackground(term: *Term, kind: engine.BgOp.Kind) !*engine.BgOp {- const op = try std.testing.allocator.create(engine.BgOp);- errdefer std.testing.allocator.destroy(op);- op.* = .{ .kind = kind, .gpa = std.testing.allocator, .threaded = false };- try term.model.push(.pending, "background operation");- term.model.bg = op;- return op;-}--const Fixture = struct {- term: Term,- bg: ?*engine.BgOp = null,-- fn init(trajectory: PasteTrajectory) !Fixture {- var fixture: Fixture = undefined;- fixture.bg = null;- fixture.term.init(std.testing.allocator, 80, 24);- errdefer fixture.term.deinit();- try fixture.term.model.push(.user, "existing turn");- switch (trajectory) {- .idle => {},- .live_turn => try installPending(&fixture.term),- .background_compact => fixture.bg = try installBackground(&fixture.term, .compact),- .background_bash => fixture.bg = try installBackground(&fixture.term, .bash),- .background_files => fixture.bg = try installBackground(&fixture.term, .files),- }- fixture.term.model.scroll = 7;- fixture.term.model.follow = false;- fixture.term.model.selected = 3;- fixture.term.now_ms = 100;- fixture.term.model.now_ms = 100;- return fixture;- }-- fn deinit(self: *Fixture) void {- if (self.bg) |op| {- self.term.model.bg = null;- std.testing.allocator.destroy(op);- }- if (self.term.model.pending) |job| {- self.term.model.pending = null;- std.testing.allocator.destroy(job);- }- self.term.deinit();- }-};--fn trajectoryName(trajectory: PasteTrajectory) []const u8 {- return switch (trajectory) {- .idle => "idle",- .live_turn => "live-turn",- .background_compact => "background-compact",- .background_bash => "background-bash",- .background_files => "background-files",- };-}--/// Deliver a genuine Escape through the same 25ms stall policy as run.zig,-/// then advance beyond its 400ms carried-head window but not its 1s exact-tail-/// arm. A live operation uses the full bounded one-second ambiguity window.-fn armCarryExpiredEscape(term: *Term) !void {- _ = term.feed("\x1b");- var verdict: stall.StallVerdict = .wait;- for (0..stall.live_escape_stalls) |_| {- verdict = term.stallTimeout();- if (verdict != .wait) break;- }- try std.testing.expectEqual(stall.StallVerdict.escape_key, verdict);- term.now_ms += 401;-}--fn expectOperationAlive(fixture: *Fixture, trajectory: PasteTrajectory) !void {- try std.testing.expect(!fixture.term.model.cancel_requested);- if (trajectory == .live_turn) try std.testing.expect(fixture.term.model.pending != null);- if (isBackground(trajectory)) try std.testing.expect(fixture.term.model.bg != null and !fixture.bg.?.cancelled);-}--const C0PasteCase = struct {- name: []const u8,- byte: u8,- expected: []const u8,-};--// These are the actual single-byte tty encodings, not synthetic Key values.-// In particular, Ctrl-J is LF and is intentionally retained as paste newline.-const c0_paste_cases = [_]C0PasteCase{- .{ .name = "Ctrl-Q", .byte = 0x11, .expected = "leftright " },- .{ .name = "Ctrl-C", .byte = 0x03, .expected = "leftright " },- .{ .name = "Ctrl-Z", .byte = 0x1a, .expected = "leftright " },- .{ .name = "Ctrl-N", .byte = 0x0e, .expected = "leftright " },- .{ .name = "Ctrl-J", .byte = 0x0a, .expected = "left\nright " },- .{ .name = "Ctrl-K", .byte = 0x0b, .expected = "leftright " },- .{ .name = "Tab", .byte = 0x09, .expected = "leftright " },- .{ .name = "Backspace (DEL)", .byte = 0x7f, .expected = "leftright " },- .{ .name = "Backspace (BS)", .byte = 0x08, .expected = "leftright " },-};--fn pasteInvariantFailure(failures: *usize, trajectory: PasteTrajectory, case: C0PasteCase, what: []const u8) void {- failures.* += 1;- std.debug.print("C0 paste failure [{s} / {s}]: {s}\n", .{ trajectoryName(trajectory), case.name, what });-}--// A bracketed paste is one draft on every TUI path. The raw byte is fed in its-// own read to exercise the runtime parser boundary while idle, during a turn,-// and during a background engine operation.-test "C0 bytes inside bracketed paste stay one draft on every TUI trajectory (#537)" {- var failures: usize = 0;-- for (all_trajectories) |trajectory| {- for (c0_paste_cases) |case| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- const history_len = fixture.term.model.history.items.len;-- _ = fixture.term.feed("\x1b[200~left");- const effect = fixture.term.feed(&[_]u8{case.byte});- if (!fixture.term.model.pasting) pasteInvariantFailure(&failures, trajectory, case, "lost the paste latch before its terminator");- _ = fixture.term.feed("right\x1b[201~");-- const m = &fixture.term.model;- if (effect != .stay) pasteInvariantFailure(&failures, trajectory, case, "returned a non-stay effect");- if (m.quit_requested) pasteInvariantFailure(&failures, trajectory, case, "requested quit");- if (!std.mem.eql(u8, case.expected, m.input.getValue())) pasteInvariantFailure(&failures, trajectory, case, "changed the draft");- if (m.steer_queue.items.len != 0) pasteInvariantFailure(&failures, trajectory, case, "queued a steer");- if (m.history.items.len != history_len) pasteInvariantFailure(&failures, trajectory, case, "created a history entry");- if (m.focus != .prompt) pasteInvariantFailure(&failures, trajectory, case, "moved focus");- if (m.scroll != 7 or m.follow) pasteInvariantFailure(&failures, trajectory, case, "navigated the viewport");- if (m.selected != 3) pasteInvariantFailure(&failures, trajectory, case, "changed the selected turn");- if (m.new_arm_until_ms != 0) pasteInvariantFailure(&failures, trajectory, case, "armed Ctrl-N");- if (m.pasting) pasteInvariantFailure(&failures, trajectory, case, "did not accept the paste terminator");- if (m.cancel_requested) pasteInvariantFailure(&failures, trajectory, case, "cancelled an in-flight turn");- if (trajectory == .live_turn and m.pending == null) pasteInvariantFailure(&failures, trajectory, case, "dropped the live turn");- if (isBackground(trajectory) and (m.bg == null or fixture.bg.?.cancelled)) pasteInvariantFailure(&failures, trajectory, case, "cancelled the background operation");- }- }-- try std.testing.expectEqual(@as(usize, 0), failures);-}--const ParsedPasteCase = struct {- name: []const u8,- bytes: []const u8,- middle: []const u8 = "left",- final: []const u8 = "leftright ",- held: u32 = 0,-};--const parsed_paste_cases = [_]ParsedPasteCase{- .{ .name = "SGR mouse", .bytes = "\x1b[<0;1;1M" },- .{ .name = "X10 mouse", .bytes = "\x1b[M !!" },- .{ .name = "background OSC", .bytes = "\x1b]11;rgb:f6/f6/f6\x07" },- .{ .name = "kitty Super down", .bytes = "\x1b[57444;1:1u" },- .{ .name = "kitty Super release", .bytes = "\x1b[57444;1:3u", .held = 8 },- .{ .name = "kitty modified Backspace", .bytes = "\x1b[127;9u" },- .{ .name = "kitty text", .bytes = "\x1b[97u", .middle = "lefta", .final = "leftaright ", .held = 8 },- .{ .name = "CSI arrow", .bytes = "\x1b[A" },- .{ .name = "CSI Delete", .bytes = "\x1b[3~" },- .{ .name = "SS3 arrow", .bytes = "\x1bOA" },- .{ .name = "truncated CSI before SGR", .bytes = "\x1b[99;\x1b[<35;2;2M" },- .{ .name = "truncated SS3 before SS3", .bytes = "\x1bO\x1bOA" },-};--fn expectParsedPasteSafe(fixture: *Fixture, trajectory: PasteTrajectory, case: ParsedPasteCase, cut: usize) !void {- const m = &fixture.term.model;- errdefer std.debug.print("parsed paste failure [{s} / {s} / split {d}]\n", .{ trajectoryName(trajectory), case.name, cut });-- try std.testing.expectEqual(Effect.stay, fixture.term.feed(case.bytes[0..cut]));- try std.testing.expectEqual(Effect.stay, fixture.term.feed(case.bytes[cut..]));- try std.testing.expect(m.pasting);- try std.testing.expect(key_mod.inPaste());- try std.testing.expectEqualStrings(case.middle, m.input.getValue());- try std.testing.expectEqual(app.Overlay.help, m.overlay);- try std.testing.expect(m.sel.active and m.sel.pressed);- try std.testing.expectEqual(@as(theme_mod.Id, .night), m.theme_id);- try std.testing.expectEqual(case.held, key_mod.held);- try std.testing.expect(!m.cancel_requested);- try std.testing.expect(!m.quit_requested);- try std.testing.expectEqual(@as(usize, 0), m.steer_queue.items.len);- if (trajectory == .live_turn) try std.testing.expect(m.pending != null);- if (isBackground(trajectory)) try std.testing.expect(m.bg != null and !fixture.bg.?.cancelled);-}--// Complete controls and every possible read split have identical inert-// semantics inside a paste. Kitty text remains text, while mouse/background,-// modifier, CSI, and SS3 events cannot reach TUI actions or parser latches.-test "parsed controls inside paste are inert at every split on every TUI trajectory (#537)" {- for (all_trajectories) |trajectory| {- for (parsed_paste_cases) |case| {- var cut: usize = 0;- while (cut <= case.bytes.len) : (cut += 1) {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.feed("\x1b[200~left");- fixture.term.model.overlay = .help;- fixture.term.model.sel.active = true;- fixture.term.model.sel.pressed = true;- fixture.term.model.theme_id = .night;- key_mod.held = case.held;-- try expectParsedPasteSafe(&fixture, trajectory, case, cut);- _ = fixture.term.feed("right\x1b[201~");- try std.testing.expectEqualStrings(case.final, fixture.term.model.input.getValue());- try std.testing.expect(!fixture.term.model.pasting);- try std.testing.expect(!key_mod.inPaste());- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- }- }- }-}--test "Escape remains the intentional bracketed paste hatch (#536/#548)" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- key_mod.held = 8;- _ = term.feed("\x1b[200~draft");- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- key_mod.held = 8;- _ = term.press(.escape);- try std.testing.expect(!term.model.pasting);- try std.testing.expect(!key_mod.inPaste());- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- try std.testing.expectEqualStrings("draft ", term.model.input.getValue());- // Once Escape intentionally closes the paste, a subsequent Ctrl-Q is an- // ordinary key again; the hatch is not a permanent suppression switch.- try std.testing.expectEqual(Effect.quit, term.feed("\x11"));-}--const ParserLoop = struct {- inbuf: [256]u8 = undefined,- pending: usize = 0,- typed: std.array_list.Managed(u8),- mice: usize = 0,- arrows: usize = 0,-- fn init() ParserLoop {- key_mod.resetInputState();- return .{ .typed = std.array_list.Managed(u8).init(std.testing.allocator) };- }-- fn deinit(self: *ParserLoop) void {- self.typed.deinit();- key_mod.resetInputState();- }-- fn read(self: *ParserLoop, bytes: []const u8) !void {- @memcpy(self.inbuf[self.pending .. self.pending + bytes.len], bytes);- var i: usize = 0;- const n = self.pending + bytes.len;- while (key_mod.next(self.inbuf[0..n], &i)) |k| switch (k) {- .char => |c| try self.typed.append(c),- .mouse => self.mice += 1,- .left, .right, .up, .down => self.arrows += 1,- else => {},- };- self.pending = if (i < n) blk: {- const rest = n - i;- std.mem.copyForwards(u8, self.inbuf[0..rest], self.inbuf[i..n]);- break :blk rest;- } else 0;- }-};--const EmbeddedEscapeCase = struct {- name: []const u8,- bytes: []const u8,- mice: usize = 0,- arrows: usize = 0,-};--const embedded_escape_cases = [_]EmbeddedEscapeCase{- .{ .name = "CSI then SGR", .bytes = "left\x1b[99;\x1b[<35;2;2Mright", .mice = 1 },- .{ .name = "X10 then CSI", .bytes = "left\x1b[M \x1b[Aright", .arrows = 1 },- .{ .name = "CSI then CSI", .bytes = "left\x1b[99;\x1b[Aright", .arrows = 1 },- .{ .name = "SS3 then SS3", .bytes = "left\x1bO\x1bOAright", .arrows = 1 },- .{ .name = "SS3 then CSI", .bytes = "left\x1bO\x1b[Aright", .arrows = 1 },-};--// An ESC embedded in a truncated CSI/SS3 is a new event head. Only the old-// prefix is discarded; the new event is reparsed and its body never becomes-// composer text, regardless of the tty read boundary.-test "50-250ms ESC splits preserve state on every TUI trajectory (#537)" {- const protected = [_]struct { tail: []const u8, ticks: usize }{- .{ .tail = "[A", .ticks = 2 }, // exact CSI at about 50ms- .{ .tail = "OA", .ticks = 10 }, // exact SS3 at about 250ms- .{ .tail = "[57350;1u", .ticks = 10 }, // parameterized kitty- };- // Pre-arm two-Escape clear: a phantom Escape would visibly erase the draft.- for (all_trajectories) |trajectory| for (protected) |case| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("draft survives");- _ = fixture.term.press(.escape);- _ = fixture.term.feed("\x1b");- for (0..case.ticks) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- _ = fixture.term.feed(case.tail);- try std.testing.expectEqualStrings("draft survives", fixture.term.model.input.getValue());- try expectOperationAlive(&fixture, trajectory);- };-- // The ambiguity remains bounded: an actual idle Escape lands on poll 12.- var idle = try Fixture.init(.idle);- defer idle.deinit();- try idle.term.model.input.setValue("clear me");- _ = idle.term.press(.escape);- _ = idle.term.feed("\x1b");- for (0..11) |_| try std.testing.expectEqual(stall.StallVerdict.wait, idle.term.stallTimeout());- try std.testing.expectEqual(stall.StallVerdict.escape_key, idle.term.stallTimeout());- try std.testing.expectEqualStrings("", idle.term.model.input.getValue());-}--const x10_report = "\x1b[M !!";--// X10's final-looking `M` is only the introducer for three payload bytes. Every-// read boundary and every reported 50–250ms delay must retain that whole body.-test "X10 mouse survives every split on every TUI trajectory and in paste (#537)" {- const stalls = [_]usize{ 2, 4, 6, 8, 10 };- for (all_trajectories) |trajectory| {- for ([_]bool{ false, true }) |pasting| {- for (stalls) |ticks| {- for (0..x10_report.len + 1) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- errdefer std.debug.print("X10 failure [{s} / paste={} / split {d} / stalls {d}]\n", .{ trajectoryName(trajectory), pasting, cut, ticks });- if (pasting) {- _ = fixture.term.feed("\x1b[200~left");- } else if (trajectory == .idle) {- try fixture.term.model.input.setValue("draft survives");- _ = fixture.term.press(.escape); // a phantom Escape would clear it- }- try std.testing.expectEqual(Effect.stay, fixture.term.feed(x10_report[0..cut]));- for (0..ticks) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(Effect.stay, fixture.term.feed(x10_report[cut..]));- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- if (pasting) {- try std.testing.expect(key_mod.inPaste() and fixture.term.model.pasting);- try std.testing.expectEqualStrings("left", fixture.term.model.input.getValue());- _ = fixture.term.feed("right\x1b[201~");- try std.testing.expectEqualStrings("leftright ", fixture.term.model.input.getValue());- } else if (trajectory == .idle) {- try std.testing.expectEqualStrings("draft survives", fixture.term.model.input.getValue());- } else try std.testing.expectEqualStrings("", fixture.term.model.input.getValue());- try expectOperationAlive(&fixture, trajectory);- }- }- }- }-}--test "carry-expired mouse bodies recover at every split on every trajectory (#537)" {- const bodies = [_][]const u8{ x10_report[1..], "[<35;80;24M" };- for (all_trajectories) |trajectory| for (bodies) |body| for (0..body.len + 1) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed");- try armCarryExpiredEscape(&fixture.term);- _ = fixture.term.feed(body[0..cut]);- _ = fixture.term.feed(body[cut..]);- errdefer std.debug.print("late mouse failure [{s} / split {d}]\n", .{ trajectoryName(trajectory), cut });- try std.testing.expectEqualStrings("seed", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectOperationAlive(&fixture, trajectory);- };-}--test "an ESC inside X10 payload reparses a paste terminator at every split (#537)" {- const broken = "\x1b[M \x1b[201~";- for (all_trajectories) |trajectory| for (0..broken.len + 1) |cut| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.feed("\x1b[200~left");- try std.testing.expectEqual(Effect.stay, fixture.term.feed(broken[0..cut]));- for (0..10) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- try std.testing.expectEqual(Effect.stay, fixture.term.feed(broken[cut..]));- errdefer std.debug.print("X10 paste terminator failure [{s} / split {d}]\n", .{ trajectoryName(trajectory), cut });- try std.testing.expect(!key_mod.inPaste() and !fixture.term.model.pasting);- try std.testing.expectEqualStrings("left ", fixture.term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectOperationAlive(&fixture, trajectory);- };-}--test "live state is latched at the ESC head across fast completion (#537)" {- for (all_trajectories[1..]) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("draft survives");- _ = fixture.term.press(.escape);- _ = fixture.term.feed("\x1b");-- // The worker finishes before the first quiet tick. Restore the owned- // fixture pointers only for teardown; policy must use the arrival-time- // latch rather than these now-idle model fields.- const pending = fixture.term.model.pending;- const bg = fixture.term.model.bg;- fixture.term.model.pending = null;- fixture.term.model.bg = null;- defer {- fixture.term.model.pending = pending;- fixture.term.model.bg = bg;- }- for (0..12) |_| try std.testing.expectEqual(stall.StallVerdict.wait, fixture.term.stallTimeout());- _ = fixture.term.feed("[A");- try std.testing.expectEqualStrings("draft survives", fixture.term.model.input.getValue());- if (fixture.bg) |op| try std.testing.expect(!op.cancelled);- }-}--test "carry-expired paste start latches parser and model before same-read controls (#537)" {- for (all_trajectories) |trajectory| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed:");- const history_len = fixture.term.model.history.items.len;- try armCarryExpiredEscape(&fixture.term);-- const effect = fixture.term.feed("[200~left\x11\x03\nright");- errdefer std.debug.print("late paste failure [{s}]\n", .{trajectoryName(trajectory)});- try std.testing.expectEqual(Effect.stay, effect);- try std.testing.expect(key_mod.inPaste());- try std.testing.expect(fixture.term.model.pasting);- try std.testing.expectEqualStrings("seed:left\nright", fixture.term.model.input.getValue());- try std.testing.expect(!fixture.term.model.quit_requested);- try std.testing.expectEqual(history_len, fixture.term.model.history.items.len);- try expectOperationAlive(&fixture, trajectory);-- _ = fixture.term.feed("\x1b[201~");- try std.testing.expect(!key_mod.inPaste());- try std.testing.expect(!fixture.term.model.pasting);- }-}--test "carry-expired exact tails stay text while kitty and OSC remain events (#537)" {- const exact = [_]struct { tail: []const u8, expected: []const u8 }{- .{ .tail = "[D", .expected = "ab[D" },- .{ .tail = "OD", .expected = "abOD" },- };- for (all_trajectories) |trajectory| {- for (exact) |case| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("ab");- try armCarryExpiredEscape(&fixture.term);- _ = fixture.term.feed(case.tail);- try std.testing.expectEqualStrings(case.expected, fixture.term.model.input.getValue());- try expectOperationAlive(&fixture, trajectory);- }- var kitty = try Fixture.init(trajectory);- defer kitty.deinit();- try kitty.term.model.input.setValue("ab");- try armCarryExpiredEscape(&kitty.term);- _ = kitty.term.feed("[57350;1uX");- try std.testing.expectEqualStrings("aXb", kitty.term.model.input.getValue());- try expectOperationAlive(&kitty, trajectory);-- var osc = try Fixture.init(trajectory);- defer osc.deinit();- try osc.term.model.input.setValue("osc:");- osc.term.model.theme_explicit = false;- osc.term.model.theme_id = .night;- try armCarryExpiredEscape(&osc.term);- _ = osc.term.feed("]11;rgb:f6/f6/f6\x07X");- try std.testing.expectEqualStrings("osc:X", osc.term.model.input.getValue());- try std.testing.expectEqual(theme_mod.Id.day, osc.term.model.theme_id);- try expectOperationAlive(&osc, trajectory);- }-}--test "50ms byte-read human text survives carry-expired Escape on every trajectory (#537)" {- const human = [_][]const u8{ "[Alice]", "[Home]", "[Down]", "3u apples", "[3~ apples" };- for (all_trajectories) |trajectory| for (human) |text| {- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- try fixture.term.model.input.setValue("seed:");- try armCarryExpiredEscape(&fixture.term);- for (text) |c| {- _ = fixture.term.feed(&[_]u8{c});- fixture.term.now_ms += 50;- }- const value = fixture.term.model.input.getValue();- errdefer std.debug.print("human text failure [{s} / {s}]: {s}\n", .{ trajectoryName(trajectory), text, value });- try std.testing.expect(std.mem.startsWith(u8, value, "seed:"));- try std.testing.expectEqualStrings(text, value["seed:".len..]);- try std.testing.expectEqual(@as(usize, 0), fixture.term.pending);- try expectOperationAlive(&fixture, trajectory);- };-}--test "abandoned kitty releases clear Super before a bare DEL (#537)" {- const super_down = "\x1b[57444;1:1u";- {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("draft");- _ = term.feed(super_down);- try std.testing.expectEqual(@as(u32, 8), key_mod.held);- // The release lost its final `u`; a new ESC replaces that truncated- // sequence and must also clear the modifier it can no longer release.- _ = term.feed("\x1b[57444;1:3\x1b[A");- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- _ = term.feed("\x7f");- try std.testing.expectEqualStrings("draf", term.model.input.getValue());- }- {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("draft");- _ = term.feed(super_down);- var wedge: [16 * 1024]u8 = undefined;- const lost_release = "\x1b[57444;1:3";- @memcpy(wedge[0..lost_release.len], lost_release);- @memset(wedge[lost_release.len..], '1');- _ = term.feed(&wedge);- try std.testing.expectEqual(wedge.len, term.pending);- try std.testing.expectEqual(@as(u32, 8), key_mod.held);- // The next read abandons the full production-sized pending wedge, but- // keeps scoped orphan recovery alive while DEL reparses as Backspace.- _ = term.feed("\x7f");- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- try std.testing.expectEqual(@as(usize, 0), term.pending);- try std.testing.expectEqualStrings("draf", term.model.input.getValue());- }- {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.feed("\x1b[200~left");- var wedge: [16 * 1024]u8 = undefined;- @memcpy(wedge[0..2], "\x1b[");- @memset(wedge[2..], '1');- _ = term.feed(&wedge);- key_mod.held = 8;- // Full-wedge cleanup is scoped: Ctrl-Q stays inert inside the paste,- // and the real terminator still owns both parser and model teardown.- try std.testing.expectEqual(Effect.stay, term.feed("\x11"));- try std.testing.expect(key_mod.inPaste() and term.model.pasting);- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- _ = term.feed("\x1b[201~");- try std.testing.expect(!key_mod.inPaste() and !term.model.pasting);- try std.testing.expectEqualStrings("left ", term.model.input.getValue());- }-}--test "CSI and SS3 reparse embedded Escape at every split (#537)" {- for (embedded_escape_cases) |case| {- var cut: usize = 0;- while (cut <= case.bytes.len) : (cut += 1) {- var loop = ParserLoop.init();- defer loop.deinit();- errdefer std.debug.print("embedded Escape failure [{s} / split {d}]\n", .{ case.name, cut });- try loop.read(case.bytes[0..cut]);- try loop.read(case.bytes[cut..]);- try std.testing.expectEqualStrings("leftright", loop.typed.items);- try std.testing.expectEqual(case.mice, loop.mice);- try std.testing.expectEqual(case.arrows, loop.arrows);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }- }-}diff --git a/TUI/issue_737_tests.zig b/TUI/issue_737_tests.zigdeleted file mode 100644index d9bf654c..00000000--- a/TUI/issue_737_tests.zig+++ /dev/null@@ -1,121 +0,0 @@-//! #737: no emulator, model calls or terminal spawn. Real read/batch seam.-const std = @import("std");-const sim = @import("sim.zig");-const engine = @import("engine.zig");-const key = @import("key.zig");--fn draft(term: *sim.Term, expected: []const u8, history_len: usize) !void {- const got = term.model.input.getValue();- if (expected.len > 0 and !std.ascii.isWhitespace(expected[expected.len - 1])) {- try std.testing.expectEqual(expected.len + 1, got.len);- try std.testing.expectEqualStrings(expected, got[0..expected.len]);- try std.testing.expectEqual(@as(u8, ' '), got[got.len - 1]);- } else try std.testing.expectEqualStrings(expected, got);- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expectEqual(history_len, term.model.history.items.len);- try std.testing.expect(term.model.pending != null);- try std.testing.expect(!term.model.cancel_requested);- try std.testing.expect(!term.model.quit_requested);-}--test "#737 long bracketed single/LF/CRLF paste across reads and batches stays unsent until Enter" {- const a = std.testing.allocator;- for ([_][]const u8{ "", "\n", "\r\n" }) |ending| {- // Includes one-byte reads (every marker and CRLF split), batch-cap- // boundaries, and actual 16KiB read boundaries. Each payload >32KiB.- for ([_]usize{ 1, 63, 64, 65, 16384 }) |chunk| {- var term: sim.Term = undefined;- term.init(a, 80, 24);- defer term.deinit();- const job = try a.create(engine.Job);- job.* = .{ .gpa = a, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- term.model.pending = job;- defer {- term.model.pending = null;- a.destroy(job);- }- try term.model.push(.pending, "active turn");- const history_len = term.model.history.items.len;- var payload: std.ArrayList(u8) = .empty;- defer payload.deinit(a);- var expected: std.ArrayList(u8) = .empty;- defer expected.deinit(a);- const paragraph: [1023]u8 = @splat('p');- for (0..33) |p| {- if (p != 0) {- try payload.appendSlice(a, ending);- try expected.appendSlice(a, ending);- }- try payload.appendSlice(a, ¶graph);- try expected.appendSlice(a, ¶graph);- }- var wire: std.ArrayList(u8) = .empty;- defer wire.deinit(a);- try wire.appendSlice(a, "\x1b[200~");- try wire.appendSlice(a, payload.items);- try wire.appendSlice(a, "\x1b[201~");- var offset: usize = 0;- while (offset < wire.items.len) {- const end = @min(offset + chunk, wire.items.len);- try std.testing.expectEqual(.stay, term.feed(wire.items[offset..end]));- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expectEqual(history_len, term.model.history.items.len);- try std.testing.expect(!term.model.cancel_requested);- offset = end;- }- try draft(&term, expected.items, history_len);- try std.testing.expect(!term.model.pasting and !key.inPaste());- // No synthetic delay: explicit termination must retire burst carry.- _ = term.feed("\r");- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- try std.testing.expectEqualStrings(expected.items, term.model.steer_queue.items[0]);- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expect(!term.model.cancel_requested);- }- }-}--test "#737 Enter coalesced with bracketed terminator submits once, not a paste newline" {- const a = std.testing.allocator;- var term: sim.Term = undefined;- term.init(a, 80, 24);- defer term.deinit();- const job = try a.create(engine.Job);- job.* = .{ .gpa = a, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- term.model.pending = job;- defer {- term.model.pending = null;- a.destroy(job);- }- try term.model.push(.pending, "active turn");- // Includes embedded LF in the SAME read as the explicit Enter, so the- // per-read heuristic must not reclassify that key after CSI 201~.- _ = term.feed("\x1b[200~first\nsecond\x1b[201~\r");- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- try std.testing.expectEqualStrings("first\nsecond", term.model.steer_queue.items[0]);- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expect(!term.model.cancel_requested);-}--test "#737 delayed paste_end dispatch cannot reset a subsequent decoded paste" {- const a = std.testing.allocator;- var term: sim.Term = undefined;- term.init(a, 80, 24);- defer term.deinit();- const job = try a.create(engine.Job);- job.* = .{ .gpa = a, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- term.model.pending = job;- defer {- term.model.pending = null;- a.destroy(job);- }- try term.model.push(.pending, "active turn");- _ = term.feed("\x1b[200~first\x1b[201~\x1b[200~second");- _ = term.feed("\r");- _ = term.feed("\nthird\x1b[201~");- const got = term.model.input.getValue();- try std.testing.expect(std.mem.startsWith(u8, got, "first second"));- try std.testing.expect(std.mem.endsWith(u8, got, "third "));- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);-}diff --git a/TUI/issue_788_tests.zig b/TUI/issue_788_tests.zigdeleted file mode 100644index 34afecb5..00000000--- a/TUI/issue_788_tests.zig+++ /dev/null@@ -1,122 +0,0 @@-//! Regression coverage for issue 788: wrapped composer URLs keep one safe OSC 8-//! target without leaking hyperlink state into row padding, borders, or footer.--const std = @import("std");-const render_mod = @import("render.zig");-const sim = @import("sim.zig");-const theme = @import("theme.zig");--const open_prefix = "\x1b]8;id=graff-composer-";-const close = "\x1b]8;;\x07";--fn expectTargetRows(a: std.mem.Allocator, frame: []const u8, target: []const u8, minimum: usize) !usize {- const target_end = try std.fmt.allocPrint(a, ";{s}\x07", .{target});- defer a.free(target_end);- var count: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |row| {- const opens = std.mem.count(u8, row, open_prefix);- const closes = std.mem.count(u8, row, close);- if (opens == 0) {- try std.testing.expectEqual(@as(usize, 0), closes);- continue;- }- const target_at = std.mem.indexOf(u8, row, target_end) orelse return error.WrongLinkTarget;- count += 1;- const open_at = std.mem.lastIndexOf(u8, row[0 .. target_at + 1], open_prefix) orelse return error.MissingLinkOpen;- const linked_at = target_at + target_end.len;- const close_at = std.mem.indexOfPos(u8, row, linked_at, close) orelse return error.MissingLinkClose;- const border_at = std.mem.lastIndexOf(u8, row, "│") orelse return error.MissingComposerBorder;- try std.testing.expect(open_at < target_at);- try std.testing.expect(theme.visibleLen(row[linked_at..close_at]) > 0);- try std.testing.expect(close_at < border_at);- try std.testing.expectEqual(opens, closes);- }- try std.testing.expect(count >= minimum);- return count;-}--fn renderTerm(term: *sim.Term) ![]const u8 {- return render_mod.render(&term.model, term.alloc, term.cols, term.rows, term.now_ms);-}--test "headless composer preserves wrapped http https and www targets" {- const cases = [_]struct { visible: []const u8, target: []const u8 }{- .{- .visible = "http://example.test/one/two/three/four/five/six/seven/eight/nine",- .target = "http://example.test/one/two/three/four/five/six/seven/eight/nine",- },- .{- .visible = "https://example.test/one/two/three/four/five/six/seven/eight/nine",- .target = "https://example.test/one/two/three/four/five/six/seven/eight/nine",- },- .{- .visible = "www.example.test/one/two/three/four/five/six/seven/eight/nine",- .target = "https://www.example.test/one/two/three/four/five/six/seven/eight/nine",- },- };- for (cases) |case| {- var term: sim.Term = undefined;- term.init(std.testing.allocator, 40, 24);- defer term.deinit();- _ = term.typeText(case.visible);- const narrow = try renderTerm(&term);- defer std.testing.allocator.free(narrow);- _ = try expectTargetRows(std.testing.allocator, narrow, case.target, 2);-- term.cols = 57;- const resized = try renderTerm(&term);- defer std.testing.allocator.free(resized);- _ = try expectTargetRows(std.testing.allocator, resized, case.target, 2);- }-}--test "headless composer starts a truncated eight-row link window balanced" {- const target = "https://example.test/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";- var term: sim.Term = undefined;- term.init(std.testing.allocator, 40, 24);- defer term.deinit();- _ = term.typeText(target);- const frame = try renderTerm(&term);- defer std.testing.allocator.free(frame);- const rows = try expectTargetRows(std.testing.allocator, frame, target, 8);- try std.testing.expectEqual(@as(usize, 8), rows);-}--test "headless composer edits non-ASCII links only at scalar boundaries" {- const original = "https://example.test/é";- var term: sim.Term = undefined;- term.init(std.testing.allocator, 40, 24);- defer term.deinit();- _ = term.typeText(original);- _ = term.press(.left);- _ = term.typeText("x");- try std.testing.expectEqualStrings("https://example.test/xé", term.model.input.getValue());- const frame = try renderTerm(&term);- defer std.testing.allocator.free(frame);- _ = try expectTargetRows(std.testing.allocator, frame, "https://example.test/xé", 1);-}--test "headless composer does not emit links for unsafe or embedded forms" {- const cases = [_][]const u8{- "javascript:alert(1)",- "data:text/html,hello",- "file:///tmp/a",- "mailto:[email protected]",- "ssh://example.test/path",- "javascript:https://example.test/path",- "[email protected]/path",- "https://a.-b.example/path",- "https://[:::]/path",- "www.example.test:bad/path",- };- for (cases) |value| {- var term: sim.Term = undefined;- term.init(std.testing.allocator, 40, 24);- defer term.deinit();- _ = term.typeText(value);- const frame = try renderTerm(&term);- defer std.testing.allocator.free(frame);- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, frame, open_prefix));- }-}diff --git a/TUI/issue_789_tests.zig b/TUI/issue_789_tests.zigdeleted file mode 100644index f2987608..00000000--- a/TUI/issue_789_tests.zig+++ /dev/null@@ -1,101 +0,0 @@-//! Fullscreen TUI constraint review and runtime-trajectory coverage for #789.--const std = @import("std");--const engine = @import("engine.zig");-const Term = @import("sim.zig").Term;--var callback_calls: usize = 0;--fn constraintCallback(_: ?*anyopaque, gpa: std.mem.Allocator, line: []const u8) ?[]const u8 {- callback_calls += 1;- return std.fmt.allocPrint(gpa, "scope=project · origin=user:1\n{s}\nundo with /never rm <unique text>\n", .{line}) catch null;-}--const Trajectory = enum { idle, live_turn, background_compact, background_bash, background_files };-const trajectories = [_]Trajectory{ .idle, .live_turn, .background_compact, .background_bash, .background_files };--const Fixture = struct {- term: Term,- bg: ?*engine.BgOp = null,-- fn init(trajectory: Trajectory) !Fixture {- var fixture: Fixture = undefined;- fixture.bg = null;- fixture.term.init(std.testing.allocator, 80, 24);- errdefer fixture.term.deinit();- switch (trajectory) {- .idle => {},- .live_turn => {- const job = try std.testing.allocator.create(engine.Job);- job.* = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- fixture.term.model.pending = job;- },- .background_compact, .background_bash, .background_files => {- const kind: engine.BgOp.Kind = switch (trajectory) {- .background_compact => .compact,- .background_bash => .bash,- .background_files => .files,- else => unreachable,- };- const op = try std.testing.allocator.create(engine.BgOp);- op.* = .{ .kind = kind, .gpa = std.testing.allocator, .threaded = false };- fixture.term.model.bg = op;- fixture.bg = op;- },- }- return fixture;- }-- fn deinit(self: *Fixture) void {- if (self.term.model.pending) |job| {- self.term.model.pending = null;- std.testing.allocator.destroy(job);- }- if (self.bg) |op| {- self.term.model.bg = null;- std.testing.allocator.destroy(op);- }- self.term.deinit();- }-};--test "#789 fullscreen TUI exposes visible constraint review and text removal" {- engine.g_constraint_fn = constraintCallback;- defer engine.g_constraint_fn = null;- callback_calls = 0;-- var fixture = try Fixture.init(.idle);- defer fixture.deinit();- _ = fixture.term.typeText("/constraint rm navigation dots");- const effect = fixture.term.enter();- try std.testing.expectEqual(@import("app.zig").Effect.stay, effect);- try std.testing.expectEqual(@as(usize, 1), callback_calls);- try std.testing.expect(fixture.term.model.running);- try std.testing.expect(!fixture.term.model.quit_requested);- const screen = try fixture.term.screen();- defer std.testing.allocator.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, "scope=project") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "origin=user:1") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "unique text") != null);-}--test "#789 constraint commands never disrupt live TUI trajectories" {- engine.g_constraint_fn = constraintCallback;- defer engine.g_constraint_fn = null;-- for (trajectories[1..]) |trajectory| {- callback_calls = 0;- var fixture = try Fixture.init(trajectory);- defer fixture.deinit();- _ = fixture.term.typeText("/never rm navigation dots");- const effect = fixture.term.enter();- try std.testing.expectEqual(@import("app.zig").Effect.stay, effect);- try std.testing.expectEqual(@as(usize, 0), callback_calls);- try std.testing.expect(fixture.term.model.running);- try std.testing.expect(!fixture.term.model.quit_requested);- try std.testing.expect(!fixture.term.model.cancel_requested);- if (trajectory == .live_turn) try std.testing.expect(fixture.term.model.pending != null);- if (fixture.bg) |op| try std.testing.expect(fixture.term.model.bg == op and !op.cancelled);- }-}diff --git a/TUI/issue_792_tests.zig b/TUI/issue_792_tests.zigdeleted file mode 100644index cfbfd8a5..00000000--- a/TUI/issue_792_tests.zig+++ /dev/null@@ -1,246 +0,0 @@-//! #792: pasted items need separators and paste-origin file paths need identity.--const std = @import("std");-const Term = @import("sim.zig").Term;--fn paste(term: *Term, text: []const u8) void {- _ = term.feed("\x1b[200~");- _ = term.feed(text);- _ = term.feed("\x1b[201~");-}--fn writeTmp(tmp: anytype, name: []const u8, buf: []u8) ![]const u8 {- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "file" });- const n = try tmp.dir.realPath(io, buf);- if (n + 1 + name.len > buf.len) return error.NameTooLong;- buf[n] = '/';- @memcpy(buf[n + 1 ..][0..name.len], name);- return buf[0 .. n + 1 + name.len];-}--test "#792 bracketed text paste leaves one trailing separator" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, "hello");- try std.testing.expectEqualStrings("hello ", term.model.input.getValue());-}--test "#792 existing trailing whitespace is not duplicated" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, "hello ");- try std.testing.expectEqualStrings("hello ", term.model.input.getValue());-}--test "#792 consecutive pasted or dropped file paths stay separated" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var one_buf: [std.fs.max_path_bytes]u8 = undefined;- var two_buf: [std.fs.max_path_bytes]u8 = undefined;- const one = try writeTmp(&tmp, "one file.txt", &one_buf);- const two = try writeTmp(&tmp, "two file.txt", &two_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, one);- paste(&term, two);- const expected = try std.fmt.allocPrint(std.testing.allocator, "{s} {s} ", .{ one, two });- defer std.testing.allocator.free(expected);- try std.testing.expectEqualStrings(expected, term.model.input.getValue());-}--test "#792 backspace removes a paste-origin file path as one item" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "one file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, path);- _ = term.feed("\x7f"); // remove the separator- _ = term.feed("\x7f"); // remove the pasted path as one item- try std.testing.expectEqualStrings("", term.model.input.getValue());-}--test "#792 delete removes a paste-origin file path at its leading edge" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "one file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, path);- _ = term.feed("\x1b[H"); // home- _ = term.feed("\x1b[3~"); // delete at the span's leading edge- try std.testing.expectEqualStrings(" ", term.model.input.getValue());-}--test "#792 word movement skips a paste-origin file path" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "one file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, path);- _ = term.feed("\x1bb"); // word-left from after the separator- try std.testing.expectEqual(@as(usize, 0), term.model.input.cursor);-}--test "#792 manually typed path remains ordinary character-editable text" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "one file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- _ = term.typeText(path);- _ = term.feed("\x1bb"); // word-left stops at the path's internal space- const boundary = std.mem.indexOfScalar(u8, path, ' ').? + 1;- try std.testing.expectEqual(boundary, term.model.input.cursor);- _ = term.feed("\x7f");- const expected = try std.fmt.allocPrint(std.testing.allocator, "{s}file.txt", .{path[0 .. boundary - 1]});- defer std.testing.allocator.free(expected);- try std.testing.expectEqualStrings(expected, term.model.input.getValue());-}--test "#792 typing after a paste uses the removable separator" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, "hello");- _ = term.typeText("world");- try std.testing.expectEqualStrings("hello world", term.model.input.getValue());-}--test "#792 existing whitespace to the right is not duplicated" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- try term.model.input.setValue(" right");- _ = term.press(.home);- paste(&term, "hello");- try std.testing.expectEqualStrings("hello right", term.model.input.getValue());-}--test "#792 file URL paste normalizes and highlights only the semantic span" {- const theme = @import("theme.zig");- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "one file.txt", &path_buf);- const space = std.mem.indexOfScalar(u8, path, ' ').?;- const url = try std.fmt.allocPrint(std.testing.allocator, "file://{s}%20{s}", .{ path[0..space], path[space + 1 ..] });- defer std.testing.allocator.free(url);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, url);- const expected = try std.fmt.allocPrint(std.testing.allocator, "{s} ", .{path});- defer std.testing.allocator.free(expected);- try std.testing.expectEqualStrings(expected, term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);- const styled = try term.model.input.viewStyled(std.testing.allocator, theme.of(.night).accent, theme.of(.night).text);- defer std.testing.allocator.free(styled);- try std.testing.expect(std.mem.indexOf(u8, styled, theme.of(.night).accent) != null);-- try term.model.input.setValue(path);- const plain = try term.model.input.viewStyled(std.testing.allocator, theme.of(.night).accent, theme.of(.night).text);- defer std.testing.allocator.free(plain);- try std.testing.expect(std.mem.indexOf(u8, plain, theme.of(.night).accent) == null);-}--test "#792 undo restores file span identity after atomic deletion" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "undo file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- paste(&term, path);- _ = term.press(.backspace); // separator- _ = term.press(.backspace); // span- try std.testing.expectEqualStrings("", term.model.input.getValue());- _ = term.press(.undo);- try std.testing.expectEqualStrings(path, term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);- _ = term.press(.backspace);- try std.testing.expectEqualStrings("", term.model.input.getValue());-}--test "#792 prompt history round trip preserves an unsent file span" {- const history = @import("prompt_history.zig");- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const path = try writeTmp(&tmp, "draft file.txt", &path_buf);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.prompt_hist.append(try std.testing.allocator.dupe(u8, "older"));- try term.model.prompt_hist_images.append(&.{});-- paste(&term, path);- history.recallPrev(&term.model);- try std.testing.expectEqualStrings("older", term.model.input.getValue());- history.recallNext(&term.model);- try std.testing.expectEqual(@as(usize, 1), term.model.input.semanticSpans().len);- _ = term.press(.backspace);- _ = term.press(.backspace);- try std.testing.expectEqualStrings("", term.model.input.getValue());-}--test "#792 image paste consumes only its inserted range" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("keep me");-- paste(&term, "/tmp/pic.png");- try std.testing.expectEqualStrings("keep me", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);- try std.testing.expectEqualStrings("/tmp/pic.png", term.model.images.items[0]);-}--test "#792 mid-buffer image paste does not edit surrounding text" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("keepme");- _ = term.press(.home);- for (0..4) |_| _ = term.press(.right);-- paste(&term, "/tmp/pic.png");- try std.testing.expectEqualStrings("keepme", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);-}--test "#792 empty paste does not consume an undo step" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("x");-- paste(&term, "");- _ = term.press(.undo);- try std.testing.expectEqualStrings("", term.model.input.getValue());-}diff --git a/TUI/issue_798_tests.zig b/TUI/issue_798_tests.zigdeleted file mode 100644index 2206d616..00000000--- a/TUI/issue_798_tests.zig+++ /dev/null@@ -1,54 +0,0 @@-//! #798: prompt history must clear the rendered composer after Down.-const std = @import("std");-const sim = @import("sim.zig");--fn composerContains(vis: []const u8, first_row: usize, needle: []const u8) bool {- var row: usize = 0;- var lines = std.mem.splitScalar(u8, vis, '\n');- while (lines.next()) |line| : (row += 1) {- if (row >= first_row and std.mem.indexOf(u8, line, needle) != null) return true;- }- return false;-}--test "#798: Down from a wrapped prompt leaves only the fresh composer draft" {- const a = std.testing.allocator;- var term: sim.Term = undefined;- term.init(a, 80, 24);- defer term.deinit();-- var prompt: std.ArrayList(u8) = .empty;- defer prompt.deinit(a);- try prompt.appendSlice(a, "issue-798-recalled-head ");- for (0..32) |_| try prompt.appendSlice(a, "a wrapped submitted segment ");- try prompt.appendSlice(a, "issue-798-recalled-tail");-- // Submit through the same sim feed path as the fullscreen loop.- _ = term.typeText(prompt.items);- _ = term.enter();- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 1), term.model.prompt_hist.items.len);-- // The live history cursor sits just past the newest item before Up. Keep- // this seam explicit: the regression starts after Up has recalled the row.- term.model.hist_idx = term.model.prompt_hist.items.len;- _ = term.feed("\x1b[A");- try std.testing.expectEqualStrings(prompt.items, term.model.input.getValue());- const recalled = try term.screen();- defer a.free(recalled);- try std.testing.expect(composerContains(recalled, term.model.prompt_origin, "issue-798-recalled-tail"));-- _ = term.feed("\x1b[B");- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expectEqual(@as(?usize, null), term.model.hist_idx);- const fresh = try term.screen();- defer a.free(fresh);- try std.testing.expect(!composerContains(fresh, term.model.prompt_origin, "issue-798-recalled-tail"));-- _ = term.typeText("ONLY-FRESH-TYPED");- try std.testing.expectEqualStrings("ONLY-FRESH-TYPED", term.model.input.getValue());- const typed = try term.screen();- defer a.free(typed);- try std.testing.expect(composerContains(typed, term.model.prompt_origin, "ONLY-FRESH-TYPED"));- try std.testing.expect(!composerContains(typed, term.model.prompt_origin, "issue-798-recalled-tail"));-}diff --git a/TUI/issue_805_tests.zig b/TUI/issue_805_tests.zigdeleted file mode 100644index 4dfa1c19..00000000--- a/TUI/issue_805_tests.zig+++ /dev/null@@ -1,17 +0,0 @@-//! Citation control markup must not appear as raw PUA in the TUI transcript (#805).--const std = @import("std");-const sim = @import("sim.zig");--test "TUI transcript strips citation annotations (#805)" {- var term: sim.Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.assistant, "See the docs\u{E200}cite\u{E202}turn0view0\u{E201} for details.");- try std.testing.expectEqualStrings("See the docs for details.", term.model.history.items[0].text);- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "See the docs for details.") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "turn0view0") == null);- try std.testing.expect(std.mem.indexOf(u8, vis, "\u{E200}") == null);-}diff --git a/TUI/issue_845_tests.zig b/TUI/issue_845_tests.zigdeleted file mode 100644index 0e88b404..00000000--- a/TUI/issue_845_tests.zig+++ /dev/null@@ -1,85 +0,0 @@-//! #845: composing or queuing a follow-up must not freeze the thinking-//! indicator or interrupt the live turn. Driven through Term (AGENTS.md).--const std = @import("std");--const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const Term = @import("sim.zig").Term;--fn attachThinking(term: *Term, alloc: std.mem.Allocator) !*engine.Job {- try term.model.push(.user, "think about this");- try term.model.push(.pending, "");- const job = try alloc.create(engine.Job);- job.* = .{- .gpa = alloc,- .history = &.{},- .params = .{},- .stream = .{},- .raw = .{},- .threaded = false,- };- job.events.attach(alloc);- term.model.pending = job;- return job;-}--test "queuing a follow-up keeps the thinking indicator live (#845)" {- const alloc = std.testing.allocator;- var term: Term = undefined;- term.init(alloc, 80, 24);- defer term.deinit();- const job = try attachThinking(&term, alloc);-- term.now_ms = 0;- const idle = try term.screen();- defer alloc.free(idle);- try std.testing.expect(std.mem.indexOf(u8, idle, "Thinking") != null);- try std.testing.expect(std.mem.indexOf(u8, idle, glyphs.thinking[0]) != null);-- _ = term.typeText("queued follow-up");- try std.testing.expectEqualStrings("queued follow-up", term.model.input.getValue());- try std.testing.expect(term.model.pending != null);- try std.testing.expect(!term.model.cancel_requested);-- term.now_ms = 500;- const composing = try term.screen();- defer alloc.free(composing);- try std.testing.expect(std.mem.indexOf(u8, composing, "Thinking") != null);- try std.testing.expect(std.mem.indexOf(u8, composing, "queued follow-up") != null);- try std.testing.expect(std.mem.indexOf(u8, composing, glyphs.thinking[1]) != null);- try std.testing.expect(std.mem.indexOf(u8, composing, glyphs.thinking[0]) == null);-- _ = term.enter();- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- try std.testing.expectEqualStrings("queued follow-up", term.model.steer_queue.items[0]);- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expect(term.model.pending != null);- try std.testing.expect(!term.model.cancel_requested);- try std.testing.expect(term.model.pending.? == job);-- term.now_ms = 1000;- const queued = try term.screen();- defer alloc.free(queued);- try std.testing.expect(std.mem.indexOf(u8, queued, "Thinking") != null);- try std.testing.expect(std.mem.indexOf(u8, queued, "queued") != null);- try std.testing.expect(std.mem.indexOf(u8, queued, glyphs.thinking[0]) != null);- try std.testing.expect(std.mem.indexOf(u8, queued, glyphs.thinking[1]) == null);-}--test "empty Enter with a queued follow-up is the interrupt; typing is not (#845)" {- const alloc = std.testing.allocator;- var term: Term = undefined;- term.init(alloc, 80, 24);- defer term.deinit();- _ = try attachThinking(&term, alloc);-- _ = term.typeText("next");- _ = term.enter();- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);-- _ = term.enter();- try std.testing.expect(term.model.cancel_requested);- try std.testing.expect(term.model.pending != null);-}diff --git a/TUI/issue_883_tests.zig b/TUI/issue_883_tests.zigdeleted file mode 100644index e44d2690..00000000--- a/TUI/issue_883_tests.zig+++ /dev/null@@ -1,429 +0,0 @@-//! #883: exercise Ctrl-V dispatch without a terminal or clipboard access.-//! PasteFn exposes only image paths (>0), errors (<0), and no image (0).-//! Text fallback and image/text precedence require a seam inside pasteCb;-//! these tests deliberately make no claims about those backend decisions.--const std = @import("std");-const engine = @import("engine.zig");-const Term = @import("sim.zig").Term;--const Paste = struct {- payload: []const u8,- failed: bool = false,- owned: bool = false,- calls: usize = 0,-- fn call(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {- const self: *Paste = @ptrCast(@alignCast(ctx.?));- self.calls += 1;- owned.* = self.owned;- const n = @min(self.payload.len, dest.len);- @memcpy(dest[0..n], self.payload[0..n]);- const result: isize = @intCast(n);- return if (self.failed) -result else result;- }-};--fn expectVisible(term: *Term, text: []const u8) !void {- const screen = try term.screen();- defer term.alloc.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, text) != null);-}--test "#883 Ctrl-V callback failures remain visible and preserve the prompt and attachments" {- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- engine.g_paste_fn = Paste.call;-- // Synthetic backend errors: dispatch must display, not reinterpret them.- for ([_][]const u8{ "clipboard read failed", "clipboard image export failed", "clipboard text read failed" }) |message| {- var paste = Paste{ .payload = message, .failed = true };- engine.g_turn_ctx = &paste;- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- _ = term.typeText("keep this prompt");- _ = term.feed("\x1b[D");- const cursor = term.model.input.cursor;- term.model.attachImage("/synthetic/existing.png");-- _ = term.feed("\x16");-- try std.testing.expectEqual(@as(usize, 1), paste.calls);- try std.testing.expectEqualStrings("keep this prompt", term.model.input.getValue());- try std.testing.expectEqual(cursor, term.model.input.cursor);- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);- try std.testing.expectEqualStrings("/synthetic/existing.png", term.model.images.items[0]);- try expectVisible(&term, message);- }-}--test "#883 Ctrl-V image result attaches without replacing prompt text" {- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- var paste = Paste{ .payload = "/synthetic/clipboard.png" };- engine.g_paste_fn = Paste.call;- engine.g_turn_ctx = &paste;- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- _ = term.typeText("describe this");- _ = term.feed("\x1b[D");- const cursor = term.model.input.cursor;-- _ = term.feed("\x1b[118;5u");-- try std.testing.expectEqual(@as(usize, 1), paste.calls);- try std.testing.expectEqualStrings("describe this", term.model.input.getValue());- try std.testing.expectEqual(cursor, term.model.input.cursor);- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);- try std.testing.expectEqualStrings(paste.payload, term.model.images.items[0]);- try expectVisible(&term, "[Image #1] attached");-}--test "#883 Ctrl-V empty callback result is visible without changing the prompt" {- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- var paste = Paste{ .payload = "" };- engine.g_paste_fn = Paste.call;- engine.g_turn_ctx = &paste;- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- _ = term.typeText("keep this prompt");- const cursor = term.model.input.cursor;-- _ = term.feed("\x16");-- try std.testing.expectEqual(@as(usize, 1), paste.calls);- try std.testing.expectEqualStrings("keep this prompt", term.model.input.getValue());- try std.testing.expectEqual(cursor, term.model.input.cursor);- try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);- try expectVisible(&term, "no image on the clipboard");-}--test "clipboard-owned attachment removal deletes the export but preserves an original" {- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- engine.g_paste_fn = Paste.call;- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);- defer std.testing.allocator.free(root);- const path = try std.fs.path.join(std.testing.allocator, &.{ root, "paste.png" });- defer std.testing.allocator.free(path);- for ([_]bool{ true, false }) |owned| {- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- var paste = Paste{ .payload = path, .owned = owned };- engine.g_turn_ctx = &paste;- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- _ = term.feed("\x16");- try std.testing.expectEqual(@as(usize, 1), term.model.images.items.len);- _ = term.feed("\x7f");- try std.testing.expectEqual(@as(usize, 0), term.model.images.items.len);- if (owned) {- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));- } else {- const original = try tmp.dir.openFile(io, "paste.png", .{});- original.close(io);- }- }-}--test "sent clipboard export survives prompt recall and remains available for saved replay" {- const saved_fn = engine.g_paste_fn;- const saved_ctx = engine.g_turn_ctx;- defer {- engine.g_paste_fn = saved_fn;- engine.g_turn_ctx = saved_ctx;- }- engine.g_paste_fn = Paste.call;- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(path);- var paste = Paste{ .payload = path, .owned = true };- engine.g_turn_ctx = &paste;- {- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- _ = term.feed("\x16");- _ = term.typeText("describe this");- _ = term.enter();- @import("owned_images.zig").collect(&term.model);- const retained = try tmp.dir.openFile(io, "paste.png", .{});- retained.close(io);- @import("prompt_history.zig").recallPrev(&term.model);- try std.testing.expectEqualStrings(path, term.model.images.items[0]);- @import("image.zig").clearAll(&term.model);- const history = try tmp.dir.openFile(io, "paste.png", .{});- history.close(io);- }- const replay = try tmp.dir.openFile(io, "paste.png", .{});- replay.close(io);-}--test "queued clipboard exports remain readable until the queue releases them" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(path);- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- @import("owned_images.zig").attach(&term.model, path, true);- @import("dispatch.zig").queueSteerLine(&term.model, "describe this");- @import("owned_images.zig").collect(&term.model);- const retained = try tmp.dir.openFile(io, "paste.png", .{});- retained.close(io);- term.model.alloc.free(term.model.steer_queue.pop().?);- @import("owned_images.zig").collect(&term.model);- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));-}--test "closing an unsent clipboard draft releases only its owned export" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(path);- {- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- @import("owned_images.zig").attach(&term.model, path, true);- }- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));-}--test "clipboard removal preserves a replacement file at the exported path" {- try changedExport(false, false);-}--test "clipboard teardown preserves edited exports" {- try changedExport(true, false);-}--test "clipboard removal preserves a symlink substituted for the export" {- try changedExport(false, true);-}--fn changedExport(edited: bool, symlink: bool) !void {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(file_path);- {- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- @import("owned_images.zig").attach(&term.model, file_path, true);- if (!edited) try tmp.dir.rename("paste.png", tmp.dir, "old.png", io);- if (symlink) {- try tmp.dir.symLink(io, "old.png", "paste.png", .{});- } else {- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "user replacement pixels" });- }- if (!edited) _ = term.feed("\x7f");- }- const preserved = try tmp.dir.openFile(io, "paste.png", .{});- defer preserved.close(io);- var bytes: [64]u8 = undefined;- const n = try preserved.readPositionalAll(io, &bytes, 0);- try std.testing.expectEqualStrings(if (symlink) "pixels" else "user replacement pixels", bytes[0..n]);-}--test "sent clipboard exports survive clearing visible history and prompt recall" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(file_path);- {- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- @import("owned_images.zig").attach(&term.model, file_path, true);- _ = term.typeText("describe this");- _ = term.enter();- term.model.clearHistory();- @import("prompt_history.zig").deinit(&term.model);- term.model.prompt_hist_images = std.array_list.Managed([]const []const u8).init(term.alloc);- @import("owned_images.zig").collect(&term.model);- const retained = try tmp.dir.openFile(io, "paste.png", .{});- retained.close(io);- }- const replay = try tmp.dir.openFile(io, "paste.png", .{});- replay.close(io);-}--test "completed model worker releases a removed unsent clipboard draft" {- try workerReleasesDraft(false);-}--test "completed background worker releases a removed unsent clipboard draft" {- try workerReleasesDraft(true);-}--fn workerReleasesDraft(background: bool) !void {- const io = std.Io.Threaded.global_single_threaded.io();- const gpa = std.testing.allocator;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", gpa);- defer gpa.free(file_path);- var term: Term = undefined;- term.init(gpa, 100, 24);- defer term.deinit();- @import("owned_images.zig").attach(&term.model, file_path, true);- if (background) {- const op = try gpa.create(engine.BgOp);- op.* = .{ .kind = .files, .gpa = gpa, .threaded = false };- term.model.bg = op;- } else {- const job = try gpa.create(engine.Job);- job.* = .{ .gpa = gpa, .threaded = false, .history = try gpa.alloc(engine.Turn, 0), .params = .{}, .stream = .{} };- term.model.pending = job;- }- @import("image.zig").clearAll(&term.model);- const pending = try tmp.dir.openFile(io, "paste.png", .{});- pending.close(io);- if (background) {- term.model.bg.?.done.store(true, .release);- @import("bgop.zig").finish(&term.model);- } else {- term.model.pending.?.done.store(true, .release);- @import("turn.zig").finishJob(&term.model);- }- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "paste.png", .{}));-}--test "clipboard recovery skips live leases and reclaims exports after owner exit" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);- defer std.testing.allocator.free(root);- const Recovery = @import("clipboard_recovery.zig").Store;- var store = try Recovery.init(io, std.testing.allocator, root);- defer store.deinit();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(file_path);- const lease = try store.record(file_path, try tmp.dir.statFile(io, "paste.png", .{}));- try std.testing.expectEqual(@as(usize, 0), store.sweep(64));- // Closing the descriptor models the kernel releasing it at process exit.- lease.file.close(io);- try std.testing.expectEqual(@as(usize, 1), store.sweep(64));- try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "paste.png", .{}));-}--test "clipboard recovery excludes submitted images and respects its scan bound" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);- defer std.testing.allocator.free(root);- var store = try @import("clipboard_recovery.zig").Store.init(io, std.testing.allocator, root);- defer store.deinit();- for ([_][]const u8{ "sent.png", "draft1.png", "draft2.png" }) |name| {- try tmp.dir.writeFile(io, .{ .sub_path = name, .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, name, std.testing.allocator);- defer std.testing.allocator.free(file_path);- var lease: ?@import("clipboard_recovery.zig").Lease = try store.record(file_path, try tmp.dir.statFile(io, name, .{}));- if (std.mem.eql(u8, name, "sent.png")) try store.retain(&lease) else lease.?.file.close(io);- }- var removed: usize = 0;- for (0..16) |_| {- const n = store.sweep(1);- try std.testing.expect(n <= 1);- removed += n;- }- try std.testing.expectEqual(@as(usize, 2), removed);- _ = try tmp.dir.statFile(io, "sent.png", .{});-}--test "clipboard recovery preserves changed exports and malformed records" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);- defer std.testing.allocator.free(root);- var store = try @import("clipboard_recovery.zig").Store.init(io, std.testing.allocator, root);- defer store.deinit();- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(file_path);- const lease = try store.record(file_path, try tmp.dir.statFile(io, "paste.png", .{}));- lease.file.close(io);- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "edited pixels" });- try tmp.dir.writeFile(io, .{ .sub_path = "00000000000000000000000000000000.pending", .data = "invalid" });- try std.testing.expectEqual(@as(usize, 0), store.sweep(64));- _ = try tmp.dir.statFile(io, "paste.png", .{});-}--test "TUI submission retires recovery authority before accepting image history" {- const io = std.Io.Threaded.global_single_threaded.io();- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const root = try tmp.dir.realPathFileAlloc(io, ".", std.testing.allocator);- defer std.testing.allocator.free(root);- var store = try @import("clipboard_recovery.zig").Store.init(io, std.testing.allocator, root);- defer store.deinit();- const owned = @import("owned_images.zig");- owned.test_store = &store;- defer owned.test_store = null;- try tmp.dir.writeFile(io, .{ .sub_path = "paste.png", .data = "pixels" });- const file_path = try tmp.dir.realPathFileAlloc(io, "paste.png", std.testing.allocator);- defer std.testing.allocator.free(file_path);- var term: Term = undefined;- term.init(std.testing.allocator, 100, 24);- defer term.deinit();- owned.attach(&term.model, file_path, true);- const record_name = term.model.owned_images.items[0].lease.?.name;- // Force retirement failure without deleting the still-locked record.- try tmp.dir.rename(&record_name, tmp.dir, "held-record", io);- try tmp.dir.createDir(io, &record_name, .default_dir);- _ = term.typeText("describe this");- _ = term.enter();- try std.testing.expectEqual(@as(usize, 0), term.model.userTurnCount());- try expectVisible(&term, "could not preserve the submitted attachment");- _ = try tmp.dir.statFile(io, "paste.png", .{});- try tmp.dir.deleteDir(io, &record_name);- try tmp.dir.rename("held-record", tmp.dir, &record_name, io);- @import("prompt_history.zig").recallPrev(&term.model);- _ = term.enter();- try std.testing.expectEqual(@as(usize, 1), term.model.userTurnCount());- try std.testing.expect(term.model.owned_images.items[0].retained);- try std.testing.expect(term.model.owned_images.items[0].lease == null);- try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, &record_name, .{}));-}diff --git a/TUI/issue_887_tests.zig b/TUI/issue_887_tests.zigdeleted file mode 100644index 6e7daf68..00000000--- a/TUI/issue_887_tests.zig+++ /dev/null@@ -1,130 +0,0 @@-const std = @import("std");--const app = @import("app.zig");-const chrome = @import("chrome.zig");-const engine = @import("engine.zig");-const sim = @import("sim.zig");-const theme = @import("theme.zig");--const Model = app.Model;--fn footerRow(box: []const u8) ![]const u8 {- var it = std.mem.splitScalar(u8, box, '\n');- while (it.next()) |line| {- if (std.mem.indexOf(u8, line, "╰") != null) return line;- }- return error.NoFooterRow;-}--test "#887 composer footer names the seat, auto-accept mode, and meters" {- engine.g_model_name = "claude-opus-4-1";- engine.g_model_provider = "anthropic";- defer {- engine.g_model_name = "";- engine.g_model_provider = "";- }-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.mode = .always_approve;- m.effort = .high;- m.setStatus(.{- .model = engine.g_model_name,- .provider_id = engine.g_model_provider,- .has_context = true,- .tokens = 52,- .window = 100,- .cache_read = 19,- });-- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const row = try footerRow(try chrome.promptBox(&m, arena.allocator(), 120));-- try std.testing.expect(std.mem.indexOf(u8, row, "anthropic/claude-opus-4-1") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "high") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "auto-accept") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "ctx 52%") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "cache 36%") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "always-approve") == null);-}--test "#887 composer footer does not invent context before a measured turn" {- engine.g_model_name = "gpt-5.6";- engine.g_model_provider = "openai";- defer {- engine.g_model_name = "";- engine.g_model_provider = "";- }-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();-- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const row = try footerRow(try chrome.promptBox(&m, arena.allocator(), 80));-- try std.testing.expect(std.mem.indexOf(u8, row, "openai/gpt-5.6") != null);- try std.testing.expect(std.mem.indexOf(u8, row, "ctx") == null);- try std.testing.expect(std.mem.indexOf(u8, row, "cache") == null);-}--test "#887 simulator exposes the standing footer in a rendered frame" {- engine.g_model_name = "gpt-5.6-codex";- engine.g_model_provider = "openai";- defer {- engine.g_model_name = "";- engine.g_model_provider = "";- }-- var term: sim.Term = undefined;- term.init(std.testing.allocator, 120, 24);- defer term.deinit();- term.model.mode = .always_approve;- term.model.setStatus(.{- .model = engine.g_model_name,- .provider_id = engine.g_model_provider,- .has_context = true,- .tokens = 25,- .window = 100,- .cache_read = 20,- });-- const screen = try term.screen();- defer std.testing.allocator.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, "openai/gpt-5.6-codex") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "auto-accept") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "ctx 25%") != null);- try std.testing.expect(std.mem.indexOf(u8, screen, "cache 80%") != null);-}--test "#887 composer footer remains exactly one terminal row at supported widths" {- engine.g_model_name = "grok-4";- engine.g_model_provider = "xai";- defer {- engine.g_model_name = "";- engine.g_model_provider = "";- }-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.setStatus(.{- .model = engine.g_model_name,- .provider_id = engine.g_model_provider,- .has_context = true,- .tokens = 9,- .window = 100,- .cache_read = 4,- });-- for ([_]usize{ 40, 80, 120 }) |width| {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const row = try footerRow(try chrome.promptBox(&m, arena.allocator(), width));- try std.testing.expectEqual(width, theme.visibleLen(row));- try std.testing.expect(std.mem.indexOfScalar(u8, row, '\n') == null);- }-}diff --git a/TUI/key.zig b/TUI/key.zigdeleted file mode 100644index fbe995ad..00000000--- a/TUI/key.zig+++ /dev/null@@ -1,599 +0,0 @@-//! Keyboard tokens. Understands classic CSI, SS3, and kitty CSI-u (Ghostty).--const std = @import("std");-const orphan = @import("key_orphan.zig");-const recover = @import("key_recover.zig");-const paste = @import("key_paste.zig");--/// Super/alt currently held, from kitty modifier-key events (Ghostty Cmd+Delete-/// often arrives as a bare DEL after Super-down).-pub var held: u32 = 0;--/// Inside `CSI 200~ … CSI 201~`. Every byte between them is literal text by-/// definition, and a long paste spans several reads — so the debris guard must-/// stay out of it or a chunk that happens to start `39;7;32M` gets eaten.-var in_paste: bool = false;-// A terminator makes subsequent keys in this read explicit user input.-var paste_ended_in_read = false;--pub fn inPaste() bool {- return in_paste;-}--/// Close paste and ignored modifiers, also on lost-terminator recovery (#548).-pub fn endPaste() void {- in_paste = false;- abandonSequence("", .none);-}--/// Arm/disarm broad orphan recovery after the read loop drops a sequence.-pub fn armOrphan(on: bool) void {- if (on) orphan.armDropped() else orphan.disarm();-}--/// Expire the short genuine-Escape carry without discarding a dropped head.-pub fn expireOrphanHead() void {- orphan.expireHead();-}--/// Prepend a completing stashed head; every read spends this one-shot.-pub fn joinOrphanHead(buf: []u8, n: usize) usize {- return orphan.joinHead(buf, n);-}--pub const SequenceRecovery = enum { none, escape, dropped };-/// Clear stale modifiers, changing orphan state only as requested by recovery.-pub fn abandonSequence(bytes: []const u8, recovery: SequenceRecovery) void {- held = 0;- if (recovery != .none) orphan.stashHead(bytes);- switch (recovery) {- .none => {},- .escape => orphan.armEscape(),- .dropped => orphan.armDropped(),- }-}-/// A fresh input loop must not inherit any parser latch from the previous one.-pub fn resetInputState() void {- abandonSequence("", .none);- in_paste = false;- paste.resetBurst();- orphan.reset();-}--pub const Key = union(enum) {- char: u8,- /// Non-ASCII codepoint delivered via kitty CSI-u (é and friends).- codepoint: u21,- /// OSC 11 reply: the terminal's background RGB (auto light/dark).- bg_report: [3]u8,- ctrl: u8,- ignore,- enter,- shift_enter,- tab,- shift_tab,- backspace,- escape,- up,- down,- left,- right,- page_up,- page_down,- home,- end,- f1,- f2,- paste_start,- paste_end,- delete_word,- delete_to_start,- delete_to_end,- word_left,- word_right,- prev_turn,- next_turn,- delete,- undo,- mouse: Mouse,-};--pub const Mouse = struct {- btn: u8,- x: u16,- y: u16,- down: bool,-};--pub fn next(bytes: []const u8, i: *usize) ?Key {- if (i.* == 0) paste_ended_in_read = false;- // Full reads recover orphan events ahead of their buffered payload.- if (i.* == 0) if (orphan.takeRecoveredEvent()) |event| {- orphan.end = std.math.maxInt(usize);- return event;- };- if (i.* >= bytes.len) return null;- // Orphan debris is only a read HEAD after a lost ESC. Digit runs elsewhere- // are text: swallowing them ate `0x1f`, `[12]`, `1e5` and version strings.- if (!in_paste and (i.* == 0 or i.* == orphan.end)) {- switch (orphan.take(bytes, i)) {- .took => |k| {- orphan.end = i.*;- // The arm covers exactly ONE lost head. Leaving it latched let- // the sweeper keep eating whatever the user typed next — `3u- // apples` reached the composer as ` apples`, and a lone `3`- // was held pending until the stall path dropped it (#531).- orphan.disarm();- return k;- },- // Debris cut short at the read boundary: hold the bytes so the loop- // carries them into the next read instead of typing the digits. The- // arm must SURVIVE that carry — the rejoined fragment is the same- // one lost head, and disarming here made `3` + `u` read as typed- // text and type itself (#546).- .partial => return null,- .none => {},- }- }- orphan.end = std.math.maxInt(usize);- orphan.disarm();- const b = bytes[i.*];- i.* += 1;- if (paste.takeSplitLf(b)) return .ignore;- if (b == 0x1b) return escapeSeq(bytes, i);- if (b == 0x0d or b == 0x0a) {- // Newlines inside a paste are text, not the Enter/send key: bracketed,- // a multiline dump in this read, or a run spanning reads (#643/#737).- if (in_paste) return .{ .char = b }; // preserve bracketed CRLF across reads (#737)- if (!paste_ended_in_read and (paste.burstActive() or paste.looksLikeBurst(bytes))) {- if (paste.pasteNewline(bytes, i, b)) |nl| return .{ .char = nl };- }- return .enter;- }- if (b == 0x09) return .tab;- if (b == 0x7f or b == 0x08) {- if (held & 8 != 0) return .delete_to_start;- if (held & 2 != 0) return .delete_word;- return .backspace;- }- if (b >= 1 and b <= 26) return .{ .ctrl = 'a' + (b - 1) };- if (b >= 32) return .{ .char = b };- return next(bytes, i);-}--fn escapeSeq(bytes: []const u8, i: *usize) ?Key {- if (i.* >= bytes.len) {- // Trailing lone ESC: the Esc key, or a sequence split across reads —- // we can't know yet. Rewind; run.zig delivers a real .escape only if- // nothing follows within its grace poll (#94).- i.* -= 1;- return null;- }- const c0 = bytes[i.*];- if (c0 == 0x7f or c0 == 0x08) {- i.* += 1;- return .delete_word;- }- if (c0 == 'b') {- i.* += 1;- return .word_left;- }- if (c0 == 'f') {- i.* += 1;- return .word_right;- }- if (c0 == 0x0d or c0 == 0x0a) {- i.* += 1;- return .shift_enter;- }- const double_esc = c0 == 0x1b;- if (double_esc) {- // Legacy Alt arrows are ESC ESC CSI. Keep both ESC bytes ambiguous- // until the CSI is complete, otherwise the first one cancels work.- if (i.* + 1 >= bytes.len) {- i.* -= 1;- return null;- }- if (bytes[i.* + 1] != '[') return .escape;- i.* += 2;- } else {- if (c0 == 'O') return ss3(bytes, i);- if (c0 == ']' or c0 == 'P' or c0 == '_' or c0 == '^' or c0 == 'X') return stringSeq(bytes, i);- if (c0 != '[') {- // Unbound Alt+<char> chord: swallow both bytes so the char is not- // typed into the composer behind a phantom Escape.- i.* += 1;- return .ignore;- }- i.* += 1;- }- const start = i.*;- while (i.* < bytes.len) : (i.* += 1) {- const c = bytes[i.*];- if (c == 0x1b) {- abandonSequence("", .none);- return .ignore; // reparse this event head- }- if (c >= 0x40 and c <= 0x7e) {- const final = c;- const params = bytes[start..i.*];- i.* += 1;- if (final == 'M' and params.len == 0) return x10Mouse(bytes, i, start);- if (double_esc and !recover.legacyCsiBoundary(params, final, bytes, i.*)) return recover.legacyDoubleEscape(i, start);- return decodeCsi(params, final);- }- }- // Incomplete CSI (split paste / arrow) — rewind so the next read can finish it.- i.* = start - @as(usize, if (double_esc) 3 else 2);- return null;-}--/// OSC/DCS/APC/PM/SOS reply on stdin (e.g. a color query answer) — consume-/// through BEL or ST so the payload is never typed into the prompt.-/// Longest stdin reply we ever solicit (OSC 10/11 color answers are ~25-/// bytes; kitty acks are shorter). Anything bigger behind an unterminated-/// introducer is typed text, not a reply (#516).-const max_reply_pending = 128;--fn stringSeq(bytes: []const u8, i: *usize) ?Key {- const start = i.*; // bytes[start] is ']' for OSC- var j = i.* + 1;- while (j < bytes.len) : (j += 1) {- if (bytes[j] == 0x07) {- const body = bytes[start + 1 .. j];- i.* = j + 1;- return oscReply(bytes[start], body);- }- if (bytes[j] == 0x1b) {- if (j + 1 < bytes.len) {- // ST (ESC \) ends the string; any other ESC starts a new- // sequence — leave it for the next parse.- if (bytes[j + 1] == '\\') {- const body = bytes[start + 1 .. j];- i.* = j + 2;- return oscReply(bytes[start], body);- }- abandonSequence("", .none);- i.* = j;- return .ignore;- }- break; // ST split across reads — wait for the backslash- }- if (bytes[j] == 0x0d or bytes[j] == 0x0a) {- // Replies never carry CR/LF: this is typed text behind an- // Alt+]/P/X/^/_ chord. Swallow only the introducer — like any- // unbound alt-chord — so the text reparses instead of the- // keyboard wedging until it is destroyed (#516).- abandonSequence("", .none);- i.* += 1;- return .ignore;- }- }- if (bytes.len - i.* > max_reply_pending) {- abandonSequence("", .none);- i.* += 1; // over any real reply's size — same chord recovery (#516)- return .ignore;- }- i.* -= 1; // rewind to the ESC; the terminator is still in flight- return null;-}--/// A terminated OSC body. The only reply we act on is OSC 11 (background-/// color, answering run.zig's startup query) — everything else stays inert.-pub fn oscReply(kind: u8, body: []const u8) Key {- if (kind != ']') return .ignore;- if (!std.mem.startsWith(u8, body, "11;")) return .ignore;- const rgb = parseXColor(body[3..]) orelse return .ignore;- return .{ .bg_report = rgb };-}--/// `rgb:RRRR/GGGG/BBBB` (high byte) or `rgb:RR/GG/BB`.-fn parseXColor(s: []const u8) ?[3]u8 {- if (!std.mem.startsWith(u8, s, "rgb:")) return null;- var out: [3]u8 = undefined;- var it = std.mem.splitScalar(u8, s[4..], '/');- for (0..3) |n| {- const part = it.next() orelse return null;- if (part.len != 2 and part.len != 4) return null;- const v = std.fmt.parseInt(u16, part, 16) catch return null;- out[n] = if (part.len == 4) @intCast(v >> 8) else @intCast(v);- }- if (it.next() != null) return null;- return out;-}--/// ESC O <final> — SS3 application keys (tmux/screen, macOS Terminal).-fn ss3(bytes: []const u8, i: *usize) ?Key {- if (i.* + 1 >= bytes.len) {- i.* -= 1; // rewind to the ESC; the final byte is still in flight- return null;- }- const final = bytes[i.* + 1];- i.* += if (final == 0x1b) 1 else 2;- if (final == 0x1b) {- abandonSequence("", .none);- return .ignore;- }- return decodeSs3(final);-}--pub fn decodeSs3(final: u8) Key {- return switch (final) {- 'A' => .up,- 'B' => .down,- 'C' => .right,- 'D' => .left,- 'H' => .home,- 'F' => .end,- 'P' => .f1,- 'Q' => .f2,- 'M' => .enter,- else => .ignore,- };-}--/// CSI M b x y — X10 fallback when the terminal ignores SGR 1006.-fn x10Mouse(bytes: []const u8, i: *usize, start: usize) ?Key {- const available_end = @min(i.* + 3, bytes.len);- if (std.mem.indexOfScalar(u8, bytes[i.*..available_end], 0x1b)) |at| {- i.* += at;- abandonSequence("", .none);- return .ignore;- }- if (i.* + 3 > bytes.len) {- i.* = start - 2;- return null;- }- const event = decodeX10(bytes[i.* .. i.* + 3]);- i.* += 3;- return event;-}--pub fn decodeX10(payload: []const u8) Key {- std.debug.assert(payload.len == 3);- const b = payload[0] -| 32;- return .{ .mouse = .{- .btn = b,- .x = payload[1] -| 32,- .y = payload[2] -| 32,- .down = (b & 3) != 3,- } };-}--pub fn decodeCsi(params: []const u8, final: u8) Key {- const mods = csiMods(params);- const alt = mods & 2 != 0;- const ctrl = mods & 4 != 0;- const super = mods & 8 != 0;- // With kitty report-event-types on, releases arrive as `CSI 1;1:3 A` etc.- // Acting on them double-fires every arrow / PgUp / Delete.- if (final != 'u' and final != 'M' and final != 'm' and eventOf(params) == 3) return .ignore;- return switch (final) {- 'A' => .up,- 'B' => .down,- 'C' => if (mods & 1 != 0) .next_turn else if (alt or ctrl) .word_right else if (super) .end else .right,- 'D' => if (mods & 1 != 0) .prev_turn else if (alt or ctrl) .word_left else if (super) .home else .left,- 'H' => .home,- 'F' => .end,- 'Z' => .shift_tab,- '~' => switch (leadingInt(params)) {- 1, 7 => .home,- 3 => if (super) .delete_to_end else .delete,- 4, 8 => .end,- 5 => .page_up,- 6 => .page_down,- 11 => .f1,- 12 => .f2,- 200 => blk: {- in_paste = true;- abandonSequence("", .none);- break :blk .paste_start;- },- 201 => blk: {- endPaste();- paste.resetBurst(); // an explicit terminator ends the read heuristic too (#737)- paste_ended_in_read = true;- break :blk .paste_end;- },- 27 => fixterms(params),- // 2 (Insert), 13-24 (F3-F12) and friends: inert, never Escape.- else => .ignore,- },- 'u' => kitty(params),- 'P' => .f1,- 'Q' => .f2,- 'M', 'm' => if (std.mem.count(u8, params, ";") == 2) sgrMouse(params, final == 'M') else .ignore,- // Unknown final — a stray reply or unsupported key, not the Esc key.- else => .ignore,- };-}--fn csiMods(params: []const u8) u32 {- const s = std.mem.indexOfScalar(u8, params, ';') orelse return 0;- var mods = leadingInt(params[s + 1 ..]);- if (mods > 0) mods -= 1;- return mods;-}--/// kitty event-type sub-param (field 2 after ':'): 1 press, 2 repeat, 3 release.-///-/// It lives in the MODIFIER field and nowhere else. Scanning the whole tail for-/// the first ':' read field 3 instead — the associated-text codepoints, which-/// are ':'-separated too — so `CSI 97;2;65:66u` reported event 66, and a text-/// field ending `:3` silently swallowed a real keypress as a release (#549).-fn eventOf(params: []const u8) u32 {- const s = std.mem.indexOfScalar(u8, params, ';') orelse return 1;- var field = params[s + 1 ..];- if (std.mem.indexOfScalar(u8, field, ';')) |e| field = field[0..e];- const c = std.mem.indexOfScalar(u8, field, ':') orelse return 1;- return leadingInt(field[c + 1 ..]);-}--/// CSI unicode ; mods u — kitty/ghostty. mods bit 2 = ctrl, 1 = shift.-fn kitty(params: []const u8) Key {- var it = std.mem.splitScalar(u8, params, ';');- const keys = it.next() orelse "";- const code = leadingInt(keys);- var shifted: u32 = 0;- if (std.mem.indexOfScalar(u8, keys, ':')) |c| shifted = leadingInt(keys[c + 1 ..]);- var mods: u32 = 0;- var has_mods = false;- if (std.mem.indexOfScalar(u8, params, ';')) |s| {- has_mods = true;- mods = leadingInt(params[s + 1 ..]);- if (mods > 0) mods -= 1; // kitty encodes mods+1- }- const ev = eventOf(params);- if (code >= 57344 and code <= 57454) return functional(code, mods, ev);- if (ev == 3) return .ignore;- // Outside paste, a live key is ground truth — resync so a missed- // release can't latch alt/super forever. The ABSENT mods field is ground- // truth too: kitty omits it exactly when no modifiers are down, so a- // plain keypress must clear the latch. Before this, Cmd+Tab-ing away- // mid-composition latched super (the release went to the other app) and- // the next plain Backspace became Cmd+Backspace = delete-to-start,- // silently wiping the composer.- if (!in_paste) held = if (has_mods) mods & 10 else 0;- return mapCode(code, mods);-}--/// kitty functional block (57344-57454): modifiers, locks, F13+, media, keypad.-fn functional(code: u32, mods: u32, ev: u32) Key {- // Real kitty table: 57443/57449 = L/R Alt, 57444/57450 = L/R Super.- // (57447/57448 are Right-Shift/Right-Ctrl — NOT alt/super.)- const bit: u32 = switch (code) {- 57443, 57449 => 2,- 57444, 57450 => 8,- else => 0,- };- if (bit != 0) {- if (!in_paste) held = if (ev == 3) held & ~bit else held | bit;- return .ignore;- }- if (ev == 3) return .ignore;- return switch (code) {- 57344 => .escape,- 57345, 57414 => if (mods & 3 != 0) .shift_enter else .enter,- 57346 => if (mods & 1 != 0) .shift_tab else .tab,- 57347 => mapCode(127, mods),- 57349, 57426 => .delete,- 57350, 57417 => .left,- 57351, 57418 => .right,- 57352, 57419 => .up,- 57353, 57420 => .down,- 57354, 57421 => .page_up,- 57355, 57422 => .page_down,- 57356, 57423 => .home,- 57357, 57424 => .end,- // Numeric keypad. With `>11u` on, kitty reports these INSTEAD of the- // plain ASCII byte, so leaving them unmapped dropped every keypad- // digit and operator on the floor (#549).- 57399...57408 => .{ .char = '0' + @as(u8, @intCast(code - 57399)) },- 57409 => .{ .char = '.' },- 57410 => .{ .char = '/' },- 57411 => .{ .char = '*' },- 57412 => .{ .char = '-' },- 57413 => .{ .char = '+' },- 57415 => .{ .char = '=' },- 57416 => .{ .char = ',' },- // KP_Insert (57425) and KP_Begin (57427) have no binding here and stay- // inert exactly like CSI 2~ — never a phantom Escape. Locks,- // PrintScreen, media and F13+ likewise.- else => .ignore,- };-}--fn fixterms(params: []const u8) Key {- var it = std.mem.splitScalar(u8, params, ';');- _ = it.next();- var mods = leadingInt(it.next() orelse "1");- if (mods > 0) mods -= 1;- return mapCode(leadingInt(it.next() orelse "0"), mods);-}--fn mapCode(code: u32, mods: u32) Key {- const ctrl = mods & 4 != 0;- const shift = mods & 1 != 0;- const alt = mods & 2 != 0;- const super = mods & 8 != 0 or held & 8 != 0;- if (code == 13 or code == 10) {- if (in_paste) return .{ .char = '\n' };- return if (shift or alt) .shift_enter else .enter;- }- if (code == 9) return if (shift) .shift_tab else .tab;- if (code == 27) return .escape;- if (code == 127 or code == 8) {- if (super or ctrl) return .delete_to_start;- if (alt or held & 2 != 0) return .delete_word;- return .backspace;- }- if (code >= 1 and code <= 26) return .{ .ctrl = 'a' + @as(u8, @intCast(code - 1)) };- if (code >= 32 and code < 127) {- const ch: u8 = @intCast(code);- if ((ctrl or super) and !shift and (ch == 'z' or ch == 'Z')) return .undo;- if (ctrl and ch >= 'a' and ch <= 'z') return .{ .ctrl = ch };- if (ctrl and ch >= 'A' and ch <= 'Z') return .{ .ctrl = ch + 32 };- if (shift) return .{ .char = shiftedAscii(ch) };- return .{ .char = ch };- }- if (code >= 57344 and code <= 57454) return .ignore; // functional block, handled upstream- if (code >= 128 and code <= 0x10ffff) return .{ .codepoint = @intCast(code) };- // Unknown code: inert. Only a real Esc (27) may become .escape.- return .ignore;-}--/// Kitty/modifyOtherKeys report the unshifted key + Shift. US layout.-fn shiftedAscii(ch: u8) u8 {- return switch (ch) {- 'a'...'z' => ch - 32,- '1' => '!',- '2' => '@',- '3' => '#',- '4' => '$',- '5' => '%',- '6' => '^',- '7' => '&',- '8' => '*',- '9' => '(',- '0' => ')',- '-' => '_',- '=' => '+',- '[' => '{',- ']' => '}',- '\\' => '|',- ';' => ':',- '\'' => '"',- ',' => '<',- '.' => '>',- '/' => '?',- '`' => '~',- else => ch,- };-}--fn sgrMouse(params: []const u8, down: bool) Key {- if (params.len < 6 or params[0] != '<' or params[1] == ';' or params[params.len - 1] == ';' or- std.mem.indexOf(u8, params, ";;") != null or std.mem.indexOfScalar(u8, params, ':') != null) return .ignore;- for (params[1..]) |c| if ((c < '0' or c > '9') and c != ';') return .ignore;- var it = std.mem.splitScalar(u8, params[1..], ';');- const btn = leadingInt(it.next() orelse "0");- const x = leadingInt(it.next() orelse "1");- const y = leadingInt(it.next() orelse "1");- return .{ .mouse = .{- .btn = @intCast(@min(btn, 255)),- .x = @intCast(@min(x, 999)),- .y = @intCast(@min(y, 999)),- .down = down,- } };-}--pub fn leadingInt(s: []const u8) u32 {- // Saturating (#545): hostile 10+-digit params used to abort the TUI;- // maxInt safely decodes as ignore/clamped coords. Used by key_orphan too.- var n: u32 = 0;- for (s) |c| {- if (c < '0' or c > '9') break;- n = n *| 10 +| (c - '0');- }- return n;-}diff --git a/TUI/key_loop_tests.zig b/TUI/key_loop_tests.zigdeleted file mode 100644index e6d5b02f..00000000--- a/TUI/key_loop_tests.zig+++ /dev/null@@ -1,506 +0,0 @@-//! The read-loop half of key.zig's battery: everything that only shows up-//! ACROSS a read boundary. Parked out of key_tests.zig under the 600-line-//! ceiling.--const std = @import("std");-const key = @import("key.zig");-const Key = key.Key;-const next = key.next;--/// run.zig's read loop, minus the terminal: fixed input buffer, parse to-/// exhaustion, carry the unparsed tail into the next read. Regressions in the-/// carry/rewind contract only show up across a read boundary, so the debris-/// tests have to drive the real thing.-const Loop = struct {- inbuf: [4096]u8 = undefined,- pending: usize = 0,- typed: std.array_list.Managed(u8),- mice: usize = 0,- arrows: usize = 0,- paste_starts: usize = 0,- paste_ends: usize = 0,- bg_reports: usize = 0,-- fn init(a: std.mem.Allocator) Loop {- key.resetInputState();- return .{ .typed = std.array_list.Managed(u8).init(a) };- }- fn deinit(self: *Loop) void {- self.typed.deinit();- }-- fn read(self: *Loop, bytes: []const u8) !void {- @memcpy(self.inbuf[self.pending .. self.pending + bytes.len], bytes);- const n = key.joinOrphanHead(&self.inbuf, self.pending + bytes.len);- var i: usize = 0;- while (next(self.inbuf[0..n], &i)) |k| switch (k) {- .char => |c| try self.typed.append(c),- .codepoint => try self.typed.append('?'),- .mouse => self.mice += 1,- .left, .right, .up, .down => self.arrows += 1,- .escape => try self.typed.append('E'), // a phantom Escape cancels the turn- .paste_start => self.paste_starts += 1,- .paste_end => self.paste_ends += 1,- .bg_report => self.bg_reports += 1,- else => {},- };- self.pending = if (i < n) blk: {- const rest = n - i;- std.mem.copyForwards(u8, self.inbuf[0..rest], self.inbuf[i..n]);- break :blk rest;- } else 0;- }-- /// run.zig's `.escape_key` verdict: a lone pending ESC outlived the #94- /// grace, so a real Escape is delivered — but the byte is carried, not- /// thrown away.- fn stallEscape(self: *Loop) !void {- key.abandonSequence(self.inbuf[0..self.pending], .escape);- self.pending = 0;- try self.typed.append('E');- }-- /// run.zig's `.drop` verdict: carry the head, arm the sweeper, and close- /// out a paste that can no longer be closed by its own marker.- fn stallDrop(self: *Loop) void {- key.abandonSequence(self.inbuf[0..self.pending], .dropped);- self.pending = 0;- if (key.inPaste()) {- key.endPaste();- self.paste_ends += 1;- }- }-- /// run.zig's short genuine-Escape carry elapsing. Dropped non-lone heads- /// retain their exact framing until the full recovery interval ends.- fn expireCarry(_: *Loop) void {- key.expireOrphanHead();- }-- /// run.zig's arm window elapsing (`stall.armExpired`): the loop disarms the- /// sweeper before parsing, because a claim that a head was "just" dropped- /// goes stale. Strictly the longer of the two windows.- fn expireArm(self: *Loop) void {- self.expireCarry();- key.armOrphan(false);- }-};--test "dropping a sequence clears kitty modifiers without clearing recovery" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- key.held = 8; // a Super release was the sequence that got lost- try loop.read("\x1b[57444;1:3");- loop.stallDrop();- try std.testing.expectEqual(@as(u32, 0), key.held);- var tail: [32]u8 = undefined;- tail[0] = 'u';- const n = key.joinOrphanHead(&tail, 1);- var i: usize = 0;- try std.testing.expectEqual(Key.ignore, next(tail[0..n], &i).?);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);-}--test "SGR motion flood chopped at every byte offset never types a character" {- key.armOrphan(false);- // The exact bytes the user saw on the bottom row, plus one hover report.- const flood = "\x1b[<39;7;32M\x1b[<39;4;32M\x1b[<39;3;33M\x1b[<39;1;33M\x1b[<35;80;24M";- var cut: usize = 0;- while (cut <= flood.len) : (cut += 1) {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read(flood[0..cut]);- try loop.read(flood[cut..]);- try std.testing.expectEqualStrings("", loop.typed.items);- try std.testing.expectEqual(@as(usize, 5), loop.mice);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }-}--test "debris after a dropped ESC head is consumed, not typed — even split again" {- // run.zig drops a pending head that never completed and arms us; the tail- // arrives alone, and may itself straddle the next read boundary.- const tail = "39;7;32M\x1b[<39;4;32M";- var cut: usize = 0;- while (cut <= tail.len) : (cut += 1) {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- key.armOrphan(true);- defer key.armOrphan(false);- try loop.read(tail[0..cut]);- try loop.read(tail[cut..]);- try std.testing.expectEqualStrings("", loop.typed.items);- try std.testing.expectEqual(@as(usize, 1), loop.mice);- }-}--test "typed and pasted text survives the debris guard (0x1f, [12], 1e5)" {- key.armOrphan(false);- const cases = [_][]const u8{- "const x = 0x1f;",- "v1e5 [12] 2xM",- "1.5]",- "0x1f",- "[12]",- "1e5",- "grep -n '39;7;32M' log", // debris-shaped text, but not at a read head- "step 3 of 10 (2m30s)",- };- for (cases) |text| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read(text);- try std.testing.expectEqualStrings(text, loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.mice);- }- // Byte-at-a-time typing is the same string.- var slow = Loop.init(std.testing.allocator);- defer slow.deinit();- for ("0x1f + [12] = 1e5") |c| try slow.read(&[_]u8{c});- try std.testing.expectEqualStrings("0x1f + [12] = 1e5", slow.typed.items);-}--test "bracketed paste of debris-shaped code reaches the composer intact" {- key.armOrphan(false);- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[200~");- try loop.read("39;7;32M and 0x1f");- try loop.read("\x1b[201~");- try std.testing.expectEqualStrings("39;7;32M and 0x1f", loop.typed.items);-}--test "a body that arrives after the escape_key verdict rejoins its ESC (#530)" {- // ssh/tmux cuts right after the 0x1b of a sequence and the next segment is- // >50ms late. run.zig delivers Escape (the E below) — but throwing the ESC- // away typed the whole body into the composer on top of that.- const bodies = [_][]const u8{ "[<35;80;24M", "[M !!", "[A", "[3~", "OA", "]11;rgb:14/14/14\x07" };- for (bodies) |body| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b");- try loop.stallEscape();- try loop.read(body);- try std.testing.expectEqualStrings("E", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }- // ...and the rejoined sequences are the real events, not merely swallowed.- var mouse = Loop.init(std.testing.allocator);- defer mouse.deinit();- try mouse.read("\x1b");- try mouse.stallEscape();- try mouse.read("[<35;80;24M\x1b[M !!");- try std.testing.expectEqual(@as(usize, 2), mouse.mice);- var osc = Loop.init(std.testing.allocator);- defer osc.deinit();- try osc.read("\x1b");- try osc.stallEscape();- try osc.read("]11;rgb:14/14/14\x07");- try std.testing.expectEqual(@as(usize, 1), osc.bg_reports);-}--test "carry-expired unambiguous mouse kitty and OSC bodies recover (#537)" {- const cases = [_]struct {- body: []const u8,- mice: usize = 0,- arrows: usize = 0,- bg_reports: usize = 0,- }{- .{ .body = "[M !!", .mice = 1 },- .{ .body = "[<35;80;24M", .mice = 1 },- .{ .body = "[57350;1u", .arrows = 1 },- .{ .body = "]11;rgb:14/14/14\x07", .bg_reports = 1 },- .{ .body = "]11;rgb:1414/1414/1414\x1b\\", .bg_reports = 1 },- };- for (cases) |case| for (0..case.body.len + 1) |cut| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b");- try loop.stallEscape();- loop.expireCarry();- try loop.read(case.body[0..cut]);- try loop.read(case.body[cut..]);- try std.testing.expectEqualStrings("E", loop.typed.items);- try std.testing.expectEqual(case.mice, loop.mice);- try std.testing.expectEqual(case.arrows, loop.arrows);- try std.testing.expectEqual(case.bg_reports, loop.bg_reports);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- };-}--test "carry-expired paste start is real before control-bearing same-read payload (#537)" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b");- try loop.stallEscape();- loop.expireCarry();- try loop.read("[200~left\x11\x03\nright");- try std.testing.expectEqual(@as(usize, 1), loop.paste_starts);- try std.testing.expect(key.inPaste());- try std.testing.expectEqualStrings("Eleft\nright", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- try loop.read("\x1b[201~");- try std.testing.expectEqual(@as(usize, 1), loop.paste_ends);- try std.testing.expect(!key.inPaste());-}--test "post-Escape byte-at-a-time human and exact tails stay text (#537)" {- const human = [_][]const u8{- "[Alice]",- "[Home]",- "[Down]",- "[A",- "OA",- "3u apples",- "[3~ apples",- "Orange",- };- for (human) |text| for ([_]bool{ false, true }) |expire| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b");- try loop.stallEscape();- if (expire) loop.expireCarry();- for (text) |c| try loop.read(&[_]u8{c});- try std.testing.expectEqualStrings("E", loop.typed.items[0..1]);- try std.testing.expectEqualStrings(text, loop.typed.items[1..]);- };-- // After the 1s arm window even an exact CSI token is ordinary text.- var expired = Loop.init(std.testing.allocator);- defer expired.deinit();- try expired.read("\x1b");- try expired.stallEscape();- expired.expireArm();- try expired.read("[A");- try std.testing.expectEqualStrings("E[A", expired.typed.items);-}--test "a dropped head rejoins its tail whatever the split (#531/#546)" {- // Every shape takeOrphanCsi structurally cannot sweep: a split ON the- // separator, a non-mouse final, an OSC body.- const cases = [_]struct { head: []const u8, tail: []const u8, mice: usize }{- .{ .head = "\x1b[<35;80", .tail = ";24M", .mice = 1 },- .{ .head = "\x1b[", .tail = "A", .mice = 0 },- .{ .head = "\x1b[3", .tail = "~", .mice = 0 },- .{ .head = "\x1b]11;rgb:1c", .tail = "1c/1c1c/1c1c\x07", .mice = 0 },- .{ .head = "\x1b[<39;7;32", .tail = "M", .mice = 1 },- };- for (cases) |c| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read(c.head);- loop.stallDrop();- try loop.read(c.tail);- try std.testing.expectEqualStrings("", loop.typed.items);- try std.testing.expectEqual(c.mice, loop.mice);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }-}--test "a head whose tail never comes never eats the keystrokes that follow" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[<35;80");- loop.stallDrop();- // The user gave up waiting and resumed typing: nothing is glued on, and- // the armed sweeper must not swallow the words either.- try loop.read("hello world");- try std.testing.expectEqualStrings("hello world", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);-}--test "the orphan arm covers exactly one lost head (#531)" {- // Latched, the sweeper kept eating: `3u apples` reached the composer as- // ` apples`, and a lone `3` was held pending until the loop dropped it.- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- key.armOrphan(true);- try loop.read("39;7;32M");- try std.testing.expectEqual(@as(usize, 0), loop.mice);- try loop.read("3u apples");- try std.testing.expectEqualStrings("3u apples", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);-- var slow = Loop.init(std.testing.allocator);- defer slow.deinit();- key.armOrphan(true);- try slow.read("39;7;32M");- try slow.read("3");- try std.testing.expectEqual(@as(usize, 0), slow.pending);- try std.testing.expectEqualStrings("3", slow.typed.items);- key.armOrphan(false);-}--test "a headless debris tail that opens on a separator is eaten, not typed (#546)" {- // The head is gone for good (no carry): the sweeper is the only guard- // left, and it must accept the `;`-led continuation while armed.- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- key.armOrphan(true);- try loop.read(";24M");- try std.testing.expectEqualStrings("", loop.typed.items);- // Never a phantom click at (1,1): the coordinates cannot be reconstructed.- try std.testing.expectEqual(@as(usize, 0), loop.mice);- // Split again, on the final byte this time.- var split = Loop.init(std.testing.allocator);- defer split.deinit();- key.armOrphan(true);- try split.read("3");- try split.read("u");- try std.testing.expectEqualStrings("", split.typed.items);- key.armOrphan(false);- // Unarmed, the very same bytes are the user typing.- var typed = Loop.init(std.testing.allocator);- defer typed.deinit();- try typed.read(";24M");- try std.testing.expectEqualStrings(";24M", typed.typed.items);-}--test "a paste whose end marker is lost still closes (#532/#536/#548)" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[200~");- try loop.read("hello");- try loop.read("\x1b[201");- try std.testing.expect(key.inPaste());- loop.stallDrop(); // ~2s of silence: give up on the marker- try std.testing.expect(!key.inPaste());- try std.testing.expectEqual(@as(usize, 1), loop.paste_ends);- // The late `~` rejoins its head, so it is never typed either.- try loop.read("~");- try std.testing.expectEqualStrings("hello", loop.typed.items);- // And the debris guard is live again, because the paste really did close.- try loop.read("\x1b[<39;7;32M");- try std.testing.expectEqualStrings("hello", loop.typed.items);- try std.testing.expectEqual(@as(usize, 1), loop.mice);-}--test "an unterminated paste releases on the idle timeout (#548)" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[200~body");- try std.testing.expect(key.inPaste());- key.endPaste(); // run.zig's paste_idle_ms sweep- try std.testing.expect(!key.inPaste());- // Back to a normal composer: debris is eaten again instead of typed.- try loop.read("\x1b[<39;7;32M");- try std.testing.expectEqualStrings("body", loop.typed.items);- try std.testing.expectEqual(@as(usize, 1), loop.mice);-}--test "a real multi-read paste is untouched by any of the recovery paths" {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[200~");- try loop.read("39;7;32M and 0x1f ");- try loop.read("second chunk ;24M");- try loop.read("\x1b[201~");- try std.testing.expectEqualStrings("39;7;32M and 0x1f second chunk ;24M", loop.typed.items);- try std.testing.expectEqual(@as(usize, 1), loop.paste_ends);- try std.testing.expectEqual(@as(usize, 0), loop.mice);- try std.testing.expect(!key.inPaste());-}--test "a stale debris arm never eats the token the user types later" {- // The arm had no clock at all, so it stayed live until something happened- // to consume it: `3u apples` reached the composer as ` apples` twelve- // seconds after the head was dropped, from a keyboard (Alt+[ on a- // meta-sending terminal is enough to lose a head).- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[<35;80");- loop.stallDrop();- loop.expireArm(); // ~1s later: the claim is stale- try loop.read("3u apples");- try std.testing.expectEqualStrings("3u apples", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.mice);- try std.testing.expectEqual(@as(usize, 0), loop.pending);-- // Human-speed typing lost even more, through the `.partial` hold: `2m- // later` arrived as `m later` with the `2m` swallowed as a mouse report.- var slow = Loop.init(std.testing.allocator);- defer slow.deinit();- try slow.read("\x1b[<35;80");- slow.stallDrop();- slow.expireArm();- for ("2m later") |c| try slow.read(&[_]u8{c});- try std.testing.expectEqualStrings("2m later", slow.typed.items);- try std.testing.expectEqual(@as(usize, 0), slow.mice);- try std.testing.expectEqual(@as(usize, 0), slow.pending);-}--test "late debris tails are eaten while armed and typed when they are not" {- // The head is unavailable, broad recovery is armed, and the tail lands- // late: `take` rejected every final outside `M/m/u/~`, so `2A`, `~`, `[A`- // and a split paste START marker all typed themselves into the composer.- const tails = [_][]const u8{ "2A", "~", "[A", "[3~", "1;2D", "[H", "[Z", "2F" };- for (tails) |tail| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- key.armOrphan(true);- defer key.armOrphan(false);- try loop.read(tail);- try std.testing.expectEqualStrings("", loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }-- // A paste START marker split off its ESC: the marker goes, the body is- // still text, and the arm is spent on that one fragment.- var split = Loop.init(std.testing.allocator);- defer split.deinit();- key.armOrphan(true);- try split.read("[200~PASTED");- try std.testing.expectEqualStrings("PASTED", split.typed.items);- key.armOrphan(false);-- // Unarmed, every one of those is somebody typing and must arrive intact —- // this is the half the widened final set must not regress.- for (tails) |tail| {- var typed = Loop.init(std.testing.allocator);- defer typed.deinit();- try typed.read(tail);- try std.testing.expectEqualStrings(tail, typed.typed.items);- try std.testing.expectEqual(@as(usize, 0), typed.mice);- }- // ...including the shapes the widening comes closest to: a bare `[` really- // is the start of typed text when no head was lost.- var text = Loop.init(std.testing.allocator);- defer text.deinit();- try text.read("[12] and 3H at 2:30");- try std.testing.expectEqualStrings("[12] and 3H at 2:30", text.typed.items);-}--test "an armed sweeper still never swallows a word the user typed" {- // The widened final set includes `h` and `l` (CSI mode replies), which are- // also the first letters of ordinary words. They may only ever count- // BEHIND an orphaned `[` or a parameter run, never bare.- const words = [_][]const u8{ "hello world", "list the files", "done", "Fix it", "Zoom" };- for (words) |w| {- var loop = Loop.init(std.testing.allocator);- defer loop.deinit();- try loop.read("\x1b[<35;80");- loop.stallDrop();- loop.expireCarry(); // the head is spent; the ARM is what is on trial- try loop.read(w);- try std.testing.expectEqualStrings(w, loop.typed.items);- try std.testing.expectEqual(@as(usize, 0), loop.pending);- }- key.armOrphan(false);-}--test "Alt+Left as ESC ESC CSI does not cancel (#524)" {- var same = Loop.init(std.testing.allocator);- defer same.deinit();- try same.read("\x1b\x1b[D");- try std.testing.expectEqualStrings("", same.typed.items);- try std.testing.expectEqual(@as(usize, 1), same.arrows);-- var split = Loop.init(std.testing.allocator);- defer split.deinit();- try split.read("\x1b");- try split.read("\x1b[D");- try std.testing.expectEqualStrings("", split.typed.items);- try std.testing.expectEqual(@as(usize, 1), split.arrows);-}diff --git a/TUI/key_orphan.zig b/TUI/key_orphan.zigdeleted file mode 100644index 4ee5523a..00000000--- a/TUI/key_orphan.zig+++ /dev/null@@ -1,593 +0,0 @@-//! Escape-sequence debris recovery, parked out of key.zig under the 600-line-//! ceiling.-//!-//! Two halves of one problem: the read loop gives up on a truncated escape-//! head once the terminal goes quiet (an ssh/tmux hiccup mid-sequence), and-//! that sequence's tail can still land on a LATER read with its introducer-//! gone.-//!-//! * `stashHead`/`joinHead` keep the abandoned head for the next read and-//! re-attach it when the new bytes really do complete it. A dropped-//! non-lone head keeps that exact framing for the full recovery interval;-//! a delivered Escape keeps its shorter, ambiguity-limited carry. The tail-//! then parses as the thing it always was, with no shape guessing-//! (#530/#531).-//! * `take` is the fallback once that exact carry is gone. After a genuine-//! Escape it accepts only bodies distinguishable from prose (mouse, kitty,-//! paste, terminated OSC); short CSI/SS3 spellings remain text (#537).--const std = @import("std");-const key = @import("key.zig");-const recover = @import("key_recover.zig");-const Key = key.Key;--/// Set by the read loop when it abandons a truncated escape head: the NEXT-/// read may legitimately open with that sequence's orphaned tail.-pub var armed: bool = false;-/// Narrow arm used after a lone ESC was delivered as a genuine key. Its late-/// body must retain a CSI/SS3/OSC introducer; accepting headless parameter runs-/// here would eat ordinary text such as `3u apples` after a real Escape.-pub var escape_armed: bool = false;--/// End offset of the last fragment consumed from the buffer currently being-/// parsed, so back-to-back debris keeps being eaten while a digit run that-/// follows real input never is. `maxInt` = no run in progress.-pub var end: usize = std.math.maxInt(usize);--/// Longest head worth carrying. Real CSI/OSC heads are far shorter; anything-/// bigger is a parser wedge, not a sequence.-const max_head = 64;-var head: [max_head]u8 = undefined;-var head_len: usize = 0;-const RecoveredPaste = enum { start, end };-var recovered_event: ?Key = null;--pub fn reset() void {- disarm();- end = std.math.maxInt(usize);- head_len = 0;- recovered_event = null;-}--pub fn armDropped() void {- armed = true;- escape_armed = false;-}--pub fn armEscape() void {- armed = false;- escape_armed = true;-}--pub fn disarm() void {- armed = false;- escape_armed = false;- head_len = 0;- recovered_event = null;-}--/// Expire only the short exact carry used after a genuine Escape. A non-lone-/// sequence that the loop actually dropped is stronger evidence, so its exact-/// framing remains until the broad recovery interval expires or the next read-/// spends it.-pub fn expireHead() void {- if (!armed) head_len = 0;-}--/// Keep the head the loop just gave up on. `joinHead` may extend it with valid-/// partial tails, but any mismatch spends it before fresh input is parsed.-pub fn stashHead(bytes: []const u8) void {- head_len = 0;- recovered_event = null;- if (bytes.len == 0 or bytes.len > max_head) return;- @memcpy(head[0..bytes.len], bytes);- head_len = bytes.len;-}--const PasteProgress = union(enum) {- partial,- complete: struct { kind: RecoveredPaste, tail_len: usize },-};--fn pasteProgress(h: []const u8, t: []const u8) ?PasteProgress {- const markers = [_]struct { bytes: []const u8, kind: RecoveredPaste }{- .{ .bytes = "\x1b[200~", .kind = .start },- .{ .bytes = "\x1b[201~", .kind = .end },- };- const n = h.len + t.len;- for (markers) |marker| {- if (h.len >= marker.bytes.len) continue;- var k: usize = 0;- while (k < @min(n, marker.bytes.len) and at(h, t, k) == marker.bytes[k]) : (k += 1) {}- if (k != @min(n, marker.bytes.len)) continue;- if (n < marker.bytes.len) return .partial;- return .{ .complete = .{ .kind = marker.kind, .tail_len = marker.bytes.len - h.len } };- }- return null;-}--/// A dropped exact head may itself be split over several late reads. Retain-/// only prefixes that can still become the same framed sequence, under the-/// same 64-byte and one-second bounds as the original head.-fn validPartial(h: []const u8, t: []const u8) bool {- const n = h.len + t.len;- if (n == 0 or n > max_head or at(h, t, 0) != 0x1b) return false;- if (n == 1) return true;- switch (at(h, t, 1)) {- 0x1b => return recover.legacyCsiPrefix(h, t, n),- 'O' => return n < 3,- '[' => {- var k: usize = 2;- while (k < n) : (k += 1) {- const c = at(h, t, k);- if (c >= 0x20 and c <= 0x3f) continue;- if (k == 2 and c == 'M') {- if (n >= 6) return false;- for (k + 1..n) |payload| if (at(h, t, payload) == 0x1b) return false;- return true;- }- return false; // a final is complete or invalid, never partial- }- return true;- },- ']', 'P', '_', '^', 'X' => {- var k: usize = 2;- while (k < n) : (k += 1) {- const c = at(h, t, k);- if (c == 0x07 or c == '\r' or c == '\n') return false;- if (c == 0x1b) return k + 1 == n;- }- return true;- },- else => return false,- }-}--/// A full read leaves no room to prepend a saved head. Return the event decoded-/// from that head and the exact leading tail bytes `joinHead` removed.-pub fn takeRecoveredEvent() ?Key {- const event = recovered_event orelse return null;- recovered_event = null;- return event;-}--/// Re-attach a stashed head when a later read completes it. Valid dropped-head-/// prefixes accumulate across reads; an invalid or oversized tail disarms and-/// is processed as fresh input, so recovery remains bounded and fails closed.-pub fn joinHead(buf: []u8, n: usize) usize {- const h = head_len;- if (h == 0 or n == 0) return n;- const dropped = armed;- if (recover.legacyCsiProse(head[0..h], buf[0..n], h + n)) |prefix_len| {- if (prefix_len + n <= buf.len) {- std.mem.copyBackwards(u8, buf[prefix_len .. prefix_len + n], buf[0..n]);- @memcpy(buf[0..prefix_len], head[2..h]);- disarm();- return prefix_len + n;- }- }- const progress = if (dropped) pasteProgress(head[0..h], buf[0..n]) else null;- if (completesWithEvidence(head[0..h], buf[0..n], dropped)) {- if (h + n <= buf.len) {- std.mem.copyBackwards(u8, buf[h .. h + n], buf[0..n]);- @memcpy(buf[0..h], head[0..h]);- disarm();- return n + h;- }- if (recover.completed(head[0..h], buf[0..n])) |recovered| {- std.mem.copyForwards(u8, buf[0 .. n - recovered.tail_len], buf[recovered.tail_len..n]);- disarm();- recovered_event = recovered.event;- return n - recovered.tail_len;- }- } else if (dropped and ((if (progress) |p| switch (p) {- .partial => true,- .complete => false,- } else false) or validPartial(head[0..h], buf[0..n]))) {- if (h + n <= max_head) {- @memcpy(head[h .. h + n], buf[0..n]);- head_len = h + n;- return 0;- }- }- // These bytes do not finish the saved head. They are fresh input: broad- // recovery must not reinterpret byte-at-a-time prose as a cursor key.- head_len = 0;- if (dropped) disarm();- return n;-}--fn at(h: []const u8, t: []const u8, k: usize) u8 {- return if (k < h.len) h[k] else t[k - h.len];-}--fn alignedFields(h: []const u8, t: []const u8, start: usize, end_at: usize, semicolons: ?usize, colon: bool) bool {- var semis: usize = 0;- var need_digit = true;- for (start..end_at) |k| {- const c = at(h, t, k);- if (c >= '0' and c <= '9') {- need_digit = false;- } else if (!need_digit and (c == ';' or (colon and c == ':'))) {- if (c == ';') semis += 1;- need_digit = true;- } else return false;- }- return !need_digit and (semicolons == null or semis == semicolons.?);-}--fn framedDroppedSuffix(h: []const u8, t: []const u8, final_at: usize, final: u8) bool {- if ((final == 'M' or final == 'm') and final_at > 3 and at(h, t, 2) == '<')- return alignedFields(h, t, 3, final_at, 2, false);- if (final == 'u') return alignedFields(h, t, 2, final_at, null, true);- if (final != '~' or final_at != 5) return false;- return at(h, t, 2) == '2' and at(h, t, 3) == '0' and- (at(h, t, 4) == '0' or at(h, t, 4) == '1');-}--pub fn isSeqIntroducer(c: u8) bool {- return switch (c) {- '[', 'O', ']', 'P', '_', '^', 'X' => true,- else => false,- };-}--/// Does `t` finish the truncated escape `h`? Only a join that yields a-/// COMPLETE sequence is worth making: after a give-up stall the next bytes are-/// just as likely to be a human resuming typing, and gluing a stale head onto-/// those would eat a keystroke.-pub fn completes(h: []const u8, t: []const u8) bool {- return completesWithEvidence(h, t, false);-}--fn completesWithEvidence(h: []const u8, t: []const u8, dropped: bool) bool {- const n = h.len + t.len;- if (h.len == 0 or t.len == 0 or h[0] != 0x1b or n < 2) return false;- // The first ESC was already delivered by the bounded genuine-Escape path;- // do not turn its late second ESC into a new double-Escape candidate.- if (!dropped and h.len == 1 and t[0] == 0x1b) return false;- switch (at(h, t, 1)) {- 0x1b => return if (n > 2 and at(h, t, 2) == '[') recover.legacyCsiComplete(h, t, n, dropped) else true,- 'O' => return n >= 3 and isSs3Final(at(h, t, 2)) and- (n == 3 or at(h, t, 3) < 0x20 or at(h, t, 3) == 0x7f),- '[' => {- var k: usize = 2;- while (k < n) : (k += 1) {- const c = at(h, t, k);- if (c >= 0x20 and c <= 0x3f) continue; // params + intermediates- if (!isInputFinal(c)) return false;- if (k == 2 and c == 'M') {- if (n < 6) return false; // X10 is CSI M plus three bytes- for (3..6) |payload| if (at(h, t, payload) == 0x1b) return false;- return true;- }- // A complete cursor key followed by printable bytes is also- // ordinary text (`[Alice]`, `[Home]`). Favor that reading.- // Bracketed-paste start is the exception: suffix bytes are its- // payload and must be parsed with paste mode already latched.- const next_is_control = k + 1 < n and- (at(h, t, k + 1) < 0x20 or at(h, t, k + 1) == 0x7f);- return k + 1 == n or next_is_control or (dropped and framedDroppedSuffix(h, t, k, c)) or- (k == 5 and c == '~' and at(h, t, 2) == '2' and at(h, t, 3) == '0' and at(h, t, 4) == '0');- }- return false;- },- ']', 'P', '_', '^', 'X' => {- var k: usize = 2;- while (k < n) : (k += 1) {- const c = at(h, t, k);- if (c == 0x07) return true; // BEL- if (c == 0x1b) return k + 1 < n and at(h, t, k + 1) == '\\'; // ST- if (c == 0x0d or c == 0x0a) return false; // typed text, not a reply- }- return false;- },- // A lone ESC in front of ordinary text is an Alt chord, and joining it- // would SWALLOW that character. Typing it is the lesser harm.- else => return false,- }-}--/// CSI finals a terminal actually sends on stdin. Deliberately narrow: the-/// whole 0x40..0x7e range would let a stale head glue itself onto the first-/// letter a human types after the stall.-fn isInputFinal(c: u8) bool {- return switch (c) {- 'A'...'F', 'H', 'M', 'P'...'S', 'Z', 'm', 'u', '~' => true,- else => false,- };-}--/// Finals that count only while `armed`. Cursor/mode replies (`[2A`, `[H`,-/// `[?1003l`) reach the sweeper when an oversized head could not be retained;-/// typing `2A` into the composer is exactly the debris this file exists to eat.-/// Unarmed they stay ordinary text — `2A`, `3H` and `1F`-/// are all things people write, and the suite pins them.-fn isArmedFinal(c: u8) bool {- return switch (c) {- 'A'...'D', 'F', 'H', 'Z', 'h', 'l' => true,- else => false,- };-}--fn isFinal(c: u8, armed_now: bool) bool {- return c == 'M' or c == 'm' or c == 'u' or c == '~' or (armed_now and isArmedFinal(c));-}--fn isSs3Final(c: u8) bool {- return switch (c) {- 'A'...'D', 'F', 'H', 'M', 'P'...'S' => true,- else => false,- };-}--fn delimitedDecimal(bytes: []const u8, colon: bool) bool {- var separators: usize = 0;- var need_digit = true;- for (bytes) |c| {- if (c >= '0' and c <= '9') {- need_digit = false;- continue;- }- if (need_digit or (c != ';' and (!colon or c != ':'))) return false;- separators += 1;- need_digit = true;- }- return !need_digit and separators > 0;-}--/// Shapes specific enough to recover after the exact ESC carry is gone.-/// `[A`, `[H`, `[3~`, and every SS3 token are intentionally absent: at a read-/// boundary they are indistinguishable from prefixes of human prose.-fn unambiguousLateCsi(params: []const u8, final: u8) bool {- if (final == '~') return std.mem.eql(u8, params, "200") or std.mem.eql(u8, params, "201");- if ((final == 'M' or final == 'm') and params.len > 1 and params[0] == '<')- return std.mem.count(u8, params[1..], ";") == 2 and delimitedDecimal(params[1..], false);- return final == 'u' and delimitedDecimal(params, true);-}--/// Recover the unambiguous body of a sequence whose lone ESC was already-/// delivered as a genuine key. Ambiguous short CSI stays ordinary text.-fn takeLateCsi(bytes: []const u8, i: *usize, dropped_head: bool) Orphan {- const start = i.*; // bytes[start] is '['- var k = start + 1;- while (k < bytes.len) : (k += 1) {- const c = bytes[k];- if (c == 0x1b) {- i.* = k;- key.abandonSequence("", .none);- return .{ .took = .ignore };- }- if (c >= 0x20 and c <= 0x3f) continue;- if (!isInputFinal(c)) return .none;- const params = bytes[start + 1 .. k];- if (c == 'M' and params.len == 0) return takeLateX10(bytes, i, k);- if (!unambiguousLateCsi(params, c)) {- if (!dropped_head) return .none;- const printable_suffix = k + 1 < bytes.len and bytes[k + 1] >= 0x20 and bytes[k + 1] != 0x7f;- if (printable_suffix) return .none;- }- i.* = k + 1;- return .{ .took = key.decodeCsi(params, c) };- }- return if (bytes.len - start <= max_head) .partial else .none;-}--fn takeLateX10(bytes: []const u8, i: *usize, final_at: usize) Orphan {- const payload = final_at + 1;- const available_end = @min(payload + 3, bytes.len);- if (std.mem.indexOfScalar(u8, bytes[payload..available_end], 0x1b)) |offset| {- i.* = payload + offset;- key.abandonSequence("", .none);- return .{ .took = .ignore };- }- if (payload + 3 > bytes.len) return .partial;- i.* = payload + 3;- return .{ .took = key.decodeX10(bytes[payload .. payload + 3]) };-}--fn isHex(c: u8) bool {- return (c >= '0' and c <= '9') or (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'F');-}--/// Only the OSC reply this TUI solicits may remain pending across another read.-/// A complete BEL/ST-terminated OSC is exact and can always be discarded.-fn osc11Prefix(body: []const u8) bool {- const lead = "11;rgb:";- if (body.len <= lead.len) return std.mem.startsWith(u8, lead, body);- if (!std.mem.startsWith(u8, body, lead)) return false;- var digits: usize = 0;- var slashes: usize = 0;- for (body[lead.len..]) |c| {- if (isHex(c)) {- digits += 1;- if (digits > 4) return false;- } else if (c == '/' and (digits == 2 or digits == 4) and slashes < 2) {- digits = 0;- slashes += 1;- } else return false;- }- return true;-}--fn takeLateOsc(bytes: []const u8, i: *usize) Orphan {- const start = i.*; // bytes[start] is ']'- var j = start + 1;- while (j < bytes.len) : (j += 1) {- if (bytes[j] == 0x07) {- i.* = j + 1;- return .{ .took = key.oscReply(']', bytes[start + 1 .. j]) };- }- if (bytes[j] == 0x1b) {- if (j + 1 < bytes.len) {- if (bytes[j + 1] != '\\') {- i.* = j;- key.abandonSequence("", .none);- return .{ .took = .ignore };- }- i.* = j + 2;- return .{ .took = key.oscReply(']', bytes[start + 1 .. j]) };- }- return if (osc11Prefix(bytes[start + 1 .. j])) .partial else .none;- }- if (bytes[j] == '\r' or bytes[j] == '\n') return .none;- }- return if (bytes.len - start <= 128 and osc11Prefix(bytes[start + 1 ..])) .partial else .none;-}--fn takeEscapeBody(bytes: []const u8, i: *usize) Orphan {- return switch (bytes[i.*]) {- '[' => takeLateCsi(bytes, i, false),- ']' => takeLateOsc(bytes, i),- else => .none, // every short SS3 body is prose-ambiguous without ESC- };-}--pub const Orphan = union(enum) {- /// Not debris — hand the bytes to the normal parser (typed text).- none,- /// Debris shape, cut short by the read boundary: hold, do not type it.- partial,- took: Key,-};--/// CSI debris after a lost ESC (`7444;9u`, `39;33;23M`, `<35;80;24M`). Never a-/// letter and never Escape/Ctrl-C — those cancel or kill the turn.-///-/// Strictly shaped, because this runs against text a human may have typed: an-/// optional `<`, then digits with `;`/`:` separators, then a MOUSE or CSI-u-/// final (`M`/`m`/`u`/`~`). Any other terminator is text — accepting the whole-/// 0x40..0x7e range ate `0x1f` (final `x`), `[12]` (final `]`) and `1e5`-/// (final `e`). A run with neither `<` nor a separator (`3u`) is debris only-/// while `armed` says the loop really did drop a truncated sequence.-///-/// `armed` also widens the shape, because it means the loop REALLY lost a head-/// whose exact bytes were unavailable: an orphaned `[` introducer counts, as do-/// cursor/mode finals (`2A`, `[H`, `[200~`) and a-/// bare `~` whose parameters went with the head. Unarmed none of that moves —-/// every one of those strings is something a human types.-pub fn take(bytes: []const u8, i: *usize) Orphan {- const start = i.*;- if (start >= bytes.len) return .none;- if (escape_armed) return takeEscapeBody(bytes, i);- // A dropped parser head is stronger evidence than a genuine Escape key:- // retain its bounded exact-tail recovery, while a same-read printable- // suffix still makes `[Alice]` prose.- if (armed and bytes[start] == '[') return takeLateCsi(bytes, i, true);- var j = start;- const lt = bytes[j] == '<';- if (lt) j += 1;- var sep = false;- // A dropped head can split ON a separator (`\x1b[<35;80` + `;24M`), so the- // tail opens with `;`/`:`. That is never typed text at the head of a read,- // but it is only debris once the loop has told us a head was lost (#546).- var headless = false;- if (j < bytes.len and (bytes[j] == ';' or bytes[j] == ':') and armed) {- sep = true;- headless = true;- j += 1;- }- if (j >= bytes.len) return if (headless) .partial else .none;- if (bytes[j] < '0' or bytes[j] > '9') {- // With all parameters lost, only `~` is distinctive enough to drop.- // A bare letter is human text, even while recovery is armed.- if (armed and bytes[j] == '~') {- i.* = j + 1;- return .{ .took = .ignore };- }- return .none;- }- var k = j;- while (k < bytes.len) : (k += 1) {- const c = bytes[k];- if (c >= '0' and c <= '9') continue;- if (c == ';' or c == ':') {- sep = true;- continue;- }- if (isFinal(c, armed)) {- if (!lt and !sep and !armed) return .none;- i.* = k + 1;- // Only `<` proves that this tail starts at SGR field zero. A- // digit/separator-led tail may start at button, x, or y; decoding- // it would fabricate a click or wheel direction. Drop unless all- // three framed fields are present and aligned.- if (lt and (c == 'M' or c == 'm')) {- const body = bytes[j..k];- if (std.mem.count(u8, body, ";") != 2 or !delimitedDecimal(body, false))- return .{ .took = .ignore };- var it = std.mem.splitScalar(u8, body, ';');- const btn = key.leadingInt(it.next().?);- const x = key.leadingInt(it.next().?);- const y = key.leadingInt(it.next().?);- return .{ .took = .{ .mouse = .{- .btn = @intCast(@min(btn, 255)),- .x = @intCast(@min(x, 999)),- .y = @intCast(@min(y, 999)),- .down = c == 'M',- } } };- }- return .{ .took = .ignore };- }- if (c == 0x1b and armed) {- i.* = k;- key.abandonSequence("", .none);- return .{ .took = .ignore };- }- return .none;- }- // A bare unarmed digit run is somebody typing, not a partial sequence.- return if (lt or sep or armed) .partial else .none;-}--test "a join only happens when the tail really completes the head" {- // The shapes run.zig drops mid-flight, rejoined.- try std.testing.expect(completes("\x1b", "[<35;80;24M"));- try std.testing.expect(completes("\x1b", "[M !!"));- try std.testing.expect(completes("\x1b[M ", "!!"));- try std.testing.expect(completes("\x1b", "[A"));- try std.testing.expect(completes("\x1b", "[3~"));- try std.testing.expect(completes("\x1b", "OA"));- try std.testing.expect(completes("\x1b", "]11;rgb:14/14/14\x07"));- try std.testing.expect(completes("\x1b", "[200~payload"));- try std.testing.expect(completes("\x1b\x1b", "[D"));- // A delivered lone Escape must not rejoin onto a later ESC CSI — that- // first ESC already cancelled or resolved as Escape (#707).- try std.testing.expect(!completes("\x1b", "\x1b[D"));- try std.testing.expect(completes("\x1b\x1b", "OA"));- try std.testing.expect(completes("\x1b[<35;80", ";24M"));- try std.testing.expect(completes("\x1b[201", "~"));- try std.testing.expect(completes("\x1b]11;rgb:1c", "1c/1c1c/1c1c\x07"));- // ...and never onto a human who simply resumed typing.- try std.testing.expect(!completes("\x1b", "hello"));- try std.testing.expect(!completes("\x1b", "[M"));- try std.testing.expect(!completes("\x1b", "[M \x1b[A"));- try std.testing.expect(!completes("\x1b", "[Alice]"));- try std.testing.expect(!completes("\x1b", "[Home]"));- try std.testing.expect(!completes("\x1b", "[Down]"));- try std.testing.expect(!completes("\x1b", "Orange"));- try std.testing.expect(!completes("\x1b", ""));- try std.testing.expect(!completes("\x1b[<35;80", "hello"));- try std.testing.expect(!completes("\x1b[", "3")); // still incomplete- try std.testing.expect(!completes("\x1b]11;rgb:1c", "fix it\r"));- try std.testing.expect(!completes("", "[A"));- try std.testing.expect(!completes("39;7", ";32M")); // headless debris is take()'s job-}--test "joinHead spends the head on the next read either way" {- reset();- var buf: [32]u8 = undefined;- stashHead("\x1b[<35;80");- @memcpy(buf[0..4], ";24M");- try std.testing.expectEqual(@as(usize, 12), joinHead(&buf, 4));- try std.testing.expectEqualStrings("\x1b[<35;80;24M", buf[0..12]);- // Second read: the head is spent, nothing is glued on.- @memcpy(buf[0..4], ";24M");- try std.testing.expectEqual(@as(usize, 4), joinHead(&buf, 4));- // A head whose tail never came never corrupts the keystroke that follows.- stashHead("\x1b[<35;80");- @memcpy(buf[0..5], "hello");- try std.testing.expectEqual(@as(usize, 5), joinHead(&buf, 5));- try std.testing.expectEqualStrings("hello", buf[0..5]);- reset();-}diff --git a/TUI/key_paste.zig b/TUI/key_paste.zigdeleted file mode 100644index 05ca0f96..00000000--- a/TUI/key_paste.zig+++ /dev/null@@ -1,143 +0,0 @@-//! Multiline paste burst: a single tty read that carries more than one-//! prompt line. Bracketed paste already latches `in_paste`; this catches-//! the wrap-less dump (clipboard `\r\n` without `CSI 200~/201~`) so each-//! newline cannot fire Enter/send (#643).--const std = @import("std");--/// True when `bytes` is a multi-line paste, not a typed line plus Enter.-/// A lone trailing CR/LF (submit) and a double-Enter mash (force-interrupt)-/// stay false.-pub fn looksLikeBurst(bytes: []const u8) bool {- var breaks: usize = 0;- var text: usize = 0;- var text_after_break = false;- var seen_break = false;- var i: usize = 0;- while (i < bytes.len) : (i += 1) {- if (bytes[i] == 0x0d) {- breaks += 1;- seen_break = true;- if (i + 1 < bytes.len and bytes[i + 1] == 0x0a) i += 1;- } else if (bytes[i] == 0x0a) {- breaks += 1;- seen_break = true;- } else if (bytes[i] >= 32) {- text += 1;- if (seen_break) text_after_break = true;- }- }- return text_after_break or (breaks >= 2 and text > 0);-}--/// A paste larger than one tty read arrives as several reads back to back.-/// `looksLikeBurst` only ever sees one of them, so a chunk that happens to-/// end at a line boundary looks like a typed line plus Enter and submits-/// mid-paste — one pasted message became several prompts (#737, a return of-/// #643 by another route). A burst therefore latches for a short window, and-/// every read that still looks like one pushes the window out.-var burst_until_ms: u64 = 0;--/// Reads this close together are the same paste. Terminals deliver the-/// chunks with no gap; a person reaching for Enter takes far longer.-pub const burst_window_ms: u64 = 150;--pub fn armBurst(now_ms: u64) void {- burst_until_ms = now_ms + burst_window_ms;-}--pub fn inBurst(now_ms: u64) bool {- return now_ms < burst_until_ms;-}--pub fn resetBurst() void {- burst_until_ms = 0;- active = false;- split_cr = false;-}--/// Whether the read the parser is walking belongs to a paste. The read loop-/// decides (it holds the clock); the parser only asks.-var active: bool = false;--pub fn setBurstRead(on: bool) void {- active = on;-}--pub fn burstActive() bool {- return active;-}--/// True when this read is part of a paste: it looks like one on its own, or-/// it arrived inside the window opened by the read before it. Arms the-/// window either way so the next chunk is covered too.-pub fn burstRead(bytes: []const u8, now_ms: u64) bool {- const carried = inBurst(now_ms);- if (!looksLikeBurst(bytes) and !carried) return false;- armBurst(now_ms);- return true;-}--var split_cr = false;--/// Consume only the immediately following LF, including across tty reads.-/// Any other byte (notably a paste terminator) clears this one-byte carry.-pub fn takeSplitLf(b: u8) bool {- const skip = split_cr and b == '\n';- split_cr = false;- return skip;-}--/// CR/LF inside a bracketed paste or a wrap-less burst is a literal newline,-/// never the Enter/send key. Collapses `\r\n` to one `\n`.-pub fn pasteNewline(bytes: []const u8, i: *usize, b: u8) ?u8 {- if (b != 0x0d and b != 0x0a) return null;- if (b == 0x0d) {- split_cr = i.* == bytes.len;- if (i.* < bytes.len and bytes[i.*] == 0x0a) i.* += 1;- }- return '\n';-}--test "a typed line plus Enter is not a paste burst" {- try std.testing.expect(!looksLikeBurst("hello\r"));- try std.testing.expect(!looksLikeBurst("hello\n"));- try std.testing.expect(!looksLikeBurst("hello\r\n"));- try std.testing.expect(!looksLikeBurst("\r"));- try std.testing.expect(!looksLikeBurst("\r\r")); // double-enter force-}--test "text after a newline is a paste burst (#643)" {- try std.testing.expect(looksLikeBurst("line1\nline2"));- try std.testing.expect(looksLikeBurst("line1\r\nline2\r\nline3"));- try std.testing.expect(looksLikeBurst("line1\nline2\n"));-}--test "blank-line-only dumps are not a burst" {- try std.testing.expect(!looksLikeBurst("\n\n"));-}--test "a paste split across reads stays one prompt (#737)" {- resetBurst();- // The terminal hands over a long paste in chunks. The first is plainly a- // burst; the second ends at a line boundary and, judged alone, reads as a- // typed line plus Enter — which is what submitted mid-paste.- try std.testing.expect(!looksLikeBurst("tail of the paragraph\n"));- try std.testing.expect(burstRead("first paragraph\nsecond paragraph\n", 1_000));- try std.testing.expect(burstRead("tail of the paragraph\n", 1_010));- try std.testing.expect(burstRead("and the last line\n", 1_100));-}--test "a typed Enter after the paste settles still sends" {- resetBurst();- try std.testing.expect(burstRead("pasted line one\npasted line two\n", 1_000));- // Long enough after the last chunk to be a person, not the terminal.- try std.testing.expect(!burstRead("now my own line\n", 1_000 + burst_window_ms + 1));-}--test "an ordinary typed line never opens the window" {- resetBurst();- try std.testing.expect(!burstRead("hello\r", 5_000));- try std.testing.expect(!inBurst(5_000));- try std.testing.expect(!burstRead("\r", 5_010));-}diff --git a/TUI/key_recover.zig b/TUI/key_recover.zigdeleted file mode 100644index 6cd63f29..00000000--- a/TUI/key_recover.zig+++ /dev/null@@ -1,164 +0,0 @@-//! Decode a proven escape sequence split between a saved head and a full read.-//! Kept separate so key_orphan.zig remains below the 600-line ceiling.--const key = @import("key.zig");-const Key = key.Key;--pub const Event = struct { event: Key, tail_len: usize };-const max_body = 128;--pub fn legacyCsiPrefix(head: []const u8, tail: []const u8, n: usize) bool {- if (n == 2) return true;- if (n < 3 or at(head, tail, 2) != '[') return false;- for (3..n) |i| {- const c = at(head, tail, i);- if (c < 0x20 or c > 0x3f) return false;- }- return true;-}--pub fn legacyCsiNavigation(params: []const u8, final: u8) bool {- if (final < 'A' or final > 'D') return false;- if (params.len == 0) return true;- var semicolon = false;- var field: u32 = 0;- var need_digit = true;- for (params) |c| {- if (c >= '0' and c <= '9') {- field = field *| 10 +| (c - '0');- need_digit = false;- } else if (c == ';' and !need_digit) {- semicolon = true;- field = 0;- need_digit = true;- } else return false;- }- return !need_digit and (!semicolon or field == 3);-}--fn legacyNavigation(head: []const u8, tail: []const u8, start: usize, end: usize, final: u8) bool {- var params_buf: [max_body]u8 = undefined;- const params = combinedSlice(head, tail, start, end, ¶ms_buf) orelse return false;- return legacyCsiNavigation(params, final);-}--pub fn legacyCsiBoundary(params: []const u8, final: u8, bytes: []const u8, after: usize) bool {- if (!legacyCsiNavigation(params, final)) return true;- // A complete navigation may share a read with the next printable key.- // Reject only recognizable bracketed prose, not every printable suffix.- var i = after;- while (i < bytes.len and bytes[i] >= 0x20 and bytes[i] <= 0x7e) : (i += 1) {- if (bytes[i] == ']') return false;- }- return true;-}--/// A recovered double-ESC prefix that was followed by bracketed prose. Return-/// the literal CSI prefix so the recovery path can preserve the human text.-pub fn legacyCsiProse(head: []const u8, tail: []const u8, n: usize) ?usize {- if (head.len < 3 or at(head, tail, 0) != 0x1b or at(head, tail, 1) != 0x1b or at(head, tail, 2) != '[') return null;- var i: usize = 3;- while (i < n and at(head, tail, i) >= 0x20 and at(head, tail, i) <= 0x3f) : (i += 1) {}- if (i >= n or !legacyNavigation(head, tail, 3, i, at(head, tail, i))) return null;- if (i + 1 >= n or at(head, tail, i + 1) < 0x20 or at(head, tail, i + 1) == 0x7f) return null;- while (i < n and at(head, tail, i) >= 0x20 and at(head, tail, i) <= 0x7e) : (i += 1) {- if (at(head, tail, i) == ']') return head.len - 2;- }- return null;-}--pub fn legacyDoubleEscape(i: *usize, start: usize) Key {- i.* = start - 1;- return .escape;-}--pub fn legacyCsiComplete(head: []const u8, tail: []const u8, n: usize, dropped: bool) bool {- var i: usize = 3;- while (i < n) : (i += 1) {- const c = at(head, tail, i);- if (c >= 0x20 and c <= 0x3f) continue;- if (!legacyNavigation(head, tail, 3, i, c)) return false;- if (legacyCsiProse(head, tail, n) != null) return false;- const control = i + 1 < n and (at(head, tail, i + 1) < 0x20 or at(head, tail, i + 1) == 0x7f);- return i + 1 == n or control or (dropped and legacyNavigation(head, tail, 3, i, c));- }- return false;-}--fn at(head: []const u8, tail: []const u8, i: usize) u8 {- return if (i < head.len) head[i] else tail[i - head.len];-}--fn combinedSlice(head: []const u8, tail: []const u8, start: usize, end: usize, out: *[max_body]u8) ?[]const u8 {- const len = end - start;- if (len > out.len) return null;- for (start..end, 0..) |i, j| out[j] = at(head, tail, i);- return out[0..len];-}--/// Decode one sequence key_orphan has already proved. Unsupported framed-/// strings become ignore, but their exact completing bytes are still consumed.-pub fn completed(head: []const u8, tail: []const u8) ?Event {- const n = head.len + tail.len;- switch (at(head, tail, 1)) {- 0x1b => {- if (n <= 2 or at(head, tail, 2) != '[') return .{ .event = .escape, .tail_len = 0 };- var final_at: usize = 3;- while (final_at < n and at(head, tail, final_at) >= 0x20 and at(head, tail, final_at) <= 0x3f) : (final_at += 1) {}- if (final_at >= n) return null;- var params_buf: [max_body]u8 = undefined;- const params = combinedSlice(head, tail, 3, final_at, ¶ms_buf) orelse return null;- const event_end = final_at + 1;- if (event_end < head.len) return null;- return .{ .event = key.decodeCsi(params, at(head, tail, final_at)), .tail_len = event_end - head.len };- },- 'O' => {- if (head.len > 3) return null;- return .{ .event = key.decodeSs3(at(head, tail, 2)), .tail_len = 3 - head.len };- },- '[' => {- var final_at: usize = 2;- while (final_at < n and at(head, tail, final_at) >= 0x20 and at(head, tail, final_at) <= 0x3f) : (final_at += 1) {}- if (final_at >= n) return null;- const final = at(head, tail, final_at);- var event: Key = .ignore;- var event_end = final_at + 1;- if (final == 'M' and final_at == 2) {- event_end = 6;- var payload: [3]u8 = undefined;- for (3..6, 0..) |i, j| payload[j] = at(head, tail, i);- event = key.decodeX10(&payload);- } else {- var params_buf: [max_body]u8 = undefined;- if (combinedSlice(head, tail, 2, final_at, ¶ms_buf)) |params|- event = key.decodeCsi(params, final);- }- if (event_end < head.len) return null;- return .{ .event = event, .tail_len = event_end - head.len };- },- ']', 'P', '_', '^', 'X' => {- var body_end: usize = 2;- var event_end: usize = 0;- while (body_end < n) : (body_end += 1) {- const c = at(head, tail, body_end);- if (c == 0x07) {- event_end = body_end + 1;- break;- }- if (c == 0x1b and body_end + 1 < n and at(head, tail, body_end + 1) == '\\') {- event_end = body_end + 2;- break;- }- }- if (event_end == 0 or event_end < head.len) return null;- var event: Key = .ignore;- if (at(head, tail, 1) == ']') {- var body_buf: [max_body]u8 = undefined;- if (combinedSlice(head, tail, 2, body_end, &body_buf)) |body|- event = key.oscReply(']', body);- }- return .{ .event = event, .tail_len = event_end - head.len };- },- else => return null,- }-}diff --git a/TUI/key_tests.zig b/TUI/key_tests.zigdeleted file mode 100644index 0070496a..00000000--- a/TUI/key_tests.zig+++ /dev/null@@ -1,404 +0,0 @@-//! key.zig's test battery, parked here under the 600-line ceiling.--const std = @import("std");-const key = @import("key.zig");-const Key = key.Key;-const next = key.next;--test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {- var i: usize = 0;- try std.testing.expectEqual(Key{ .char = 'a' }, next("a", &i).?);- i = 0;- try std.testing.expectEqual(Key.enter, next("\r", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .ctrl = 'c' }, next("\x03", &i).?);- i = 0;- try std.testing.expectEqual(Key.up, next("\x1b[A", &i).?);- i = 0;- try std.testing.expectEqual(Key.shift_tab, next("\x1b[Z", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .ctrl = 'p' }, next("\x1b[112;5u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '/' }, next("/", &i).?);- i = 0;- const click = next("\x1b[<0;12;8M", &i).?;- try std.testing.expect(click == .mouse);- try std.testing.expectEqual(@as(u8, 0), click.mouse.btn);- try std.testing.expectEqual(@as(u16, 12), click.mouse.x);- try std.testing.expectEqual(@as(u16, 8), click.mouse.y);- try std.testing.expect(click.mouse.down);- i = 0;- try std.testing.expectEqual(Key.paste_start, next("\x1b[200~", &i).?);- i = 0;- try std.testing.expectEqual(Key.paste_end, next("\x1b[201~", &i).?);- i = 0;- try std.testing.expect(next("\x1b[20", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);- i = 0;- try std.testing.expectEqual(Key{ .char = 0xc3 }, next("\xc3\xa9", &i).?);- try std.testing.expectEqual(Key{ .char = 0xa9 }, next("\xc3\xa9", &i).?);- i = 0;- try std.testing.expectEqual(Key.delete_to_start, next("\x1b[127;9u", &i).?);- key.held = 0;- i = 0;- try std.testing.expectEqual(Key.delete_word, next("\x1b\x7f", &i).?);- i = 0;- try std.testing.expectEqual(Key.prev_turn, next("\x1b[1;2D", &i).?);- i = 0;- try std.testing.expectEqual(Key.next_turn, next("\x1b[1;2C", &i).?);- i = 0;- try std.testing.expectEqual(Key.word_left, next("\x1b[1;3D", &i).?);- i = 0;- try std.testing.expectEqual(Key.home, next("\x1b[1;9D", &i).?);- i = 0;- try std.testing.expectEqual(Key.shift_enter, next("\x1b[13;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key.shift_enter, next("\x1b\r", &i).?);- i = 0;- try std.testing.expectEqual(Key.delete_to_start, next("\x1b[27;9;127~", &i).?);- i = 0;- key.held = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57444;1:1u", &i).?);- i = 0;- try std.testing.expectEqual(Key.delete_to_start, next("\x7f", &i).?);- key.held = 0;-}--test "lone trailing ESC stays pending, not an instant Escape" {- var i: usize = 0;- try std.testing.expect(next("\x1b", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);-}--test "ESC ESC stays pending until its Alt-CSI ambiguity is bounded" {- var i: usize = 0;- try std.testing.expect(next("\x1b\x1b", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);-}--test "ESC ESC CSI is Alt+arrow, not Escape (#524)" {- var i: usize = 0;- try std.testing.expectEqual(Key.left, next("\x1b\x1b[D", &i).?);- try std.testing.expectEqual(@as(usize, 4), i);- i = 0;- try std.testing.expectEqual(Key.right, next("\x1b\x1b[C", &i).?);- i = 0;- try std.testing.expectEqual(Key.up, next("\x1b\x1b[A", &i).?);- i = 0;- try std.testing.expectEqual(Key.down, next("\x1b\x1b[B", &i).?);- i = 0;- // SS3 is not a legacy Alt prefix — only ESC ESC CSI is. The first ESC- // is Escape; the OA is a later SS3 up.- try std.testing.expectEqual(Key.escape, next("\x1b\x1bOA", &i).?);-}--test "kitty release events never fire keys" {- var i: usize = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);- i = 0;- try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts-}--test "right-side modifiers follow the real kitty table, never Escape" {- key.held = 0;- var i: usize = 0;- // Right-Shift (57447) and Right-Ctrl (57448) must not latch key.held bits.- try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);- // Right-Alt (57449) latches alt; its release clears it.- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);- i = 0;- try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);- key.held = 0;-}--test "unknown keys and replies are inert, never Escape" {- var i: usize = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply-}--test "kitty functional arrows and keypad map; a stale super latch resyncs" {- key.held = 8; // pretend we missed the Super release- var i: usize = 0;- try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);- try std.testing.expectEqual(@as(u32, 0), key.held);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);- i = 0;- try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER- key.held = 0;-}--test "SS3 application keys and unbound alt-chords" {- var i: usize = 0;- try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);- i = 0;- try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);- i = 0;- // Split SS3 stays pending.- try std.testing.expect(next("\x1bO", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);- i = 0;- // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.- try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);- try std.testing.expectEqual(@as(usize, 2), i);- try std.testing.expect(next("\x1bp", &i) == null);-}--test "X10 mouse fallback consumes its payload instead of typing it" {- var i: usize = 0;- const ev = next("\x1b[M\x20\x2c\x28", &i).?;- try std.testing.expect(ev == .mouse);- try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);- try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);- try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);- try std.testing.expect(ev.mouse.down);- try std.testing.expectEqual(@as(usize, 6), i);- i = 0;- // Split short — wait for the rest.- try std.testing.expect(next("\x1b[M\x20", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);-}--test "non-ASCII CSI-u codepoints type text instead of Escape" {- var i: usize = 0;- try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);- key.held = 0;-}--test "OSC and APC replies on stdin are consumed, never typed" {- var i: usize = 0;- // OSC 11 replies now carry the terminal background (auto light/dark).- try std.testing.expectEqual(Key{ .bg_report = .{ 0x14, 0x14, 0x14 } }, next("\x1b]11;rgb:14/14/14\x07", &i).?);- try std.testing.expectEqual(@as(usize, 18), i);- i = 0;- // 4-digit form takes the high byte; other OSC bodies stay inert.- try std.testing.expectEqual(Key{ .bg_report = .{ 0xf6, 0xf6, 0xf6 } }, next("\x1b]11;rgb:f6f6/f6f6/f6f6\x1b\\", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b]10;rgb:14/14/14\x07", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);- try std.testing.expectEqual(@as(usize, 11), i);- i = 0;- // Unterminated reply stays pending until the rest arrives.- try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);- try std.testing.expectEqual(@as(usize, 0), i);-}--test "orphan SGR needs field-zero framing before it can become a mouse" {- var i: usize = 0;- // A digit-led tail may begin at button, x, or y. Consume it as debris, but- // never fabricate a click or wheel direction from guessed alignment.- const k = next("39;33;23M", &i).?;- try std.testing.expectEqual(Key.ignore, k);- try std.testing.expectEqual(@as(usize, 9), i);- i = 0;- // `<` proves this is field zero, so all three exact fields are actionable.- const k2 = next("<64;4;8Mhi", &i).?;- try std.testing.expect(k2 == .mouse);- try std.testing.expectEqual(@as(u8, 64), k2.mouse.btn);- try std.testing.expectEqual(Key{ .char = 'h' }, next("<64;4;8Mhi", &i).?);-}--test "SGR mouse flood does not leak digits" {- const seq = "\x1b[<39;33;23M\x1b[<39;26;20M\x1b[<39;25;19M";- var i: usize = 0;- var n: usize = 0;- while (next(seq, &i)) |k| {- try std.testing.expect(k == .mouse);- n += 1;- }- try std.testing.expectEqual(@as(usize, 3), n);- try std.testing.expectEqual(seq.len, i);-}--test "orphan kitty CSI-u is ignore, never letters or Escape" {- var i: usize = 0;- const seq = "3u7444;9u7441;10u";- // `3u` carries neither a `<` nor a `;`, so on its own it reads as somebody- // typing. The loop arms us when it drops a truncated sequence — which is- // the only way this tail can exist.- key.armOrphan(true);- defer key.armOrphan(false);- var n: usize = 0;- while (next(seq, &i)) |k| {- try std.testing.expect(k == .ignore);- n += 1;- }- try std.testing.expectEqual(@as(usize, 3), n);- try std.testing.expectEqual(seq.len, i);- i = 0;- try std.testing.expectEqual(Key{ .char = 'h' }, next("hi", &i).?);-}--test "Shift+9 is open-paren, Shift+0 is close-paren" {- var i: usize = 0;- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = ')' }, next("\x1b[48;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57:40;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2;40u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '!' }, next("\x1b[49;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[27;2;57~", &i).?);-}--test "a plain CSI-u keypress clears a stale super latch — Backspace stays Backspace" {- // Cmd+Tab mid-composition: the super PRESS arrives, focus leaves, the- // RELEASE goes to the other app. Typing resumes with plain CSI-u keys- // (no mods field). Those must resync held to 0, or the next Backspace- // reads as Cmd+Backspace = delete_to_start and wipes the composer.- key.held = 8; // stale Super- var i: usize = 0;- try std.testing.expectEqual(Key{ .char = 'h' }, next("\x1b[104u", &i).?);- try std.testing.expectEqual(@as(u32, 0), key.held);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);- // Stale alt is the same class of bug (backspace -> delete_word).- key.held = 2;- i = 0;- try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97u", &i).?);- i = 0;- try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);- key.held = 0;-}--test "typed text behind an Alt+] chord recovers instead of wedging (#516)" {- // CR proves it is not a reply: the introducer is swallowed as a chord- // and the sentence reparses as ordinary keys, Enter included.- var i: usize = 0;- const bytes = "\x1b]fix it\r";- try std.testing.expectEqual(Key.ignore, next(bytes, &i).?);- try std.testing.expectEqual(Key{ .char = 'f' }, next(bytes, &i).?);- var last: Key = .ignore;- while (next(bytes, &i)) |k| last = k;- try std.testing.expectEqual(Key.enter, last);- // Longer than any real reply — recover even without CR/LF.- var big: [140]u8 = undefined;- big[0] = 0x1b;- big[1] = 'P';- @memset(big[2..], 'a');- i = 0;- try std.testing.expectEqual(Key.ignore, next(&big, &i).?);- try std.testing.expectEqual(Key{ .char = 'a' }, next(&big, &i).?);-}-test "kitty numeric keypad types instead of vanishing (#549)" {- var i: usize = 0;- try std.testing.expectEqual(Key{ .char = '0' }, next("\x1b[57399u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '7' }, next("\x1b[57406u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '9' }, next("\x1b[57408u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '.' }, next("\x1b[57409u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '/' }, next("\x1b[57410u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '*' }, next("\x1b[57411u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '-' }, next("\x1b[57412u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '+' }, next("\x1b[57413u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = '=' }, next("\x1b[57415u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = ',' }, next("\x1b[57416u", &i).?);- // Releases stay inert, and the unbound keypad keys are still never Escape.- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57406;1:3u", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57425u", &i).?); // KP_Insert- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[57427u", &i).?); // KP_Begin- key.held = 0;-}--test "the event type is read from the modifier field, not the text field (#549)" {- // `CSI code ; mods:event ; text:text u` — the associated-text codepoints in- // field 3 are ':'-separated too, and scanning the whole tail found those.- var i: usize = 0;- try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2;65:66u", &i).?);- i = 0;- try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1;97:3u", &i).?);- // A genuine release, in field 2, is still ignored.- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);- i = 0;- try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);- key.held = 0;-}--test "next: embedded paste newlines are chars, not Enter (#643)" {- key.resetInputState();- defer key.resetInputState();- var i: usize = 0;- const p = "\x1b[200~a\r\nb\x1b[201~";- try std.testing.expectEqual(Key.paste_start, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = 'a' }, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = '\r' }, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = '\n' }, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = 'b' }, next(p, &i).?);- try std.testing.expectEqual(Key.paste_end, next(p, &i).?);-}--test "next: wrap-less multiline burst is not Enter (#643)" {- key.resetInputState();- defer key.resetInputState();- var i: usize = 0;- const p = "a\r\nb";- try std.testing.expectEqual(Key{ .char = 'a' }, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = '\n' }, next(p, &i).?);- try std.testing.expectEqual(Key{ .char = 'b' }, next(p, &i).?);- i = 0;- try std.testing.expectEqual(Key.enter, next("\r", &i).?);-}--test "#545: 10+-digit CSI params saturate instead of aborting the TUI" {- try std.testing.expectEqual(std.math.maxInt(u32), key.leadingInt("99999999999999999999"));- try std.testing.expectEqual(std.math.maxInt(u32), key.leadingInt("9999999999"));- try std.testing.expectEqual(@as(u32, 4294967295), key.leadingInt("4294967295"));- try std.testing.expectEqual(@as(u32, 200), key.leadingInt("200~tail"));- key.resetInputState();- defer key.resetInputState();- const payloads = [_][]const u8{- "\x1b[99999999999999999999;1u",- "\x1b[9999999999;1u",- "\x1b[<0;9999999999;5M",- "\x1b[200~hello \x1b[99999999999999999999;1u world\x1b[201~",- };- for (payloads) |p| {- var i: usize = 0;- while (i < p.len) {- const before = i;- _ = next(p, &i);- if (i <= before) break;- }- }-}diff --git a/TUI/keys.zig b/TUI/keys.zigdeleted file mode 100644index b38853ee..00000000--- a/TUI/keys.zig+++ /dev/null@@ -1,482 +0,0 @@-//! Grok Build key bindings. Returns Effect — no zigzag Cmd.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const click = @import("click.zig");-const composer_paste = @import("composer_paste.zig");-const dispatch = @import("dispatch.zig");-const hover = @import("hover.zig");-const layout_cache = @import("layout_cache.zig");-const selection = @import("selection.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const pacing = @import("pacing.zig");-const theme_mod = @import("theme.zig");-const turn = @import("turn.zig");-const Key = key_mod.Key;-const Model = app.Model;-const Effect = app.Effect;--pub fn handle(self: *Model, k: Key) Effect {- if (k == .ignore) return .stay;- if (k == .paste_start) {- self.pasting = true;- self.focus = .prompt;- composer_paste.begin(self);- return .stay;- }- if (k == .paste_end) {- self.pasting = false;- // Decoder owns its latch: batching may already have decoded the next- // paste_start. Rewinding it here turns that paste's LF into Enter (#737).- composer_paste.finish(self);- return .stay;- }- if (self.pasting) {- switch (k) {- .enter, .shift_enter => self.input.handle(.{ .char = '\n' }),- .char => |c| self.input.handle(.{ .char = c }),- .codepoint => self.input.handle(k),- // In-band escape hatch. A paste whose `CSI 201~` never arrived- // latches this branch forever, and it swallows Enter, Tab, the- // slash menu and every overlay — indistinguishable from a hung- // TUI. Escape breaks the latch instead of vanishing (#536/#548).- .escape => {- self.pasting = false;- key_mod.endPaste();- composer_paste.finish(self);- self.setToast("paste ended");- },- // Editor actions and non-newline controls are not paste text.- .tab, .backspace, .ctrl => {},- else => {},- }- return .stay;- }-- // Anything that is not part of the drag gesture drops the selection band- // (#529). The OSC-11 polarity reply is the terminal talking, not the user.- if (k != .mouse and k != .bg_report) {- selection.clear(self);- // A key can only arrive with the button up: a gutter drag whose- // release went missing must not keep the pointer captured (click.zig).- self.click.gutter = false;- }- if (k == .bg_report) {- // Startup OSC 11 reply: adopt the terminal's polarity unless the user- // explicitly picked a theme. Fixed palettes, 1-bit decision (grok).- if (!self.theme_explicit) {- const want: @import("theme.zig").Id = if (@import("theme.zig").classifyLight(k.bg_report[0], k.bg_report[1], k.bg_report[2])) .day else .night;- self.theme_id = want;- }- return .stay;- }- if (k == .mouse) return mouseKey(self, k.mouse);-- if (self.pending) |job| if (job.events.permission.peek()) |request| {- if (isCtrl(k, 'q') or isCtrl(k, 'd')) {- _ = job.events.permission.respond(request.id, .deny);- if (engine.g_cancel_fn) |cancel| cancel(engine.g_turn_ctx);- return .quit;- }- if (isChar(k, 'y') or isChar(k, 'Y')) {- _ = job.events.permission.respond(request.id, .allow_once);- } else if (isChar(k, 'n') or isChar(k, 'N') or k == .escape or isCtrl(k, 'c')) {- _ = job.events.permission.respond(request.id, .deny);- if (k == .escape or isCtrl(k, 'c')) if (engine.g_cancel_fn) |cancel| cancel(engine.g_turn_ctx);- }- return .stay;- };- if (@import("nav.zig").handle(self, k)) |e| return e;- // Job-control wins overlays so Ctrl+C always does something.- if (isCtrl(k, 'c')) return ctrlC(self);- if (k == .undo or isCtrl(k, 'z')) {- if (self.input.undo()) self.setToast("undone");- return .stay;- }- if (self.overlay != .none) return @import("overlays.zig").key(self, k);- if (slashOpen(self) and slashKey(self, k)) return .stay;- if (isChar(k, '@') and self.focus == .prompt and !slashOpen(self)) {- // Grok-style file mention: keep the typed @, open the fuzzy picker.- self.input.handle(.{ .char = '@' });- @import("overlays.zig").openFiles(self);- return .stay;- }-- if (isCtrl(k, 'd')) return ctrlD(self);- if (k == .escape) return esc(self);- if (isCtrl(k, 'p') or (isChar(k, '?') and std.mem.trim(u8, self.input.getValue(), " \t").len == 0)) {- self.openOverlay(.palette);- return .stay;- }- if (isCtrl(k, 'x') or k == .f1) {- self.openOverlay(.help);- return .stay;- }- if (k == .f2) {- self.openOverlay(.settings);- return .stay;- }- if (k == .shift_tab) {- self.cycleMode();- return .stay;- }- if (k == .tab) {- self.focus = if (self.focus == .prompt) .scrollback else .prompt;- return .stay;- }- if (isCtrl(k, 'o')) {- self.mode = if (self.mode == .always_approve) .normal else .always_approve;- self.setToast(self.modeLabel());- return .stay;- }- if (isCtrl(k, 'm')) {- self.multiline = !self.multiline;- return .stay;- }- if (k == .page_up) {- scrollBy(self, @intCast(pageSize(self)));- return .stay;- }- if (k == .page_down) {- scrollBy(self, -@as(i32, @intCast(pageSize(self))));- return .stay;- }- if (isCtrl(k, 'r')) {- dispatch.recallPrev(self);- return .stay;- }- if (isCtrl(k, 'v')) {- dispatch.pasteClipboard(self);- return .stay;- }- if (self.focus == .scrollback) return scrollbackKey(self, k);- return promptKey(self, k);-}--fn promptKey(self: *Model, k: Key) Effect {- if (k == .shift_enter) {- self.input.handle(.{ .char = '\n' });- return .stay;- }- if (k == .enter) {- if (self.pasting or self.multiline) {- self.input.handle(.{ .char = '\n' });- return .stay;- }- if (self.pending != null) {- turn.steerEnter(self);- return .stay;- }- const effect = dispatch.applyLine(self, self.input.getValue());- self.input.setValue("") catch {};- return effect;- }- if (k == .up or k == .down) {- if (self.hist_idx != null) {- if (k == .up) dispatch.recallPrev(self) else dispatch.recallNext(self);- return .stay;- }- if (std.mem.trim(u8, self.input.getValue(), " \t").len == 0) {- scrollBy(self, if (k == .up) 3 else -3);- return .stay;- }- }- if (k == .backspace and std.mem.trim(u8, self.input.getValue(), " \t").len == 0) {- if (@import("image.zig").dropLast(self)) {- self.setToast("image detached");- return .stay;- }- }- if ((k == .delete_to_start or isCtrl(k, 'u')) and self.images.items.len > 0) {- @import("image.zig").clearAll(self);- }- self.input.handle(k);- return .stay;-}--fn pageSize(self: *const Model) u32 {- const h = self.last_term_height;- const room = if (h > 8) h - 6 else 3;- return @intCast(@max(room, 3));-}--pub fn scrollBy(self: *Model, delta: i32) void {- // The content slid out from under a pointer that never moved: the hovered- // row now names a different entry, so the affordance is dropped and the- // next motion report re-arms it.- hover.scrolled(self);- // Every door into the viewport comes through here — wheel, arrows, page- // keys — so this is the one place the scrollbar's fade clock has to be- // wound (scrollbar.zig). A tail-parked viewport shows the gutter for a- // moment after the last movement and then lets it go.- self.scroll_seen_ms = @max(self.now_ms, 1);- if (delta > 0) {- self.scroll +|= @as(usize, @intCast(delta));- self.follow = false;- return;- }- const down: usize = @intCast(-delta);- if (self.scroll <= down) {- self.scroll = 0;- self.follow = true;- } else self.scroll -= down;-}--fn scrollbackKey(self: *Model, k: Key) Effect {- const down = k == .down or (self.vim_mode and isChar(k, 'j'));- const up = k == .up or (self.vim_mode and isChar(k, 'k'));- if (down) {- scrollBy(self, -3);- return .stay;- }- if (up) {- scrollBy(self, 3);- return .stay;- }- if (k == .left) {- if (self.selected < self.history.items.len) self.toggleToolGroup(self.selected);- return .stay;- }- if (k == .right or k == .enter) {- if (self.selected < self.history.items.len and self.history.items[self.selected].kind == .tool) {- self.toggleToolGroup(self.selected);- return .stay;- }- if (k == .enter or (self.vim_mode and isChar(k, 'i'))) {- self.focus = .prompt;- }- return .stay;- }- if (!self.vim_mode) {- if (k == .char or k == .codepoint or k == .ctrl) {- self.focus = .prompt;- return promptKey(self, k);- }- }- return .stay;-}--/// Production batch dispatch shared with run.zig. Keeping the folded wheel on-/// this door prevents coalescing from bypassing paste-mode key handling.-pub fn handleBatchItem(self: *Model, item: pacing.Item) Effect {- return switch (item) {- .key => |k| handle(self, k),- .wheel => |notches| wheelScroll(self, notches),- };-}--/// Apply `notches` of wheel scroll. One report and a whole coalesced momentum-/// run go through the SAME door (pacing.zig folds consecutive reports into one-/// delta), so a storm can never mean something a single report does not.-pub fn wheelScroll(self: *Model, notches: i32) Effect {- if (self.pasting or notches == 0) return .stay;- // An open picker or the completion menu owns the wheel: one notch is one- // ITEM there, never a scroll of the transcript underneath. A folded batch- // carries N notches, so replay it one item at a time.- var n = @abs(notches);- if (@import("overlays.zig").wheel(self, notches > 0)) {- while (n > 1) : (n -= 1) _ = @import("overlays.zig").wheel(self, notches > 0);- return .stay;- }- // The band is anchored to screen rows, so scrolling it would slide it onto- // other content — drop it and scroll.- selection.clear(self);- // An open picker or the completion menu owns the wheel: one notch is one- // ITEM there, never a scroll of the transcript underneath. A coalesced run- // steps once per notch, so a flick lands where the same notches typed- // slowly would.- const overlays = @import("overlays.zig");- const up = notches > 0;- if (overlays.wheel(self, up)) {- var left: u32 = @as(u32, @intCast(@abs(notches))) -| 1;- while (left > 0) : (left -= 1) _ = overlays.wheel(self, up);- return .stay;- }- scrollBy(self, notches *| @import("pacing.zig").lines_per_notch);- return .stay;-}--fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {- if (@import("pacing.zig").wheelNotch(.{ .mouse = ev })) |n| return wheelScroll(self, n);- // Pure motion under ?1003h: track the row so the frame can announce that it- // is clickable. Never consumed — the image-chip preview reads it too.- _ = hover.mouse(self, ev);- // The scroll gutter owns its column BEFORE the selection can anchor there:- // a press on the thumb is a scrollbar gesture and never a drag-copy.- if (click.gutterGesture(self, ev)) return .stay;- // A drag or its release belongs to the selection; a press only ANCHORS one- // and falls through, so a plain click keeps its meaning (#529).- if (selection.mouse(self, ev)) return .stay;- if (@import("image.zig").mouse(self, ev)) return .stay;- if (!ev.down or ev.btn != 0) return .stay;- // An open list answers the press on its own row (click.zig). It declines- // everything else, including the backdrop around a panel and every overlay- // that has no rows to pick — those keep the dismissal below.- if (click.press(self, ev)) |e| return e;- if (self.overlay != .none) {- self.closeOverlay();- return .stay;- }- const y: usize = if (ev.y > 0) ev.y - 1 else 0;- const x: usize = if (ev.x > 0) ev.x - 1 else 0;- // Two presses on one cell inside the window. The FIRST is always today's- // click, unchanged; the second replaces it rather than repeating it.- const dbl = hover.press(self, y, x);- if (y >= self.prompt_origin) {- self.focus = .prompt;- return .stay;- }- if (y < self.mid_origin) return .stay;- // Sticky-header chrome occludes the top content rows — a click there must- // not toggle whatever is hidden underneath it. A DOUBLE click on the pin- // scrolls the prompt it is pinning back onto the screen.- if (y < self.mid_origin + self.sticky_rows) {- if (dbl) hover.jumpToSticky(self);- return .stay;- }- const vis = y - self.mid_origin + self.mid_skip;- self.focus = .scrollback;- // A click on blank padding maps to no entry — it must not select or- // toggle anything (#519).- const i = layout_cache.indexAtVisual(self, vis, @import("inset.zig").wrapWidth(self)) orelse return .stay;- self.selected = i;- if (self.history.items[i].kind == .tool and !dbl) {- // A double click is ONE net toggle of the whole group: the first press- // already toggled it, so toggling again would only put it back and the- // gesture would look like it did nothing at all.- self.toggleToolGroup(i);- // Remembered so the fold can be put back if this press turns out to be- // the start of a drag — selecting text must not restructure the view.- self.sel.undo_idx = i;- }- return .stay;-}--fn slashOpen(self: *const Model) bool {- const v = self.input.getValue();- return self.focus == .prompt and v.len > 0 and v[0] == '/';-}--fn slashKey(self: *Model, k: Key) bool {- if (k == .down) {- // Clamp to the filtered list so the highlight and the Enter target- // can never diverge onto an invisible command (#522).- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- if (n > 0 and self.slash_sel + 1 < n) self.slash_sel += 1;- return true;- }- if (k == .up) {- self.slash_sel -|= 1;- return true;- }- if (k == .tab or k == .enter) {- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- if (n == 0) return false;- const pick = catalog.items[idx[@min(self.slash_sel, n - 1)]];- if (k == .tab) {- self.input.setValue(pick.name) catch {};- return true;- }- self.input.setValue("") catch {};- _ = dispatch.runCommand(self, pick.name);- return true;- }- return false;-}--fn esc(self: *Model) Effect {- if (slashOpen(self)) {- self.input.setValue("") catch {};- return .stay;- }- const empty = std.mem.trim(u8, self.input.getValue(), " \t\r\n").len == 0;- // A draft in the composer outranks every interrupt. While a turn or- // background op runs, the composer is the STEER channel — pressing Esc to- // fix your wording must not abort the work in flight (observed live:- // "✗ interrupted (esc)" right after steering text landed). Same armed- // two-press flow as the idle path below: first Esc arms, second clears.- if (!empty) {- if (self.esc_arm == .clear and self.now_ms <= self.esc_until_ms) {- self.input.setValue("") catch {};- self.esc_arm = .none;- self.setToast("cleared");- } else {- self.esc_arm = .clear;- self.esc_until_ms = self.now_ms + app.ESC_MS;- self.setToast("press again to clear");- }- return .stay;- }- if (self.bg != null) {- // A background engine op (/compact, !cmd) is exactly as interruptible- // as a turn now that it no longer blocks this thread (#533).- @import("bgop.zig").cancel(self);- self.setToast("cancelled");- return .stay;- }- if (self.pending != null) {- turn.cancelTurn(self);- self.setToast("cancelled");- return .stay;- }- if (self.userTurnCount() > 0) {- if (self.esc_arm == .rewind and self.now_ms <= self.esc_until_ms) {- self.esc_arm = .none;- self.openOverlay(.rewind);- } else {- self.esc_arm = .rewind;- self.esc_until_ms = self.now_ms + app.ESC_MS;- }- }- return .stay;-}--/// The line REPL advertises "ctrl-d quits" but the fullscreen TUI swallowed it-/// silently (#549). Empty composer quits, exactly like Ctrl+Q; with a draft in-/// hand it stays ignored, so a stray ^D can never throw work away.-fn ctrlD(self: *Model) Effect {- if (std.mem.trim(u8, self.input.getValue(), " \t\r\n").len > 0) return .stay;- return .quit;-}--fn ctrlC(self: *Model) Effect {- if (self.bg) |op| {- if (!op.cancelled) {- @import("bgop.zig").cancel(self);- self.setToast("cancelled — Ctrl+C again to quit");- return .stay;- }- }- if (self.pending != null and !self.cancel_requested) {- turn.cancelTurn(self);- self.setToast("cancelled — Ctrl+C again to quit");- return .stay;- }- return .quit;-}--fn isCtrl(k: Key, c: u8) bool {- return switch (k) {- .ctrl => |x| x == c,- else => false,- };-}--fn isChar(k: Key, c: u8) bool {- return switch (k) {- .char => |x| x == c,- else => false,- };-}--test {- // The tests live next door (this file is at the line ceiling). Without this- // reference they compile for nobody and silently never run.- _ = @import("keys_tests.zig");- _ = @import("issue_537_tests.zig");-}diff --git a/TUI/keys_tests.zig b/TUI/keys_tests.zigdeleted file mode 100644index af6e2afa..00000000--- a/TUI/keys_tests.zig+++ /dev/null@@ -1,522 +0,0 @@-//! Tests for keys.zig — the dispatcher itself sits at the 600-line ceiling, so-//! its test block lives here. Reached from keys.zig's test block, which is-//! reached from root.zig: a module nobody references never runs its tests.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const keys = @import("keys.zig");-const Key = key_mod.Key;-const Model = app.Model;-const Effect = app.Effect;--const handle = keys.handle;--/// The Escape key through the PUBLIC door. `keys.esc` is private, and it should-/// stay that way: what a test wants pinned is what pressing Escape does, not-/// which internal helper happens to implement it.-fn esc(m: *Model) Effect {- return handle(m, .escape);-}--test "Esc on a draft arms clear, second press clears" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.now_ms = 1000;- m.input.setValue("draft") catch {};- _ = esc(&m);- try std.testing.expectEqual(app.EscArm.clear, m.esc_arm);- try std.testing.expectEqualStrings("draft", m.input.getValue());- m.now_ms = 1200;- _ = esc(&m);- try std.testing.expectEqualStrings("", m.input.getValue());-}--test "Ctrl+C quits when idle" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'c' }));- try m.input.setValue("ab");- _ = handle(&m, .{ .char = 'x' });- try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'z' }));- try std.testing.expectEqualStrings("ab", m.input.getValue());-}--test "Ctrl+D quits an empty composer and is ignored with a draft (#549)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.input.setValue("half a thought");- try std.testing.expectEqual(Effect.stay, handle(&m, .{ .ctrl = 'd' }));- try std.testing.expectEqualStrings("half a thought", m.input.getValue());- try m.input.setValue(" ");- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));- try m.input.setValue("");- try std.testing.expectEqual(Effect.quit, handle(&m, .{ .ctrl = 'd' }));-}--test "Tab toggles focus" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(app.Focus.prompt, m.focus);- _ = handle(&m, .tab);- try std.testing.expectEqual(app.Focus.scrollback, m.focus);- _ = handle(&m, .tab);- try std.testing.expectEqual(app.Focus.prompt, m.focus);-}--test "Shift+Tab cycles Normal Plan Always-approve" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try std.testing.expectEqual(app.AgentMode.normal, m.mode);- _ = handle(&m, .shift_tab);- try std.testing.expectEqual(app.AgentMode.plan, m.mode);- _ = handle(&m, .shift_tab);- try std.testing.expectEqual(app.AgentMode.always_approve, m.mode);- _ = handle(&m, .shift_tab);- try std.testing.expectEqual(app.AgentMode.normal, m.mode);-}--const two_models = [_]engine.ModelEntry{- .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },-};--test "model overlay Enter picks the selected name" {- engine.g_model_entries = &two_models;- engine.g_model_name = "grok-4";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- engine.g_model_fn = null;- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- m.overlay_sel = 1;- _ = handle(&m, .enter);- try std.testing.expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqualStrings("gpt-5.5", engine.g_model_name);- try std.testing.expectEqualStrings("openai", engine.g_model_provider);-}--test "model overlay type-to-search picks the filtered name" {- engine.g_model_entries = &.{- .{ .name = "grok-4", .provider = "xai", .has_key = true },- .{ .name = "gpt-5.5", .provider = "openai", .has_key = true },- .{ .name = "deepseek-v4-pro", .provider = "codegraff", .has_key = true, .cost = .credits },- };- engine.g_model_name = "grok-4";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- engine.g_model_fn = null;- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- _ = handle(&m, .{ .char = 'd' });- _ = handle(&m, .{ .char = 'e' });- _ = handle(&m, .{ .char = 'e' });- try std.testing.expectEqualStrings("dee", m.overlay_filter);- _ = handle(&m, .enter);- try std.testing.expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqualStrings("deepseek-v4-pro", engine.g_model_name);- try std.testing.expectEqualStrings("codegraff", engine.g_model_provider);-}--/// Records what the engine was ASKED to switch to. The bug this pins: the-/// picker handed over a name and the engine re-resolved the provider itself.-var asked_provider: []const u8 = "";-var asked_name: []const u8 = "";--fn recordSwitch(_: ?*anyopaque, gpa: std.mem.Allocator, provider: []const u8, name: []const u8) ?engine.Picked {- asked_provider = provider;- asked_name = name;- return .{ .model = gpa.dupe(u8, name) catch return null, .provider = provider };-}--test "picking the SECOND of two same-named rows switches to that row's provider" {- // codex serves gpt-5.6 on a ChatGPT plan and openai serves it on a metered- // key. Both rows read "gpt-5.6"; picking the openai one used to send the- // bare name and land wherever the router preferred — usually codex.- engine.g_model_entries = &.{- .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },- };- engine.g_model_fn = recordSwitch;- asked_provider = "";- asked_name = "";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- engine.g_model_fn = null;- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- m.overlay_sel = 1;- _ = handle(&m, .enter);- try std.testing.expectEqualStrings("openai", asked_provider);- try std.testing.expectEqualStrings("gpt-5.6", asked_name);- try std.testing.expectEqualStrings("openai", engine.g_model_provider);- try std.testing.expectEqualStrings("gpt-5.6", engine.g_model_name);-- // ...and the first row still reaches codex, so this is a routed pick and- // not a constant.- m.openOverlay(.model);- m.overlay_sel = 0;- _ = handle(&m, .enter);- try std.testing.expectEqualStrings("codex", asked_provider);- try std.testing.expectEqualStrings("codex", engine.g_model_provider);-}--test "a provider-filtered pick keeps the provider of the row it matched" {- engine.g_model_entries = &.{- .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "k3", .provider = "kimi", .has_key = true, .cost = .plan },- };- engine.g_model_fn = recordSwitch;- asked_provider = "";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- engine.g_model_fn = null;- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- for ("openai") |c| _ = handle(&m, .{ .char = c });- _ = handle(&m, .enter);- try std.testing.expectEqualStrings("openai", asked_provider);- try std.testing.expectEqualStrings("gpt-5.6", asked_name);-}--test "PgUp leaves follow; PgDn returns to the live tail" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_height = 24;- try std.testing.expect(m.follow);- _ = handle(&m, .page_up);- try std.testing.expect(!m.follow);- try std.testing.expect(m.scroll > 0);- _ = handle(&m, .page_down);- try std.testing.expect(m.follow);- try std.testing.expectEqual(@as(usize, 0), m.scroll);-}--test "Cmd+Delete and Ctrl+U kill the draft, not the viewport" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_height = 24;- try m.input.setValue("keep scrolling separate");- m.input.cursor = m.input.getValue().len;- _ = handle(&m, .delete_to_start);- try std.testing.expectEqualStrings("", m.input.getValue());- try std.testing.expect(m.follow);- try m.input.setValue("word two");- m.input.cursor = m.input.getValue().len;- _ = handle(&m, .{ .ctrl = 'u' });- try std.testing.expectEqualStrings("", m.input.getValue());- try std.testing.expect(m.follow);-}--// The click-behaviour tests live beside the drag tests in selection.zig: a-// click and a drag are two readings of the same press, and they only stay-// separable if they are pinned together.--test "slash selection clamps to the filtered list and stays visible (#522)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.input.setValue("/");- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter("/", &idx);- try std.testing.expect(n > 8); // the bug needs more commands than visible rows- var presses: usize = 0;- while (presses < n + 10) : (presses += 1) _ = handle(&m, .down);- try std.testing.expectEqual(n - 1, m.slash_sel);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const menu = try @import("chrome.zig").slashMenu(&m, arena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, menu, "› ") != null);-}--test "empty Up scrolls transcript and keeps prompt focus" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_height = 24;- try std.testing.expect(m.focus == .prompt);- _ = handle(&m, .up);- try std.testing.expect(!m.follow);- try std.testing.expect(m.scroll > 0);- try std.testing.expect(m.focus == .prompt);- _ = handle(&m, .down);- try std.testing.expect(m.follow);- try std.testing.expectEqual(@as(usize, 0), m.scroll);-}--test "bracketed paste lands in the prompt as text" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.focus = .scrollback;- _ = handle(&m, .paste_start);- _ = handle(&m, .{ .char = 'h' });- _ = handle(&m, .{ .char = 'i' });- _ = handle(&m, .enter);- _ = handle(&m, .{ .char = '!' });- _ = handle(&m, .paste_end);- try std.testing.expectEqualStrings("hi\n! ", m.input.getValue());- try std.testing.expect(m.focus == .prompt);- try std.testing.expect(!m.pasting);-}--test "pasted image path becomes an attachment chip" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = handle(&m, .paste_start);- for ("/tmp/pic.png") |c| _ = handle(&m, .{ .char = c });- _ = handle(&m, .paste_end);- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings("/tmp/pic.png", m.images.items[0]);- try std.testing.expectEqualStrings("", m.input.getValue());-}--test "Ctrl+R walks prompt history" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "older"));- try m.prompt_hist.append(try std.testing.allocator.dupe(u8, "newer"));- _ = handle(&m, .{ .ctrl = 'r' });- try std.testing.expectEqualStrings("newer", m.input.getValue());- _ = handle(&m, .up);- try std.testing.expectEqualStrings("older", m.input.getValue());-}--test "Ctrl+R after an image prompt restores the attachment (#577)" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = "shot.png", .data = "png" });- var dir_buf: [std.fs.max_path_bytes]u8 = undefined;- const dir_n = try tmp.dir.realPath(io, &dir_buf);- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const live = try std.fmt.bufPrint(&path_buf, "{s}/shot.png", .{dir_buf[0..dir_n]});-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage(live);- _ = @import("dispatch.zig").applyLine(&m, "what is this");- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);- _ = handle(&m, .{ .ctrl = 'r' });- try std.testing.expectEqualStrings("what is this", m.input.getValue());- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings(live, m.images.items[0]);-}--test "backspace on an empty composer detaches the last chip (#634)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage("/tmp/a.png");- m.attachImage("/tmp/b.png");- _ = handle(&m, .backspace);- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings("/tmp/a.png", m.images.items[0]);- _ = handle(&m, .delete_to_start);- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);-}--test "backspace with typed text does not drop chips (#634)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.input.setValue("hi");- m.input.cursor = 2;- m.attachImage("/tmp/shot.png");- _ = handle(&m, .backspace);- try std.testing.expectEqualStrings("h", m.input.getValue());- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);-}--test "Ctrl+U clears chips with the draft (#634)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.input.setValue("keep");- m.input.cursor = m.input.getValue().len;- m.attachImage("/tmp/shot.png");- _ = handle(&m, .{ .ctrl = 'u' });- try std.testing.expectEqualStrings("", m.input.getValue());- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);-}--fn pendingTerm() !@import("sim.zig").Term {- const Term = @import("sim.zig").Term;- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- };- try term.model.push(.pending, "");- term.model.pending = job;- return term;-}--fn dropPending(term: *@import("sim.zig").Term) void {- if (term.model.pending) |job| {- term.model.pending = null;- std.testing.allocator.destroy(job);- }-}--test "idle bracketed multiline paste stays one unsent draft (#643)" {- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.feed("\x1b[200~line1\nline2\nline3\x1b[201~");- try std.testing.expectEqualStrings("line1\nline2\nline3 ", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- var users: usize = 0;- for (term.model.history.items) |e| {- if (e.kind == .user) users += 1;- }- try std.testing.expectEqual(@as(usize, 0), users);- _ = term.enter();- try std.testing.expectEqualStrings("", term.model.input.getValue());- users = 0;- for (term.model.history.items) |e| {- if (e.kind == .user) users += 1;- }- try std.testing.expectEqual(@as(usize, 1), users);- try std.testing.expectEqualStrings("line1\nline2\nline3", term.model.history.items[0].text);-}--test "streaming bracketed paste does not steer, Enter queues one (#643)" {- var term = try pendingTerm();- defer {- dropPending(&term);- term.deinit();- }- _ = term.feed("\x1b[200~first\nsecond\nthird\x1b[201~");- try std.testing.expectEqualStrings("first\nsecond\nthird ", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);- _ = term.enter();- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- try std.testing.expectEqualStrings("first\nsecond\nthird", term.model.steer_queue.items[0]);- try std.testing.expectEqualStrings("", term.model.input.getValue());-}--test "bracketed CRLF paste cannot invoke Enter/send (#643)" {- var term = try pendingTerm();- defer {- dropPending(&term);- term.deinit();- }- _ = term.feed("\x1b[200~one\r\ntwo\r\nthree\x1b[201~");- try std.testing.expectEqualStrings("one\r\ntwo\r\nthree ", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);- var forced: usize = 0;- for (term.model.history.items) |e| {- if (std.mem.eql(u8, e.text, "↳ force › interrupting…")) forced += 1;- }- try std.testing.expectEqual(@as(usize, 0), forced);-}--test "#737 streaming large single paragraph crosses real read and batch boundaries" {- try streamingPaste737("a long single paragraph ", 2500);-}--test "#737 streaming multiline paste preserves LF CRLF and trailing newline across reads" {- try streamingPaste737("first paragraph\n\nsecond paragraph\r\n", 1800);-}--fn streamingPaste737(unit: []const u8, repeats: usize) !void {- var term = try pendingTerm();- defer {- dropPending(&term);- term.deinit();- }- const a = std.testing.allocator;- const body = try a.alloc(u8, unit.len * repeats);- defer a.free(body);- for (0..repeats) |j| @memcpy(body[j * unit.len ..][0..unit.len], unit);- // Both markers arrive split, with enough body to overflow the production- // 16KiB input read and 64-event batch many times. No timing/model calls.- for ([_][]const u8{ "\x1b", "[2", "00~" }) |part| _ = term.feed(part);- var at: usize = 0;- while (at < body.len) {- const end = @min(at + 16381, body.len);- _ = term.feed(body[at..end]);- try std.testing.expectEqualStrings(body[0..end], term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);- for (term.model.history.items) |entry| try std.testing.expect(entry.kind != .user);- at = end;- }- for ([_][]const u8{ "\x1b[", "20", "1~" }) |part| _ = term.feed(part);- try std.testing.expectEqualStrings(body, term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- _ = term.enter();- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);- // steerEnter trims surrounding whitespace, so don't confuse its existing- // submit policy with the lossless unsent draft assertion above.- try std.testing.expectEqualStrings(std.mem.trim(u8, body, " \t\r\n"), term.model.steer_queue.items[0]);- try std.testing.expectEqualStrings("", term.model.input.getValue());-}--test "#737 delayed paste_end dispatch cannot reset a subsequent decoded paste" {- var term = try pendingTerm();- defer {- dropPending(&term);- term.deinit();- }- _ = term.feed("\x1b[200~first\x1b[201~\x1b[200~second");- _ = term.feed("\r");- _ = term.feed("\nthird\x1b[201~");- try std.testing.expectEqualStrings("first second\r\nthird ", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);-}--test "wrap-less CRLF dump while streaming stays one draft (#643)" {- var term = try pendingTerm();- defer {- dropPending(&term);- term.deinit();- }- _ = term.feed("alpha\r\nbeta\r\ngamma");- try std.testing.expectEqualStrings("alpha\nbeta\ngamma", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try std.testing.expect(!term.model.cancel_requested);-}diff --git a/TUI/layout_cache.zig b/TUI/layout_cache.zigdeleted file mode 100644index f824e73f..00000000--- a/TUI/layout_cache.zig+++ /dev/null@@ -1,371 +0,0 @@-//! Virtual layout for the transcript viewport.-//!-//! scrollback.render lays the WHOLE history out on every call: every entry is-//! re-wrapped through theme.wrapToWidth and the result concatenated into one-//! string, which render.zig then splits back into lines and throws all but a-//! screenful of away. That makes one wheel tick cost O(total transcript), and-//! on a long session it is exactly why scrolling feels bad.-//!-//! grok-build's answer, and this one: lay each BLOCK out once, keep the wrapped-//! bytes, and keep a prefix sum of where each block starts in virtual-Y. A-//! scroll is then a viewport SLICE — binary search to the block holding the top-//! line, walk forward a screenful — so a frame costs O(view height + log n)-//! instead of O(history).-//!-//! A block is one history entry, or a whole consecutive tool RUN (collapsed or-//! expanded), because that is the unit scrollback.render emits between '\n's.-//! Everything a block's bytes depend on — its entries' identity and fold state,-//! the width, the theme, whether the selection is inside it, and the user-//! ordinal that numbers a prompt — is folded into a 64-bit key, and a block-//! whose key still matches is reused verbatim. Appending to the transcript-//! therefore reuses the entire cached prefix, and a streaming turn re-lays out-//! only its own tail.-//!-//! Presentation state by construction: nothing here is engine state, and the-//! cache is a pure memo — dropping it changes performance and nothing else.-//! scrollback.render stays as the uncached reference that the property tests in-//! layout_cache_tests.zig check this against, byte for byte.--const std = @import("std");--const app = @import("app.zig");-const foldhdr = @import("foldhdr.zig");-const scrollback = @import("scrollback.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--/// A laid-out block: the bytes scrollback.render would have emitted for the-/// history range [start, end), plus where they sit in virtual-Y.-pub const Block = struct {- /// First history index of the block; `end` is exclusive. A live block — the- /// pending stream tail or the steer notice — is not history at all and- /// carries start >= history.len so it maps to no entry.- start: usize,- end: usize,- key: u64,- /// Owned by the cache's allocator. Empty only under OOM.- text: []u8,- lines: usize,- first_line: usize = 0,- /// Laid out fresh every frame and never reused: a `.pending` row animates- /// off now_ms, and the live rows below change with the stream.- vol: bool = false,- /// Not history: the streaming tail or the steer notice. Maps to no entry.- live: bool = false,- /// The nearest `.user` entry's text at or before this block — what the- /// sticky header pins. Refreshed on every walk, so it can never outlive the- /// entry it points at.- user_text: ?[]const u8 = null,-};--pub const Cache = struct {- blocks: std.ArrayList(Block) = .empty,- /// The width and theme the cached bytes were laid out at. A change in- /// either is a cold rebuild: every block rewraps.- width: usize = 0,- theme: u8 = 0xff,- total: usize = 0,- hits: u64 = 0,- misses: u64 = 0,- colds: u64 = 0,-- pub fn deinit(self: *Cache, gpa: std.mem.Allocator) void {- self.invalidate(gpa);- self.blocks.deinit(gpa);- self.* = .{};- }-- /// Drop every laid-out block, keeping the array's capacity. Callers that- /// free the entries themselves (clearHistory) must come through here: a- /// cached `user_text` points into entry storage.- pub fn invalidate(self: *Cache, gpa: std.mem.Allocator) void {- for (self.blocks.items) |b| if (b.text.len > 0) gpa.free(b.text);- self.blocks.clearRetainingCapacity();- self.total = 0;- }-};--/// Bring the cache up to date for `width` and return it. Cheap when nothing-/// changed: one key per block, no wrapping and no allocation.-pub fn ensure(m: *Model, width: usize) *Cache {- const c = &m.layout;- const th: u8 = @intFromEnum(m.theme_id);- if (c.width != width or c.theme != th) {- c.invalidate(m.alloc);- c.width = width;- c.theme = th;- c.colds += 1;- }- var arena = std.heap.ArenaAllocator.init(m.alloc);- defer arena.deinit();-- var w: Walk = .{ .m = m, .c = c, .arena = &arena, .width = width, .th = th };- var i: usize = 0;- while (i < m.history.items.len) {- const e = m.history.items[i];- const end = if (e.kind == .tool) m.toolRun(i).end else i + 1;- if (e.kind == .user) {- w.users += 1;- w.user_text = e.text;- }- if (e.kind == .pending and scrollback.liveHasBytes(m)) {- i = end;- continue;- }- w.place(i, end, e.kind == .pending, false);- i = end;- }- w.placeLive();- // Whatever the walk did not claim describes a transcript that no longer- // exists — a cleared history, a removed pending row, a collapsed run.- for (c.blocks.items[w.pos..]) |b| if (b.text.len > 0) m.alloc.free(b.text);- c.blocks.shrinkRetainingCapacity(w.pos);- c.total = w.line;- return c;-}--const Walk = struct {- m: *Model,- c: *Cache,- arena: *std.heap.ArenaAllocator,- width: usize,- th: u8,- pos: usize = 0,- line: usize = 0,- users: u32 = 0,- user_text: ?[]const u8 = null,-- fn place(self: *Walk, start: usize, end: usize, vol: bool, live: bool) void {- const key = if (vol) 0 else blockKey(self.m, start, end, self.width, self.th, self.users);- if (self.pos < self.c.blocks.items.len) {- const b = &self.c.blocks.items[self.pos];- if (!vol and !b.vol and b.key == key and b.start == start and b.end == end) {- b.first_line = self.line;- b.user_text = self.user_text;- self.line += b.lines;- self.pos += 1;- self.c.hits += 1;- return;- }- if (b.text.len > 0) self.m.alloc.free(b.text);- b.* = self.build(start, end, key, vol, live);- self.line += b.lines;- self.pos += 1;- self.c.misses += 1;- return;- }- const b = self.build(start, end, key, vol, live);- self.c.blocks.append(self.m.alloc, b) catch {- if (b.text.len > 0) self.m.alloc.free(b.text);- return;- };- self.line += b.lines;- self.pos += 1;- self.c.misses += 1;- }-- fn build(self: *Walk, start: usize, end: usize, key: u64, vol: bool, live: bool) Block {- _ = self.arena.reset(.retain_capacity);- const a = self.arena.allocator();- const text = if (live)- liveText(self.m, a, start, end, self.width) catch ""- else- blockText(self.m, a, start, end, self.width, self.users) catch "";- const owned: []u8 = self.m.alloc.dupe(u8, text) catch &.{};- return .{- .start = start,- .end = end,- .key = key,- .text = owned,- .lines = scrollback.lineCount(owned),- .first_line = self.line,- .vol = vol,- .live = live,- .user_text = self.user_text,- };- }-- /// The two rows a live turn owns: the streaming prose tail and the steer- /// notice. Both change every frame, so they are laid out fresh every time- /// and never claim a cached slot's identity.- fn placeLive(self: *Walk) void {- const m = self.m;- const job = m.pending orelse return;- if (m.cancel_requested) return;- const n = m.history.items.len;- if (job.raw.len.load(.acquire) > 0 or job.stream.len.load(.acquire) > 0) self.place(n, n, true, true);- if (m.steer_queue.items.len > 0) self.place(n, n + 1, true, true);- }-};--/// Which live row this is: `end == start` is the stream tail, anything else is-/// the steer notice. Keeps the two apart without a third field.-fn liveText(m: *Model, a: std.mem.Allocator, start: usize, end: usize, width: usize) ![]const u8 {- if (end != start) return steerText(m, a);- const job = m.pending orelse return "";- const raw_bash = job.raw.len.load(.acquire) > 0;- const src = if (raw_bash) &job.raw else &job.stream;- const live = src.snapshot(a) orelse return "";- return scrollback.liveAnswer(m, a, live, raw_bash, width, m.now_ms);-}--fn steerText(m: *Model, a: std.mem.Allocator) ![]const u8 {- return theme_mod.paint(a, m.theme().muted, try std.fmt.allocPrint(a, " ↳ {d} queued · empty Enter sends now", .{m.steer_queue.items.len}));-}--/// One block's bytes, composed exactly as scrollback.render composes them —-/// same helpers, same selection rule, same '\n' between the rows of an expanded-/// tool run.-fn blockText(m: *const Model, a: std.mem.Allocator, start: usize, end: usize, width: usize, users: u32) ![]const u8 {- const e = m.history.items[start];- 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 scrollback.runVisual(m, a, start, end, width, m.now_ms);-}--/// Everything the block's bytes are a function of. Entry identity is the-/// (pointer, length) of its owned strings — entries are immutable once pushed,-/// and freed on replacement — with a bounded content sample mixed in so an-/// allocator that hands the same address and length back for different bytes-/// cannot fake a hit.-fn blockKey(m: *const Model, start: usize, end: usize, width: usize, th: u8, users: u32) u64 {- var h = std.hash.Wyhash.init(0x1a70c0de);- h.update(std.mem.asBytes(&width));- h.update(std.mem.asBytes(&th));- h.update(std.mem.asBytes(&users));- const sel: usize = if (m.focus == .scrollback and m.selected >= start and m.selected < end) m.selected + 1 else 0;- h.update(std.mem.asBytes(&sel));- // 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];- var flags: u8 = @intFromEnum(e.kind);- flags |= @as(u8, @intFromBool(e.folded)) << 4;- h.update(std.mem.asBytes(&flags));- mixSlice(&h, e.text);- var tf: u8 = 0;- if (e.tool) |t| {- tf = 1;- tf |= @as(u8, @intFromBool(t.done)) << 1;- tf |= @as(u8, @intFromBool(t.is_error)) << 2;- tf |= @as(u8, @intFromBool(t.denied)) << 3;- h.update(std.mem.asBytes(&tf));- mixSlice(&h, t.name);- mixSlice(&h, t.detail);- } else h.update(std.mem.asBytes(&tf));- }- return h.final();-}--fn mixSlice(h: *std.hash.Wyhash, s: []const u8) void {- const p = @intFromPtr(s.ptr);- h.update(std.mem.asBytes(&p));- const n = s.len;- h.update(std.mem.asBytes(&n));- if (s.len <= 32) {- h.update(s);- return;- }- h.update(s[0..16]);- h.update(s[s.len - 16 ..]);-}--// --- viewport queries --------------------------------------------------------/// The `count` display lines starting at virtual row `from`. The slices point-/// into the cache's own bytes, so this allocates only the index array.-pub fn window(c: *const Cache, a: std.mem.Allocator, from: usize, count: usize) ![]const []const u8 {- var out = std.array_list.Managed([]const u8).init(a);- if (count == 0) return out.items;- var bi = blockOfLine(c, from) orelse return out.items;- while (bi < c.blocks.items.len and out.items.len < count) : (bi += 1) {- const b = c.blocks.items[bi];- var it = std.mem.splitScalar(u8, b.text, '\n');- var ord: usize = 0;- while (it.next()) |ln| : (ord += 1) {- if (b.first_line + ord < from) continue;- if (out.items.len >= count) break;- try out.append(ln);- }- }- return out.items;-}--/// History index shown on virtual row `y` — a tool run answers with its start,-/// a live row with null. Mirrors scrollback.indexAtVisual.-pub fn indexAt(c: *const Cache, y: usize) ?usize {- const bi = blockOfLine(c, y) orelse return null;- const b = c.blocks.items[bi];- if (b.live) return null;- return b.start;-}--/// First virtual row of entry `idx` (a tool run answers with its own first-/// row). Mirrors scrollback.visualOfIndex.-pub fn lineOf(c: *const Cache, idx: usize) ?usize {- const bs = c.blocks.items;- if (bs.len == 0) return null;- var lo: usize = 0;- var hi: usize = bs.len;- while (lo + 1 < hi) {- const mid = lo + (hi - lo) / 2;- if (bs[mid].start <= idx) lo = mid else hi = mid;- }- const b = bs[lo];- if (b.live or idx < b.start or idx >= b.end) return null;- return b.first_line;-}--/// The last user prompt whose first row sits strictly above `top` — the grok-/// sticky-header candidate, in O(log n) off the per-block back-pointer.-pub fn stickyUserAbove(c: *const Cache, top: usize) ?[]const u8 {- const bs = c.blocks.items;- if (bs.len == 0 or top == 0 or bs[0].first_line >= top) return null;- var lo: usize = 0;- var hi: usize = bs.len;- while (lo + 1 < hi) {- const mid = lo + (hi - lo) / 2;- if (bs[mid].first_line < top) lo = mid else hi = mid;- }- return bs[lo].user_text;-}--fn blockOfLine(c: *const Cache, y: usize) ?usize {- const bs = c.blocks.items;- if (bs.len == 0 or y >= c.total) return null;- var lo: usize = 0;- var hi: usize = bs.len;- while (lo + 1 < hi) {- const mid = lo + (hi - lo) / 2;- if (bs[mid].first_line <= y) lo = mid else hi = mid;- }- return lo;-}--// --- Model-level convenience (same shapes as the scrollback originals) --------pub fn totalVisualLines(m: *Model, width: usize) usize {- return ensure(m, width).total;-}--pub fn indexAtVisual(m: *Model, y: usize, width: usize) ?usize {- return indexAt(ensure(m, width), y);-}--pub fn visualOfIndex(m: *Model, idx: usize, width: usize) ?usize {- return lineOf(ensure(m, width), idx);-}--test {- _ = @import("layout_cache_tests.zig");-}diff --git a/TUI/layout_cache_tests.zig b/TUI/layout_cache_tests.zigdeleted file mode 100644index bafcdd27..00000000--- a/TUI/layout_cache_tests.zig+++ /dev/null@@ -1,336 +0,0 @@-//! The layout cache is only allowed to be faster — never different. Every test-//! here pins it against scrollback.zig's uncached path, which stays in the tree-//! precisely as the oracle: it re-wraps the whole history on every call, so if-//! the two ever disagree the cache is wrong by definition.-//!-//! The last test is the benchmark. It runs a token-sized transcript by default-//! (Debug timings are meaningless, so it asserts REUSE there, not speed) and-//! the full 10k-display-line matrix with numbers when GRAFF_TUI_BENCH is set —-//! see scripts/bench-tui-layout.sh, which builds it ReleaseFast.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const layout = @import("layout_cache.zig");-const render_mod = @import("render.zig");-const scrollback = @import("scrollback.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;-const testing = std.testing;--/// The whole transcript, read back out of the cache one display line at a time-/// and re-joined. Byte-identical to scrollback.render is the contract.-fn cachedAll(m: *Model, a: std.mem.Allocator, width: usize) ![]const u8 {- const c = layout.ensure(m, width);- const lines = try layout.window(c, a, 0, c.total);- var out = std.array_list.Managed(u8).init(a);- for (lines, 0..) |ln, i| {- if (i > 0) try out.append('\n');- try out.appendSlice(ln);- }- return out.items;-}--const prose = "a long explanation line that fills the scrollback with content and keeps wrapping at every narrow width the matrix below tests";--fn fixture(m: *Model) !void {- try m.push(.user, "how do I frobnicate the widget? and keep the question long enough to wrap");- try m.push(.assistant, prose);- try m.pushTool(.{ .name = "bash", .detail = "printf hello | wc -c" });- try m.pushTool(.{ .name = "bash", .detail = "6", .done = true });- try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "needle" });- try m.pushTool(.{ .name = "mcp__codedbpro__faster_search", .detail = "3 hits", .done = true });- try m.push(.assistant, "## heading\n\n- one\n- two\n\n`code` and **bold** " ++ prose);- try m.push(.system, "· a system notice");- try m.push(.err, "something went wrong while doing the thing that went wrong");- try m.push(.user, "second prompt");- try m.pushTool(.{ .name = "read_file", .detail = "src/foo.zig" });- try m.pushTool(.{ .name = "read_file", .detail = "const std = @import(\"std\");", .done = true });- try m.push(.assistant, "done");-}--// 44/80/120 are the audited trio (narrow, default, wide); the rest surround-// them so an off-by-one in the wrap math cannot hide between two sampled-// widths.-const widths = [_]usize{ 28, 41, 44, 60, 80, 100, 120, 132 };--test "cached layout is byte-identical to the uncached render over widths, themes and folds" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fixture(&m);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();-- // Every phase mutates something the cache keys on, WITHOUT clearing it:- // the point is that invalidation is derived, not announced.- for (theme_mod.all) |tid| {- m.theme_id = tid;- for (widths) |w| {- for (0..8) |phase| {- switch (phase) {- 1 => m.toggleToolGroup(2), // expand the bash run- 2 => m.toggleToolGroup(4), // expand the search run- 3 => {- m.focus = .scrollback;- m.selected = 5;- },- 4 => m.selected = 1,- 5 => m.toggleToolGroup(2), // fold it back under selection- 6 => m.focus = .prompt,- 7 => {- try m.push(.assistant, "an appended answer that arrives after everything was cached " ++ prose);- try m.push(.pending, "");- m.now_ms = 700; // past the ❙/❘ blink half-period- },- else => {},- }- _ = arena.reset(.retain_capacity);- const a = arena.allocator();- const want = try scrollback.render(&m, a, w, m.now_ms);- const got = try cachedAll(&m, a, w);- testing.expectEqualStrings(want, got) catch |e| {- std.debug.print("theme={s} width={d} phase={d}\n", .{ tid.label(), w, phase });- return e;- };- }- // The pending row is a history entry, not chrome: it maps back to- // its own index the way every other row does.- const c = layout.ensure(&m, w);- const last = m.history.items.len - 1;- try testing.expectEqual(last, layout.indexAt(c, c.total - 1).?);- // Unwind phase 7's pushes so the next width starts from the fixture.- m.freeEntry(m.history.pop().?);- m.freeEntry(m.history.pop().?);- m.now_ms = 0;- }- }-}--test "cached virtual-Y agrees with the uncached row math entry for entry" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fixture(&m);- for (widths) |w| {- for (0..3) |phase| {- if (phase == 1) m.toggleToolGroup(2);- if (phase == 2) m.toggleToolGroup(4);- const c = layout.ensure(&m, w);- try testing.expectEqual(scrollback.totalVisualLines(&m, w), c.total);- var idx: usize = 0;- while (idx < m.history.items.len) : (idx += 1) {- try testing.expectEqual(scrollback.visualOfIndex(&m, idx, w), layout.lineOf(c, idx));- }- var y: usize = 0;- while (y < c.total + 3) : (y += 1) {- try testing.expectEqual(scrollback.indexAtVisual(&m, y, w), layout.indexAt(c, y));- try testing.expectEqual(scrollback.stickyUserAbove(&m, y, w), layout.stickyUserAbove(c, y));- }- }- m.toggleToolGroup(2);- m.toggleToolGroup(4);- }-}--test "the live turn's streaming tail and steer notice stay in the layout" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fixture(&m);- var sbuf: [256]u8 = undefined;- var none: [0]engine.Turn = .{};- var job: engine.Job = .{- .gpa = testing.allocator,- .history = &none,- .params = .{},- .stream = .{ .buf = &sbuf },- };- m.pending = &job;- defer m.pending = null;- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();-- // Nothing streamed yet, then prose arrives a chunk at a time: only the tail- // may move, and the whole frame must still match the oracle.- for ([_][]const u8{ "", "thinking about it", "\nand a second line", "\nthird" }) |chunk| {- if (chunk.len > 0) job.stream.appendBytes(chunk);- _ = arena.reset(.retain_capacity);- const a = arena.allocator();- try testing.expectEqualStrings(try scrollback.render(&m, a, 80, m.now_ms), try cachedAll(&m, a, 80));- }- const queued = try testing.allocator.dupe(u8, "next thing");- try m.steer_queue.append(queued);- _ = arena.reset(.retain_capacity);- const a = arena.allocator();- try testing.expectEqualStrings(try scrollback.render(&m, a, 80, m.now_ms), try cachedAll(&m, a, 80));- // A live row belongs to no history entry — clicking it must select nothing.- const c = layout.ensure(&m, 80);- try testing.expect(layout.indexAt(c, c.total - 1) == null);-}--test "appending reuses the whole cached prefix; a fold or a width change does not" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fixture(&m);- var i: usize = 0;- while (i < 40) : (i += 1) try m.push(.assistant, prose);-- const first = layout.ensure(&m, 80);- const blocks = first.blocks.items.len;- try testing.expect(blocks > 10);- try testing.expectEqual(blocks, first.misses);-- // A frame with nothing changed lays NOTHING out again.- first.hits = 0;- first.misses = 0;- _ = layout.ensure(&m, 80);- try testing.expectEqual(@as(u64, 0), first.misses);- try testing.expectEqual(@as(u64, blocks), first.hits);-- // An append re-lays out exactly one block, and the prefix is reused.- first.hits = 0;- first.misses = 0;- try m.push(.assistant, "one more");- _ = layout.ensure(&m, 80);- try testing.expectEqual(@as(u64, 1), first.misses);- try testing.expectEqual(@as(u64, blocks), first.hits);-- // A fold touches its own block only.- first.hits = 0;- first.misses = 0;- m.toggleToolGroup(2);- _ = layout.ensure(&m, 80);- try testing.expectEqual(@as(u64, 1), first.misses);-- // A width change is a cold rebuild; so is a theme change at the same width.- const colds = first.colds;- _ = layout.ensure(&m, 72);- try testing.expectEqual(colds + 1, first.colds);- m.theme_id = .day;- _ = layout.ensure(&m, 72);- try testing.expectEqual(colds + 2, first.colds);-}--test "a cleared history drops the layout with the entries it points into" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try fixture(&m);- const c = layout.ensure(&m, 80);- try testing.expect(c.total > 0);- m.clearHistory();- try testing.expectEqual(@as(usize, 0), m.layout.blocks.items.len);- try testing.expectEqual(@as(usize, 0), layout.ensure(&m, 80).total);- // And the transcript comes back correctly after the reset.- try fixture(&m);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const a = arena.allocator();- try testing.expectEqualStrings(try scrollback.render(&m, a, 80, 0), try cachedAll(&m, a, 80));-}--// --- benchmark ---------------------------------------------------------------fn p95(v: []u64) u64 {- std.mem.sort(u64, v, {}, std.sort.asc(u64));- return v[(v.len * 95) / 100];-}--fn grow(m: *Model, target: usize, width: usize) !void {- while (layout.totalVisualLines(m, width) < target) {- try m.push(.user, "a user prompt that is long enough to wrap at the narrower widths in the matrix");- try m.push(.assistant, prose ++ " " ++ prose);- try m.pushTool(.{ .name = "bash", .detail = "printf hello | wc -c" });- try m.pushTool(.{ .name = "bash", .detail = "6", .done = true });- try m.push(.system, "· a system notice");- }-}--test "layout cache benchmark: frame build while scrolling, and cold rebuild" {- const full = std.c.getenv("GRAFF_TUI_BENCH") != null;- const target: usize = if (full) 10_000 else 1_200;- const frames: usize = if (full) 400 else 40;- const gpa = testing.allocator;- var m: Model = undefined;- m.setup(gpa);- defer m.deinit();- try grow(&m, target, 100);- m.follow = false;- const total = layout.totalVisualLines(&m, 100);-- const scroll_ns = try gpa.alloc(u64, frames);- defer gpa.free(scroll_ns);- const io = std.Io.Threaded.global_single_threaded.io();- // Warm the layout so the first sample is a scroll, not the cold build.- gpa.free(try render_mod.render(&m, gpa, 100, 40, 0));- m.layout.hits = 0;- m.layout.misses = 0;- for (scroll_ns, 0..) |*slot, i| {- m.scroll = (i * 3) % (total - 20);- const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;- const frame = try render_mod.render(&m, gpa, 100, 40, @intCast(i));- slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));- gpa.free(frame);- }- const scroll_p95 = p95(scroll_ns);- // Snapshot before the cold loop: those rebuilds are the thing being timed- // next, and folding them in here would hide the claim this makes.- const scroll_hits = m.layout.hits;- const scroll_misses = m.layout.misses;-- var cold_ns: [6]u64 = undefined;- for (&cold_ns, 0..) |*slot, i| {- const w = widths[i % widths.len];- const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;- const frame = try render_mod.render(&m, gpa, w, 40, 0);- slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));- gpa.free(frame);- }- const cold_max = std.mem.max(u64, &cold_ns);- for (cold_ns, 0..) |ns, i| std.debug.print(- "[layout-bench] cold rebuild at width {d:>4} = {d:.3} ms\n",- .{ widths[i % widths.len], @as(f64, @floatFromInt(ns)) / 1e6 },- );-- // The path this replaces, on the same transcript: one uncached full- // layout, which is what every wheel tick used to cost.- var arena = std.heap.ArenaAllocator.init(gpa);- defer arena.deinit();- var before: [8]u64 = undefined;- for (&before) |*slot| {- _ = arena.reset(.retain_capacity);- const t0 = std.Io.Timestamp.now(io, .boot).nanoseconds;- const text = try scrollback.render(&m, arena.allocator(), 100, 0);- std.mem.doNotOptimizeAway(text.len);- slot.* = @intCast(@max(0, std.Io.Timestamp.now(io, .boot).nanoseconds - t0));- }- const before_med = p95(before[0..4]);-- std.debug.print(- "\n[layout-bench] mode={s} entries={d} display_lines={d} frames={d}\n" ++- " scroll frame build p95 = {d:.3} ms (max {d:.3} ms)\n" ++- " cold rebuild after width change, worst of {d} = {d:.3} ms\n" ++- " block layouts during the scroll run: {d} reused / {d} rebuilt\n" ++- " uncached full layout (the path this replaces) = {d:.3} ms\n",- .{- if (full) "full" else "smoke", m.history.items.len,- total, frames,- @as(f64, @floatFromInt(scroll_p95)) / 1e6, @as(f64, @floatFromInt(scroll_ns[scroll_ns.len - 1])) / 1e6,- cold_ns.len, @as(f64, @floatFromInt(cold_max)) / 1e6,- scroll_hits, scroll_misses,- @as(f64, @floatFromInt(before_med)) / 1e6,- },- );-- // A scroll must never re-lay a block out: that is the whole claim.- try testing.expectEqual(@as(u64, 0), scroll_misses);- try testing.expect(scroll_hits > 0);- if (full) {- try testing.expect(total >= 10_000);- try testing.expect(scroll_p95 < 1_000_000); // < 1 ms- try testing.expect(cold_max < 10_000_000); // < 10 ms- }-}diff --git a/TUI/livetail.zig b/TUI/livetail.zigdeleted file mode 100644index 3b754a8a..00000000--- a/TUI/livetail.zig+++ /dev/null@@ -1,44 +0,0 @@-//! Live stream tail for an in-flight turn. Split from scrollback.zig so-//! the transcript layout stays under the 600-line ceiling.--const std = @import("std");--const app = @import("app.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--/// Drop escapes/C0 from the live tail so a CR cannot rewind the row.-pub fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {- return @import("markdown.zig").sanitize(a, s) catch s;-}--/// True once the engine has put tokens (or raw bash) on the wire. The-/// pending "Thinking" row is then redundant — liveAnswer is the reply.-pub fn liveHasBytes(self: *const Model) bool {- const job = self.pending orelse return false;- if (self.cancel_requested) return false;- return job.stream.len.load(.acquire) > 0 or job.raw.len.load(.acquire) > 0;-}--/// Live prose uses the same renderer as a settled assistant row. Raw bash-/// stays sanitized-only — those bytes are a terminal, not markdown.-pub fn liveTail(self: *const Model, a: std.mem.Allocator, live: []const u8, raw_bash: bool, width: usize) ![]const u8 {- const clean = strip(a, live);- if (raw_bash) return tail(a, clean, width, 4);- const painted = @import("markdown.zig").renderThemed(a, clean, self.theme(), width -| 4) catch clean;- return tail(a, painted, width, 48);-}--pub fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {- var lines = std.array_list.Managed([]const u8).init(a);- var it = std.mem.splitScalar(u8, s, '\n');- // Live tail is prose, or the raw bash projection when that buf is live.- while (it.next()) |ln| try lines.append(ln);- const start = if (lines.items.len > max_lines) lines.items.len - max_lines else 0;- var out = std.array_list.Managed(u8).init(a);- for (lines.items[start..], 0..) |ln, n| {- if (n > 0) try out.append('\n');- try out.appendSlice(try theme_mod.wrapToWidth(a, try std.fmt.allocPrint(a, " {s}", .{ln}), width));- }- return out.items;-}diff --git a/TUI/markdown.zig b/TUI/markdown.zigdeleted file mode 100644index 674b9e9e..00000000--- a/TUI/markdown.zig+++ /dev/null@@ -1,433 +0,0 @@-//! Compact ANSI markdown for the pager. No zigzag — SGR only.--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");-const image = @import("image.zig");--/// Headers, fences, lists, quotes, tasks, `code`, **bold**, `_italic_`, and `/slash` tokens.-pub fn render(a: std.mem.Allocator, src: []const u8, accent: []const u8) ![]const u8 {- return renderTinted(a, src, accent, theme_mod.zinc400, theme_mod.zinc200);-}--// ── Streaming contract ──────────────────────────────────────────────────────-// Every renderer here is a PURE function of the accumulated message text: the-// pager re-renders the whole entry each frame, so a document that arrived in-// deltas lands on exactly the bytes a one-shot render produces. The only thing-// a chunk boundary can hand us is a partial TAIL, and `sanitize` is what makes-// that tail harmless — see markdown_stream_tests.zig for the pinned invariant.--/// Is there anything in `src` a frame cannot carry? Model text goes to the-/// terminal verbatim, so a C0 control (CR rewinds the row, BEL rings, ESC-/// paints) or a byte sequence that is not valid UTF-8 (a delta split a glyph)-/// has to be filtered first. The scan is the fast path: clean prose renders-/// with no copy at all.-fn needsClean(src: []const u8) bool {- for (src) |b| {- if (b < 0x20) {- if (b != '\n' and b != '\t') return true;- } else if (b == 0x7f) return true;- }- return !std.unicode.utf8ValidateSlice(src);-}--/// Drop what `needsClean` found: whole escape sequences (never just the ESC,-/// or the parameter bytes would land as literal text), C0/DEL other than-/// newline and tab, and any byte that is not part of a complete UTF-8-/// codepoint. A glyph the delta cut in half is HELD BACK rather than painted-/// as U+FFFD — the next delta completes it and the frame settles.-pub fn sanitize(a: std.mem.Allocator, src: []const u8) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- errdefer out.deinit();- var i: usize = 0;- while (i < src.len) {- const b = src[i];- if (b == 0x1b) {- i = theme_mod.skipEsc(src, i); // a truncated sequence eats the rest- continue;- }- if (b < 0x20 or b == 0x7f) {- if (b == '\n' or b == '\t') try out.append(b);- i += 1;- continue;- }- if (b < 0x80) {- try out.append(b);- i += 1;- continue;- }- const len = std.unicode.utf8ByteSequenceLength(b) catch {- i += 1;- continue;- };- if (i + len > src.len) break; // the tail of a split glyph: wait for it- _ = std.unicode.utf8Decode(src[i .. i + len]) catch {- i += 1;- continue;- };- try out.appendSlice(src[i .. i + len]);- i += len;- }- return out.toOwnedSlice();-}--/// Theme-aware render: grok-style code fences — markers hidden behind a blank-/// separator row, a full-width background band (clear-to-EOL under the code-/// bg), and token colors from syntax.zig in the theme's polarity. Everything-/// else matches renderTinted.-pub fn renderThemed(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {- const light = th.id == .day;- const clean = if (needsClean(src)) try sanitize(a, src) else src;- defer if (clean.ptr != src.ptr) a.free(clean);- var lines = std.array_list.Managed([]const u8).init(a);- defer lines.deinit();- var split = std.mem.splitScalar(u8, clean, '\n');- while (split.next()) |line| try lines.append(line);-- var out = std.array_list.Managed(u8).init(a);- var in_fence = false;- var lang: ?*const syntax.Lang = null;- var lex: syntax.State = .{};- // This fence is a patch: its lines are banded by diff.zig instead of- // syntax-coloured on the code canvas.- var diff_fence = false;- var first = true;- // The previous line ended inside the code band, so codeBg is still the- // active canvas and the next line that is NOT band content has to reclaim- // it. Restoring on the fence line's own tail instead ended the band at the- // last code glyph: run.zig pads the rest of the row from wherever the line- // left the background, so the band has to stay open until the row ends.- var band = false;- var i: usize = 0;- while (i < lines.items.len) {- const line = lines.items[i];- if (!first) try out.append('\n');- first = false;- const t = std.mem.trimStart(u8, line, " ");- const marker = std.mem.startsWith(u8, t, "```");- if (band and !(in_fence and !marker)) {- try out.appendSlice(th.bg); // leave the band before anything paints- band = false;- }- if (marker) {- in_fence = !in_fence;- diff_fence = false;- if (in_fence) {- lang = syntax.resolve(t[3..]);- lex = .{};- diff_fence = diff.isDiffInfo(t[3..]) or diff.looksLikeLines(lines.items[i + 1 ..]);- }- // Hidden fence markers; the empty row is the grok separator.- i += 1;- continue;- }- if (in_fence and diff_fence) {- // Banded, already wrapped, and closed at every row end — the band- // must not reach the prose under the fence.- try diff.appendLine(&out, line, th, width);- band = false;- i += 1;- continue;- }- if (in_fence) {- try out.appendSlice(syntax.codeBg(light));- try out.appendSlice("\x1b[K");- if (lang) |l| {- try syntax.highlightLine(&out, line, l, &lex, light);- } else {- try out.appendSlice(th.text);- try out.appendSlice(line);- }- try out.appendSlice(theme_mod.reset); // fg/weight only: the band survives to the row end- band = true;- i += 1;- continue;- }- 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;- }- try appendBlock(&out, line, th.accent, th.muted, th.text);- i += 1;- }- return out.toOwnedSlice();-}--pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, muted: []const u8, text: []const u8) ![]const u8 {- const clean = if (needsClean(src)) try sanitize(a, src) else src;- defer if (clean.ptr != src.ptr) a.free(clean);- var lines = std.array_list.Managed([]const u8).init(a);- defer lines.deinit();- var split = std.mem.splitScalar(u8, clean, '\n');- while (split.next()) |line| try lines.append(line);-- var out = std.array_list.Managed(u8).init(a);- var in_fence = false;- var first = true;- var i: usize = 0;- while (i < lines.items.len) {- const line = lines.items[i];- if (!first) try out.append('\n');- first = false;- const t = std.mem.trimStart(u8, line, " ");- if (std.mem.startsWith(u8, t, "```")) {- in_fence = !in_fence;- const lang = std.mem.trim(u8, t[3..], " \t");- try out.appendSlice(muted);- try out.appendSlice(if (in_fence and lang.len > 0) lang else "─────");- try out.appendSlice(theme_mod.reset);- i += 1;- continue;- }- if (in_fence) {- try out.appendSlice(muted);- try out.appendSlice("▏ ");- try out.appendSlice(line);- try out.appendSlice(theme_mod.reset);- i += 1;- continue;- }- if (mdtable.tableLen(lines.items[i..])) |n| {- try mdtable.emitTable(&out, a, lines.items[i .. i + n], accent, muted, text, 0);- i += n;- continue;- }- try appendBlock(&out, line, accent, muted, text);- i += 1;- }- return out.toOwnedSlice();-}--/// User-row display: `@[path]` → `[Image #n]`, `/cmd` in accent.-pub fn renderUser(a: std.mem.Allocator, src: []const u8, accent: []const u8, text: []const u8) ![]const u8 {- const clean = if (needsClean(src)) try sanitize(a, src) else src;- defer if (clean.ptr != src.ptr) a.free(clean);- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(text);- var img_n: u32 = 0;- var i: usize = 0;- while (i < clean.len) {- if (std.mem.startsWith(u8, clean[i..], "@[")) {- if (std.mem.indexOfScalarPos(u8, clean, i + 2, ']')) |close| {- img_n += 1;- var chip: [24]u8 = undefined;- const label = std.fmt.bufPrint(&chip, "[Image #{d}]", .{img_n}) catch "[Image]";- const path = clean[i + 2 .. close];- // Accent only when the file is still there (#577). A stale or- // typed `@[path]` is ordinary text, not an attachment chip.- if (image.pathBacked(path)) {- try out.appendSlice(accent);- try out.appendSlice(label);- try out.appendSlice(text);- } else {- try out.appendSlice(label);- }- i = close + 1;- // Keep the source space; if the next chip/prose is jammed- // against `]`, insert one so `[Image #1][Image #2]see` cannot- // happen (the transcript row looked like a run-on).- if (i < clean.len and clean[i] == ' ') {- try out.append(' ');- i += 1;- } else if (i < clean.len and clean[i] != '\n') {- try out.append(' ');- }- continue;- }- }- if (clean[i] == '/' and (i == 0 or isBreak(clean[i - 1]))) {- var j = i + 1;- while (j < clean.len and (std.ascii.isAlphanumeric(clean[j]) or clean[j] == '-')) j += 1;- if (j > i + 1) {- try out.appendSlice(accent);- try out.appendSlice(clean[i..j]);- try out.appendSlice(text);- i = j;- continue;- }- }- try out.append(clean[i]);- i += 1;- }- return out.toOwnedSlice();-}--/// Headers, lists, quotes, and tasks — the pager's prose blocks. Shared by-/// the themed and tinted renderers so they cannot drift.-fn appendBlock(out: *std.array_list.Managed(u8), line: []const u8, accent: []const u8, muted: []const u8, text: []const u8) !void {- var lead: usize = 0;- while (lead < line.len and line[lead] == ' ') lead += 1;- const body = line[lead..];- var h: usize = 0;- while (h < body.len and body[h] == '#') h += 1;- if (h >= 1 and h <= 6 and h < body.len and body[h] == ' ') {- try out.appendSlice(theme_mod.bold);- try out.appendSlice(accent);- try inlineSpans(out, std.mem.trimStart(u8, body[h + 1 ..], " "), accent, text);- try out.appendSlice(theme_mod.reset);- return;- }- if (body.len >= 3 and isRule(body)) {- try out.appendSlice(muted);- try out.appendSlice("────────────");- try out.appendSlice(theme_mod.reset);- return;- }- if (taskItem(body)) |task| {- try out.appendSlice(line[0..lead]);- try out.appendSlice(accent);- try out.appendSlice(if (task.checked) "☑ " else "☐ ");- try out.appendSlice(text);- try inlineSpans(out, task.text, accent, text);- return;- }- if (std.mem.startsWith(u8, body, "> ")) {- try out.appendSlice(line[0..lead]);- try out.appendSlice(muted);- try out.appendSlice("│ ");- try out.appendSlice(text);- try inlineSpans(out, body[2..], accent, text);- return;- }- if (std.mem.startsWith(u8, body, "- ") or std.mem.startsWith(u8, body, "* ") or std.mem.startsWith(u8, body, "+ ")) {- try out.appendSlice(line[0..lead]);- try out.appendSlice(accent);- try out.appendSlice(if (lead == 0) " • " else " ◦ ");- try out.appendSlice(text);- try inlineSpans(out, body[2..], accent, text);- return;- }- var d: usize = 0;- while (d < body.len and body[d] >= '0' and body[d] <= '9') d += 1;- if (d >= 1 and d + 1 < body.len and (body[d] == '.' or body[d] == ')') and body[d + 1] == ' ') {- try out.appendSlice(line[0..lead]);- try out.appendSlice(accent);- try out.appendSlice(body[0 .. d + 1]);- try out.appendSlice(" ");- try out.appendSlice(text);- try inlineSpans(out, body[d + 2 ..], accent, text);- return;- }- try out.appendSlice(text);- try inlineSpans(out, line, accent, text);-}--const WrappedUrl = struct { url: []const u8, suffix: []const u8 };-const url_wrapper_pairs = [_]struct { open: []const u8, close: []const u8 }{- .{ .open = "**", .close = "**" }, .{ .open = "__", .close = "__" },- .{ .open = "~~", .close = "~~" }, .{ .open = "*", .close = "*" },- .{ .open = "_", .close = "_" }, .{ .open = "`", .close = "`" },-};--fn unwrapUrlCore(core: []const u8, suffix: []const u8) ?WrappedUrl {- var value = core;- var removed = false;- while (true) {- var matched = false;- for (url_wrapper_pairs) |pair| {- if (value.len <= pair.open.len + pair.close.len or- !std.mem.startsWith(u8, value, pair.open) or- !std.mem.endsWith(u8, value, pair.close)) continue;- value = value[pair.open.len .. value.len - pair.close.len];- removed = true;- matched = true;- break;- }- if (!matched) break;- }- if (!removed or !(std.mem.startsWith(u8, value, "http://") or std.mem.startsWith(u8, value, "https://"))) return null;- return .{ .url = value, .suffix = suffix };-}--fn unwrapUrlToken(token: []const u8) ?WrappedUrl {- if (unwrapUrlCore(token, "")) |match| return match;- var end = token.len;- while (end > 0 and std.mem.indexOfScalar(u8, ".,;!?:", token[end - 1]) != null) {- end -= 1;- if (unwrapUrlCore(token[0..end], token[end..])) |match| return match;- }- return null;-}--/// Inline Markdown spans. URL tokens are settled first so wrapper delimiters-/// disappear while identical marker bytes inside an unwrapped URL stay opaque.-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] == '*' or line[i] == '_' or line[i] == '~' or line[i] == '`' or line[i] == 'h') {- var token_end = i;- while (token_end < line.len and !std.ascii.isWhitespace(line[token_end])) token_end += 1;- if (unwrapUrlToken(line[i..token_end])) |match| {- try out.appendSlice(match.url);- try out.appendSlice(match.suffix);- i = token_end;- continue;- }- if (std.mem.startsWith(u8, line[i..], "http://") or std.mem.startsWith(u8, line[i..], "https://")) {- try out.appendSlice(line[i..token_end]);- i = token_end;- continue;- }- }- if (line[i] == '`') {- if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {- try out.appendSlice(accent);- try out.appendSlice(line[i + 1 .. end]);- try out.appendSlice(text);- i = end + 1;- continue;- }- } else if (line[i] == '*' and i + 1 < line.len and line[i + 1] == '*') {- if (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {- try out.appendSlice(theme_mod.bold);- try out.appendSlice(line[i + 2 .. end]);- try out.appendSlice("\x1b[22m"); // bold OFF — a 38;2 fg alone cannot clear SGR 1- try out.appendSlice(text);- i = end + 2;- continue;- }- } else if (line[i] == '_' and (i == 0 or line[i - 1] == ' ')) {- if (std.mem.indexOfScalarPos(u8, line, i + 1, '_')) |end| {- if (end > i + 1) {- try out.appendSlice(theme_mod.dim);- try out.appendSlice(line[i + 1 .. end]);- try out.appendSlice("\x1b[22m"); // dim OFF; a 38;2 fg alone cannot clear SGR 2- try out.appendSlice(text);- i = end + 1;- continue;- }- }- }- try out.append(line[i]);- i += 1;- }-}--const TaskItem = struct { checked: bool, text: []const u8 };--fn taskItem(body: []const u8) ?TaskItem {- if (body.len < 6 or (body[0] != '-' and body[0] != '*' and body[0] != '+') or body[1] != ' ' or body[2] != '[' or body[4] != ']' or body[5] != ' ') return null;- if (body[3] != ' ' and body[3] != 'x' and body[3] != 'X') return null;- return .{ .checked = body[3] != ' ', .text = body[6..] };-}--/// True if every char is one of '-', '*', or '_' (markdown thematic break).-fn isRule(body: []const u8) bool {- const c0 = body[0];- if (c0 != '-' and c0 != '*' and c0 != '_') return false;- for (body) |c| if (c != c0) return false;- return true;-}--fn isBreak(c: u8) bool {- return c == ' ' or c == '\t' or c == '\n' or c == '(' or c == '[';-}--test {- // The tests live next door (this file is at the line ceiling). Without this- // reference they compile for nobody and silently never run.- _ = @import("markdown_tests.zig");-}diff --git a/TUI/markdown_stream_tests.zig b/TUI/markdown_stream_tests.zigdeleted file mode 100644index 40a6a71b..00000000--- a/TUI/markdown_stream_tests.zig+++ /dev/null@@ -1,302 +0,0 @@-//! Streaming-markdown conformance: the pager renders assistant prose from the-//! ACCUMULATED text every frame, so a chunked arrival sequence must land on-//! exactly the bytes a one-shot render produces, and every intermediate frame-//! has to be a legal frame on its own.-//!-//! Two properties are pinned here:-//! IDEMPOTENCE — feeding a document in N-byte chunks and rendering after-//! each chunk ends byte-identical to rendering it once.-//! PREFIX SAFETY — every intermediate frame is valid UTF-8, carries no C0-//! control the model smuggled in, never holds a truncated-//! escape sequence, and closes every SGR weight it opened.--const std = @import("std");--const markdown = @import("markdown.zig");-const theme_mod = @import("theme.zig");--/// Documents that exercise every state the renderer threads across lines:-/// fences (closed, open, CRLF, block-comment), tables, nested lists, inline-/// markers (matched and dangling), emoji and CJK.-const fixtures = [_][]const u8{- // 0 — a closed fence with strings, escapes, numbers and a comment.- "# Title\nintro text\n```zig\nconst x: u32 = 0x1f; // note\nconst s = \"a\\nb\";\n```\ntail line\n",- // 1 — a fence that never closes: the stream ended mid-block.- "before\n```py\ndef f(x):\n return x + 1\n",- // 2 — CRLF everywhere, fence included.- "para one\r\n```js\r\nlet a = 1; /* open\r\nstill comment */ let b = 2;\r\n```\r\nafter\r\n",- // 3 — a pipe table plus a dangling partial row.- "| Path | What |\n| --- | --- |\n| src/ | the product |\n| `TUI/` | pager |\n",- // 4 — nested lists, emoji, CJK.- "- top level 🚀\n - nested 日本語 item\n - another ✓ one\n- back out 中文字\n",- // 5 — inline markers: matched, dangling, and adjacent.- "a `code` b **bold** c `open d **half e ``\nsecond **line** with `tick`\n",- // 6 — emoji and CJK INSIDE a fence, where the lexer walks bytes.- "```go\nfmt.Println(\"日本語 🚀 done\")\n```\n",- // 7 — prose carrying raw terminal control the model must never be able to- // paint with, plus a bare CR mid-line.- "safe \x1b[31mred?\x1b[0m and \x07bell\rreturn\nnext line\n",- // 8 — a fence whose info string is a grok citation path.- "```12:34:src/main.rs\nlet v: Vec<u8> = vec![1, 2, 3];\n```\n",- // 9 — headings, rules and a fence opened immediately after a table.- "## Heading\n| a | b |\n|---|---|\n| 1 | 2 |\n```sh\necho \"hi \\\n```\n",- // 10 — numbered lists, quotes, tasks, a rule, italic.- "1. first\n> note\n- [x] done\n- [ ] todo\n---\n_em_ and snake_case\n",-};--fn oneShot(a: std.mem.Allocator, src: []const u8, th: theme_mod.Theme, width: usize) ![]const u8 {- return markdown.renderThemed(a, src, th, width);-}--/// Walk the frame the way a terminal would and reject anything a live pager-/// could not survive.-fn checkFrame(frame: []const u8) !void {- try std.testing.expect(std.unicode.utf8ValidateSlice(frame));- var i: usize = 0;- var open_bold = false;- while (i < frame.len) {- const b = frame[i];- if (b == 0x1b) {- const end = theme_mod.skipEsc(frame, i);- // A truncated escape reaches the terminal as garbage and swallows- // the glyphs behind it: the last byte must be a real final byte.- try std.testing.expect(end > i + 1);- const fin = frame[end - 1];- try std.testing.expect(fin >= 0x40 and fin <= 0x7e);- const seq = frame[i..end];- if (std.mem.eql(u8, seq, theme_mod.bold)) open_bold = true;- if (std.mem.eql(u8, seq, "\x1b[22m") or std.mem.eql(u8, seq, theme_mod.reset)) open_bold = false;- i = end;- continue;- }- if (b == '\n') {- // Weight must not bleed across a row: run.zig pads from whatever- // state the row left behind.- try std.testing.expect(!open_bold);- i += 1;- continue;- }- // \t is legal prose; every other C0 (CR, BEL, NUL…) moves or rings the- // terminal and must have been filtered out of the model's text.- try std.testing.expect(b >= 0x20 or b == '\t');- try std.testing.expect(b != 0x7f);- i += 1;- }- try std.testing.expect(!open_bold);-}--/// Accumulate `src` in `chunk`-byte deltas, rendering after each one, and-/// return the final frame. Every intermediate frame is checked.-fn streamRender(- a: std.mem.Allocator,- src: []const u8,- th: theme_mod.Theme,- width: usize,- chunk: usize,-) ![]const u8 {- var acc = std.array_list.Managed(u8).init(a);- defer acc.deinit();- var last: []const u8 = "";- var i: usize = 0;- while (i < src.len) {- const n = @min(chunk, src.len - i);- try acc.appendSlice(src[i .. i + n]);- i += n;- last = try markdown.renderThemed(a, acc.items, th, width);- try checkFrame(last);- }- return last;-}--test "idempotence: chunked arrival lands on the one-shot render" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- for ([_]theme_mod.Id{ .night, .day }) |id| {- const th = theme_mod.of(id);- for (fixtures) |src| {- const want = try oneShot(a, src, th, 60);- try checkFrame(want);- var chunk: usize = 1;- while (chunk <= 7) : (chunk += 1) {- const got = try streamRender(a, src, th, 60, chunk);- try std.testing.expectEqualStrings(want, got);- }- }- }-}--test "prefix safety: a split at EVERY byte boundary renders a legal frame" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- for (fixtures) |src| {- const want = try oneShot(a, src, th, 48);- var k: usize = 0;- while (k <= src.len) : (k += 1) {- // The rolling window: the model stopped exactly here.- const head = try markdown.renderThemed(a, src[0..k], th, 48);- try checkFrame(head);- // …and then the rest arrives in one go.- const settled = try markdown.renderThemed(a, src, th, 48);- try std.testing.expectEqualStrings(want, settled);- }- _ = arena.reset(.retain_capacity);- }-}--test "a glyph split across chunks never leaves replacement garbage" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const src = "emoji 🚀 and 日本語 text";- var k: usize = 0;- while (k <= src.len) : (k += 1) {- const head = try markdown.renderThemed(a, src[0..k], th, 40);- // Valid UTF-8 at every boundary: a half-written glyph is HELD BACK- // until its tail arrives rather than painted as U+FFFD.- try std.testing.expect(std.unicode.utf8ValidateSlice(head));- }- const full = try markdown.renderThemed(a, src, th, 40);- try std.testing.expect(std.mem.indexOf(u8, full, "🚀") != null);- try std.testing.expect(std.mem.indexOf(u8, full, "日本語") != null);-}--test "CRLF: a carriage return never reaches the frame" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const out = try markdown.renderThemed(a, "alpha\r\nbeta\r\n```zig\r\nconst x = 1;\r\n```\r\n", th, 40);- try std.testing.expect(std.mem.indexOfScalar(u8, out, '\r') == null);- try std.testing.expect(std.mem.indexOf(u8, out, "alpha") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "const") != null);- // A CR line ending must not survive as a visible column either.- var it = std.mem.splitScalar(u8, out, '\n');- while (it.next()) |ln| try std.testing.expect(theme_mod.visibleLen(ln) <= 40);-}--test "model text cannot smuggle its own SGR or cursor control into the frame" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const out = try markdown.renderThemed(a, "hi \x1b[2Jwiped \x1b[38;2;255;0;0mred\x1b[0m done", th, 40);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[2J") == null);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[38;2;255;0;0m") == null);- // The literal parameter bytes must not be left behind as text either.- try std.testing.expect(std.mem.indexOf(u8, out, "[2J") == null);- try std.testing.expect(std.mem.indexOf(u8, out, "wiped") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "done") != null);- // A truncated escape at the very end of a delta is dropped whole — no- // half-sequence on the wire, no leftover parameter bytes as text.- const cut = try markdown.renderThemed(a, "tail \x1b[9987", th, 40);- try std.testing.expect(std.mem.indexOf(u8, cut, "9987") == null);- try std.testing.expect(std.mem.indexOf(u8, cut, "tail") != null);- try checkFrame(cut);-}--test "an unterminated fence renders as tentative code and settles when it closes" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const syntax = @import("syntax.zig");- const bg = syntax.codeBg(false);- const open = try markdown.renderThemed(a, "```zig\nconst x = 1;", th, 40);- try std.testing.expect(std.mem.indexOf(u8, open, bg) != null); // already code- const closed = try markdown.renderThemed(a, "```zig\nconst x = 1;\n```\nafter", th, 40);- // The code row is byte-identical before and after the fence closes: the- // block settles, it does not re-render differently.- const open_row = std.mem.sliceTo(open[std.mem.indexOf(u8, open, bg).?..], '\n');- const closed_row = std.mem.sliceTo(closed[std.mem.indexOf(u8, closed, bg).?..], '\n');- try std.testing.expectEqualStrings(open_row, closed_row);-}--test "highlighting state is per BLOCK, not per chunk" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const syntax = @import("syntax.zig");- const comment = syntax.color(.comment, false);- // The block comment opens on one line and closes on the next; the lexer- // must carry that across the line break no matter how the bytes arrived.- const src = "```js\nlet a = 1; /* open\nstill inside\n*/ let b = 2;\n```\n";- const want = try markdown.renderThemed(a, src, th, 60);- try std.testing.expect(std.mem.indexOf(u8, want, comment) != null);- var chunk: usize = 1;- while (chunk <= 5) : (chunk += 1) {- const got = try streamRender(a, src, th, 60, chunk);- try std.testing.expectEqualStrings(want, got);- }- // A SECOND fence restarts the lexer: an open block comment in the first- // one must not colour the second one's first line.- const two = try markdown.renderThemed(a, "```js\n/* open\n```\n```js\nlet c = 3;\n```\n", th, 60);- var rows = std.mem.splitScalar(u8, two, '\n');- var body: []const u8 = "";- while (rows.next()) |ln| {- // The last banded row is the second fence's only code line; its tokens- // are SGR-separated, so match on the band, not on the text.- if (std.mem.indexOf(u8, ln, syntax.codeBg(false)) != null) body = ln;- }- try std.testing.expect(body.len > 0);- try std.testing.expect(std.mem.indexOf(u8, body, comment) == null);- try std.testing.expect(std.mem.indexOf(u8, body, syntax.color(.keyword, false)) != null);-}--test "inline emphasis split across chunks stays literal, then settles" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- // Half a marker pair is TEXT: it must not open a weight that then runs on- // into the rest of the message.- for ([_][]const u8{ "a **bol", "a **bold*", "a `open", "a *" }) |half| {- const frame = try markdown.renderThemed(a, half, th, 40);- try std.testing.expect(std.mem.indexOf(u8, frame, theme_mod.bold) == null);- try checkFrame(frame);- }- // The closing marker arrives and the span settles into a closed weight.- const done = try markdown.renderThemed(a, "a **bold** b", th, 40);- try std.testing.expect(std.mem.indexOf(u8, done, theme_mod.bold) != null);- try std.testing.expect(std.mem.indexOf(u8, done, "\x1b[22m") != null);- try checkFrame(done);- // …and the marker itself is gone, not left on screen.- try std.testing.expect(std.mem.indexOf(u8, done, "**") == null);-}--test "end to end: hostile assistant prose cannot corrupt a transcript row" {- const app = @import("app.zig");- const scrollback = @import("scrollback.zig");- var m: app.Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "row one\rWIPED \x1b[2J\x1b[38;2;255;0;0mred\r\n```zig\r\nconst x = 1; // 日本語 🚀\r\n```\r\ndone");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const frame = try scrollback.render(&m, arena.allocator(), 40, 0);- try std.testing.expect(std.mem.indexOfScalar(u8, frame, '\r') == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "\x1b[2J") == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "\x1b[38;2;255;0;0m") == null);- try std.testing.expect(std.unicode.utf8ValidateSlice(frame));- try std.testing.expect(std.mem.indexOf(u8, frame, "日本語") != null);- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| try std.testing.expect(theme_mod.visibleLen(ln) <= 40);-}--test "renderUser is chunk-safe too" {- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const src = "look at \x1b[31m@[/tmp/a.png]\r /goal 日本語 🚀";- var k: usize = 0;- while (k <= src.len) : (k += 1) {- const head = try markdown.renderUser(a, src[0..k], theme_mod.emerald, theme_mod.zinc200);- try std.testing.expect(std.unicode.utf8ValidateSlice(head));- try std.testing.expect(std.mem.indexOfScalar(u8, head, '\r') == null);- try std.testing.expect(std.mem.indexOf(u8, head, "[31m") == null);- }-}diff --git a/TUI/markdown_tests.zig b/TUI/markdown_tests.zigdeleted file mode 100644index c0545177..00000000--- a/TUI/markdown_tests.zig+++ /dev/null@@ -1,340 +0,0 @@-//! Tests for markdown.zig — the renderer's own file sits at the 600-line-//! ceiling, so its test block lives here. Reached from markdown.zig's test-//! block, which is reached from root.zig: a module nobody references never-//! runs its tests at all.--const std = @import("std");--const diff = @import("diff.zig");-const dump = @import("dump.zig");-const syntax = @import("syntax.zig");-const theme_mod = @import("theme.zig");--const markdown = @import("markdown.zig");-const render = markdown.render;-const renderThemed = markdown.renderThemed;-const renderTinted = markdown.renderTinted;-const renderUser = markdown.renderUser;--test "numbered lists, quotes, and tasks render as blocks" {- const text = try render(std.testing.allocator, "1. first\n> note\n- [x] done\n- [ ] todo\n+ plus", theme_mod.emerald);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "1.") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "│ ") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "☑") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "☐") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "•") != null);-}--test "rules, nested bullets, and _italic_ paint; #needspace is not a heading" {- const text = try render(std.testing.allocator, "---\n - nested\n_em_ and snake_case\n#needspace", theme_mod.emerald);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "────────────") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "◦") != null);- try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.dim ++ "em" ++ "\x1b[22m") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "snake_case") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "#needspace") != null);-}--test "render paints headers, code, bold, and bullets" {- const text = try render(std.testing.allocator, "# Title\n- item\n`code` and **bold**\n```zig\nconst x = 1;\n```", theme_mod.emerald);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "Title") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "•") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "code") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "bold") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "▏ ") != null);- try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald) != null);-}--test "render keeps the issue URL exact while hiding bold delimiters" {- const url = "https://github.com/justrach/codegraff/issues/728";- const out = try render(std.testing.allocator, "**https://github.com/justrach/codegraff/issues/728**", theme_mod.emerald);- defer std.testing.allocator.free(out);- const visible = try dump.visible(std.testing.allocator, out);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings(url, visible);- try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);-}--test "renderThemed keeps the issue URL exact while hiding bold delimiters" {- const url = "https://github.com/justrach/codegraff/issues/728";- const out = try renderThemed(std.testing.allocator, "**https://github.com/justrach/codegraff/issues/728**", theme_mod.of(.night), 80);- defer std.testing.allocator.free(out);- const visible = try dump.visible(std.testing.allocator, out);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings(url, visible);- try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);-}--test "render keeps a label before a bold URL" {- const out = try render(std.testing.allocator, "Issue #728: **https://github.com/justrach/codegraff/issues/728**", theme_mod.emerald);- defer std.testing.allocator.free(out);- const visible = try dump.visible(std.testing.allocator, out);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings("Issue #728: https://github.com/justrach/codegraff/issues/728", visible);- try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);-}--test "renderThemed leaves punctuation outside a bold URL" {- const out = try renderThemed(std.testing.allocator, "See **https://github.com/justrach/codegraff/issues/728**, then continue.", theme_mod.of(.night), 80);- defer std.testing.allocator.free(out);- const visible = try dump.visible(std.testing.allocator, out);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings("See https://github.com/justrach/codegraff/issues/728, then continue.", visible);- try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);-}--test "render and renderThemed preserve an unwrapped URL ending in /**" {- const url = "https://github.com/justrach/codegraff/issues/728/**";- const plain = try render(std.testing.allocator, url, theme_mod.emerald);- defer std.testing.allocator.free(plain);- const plain_visible = try dump.visible(std.testing.allocator, plain);- defer std.testing.allocator.free(plain_visible);- try std.testing.expectEqualStrings(url, plain_visible);-- const themed = try renderThemed(std.testing.allocator, url, theme_mod.of(.night), 80);- defer std.testing.allocator.free(themed);- const themed_visible = try dump.visible(std.testing.allocator, themed);- defer std.testing.allocator.free(themed_visible);- try std.testing.expectEqualStrings(url, themed_visible);-}--fn expectVisible(out: []const u8, expected: []const u8) !void {- const visible = try dump.visible(std.testing.allocator, out);- defer std.testing.allocator.free(visible);- try std.testing.expectEqualStrings(expected, visible);-}--test "render URL wrappers as clean visible text" {- const url = "https://github.com/justrach/codegraff/issues/728";- const cases = [_]struct { source: []const u8, expected: []const u8 }{- .{ .source = "*" ++ url ++ "*", .expected = url },- .{ .source = "**" ++ url ++ "**", .expected = url },- .{ .source = "_" ++ url ++ "_", .expected = url },- .{ .source = "__" ++ url ++ "__", .expected = url },- .{ .source = "~~" ++ url ++ "~~", .expected = url },- .{ .source = "`" ++ url ++ "`", .expected = url },- // Independent spans are the mixed form supported by the TUI renderer.- .{ .source = "**" ++ url ++ "** and _" ++ url ++ "_ and `" ++ url ++ "`", .expected = url ++ " and " ++ url ++ " and " ++ url },- .{ .source = "See **" ++ url ++ "**, then continue.", .expected = "See " ++ url ++ ", then continue." },- };-- for (cases) |case| {- const plain = try render(std.testing.allocator, case.source, theme_mod.emerald);- defer std.testing.allocator.free(plain);- try expectVisible(plain, case.expected);-- const themed = try renderThemed(std.testing.allocator, case.source, theme_mod.of(.night), 120);- defer std.testing.allocator.free(themed);- try expectVisible(themed, case.expected);- }-}--test "render and renderThemed preserve marker text in unwrapped URLs" {- const cases = [_][]const u8{- "See https://example.com/path/** followed by prose.",- "https://example.com/path/__",- "https://example.com/path/~~",- "https://example.com/search?q=*",- "https://docs.python.org/3/reference/datamodel.html#object.__init__",- "https://example.com/path/a**b",- };-- for (cases) |url| {- const plain = try render(std.testing.allocator, url, theme_mod.emerald);- defer std.testing.allocator.free(plain);- try expectVisible(plain, url);-- const themed = try renderThemed(std.testing.allocator, url, theme_mod.of(.night), 120);- defer std.testing.allocator.free(themed);- try expectVisible(themed, url);- }-}--test "the code band stays open to the row end and is released on the next line" {- const th = theme_mod.of(.night);- const code_bg = syntax.codeBg(false);- const out = try renderThemed(std.testing.allocator, "intro\n```\nabc\ndef\n```\nafter", th, 40);- defer std.testing.allocator.free(out);- var it = std.mem.splitScalar(u8, out, '\n');- var rows: usize = 0;- var was_band = false;- var band_rows: usize = 0;- while (it.next()) |ln| : (rows += 1) {- const band = std.mem.indexOf(u8, ln, code_bg) != null;- if (band) {- // run.zig pads a row from whatever background the line left active,- // so a band row must NOT hand the canvas back before it ends.- try std.testing.expect(std.mem.indexOf(u8, ln, th.bg) == null);- band_rows += 1;- } else if (was_band) {- // The first row off the band reclaims the theme canvas up front.- try std.testing.expect(std.mem.startsWith(u8, ln, th.bg));- }- was_band = band;- }- try std.testing.expectEqual(@as(usize, 2), band_rows); // abc, def- // intro, opening separator, abc, def, closing separator, after- try std.testing.expectEqual(@as(usize, 6), rows);-}--test "a wrapped fence line carries its band onto every continuation row" {- const th = theme_mod.of(.night);- const bg = syntax.codeBg(false);- const src =- \\```zig- \\const message = try std.fmt.allocPrint(gpa, "hello {s} world", .{name});- \\```- ;- const body = try renderThemed(std.testing.allocator, src, th, 36);- defer std.testing.allocator.free(body);- const wrapped = try theme_mod.wrapToWidth(std.testing.allocator, body, 36);- defer std.testing.allocator.free(wrapped);- var it = std.mem.splitScalar(u8, wrapped, '\n');- var code_rows: usize = 0;- while (it.next()) |ln| {- if (theme_mod.visibleLen(ln) == 0) continue; // fence separators- code_rows += 1;- // A syntax-coloured line spends an SGR per token; the old byte-capped- // tracker had dropped the background long before the wrap point.- try std.testing.expect(std.mem.indexOf(u8, ln, bg) != null);- }- try std.testing.expect(code_rows > 1); // it really did wrap-}--test "no code background leaks past a closed fence or off the last fence row" {- const th = theme_mod.of(.night);- const code_bg = syntax.codeBg(false);- const closed = try renderThemed(std.testing.allocator, "```\nx\n```\ntail", th, 40);- defer std.testing.allocator.free(closed);- // The band ends with the fence, the next row takes the canvas back, and no- // later row re-opens codeBg.- var it = std.mem.splitScalar(u8, closed, '\n');- var seen_band = false;- var restored = false;- while (it.next()) |ln| {- const band = std.mem.indexOf(u8, ln, code_bg) != null;- if (band) {- try std.testing.expect(!restored); // never re-opened- seen_band = true;- continue;- }- if (seen_band and !restored) {- try std.testing.expect(std.mem.startsWith(u8, ln, th.bg));- restored = true;- }- }- try std.testing.expect(seen_band and restored);- // A message that ends mid-fence keeps its band (that row IS code) and adds- // no stray row after it for the theme bg to land on.- const open = try renderThemed(std.testing.allocator, "```\nx", th, 40);- defer std.testing.allocator.free(open);- try std.testing.expect(std.mem.indexOf(u8, open, th.bg) == null);- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, open, "\n"));-}--test "renderUser chips @[path] and paints slash commands" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = "a.png", .data = "png" });- var dir_buf: [std.fs.max_path_bytes]u8 = undefined;- const dir_n = try tmp.dir.realPath(io, &dir_buf);- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const live = try std.fmt.bufPrint(&path_buf, "{s}/a.png", .{dir_buf[0..dir_n]});- const src = try std.fmt.allocPrint(std.testing.allocator, "@[{s}] /goal look at this", .{live});- defer std.testing.allocator.free(src);- const text = try renderUser(std.testing.allocator, src, theme_mod.emerald, theme_mod.zinc200);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "[Image #1]") != null);- try std.testing.expect(std.mem.indexOf(u8, text, live) == null);- try std.testing.expect(std.mem.indexOf(u8, text, "/goal") != null);- try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald ++ "[Image #1]") != null);-}--test "renderUser leaves an unbacked @[path] uncolored (#577)" {- const text = try renderUser(std.testing.allocator, "@[/no/such/image-577.png] look", theme_mod.emerald, theme_mod.zinc200);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "[Image #1]") != null);- try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald ++ "[Image #1]") == null);-}--test "renderUser keeps a space between chips and prose" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = "a.png", .data = "png" });- try tmp.dir.writeFile(io, .{ .sub_path = "b.png", .data = "png" });- var dir_buf: [std.fs.max_path_bytes]u8 = undefined;- const dir_n = try tmp.dir.realPath(io, &dir_buf);- const dir = dir_buf[0..dir_n];- const src = try std.fmt.allocPrint(std.testing.allocator, "@[{s}/a.png] @[{s}/b.png]see this", .{ dir, dir });- defer std.testing.allocator.free(src);- const text = try renderUser(std.testing.allocator, src, theme_mod.emerald, theme_mod.zinc200);- defer std.testing.allocator.free(text);- const vis = try @import("dump.zig").visible(std.testing.allocator, text);- defer std.testing.allocator.free(vis);- try std.testing.expectEqualStrings("[Image #1] [Image #2] see this", vis);-}--test "render paints a Grok-style box table and hides raw pipes" {- const src = "| Path | What |\n| --- | --- |\n| src/ | the product |\n| `TUI/` | pager |\n";- const text = try render(std.testing.allocator, src, theme_mod.emerald);- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "┌") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "│") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "src/") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "pager") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "| --- |") == null);- try std.testing.expect(std.mem.indexOf(u8, text, "| Path |") == null);-}--test "a wide table fits the terminal: grid intact, one visual line per row (#tables)" {- const th = theme_mod.of(.night);- const md = "| Transport | Grok (this wire) | Codex / Claude |\n|---|---|---|\n| Item delta (previous_response_id) with a very long explanation cell that used to blow the grid | no (stalls) everywhere on narrow terminals | yes, if props match and the moon is right |";- const out = try renderThemed(std.testing.allocator, md, th, 60);- defer std.testing.allocator.free(out);- var it = std.mem.splitScalar(u8, out, '\n');- var rows: usize = 0;- while (it.next()) |ln| : (rows += 1) {- try std.testing.expect(theme_mod.visibleLen(ln) <= 60);- }- try std.testing.expectEqual(@as(usize, 5), rows); // top rule, header, mid rule, body, bottom rule- try std.testing.expect(std.mem.indexOf(u8, out, "\u{2026}") != null); // over-long cells clip with an ellipsis-}--test "a diff fence bands its edits instead of taking the code canvas" {- const th = theme_mod.of(.night);- const src = "before\n```diff\n@@ -1,2 +1,2 @@\n const keep = 0;\n-const old = 1;\n+const new = 2;\n```\nafter";- const out = try renderThemed(std.testing.allocator, src, th, 40);- defer std.testing.allocator.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, diff.addBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, out, diff.delBg(false)) != null);- // A patch is not code: it never picks up the fence's own background.- try std.testing.expect(std.mem.indexOf(u8, out, syntax.codeBg(false)) == null);- var it = std.mem.splitScalar(u8, out, '\n');- while (it.next()) |ln| {- try std.testing.expect(theme_mod.visibleLen(ln) <= 40);- if (std.mem.indexOf(u8, ln, "after") == null) continue;- // The prose under the fence inherits neither band.- try std.testing.expect(std.mem.indexOf(u8, ln, diff.addBg(false)) == null);- try std.testing.expect(std.mem.indexOf(u8, ln, diff.delBg(false)) == null);- }-}--test "an undeclared fence that IS a patch bands; a bullet list never does" {- const th = theme_mod.of(.night);- const patch = try renderThemed(std.testing.allocator, "```\n--- a/x\n+++ b/x\n-gone\n+here\n```", th, 40);- defer std.testing.allocator.free(patch);- try std.testing.expect(std.mem.indexOf(u8, patch, diff.addBg(false)) != null);- // Lines that merely START with `-` are a list, not a diff (#diff).- const list = try renderThemed(std.testing.allocator, "- one\n- two\n- three", th, 40);- defer std.testing.allocator.free(list);- try std.testing.expect(std.mem.indexOf(u8, list, diff.delBg(false)) == null);- // …and a zig fence still gets syntax colors on the code canvas.- const code = try renderThemed(std.testing.allocator, "```zig\nconst x = 1;\n```", th, 40);- defer std.testing.allocator.free(code);- try std.testing.expect(std.mem.indexOf(u8, code, syntax.codeBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, code, diff.addBg(false)) == null);-}diff --git a/TUI/mdtable.zig b/TUI/mdtable.zigdeleted file mode 100644index 72c7f7a4..00000000--- a/TUI/mdtable.zig+++ /dev/null@@ -1,165 +0,0 @@-//! 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/meters.zig b/TUI/meters.zigdeleted file mode 100644index 1c19c55d..00000000--- a/TUI/meters.zig+++ /dev/null@@ -1,137 +0,0 @@-//! The readouts backed by the ENGINE's meters (#551): /context and-//! /session-info.-//!-//! Both used to be answered from `chars_in`/`chars_out`, two counters the TUI-//! incremented with the length of the text it had drawn. That is not a context-//! window and never was: it missed the system prompt, the tool catalog and-//! every tool result, it counted characters where the provider counts tokens,-//! and it only grew — a compaction that halved the real context left the-//! "context" line climbing. The engine already computes ContextMeter and-//! CostMeter for its own status line; those now arrive as a typed event and-//! this file renders them.-//!-//! Split out of dispatch.zig for the 600-line cap.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const Model = app.Model;--/// `/context`.-pub fn contextInfo(self: *Model) void {- const st = self.status orelse {- self.push(.system, "context: not measured yet — the meter fills in once a turn reports usage") catch {};- return;- };- if (!st.has_context) {- self.pushFmt(.system, "context: {s} has not reported usage yet", .{st.model}) catch {};- return;- }- self.pushFmt(.system, "context: {d} / {d} tokens ({d}%) · cache {d}% · compacts at {d} · {d} cached", .{- st.tokens,- st.window,- st.percent(),- st.cachePercent() orelse 0,- st.compact_at,- st.cache_read,- }) catch {};-}--/// `/session-info` — mode, model and turn count from the Model; context and-/// spend from the engine.-pub fn sessionInfo(self: *Model) void {- var buf: [64]u8 = undefined;- const ctx: []const u8 = if (self.contextPercent()) |p|- (std.fmt.bufPrint(&buf, "{d}% context", .{p}) catch "context ?")- else- "context not measured";- const spend: []const u8 = if (self.status) |st| switch (st.cost) {- .hidden => "",- .subscription => " · subscription",- .unpriced => " · unpriced",- .usd => " · see /cost",- } else "";- self.pushFmt(.system, "{s} · {s} · {d} turn(s) · {s}{s} · {s}", .{- self.modeLabel(),- engine.g_model_name,- self.turns,- ctx,- spend,- engine.g_cwd,- }) catch {};-}--const testing = std.testing;--test "/context reports the engine's tokens, never a character count (#551)" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();-- // Before any turn there is nothing measured, and the line says so rather- // than printing a 0 that reads like an empty context.- contextInfo(&m);- try testing.expect(std.mem.indexOf(u8, m.history.items[0].text, "not measured") != null);-- m.setStatus(.{- .model = "sonnet",- .provider_id = "anthropic",- .has_context = true,- .tokens = 12_345,- .window = 200_000,- .compact_at = 160_000,- .cache_read = 2048,- .cost = .{ .usd = 0.42 },- });- contextInfo(&m);- const line = m.history.items[m.history.items.len - 1].text;- try testing.expect(std.mem.indexOf(u8, line, "12345") != null);- try testing.expect(std.mem.indexOf(u8, line, "200000") != null);- try testing.expect(std.mem.indexOf(u8, line, "6%") != null);- try testing.expect(std.mem.indexOf(u8, line, "cache 16%") != null);- try testing.expect(std.mem.indexOf(u8, line, "160000") != null);- try testing.expect(std.mem.indexOf(u8, line, "2048") != null);- try testing.expect(std.mem.indexOf(u8, line, "chars") == null);-}--test "/session-info shows context share, not characters" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- m.turns = 3;-- sessionInfo(&m);- try testing.expect(std.mem.indexOf(u8, m.history.items[0].text, "context not measured") != null);-- m.setStatus(.{- .model = "gpt-5.6",- .provider_id = "codex",- .has_context = true,- .tokens = 100_000,- .window = 200_000,- .cost = .subscription,- });- sessionInfo(&m);- const line = m.history.items[m.history.items.len - 1].text;- try testing.expect(std.mem.indexOf(u8, line, "3 turn(s)") != null);- try testing.expect(std.mem.indexOf(u8, line, "50% context") != null);- try testing.expect(std.mem.indexOf(u8, line, "subscription") != null);- try testing.expect(std.mem.indexOf(u8, line, " in / ") == null);-}--test "a status the engine has not measured yields no percent anywhere" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try testing.expect(m.contextPercent() == null);- // A turn ran but the provider reported no usage: still nothing to show.- m.setStatus(.{ .model = "local", .provider_id = "lmstudio" });- try testing.expect(m.contextPercent() == null);- // Measured: the share is the engine's, capped at 100.- m.setStatus(.{ .model = "local", .provider_id = "lmstudio", .has_context = true, .tokens = 500, .window = 400 });- try testing.expectEqual(@as(u64, 100), m.contextPercent().?);- // Replacing the status frees the old strings — the leak checker owns this- // assertion, but the identity is worth stating.- try testing.expectEqualStrings("local", m.status.?.model);-}diff --git a/TUI/model_confirmation_tests.zig b/TUI/model_confirmation_tests.zigdeleted file mode 100644index d6060a39..00000000--- a/TUI/model_confirmation_tests.zig+++ /dev/null@@ -1,208 +0,0 @@-//! /model confirmation regressions, driven through terminal command dispatch.-//! Imported by the parent test root; callbacks never contact a provider.-const std = @import("std");-const engine = @import("engine.zig");-const sim = @import("sim.zig");--const Fixture = struct {- provider: []const u8 = "seat-a",- model: []const u8 = "model-a",- requested: []const u8 = "model-a",- fail: bool = false,- picker: bool = false,- calls: usize = 0,- valid_request: bool = true,-- fn select(ctx: ?*anyopaque, alloc: std.mem.Allocator, provider: []const u8, name: []const u8) ?engine.Picked {- const self: *Fixture = @ptrCast(@alignCast(ctx.?));- self.calls += 1;- // Typed commands must leave routing to the backend, unlike picker rows.- const expected_provider = if (self.picker) self.provider else "";- self.valid_request = self.valid_request and std.mem.eql(u8, provider, expected_provider) and std.mem.eql(u8, name, self.requested);- if (self.fail) return null;- return .{- .model = alloc.dupe(u8, self.model) catch return null,- .provider = self.provider,- };- }-};--const Saved = struct {- ctx: ?*anyopaque,- callback: ?engine.ModelFn,- model: []const u8,- provider: []const u8,-- fn install(fixture: *Fixture) Saved {- const saved: Saved = .{- .ctx = engine.g_turn_ctx,- .callback = engine.g_model_fn,- .model = engine.g_model_name,- .provider = engine.g_model_provider,- };- engine.g_turn_ctx = fixture;- engine.g_model_fn = Fixture.select;- engine.g_model_name = "model-a";- engine.g_model_provider = "seat-a";- return saved;- }-- fn restore(self: Saved) void {- engine.g_turn_ctx = self.ctx;- engine.g_model_fn = self.callback;- engine.g_model_name = self.model;- engine.g_model_provider = self.provider;- }-};--fn submit(term: *sim.Term, name: []const u8) !void {- _ = term.typeText("/model ");- _ = term.typeText(name);- _ = term.enter();- try std.testing.expect(term.model.pending == null);- try std.testing.expect(term.model.bg == null);-}--fn expectConfirmation(term: *sim.Term, expected: []const u8) !void {- const history = term.model.history.items;- try std.testing.expect(history.len > 0);- const last = history[history.len - 1];- try std.testing.expectEqual(.system, last.kind);- try std.testing.expectEqualStrings(expected, last.text);-}--fn successfulSelection(fixture: *Fixture, expected: []const u8, repetitions: usize) !void {- const saved = Saved.install(fixture);- defer saved.restore();- var term: sim.Term = undefined;- term.init(std.testing.allocator, 100, 30);- defer term.deinit();- for (0..repetitions) |_| {- try submit(&term, fixture.requested);- try expectConfirmation(&term, expected);- try std.testing.expectEqualStrings(fixture.model, engine.g_model_name);- try std.testing.expectEqualStrings(fixture.provider, engine.g_model_provider);- }- try std.testing.expectEqual(repetitions, fixture.calls);- try std.testing.expect(fixture.valid_request);-}--test "model confirmation: repeated resolved selection is already using" {- var fixture: Fixture = .{};- // The second result is freshly allocated while the previous model is owned- // by the UI: compare values before adoption frees the previous allocation.- try successfulSelection(&fixture, "already using model-a · seat-a", 2);-}--test "model confirmation: alias resolving to current selection is already using" {- var fixture: Fixture = .{ .requested = "friendly-alias" };- try successfulSelection(&fixture, "already using model-a · seat-a", 1);-}--test "model confirmation: provider-only change is switched to" {- var fixture: Fixture = .{ .provider = "seat-b" };- try successfulSelection(&fixture, "switched to model-a · seat-b", 1);-}--test "model confirmation: actual model change is switched to" {- var fixture: Fixture = .{ .model = "model-b", .requested = "model-b" };- try successfulSelection(&fixture, "switched to model-b · seat-a", 1);-}--test "model confirmation: failure retains error and current selection" {- var fixture: Fixture = .{};- const saved = Saved.install(&fixture);- defer saved.restore();- var term: sim.Term = undefined;- term.init(std.testing.allocator, 100, 30);- defer term.deinit();- // Establish an owned selection first, then ensure failure leaves it intact.- try submit(&term, fixture.requested);- const owned = term.model.model_override.?;- fixture.fail = true;- fixture.requested = "unavailable";- try submit(&term, fixture.requested);- const history = term.model.history.items;- const last = history[history.len - 1];- try std.testing.expectEqual(.err, last.kind);- try std.testing.expectEqualStrings("couldn't switch to 'unavailable'", last.text);- try std.testing.expectEqualStrings("model-a", engine.g_model_name);- try std.testing.expectEqualStrings("seat-a", engine.g_model_provider);- try std.testing.expect(term.model.model_override.?.ptr == owned.ptr);- try std.testing.expectEqual(@as(usize, 2), fixture.calls);- try std.testing.expect(fixture.valid_request);-}--fn pick(term: *sim.Term) !void {- _ = term.typeText("/model");- _ = term.enter();- try std.testing.expectEqual(.model, term.model.overlay);- _ = term.enter();- try std.testing.expect(term.model.pending == null);- try std.testing.expect(term.model.bg == null);-}--fn pickerSelection(fixture: *Fixture, expected: []const u8, repetitions: usize) !void {- fixture.picker = true;- const saved = Saved.install(fixture);- defer saved.restore();- const previous = engine.g_model_entries;- defer engine.g_model_entries = previous;- const rows = [_]engine.ModelEntry{.{ .name = fixture.requested, .provider = fixture.provider, .has_key = true }};- engine.g_model_entries = &rows;- var term: sim.Term = undefined;- term.init(std.testing.allocator, 100, 30);- defer term.deinit();- for (0..repetitions) |_| {- try pick(&term);- try expectConfirmation(&term, expected);- try std.testing.expectEqualStrings(if (repetitions > 1) "already using this model" else fixture.model, term.model.toast);- try std.testing.expectEqualStrings(fixture.model, engine.g_model_name);- try std.testing.expectEqualStrings(fixture.provider, engine.g_model_provider);- }- try std.testing.expectEqual(repetitions, fixture.calls);- try std.testing.expect(fixture.valid_request);-}--test "model confirmation: picker same row twice is already using" {- var fixture: Fixture = .{};- try pickerSelection(&fixture, "already using model-a · seat-a", 2);-}--test "model confirmation: picker provider change retains model arrow" {- var fixture: Fixture = .{ .provider = "seat-b" };- try pickerSelection(&fixture, "model → model-a · seat-b", 1);-}--test "model confirmation: picker model change retains model arrow" {- var fixture: Fixture = .{ .model = "model-b", .requested = "model-b" };- try pickerSelection(&fixture, "model → model-b · seat-a", 1);-}--test "model confirmation: failed picker retains owned selection and error toast" {- var fixture: Fixture = .{};- const saved = Saved.install(&fixture);- defer saved.restore();- const previous = engine.g_model_entries;- defer engine.g_model_entries = previous;- const rows = [_]engine.ModelEntry{.{ .name = "unavailable", .provider = "seat-b", .has_key = true }};- engine.g_model_entries = &rows;- var term: sim.Term = undefined;- term.init(std.testing.allocator, 100, 30);- defer term.deinit();- try submit(&term, fixture.requested);- const owned = term.model.model_override.?;- const history_len = term.model.history.items.len;- fixture.fail = true;- fixture.picker = true;- fixture.provider = "seat-b";- fixture.requested = "unavailable";- try pick(&term);- try std.testing.expectEqualStrings("couldn't switch", term.model.toast);- try std.testing.expectEqualStrings("model-a", engine.g_model_name);- try std.testing.expectEqualStrings("seat-a", engine.g_model_provider);- try std.testing.expect(term.model.model_override.?.ptr == owned.ptr);- try std.testing.expectEqual(history_len, term.model.history.items.len);- try std.testing.expectEqual(@as(usize, 2), fixture.calls);- try std.testing.expect(fixture.valid_request);-}diff --git a/TUI/models.zig b/TUI/models.zigdeleted file mode 100644index 692c63ea..00000000--- a/TUI/models.zig+++ /dev/null@@ -1,387 +0,0 @@-//! Searchable model picker (same fuzzy feel as the line-REPL `/model`).--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const models_rank = @import("models_rank");-const Model = app.Model;--pub const max_models = 256;-/// Rows the picker draws at once. Public so the click map (overlays.rowSpan)-/// reads the same window the renderer draws rather than a second copy of it.-pub const visible_rows = 14;--fn isSep(c: u8) bool {- return c == '-' or c == '_' or c == ' ' or c == '.' or c == '/';-}--/// Fold separators so "5.6 sol" and "gpt-5.6-sol" share a needle.-fn foldSeps(dst: []u8, s: []const u8) []const u8 {- var n: usize = 0;- for (s) |c| {- if (isSep(c) or n >= dst.len) continue;- dst[n] = std.ascii.toLower(c);- n += 1;- }- return dst[0..n];-}--/// Case-insensitive substring, else fzf-style subsequence ("gpt56" -> gpt-5.6).-/// Spaces/hyphens/dots are ignored so "5.6 sol" hits `gpt-5.6-sol`.-pub fn modelMatch(name: []const u8, query: []const u8) bool {- if (query.len == 0) return true;- if (containsIgnoreCase(name, query)) return true;- var qi: usize = 0;- for (name) |c| {- if (qi < query.len and std.ascii.toLower(c) == std.ascii.toLower(query[qi])) qi += 1;- }- if (qi == query.len) return true;- var nb: [128]u8 = undefined;- var qb: [128]u8 = undefined;- const n = foldSeps(&nb, name);- const q = foldSeps(&qb, query);- return q.len > 0 and containsIgnoreCase(n, q);-}--fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {- if (needle.len == 0) return true;- 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;-}--/// Match one catalog row. The provider is searchable too: typing "codex"-/// narrows to the codex seats, which is the only way to answer "show me what-/// my plan serves" now that the same names appear under several providers.-pub fn entryMatch(e: engine.ModelEntry, query: []const u8) bool {- return modelMatch(e.name, query) or containsIgnoreCase(e.provider, query);-}--const Ranked = struct { e: engine.ModelEntry, score: i32, idx: usize };--fn rankedLess(_: void, a: Ranked, b: Ranked) bool {- if (a.score != b.score) return a.score > b.score;- return a.idx < b.idx;-}--fn nameScore(name: []const u8, query: []const u8) i32 {- if (query.len == 0) return 0;- var nb: [128]u8 = undefined;- var qb: [128]u8 = undefined;- const n = foldSeps(&nb, name);- const q = foldSeps(&qb, query);- const len_pen: i32 = @intCast(@min(name.len, 200));- if (q.len == 0) return -len_pen;- if (std.mem.eql(u8, n, q)) return 300_000 - len_pen;- if (std.mem.endsWith(u8, n, q)) return 200_000 - len_pen;- if (std.mem.indexOf(u8, n, q) != null) return 100_000 - len_pen;- return -len_pen;-}--/// Rank a keyed plan above a metered/reseller hit. Same `electionRank` the-/// line-REPL `/model` picker and `/models` table use — an empty query is-/// still an election, not catalog order. "5.6 sol" with a Codex login-/// lands on `gpt-5.6-sol` / codex, not openai or a gateway slug.-fn entryScore(e: engine.ModelEntry, query: []const u8) i32 {- return nameScore(e.name, query) + models_rank.electionRank(e.has_key, e.cost);-}--/// Keep the catalog rows matching `query`, ranked: keyed plan first, then-/// local, then credits, then api; a typed query adds the name score.-pub fn filterModels(list: []const engine.ModelEntry, query: []const u8, out: []engine.ModelEntry) usize {- var tmp: [max_models]Ranked = undefined;- var k: usize = 0;- for (list, 0..) |e, i| {- if (e.name.len == 0) continue;- if (!entryMatch(e, query)) continue;- if (k >= tmp.len) break;- tmp[k] = .{ .e = e, .score = entryScore(e, query), .idx = i };- k += 1;- }- std.mem.sort(Ranked, tmp[0..k], {}, rankedLess);- const n = @min(k, out.len);- for (0..n) |i| out[i] = tmp[i].e;- return n;-}--/// The row that is live right now: name AND provider, because the same name-/// under two providers is two different seats and only one of them is current.-fn isCurrent(e: engine.ModelEntry) bool {- if (!std.mem.eql(u8, e.name, engine.g_model_name)) return false;- if (engine.g_model_provider.len == 0 or e.provider.len == 0) return true;- return std.mem.eql(u8, e.provider, engine.g_model_provider);-}--/// Display columns, not bytes - model ids are ASCII today, but a padded byte-/// count would silently skew the provider column the day one is not.-fn cellWidth(text: []const u8) usize {- var n: usize = 0;- for (text) |c| {- if (c & 0xC0 != 0x80) n += 1;- }- return n;-}--/// Column width for the model names in the visible window: wide enough that-/// the provider column lines up, never wider than the pane can hold.-fn nameColumn(rows: []const engine.ModelEntry, term_width: usize) usize {- const cap = if (term_width > 46) @min(term_width - 34, 40) else 12;- var w: usize = 12;- for (rows) |e| w = @max(w, cellWidth(tailId(e.name)));- return @min(w, cap);-}--/// What the panel's top edge says: the live filter, and how much of the-/// catalogue survives it. The picker owns these strings; the frame only places-/// them (overlaypane.zig).-pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {- var rows: [max_models]engine.ModelEntry = undefined;- const all = engine.g_model_entries;- const total = @min(all.len, max_models);- const n = filterModels(all, self.overlay_filter, &rows);- return .{- .title = try std.fmt.allocPrint(a, "Model \u{203A} {s}\u{258B}", .{self.overlay_filter}),- .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total }),- };-}--pub const hint = "type to search (name or provider) \u{B7} \u{2191}\u{2193} move \u{B7} click or Enter picks \u{B7} Esc \u{B7} \u{2014} no key";--/// The ROWS only. Title, tally and keys ride in the panel's edges.-///-/// One catalog row is exactly one LINE: the panel clips each to its inner-/// width rather than wrapping, so the click map (overlays.rowSpan) can stay-/// arithmetic. A wrapped row would slide every row below it off its own line.-pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var rows: [max_models]engine.ModelEntry = undefined;- const n = filterModels(engine.g_model_entries, self.overlay_filter, &rows);- var out = std.array_list.Managed(u8).init(a);-- if (n == 0) {- try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches \u{2014} type to filter"));- try out.append('\n');- return out.items;- }-- const sel = self.overlay_sel % n;- const vis = @min(visible_rows, n);- const off = if (sel >= vis) sel - vis + 1 else 0;- const col = nameColumn(rows[off..@min(n, off + vis)], self.last_term_width);- var i = off;- while (i < n and i < off + vis) : (i += 1) {- const e = rows[i];- try out.appendSlice(if (i == sel) "\u{203A} " else " ");- const shown = tailId(e.name);- // A seat with no credential keeps its row - the catalog is the map -- // but reads as unavailable rather than as one more thing to pick.- const dim: []const u8 = if (e.has_key) "" else theme_mod.dim;- const name_sgr = try std.fmt.allocPrint(a, "{s}{s}", .{ dim, if (i == sel) th.accent else th.text });- try out.appendSlice(try theme_mod.paint(a, name_sgr, shown));- try out.appendNTimes(' ', col -| cellWidth(shown));- // provider - cost - key: the three facts a bare name hid.- const meta = try std.fmt.allocPrint(a, " {s} \u{B7} {s} {s}{s}", .{- e.provider,- e.cost.badge(),- if (e.has_key) "\u{2713}" else "\u{2014}",- if (isCurrent(e)) " (current)" else "",- });- try out.appendSlice(try theme_mod.paint(a, try std.fmt.allocPrint(a, "{s}{s}", .{ dim, th.muted }), meta));- try out.append('\n');- }- if (n > vis) try out.appendSlice(try panel.windowRow(a, th, off, vis, n));- return out.items;-}--/// Fireworks ids share a long prefix; show the distinguishing tail.-fn tailId(name: []const u8) []const u8 {- if (std.mem.lastIndexOfScalar(u8, name, '/')) |sl| {- if (sl + 1 < name.len) return name[sl + 1 ..];- }- return name;-}--test "modelMatch: substring and subsequence" {- try std.testing.expect(modelMatch("gpt-5.6", "gpt"));- try std.testing.expect(modelMatch("gpt-5.6", "gpt56"));- try std.testing.expect(modelMatch("gpt-5.6-sol", "5.6 sol"));- try std.testing.expect(modelMatch("accounts/fireworks/models/deepseek-v4-pro", "deepseek"));- try std.testing.expect(!modelMatch("gpt-5.6", "claude"));-}--const sample = [_]engine.ModelEntry{- .{ .name = "aaa", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "bbb", .provider = "codegraff", .has_key = true, .cost = .credits },- .{ .name = "ccc", .provider = "codex", .cost = .plan },- .{ .name = "accounts/fireworks/models/deepseek-v4-pro", .provider = "fireworks", .has_key = true, .cost = .api },- .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },-};--test "filterModels keeps whole catalog rows, not names" {- var buf: [8]engine.ModelEntry = undefined;- const n = filterModels(&sample, "deepseek", &buf);- try std.testing.expectEqual(@as(usize, 1), n);- try std.testing.expectEqualStrings("accounts/fireworks/models/deepseek-v4-pro", buf[0].name);- try std.testing.expectEqualStrings("fireworks", buf[0].provider);- try std.testing.expectEqual(@as(usize, 5), filterModels(&sample, "", &buf));-}--test "the query searches the provider column too" {- // "show me what my plan serves" - impossible while rows were name-only.- var buf: [8]engine.ModelEntry = undefined;- const n = filterModels(&sample, "codex", &buf);- try std.testing.expectEqual(@as(usize, 2), n);- // Keyed plan first; the keyless codex row still matches the provider column.- try std.testing.expectEqualStrings("gpt-5.6", buf[0].name);- try std.testing.expectEqualStrings("ccc", buf[1].name);- try std.testing.expectEqual(@as(usize, 1), filterModels(&sample, "codegraff", &buf));- try std.testing.expectEqual(@as(usize, 0), filterModels(&sample, "anthropic", &buf));-}--test "model overlay typed query is a filtered list, not the dump" {- engine.g_model_entries = &sample;- engine.g_model_name = "aaa";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- for ("deepseek") |c| m.typeOverlayFilter(c);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- try std.testing.expect(std.mem.indexOf(u8, text, "deepseek-v4-pro") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "gpt-5.6") == null);- // The tally and the live filter moved into the panel's top edge.- const hd = try head(&m, arena.allocator());- try std.testing.expectEqualStrings("1/5", hd.note);- try std.testing.expect(std.mem.indexOf(u8, hd.title, "Model \u{203A} deepseek") != null);-}--test "picker rows carry the provider, a cost badge and a key marker" {- // The reported bug: two seats for the same model rendered identically, so- // "codex (free) vs codegraff (paid) vs openai (paid)" was invisible.- const dupes = [_]engine.ModelEntry{- .{ .name = "gpt-5.6", .provider = "codex", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "gpt-5.6", .provider = "codegraff", .cost = .credits },- };- engine.g_model_entries = &dupes;- engine.g_model_name = "gpt-5.6";- engine.g_model_provider = "openai";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- // provider, cost and key per row - the keyless seat is marked, not hidden.- for ([_][]const u8{ "codex \u{B7} plan \u{2713}", "openai \u{B7} api \u{2713}", "codegraff \u{B7} credits \u{2014}" }) |want|- try std.testing.expect(std.mem.indexOf(u8, text, want) != null);- // Exactly one row is current, and it is the one whose PROVIDER matches -- // by name alone all three would have claimed it.- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "(current)"));- const cur = std.mem.indexOf(u8, text, "(current)").?;- const openai = std.mem.indexOf(u8, text, "openai \u{B7} api").?;- try std.testing.expect(openai < cur and cur - openai < 24);- // ...and that row is the only dimmed one.- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, theme_mod.dim));-}--test "the provider column lines up under ragged model names" {- const ragged = [_]engine.ModelEntry{- .{ .name = "k3", .provider = "kimi", .has_key = true, .cost = .plan },- .{ .name = "claude-opus-4-8", .provider = "anthropic", .has_key = true, .cost = .api },- };- engine.g_model_entries = &ragged;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- var col: ?usize = null;- var seen: usize = 0;- var it = std.mem.splitScalar(u8, text, '\n');- var buf: [512]u8 = undefined;- while (it.next()) |line| {- const plain = strip(line, &buf);- // Only the catalog rows: they alone open with the selection gutter.- if (!std.mem.startsWith(u8, plain, " ") and !std.mem.startsWith(u8, plain, "\u{203A} ")) continue;- const sep = std.mem.indexOf(u8, plain, " \u{B7} ") orelse continue;- var start = sep;- while (start > 0 and plain[start - 1] != ' ') start -= 1;- const at = cellWidth(plain[0..start]);- if (col) |c| try std.testing.expectEqual(c, at) else col = at;- seen += 1;- }- try std.testing.expectEqual(@as(usize, 2), seen);-}--test "a 5.6 sol search ranks keyed Codex above openai and a gateway slug" {- const rows = [_]engine.ModelEntry{- .{ .name = "gpt-5.6", .provider = "openai", .has_key = true, .cost = .api },- .{ .name = "openai/gpt-5.6-sol", .provider = "vercel", .has_key = true, .cost = .api },- .{ .name = "gpt-5.6-sol", .provider = "codex", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.6-sol", .provider = "codex", .cost = .plan },- };- var buf: [8]engine.ModelEntry = undefined;- const n = filterModels(&rows, "5.6 sol", &buf);- try std.testing.expectEqual(@as(usize, 3), n);- try std.testing.expectEqualStrings("gpt-5.6-sol", buf[0].name);- try std.testing.expectEqualStrings("codex", buf[0].provider);- try std.testing.expect(buf[0].has_key);- try std.testing.expectEqualStrings("openai/gpt-5.6-sol", buf[1].name);-}--test "an empty query ranks signed-in plan above credits above api" {- // Catalog order is openai / codegraff / keyless-codex / fireworks / keyed-codex.- // Opening /models with a Codex login should put that plan on top, not- // leave it at the bake position under Codegraff.- var buf: [8]engine.ModelEntry = undefined;- const n = filterModels(&sample, "", &buf);- try std.testing.expectEqual(@as(usize, 5), n);- try std.testing.expectEqualStrings("gpt-5.6", buf[0].name);- try std.testing.expectEqualStrings("codex", buf[0].provider);- try std.testing.expect(buf[0].has_key);- try std.testing.expectEqualStrings("bbb", buf[1].name);- try std.testing.expectEqualStrings("codegraff", buf[1].provider);- try std.testing.expectEqualStrings("aaa", buf[2].name);- try std.testing.expectEqualStrings("ccc", buf[4].name);- try std.testing.expect(!buf[4].has_key);-}--/// `line` with its SGR sequences removed, written into `buf`. The padding is-/// what is under test and an escape sequence is zero cells wide.-fn strip(line: []const u8, buf: []u8) []const u8 {- var n: usize = 0;- var i: usize = 0;- while (i < line.len and n < buf.len) {- if (line[i] == 0x1b) {- while (i < line.len and line[i] != 'm') i += 1;- i += 1;- continue;- }- buf[n] = line[i];- n += 1;- i += 1;- }- return buf[0..n];-}diff --git a/TUI/nav.zig b/TUI/nav.zigdeleted file mode 100644index c4854d73..00000000--- a/TUI/nav.zig+++ /dev/null@@ -1,149 +0,0 @@-//! Grok-style turn jump, line scroll, new-session, quit.--const std = @import("std");-const app = @import("app.zig");-const key_mod = @import("key.zig");-const Key = key_mod.Key;-const Model = app.Model;-const Effect = app.Effect;--pub fn handle(self: *Model, k: Key) ?Effect {- if (isCtrl(k, 'q')) return .quit;- if (isCtrl(k, 'n')) {- ctrlN(self);- return .stay;- }- if (isCtrl(k, 'j')) {- scrollLine(self, -1);- return .stay;- }- if (isCtrl(k, 'k')) {- scrollLine(self, 1);- return .stay;- }- if (k == .prev_turn) {- jumpTurn(self, -1);- return .stay;- }- if (k == .next_turn) {- jumpTurn(self, 1);- return .stay;- }- return null;-}--fn scrollLine(self: *Model, delta: i32) void {- if (delta > 0) {- self.scroll +|= @as(usize, @intCast(delta));- self.follow = false;- return;- }- const down: usize = @intCast(-delta);- if (self.scroll <= down) {- self.scroll = 0;- self.follow = true;- } else self.scroll -= down;-}--fn isCtrl(k: Key, c: u8) bool {- return k == .ctrl and k.ctrl == c;-}--fn ctrlN(self: *Model) void {- if (self.new_arm_until_ms != 0 and self.now_ms <= self.new_arm_until_ms) {- self.new_arm_until_ms = 0;- self.setToast(if (self.newSession()) "new session" else "an engine call is still running — press Esc first");- return;- }- self.new_arm_until_ms = self.now_ms + 1000;- self.setToast("press Ctrl+N again to start a new session");-}--/// Land the viewport on history entry `idx` (used by /jump).-pub fn jumpTo(self: *Model, idx: usize) void {- self.selected = idx;- self.focus = .scrollback;- self.follow = false;- const sb = @import("layout_cache.zig");- const width = @import("inset.zig").wrapWidth(self);- const total = sb.totalVisualLines(self, width);- const at = sb.visualOfIndex(self, idx, width) orelse return;- // prompt_origin - mid_origin includes the image-card rows render subtracts- // from the transcript, and the sticky header occludes the top two viewport- // rows — without both corrections /jump parked the target off-screen or- // exactly under the pinned chrome (audit: the jumped-to turn was ALWAYS- // hidden, with the PREVIOUS prompt pinned above it).- const gross = if (self.prompt_origin > self.mid_origin) self.prompt_origin - self.mid_origin else 8;- const view_h = gross -| self.preview_rows;- if (total <= view_h) {- self.scroll = 0;- return;- }- const max_scroll = total - view_h;- // Land the target at the row below the sticky slot (row 2) so it is the- // first fully visible line; at the extremes fall back to the edges.- const want = at -| 2;- self.scroll = if (want >= max_scroll) 0 else max_scroll - want;-}--fn jumpTurn(self: *Model, dir: i32) void {- if (self.history.items.len == 0) return;- var i = self.selected;- if (dir > 0) {- i += 1;- while (i < self.history.items.len) : (i += 1) {- if (self.history.items[i].kind == .user) {- self.selected = i;- break;- }- }- } else {- while (i > 0) {- i -= 1;- if (self.history.items[i].kind == .user) {- self.selected = i;- break;- }- }- }- self.focus = .scrollback;- self.follow = false;-}--test "Ctrl+N twice clears the session" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- m.now_ms = 10;- _ = handle(&m, .{ .ctrl = 'n' });- try std.testing.expect(m.history.items.len == 1);- m.now_ms = 20;- _ = handle(&m, .{ .ctrl = 'n' });- try std.testing.expectEqual(@as(usize, 0), m.history.items.len);-}--test "Shift+arrows jump between user turns" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "one");- try m.push(.assistant, "a");- try m.push(.user, "two");- m.selected = 2;- _ = handle(&m, .prev_turn);- try std.testing.expectEqual(@as(usize, 0), m.selected);- _ = handle(&m, .next_turn);- try std.testing.expectEqual(@as(usize, 2), m.selected);-}--test "wheel keeps prompt focus" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.focus = .prompt;- _ = @import("keys.zig").handle(&m, .{ .mouse = .{ .btn = 64, .x = 2, .y = 2, .down = true } });- try std.testing.expect(m.focus == .prompt);- try std.testing.expect(!m.follow);- try std.testing.expect(m.scroll > 0);-}diff --git a/TUI/osc52.zig b/TUI/osc52.zigdeleted file mode 100644index d8ba2374..00000000--- a/TUI/osc52.zig+++ /dev/null@@ -1,168 +0,0 @@-//! OSC 52 — the clipboard channel that survives SSH.-//!-//! `pbcopy`/`xclip` write the clipboard of the machine graff RUNS on. Over SSH-//! that is the server, which nobody is looking at, so the local-tool path-//! silently copies into a void. OSC 52 asks the TERMINAL to set its own-//! clipboard instead: the escape travels back over the same connection the-//! frame does, and it lands on the laptop in front of the user.-//!-//! Wire shape: `ESC ] 5 2 ; c ; <base64> BEL`. `c` is the CLIPBOARD selection-//! (not the X primary), and BEL terminates the string — ST (`ESC \`) is equally-//! legal but BEL is what tmux, iTerm2, kitty and Ghostty all accept without a-//! passthrough wrapper.-//!-//! Two properties this module exists to hold.-//!-//! * **Chunk safety.** Base64 is only concatenable on 3-byte input-//! boundaries: encode 4 bytes, then the next 4, and the padding in the-//! middle corrupts everything after it. `encode` therefore consumes the-//! input in multiples of THREE, so an implementation that streams it (or a-//! terminal that reads it in pieces) can never see interior padding.-//! * **A cap.** Terminals bound the sequence they will buffer, and a-//! multi-megabyte escape is a way to wedge one rather than to copy-//! anything. Past `max_bytes` the emission is REFUSED — never truncated,-//! because a clipboard that silently holds half a selection is worse than-//! one that says it holds nothing.-//!-//! Presentation only: nothing here reaches a provider or the engine.--const std = @import("std");--pub const prefix = "\x1b]52;c;";-pub const terminator = "\x07";--/// Largest selection that gets an OSC 52 emission. 100 KB of transcript is far-/// more than a drag can plausibly want and still well inside what terminals-/// accept.-pub const max_bytes: usize = 100 * 1024;--/// Input bytes per encoding step. A multiple of 3, which is the whole point:-/// each step emits complete base64 quanta, so the pieces concatenate.-pub const chunk_bytes: usize = 3 * 1024;--/// True when `text` is small enough to send. The caller decides what to tell-/// the user about a refusal — see selection.zig's toast.-pub fn fits(text: []const u8) bool {- return text.len > 0 and text.len <= max_bytes;-}--/// The complete escape sequence for `text`, or null when it does not fit.-/// Caller owns the result.-pub fn sequence(a: std.mem.Allocator, text: []const u8) !?[]const u8 {- if (!fits(text)) return null;- var out = std.array_list.Managed(u8).init(a);- errdefer out.deinit();- try out.appendSlice(prefix);- try encode(&out, text);- try out.appendSlice(terminator);- return try out.toOwnedSlice();-}--/// Standard base64 with padding, appended in `chunk_bytes` steps. Only the-/// FINAL step can be short, so only the final step can emit '=' — which is-/// exactly what makes the output the same bytes a one-shot encode would give.-pub fn encode(out: *std.array_list.Managed(u8), text: []const u8) !void {- const enc = std.base64.standard.Encoder;- var i: usize = 0;- while (i < text.len) {- const n = @min(chunk_bytes, text.len - i);- const piece = text[i .. i + n];- const room = enc.calcSize(piece.len);- const at = out.items.len;- try out.resize(at + room);- _ = enc.encode(out.items[at..][0..room], piece);- i += n;- }-}--// ------------------------------------------------------------------ tests--const testing = std.testing;--test "the sequence is OSC 52, clipboard selection, BEL terminated" {- const a = testing.allocator;- const got = (try sequence(a, "hi")).?;- defer a.free(got);- try testing.expectEqualStrings("\x1b]52;c;aGk=\x07", got);-}--test "base64 matches a one-shot encode at every length around a chunk edge" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- // Lengths that straddle the chunk boundary in both directions, plus the- // three residues mod 3 — the only places a streamed encoder can drift.- const lens = [_]usize{- 1, 2, 3,- 4, 5, 6,- 1023, 1024, 1025,- chunk_bytes - 2, chunk_bytes - 1, chunk_bytes,- chunk_bytes + 1, chunk_bytes + 2, chunk_bytes * 2 + 1,- };- for (lens) |n| {- const src = try ar.alloc(u8, n);- for (src, 0..) |*b, i| b.* = @truncate(i *% 37 +% 11);- var out = std.array_list.Managed(u8).init(ar);- try encode(&out, src);- const enc = std.base64.standard.Encoder;- const want = try ar.alloc(u8, enc.calcSize(n));- _ = enc.encode(want, src);- try testing.expectEqualStrings(want, out.items);- // ...and it decodes back to the original bytes.- const dec = std.base64.standard.Decoder;- const back = try ar.alloc(u8, try dec.calcSizeForSlice(out.items));- try dec.decode(back, out.items);- try testing.expectEqualSlices(u8, src, back);- }-}--test "no interior padding: '=' can only appear in the last four characters" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- // A length whose FIRST chunk is a whole number of quanta and whose tail is- // not: a chunker that split anywhere else would pad mid-stream.- const src = try ar.alloc(u8, chunk_bytes + 2);- @memset(src, 'q');- var out = std.array_list.Managed(u8).init(ar);- try encode(&out, src);- const first_pad = std.mem.indexOfScalar(u8, out.items, '=') orelse out.items.len;- try testing.expect(first_pad >= out.items.len - 4);-}--test "the cap refuses rather than truncating" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const big = try ar.alloc(u8, max_bytes + 1);- @memset(big, 'x');- try testing.expect(!fits(big));- try testing.expect((try sequence(ar, big)) == null);- // Exactly at the cap still goes.- const edge = big[0..max_bytes];- try testing.expect(fits(edge));- const seq = (try sequence(ar, edge)).?;- try testing.expect(std.mem.startsWith(u8, seq, prefix));- try testing.expect(std.mem.endsWith(u8, seq, terminator));- // Empty is not a copy.- try testing.expect(!fits(""));- try testing.expect((try sequence(ar, "")) == null);-}--test "the payload is the selection verbatim, newlines and all" {- const a = testing.allocator;- // The text-only capture contract from #529: whatever selection.zig- // captured is what the terminal's clipboard gets, byte for byte.- const text = "first row\nsecond row\n\nfourth row";- const got = (try sequence(a, text)).?;- defer a.free(got);- const body = got[prefix.len .. got.len - terminator.len];- const dec = std.base64.standard.Decoder;- const back = try a.alloc(u8, try dec.calcSizeForSlice(body));- defer a.free(back);- try dec.decode(back, body);- try testing.expectEqualStrings(text, back);-}diff --git a/TUI/overlaypane.zig b/TUI/overlaypane.zigdeleted file mode 100644index 2145ec9b..00000000--- a/TUI/overlaypane.zig+++ /dev/null@@ -1,434 +0,0 @@-//! Overlay bodies, and the panel each one is framed in.-//!-//! Split out of chrome.zig: the composer and the overlays had grown into one-//! file over its ceiling, and they answer to different rules. chrome.zig owns-//! the rows that are ALWAYS on screen; this file owns the ones that replace the-//! transcript while they are open.-//!-//! Every overlay is the same shape — a name, a tally, some rows, the keys —-//! and panel.zig turns that shape into grok-build's bordered box. Nothing here-//! paints an edge itself, so a panel cannot drift surface by surface.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--/// Scroll hint for the bodies that are PROSE rather than a list. It rides in-/// the TOP edge: those are the bodies long enough to overflow the viewport, and-/// an overflowing panel has its bottom edge off the bottom of the screen.-const scroll_note = "↑↓ scroll · Esc";--pub fn overlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- // The image card is a preview pinned above the composer, not a panel that- // replaces the transcript; it keeps its own shape (image.zig).- if (self.overlay == .none or self.overlay == .slash) return "";- if (self.overlay == .image) return @import("image.zig").render(self, a, width);- return panel.wrap(a, self.theme(), width, try spec(self, a));-}--fn spec(self: *const Model, a: std.mem.Allocator) !panel.Spec {- const th = self.theme();- return switch (self.overlay) {- .palette => blk: {- var idx: [catalog.items.len]usize = undefined;- break :blk .{- .title = "Commands",- .note = try tally(a, catalog.filter(self.input.getValue(), &idx), catalog.items.len),- .footer = "↑↓ move · click or Enter runs · Esc",- .body = try listBody(self, a),- };- },- // No tally: a list that cannot be filtered has nothing to count down.- .theme => .{- .title = "Theme",- .footer = "↑↓ move · click or Enter applies · Esc",- .body = try themeBody(self, a),- },- .help => .{- .title = "Shortcuts",- .note = scroll_note,- .footer = "Esc close",- .body = try theme_mod.paint(a, th.text, help_body),- },- .rewind => .{- .title = "Rewind",- .footer = "Enter rewind · Esc cancel",- .body = try theme_mod.paint(a, th.text, " Undo the last turn?"),- },- .debug => .{- .title = "Observability",- .note = scroll_note,- .footer = "Esc close",- .body = try debugBody(self, a),- },- .model => blk: {- const models = @import("models.zig");- const head = try models.head(self, a);- break :blk .{ .title = head.title, .note = head.note, .footer = models.hint, .body = try models.render(self, a) };- },- .effort => blk: {- const effort = @import("effort.zig");- const head = try effort.head(self, a);- break :blk .{ .title = head.title, .note = head.note, .footer = effort.hint, .body = try effort.render(self, a) };- },- .file => blk: {- const files = @import("files.zig");- const head = try files.head(self, a);- break :blk .{ .title = head.title, .note = head.note, .footer = files.hint, .body = try files.render(self, a) };- },- .settings => .{- .title = "Settings",- .footer = "↑↓ move · click or Enter changes · Esc",- .body = try settingsBody(self, a),- },- .jump => .{- .title = "Jump to turn",- .note = if (self.userTurnCount() == 0) "" else try std.fmt.allocPrint(a, "{d} turns", .{self.userTurnCount()}),- .footer = "↑↓ move · click or Enter jumps · Esc",- .body = try jumpBody(self, a),- },- .sessions => blk: {- const resume_mod = @import("resume.zig");- const head = try resume_mod.head(self, a);- break :blk .{ .title = head.title, .note = head.note, .footer = resume_mod.hint, .body = try resume_mod.render(self, a) };- },- else => .{ .body = "" },- };-}--fn tally(a: std.mem.Allocator, n: usize, total: usize) ![]const u8 {- return std.fmt.allocPrint(a, "{d}/{d}", .{ n, total });-}--fn listBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- var out = std.array_list.Managed(u8).init(a);- const show = @min(n, @as(usize, 12));- if (show == 0) {- try out.appendSlice(try theme_mod.paint(a, th.muted, " no matches"));- try out.append('\n');- return out.items;- }- const sel = self.overlay_sel % show;- var i: usize = 0;- while (i < show) : (i += 1) {- const it = catalog.items[idx[i]];- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));- // One menu entry is one ROW: a long description is CUT by the panel- // wall, never wrapped — wrapping would slide every entry below it off- // its own row.- const line = try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, it.name, it.desc });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- if (n > show) try out.appendSlice(try panel.windowRow(a, th, 0, show, n));- return out.items;-}--fn themeBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var out = std.array_list.Managed(u8).init(a);- const sel = self.overlay_sel % theme_mod.all.len;- for (theme_mod.all, 0..) |id, i| {- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));- const cur: []const u8 = if (id == self.theme_id) " (current)" else "";- const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, id.label(), cur });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- return out.items;-}--fn jumpBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var out = std.array_list.Managed(u8).init(a);- const total = self.userTurnCount();- if (total == 0) {- try out.appendSlice(try theme_mod.paint(a, th.muted, " no turns yet"));- try out.append('\n');- return out.items;- }- const sel = self.overlay_sel % total;- var no: usize = 0;- for (self.history.items) |e| {- if (e.kind != .user) continue;- const nl = std.mem.indexOfScalar(u8, e.text, '\n') orelse e.text.len;- const clip = e.text[0..@min(nl, 60)];- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(no != sel));- const line = try std.fmt.allocPrint(a, "{s}#{d} {s}", .{ mark, no + 1, clip });- try out.appendSlice(if (no == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- no += 1;- }- return out.items;-}--fn settingsBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var out = std.array_list.Managed(u8).init(a);- const rows = [_][2][]const u8{- .{ "Model", if (engine.g_model_name.len > 0) engine.g_model_name else "—" },- .{ "Effort", @tagName(self.effort) },- .{ "Mode", self.modeLabel() },- .{ "Theme", self.theme_id.label() },- };- const sel = self.overlay_sel % rows.len;- for (rows, 0..) |r, i| {- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));- const line = try std.fmt.allocPrint(a, "{s}{s:<10} {s}", .{ mark, r[0], r[1] });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- return out.items;-}--fn debugBody(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var buf: [2048]u8 = undefined;- const hud: []const u8 = if (engine.g_hud_fn) |f| buf[0..f(.debug, &buf)] else "observability (offline — no session sink)\n";- var lbuf: [256]u8 = undefined;- const lay = @import("dump.zig").layoutBuf(&lbuf, self);- const joined = try std.fmt.allocPrint(a, "{s}{s}", .{ hud, lay });- // The HUD is written for a bare pager and starts every section flush left.- // Inside a panel that puts the section headings hard against the wall while- // their own rows sit two columns in, so the block is inset to the two the- // picker rows already use and the whole overlay set shares one left margin.- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(th.text);- var it = std.mem.splitScalar(u8, joined, '\n');- while (it.next()) |ln| {- if (ln.len == 0 and it.rest().len == 0) break;- try out.appendSlice(" ");- try out.appendSlice(ln);- try out.append('\n');- }- return out.items;-}--/// The shortcut sheet. No leading heading of its own: the panel's top edge-/// already says "Shortcuts", and a body that repeated it spent a row saying-/// what the frame had said one line earlier.-const help_body =- \\ Tab prompt / scrollback- \\ Enter send- \\ Esc cancel · 2× clear · 2× rewind- \\ Ctrl+C cancel, then quit- \\ Ctrl+X / F1 this overlay- \\ Ctrl+P command palette- \\ Shift+Tab Normal → Plan → Always-approve- \\ click / ← → collapse / expand tools- \\ hover [Image] preview · backspace detach · y copy · Enter open- \\ Shift+← → prev / next user turn- \\ Ctrl+J / K scroll one line- \\ Ctrl+N N new session- \\ Ctrl+Q quit- \\ drag select transcript · copy on release- \\ Shift+drag the terminal's own selection (any region)- \\ Ctrl+Z undo composer- \\ Cmd+Delete kill to start of line- \\ Option+Delete kill previous word- \\ wheel scroll transcript- \\ PgUp / PgDn page transcript- \\ cmd+v paste text- \\ Ctrl+V attach clipboard image- \\ Ctrl+R prompt history- \\ / slash menu- \\ @ fuzzy file mention- \\ !cmd run a shell command- \\- \\Commands- \\ /quit /exit /q leave the pager- \\ /help this overlay- \\ /new /clear fresh session- \\ /home welcome screen- \\ /model switch model (type to search)- \\ /effort reasoning depth (type to filter)- \\ /settings model · effort · mode · theme- \\ /usage /cost live token/cost line- \\ /version running binary and latest release status- \\ /update install a release for the next launch- \\ /debug observability HUD- \\ /cache prompt-cache posture- \\ /plan toggle plan mode- \\ /always-approve skip permission prompts- \\ /import-claude copy Claude and Cursor MCP + skills- \\ /jump jump to a previous turn- \\ /resume list saved sessions- \\ /copy copy the last reply- \\ /btw queue an aside mid-turn- \\ /tell message a live graff (/tell all broadcasts)- \\ /peek see what a live session is doing- \\ /vim-mode vim keys in the scrollback-;--const testing = std.testing;--test "help overlay names the advertised pager commands" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- m.openOverlay(.help);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), 80);- for ([_][]const u8{- "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/cache", "/plan", "/always-approve",- "/tell", "/peek", "/resume", "Shift+Tab", "PgUp", "PgDn",- "←",- "→",- "Tab", "Enter", "Esc",- }) |name| {- try testing.expect(std.mem.indexOf(u8, text, name) != null);- }- // The name is in the FRAME, and the body no longer repeats it.- try testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "Shortcuts"));-}--test "model overlay lists the catalog with its provider column" {- engine.g_model_entries = &.{- .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },- };- engine.g_model_name = "grok-4";- engine.g_model_provider = "xai";- defer {- engine.g_model_entries = &.{};- engine.g_model_name = "";- engine.g_model_provider = "";- }- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- m.openOverlay(.model);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), 80);- try testing.expect(std.mem.indexOf(u8, text, "grok-4") != null);- try testing.expect(std.mem.indexOf(u8, text, "gpt-5.5") != null);- try testing.expect(std.mem.indexOf(u8, text, "Model ›") != null);- // The provider rides on the row, inside the frame.- try testing.expect(std.mem.indexOf(u8, text, "xai · plan") != null);- try testing.expect(std.mem.indexOf(u8, text, "openai · api") != null);-}--test "debug overlay is not the offline fallback when a hud is wired" {- engine.g_hud_fn = struct {- fn f(kind: engine.HudKind, buf: []u8) usize {- _ = kind;- const s = "observability graff.schema v1\n usage 1 api call(s)";- const n = @min(s.len, buf.len);- @memcpy(buf[0..n], s[0..n]);- return n;- }- }.f;- defer engine.g_hud_fn = null;- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- m.openOverlay(.debug);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), 80);- try testing.expect(std.mem.indexOf(u8, text, "offline") == null);- try testing.expect(std.mem.indexOf(u8, text, "usage") != null);- try testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);- try testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);-}--test "every overlay is a bordered panel with its name in the frame" {- // The audit this pass exists for: before it, an open picker was bare text- // floating on the pager with no edge anywhere, and each surface spelled its- // own title row. One panel builder means one look, and the check is that- // NONE of them opts out.- engine.g_model_entries = &.{- .{ .name = "grok-4", .provider = "xai", .has_key = true, .cost = .plan },- .{ .name = "gpt-5.5", .provider = "openai", .has_key = true, .cost = .api },- };- defer engine.g_model_entries = &.{};- const cases = [_]struct { o: app.Overlay, name: []const u8 }{- .{ .o = .palette, .name = "Commands" },- .{ .o = .theme, .name = "Theme" },- .{ .o = .help, .name = "Shortcuts" },- .{ .o = .rewind, .name = "Rewind" },- .{ .o = .debug, .name = "Observability" },- .{ .o = .model, .name = "Model" },- .{ .o = .effort, .name = "Effort" },- .{ .o = .file, .name = "File" },- .{ .o = .settings, .name = "Settings" },- .{ .o = .jump, .name = "Jump to turn" },- .{ .o = .sessions, .name = "Resume session" },- };- for (cases) |c| {- for ([_]usize{ 40, 60, 80, 120 }) |w| {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- try m.push(.user, "a turn so the jump list has a row");- m.openOverlay(c.o);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), w);- var it = std.mem.splitScalar(u8, text, '\n');- const top = it.next() orelse return error.EmptyPanel;- if (std.mem.indexOf(u8, top, "╭") == null) {- std.debug.print("{s} @ {d} has no top edge: {s}\n", .{ @tagName(c.o), w, top });- return error.NoPanelEdge;- }- try testing.expect(std.mem.indexOf(u8, top, c.name) != null);- // ...and the last row is the closing edge, with the keys on it.- var last: []const u8 = top;- while (it.next()) |ln| {- if (ln.len > 0) last = ln;- }- try testing.expect(std.mem.indexOf(u8, last, "╰") != null);- try testing.expect(std.mem.indexOf(u8, last, "Esc") != null);- // Every row is exactly the frame width — the painter's contract.- var rows = std.mem.splitScalar(u8, text, '\n');- while (rows.next()) |ln| {- if (ln.len == 0 and rows.rest().len == 0) break;- try testing.expectEqual(w, theme_mod.visibleLen(ln));- }- }- }-}--test "a windowed list says how much of itself is off-screen" {- // 75 models in a 14-row window used to show 14 rows and no hint at all- // that the other 61 existed.- var arena0 = std.heap.ArenaAllocator.init(testing.allocator);- defer arena0.deinit();- var buf = std.array_list.Managed(engine.ModelEntry).init(arena0.allocator());- for (0..75) |i| {- try buf.append(.{- .name = try std.fmt.allocPrint(arena0.allocator(), "model-{d}", .{i}),- .provider = "openai",- .has_key = true,- .cost = .api,- });- }- engine.g_model_entries = buf.items;- defer engine.g_model_entries = &.{};- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- m.openOverlay(.model);- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const text = try overlay(&m, arena.allocator(), 80);- try testing.expect(std.mem.indexOf(u8, text, "61 below") != null);- try testing.expect(std.mem.indexOf(u8, text, "0/75") == null);- try testing.expect(std.mem.indexOf(u8, text, "75/75") != null);- // Walked to the end of the list, the marker turns around instead of- // vanishing — the row is reserved either way, so nothing below it jumps.- m.overlay_sel = 74;- const tail = try overlay(&m, arena.allocator(), 80);- try testing.expect(std.mem.indexOf(u8, tail, "61 above") != null);-}diff --git a/TUI/overlays.zig b/TUI/overlays.zigdeleted file mode 100644index 099af022..00000000--- a/TUI/overlays.zig+++ /dev/null@@ -1,405 +0,0 @@-//! Overlay key routing + activation (palette, theme, model, effort, settings,-//! rewind, @-file picker, /jump, /resume). Split from keys.zig for the line budget.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const dispatch = @import("dispatch.zig");-const engine = @import("engine.zig");-const files_mod = @import("files.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Key = @import("key.zig").Key;-const Model = app.Model;-const Effect = app.Effect;--/// Overlays whose body is a SHEET rather than a list: there is no highlight to-/// move, so the arrows and the page keys scroll the body instead. keys.zig-/// routes every key here before it reaches its own page handling, so without-/// this a /help taller than the terminal had no way at all to show its second-/// half — the arrows only walked an `overlay_sel` nothing rendered.-fn scrolls(o: app.Overlay) bool {- return o == .help or o == .debug;-}--fn page(self: *const Model) usize {- const h = self.last_term_height;- return @max(if (h > 8) h - 6 else 3, 3);-}--/// One step of the sheet, clamped to its end by the frame composer (render.zig-/// knows the row count; this does not).-fn scrollSheet(self: *Model, k: Key) bool {- switch (k) {- .up => self.overlay_scroll -|= 3,- .down => self.overlay_scroll += 3,- .page_up => self.overlay_scroll -|= page(self),- .page_down => self.overlay_scroll += page(self),- else => return false,- }- return true;-}--pub fn key(self: *Model, k: Key) Effect {- if (@import("image.zig").key(self, k)) return .stay;- if (k == .escape) {- self.closeOverlay();- return .stay;- }- if (scrolls(self.overlay) and scrollSheet(self, k)) return .stay;- if (k == .up) {- self.overlay_sel -|= 1;- return .stay;- }- if (k == .down) {- self.overlay_sel += 1;- return .stay;- }- if (k == .enter) return activate(self);- if (self.overlay == .model or self.overlay == .effort or self.overlay == .file or self.overlay == .sessions) {- switch (k) {- .char => |c| self.typeOverlayFilter(c),- .backspace => self.backspaceOverlayFilter(),- else => {},- }- return .stay;- }- if (self.overlay == .palette or self.overlay == .theme) {- self.input.handle(k);- }- return .stay;-}--/// One wheel notch moves the highlighted row of an open list by EXACTLY one-/// item — the same step the arrow keys take, so a trackpad that emits a burst-/// of notches walks the list one row per notch instead of skipping three at a-/// time (the transcript's scroll step) or scrolling the transcript out from-/// under the picker, which is what the wheel used to do here. Returns true when-/// a list consumed the event.-pub fn wheel(self: *Model, up: bool) bool {- // The image card is a preview above the composer, not a list; it keeps its- // own key handling and the transcript keeps the wheel.- if (self.overlay != .none and self.overlay != .image) {- // A sheet scrolls; only a LIST has a highlight for a notch to move.- if (scrolls(self.overlay)) {- if (up) self.overlay_scroll -|= 1 else self.overlay_scroll += 1;- } else if (up) self.overlay_sel -|= 1 else self.overlay_sel += 1;- return true;- }- const v = self.input.getValue();- if (self.focus != .prompt or v.len == 0 or v[0] != '/') return false;- if (up) {- self.slash_sel -|= 1;- return true;- }- // Clamped exactly as the Down key is: the highlight and the row Enter- // fires can never diverge onto an invisible command (#522).- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(v, &idx);- if (n > 0 and self.slash_sel + 1 < n) self.slash_sel += 1;- return true;-}--// ------------------------------------------------------------- row geometry--/// Where an open list overlay's ROWS sit inside its own composed body, in body-/// lines. render.zig lays that body out exactly like the transcript - screen-/// row `mid_origin + k` shows body line `mid_skip + k` - so this plus those two-/// numbers is the whole row map a click needs.-///-/// Every overlay is a PANEL now (panel.zig): its name and its tally ride in the-/// top edge and its keys in the bottom one, so the body a list composes is its-/// rows and nothing else, and the frame contributes exactly one line above them.-/// That is why `line0` is the same for all of them - the per-overlay header-/// shapes this used to track no longer exist. The panel also CLIPS every row to-/// its inner width instead of wrapping, which is what keeps one item on one-/// line and lets this map be arithmetic rather than a second pass over bytes.-pub const Span = struct {- /// Body line of the first row drawn.- line0: usize,- /// Item index that row shows - a windowed list starts partway down.- first: usize,- /// Rows drawn.- rows: usize,- /// Items in the FILTERED list, which is what `overlay_sel` indexes.- total: usize,-};--/// The panel's top edge, and the only reason `line0` is not zero.-const frame_rows: usize = 1;--pub fn rowSpan(self: *const Model) ?Span {- const models = @import("models.zig");- const effort_mod = @import("effort.zig");- // Too narrow to frame is too narrow to CLIP: panel.zig hands the body back- // untouched, the rows wrap, and one item stops being one line. Nothing is- // clickable at that width rather than the wrong thing being.- if (self.last_term_width < panel.min_width) return null;- switch (self.overlay) {- .palette => {- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- const show = @min(n, @as(usize, 12));- if (show == 0) return null;- return .{ .line0 = frame_rows, .first = 0, .rows = show, .total = show };- },- .theme => return .{ .line0 = frame_rows, .first = 0, .rows = theme_mod.all.len, .total = theme_mod.all.len },- .settings => return .{ .line0 = frame_rows, .first = 0, .rows = 4, .total = 4 },- .jump => {- const total = self.userTurnCount();- if (total == 0) return null;- return .{ .line0 = frame_rows, .first = 0, .rows = total, .total = total };- },- .effort => {- var buf: [effort_mod.all.len]engine.Effort = undefined;- const n = effort_mod.filter(self.overlay_filter, &buf);- if (n == 0) return null;- return .{ .line0 = frame_rows, .first = 0, .rows = n, .total = n };- },- .model => {- var rows: [models.max_models]engine.ModelEntry = undefined;- const n = models.filterModels(engine.g_model_entries, self.overlay_filter, &rows);- if (n == 0) return null;- return windowed(frame_rows, n, self.overlay_sel % n, models.visible_rows);- },- .file => {- var names: [files_mod.max_files][]const u8 = undefined;- const n = files_mod.filterList(self.files_cache orelse "", self.overlay_filter, &names);- if (n == 0) return null;- return windowed(frame_rows, n, self.overlay_sel % n, files_mod.visible_rows);- },- .sessions => {- const resume_mod = @import("resume.zig");- var rows: [resume_mod.max_sessions]resume_mod.Row = undefined;- const n = resume_mod.filterList(self.sessions_cache orelse "", self.overlay_filter, &rows);- if (n == 0) return null;- return windowed(frame_rows, n, self.overlay_sel % n, resume_mod.visible_rows);- },- else => return null,- }-}--/// The scrolling window the searchable pickers draw: `vis` rows that follow the-/// highlight, so it is always on screen and always the row Enter fires.-fn windowed(line0: usize, n: usize, sel: usize, vis_max: usize) Span {- const vis = @min(vis_max, n);- const off = if (sel >= vis) sel - vis + 1 else 0;- return .{ .line0 = line0, .first = off, .rows = @min(vis, n - off), .total = n };-}--/// A click landed on item `item`. The first click on a row moves the highlight-/// there; a click on the row that already carries it CONFIRMS, exactly as-/// Enter does. Those two halves are also what make a double click a confirm,-/// without a second copy of hover.zig's double-click window.-pub fn clickRow(self: *Model, item: usize) Effect {- const span = rowSpan(self) orelse return .stay;- if (item >= span.total) return .stay;- if (self.overlay_sel % span.total == item) return activate(self);- self.overlay_sel = item;- return .stay;-}--/// Open the @-picker immediately and load the session file list in the-/// background. Loading it inline blocked the render+input thread for up to the-/// runCapped 10s cap on the first @ of a session (#533).-pub fn openFiles(self: *Model) void {- if (self.files_cache == null and engine.g_files_fn != null) {- _ = @import("bgop.zig").start(self, .files, &.{}, "", "");- }- self.openOverlay(.file);-}--pub fn activate(self: *Model) Effect {- switch (self.overlay) {- .palette => {- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter(self.input.getValue(), &idx);- if (n == 0) return .stay;- const pick = catalog.items[idx[@min(self.overlay_sel, n - 1)]];- self.closeOverlay();- self.input.setValue("") catch {};- return dispatch.runCommand(self, pick.name);- },- .theme => {- const id: theme_mod.Id = @enumFromInt(self.overlay_sel % theme_mod.all.len);- self.theme_id = id;- self.closeOverlay();- self.setToast(id.label());- },- .rewind => {- self.closeOverlay();- dispatch.rewind(self);- },- .model => {- const models = @import("models.zig");- var rows: [models.max_models]engine.ModelEntry = undefined;- const n = models.filterModels(engine.g_model_entries, self.overlay_filter, &rows);- const sel = if (n == 0) 0 else self.overlay_sel % n;- if (n == 0 or dispatch.refuseProviderMutation(self)) {- self.closeOverlay();- return .stay;- }- self.closeOverlay();- // THE row the user chose, provider and all. Handing the engine the- // name alone let it re-route by first-name-match, so picking the- // openai row for a model codex also serves landed on codex.- const pick = rows[sel];- if (engine.g_model_fn) |f| {- const previous: engine.Picked = .{ .model = engine.g_model_name, .provider = engine.g_model_provider };- if (f(engine.g_turn_ctx, self.alloc, pick.provider, pick.name)) |got| {- const same = std.mem.eql(u8, previous.model, got.model) and std.mem.eql(u8, previous.provider, got.provider);- self.adoptModel(got);- self.setToast(if (same) "already using this model" else got.model);- self.pushFmt(.system, "{s} {s} · {s}", .{ if (same) "already using" else "model →", got.model, got.provider }) catch {};- } else self.setToast("couldn't switch");- } else {- engine.g_model_name = pick.name;- engine.g_model_provider = pick.provider;- self.setToast(pick.name);- }- },- .effort => {- if (@import("effort.zig").pick(self)) |e| {- self.effort = e;- self.setToast(@tagName(e));- }- self.closeOverlay();- },- .settings => {- const which = self.overlay_sel % 4;- switch (which) {- 0 => self.openOverlay(.model),- 1 => {- self.openOverlay(.effort);- self.overlay_sel = @intFromEnum(self.effort);- },- 2 => self.cycleMode(),- else => self.openOverlay(.theme),- }- },- .file => {- var names: [files_mod.max_files][]const u8 = undefined;- const n = files_mod.filterList(self.files_cache orelse "", self.overlay_filter, &names);- const sel = if (n == 0) 0 else self.overlay_sel % n;- self.closeOverlay();- if (n == 0) return .stay;- // names point into files_cache, which closeOverlay leaves alone.- self.input.insertSlice(names[sel]);- self.input.handle(.{ .char = ' ' });- self.focus = .prompt;- },- .jump => {- const total = self.userTurnCount();- const sel = if (total == 0) 0 else self.overlay_sel % total;- self.closeOverlay();- if (total == 0) return .stay;- var seen: usize = 0;- for (self.history.items, 0..) |e, i| {- if (e.kind != .user) continue;- if (seen == sel) {- @import("nav.zig").jumpTo(self, i);- break;- }- seen += 1;- }- },- .sessions => {- const resume_mod = @import("resume.zig");- const base = resume_mod.pick(self);- self.closeOverlay();- if (base) |b| resume_mod.run(self, b);- },- else => self.closeOverlay(),- }- return .stay;-}--/// One SGR wheel report. 64 is a notch up, 65 a notch down.-fn notch(m: *Model, up: bool) void {- _ = @import("keys.zig").handle(m, .{ .mouse = .{ .btn = if (up) 64 else 65, .x = 10, .y = 5, .down = true } });-}--test "a wheel notch moves an open picker by exactly one item" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.openOverlay(.model);- // Four notches down is four items — not twelve, and not one coalesced move.- // A trackpad delivers a flick as a BURST of reports and run.zig hands every- // one of them to keys.handle, so the per-event step is the whole contract.- for (0..4) |i| {- try std.testing.expectEqual(i, m.overlay_sel);- notch(&m, false);- }- try std.testing.expectEqual(@as(usize, 4), m.overlay_sel);- for (0..4) |_| notch(&m, true);- try std.testing.expectEqual(@as(usize, 0), m.overlay_sel);- notch(&m, true); // already at the top: saturates, never wraps to a huge index- try std.testing.expectEqual(@as(usize, 0), m.overlay_sel);- // ...and the transcript underneath never moved.- try std.testing.expectEqual(@as(usize, 0), m.scroll);- try std.testing.expect(m.follow);-}--test "a wheel notch moves the completion menu one command, clamped to the list" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.focus = .prompt;- try m.input.setValue("/");- var idx: [catalog.items.len]usize = undefined;- const n = catalog.filter("/", &idx);- try std.testing.expect(n > 2);- notch(&m, false);- try std.testing.expectEqual(@as(usize, 1), m.slash_sel);- notch(&m, false);- try std.testing.expectEqual(@as(usize, 2), m.slash_sel);- notch(&m, true);- try std.testing.expectEqual(@as(usize, 1), m.slash_sel);- // Spinning past the end parks on the last row rather than selecting a- // command the menu is not showing.- for (0..n + 8) |_| notch(&m, false);- try std.testing.expectEqual(n - 1, m.slash_sel);- try std.testing.expectEqual(@as(usize, 0), m.scroll);-}--test "with no list open the wheel still scrolls the transcript" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- notch(&m, true);- try std.testing.expect(m.scroll > 0);- try std.testing.expect(!m.follow);- try std.testing.expectEqual(@as(usize, 0), m.overlay_sel);-}--test "file overlay Enter inserts the picked path after the @" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.files_cache = try std.testing.allocator.dupe(u8, "src/a.zig\ndocs/b.md");- try m.input.setValue("look at @");- m.openOverlay(.file);- for ("bmd") |c| m.typeOverlayFilter(c);- _ = key(&m, .enter);- try std.testing.expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqualStrings("look at @docs/b.md ", m.input.getValue());-}--test "jump overlay Enter selects the chosen user turn" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "one");- try m.push(.assistant, "a");- try m.push(.user, "two");- try m.push(.assistant, "b");- m.openOverlay(.jump);- m.overlay_sel = 1;- _ = key(&m, .enter);- try std.testing.expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqual(@as(usize, 2), m.selected);- try std.testing.expect(m.focus == .scrollback);- try std.testing.expect(!m.follow);-}diff --git a/TUI/owned_images.zig b/TUI/owned_images.zigdeleted file mode 100644index 391c0b90..00000000--- a/TUI/owned_images.zig+++ /dev/null@@ -1,122 +0,0 @@-//! Owned clipboard exports outlive every live draft/history consumer.-const std = @import("std");-const recovery = @import("clipboard_recovery.zig");-const Model = @import("app.zig").Model;--pub const Owned = struct {- path: []const u8,- identity: std.Io.File.Stat,- retained: bool = false,- store: ?*recovery.Store = null,- lease: ?recovery.Lease = null,-};-var default_store: ?recovery.Store = null;-pub var test_store: ?*recovery.Store = null;-fn storeForPaste() ?*recovery.Store {- if (@import("builtin").is_test) return test_store;- if (default_store == null) {- const temp = std.c.getenv("TMPDIR") orelse return null;- if (!std.fs.path.isAbsolute(std.mem.span(temp))) return null;- const root = std.fs.path.join(std.heap.page_allocator, &.{ std.mem.span(temp), "graff-tui-clipboard" }) catch return null;- defer std.heap.page_allocator.free(root);- default_store = recovery.Store.init(std.Io.Threaded.global_single_threaded.io(), std.heap.page_allocator, root) catch return null;- }- return &default_store.?;-}--fn identity(path: []const u8) ?std.Io.File.Stat {- const stat = std.Io.Dir.cwd().statFile(std.Io.Threaded.global_single_threaded.io(), path, .{ .follow_symlinks = false }) catch return null;- return if (stat.kind == .file) stat else null;-}--pub fn attach(self: *Model, path: []const u8, owned: bool) void {- if (!owned) return self.attachImage(path);- const original = identity(path) orelse return self.attachImage(path);- const copy = self.alloc.dupe(u8, path) catch {- remove(.{ .path = path, .identity = original });- return;- };- self.owned_images.append(.{ .path = copy, .identity = original }) catch {- self.alloc.free(copy);- remove(.{ .path = path, .identity = original });- return;- };- const entry = &self.owned_images.items[self.owned_images.items.len - 1];- if (storeForPaste()) |store| {- _ = store.sweep(64);- entry.store = store;- entry.lease = store.record(path, original) catch null;- }- const before = self.images.items.len;- self.attachImage(path);- if (self.images.items.len == before) collect(self);-}--fn remove(owned: Owned) void {- const current = identity(owned.path) orelse return;- const original = owned.identity;- // A pathname is not deletion authority after another file replaces it.- // Also preserve edits made in place; reading a preview only changes atime.- if (current.inode != original.inode or current.size != original.size or- !std.meta.eql(current.mtime, original.mtime) or !std.meta.eql(current.ctime, original.ctime)) return;- std.Io.Dir.cwd().deleteFile(std.Io.Threaded.global_single_threaded.io(), owned.path) catch {};-}--fn contains(paths: []const []const u8, path: []const u8) bool {- for (paths) |p| if (std.mem.eql(u8, p, path)) return true;- return false;-}--fn referenced(self: *const Model, path: []const u8) bool {- if (contains(self.images.items, path)) return true;- if (self.draft_images) |paths| if (contains(paths, path)) return true;- for (self.prompt_hist_images.items) |paths| if (contains(paths, path)) return true;- for (self.history.items) |entry| if (std.mem.indexOf(u8, entry.text, path) != null) return true;- for (self.steer_queue.items) |text| if (std.mem.indexOf(u8, text, path) != null) return true;- return false;-}--/// A submitted turn may be persisted independently of visible TUI history.-pub fn retain(self: *Model, text: []const u8) !void {- for (self.owned_images.items) |*owned| {- if (std.mem.indexOf(u8, text, owned.path) == null) continue;- if (owned.store) |store| try store.retain(&owned.lease);- owned.retained = true;- }-}--pub fn collect(self: *Model) void {- // Pending consumers may already hold a snapshot outside the model arrays.- if (self.pending != null or self.bg != null) return;- var i: usize = 0;- while (i < self.owned_images.items.len) {- var owned = self.owned_images.items[i];- const path = owned.path;- if (owned.retained or referenced(self, path)) {- i += 1;- continue;- }- remove(owned);- if (owned.store) |store| store.release(&owned.lease);- self.alloc.free(self.owned_images.orderedRemove(i).path);- }-}--fn replayReferenced(self: *const Model, path: []const u8) bool {- for (self.history.items) |entry| {- if (entry.kind == .user and std.mem.indexOf(u8, entry.text, path) != null) return true;- }- return false;-}--pub fn deinit(self: *Model, settled: bool) void {- for (self.owned_images.items) |*owned| {- const path = owned.path;- // Saved turns retain path markers. UI teardown is not proof that- // those replay consumers (or an abandoned worker) have released them.- if (settled and !owned.retained and !replayReferenced(self, path)) remove(owned.*);- if (settled) if (owned.store) |store| store.release(&owned.lease);- self.alloc.free(path);- }- self.owned_images.deinit();-}diff --git a/TUI/pacing.zig b/TUI/pacing.zigdeleted file mode 100644index 95347858..00000000--- a/TUI/pacing.zig+++ /dev/null@@ -1,288 +0,0 @@-//! Input pacing for the fullscreen loop: wheel coalescing and the frame budget.-//!-//! Trackpad momentum delivers wheel reports far faster than a frame can be-//! composed and painted. Serviced one report per paint, the loop queues work it-//! can never catch up on — the scroll trails the fingers and then jumps to the-//! end when the backlog drains. Two rules fix that, and both live here as pure-//! decisions so they can be pinned without a tty.-//!-//! 1. COALESCE. Consecutive wheel reports fold into ONE accumulated notch-//! delta. Order is preserved and any non-wheel event BREAKS the run at that-//! point, so a keystroke typed mid-storm keeps its exact place in the-//! stream and is never starved behind the flood. Folding is not only-//! cheaper, it is more faithful: `scroll` saturates at the bottom edge, so-//! applying a down-down-up run one report at a time latches `follow` back on-//! and lands somewhere the net delta never asked for.-//!-//! 2. BUDGET. At most one composed frame per `frame_budget_ms`, and only while-//! input is still arriving. Idle — which includes a single wheel tick — the-//! frame is immediate, so the budget can never add latency to a scroll the-//! user is not actually storming.--const std = @import("std");--const key_mod = @import("key.zig");-const Key = key_mod.Key;--/// ~120fps. Long enough that a momentum burst folds into one frame, short-/// enough that no eye reads the frame as late.-pub const frame_budget_ms: u64 = 8;--/// Lines per wheel notch — the xterm convention keys.mouseKey already used.-pub const lines_per_notch: i32 = 3;--/// How many distinct items one tick applies before the loop drains and reopens-/// the batch. A run of wheel reports folds into the trailing item and costs-/// nothing, so this bounds INTERLEAVING, not storm size.-pub const batch_cap: usize = 64;--/// SGR buttons 64/65 are the wheel reported as a button (?1006h). +1 scrolls-/// back through the transcript, -1 forward — the sign keys.scrollBy takes.-pub fn wheelNotch(k: Key) ?i32 {- if (k != .mouse) return null;- return switch (k.mouse.btn) {- 64 => 1,- 65 => -1,- else => null,- };-}--/// One unit of dispatch: an ordinary key, or a folded run of wheel reports-/// carrying their accumulated notch delta.-pub const Item = union(enum) {- key: Key,- wheel: i32,-};--pub const Push = enum { ok, full };--/// Events drained from one tick, with consecutive wheel reports folded.-pub const Batch = struct {- buf: [batch_cap]Item = undefined,- len: usize = 0,- /// Raw wheel reports folded in (for the paint-stats counter).- folded: usize = 0,-- pub fn push(self: *Batch, k: Key) Push {- if (wheelNotch(k)) |d| {- // Folding into the trailing run never needs a slot, which is what- // lets a 500-report storm fit in a 64-item batch.- if (self.len > 0 and self.buf[self.len - 1] == .wheel) {- self.buf[self.len - 1].wheel += d;- self.folded += 1;- return .ok;- }- if (self.len == self.buf.len) return .full;- self.buf[self.len] = .{ .wheel = d };- self.len += 1;- self.folded += 1;- return .ok;- }- if (self.len == self.buf.len) return .full;- self.buf[self.len] = .{ .key = k };- self.len += 1;- return .ok;- }-- pub fn items(self: *const Batch) []const Item {- return self.buf[0..self.len];- }-- pub fn reset(self: *Batch) void {- self.len = 0;- self.folded = 0;- }-};--/// Input still arriving faster than two frames apart. Momentum reports land-/// every millisecond or two; a second flick a tenth of a second later, or a-/// human typing at 20Hz, or a key repeating at 30Hz, are all comfortably-/// OUTSIDE this window and are never treated as a storm.-///-/// This, not "are there bytes queued right now", is the signal that matters:-/// on a fast loop each momentum report is read the instant it lands and finds-/// the queue empty behind it, so a queue check alone would happily paint 500-/// times for 500 reports.-pub const storm_gap_ms: u64 = 2 * frame_budget_ms;--pub fn storming(now_ms: u64, last_input_ms: u64) bool {- return last_input_ms != 0 and now_ms -| last_input_ms < storm_gap_ms;-}--/// May the loop compose and paint a frame this tick?-///-/// Quiet — no backlog and no recent stream — the answer is always yes: one-/// wheel tick paints on the spot with nothing added to its latency. Under a-/// storm the frame waits out the budget, which bounds paints at-/// ~1/frame_budget_ms instead of one per report; and because a skipped tick-/// goes straight back to draining, the frame that does land shows the LATEST-/// scroll position and never an intermediate one.-pub fn shouldPaint(now_ms: u64, last_frame_ms: u64, last_input_ms: u64, more_pending: bool) bool {- if (!more_pending and !storming(now_ms, last_input_ms)) return true;- return now_ms -| last_frame_ms >= frame_budget_ms;-}--/// Cap a poll timeout at the frame the loop already OWES. Called only on the-/// tick after a deferred frame, so an idle loop keeps its long, cheap waits-/// instead of spinning at 125Hz for nothing.-pub fn waitCap(now_ms: u64, last_frame_ms: u64, wait_ms: i32) i32 {- const used = now_ms -| last_frame_ms;- if (used >= frame_budget_ms) return 0;- const left: i32 = @intCast(frame_budget_ms - used);- return @min(wait_ms, left);-}--/// Has this tick's drain used up the budget? Without this a genuinely endless-/// flood would be drained forever and never painted at all.-pub fn drainExpired(now_ms: u64, tick_start_ms: u64) bool {- return now_ms -| tick_start_ms >= frame_budget_ms;-}--// --- local-only instrumentation (GRAFF_TUI_PAINT_STATS=1) -------------------// Off by default and never wired to telemetry: this exists so a pty storm test-// can assert the paint count is BUDGETED rather than one-per-report.--pub var stats_on: bool = false;-pub var ticks: u64 = 0;-pub var frames: u64 = 0;-pub var paints: u64 = 0;-pub var frames_skipped: u64 = 0;-pub var reads: u64 = 0;-pub var events: u64 = 0;-pub var wheel_events: u64 = 0;-pub var wheel_batches: u64 = 0;--pub fn resetStats() void {- ticks = 0;- frames = 0;- paints = 0;- frames_skipped = 0;- reads = 0;- events = 0;- wheel_events = 0;- wheel_batches = 0;-}--/// One line, written after the terminal has been handed back so it lands on-/// the normal screen instead of inside the alt-screen frame.-pub fn report(w: *std.Io.Writer) void {- if (!stats_on) return;- w.print(- "tui-paint-stats: paints={d} frames={d} skipped={d} ticks={d} reads={d} events={d} wheel_events={d} wheel_batches={d}\n",- .{ paints, frames, frames_skipped, ticks, reads, events, wheel_events, wheel_batches },- ) catch {};- w.flush() catch {};-}--fn wheel(btn: u8) Key {- return .{ .mouse = .{ .btn = btn, .x = 1, .y = 1, .down = true } };-}--test "consecutive wheel reports fold; a key breaks the run and keeps its place" {- var b: Batch = .{};- for (0..5) |_| try std.testing.expectEqual(Push.ok, b.push(wheel(64)));- try std.testing.expectEqual(Push.ok, b.push(.{ .char = 'x' }));- for (0..3) |_| try std.testing.expectEqual(Push.ok, b.push(wheel(65)));-- const it = b.items();- try std.testing.expectEqual(@as(usize, 3), it.len);- try std.testing.expectEqual(@as(i32, 5), it[0].wheel);- try std.testing.expectEqual(@as(u8, 'x'), it[1].key.char);- try std.testing.expectEqual(@as(i32, -3), it[2].wheel);- // 9 reports arrived, 3 units of work come out.- try std.testing.expectEqual(@as(usize, 8), b.folded);-}--test "a mixed run nets out instead of clamping at the bottom edge" {- // down-down-up is a NET one notch back. Applied report by report it hits- // scroll==0 halfway, re-latches follow, and ends a notch further along than- // the fingers asked for.- var b: Batch = .{};- _ = b.push(wheel(65));- _ = b.push(wheel(65));- _ = b.push(wheel(64));- try std.testing.expectEqual(@as(usize, 1), b.len);- try std.testing.expectEqual(@as(i32, -1), b.items()[0].wheel);-}--test "a storm of wheel reports never overflows the batch" {- var b: Batch = .{};- for (0..5000) |_| try std.testing.expectEqual(Push.ok, b.push(wheel(65)));- try std.testing.expectEqual(@as(usize, 1), b.len);- try std.testing.expectEqual(@as(i32, -5000), b.items()[0].wheel);-}--test "interleaving fills the batch and reports full so the loop can drain" {- var b: Batch = .{};- var i: usize = 0;- while (i < batch_cap) : (i += 1) {- try std.testing.expectEqual(Push.ok, b.push(.{ .char = 'a' }));- }- try std.testing.expectEqual(Push.full, b.push(.{ .char = 'a' }));- // ...but a wheel report still folds if the tail is a wheel run, so the- // full-batch path can never be reached by scrolling alone.- b.reset();- _ = b.push(wheel(64));- i = 1;- while (i < batch_cap) : (i += 1) _ = b.push(.{ .char = 'a' });- try std.testing.expectEqual(Push.full, b.push(.{ .char = 'a' }));- try std.testing.expectEqual(Push.full, b.push(wheel(64)));-}--test "non-wheel mouse events are not coalesced" {- var b: Batch = .{};- _ = b.push(.{ .mouse = .{ .btn = 0, .x = 2, .y = 3, .down = true } });- _ = b.push(.{ .mouse = .{ .btn = 0, .x = 2, .y = 4, .down = false } });- try std.testing.expectEqual(@as(usize, 2), b.len);- try std.testing.expectEqual(@as(?i32, null), wheelNotch(.{ .mouse = .{ .btn = 0, .x = 1, .y = 1, .down = true } }));- try std.testing.expectEqual(@as(?i32, null), wheelNotch(.{ .char = 'k' }));-}--test "the budget is free for one flick and bounds paints under a flood" {- // Nothing queued and nothing recent: paint now. This is the single-wheel-- // tick case, and it must not pay one millisecond for the budget...- try std.testing.expect(shouldPaint(1000, 1000, 0, false));- try std.testing.expect(shouldPaint(1000, 999, 900, false));- // ...including a second flick a tenth of a second after the first.- try std.testing.expect(shouldPaint(1000, 1000, 900, false));- // Backlog waiting: wait out the budget, then paint.- try std.testing.expect(!shouldPaint(1000, 1000, 0, true));- try std.testing.expect(!shouldPaint(1007, 1000, 0, true));- try std.testing.expect(shouldPaint(1008, 1000, 0, true));- try std.testing.expect(shouldPaint(9000, 1000, 0, true));- // ...and a stream arriving faster than the loop can back up is a storm all- // the same. Without this, momentum reports that each find an empty queue- // behind them paint one frame per report — the whole bug.- try std.testing.expect(!shouldPaint(1002, 1000, 1001, false));- try std.testing.expect(shouldPaint(1008, 1000, 1007, false));-}--test "storming is a rate, not a backlog" {- try std.testing.expect(storming(1001, 1000));- try std.testing.expect(storming(1015, 1000));- // 16ms of silence ends it: typing at 20Hz and key repeat at 30Hz are both- // outside, so neither ever costs a frame of latency.- try std.testing.expect(!storming(1016, 1000));- try std.testing.expect(!storming(1050, 1000));- // A session that has taken no input at all is not storming.- try std.testing.expect(!storming(9999, 0));-}--test "the owed-frame wait never outlives the budget and never spins" {- // A long idle wait is capped to what is left of the budget...- try std.testing.expectEqual(@as(i32, 8), waitCap(1000, 1000, 200));- try std.testing.expectEqual(@as(i32, 3), waitCap(1005, 1000, 200));- // ...but a shorter wait the loop already wanted still wins.- try std.testing.expectEqual(@as(i32, 2), waitCap(1005, 1000, 2));- // Budget spent: return immediately and paint. Returning a positive value- // here would be a spin at 125Hz that never owed a frame in the first place.- try std.testing.expectEqual(@as(i32, 0), waitCap(1008, 1000, 200));- try std.testing.expectEqual(@as(i32, 0), waitCap(9000, 1000, 200));-}--test "the drain has a deadline so an endless flood still paints" {- try std.testing.expect(!drainExpired(1000, 1000));- try std.testing.expect(!drainExpired(1007, 1000));- try std.testing.expect(drainExpired(1008, 1000));- try std.testing.expect(frame_budget_ms > 0 and frame_budget_ms <= 16);-}diff --git a/TUI/paint.zig b/TUI/paint.zigdeleted file mode 100644index 34f9640b..00000000--- a/TUI/paint.zig+++ /dev/null@@ -1,234 +0,0 @@-//! The frame painter: the only code in the TUI that writes cells to a screen.-//!-//! One invariant, and every line below exists to hold it: **when paint()-//! returns, each of the `rows` screen rows shows the matching line of `frame`-//! and nothing else** — no cell of an older frame, no colour borrowed from a-//! row that happened to be painted earlier.-//!-//! Two mechanisms carry it.-//!-//! * Every repainted row re-establishes its own style before its first cell-//! (SGR reset, then the theme background). A diff paint rewrites an-//! ARBITRARY SUBSET of rows, so a row that inherited fg/inverse from the-//! row above it under a full paint would inherit whatever the last-//! repainted row left behind under a diff paint: the same frame bytes,-//! two different pictures.-//! * Every repainted row is covered out to the last column. A row the frame-//! proves SHORTER than the screen is written, padded with the theme-//! background and erased to end of line. A row that MEASURES full is-//! erased FIRST and written after — a trailing erase would sit on the last-//! cell and eat it (that is what ate the composer's right border), and-//! simply skipping the erase trusted visibleLen to agree with the terminal-//! about every ambiguous-width glyph on the row. When it does not agree,-//! the cells past the last glyph the terminal actually drew keep the-//! PREVIOUS frame. Erase-first is right whether the measurement is or not.--const std = @import("std");-const Io = std.Io;--const scrollpaint = @import("scrollpaint.zig");-const theme_mod = @import("theme.zig");--/// Rewrite only rows that changed, so a drag-select on older transcript-/// survives a live token / thinking tick.-///-/// `prev` empty -> clear the screen and lay down every row (first paint, and-/// after anything that blanks the alt screen: SIGCONT, a-/// resize, a theme flip).-/// `force` true -> rewrite every row WITHOUT the clear: the self-heal repaint.-/// The bytes are the frame we already believe is on screen, so-/// under synchronized output (?2026) it is visually a no-op —-/// but it is also the only thing that can repair a screen some-/// other writer, or a terminal-side reflow, has disturbed.-/// `hint` set -> the composer believes the viewport merely SLID. Row i is-/// then the wrong thing to compare row i against, and every-/// row of the band reads as changed; scrollpaint.zig checks-/// the claim against both frames and, when it holds, has the-/// terminal do the sliding. It never writes on a refusal, so-/// falling through here is always safe. The self-heal MUST-/// bypass it: its whole job is to rewrite rows that are-/// already correct, which is precisely what a scroll skips.-pub fn paint(- w: *Io.Writer,- frame: []const u8,- rows: usize,- cols: usize,- prev: []const u8,- bg: []const u8,- force: bool,- hint: ?scrollpaint.Hint,-) !void {- if (prev.len == 0) {- try w.writeAll(bg);- try w.writeAll("\x1b[2J\x1b[H");- var row: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (row < rows) : (row += 1) {- try paintRow(w, if (it.next()) |ln| ln else "", cols, bg);- if (row + 1 < rows) try w.writeAll("\r\n");- }- // No trailing ED here. The release tip added one ("erase below, so a- // scrolled alt screen self-heals"), but the `\x1b[2J` above already- // clears the WHOLE display, scrolled rows included — while ED is- // cursor-INCLUSIVE, and with autowrap off the cursor sits ON the last- // column after a bottom row that measures full. It would erase the- // glyph the erase-first branch just drew. Pinned below.- try w.flush();- return;- }- if (!force) {- if (hint) |h| {- if (try scrollpaint.tryPaint(w, frame, rows, cols, prev, bg, h)) return;- }- }- var row: usize = 0;- while (row < rows) : (row += 1) {- if (!force and !rowChanged(prev, frame, row)) continue;- try w.print("\x1b[{d};1H", .{row + 1});- try paintRow(w, nthLine(frame, row), cols, bg);- }- try w.flush();-}--/// One row, cursor already at its first column. See the file header: the-/// prologue makes the row's style self-contained, and the two shapes below are-/// the entire residue story.-pub fn paintRow(w: *Io.Writer, ln: []const u8, cols: usize, bg: []const u8) !void {- try w.writeAll(row_prologue);- try w.writeAll(bg);- // Measure and write the same cells: a smuggled CR/BEL/BS is not a column- // and must not reach the terminal (CR rewinds the row, BEL rings, BS- // walks the cursor back). Tab expands to the next stop of 8 — counting- // it as one cell leaves pad() short and can preserve the previous frame.- // ESC stays — that is SGR. The frame builders already strip this; this is- // the last door so a leak cannot desync the row↔line map.- const vis = cellLen(ln);- if (vis < cols) {- try writeCells(w, ln);- try pad(w, cols - vis);- try w.writeAll(bg);- try w.writeAll("\x1b[K");- return;- }- // Provably-full or over-wide: erase the whole row up front, then draw.- try w.writeAll("\x1b[K");- // Autowrap is off (?7l), so an over-wide row piles onto the last cell- // rather than wrapping — but a terminal that ignores ?7l would push every- // row below down by one and desync the row↔line map for the whole screen.- // Cut it to fit and the question never arises.- try writeCells(w, if (vis > cols) takeCells(ln, cols) else ln);-}--/// SGR reset (all attributes, including inverse from a selection band). The-/// theme background is re-applied immediately after, so this never leaves the-/// canvas on the terminal's default.-pub const row_prologue = "\x1b[m";--fn pad(w: *Io.Writer, cells: usize) !void {- var n = cells;- while (n > 0) : (n -= 1) try w.writeByte(' ');-}--/// C0/DEL that must never be a cell. Tab is expanded to spaces by the callers;-/// ESC is kept (SGR) and handled before it reaches this predicate.-fn isRowControl(b: u8) bool {- return (b < 0x20 and b != '\t') or b == 0x7f;-}--/// Columns a tab occupies at `col`, matching terminal stops of 8.-fn tabPad(col: usize) usize {- return 8 - (col % 8);-}--fn cellLen(ln: []const u8) usize {- var n: usize = 0;- var i: usize = 0;- while (i < ln.len) {- if (ln[i] == 0x1b) {- i = theme_mod.skipEsc(ln, i);- continue;- }- if (ln[i] == '\t') {- n += tabPad(n);- i += 1;- continue;- }- if (isRowControl(ln[i])) {- i += 1;- continue;- }- const c = theme_mod.cpAt(ln, i);- i += c.step;- n += c.w;- }- return n;-}--fn takeCells(ln: []const u8, max: usize) []const u8 {- var n: usize = 0;- var i: usize = 0;- while (i < ln.len) {- if (ln[i] == 0x1b) {- i = theme_mod.skipEsc(ln, i);- continue;- }- if (ln[i] == '\t') {- const width = tabPad(n);- if (n + width > max) break;- n += width;- i += 1;- continue;- }- if (isRowControl(ln[i])) {- i += 1;- continue;- }- const c = theme_mod.cpAt(ln, i);- if (n + c.w > max) break;- i += c.step;- n += c.w;- }- return ln[0..i];-}--fn writeCells(w: *Io.Writer, ln: []const u8) !void {- var i: usize = 0;- var col: usize = 0;- while (i < ln.len) {- if (ln[i] == 0x1b) {- const e = theme_mod.skipEsc(ln, i);- try w.writeAll(ln[i..e]);- i = e;- continue;- }- if (ln[i] == '\t') {- const width = tabPad(col);- try pad(w, width);- col += width;- i += 1;- continue;- }- if (isRowControl(ln[i])) {- i += 1;- continue;- }- const start = i;- i += 1;- while (i < ln.len and ln[i] != 0x1b and ln[i] != '\t' and !isRowControl(ln[i])) : (i += 1) {}- try w.writeAll(ln[start..i]);- col += theme_mod.visibleLen(ln[start..i]);- }-}--pub fn nthLine(s: []const u8, row: usize) []const u8 {- var it = std.mem.splitScalar(u8, s, '\n');- var i: usize = 0;- while (it.next()) |ln| : (i += 1) {- if (i == row) return ln;- }- return "";-}--pub fn rowChanged(prev: []const u8, frame: []const u8, row: usize) bool {- return !std.mem.eql(u8, nthLine(prev, row), nthLine(frame, row));-}diff --git a/TUI/paint_tests.zig b/TUI/paint_tests.zigdeleted file mode 100644index dc46d83b..00000000--- a/TUI/paint_tests.zig+++ /dev/null@@ -1,528 +0,0 @@-//! Frame-painter battery. Lives next door so paint.zig stays the writer.-//!-//! The Screen double is the only thing the painter can get wrong: which-//! codepoint ends up in which cell. Autowrap is off, exactly as the TUI sets-//! it. New cases that would grow paint.zig past 600 LOC land here.--const std = @import("std");-const Io = std.Io;--const paint = @import("paint.zig");-const theme_mod = @import("theme.zig");--const test_bg = "\x1b[48;2;20;20;20m";--fn paintToBuf(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8) ![]u8 {- return paintForced(a, frame, rows, cols, prev, false);-}--fn paintForced(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8, force: bool) ![]u8 {- var aw = Io.Writer.Allocating.init(a);- errdefer aw.deinit();- try paint.paint(&aw.writer, frame, rows, cols, prev, test_bg, force, null);- return aw.toOwnedSlice();-}--/// A terminal, reduced to the only thing the painter can get wrong: which-/// codepoint ends up in which cell. Autowrap is off, exactly as the TUI sets-/// it. `untouched` marks a cell no paint has ever written, so a test can tell-/// "stale content" apart from "never drawn".-const Screen = struct {- const untouched: u21 = 0;- const wide_tail: u21 = 0x10FFFE; // right half of a double-width glyph-- rows: usize,- cols: usize,- cells: []u21,- row: usize = 0,- col: usize = 0,- /// Does this terminal honour a VS16 emoji-presentation selector by widening- /// the glyph to two cells? Real ones disagree — and that disagreement is- /// the whole hazard: when the terminal draws a row NARROWER than- /// visibleLen measured it, every cell past the last glyph it drew keeps- /// whatever the previous frame put there unless the painter erased first.- vs16_wide: bool = true,-- fn init(a: std.mem.Allocator, rows: usize, cols: usize) !Screen {- const cells = try a.alloc(u21, rows * cols);- @memset(cells, untouched);- return .{ .rows = rows, .cols = cols, .cells = cells };- }-- fn at(self: *Screen, r: usize, c: usize) *u21 {- return &self.cells[r * self.cols + c];- }-- fn put(self: *Screen, cp: u21, wide: bool) void {- if (self.row >= self.rows) return;- const c = @min(self.col, self.cols - 1);- self.at(self.row, c).* = cp;- if (wide and c + 1 < self.cols) self.at(self.row, c + 1).* = wide_tail;- self.col = @min(c + (if (wide) @as(usize, 2) else 1), self.cols);- }-- fn eraseToEol(self: *Screen) void {- if (self.row >= self.rows) return;- var c = @min(self.col, self.cols - 1);- while (c < self.cols) : (c += 1) self.at(self.row, c).* = ' ';- }-- fn clearAll(self: *Screen) void {- @memset(self.cells, ' ');- self.row = 0;- self.col = 0;- }-- /// Feed terminal output. Understands exactly what the painter emits: CUP,- /// EL, ED, CR/LF and text; every other escape is style and is skipped.- fn feed(self: *Screen, s: []const u8) void {- var i: usize = 0;- while (i < s.len) {- if (s[i] == 0x1b) {- const e = theme_mod.skipEsc(s, i);- self.control(s[i..e]);- i = e;- continue;- }- if (s[i] == '\r') {- self.col = 0;- i += 1;- continue;- }- if (s[i] == '\n') {- self.row += 1;- i += 1;- continue;- }- const len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;- const step = @min(@as(usize, len), s.len - i);- const cp = std.unicode.utf8Decode(s[i .. i + step]) catch ' ';- const own = theme_mod.visibleLen(s[i .. i + step]);- const vs16 = i + step + 3 <= s.len and std.mem.eql(u8, s[i + step .. i + step + 3], "\u{FE0F}");- if (own != 0) self.put(cp, own == 2 or (vs16 and self.vs16_wide));- i += step;- }- }-- fn control(self: *Screen, seq: []const u8) void {- if (seq.len < 3 or seq[1] != '[') return;- const final = seq[seq.len - 1];- const body = seq[2 .. seq.len - 1];- switch (final) {- 'H' => {- var r: usize = 1;- var it = std.mem.splitScalar(u8, body, ';');- if (it.next()) |p| r = std.fmt.parseInt(usize, p, 10) catch 1;- self.row = if (r > 0) r - 1 else 0;- self.col = 0;- },- 'J' => if (std.mem.eql(u8, body, "2")) self.clearAll(),- 'K' => self.eraseToEol(),- else => {},- }- }-- /// What `frame` SHOULD look like on this screen: every line padded to the- /// full width, every row past the frame's last line blank.- fn expect(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, vs16_wide: bool) !Screen {- var s = try Screen.init(a, rows, cols);- s.vs16_wide = vs16_wide;- s.clearAll();- var row: usize = 0;- while (row < rows) : (row += 1) {- s.row = row;- s.col = 0;- s.feed(theme_mod.takeCols(paint.nthLine(frame, row), cols));- }- return s;- }-- fn expectMatches(self: *Screen, other: *Screen) !void {- var r: usize = 0;- while (r < self.rows) : (r += 1) {- var c: usize = 0;- while (c < self.cols) : (c += 1) {- const got = self.at(r, c).*;- const want = other.at(r, c).*;- if (got == want) continue;- std.debug.print(- "row {d} col {d}: screen has U+{X} but the frame says U+{X}\n",- .{ r, c, got, want },- );- return error.ResidueOnScreen;- }- }- }-};--/// Rows a terminal is genuinely liable to disagree with us about: ambiguous-/// width symbols, a VS16 promotion, CJK, an emoji landing on the last cell,-/// box drawing that fills the row exactly.-const torture = [_][]const u8{- "\u{2713} bash finished ok",- "\u{2713}\u{FE0F} bash finished ok",- "\u{65E5}\u{672C}\u{8A9E} mixed \u{1F680}",- "\u{256D}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256E}",- "plain ascii row",- "",- "e\u{0301}dge combining",- "trailing wide \u{1F409}",-};--/// Frame A: the torture rows cut to exactly `cols`. Frame B: the same rows-/// half as wide, so every row shrinks under the diff paint — including the-/// ones that measured exactly full, which is where the painter used to skip-/// both the pad and the erase.-fn tortureFrames(ar: std.mem.Allocator, cols: usize) ![2][]const u8 {- var a_buf = std.array_list.Managed(u8).init(ar);- var b_buf = std.array_list.Managed(u8).init(ar);- for (torture, 0..) |row, i| {- if (i > 0) {- try a_buf.append('\n');- try b_buf.append('\n');- }- try a_buf.appendSlice(theme_mod.takeCols(row, cols));- try b_buf.appendSlice(theme_mod.takeCols(row, cols / 2));- }- return .{ a_buf.items, b_buf.items };-}--test "diff paint leaves no residue when a torture frame shrinks under it" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const cols: usize = 10;- const rows = torture.len;- const frames = try tortureFrames(ar, cols);- var screen = try Screen.init(ar, rows, cols);- screen.feed(try paintToBuf(ar, frames[0], rows, cols, ""));- var want_a = try Screen.expect(ar, frames[0], rows, cols, true);- try screen.expectMatches(&want_a);- // ...and now the diff paint, with A as the baseline.- screen.feed(try paintToBuf(ar, frames[1], rows, cols, frames[0]));- var want_b = try Screen.expect(ar, frames[1], rows, cols, true);- try screen.expectMatches(&want_b);-}--test "a terminal that disagrees with visibleLen still shows only the frame" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const cols: usize = 10;- // visibleLen says 10 — exactly full — but a terminal that ignores the- // VS16 selector draws the check mark in ONE cell and the row ends a column- // short. The frame before it filled all ten. Skipping the erase on a row- // that "measures full" left column 9 showing the previous frame's X;- // erasing the row before writing it cannot, whoever is right about the- // glyph.- const claims_full = "\u{2713}\u{FE0F}bash ok!";- const filled = "XXXXXXXXXX";- try std.testing.expectEqual(cols, theme_mod.visibleLen(claims_full));- try std.testing.expectEqual(cols, theme_mod.visibleLen(filled));- var screen = try Screen.init(ar, 1, cols);- screen.vs16_wide = false;- screen.feed(try paintToBuf(ar, filled, 1, cols, ""));- screen.feed(try paintToBuf(ar, claims_full, 1, cols, filled));- var want = try Screen.expect(ar, claims_full, 1, cols, false);- try screen.expectMatches(&want);-}--test "a row that measures full is erased before it is written, never after" {- const a = std.testing.allocator;- // 10 columns of box drawing: EL after the last cell would erase the right- // corner, EL before it cannot, and skipping EL entirely would strand the- // previous frame's cells if the terminal draws the row narrower than we- // measured it.- const full = "\u{256D}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{256E}";- try std.testing.expectEqual(@as(usize, 10), theme_mod.visibleLen(full));- const out = try paintToBuf(a, full, 1, 10, "XXXXXXXXXX");- defer a.free(out);- const erase = std.mem.indexOf(u8, out, "\x1b[K").?;- const corner = std.mem.indexOf(u8, out, "\u{256D}").?;- try std.testing.expect(erase < corner);- try std.testing.expect(std.mem.indexOfPos(u8, out, corner, "\x1b[K") == null);- // The border itself survives intact.- try std.testing.expect(std.mem.indexOf(u8, out, full) != null);-}--test "a shorter row is padded to the width and then erased" {- const a = std.testing.allocator;- const out = try paintToBuf(a, "short", 1, 12, "RESIDUERESID");- defer a.free(out);- const text = std.mem.indexOf(u8, out, "short").?;- const filler = std.mem.indexOfPos(u8, out, text, " ").?; // 12 - 5- const erase = std.mem.indexOfPos(u8, out, filler, "\x1b[K").?;- try std.testing.expect(erase > filler);-}--test "an over-wide row is cut to the width instead of overflowing it" {- const a = std.testing.allocator;- // A builder bug (or a width the frame was composed at before a resize)- // must not hand the terminal more cells than the row has: with autowrap- // off it piles onto the last cell, and with autowrap ON it would shift- // every row below by one and desync the whole diff model.- const out = try paintToBuf(a, "abcdefghijklmnop", 1, 8, "old row!");- defer a.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "abcdefgh") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "abcdefghi") == null);-}--test "every repainted row re-establishes its own style" {- const a = std.testing.allocator;- // Row 0 opens a colour and never closes it; row 1 is plain. Under a diff- // paint that touches only row 1 it must NOT inherit row 0's colour — and- // the only way to promise that is to reset at the head of every row.- const frame = "\x1b[31mred and unterminated\nplain";- const out = try paintToBuf(a, frame, 2, 40, "\x1b[31mred and unterminated\nSTALE");- defer a.free(out);- const cup = std.mem.indexOf(u8, out, "\x1b[2;1H").?;- try std.testing.expectEqualStrings(paint.row_prologue, out[cup + 6 ..][0..paint.row_prologue.len]);- // Row 0 did not change, so it was not touched at all.- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[1;1H") == null);- // The full path resets per row too.- const full = try paintToBuf(a, frame, 2, 40, "");- defer a.free(full);- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, full, paint.row_prologue));-}--test "clearing a selection band repaints every row the band covered" {- const a = std.testing.allocator;- // The band is an SGR-only change on rows 1 and 2 — byte-wise different,- // which is exactly why the diff painter has to rewrite them when the band- // goes away. (If it ever compared visible text instead of bytes, the- // inverse video would stay on screen after the copy.)- const banded = "head\n\x1b[7malpha\x1b[27m\n\x1b[7mbeta\x1b[27m\ntail";- const clean = "head\nalpha\nbeta\ntail";- try std.testing.expect(!paint.rowChanged(banded, clean, 0));- try std.testing.expect(paint.rowChanged(banded, clean, 1));- try std.testing.expect(paint.rowChanged(banded, clean, 2));- try std.testing.expect(!paint.rowChanged(banded, clean, 3));- const out = try paintToBuf(a, clean, 4, 20, banded);- defer a.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7m") == null);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[2;1H") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[3;1H") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[1;1H") == null);-}--test "the self-heal rewrites every row and never flashes the screen" {- const a = std.testing.allocator;- const frame = "one\ntwo\nthree";- // Identical baseline: without `force` this is a no-op paint...- const idle = try paintToBuf(a, frame, 3, 20, frame);- defer a.free(idle);- try std.testing.expectEqual(@as(usize, 0), idle.len);- // ...and with it, every row is rewritten, with no clear-screen in sight.- const healed = try paintForced(a, frame, 3, 20, frame, true);- defer a.free(healed);- for ([_][]const u8{ "\x1b[1;1H", "\x1b[2;1H", "\x1b[3;1H", "one", "two", "three" }) |want| {- try std.testing.expect(std.mem.indexOf(u8, healed, want) != null);- }- try std.testing.expect(std.mem.indexOf(u8, healed, "\x1b[2J") == null);- // The heal is idempotent on a screen that already shows the frame.- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var screen = try Screen.init(ar, 3, 20);- screen.feed(try paintToBuf(ar, frame, 3, 20, ""));- var want = try Screen.expect(ar, frame, 3, 20, true);- try screen.expectMatches(&want);- screen.feed(try paintForced(ar, frame, 3, 20, frame, true));- try screen.expectMatches(&want);-}--test "a full repaint never ends with a cursor-inclusive erase" {- const a = std.testing.allocator;- // The bottom row measures EXACTLY the width, so the erase-first branch- // draws it and leaves the cursor ON the last column (autowrap is off).- // Any ED/EL emitted after that erases the glyph just drawn — which is the- // same class of loss the erase-first design exists to prevent, one row- // lower. The clear at the head of a full paint already covers the whole- // display, so nothing after the last row is needed OR safe.- const bar = "\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}\u{2500}";- const frame = "top row\nmiddle\n" ++ bar;- try std.testing.expectEqual(@as(usize, 10), theme_mod.visibleLen(bar));- const out = try paintToBuf(a, frame, 3, 10, "");- defer a.free(out);- const last = std.mem.lastIndexOf(u8, out, "\u{2500}").? + 3;- try std.testing.expectEqualStrings("", out[last..]);-}--test "rows past the end of the frame are blanked, not left stale" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var screen = try Screen.init(ar, 4, 12);- screen.feed(try paintToBuf(ar, "aaaa\nbbbb\ncccc\ndddd", 4, 12, ""));- // The next frame is two rows shorter — the transcript scrolled away.- screen.feed(try paintToBuf(ar, "aaaa\nbbbb", 4, 12, "aaaa\nbbbb\ncccc\ndddd"));- var want = try Screen.expect(ar, "aaaa\nbbbb", 4, 12, true);- try screen.expectMatches(&want);-}--test "composer shrink clears rows exposed by a taller transcript band" {- const app_mod = @import("app.zig");- const render_mod = @import("render.zig");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const a = arena.allocator();- var m: app_mod.Model = undefined;- m.setup(a);- defer m.deinit();- for (0..80) |i| try m.pushFmt(.assistant, "transcript line {d} with enough words to wrap", .{i});-- try m.input.setValue("old composer text with enough words to occupy many wrapped rows " ++- "before the draft gets shorter and exposes transcript cells");- const before = try render_mod.render(&m, a, 40, 24, 0);- const before_band = m.band;- const before_prompt = m.prompt_origin;-- try m.input.setValue("new draft");- const after = try render_mod.render(&m, a, 40, 24, 0);- const after_band = m.band;-- // The composer lost several wrapped rows, so the transcript both grew and- // moved its viewport. That geometry change must refuse scrollpaint and use- // the row diff, including rows that used to contain the old composer.- try std.testing.expect(m.prompt_origin >= before_prompt + 2);- try std.testing.expect(after_band.len >= before_band.len + 2);- try std.testing.expect(after_band.off != before_band.off);- try std.testing.expect(m.paint_hint == null);-- var screen = try Screen.init(a, 24, 40);- screen.feed(try paintToBuf(a, before, 24, 40, ""));- screen.feed(try paintToBuf(a, after, 24, 40, before));- var want = try Screen.expect(a, after, 24, 40, true);- try screen.expectMatches(&want);-}--test "the real band's rows are exactly the rows the painter rewrites (#529)" {- // The band is a post-pass over the composed frame, so when it CLEARS the- // only thing that puts those rows back is the byte comparison in- // rowChanged. An SGR-only difference is still a difference — this pins- // that, end to end, through the real model rather than a hand-written- // frame, because a painter that ever compared visible TEXT instead would- // leave inverse video on screen after the copy.- const app = @import("app.zig");- const keys = @import("keys.zig");- const render_mod = @import("render.zig");- const a = std.testing.allocator;- var m: app.Model = undefined;- m.setup(a);- defer m.deinit();- try m.push(.assistant, "BANDME alpha line");- try m.push(.assistant, "BANDME beta line");- a.free(try render_mod.render(&m, a, 80, 24, 0)); // lays down mid_origin- const top = m.mid_origin + m.sticky_rows;- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 1), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 40, .y = @intCast(top + 2), .down = true } });- const banded = try render_mod.render(&m, a, 80, 24, 0);- defer a.free(banded);- try std.testing.expect(std.mem.indexOf(u8, banded, "\x1b[7m") != null);- _ = keys.handle(&m, .{ .char = 'x' }); // any ordinary key drops the band- const clean = try render_mod.render(&m, a, 80, 24, 0);- defer a.free(clean);- try std.testing.expect(paint.rowChanged(banded, clean, top));- try std.testing.expect(paint.rowChanged(banded, clean, top + 1));- const out = try paintToBuf(a, clean, 24, 80, banded);- defer a.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7m") == null);- var buf: [16]u8 = undefined;- for ([_]usize{ top + 1, top + 2 }) |one_based| {- const cup = try std.fmt.bufPrint(&buf, "\x1b[{d};1H", .{one_based});- try std.testing.expect(std.mem.indexOf(u8, out, cup) != null);- }-}--test "rowChanged only flags the line that actually moved" {- const prev = "top\nmiddle\nbottom";- const next = "top\nmiddle\nBOTTOM";- try std.testing.expect(!paint.rowChanged(prev, next, 0));- try std.testing.expect(!paint.rowChanged(prev, next, 1));- try std.testing.expect(paint.rowChanged(prev, next, 2));- try std.testing.expect(!paint.rowChanged(prev, prev, 2));-}--test "paint erases a row whose glyphs are ambiguous width" {- const a = std.testing.allocator;- // " ✓ bash finished ok" draws 20 cells. When visibleLen claimed 21 it- // measured full at cols=21, so the old painter skipped the pad AND the- // erase and the 21st cell kept the previous frame.- const frame = " \u{2713} bash finished ok";- try std.testing.expectEqual(@as(usize, 20), theme_mod.visibleLen(frame));- const out = try paintToBuf(a, frame, 1, 21, "RESIDUE RESIDUE RESIDU");- defer a.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[K") != null);-}--test "a smuggled CR or BEL in a frame row never reaches the terminal" {- const a = std.testing.allocator;- // A builder leak (or a tool result that slipped the history filter) used- // to write CR/BEL/BS straight to the tty: CR rewound the row and painted- // over its own prefix, BEL rang, BS walked the cursor back. The painter- // is the last door — the glyphs stay, the controls do not.- const dirty = "ok\rrewind\x07bell\x08!";- const out = try paintToBuf(a, dirty, 1, 20, "XXXXXXXXXXXXXXXXXXXX");- defer a.free(out);- try std.testing.expect(std.mem.indexOfScalar(u8, out, '\r') == null);- try std.testing.expect(std.mem.indexOfScalar(u8, out, 0x07) == null);- try std.testing.expect(std.mem.indexOfScalar(u8, out, 0x08) == null);- try std.testing.expect(std.mem.indexOf(u8, out, "okrewindbell!") != null);- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var screen = try Screen.init(ar, 1, 20);- screen.feed(out);- var want = try Screen.expect(ar, "okrewindbell!", 1, 20, true);- try screen.expectMatches(&want);-}--test "SGR survives the cell filter and tabs expand to terminal stops" {- const a = std.testing.allocator;- // "red" is 3 cells; tab -> 5 spaces (stop 8); "a" then tab -> 7 spaces.- const frame = "\x1b[31mred\x1b[0m\ta\tb";- const out = try paintToBuf(a, frame, 1, 20, "");- defer a.free(out);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[31mred\x1b[0m a b") != null);- try std.testing.expect(std.mem.indexOfScalar(u8, out, '\t') == null);-}--test "a tabbed code row shrinks without leaving the previous prompt behind (#798)" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const cols: usize = 20;- const recalled = "XXXXXXXXXXXXXXXXXXXX";- const fresh = "ab\tcd";- var screen = try Screen.init(ar, 1, cols);- screen.feed(try paintToBuf(ar, recalled, 1, cols, ""));- screen.feed(try paintToBuf(ar, fresh, 1, cols, recalled));- var want = try Screen.expect(ar, "ab cd", 1, cols, true);- try screen.expectMatches(&want);-}--test "history C0 never reaches the composed frame or the paint stream" {- const app = @import("app.zig");- const render_mod = @import("render.zig");- const a = std.testing.allocator;- var m: app.Model = undefined;- m.setup(a);- defer m.deinit();- try m.push(.assistant, "safe\x07text\rhere");- try std.testing.expectEqualStrings("safetexthere", m.history.items[0].text);- const frame = try render_mod.render(&m, a, 80, 24, 0);- defer a.free(frame);- try std.testing.expect(std.mem.indexOfScalar(u8, frame, 0x07) == null);- try std.testing.expect(std.mem.indexOfScalar(u8, frame, '\r') == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "safetexthere") != null);- const out = try paintToBuf(a, frame, 24, 80, "");- defer a.free(out);- // BEL must not be on the wire. CR is the painter's own row advance- // (`\r\n` on the full path) — that is cursor motion, not model text.- try std.testing.expect(std.mem.indexOfScalar(u8, out, 0x07) == null);- try std.testing.expect(std.mem.indexOf(u8, out, "safetexthere") != null);-}diff --git a/TUI/panel.zig b/TUI/panel.zigdeleted file mode 100644index 3fafd1dd..00000000--- a/TUI/panel.zig+++ /dev/null@@ -1,343 +0,0 @@-//! The bordered panel every overlay body sits inside.-//!-//! grok-build draws an overlay as a PANEL: a box whose TOP edge carries the-//! name of the thing and whose BOTTOM edge carries the keys, so chrome and-//! content never compete for a row. graff's overlays used to be bare text-//! floating on the pager — the same rows, but with no edge telling the eye-//! where the list stopped and the transcript resumed, and with the title-//! spending a whole content row to say one word.-//!-//! The panel reuses the composer's own walls (╭ ─ ╮ │ ╰ ╯) at the same inset,-//! so an open picker and the box under it read as one frame rather than two-//! unrelated widgets.-//!-//! LAW: every row is EXACTLY `width` columns, corner to corner. The painter-//! addresses screen row N as the Nth line of the composed frame (render.zig);-//! a row that measured wider would be chopped by the terminal — or, on a-//! terminal that ignores ?7l, wrapped — and every row below it would slide out-//! from under the row-to-line map that clicks, the sticky header and the-//! selection band all ride on.-//!-//! The two edge slots are not interchangeable. Anything the user must still be-//! able to read when the body OVERFLOWS the viewport goes in the top edge: a-//! panel taller than the screen has its bottom edge cut off, so a scroll hint-//! parked down there would be visible only when it was not needed.--const std = @import("std");--const theme_mod = @import("theme.zig");-const Theme = theme_mod.Theme;--/// Below this the box is more chrome than content — two walls, two corner-/// dashes and a title would leave nothing for the rows — so the body is-/// returned unframed instead of being squeezed.-pub const min_width: usize = 16;--pub const Spec = struct {- /// Named in the TOP edge.- title: []const u8 = "",- /// Right-hand slot of the TOP edge: a tally, a window position, a scroll- /// hint. Top, never bottom — see the module note.- note: []const u8 = "",- /// Left-hand slot of the BOTTOM edge: what the keys do.- footer: []const u8 = "",- /// Body rows, newline-separated, already carrying their own SGR.- body: []const u8 = "",-};--/// The two TOP-edge slots a picker fills in: what it is, and how much of it-/// the reader is looking at.-pub const Head = struct { title: []const u8, note: []const u8 };--/// The one row a WINDOWED list owes the reader: how much of it is off-screen.-/// Present for as long as the list overflows its window and never for a moment-/// less — a marker that came and went as the highlight moved would make every-/// row above it jump a line on an arrow key.-pub fn windowRow(a: std.mem.Allocator, th: Theme, off: usize, vis: usize, n: usize) ![]const u8 {- const below = n -| (off + vis);- const text = if (off > 0 and below > 0)- try std.fmt.allocPrint(a, " \u{2026} {d} above · {d} below", .{ off, below })- else if (off > 0)- try std.fmt.allocPrint(a, " \u{2026} {d} above", .{off})- else- try std.fmt.allocPrint(a, " \u{2026} {d} below", .{below});- return theme_mod.paint(a, th.muted, text);-}--/// `spec` as a box exactly `width` columns wide, newline-terminated.-pub fn wrap(a: std.mem.Allocator, th: Theme, width: usize, spec: Spec) ![]const u8 {- if (width < min_width) return a.dupe(u8, spec.body);- var out = std.array_list.Managed(u8).init(a);- // Bold accent title, muted note. grok-build's modal draws the same pair on- // its top border: the dashes take the border colour and the title itself- // stays bold, so the name reads as a label ON the frame rather than a row- // of content that happens to be first.- const title_sgr = try std.fmt.allocPrint(a, "{s}{s}", .{ theme_mod.bold, th.accent });- try out.appendSlice(try edge(a, th, width, "╭", "╮", spec.title, title_sgr, spec.note, th.muted));- try out.append('\n');- // A body may paint MANY rows with one SGR prefix — the help block is one- // string in one colour — and the painter repaints rows independently, so a- // continuation row that carries no SGR of its own renders in whatever the- // previous paint left behind. Same rule, and the same tracker, as the- // wrappers in theme.zig: remember the pen and re-open it on every row.- var active: theme_mod.Sgr = .{};- var sgr_buf: [theme_mod.Sgr.max_render]u8 = undefined;- var it = std.mem.splitScalar(u8, spec.body, '\n');- while (it.next()) |ln| {- // A body built with an append('\n') after every row ends in an empty- // segment. Framing it would open a blank row above the footer that no- // caller asked for.- if (ln.len == 0 and it.rest().len == 0) break;- try out.appendSlice(try row(a, th, width, ln, active.render(&sgr_buf)));- try out.append('\n');- noteAll(&active, ln);- }- try out.appendSlice(try edge(a, th, width, "╰", "╯", spec.footer, th.muted, "", th.muted));- try out.append('\n');- // Owned, not `items`: an ArrayList's buffer is longer than what it holds,- // and a caller freeing the returned slice must be handed an allocation- // whose length is the one the allocator recorded.- return out.toOwnedSlice();-}--/// One body row: a wall, the text clipped and padded to the inner width, a-/// wall. The pad is measured with visibleLen, so a wide glyph moves the right-/// wall by the two cells it actually draws and never by the bytes it occupies.-fn row(a: std.mem.Allocator, th: Theme, width: usize, text: []const u8, carry: []const u8) ![]const u8 {- const inner = width - 2;- const shown = theme_mod.takeCols(text, inner);- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(th.border);- try out.appendSlice("│");- try out.appendSlice(theme_mod.reset);- try out.appendSlice(carry);- try out.appendSlice(shown);- try out.appendSlice(theme_mod.reset);- const cols = theme_mod.visibleLen(shown);- if (cols < inner) try out.appendNTimes(' ', inner - cols);- try out.appendSlice(th.border);- try out.appendSlice("│");- try out.appendSlice(theme_mod.reset);- return out.items;-}--/// One horizontal edge, corner to corner, with the label and note inlaid.-///-/// Both slots degrade rather than overflow, in the order that keeps the panel-/// legible: the note goes first (it is a tally), then the label is clipped, and-/// a width with room for neither draws a plain rule. Nothing here may return a-/// row that is not exactly `width` columns.-fn edge(- a: std.mem.Allocator,- th: Theme,- width: usize,- left: []const u8,- right: []const u8,- label_in: []const u8,- label_sgr: []const u8,- note_in: []const u8,- note_sgr: []const u8,-) ![]const u8 {- const inner = width - 2;- var out = std.array_list.Managed(u8).init(a);- try out.appendSlice(th.border);- try out.appendSlice(left);- if (inner < 2) {- try dashes(&out, inner);- try out.appendSlice(right);- try out.appendSlice(theme_mod.reset);- return out.items;- }- // One dash hugs each corner, so a label never touches the corner glyph.- const budget = inner - 2;- var label = label_in;- var note = note_in;- var label_cols = slotCols(label);- var note_cols = slotCols(note);- if (label_cols + note_cols > budget) {- note = "";- note_cols = 0;- }- if (label_cols > budget) {- label = fitLabel(label, budget);- label_cols = slotCols(label);- }- const fill = budget - label_cols - note_cols;- try dashes(&out, 1);- if (label_cols > 0) try slot(&out, th, label, label_sgr);- try dashes(&out, fill);- if (note_cols > 0) try slot(&out, th, note, note_sgr);- try dashes(&out, 1);- try out.appendSlice(right);- try out.appendSlice(theme_mod.reset);- return out.items;-}--/// A label too wide for its edge, made to fit.-///-/// Hints are a "·"-joined list, ordered least-urgent first: "type to search ·-/// ↑↓ move · Enter pick · Esc". Clipping such a line from the RIGHT is exactly-/// backwards — a 40-column terminal kept "type to search · ↑↓ move · Enter pi"-/// and threw away the one key that closes the panel. Whole segments come off-/// the FRONT instead, so the last thing to survive is the last thing named.-fn fitLabel(label_in: []const u8, budget: usize) []const u8 {- var label = label_in;- while (slotCols(label) > budget) {- const cut = std.mem.indexOf(u8, label, " · ") orelse break;- label = label[cut + " · ".len ..];- }- // A single segment that still will not fit is clipped, as a title is.- return if (slotCols(label) > budget) theme_mod.takeCols(label, budget -| 2) else label;-}--/// Columns a slot spends: the text plus the space either side of it. An empty-/// slot spends nothing at all — not even its spaces.-fn slotCols(s: []const u8) usize {- return if (s.len == 0) 0 else theme_mod.visibleLen(s) + 2;-}--fn slot(out: *std.array_list.Managed(u8), th: Theme, text: []const u8, sgr: []const u8) !void {- try out.append(' ');- try out.appendSlice(sgr);- try out.appendSlice(text);- try out.appendSlice(theme_mod.reset);- try out.appendSlice(th.border);- try out.append(' ');-}--/// Fold every escape in `s` into the tracker — the whole line, not the clipped-/// part: a colour set past the right wall still governs the row after it.-fn noteAll(active: *theme_mod.Sgr, s: []const u8) void {- var i: usize = 0;- while (i < s.len) : (i += 1) {- if (s[i] != 0x1b) continue;- const end = theme_mod.skipEsc(s, i);- active.note(s[i..end]);- i = end - 1;- }-}--fn dashes(out: *std.array_list.Managed(u8), n: usize) !void {- var i: usize = 0;- while (i < n) : (i += 1) try out.appendSlice("─");-}--const testing = std.testing;--test "every row of a panel is exactly `width` columns" {- // The painter contract, at the one place a box can break it. Titles and- // notes long enough to need every degrade step are in the table on purpose.- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const specs = [_]Spec{- .{ .title = "Model", .note = "3/75", .footer = "↑↓ move · Enter pick · Esc", .body = "› one\n two\n" },- .{ .title = "", .note = "", .footer = "", .body = "bare\n" },- .{ .title = "a title far too long to fit any narrow terminal edge at all", .note = "999/999", .footer = "and a footer hint that is itself much too long to sit in the bottom rule", .body = "x\n" },- .{ .title = "Model › 日本語のフィルタ▋", .note = "0/75", .footer = "Esc", .body = " 🚀 wide glyph row that runs long enough to be clipped by the wall\n" },- .{ .title = "T", .note = "N", .footer = "F", .body = "" },- };- for (specs) |spec| {- for ([_]usize{ 16, 17, 20, 24, 40, 41, 60, 80, 120, 200 }) |w| {- const box = try wrap(a, th, w, spec);- var it = std.mem.splitScalar(u8, box, '\n');- var n: usize = 0;- while (it.next()) |ln| {- if (ln.len == 0 and it.rest().len == 0) break;- try testing.expectEqual(w, theme_mod.visibleLen(ln));- n += 1;- }- try testing.expect(n >= 2); // two edges, always- }- }-}--test "the title rides in the top edge and the footer in the bottom one" {- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const box = try wrap(arena.allocator(), theme_mod.of(.night), 60, .{- .title = "Commands",- .note = "4/12",- .footer = "Enter run · Esc",- .body = "› /new\n /home\n",- });- var it = std.mem.splitScalar(u8, box, '\n');- const top = it.next().?;- try testing.expect(std.mem.indexOf(u8, top, "╭") != null);- try testing.expect(std.mem.indexOf(u8, top, "Commands") != null);- try testing.expect(std.mem.indexOf(u8, top, "4/12") != null);- // The note sits to the RIGHT of the title, never before it.- try testing.expect(std.mem.indexOf(u8, top, "Commands").? < std.mem.indexOf(u8, top, "4/12").?);- const r1 = it.next().?;- try testing.expect(std.mem.indexOf(u8, r1, "│") != null);- try testing.expect(std.mem.indexOf(u8, r1, "/new") != null);- _ = it.next().?;- const bottom = it.next().?;- try testing.expect(std.mem.indexOf(u8, bottom, "╰") != null);- try testing.expect(std.mem.indexOf(u8, bottom, "Enter run · Esc") != null);- try testing.expect(std.mem.indexOf(u8, bottom, "╯") != null);- // Three body rows would mean the body's trailing newline opened a blank one.- try testing.expectEqual(@as(usize, 4), std.mem.count(u8, box, "\n"));-}--test "a narrow edge drops the note before it clips the title" {- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- // 24 columns: the title, its two spaces, the two corner dashes and the two- // corners come to exactly 22, so the tally has nowhere to go — and the- // title, which names the panel, survives whole.- const box = try wrap(a, th, 24, .{ .title = "Reasoning effort", .note = "6/6", .body = "x\n" });- const top = box[0..std.mem.indexOfScalar(u8, box, '\n').?];- try testing.expect(std.mem.indexOf(u8, top, "Reasoning effort") != null);- try testing.expect(std.mem.indexOf(u8, top, "6/6") == null);- try testing.expectEqual(@as(usize, 24), theme_mod.visibleLen(top));-}--test "a hint too wide for the edge loses its first segment, never its last" {- // "Esc" is what gets you out. Right-clipping dropped it and kept "type to- // sea"; segment-dropping keeps the keys and loses the prose.- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const a = arena.allocator();- const th = theme_mod.of(.night);- const long = "type to search · ↑↓ move · Enter pick · Esc";- for ([_]usize{ 24, 32, 40, 48 }) |w| {- const box = try wrap(a, th, w, .{ .title = "Model", .footer = long, .body = "x\n" });- var it = std.mem.splitScalar(u8, box, '\n');- var last: []const u8 = "";- while (it.next()) |ln| {- if (ln.len > 0) last = ln;- }- try testing.expect(std.mem.indexOf(u8, last, "Esc") != null);- try testing.expectEqual(w, theme_mod.visibleLen(last));- }- // Wide enough and the whole hint is there.- const wide = try wrap(a, th, 80, .{ .title = "Model", .footer = long, .body = "x\n" });- try testing.expect(std.mem.indexOf(u8, wide, "type to search") != null);-}--test "below min_width the body comes back unframed" {- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const got = try wrap(arena.allocator(), theme_mod.of(.night), 10, .{ .title = "X", .body = "row\n" });- try testing.expectEqualStrings("row\n", got);-}--test "panel colours come from the theme, never from a literal" {- // Every panel byte that is not content is a border token or a reset. A raw- // SGR literal here would survive a theme switch and paint grok-night walls- // on the day palette.- var arena = std.heap.ArenaAllocator.init(testing.allocator);- defer arena.deinit();- const a = arena.allocator();- for (theme_mod.all) |id| {- const th = theme_mod.of(id);- const box = try wrap(a, th, 40, .{ .title = "T", .note = "N", .footer = "F", .body = "r\n" });- try testing.expect(std.mem.indexOf(u8, box, th.border) != null);- try testing.expect(std.mem.indexOf(u8, box, th.accent) != null);- try testing.expect(std.mem.indexOf(u8, box, th.muted) != null);- }-}diff --git a/TUI/peer_cmd.zig b/TUI/peer_cmd.zigdeleted file mode 100644index 32eed0d3..00000000--- a/TUI/peer_cmd.zig+++ /dev/null@@ -1,30 +0,0 @@-//! TUI `/tell` and `/peek`: thin client of the engine mailbox.-//! Posting lives in `src/peer_channel.zig`; this file only routes the slash.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const Model = app.Model;--pub const tell_usage = "usage: /tell <session|all> <text> — all reaches every live session on this device, any folder";-pub const peek_usage = "usage: /peek <session> — what a live session is doing right now";-pub const offline_note = "peer talk needs a live session (offline)";--pub fn run(self: *Model, canon: []const u8, arg: []const u8) void {- if (engine.g_peer_fn) |f| {- var buf: [2048]u8 = undefined;- const line = if (arg.len == 0) canon else (std.fmt.bufPrint(&buf, "{s} {s}", .{ canon, arg }) catch canon);- if (f(engine.g_turn_ctx, self.alloc, line)) |text| {- defer self.alloc.free(text);- const trimmed = std.mem.trimEnd(u8, text, " \t\r\n");- if (trimmed.len > 0) self.push(.system, trimmed) catch {};- }- return;- }- if (arg.len == 0) {- self.push(.system, if (std.mem.eql(u8, canon, "/peek")) peek_usage else tell_usage) catch {};- } else {- self.push(.system, offline_note) catch {};- }-}diff --git a/TUI/peer_tests.zig b/TUI/peer_tests.zigdeleted file mode 100644index 4aeab5e3..00000000--- a/TUI/peer_tests.zig+++ /dev/null@@ -1,101 +0,0 @@-//! #563 Slice B: TUI `/tell` / `/peek` are catalogued and route through the-//! engine. Drive the pager with `sim.Term` — no PTY, no Ghostty window.--const std = @import("std");--const app = @import("app.zig");-const catalog = @import("catalog.zig");-const dispatch = @import("dispatch.zig");-const engine = @import("engine.zig");-const peer_cmd = @import("peer_cmd.zig");-const sim = @import("sim.zig");--test "catalog lists /tell and /peek" {- try std.testing.expect(catalog.lookup("/tell") != null);- try std.testing.expect(catalog.lookup("/peek") != null);- try std.testing.expectEqualStrings("/tell", catalog.lookup("/tell").?.name);- try std.testing.expectEqualStrings("/peek", catalog.lookup("/peek").?.name);-}--test "bare /tell and /peek print usage when the engine is offline" {- var m: app.Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = dispatch.applyLine(&m, "/tell");- try std.testing.expect(std.mem.indexOf(u8, m.history.items[m.history.items.len - 1].text, "usage: /tell") != null);- _ = dispatch.applyLine(&m, "/peek");- try std.testing.expect(std.mem.indexOf(u8, m.history.items[m.history.items.len - 1].text, "usage: /peek") != null);-}--test "/tell from the pager reaches the engine and shows the posted line" {- const Seen = struct {- var line: []u8 = &.{};- var room: std.ArrayList(u8) = .empty;- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, raw: []const u8) ?[]const u8 {- if (line.len > 0) gpa.free(line);- line = gpa.dupe(u8, raw) catch return null;- room.appendSlice(gpa, raw) catch {};- room.append(gpa, '\n') catch {};- return gpa.dupe(u8, "⇢ posted to the device-wide room") catch null;- }- };- Seen.line = &.{};- Seen.room = .empty;- engine.g_peer_fn = Seen.f;- defer {- engine.g_peer_fn = null;- if (Seen.line.len > 0) std.testing.allocator.free(Seen.line);- Seen.room.deinit(std.testing.allocator);- }-- var term: sim.Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("/tell all hold the tree");- _ = term.enter();-- try std.testing.expectEqualStrings("/tell all hold the tree", Seen.line);- try std.testing.expect(std.mem.indexOf(u8, Seen.room.items, "hold the tree") != null);- try std.testing.expect(term.model.history.items.len > 0);- const last = term.model.history.items[term.model.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, last, "posted to the device-wide room") != null);-- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "posted to the device-wide room") != null);-}--test "/peek from the pager reaches the engine" {- const Seen = struct {- var line: []u8 = &.{};- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, raw: []const u8) ?[]const u8 {- if (line.len > 0) gpa.free(line);- line = gpa.dupe(u8, raw) catch return null;- return gpa.dupe(u8, "⚡ other · pid 9 · goal: refactor") catch null;- }- };- Seen.line = &.{};- engine.g_peer_fn = Seen.f;- defer {- engine.g_peer_fn = null;- if (Seen.line.len > 0) std.testing.allocator.free(Seen.line);- }-- var term: sim.Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("/peek other");- _ = term.enter();- try std.testing.expectEqualStrings("/peek other", Seen.line);- const last = term.model.history.items[term.model.history.items.len - 1].text;- try std.testing.expect(std.mem.indexOf(u8, last, "goal: refactor") != null);-}--test "offline /tell with a payload explains instead of posting" {- engine.g_peer_fn = null;- var m: app.Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- _ = dispatch.applyLine(&m, "/tell all hi");- try std.testing.expectEqualStrings(peer_cmd.offline_note, m.history.items[m.history.items.len - 1].text);-}diff --git a/TUI/permission.zig b/TUI/permission.zigdeleted file mode 100644index 818957b2..00000000--- a/TUI/permission.zig+++ /dev/null@@ -1,127 +0,0 @@-//! Job-owned request/response mailbox. Payloads never borrow a turn arena.-const std = @import("std");-pub const Decision = enum { allow_once, deny };-pub const Request = struct {- id: u64,- bytes: [2048]u8 = undefined,- len: usize = 0,- pub fn description(self: *const Request) []const u8 {- return self.bytes[0..self.len];- }-};-pub const Mailbox = struct {- lock: std.atomic.Value(bool) = .init(false),- serial: u64 = 0,- pending: ?Request = null,- answer: ?Decision = null,- fn acquire(self: *Mailbox) void {- while (self.lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();- }- fn release(self: *Mailbox) void {- self.lock.store(false, .release);- }- pub fn begin(self: *Mailbox, description: []const u8) ?u64 {- self.acquire();- defer self.release();- if (self.pending != null or description.len > 2048) return null;- self.serial +%= 1;- var req: Request = .{ .id = self.serial };- req.len = @min(description.len, req.bytes.len);- while (req.len < description.len and req.len > 0 and description[req.len] & 0xc0 == 0x80) req.len -= 1;- for (description[0..req.len], 0..) |c, i| req.bytes[i] = if (c < 0x20 or c == 0x7f) ' ' else c;- self.pending = req;- self.answer = null;- return req.id;- }- pub fn peek(self: *Mailbox) ?Request {- self.acquire();- defer self.release();- if (self.answer != null) return null;- return self.pending;- }- pub fn respond(self: *Mailbox, id: u64, decision: Decision) bool {- self.acquire();- defer self.release();- const req = self.pending orelse return false;- if (req.id != id or self.answer != null) return false;- self.answer = decision;- return true;- }- pub fn poll(self: *Mailbox, id: u64) ?Decision {- self.acquire();- defer self.release();- const req = self.pending orelse return .deny;- if (req.id != id) return .deny;- return self.answer;- }- pub fn retire(self: *Mailbox, id: u64) void {- self.acquire();- defer self.release();- if (self.pending) |req| if (req.id == id) {- self.pending = null;- self.answer = null;- };- }-};--test "permission replies are once-only and stale request IDs cannot approve the next tool" {- var box: Mailbox = .{};- const first = box.begin("first") orelse unreachable;- try std.testing.expect(box.begin("overlap") == null);- try std.testing.expect(box.respond(first, .deny));- try std.testing.expect(!box.respond(first, .allow_once));- box.retire(first);- const second = box.begin("second") orelse unreachable;- try std.testing.expect(!box.respond(first, .allow_once));- box.retire(first);- try std.testing.expect(box.poll(second) == null);- try std.testing.expect(box.respond(second, .allow_once));- try std.testing.expectEqual(Decision.allow_once, box.poll(second).?);-}--test "permission simulator renders request and accepts only explicit unpasted decisions" {- const engine = @import("engine.zig");- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- var job: engine.Job = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- term.model.pending = &job;- defer term.model.pending = null;- const id = job.events.permission.begin("run: write a file") orelse unreachable;- const screen = try term.screen();- defer std.testing.allocator.free(screen);- try std.testing.expect(std.mem.indexOf(u8, screen, "Permission: run: write a file") != null);- _ = term.feed("\x1b[200~y\x1b[201~");- try std.testing.expect(job.events.permission.poll(id) == null);- _ = term.typeText("y");- try std.testing.expectEqual(Decision.allow_once, job.events.permission.poll(id).?);- job.events.permission.retire(id);- const denied = job.events.permission.begin("second") orelse unreachable;- _ = term.typeText("n");- try std.testing.expectEqual(Decision.deny, job.events.permission.poll(denied).?);-}--test "permission simulator Escape cancels and oversized descriptions fail closed" {- const engine = @import("engine.zig");- const Callback = struct {- var cancelled = false;- fn cancel(_: ?*anyopaque) void {- cancelled = true;- }- };- const previous = engine.g_cancel_fn;- defer engine.g_cancel_fn = previous;- engine.g_cancel_fn = Callback.cancel;- Callback.cancelled = false;- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- var job: engine.Job = .{ .gpa = std.testing.allocator, .history = &.{}, .params = .{}, .stream = .{}, .threaded = false };- term.model.pending = &job;- defer term.model.pending = null;- try std.testing.expect(job.events.permission.begin(&@as([2049]u8, @splat('x'))) == null);- const id = job.events.permission.begin("command") orelse unreachable;- _ = @import("keys.zig").handle(&term.model, .escape);- try std.testing.expect(Callback.cancelled);- try std.testing.expectEqual(Decision.deny, job.events.permission.poll(id).?);-}diff --git a/TUI/prompt_history.zig b/TUI/prompt_history.zigdeleted file mode 100644index 07de4e5e..00000000--- a/TUI/prompt_history.zig+++ /dev/null@@ -1,190 +0,0 @@-//! TUI prompt-history sidecar (#577). Recalling a line restores the image-//! paths that were attached when it was submitted; only a path that still-//! exists is put back on the composer. Split out of dispatch.zig (600-line-//! cap). Modeled on src/readline_history.zig.--const std = @import("std");--const app = @import("app.zig");-const image = @import("image.zig");-const Model = app.Model;--pub fn deinit(self: *Model) void {- for (self.prompt_hist_images.items) |paths| freePaths(self, paths);- self.prompt_hist_images.deinit();- clearDraft(self);-}--pub fn remember(self: *Model, line: []const u8) void {- const dup = self.alloc.dupe(u8, line) catch return;- self.prompt_hist.append(dup) catch {- self.alloc.free(dup);- return;- };- recordImages(self);- self.hist_idx = null;- clearDraft(self);- @import("owned_images.zig").collect(self);-}--pub fn recallPrev(self: *Model) void {- if (self.prompt_hist.items.len == 0) return;- if (self.hist_idx == null) snapshotDraft(self);- const next_i: usize = if (self.hist_idx) |i| (if (i == 0) 0 else i - 1) else self.prompt_hist.items.len - 1;- self.hist_idx = next_i;- apply(self, self.prompt_hist.items[next_i], imagesAt(self, next_i));-}--pub fn recallNext(self: *Model) void {- const i = self.hist_idx orelse return;- if (i + 1 >= self.prompt_hist.items.len) {- self.hist_idx = null;- restoreDraft(self);- return;- }- self.hist_idx = i + 1;- apply(self, self.prompt_hist.items[i + 1], imagesAt(self, i + 1));-}--fn recordImages(self: *Model) void {- while (self.prompt_hist_images.items.len + 1 < self.prompt_hist.items.len) {- self.prompt_hist_images.append(&.{}) catch return;- }- var paths = std.array_list.Managed([]const u8).init(self.alloc);- for (self.images.items) |p| {- const owned = self.alloc.dupe(u8, p) catch continue;- paths.append(owned) catch self.alloc.free(owned);- }- const slice = paths.toOwnedSlice() catch {- for (paths.items) |p| self.alloc.free(p);- paths.deinit();- self.prompt_hist_images.append(&.{}) catch {};- return;- };- self.prompt_hist_images.append(slice) catch {- freePaths(self, slice);- };-}--fn snapshotDraft(self: *Model) void {- clearDraft(self);- self.draft_input = self.input.snapshot() catch null;- if (self.images.items.len == 0) return;- var paths = std.array_list.Managed([]const u8).init(self.alloc);- for (self.images.items) |p| {- const owned = self.alloc.dupe(u8, p) catch continue;- paths.append(owned) catch self.alloc.free(owned);- }- self.draft_images = paths.toOwnedSlice() catch {- for (paths.items) |p| self.alloc.free(p);- paths.deinit();- return;- };-}--fn clearDraft(self: *Model) void {- if (self.draft_input) |state| {- self.input.freeSnapshot(state);- self.draft_input = null;- }- if (self.draft_images) |paths| {- freePaths(self, paths);- self.draft_images = null;- }-}--fn restoreDraft(self: *Model) void {- if (self.draft_input) |state| {- self.input.setState(state) catch {};- } else self.input.setValue("") catch {};- replaceImages(self, self.draft_images orelse &.{});-}--fn apply(self: *Model, text: []const u8, paths: []const []const u8) void {- self.input.setValue(text) catch {};- replaceImages(self, paths);-}--fn replaceImages(self: *Model, paths: []const []const u8) void {- for (self.images.items) |p| self.alloc.free(p);- self.images.clearRetainingCapacity();- for (paths) |p| {- if (!image.pathBacked(p)) continue;- const owned = self.alloc.dupe(u8, p) catch continue;- self.images.append(owned) catch self.alloc.free(owned);- }- @import("owned_images.zig").collect(self);-}--fn imagesAt(self: *const Model, idx: usize) []const []const u8 {- if (idx < self.prompt_hist_images.items.len) return self.prompt_hist_images.items[idx];- return &.{};-}--fn freePaths(self: *Model, paths: []const []const u8) void {- for (paths) |p| self.alloc.free(p);- if (paths.len > 0) self.alloc.free(paths);-}--fn writeTmp(tmp: anytype, name: []const u8, data: []const u8, buf: []u8) ![]const u8 {- const io = std.testing.io;- try tmp.dir.writeFile(io, .{ .sub_path = name, .data = data });- const n = try tmp.dir.realPath(io, buf);- if (n + 1 + name.len > buf.len) return error.NameTooLong;- buf[n] = '/';- @memcpy(buf[n + 1 ..][0..name.len], name);- return buf[0 .. n + 1 + name.len];-}--test "remember + recall restores backed image paths and drops missing ones" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var path_buf: [std.fs.max_path_bytes]u8 = undefined;- const live = try writeTmp(&tmp, "shot.png", "png", &path_buf);-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage(live);- m.attachImage("/no/such/image-577.png");- remember(&m, "what is this");- try std.testing.expectEqual(@as(usize, 1), m.prompt_hist.items.len);- try std.testing.expectEqual(@as(usize, 2), m.images.items.len);-- for (m.images.items) |p| m.alloc.free(p);- m.images.clearRetainingCapacity();- try std.testing.expectEqual(@as(usize, 0), m.images.items.len);-- recallPrev(&m);- try std.testing.expectEqualStrings("what is this", m.input.getValue());- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings(live, m.images.items[0]);-}--test "down past newest restores the draft and its attachments" {- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- var a_buf: [std.fs.max_path_bytes]u8 = undefined;- var b_buf: [std.fs.max_path_bytes]u8 = undefined;- const older = try writeTmp(&tmp, "a.png", "a", &a_buf);- const draft_path = try writeTmp(&tmp, "b.png", "b", &b_buf);-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.attachImage(older);- remember(&m, "older");- for (m.images.items) |p| m.alloc.free(p);- m.images.clearRetainingCapacity();-- m.attachImage(draft_path);- m.input.setValue("draft in progress") catch {};- recallPrev(&m);- try std.testing.expectEqualStrings("older", m.input.getValue());- try std.testing.expectEqualStrings(older, m.images.items[0]);-- recallNext(&m);- try std.testing.expectEqualStrings("draft in progress", m.input.getValue());- try std.testing.expectEqual(@as(usize, 1), m.images.items.len);- try std.testing.expectEqualStrings(draft_path, m.images.items[0]);-}diff --git a/TUI/render.zig b/TUI/render.zigdeleted file mode 100644index e9cf069f..00000000--- a/TUI/render.zig+++ /dev/null@@ -1,391 +0,0 @@-//! Compose one frame: top bar, welcome or scrollback, slash menu / overlay,-//! prompt box, status. Viewport math matches grok's "prompt pinned, history-//! scrolls".--const std = @import("std");--const anchor = @import("anchor.zig");-const app = @import("app.zig");-const chrome = @import("chrome.zig");-const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const hover = @import("hover.zig");-const inset = @import("inset.zig");-const layout_cache = @import("layout_cache.zig");-const scrollbar = @import("scrollbar.zig");-const scrollback = @import("scrollback.zig");-const scrollpaint = @import("scrollpaint.zig");-const selection = @import("selection.zig");-const theme_mod = @import("theme.zig");-const welcome = @import("welcome.zig");-const Model = app.Model;--pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize, now_ms: u64) ![]const u8 {- // A horizontal resize rewraps everything under the viewport, so the row- // count in `scroll` stops meaning what it meant. Take a LOGICAL anchor off- // the frame we last painted — read at the OLD width, before it is- // overwritten — and restore the viewport onto it below. Only the- // transcript is anchored this way: an overlay body scrolls too, but its- // rows are not history entries.- const rewrap: ?anchor.Anchor = if (width != self.last_term_width and- (self.overlay == .none or self.overlay == .image))- anchor.capture(self, inset.forTerm(self.last_term_width, self.compact_mode).inner)- else- null;- self.last_term_width = width;- self.last_term_height = height;- self.now_ms = now_ms;- // Where the scrollable band was last time, so the painter can be told the- // viewport SLID rather than left to conclude every row changed. Presentation- // state, and only ever a hint: paint.zig verifies it against the bytes.- const prev_band = self.band;- self.band = .{};- @import("turn.zig").drainEvents(self);-- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const a = arena_state.allocator();-- // grok-build outer_hpad (inset.zig): transcript / composer / footer wrap- // to `inner` and pick up a left gutter. Overlay and slash panels stay- // full-width so they still dock on the composer as a closed box.- const pads = inset.forTerm(width, self.compact_mode);- const inner = pads.inner;- const left = pads.left;-- // Nothing composed here may be wider than the screen. A row that is- // becomes a lie the painter has to clean up after: with autowrap off the- // terminal chops it, and on any terminal that does not honour ?7l it wraps- // and pushes every row below it down by one — which desyncs the row↔line- // map the composer's click math, the sticky header and the selection band- // all ride on. The chrome builders that take `width` clamp themselves; the- // overlay bodies and the image card historically did not.- const top = theme_mod.takeCols(try chrome.topBar(self, a, inner), inner);- const image_card = if (self.overlay == .image)- try theme_mod.wrapToWidth(a, try chrome.overlay(self, a, width), width)- else- "";- // The image overlay is a card ABOVE the composer, so `mid` stays the- // transcript; every other overlay replaces it with its own body.- const overlay_body = self.overlay != .none and self.overlay != .image;- // Anything in the transcript — including a live background op's pending- // row — outranks the welcome pane: keeping it up hid a running `!cmd`/- // @-list entirely and froze the paint loop (the welcome frame is static,- // so the hash-diff suppressed every paint).- const welcome_pane = self.screen == .welcome and self.history.items.len == 0 and self.pending == null;- const mid = if (overlay_body)- try theme_mod.wrapToWidth(a, try chrome.overlay(self, a, width), width)- else if (welcome_pane)- try welcome.render(self, a, inner)- else- "";- // The transcript is never composed whole: the layout cache holds its- // wrapped lines and the frame takes a SLICE of them (layout_cache.zig).- const cache: ?*layout_cache.Cache = if (overlay_body or welcome_pane) null else layout_cache.ensure(self, inner);- const slash = try chrome.slashMenu(self, a, width);- const permission = if (self.pending) |job| job.events.permission.peek() else null;- const prompt = if (permission) |req|- try theme_mod.wrapToWidth(a, try std.fmt.allocPrint(a, "Permission: {s}\n[y] allow once [n] deny [Esc] cancel", .{req.description()}), inner)- else- try chrome.promptBox(self, a, inner);- const status = try chrome.statusBar(self, a, inner);- // Overlay / slash panels dock on the composer — no gap, or they float.- const gap: usize = if (overlay_body or slash.len > 0) 0 else pads.vpad;-- var bottom = std.array_list.Managed(u8).init(a);- if (slash.len > 0) {- try bottom.appendSlice(slash);- if (slash[slash.len - 1] != '\n') try bottom.append('\n');- }- try inset.appendPadded(&bottom, prompt, left);- if (prompt.len == 0 or prompt[prompt.len - 1] != '\n') try bottom.append('\n');- try inset.appendPadded(&bottom, status, left);-- const top_lines = countLines(top);- // countLines counts a trailing '\n' as an extra line but the append below- // adds no newline of its own — the off-by-one shifted the whole frame up- // one row and broke composer clicks (prompt_origin pointed past the box).- const card_lines = if (image_card.len == 0) 0 else countLines(image_card) - @intFromBool(image_card[image_card.len - 1] == '\n');- // The bottom block owns the LAST rows of the screen, so when the chrome- // cannot all fit — a short terminal with the slash menu open — it is- // trimmed from the top, where the expendable rows (the menu, the paste- // hint) are. Untrimmed, the composed frame ran LONGER than the screen: the- // painter clipped it at the last row, so the composer and the status bar- // were simply never drawn, while prompt_origin went on claiming a row for- // a composer that was not on screen.- const room = if (height > top_lines + card_lines + gap + 1) height - top_lines - card_lines - gap - 1 else 1;- const bottom_block = lastLines(bottom.items, room);- const bottom_lines = countLines(bottom_block);- // The completion menu rides at the TOP of the bottom block, and a short- // terminal trims that block from the top — so what survives is what a- // click can land on (click.zig). Counted here, where both the untrimmed- // and the trimmed shapes are in hand.- self.slash_rows = if (slash.len == 0)- 0- else- (countLines(slash) - @intFromBool(slash[slash.len - 1] == '\n')) -| (countLines(bottom.items) - bottom_lines);- self.preview_rows = card_lines;- self.mid_origin = top_lines;- self.prompt_origin = if (height > bottom_lines) height - bottom_lines else 0;- const used = bottom_lines + top_lines + card_lines + gap;- const view_h: usize = if (height > used) height - used else 1;-- var mid_lines = std.array_list.Managed([]const u8).init(a);- if (cache == null) {- var it = std.mem.splitScalar(u8, mid, '\n');- while (it.next()) |ln| try mid_lines.append(ln);- if (mid_lines.items.len > 0 and mid_lines.items[mid_lines.items.len - 1].len == 0) _ = mid_lines.pop();- }-- var out = std.array_list.Managed(u8).init(a);- try inset.appendPadded(&out, top, left);- if (top.len > 0 and top[top.len - 1] != '\n') try out.append('\n');-- const n = if (cache) |c| c.total else mid_lines.items.len;- // Mid lines this frame, transcript or overlay body alike. A press below- // the last of them is on the backdrop, not on the panel (click.zig).- self.mid_total = n;- self.sticky_rows = 0;- if (n <= view_h) {- self.scroll = 0;- self.mid_skip = 0;- // An overlay panel DOCKS to the composer, the way the slash menu does- // and grok-build's minimal pickers do: the list rises out of the box- // you are typing in. Top-anchored it floated at the ceiling with a- // field of blank rows between the thing being chosen and the caret- // choosing it. The transcript keeps its own habit, top-down.- const above: usize = if (overlay_body) view_h - n else 0;- var lead = above;- while (lead > 0) : (lead -= 1) try out.append('\n');- for (try midSlice(a, cache, mid_lines.items, 0, n)) |ln| {- if (!overlay_body) try out.appendNTimes(' ', left);- try out.appendSlice(ln);- try out.append('\n');- }- var pad: usize = view_h - n - above;- while (pad > 0) : (pad -= 1) try out.append('\n');- self.mid_origin += above;- } else {- const max_scroll = n - view_h;- // An overlay body reads TOP-DOWN. The transcript is pinned to its tail- // because the newest line is the one you want; a shortcut sheet is a- // document, and opening one at its last row showed the tail of /help- // and nothing else. Its own cursor, so closing the overlay leaves the- // transcript's viewport where it was.- var start: usize = undefined;- if (overlay_body) {- if (self.overlay_scroll > max_scroll) self.overlay_scroll = max_scroll;- start = self.overlay_scroll;- } else {- if (self.follow) self.scroll = 0;- // Put the anchored logical line back on the top row. Saturating:- // when the rewrap pushed it past the last possible top line the- // viewport parks at the bottom, which still shows it.- if (rewrap) |anc| {- if (cache) |c| self.scroll = max_scroll -| anchor.rowAt(self, c, anc);- }- if (self.scroll > max_scroll) self.scroll = max_scroll;- start = max_scroll - self.scroll;- }- self.mid_skip = start;- // grok sticky header (minimal single slot): once the last user prompt- // scrolls past the viewport top, its first line stays pinned as row 0- // with a blank separator row under it. The two chrome rows OCCLUDE the- // two top content lines instead of shifting them, so the row↔line map- // for everything below is unchanged and the bottom line stays put.- var chrome_rows: usize = 0;- // Only the transcript gets a pinned prompt. On an overlay screen `mid`- // is the overlay's own body, and a long one (/help, /models) scrolls- // too — ungated, this pinned a user prompt over its first two rows.- if (!overlay_body and view_h >= 5) {- if (if (cache) |c| layout_cache.stickyUserAbove(c, start) else null) |utext| {- const th = self.theme();- var head = std.array_list.Managed(u8).init(a);- try head.appendSlice(th.accent);- try head.appendSlice(glyphs.prompt_mark ++ " ");- try head.appendSlice(th.text);- var one = utext;- if (std.mem.indexOfScalar(u8, utext, '\n')) |nl| one = utext[0..nl];- try head.appendSlice(one);- const cols = if (inner > 2) inner - 2 else 1;- try out.appendNTimes(' ', left);- try out.appendSlice(theme_mod.takeCols(head.items, cols));- try out.appendSlice(theme_mod.reset);- try out.append('\n');- try out.append('\n');- chrome_rows = 2;- self.sticky_rows = 2;- }- }- for (try midSlice(a, cache, mid_lines.items, start + chrome_rows, view_h - chrome_rows)) |ln| {- if (!overlay_body) try out.appendNTimes(' ', left);- try out.appendSlice(ln);- try out.append('\n');- }- // The band is the part of the frame a wheel event MOVES: content rows- // only. The sticky header occludes the top of the viewport, so it is- // chrome that happens to sit inside it, and the composer, status bar- // and image card are below the end.- self.band = .{- .live = true,- .top = self.mid_origin + chrome_rows,- .len = view_h - chrome_rows,- .off = start + chrome_rows,- .total = n,- };- }- var mid_gap = gap;- while (mid_gap > 0) : (mid_gap -= 1) try out.append('\n');- if (image_card.len > 0) {- try out.appendSlice(image_card);- if (image_card[image_card.len - 1] != '\n') try out.append('\n');- }- try out.appendSlice(bottom_block);- // Hover, selection and the scroll gutter are all post-passes over the- // finished frame: the row builders stay unaware of all three, and each- // lands on screen rows exactly as the mouse reported them (#529). Hover- // runs FIRST so a drag band painted over the same row wins — a selection- // CLAIMS a region, a hover tint only announces one.- const hovered = try hover.paint(self, a, out.items, width);- const banded = try selection.paint(self, a, hovered, width);- // The scroll gutter goes LAST, after the capture: the thumb is chrome the- // selection must never copy, and it hides for the duration of a drag- // anyway (scrollbar.zig owns both halves of that rule).- const had_gutter = self.gutter_on;- const painted = try scrollbar.paint(self, a, banded, width);- // The hint describes the FINISHED frames, so it is taken after every- // post-pass: the gutter reshapes every band row, and whether the painter- // may scroll them depends on the two frames having the same shape.- self.paint_hint = scrollHint(self, prev_band, had_gutter and self.gutter_on);- return gpa.dupe(u8, painted);-}--/// `count` mid rows starting at `from`, taken from the layout cache when the-/// mid IS the transcript and from the composed overlay/welcome lines otherwise.-/// The cached path never materialises the rows outside the viewport, which is-/// the whole point: a wheel tick copies a screenful, not a transcript.-fn midSlice(a: std.mem.Allocator, cache: ?*layout_cache.Cache, lines: [][]const u8, from: usize, count: usize) ![]const []const u8 {- if (cache) |c| return layout_cache.window(c, a, from, count);- const end = @min(lines.len, from + count);- return lines[@min(from, end)..end];-}--/// The delta the scrollable band moved by between the last frame and this one,-/// when that is the ONLY thing that happened to it — the painter's scroll fast-/// path. Null is always safe: it just means the ordinary row diff.-fn scrollHint(self: *const Model, prev: app.Band, gutter: bool) ?scrollpaint.Hint {- const cur = self.band;- if (!cur.live or !prev.live) return null;- // Geometry moved, so screen row N is not the same slot it was: a resize, an- // image card appearing, the sticky header engaging, an overlay opening.- if (cur.top != prev.top or cur.len != prev.len) return null;- if (cur.off == prev.off) return null;- // The drag-selection band is anchored to SCREEN rows (#529), so its- // inverse video does not travel with the content a hardware scroll moves.- // The wheel drops the band for exactly this reason; keyboard scrolling- // keeps it, and that case has to keep repainting.- if (self.sel.active or self.sel.pressed) return null;- const d = @as(isize, @intCast(cur.off)) - @as(isize, @intCast(prev.off));- if (@abs(d) >= cur.len) return null;- return .{ .top = cur.top, .len = cur.len, .delta = d, .gutter = gutter };-}--fn countLines(s: []const u8) usize {- if (s.len == 0) return 0;- return std.mem.count(u8, s, "\n") + 1;-}--/// The last `n` lines of `s`, whole. Trimming a block that has to sit on the-/// screen's last rows can only ever come off the top.-fn lastLines(s: []const u8, n: usize) []const u8 {- if (n == 0) return "";- var have = countLines(s);- var i: usize = 0;- while (have > n) : (have -= 1) {- i = (std.mem.indexOfScalarPos(u8, s, i, '\n') orelse return s[i..]) + 1;- }- return s[i..];-}--test "lastLines keeps whole lines off the bottom" {- try std.testing.expectEqualStrings("c", lastLines("a\nb\nc", 1));- try std.testing.expectEqualStrings("b\nc", lastLines("a\nb\nc", 2));- try std.testing.expectEqualStrings("a\nb\nc", lastLines("a\nb\nc", 9));- try std.testing.expectEqualStrings("", lastLines("a\nb", 0));-}--test "a frame is exactly `height` rows of at most `width` columns" {- // The painter addresses screen row N as the Nth line of this string, and- // nothing else ever tells it where a row is. Every off-by-one in this- // file — the trailing-newline overcount that once shifted the whole frame- // up a row and broke composer clicks — shows up here first, and the- // occluding chrome rows (sticky header) and the image card are exactly the- // regions that write OUTSIDE the plain mid-lines flow.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- // Model-owned: deinit frees it.- m.session_name = try std.testing.allocator.dupe(u8, "a session name for the top bar");- for ([_][2]usize{ .{ 40, 12 }, .{ 80, 24 }, .{ 100, 30 }, .{ 132, 60 }, .{ 200, 40 } }) |wh| {- const w = wh[0];- const h = wh[1];- // Welcome, then a short transcript, then one long enough to scroll (so- // the sticky header pins two chrome rows), then the same with the- // image card above the composer, then an overlay body.- for (0..7) |stage| {- switch (stage) {- 1 => {- try m.push(.user, "how do I frobnicate the widget?");- try m.push(.assistant, "like this");- },- 2 => for (0..60) |_| try m.push(.assistant, "filler prose that fills the scrollback with wrapped content"),- 3 => {- m.preview_path = "/tmp/shot.png";- m.preview_n = 1;- m.openOverlay(.image);- },- 4 => {- m.closeOverlay();- m.openOverlay(.help);- },- 5 => {- m.closeOverlay();- if (m.goal) |g| std.testing.allocator.free(g);- m.goal = try std.testing.allocator.dupe(u8, "a standing goal long enough to overrun a narrow top bar");- },- 6 => {- m.focus = .prompt;- try m.input.setValue("/");- },- else => {},- }- const frame = try render(&m, std.testing.allocator, w, h, 0);- defer std.testing.allocator.free(frame);- try std.testing.expectEqual(h, countLines(frame));- var it = std.mem.splitScalar(u8, frame, '\n');- var rown: usize = 0;- while (it.next()) |ln| : (rown += 1) {- if (theme_mod.visibleLen(ln) > w) {- const dump = @import("dump.zig");- const vis = try dump.visible(std.testing.allocator, ln);- defer std.testing.allocator.free(vis);- std.debug.print("w={d} h={d} stage={d} row={d} cols={d}: {s}\n", .{ w, h, stage, rown, theme_mod.visibleLen(ln), vis });- }- try std.testing.expect(theme_mod.visibleLen(ln) <= w);- }- }- m.closeOverlay();- }-}--test "countLines" {- try std.testing.expectEqual(@as(usize, 0), countLines(""));- try std.testing.expectEqual(@as(usize, 1), countLines("hi"));- try std.testing.expectEqual(@as(usize, 3), countLines("a\nb\nc"));-}--test {- // The frame-level tests live next door so this file stays under the- // ceiling. Without this reference they compile for nobody and never run.- _ = @import("render_tests.zig");-}diff --git a/TUI/render_tests.zig b/TUI/render_tests.zigdeleted file mode 100644index 95585871..00000000--- a/TUI/render_tests.zig+++ /dev/null@@ -1,271 +0,0 @@-//! Frame-level tests for render.zig.-//!-//! Split out of render.zig to keep it under the line ceiling. These drive the-//! PUBLIC `render` entry point and read the composed frame back, so they live-//! just as well next door; the two tests that reach for render.zig's private-//! line helpers stayed behind with them.--const std = @import("std");--const app = @import("app.zig");-const chrome = @import("chrome.zig");-const dump_mod = @import("dump.zig");-const engine = @import("engine.zig");-const scrollback = @import("scrollback.zig");-const selection = @import("selection.zig");-const welcome = @import("welcome.zig");-const Model = app.Model;--const render = @import("render.zig").render;--test "welcome frame has chrome, prompt, and no offline stub" {- engine.g_model_name = "grok-4";- engine.g_cwd = "/tmp/proj";- defer {- engine.g_model_name = "";- engine.g_cwd = ".";- }- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- try std.testing.expect(std.mem.indexOf(u8, frame, "grok-4") != null);- try std.testing.expect(std.mem.indexOf(u8, frame, "╭") != null);- try std.testing.expect(std.mem.indexOf(u8, frame, "›") != null);- try std.testing.expect(std.mem.indexOf(u8, frame, "offline") == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "Fullscreen") == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "click") == null);- // Boot receipts (plugins:/mcp:/companion:) print before alt-screen.- try std.testing.expect(std.mem.indexOf(u8, frame, "plugins:") == null);- try std.testing.expect(std.mem.indexOf(u8, frame, "companion:") == null);- if (std.c.getenv("GRAFF_DUMP_WELCOME")) |path_z| {- const vis = try dump_mod.visible(std.testing.allocator, frame);- defer std.testing.allocator.free(vis);- const io = std.Io.Threaded.global_single_threaded.io();- std.Io.Dir.cwd().writeFile(io, .{ .sub_path = std.mem.span(path_z), .data = vis }) catch {};- }-}--test "click on a painted fold header expands the tools" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "Hey. I am in /Users/blackfloofie/codegraff on wip/shared-checkout-2026-08-14 and holding a long worktree path so this wraps");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- var row: usize = 0;- var hit: ?usize = null;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (row += 1) {- if (std.mem.indexOf(u8, ln, "Ran bash") != null) {- hit = row;- break;- }- }- try std.testing.expect(hit != null);- try std.testing.expect(m.history.items[1].folded);- _ = @import("keys.zig").handle(&m, .{ .mouse = .{ .btn = 0, .x = 4, .y = @intCast(hit.? + 1), .down = true } });- try std.testing.expect(!m.history.items[1].folded);-}--test "image overlay keeps the conversation and paints the Grok card" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "@[/tmp/shot.png] look");- try m.push(.assistant, "got it");- m.preview_path = "/tmp/shot.png";- m.preview_n = 1;- m.openOverlay(.image);- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- try std.testing.expect(std.mem.indexOf(u8, frame, "Image #1") != null);- try std.testing.expect(std.mem.indexOf(u8, frame, "got it") != null);- try std.testing.expect(std.mem.indexOf(u8, frame, "y copy path") != null);-}--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();- try m.push(.user, "@[/tmp/shot.png] look");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- 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, "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);- const lay = try dump_mod.layout(std.testing.allocator, &m);- defer std.testing.allocator.free(lay);- try std.testing.expect(std.mem.indexOf(u8, lay, "overlay none") != null);- try std.testing.expect(std.mem.indexOf(u8, lay, "prompt-origin") != null);- try std.testing.expect(std.mem.indexOf(u8, lay, "mid-origin") != null);- try std.testing.expect(std.mem.indexOf(u8, lay, "images") != null);-- m.openOverlay(.debug);- // The overlay body is built from many small pieces now that it is framed- // (panel.zig), so it wants the arena every other chrome builder gets.- var oarena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer oarena.deinit();- const dbg = try chrome.overlay(&m, oarena.allocator(), 80);- const lay_dbg = try dump_mod.layout(std.testing.allocator, &m);- defer std.testing.allocator.free(lay_dbg);- try std.testing.expect(std.mem.indexOf(u8, lay_dbg, "overlay debug") != null);- try std.testing.expect(std.mem.indexOf(u8, dbg, "Observability") != null);- if (std.c.getenv("GRAFF_TUI_DUMP")) |dir_z| {- const dir = std.mem.span(dir_z);- const io = std.Io.Threaded.global_single_threaded.io();- var fb: [512]u8 = undefined;- var lb: [512]u8 = undefined;- const fp = std.fmt.bufPrint(&fb, "{s}/tui-frame.txt", .{dir}) catch return error.PathTooLong;- const lp = std.fmt.bufPrint(&lb, "{s}/tui-layout.txt", .{dir}) catch return error.PathTooLong;- std.Io.Dir.cwd().writeFile(io, .{ .sub_path = fp, .data = vis }) catch {};- const both = try std.fmt.allocPrint(std.testing.allocator, "--- overlay none ---\n{s}\n--- overlay debug ---\n{s}\n--- debug overlay body ---\n{s}", .{ lay, lay_dbg, dbg });- defer std.testing.allocator.free(both);- std.Io.Dir.cwd().writeFile(io, .{ .sub_path = lp, .data = both }) catch {};- }-}--test "debug overlay keeps the observability HUD and adds layout" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "@[/tmp/shot.png] look");- try m.pushTool(.{ .name = "bash" });- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- m.openOverlay(.debug);- var oarena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer oarena.deinit();- const text = try chrome.overlay(&m, oarena.allocator(), 80);- try std.testing.expect(std.mem.indexOf(u8, text, "Observability") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "offline") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "focus") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "mid-origin") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "images") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "pending") != null);-}--test "a wheel notch reports a scroll hint; anything else about the frame refuses one" {- const keys = @import("keys.zig");- const a = std.testing.allocator;- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try m.push(.user, "how do I frobnicate the widget?");- var i: usize = 0;- while (i < 60) : (i += 1)- try m.pushFmt(.assistant, "explanation line {d}, long enough to fill the transcript", .{i});-- // A first frame has nothing to compare against, and an idle one has not moved.- for (0..2) |_| {- a.free(try render(&m, a, 80, 24, 0));- try std.testing.expect(m.paint_hint == null);- }-- // One wheel notch. The band slides by exactly the three content lines- // keys.zig moved the viewport, and keeps its geometry — which is the whole- // claim paint.zig acts on. `top` clears the sticky header: those rows are- // chrome occluding the viewport, and a hardware scroll must not move them.- _ = keys.handle(&m, .{ .mouse = .{ .btn = 64, .x = 1, .y = 5, .down = true } });- a.free(try render(&m, a, 80, 24, 0));- const h = m.paint_hint orelse return error.NoScrollHint;- try std.testing.expectEqual(@as(isize, -3), h.delta);- try std.testing.expectEqual(m.mid_origin + m.sticky_rows, h.top);- try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);- try std.testing.expect(h.len >= 2 and h.top + h.len <= 24);-- // A resize on the same frame as a scroll: every row below rewraps, so the- // band is not the same band and nothing about it may be claimed to slide.- keys.scrollBy(&m, 3);- a.free(try render(&m, a, 79, 24, 0));- try std.testing.expect(m.paint_hint == null);-- // A live drag-selection band is anchored to SCREEN rows, so its inverse- // video does not travel with the content a hardware scroll would move.- a.free(try render(&m, a, 79, 24, 0));- m.sel.active = true;- keys.scrollBy(&m, 3);- a.free(try render(&m, a, 79, 24, 0));- try std.testing.expect(m.paint_hint == null);- m.sel.active = false;-- // Scrolling all the way to the top clamps: the viewport stops moving, and- // a band that did not move is not a scroll.- m.scroll = 1_000_000;- a.free(try render(&m, a, 79, 24, 0));- a.free(try render(&m, a, 79, 24, 0));- try std.testing.expect(m.paint_hint == null);-- // An overlay replaces the whole viewport — no band at all, so no hint even- // though the frame changed completely.- m.openOverlay(.help);- a.free(try render(&m, a, 79, 24, 0));- try std.testing.expect(m.paint_hint == null);-}--test "the sticky header never pins a prompt over an overlay" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "SECRETPROMPT about widgets");- var i: usize = 0;- while (i < 40) : (i += 1) try m.push(.assistant, "filler assistant prose to make the transcript long");- // It engages on the transcript...- const transcript = try render(&m, std.testing.allocator, 80, 24, 0);- std.testing.allocator.free(transcript);- try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);- // ...and stands down once `mid` is an overlay body long enough to scroll:- // ungated, the pin ate the overlay's own first two rows.- m.openOverlay(.help);- const overlay_frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(overlay_frame);- try std.testing.expectEqual(@as(usize, 0), m.sticky_rows);- try std.testing.expect(std.mem.indexOf(u8, overlay_frame, "SECRETPROMPT") == null);- // The image overlay is a card, not a body: the transcript keeps its pin.- m.closeOverlay();- m.preview_path = "/tmp/shot.png";- m.preview_n = 1;- m.openOverlay(.image);- const card_frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(card_frame);- try std.testing.expectEqual(@as(usize, 2), m.sticky_rows);-}--test "sticky header pins the last scrolled-past user prompt with a blank separator" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "how do I frobnicate the widget?");- var i: usize = 0;- while (i < 40) : (i += 1) try m.push(.assistant, "a long explanation line that fills the scrollback with content");- // follow-mode bottom: prompt is far above, so it pins.- const frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(frame);- var it = std.mem.splitScalar(u8, frame, '\n');- var row: usize = 0;- var pin_row: ?usize = null;- while (it.next()) |ln| : (row += 1) {- if (std.mem.indexOf(u8, ln, "\u{276F} ") != null and std.mem.indexOf(u8, ln, "frobnicate") != null) {- pin_row = row;- break;- }- }- try std.testing.expect(pin_row != null);- // scrolled fully back to the top, the prompt is inline: no pin.- m.follow = false;- m.scroll = 100000;- const top_frame = try render(&m, std.testing.allocator, 80, 24, 0);- defer std.testing.allocator.free(top_frame);- try std.testing.expect(std.mem.indexOf(u8, top_frame, "\u{276F} ") == null);-}diff --git a/TUI/restore.zig b/TUI/restore.zigdeleted file mode 100644index bf6a9153..00000000--- a/TUI/restore.zig+++ /dev/null@@ -1,389 +0,0 @@-//! Terminal-state restoration that must survive abnormal exits.-//! The kitty keyboard pop and alt-screen exit live here so SIGTERM/SIGHUP-//! (or an abort, a crash, or a job-control stop) cannot strand the shell in-//! raw fullscreen mode with the kitty protocol still pushed, the cursor-//! hidden, and mouse tracking on.--const std = @import("std");-const builtin = @import("builtin");-const tty = @import("tty.zig");--/// Inverse of run.zig's enable string: synchronized update closed, scroll-/// margins dropped, modifyOtherKeys off, kitty pop, autowrap on, mouse off-/// (1006/1003/1000), bracketed paste off, cursor visible. The alt-screen exit-/// stays last so everything lands on the primary screen.-///-/// The first two are not inverses of anything in the enable string — they undo-/// state a paint sets and clears WITHIN itself (scrollpaint.zig brackets a-/// DECSTBM region exactly as run.zig brackets ?2026). A crash lands between the-/// two halves often enough to matter, and margins left set turn every later-/// newline in the user's shell into a scroll inside a window that is gone.-pub const seq = "\x1b[?2026l\x1b[r\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l";--/// Every signal that ends the process with the terminal still ours. The first-/// `first_fault` are the polite ones (a human or an init system asking us to-/// go); the rest are crashes. SEGV/BUS/ILL/FPE/TRAP are the ones that matter-/// in a shipped build: ReleaseFast has runtime_safety off, so std's own-/// segfault handler is never installed and nothing else would put the shell-/// back (#535, #547).-pub const fatal = [_]std.posix.SIG{ .TERM, .HUP, .INT, .QUIT, .ABRT, .SEGV, .BUS, .ILL, .FPE, .TRAP };--/// Index in `fatal` where the crash signals start. Those hand the signal back-/// to whoever held it before us — in Debug/ReleaseSafe that is Zig's stack-/// trace dumper, and blind-defaulting to SIG_DFL would delete dev diagnostics.-const first_fault = 4;--/// Job control. SIGTSTP's default action stops the process, which with the-/// alt screen up and termios raw hands the user a dead-looking shell (#549).-pub const stop_signals = [_]std.posix.SIG{.TSTP};--/// Window-size changes. SIGWINCH's default disposition is "ignore", so without-/// a handler the loop only ever learns about a resize by comparing the-/// dimensions it read on two successive iterations — which misses a resize-/// that lands between the size read and the paint, and misses one that ends on-/// the size it started from even though the terminal reflowed the screen in-/// between. Both leave the diff painter's baseline describing a screen that no-/// longer exists, and no frame byte changes, so nothing would ever repair it.-pub const size_signals = [_]std.posix.SIG{.WINCH};--var armed = std.atomic.Value(bool).init(false);-var saved: tty.RawState = undefined;-var prev_fatal: [fatal.len]std.posix.Sigaction = undefined;-var prev_saved = false;-/// run.zig's fullscreen enable string, so the SIGTSTP handler can put the-/// screen back after the shell hands the terminal over on SIGCONT.-var enable: []const u8 = "";-/// Set by the stop handler once the process is continued: the paint diff-/// baseline is stale after a suspend, so run.zig must repaint in full.-var resumed = std.atomic.Value(bool).init(false);-/// Set by the window-size handler: run.zig turns it into a forced full-/// repaint, so a reflowed or cleared screen is never left half-drawn.-var resized = std.atomic.Value(bool).init(false);--/// Remember the pre-raw termios and hook fatal signals. Test builds skip the-/// signal hooks so the test runner's dispositions stay untouched.-pub fn arm(orig: tty.RawState, enable_seq: []const u8) void {- saved = orig;- enable = enable_seq;- armed.store(true, .release);- if (builtin.os.tag == .windows or builtin.is_test) return;- installFatalHandlers();- installStopHandlers();- installSizeHandlers();-}--pub fn disarm() void {- armed.store(false, .release);-}--/// True while a fatal-signal restore is hooked — `run` uses this so an-/// early `claimScreen` (alt-screen before keys/MCP/prompt) is not armed-/// twice, which would save already-raw termios and strand the shell.-pub fn isArmed() bool {- return armed.load(.acquire);-}--/// Early alt-screen claim so leftover boot happens *inside* the pager.-/// `run` takes ownership via `takeClaim`; `releaseIfOwned` (shutdown-/// teardown + fatal signals already hooked by `arm`) restores if we never-/// get there. No libc `atexit`: Zig exits via syscall and skips C exits.-var claim_owned = std.atomic.Value(bool).init(false);-var claim_raw: tty.RawState = undefined;--pub fn claimScreen(enable_seq: []const u8) bool {- if (builtin.is_test) return false;- if (claim_owned.load(.acquire) or armed.load(.acquire)) return true;- const raw = tty.enterRaw() orelse return false;- claim_raw = raw;- arm(raw, enable_seq);- if (builtin.os.tag != .windows) {- // Alt-screen only. Kitty/mouse/paste are a stack — run() writes- // the full enable_seq once when the loop actually starts.- const first = "\x1b[?1049h\x1b[?25l\x1b[H\x1b[2J";- _ = std.posix.system.write(std.posix.STDOUT_FILENO, first.ptr, first.len);- }- muteStderr();- claim_owned.store(true, .release);- return true;-}--/// Hand the claimed raw state to `run`. After this, `releaseIfOwned` no-ops-/// — `run` owns restore. Null when nothing was claimed (off-TTY, or `run` first).-pub fn takeClaim() ?tty.RawState {- if (!claim_owned.swap(false, .acq_rel)) return null;- return claim_raw;-}--/// Teardown / error-return path after an early claim that never reached `run`.-/// First call wins; later stamps are a single atomic load.-pub fn releaseIfOwned() void {- if (!claim_owned.load(.acquire)) return;- emergency();- claim_owned.store(false, .release);-}--/// True exactly once per resume from SIGTSTP — run.zig drops its diff-/// baseline so the first frame after `fg` is a full repaint.-pub fn takeResumed() bool {- return resumed.swap(false, .acq_rel);-}--/// True once per window-size change since the last call.-pub fn takeResized() bool {- return resized.swap(false, .acq_rel);-}--fn installSizeHandlers() void {- if (builtin.os.tag == .windows) return;- var sa = std.posix.Sigaction{- .handler = .{ .handler = onWinch },- .mask = std.posix.sigemptyset(),- // std.posix.poll/read both retry on EINTR, so an arriving SIGWINCH- // costs the loop nothing beyond one restarted wait — the latch is- // read on the next pass, at most one idle timeout later.- .flags = std.posix.SA.ONSTACK,- };- for (size_signals) |sig| std.posix.sigaction(sig, &sa, null);-}--/// Async-signal-safe: one relaxed store, nothing else.-fn onWinch(_: std.posix.SIG) callconv(.c) void {- resized.store(true, .release);-}--fn installFatalHandlers() void {- if (builtin.os.tag == .windows) return;- var sa = std.posix.Sigaction{- .handler = .{ .handler = onFatal },- .mask = std.posix.sigemptyset(),- // A stack-overflow SEGV has no room left on the faulting stack: without- // ONSTACK the handler re-faults and the terminal is stranded anyway.- .flags = std.posix.SA.ONSTACK,- };- for (fatal, 0..) |sig, i| std.posix.sigaction(sig, &sa, &prev_fatal[i]);- prev_saved = true;-}--fn installStopHandlers() void {- if (builtin.os.tag == .windows) return;- var sa = std.posix.Sigaction{- .handler = .{ .handler = onStop },- .mask = std.posix.sigemptyset(),- .flags = std.posix.SA.ONSTACK,- };- for (stop_signals) |sig| std.posix.sigaction(sig, &sa, null);-}--/// While the fullscreen TUI owns the screen, NOTHING may write to the real-/// terminal around the frame painter — but std.debug.print (subagent status-/// cards, worker lines, debug notices, any pool thread) goes straight to fd 2-/// and scrolls the alt screen out from under the diff painter: stale rows-/// "bleed through". So the TUI parks fd 2 on .graff/tui-stderr.log for its-/// whole lifetime and every exit path — quit, crash, suspend — puts it back-/// so panic traces and shell prompts land on the real terminal again.-/// (Child processes spawned BEFORE the mute keep their inherited fd 2; MCP-/// servers boot pre-TUI and are the remaining, far rarer leak.)-var real_stderr: std.posix.fd_t = -1;--pub fn muteStderr() void {- if (builtin.os.tag == .windows or builtin.is_test) return;- if (real_stderr != -1) return;- _ = std.posix.system.mkdir(".graff", 0o755);- const log = std.posix.openat(- std.posix.AT.FDCWD,- ".graff/tui-stderr.log",- .{ .ACCMODE = .WRONLY, .CREAT = true, .APPEND = true },- 0o644,- ) catch return;- // The raw syscall layer returns usize on Linux and c_int through libc,- // so success is judged by errno, not by the sign of the return.- const saved_rc = std.posix.system.dup(std.posix.STDERR_FILENO);- if (std.posix.errno(saved_rc) != .SUCCESS) {- _ = std.posix.system.close(log);- return;- }- real_stderr = @intCast(saved_rc);- const swap_rc = std.posix.system.dup2(log, std.posix.STDERR_FILENO);- if (std.posix.errno(swap_rc) != .SUCCESS) {- _ = std.posix.system.close(real_stderr);- real_stderr = -1;- }- _ = std.posix.system.close(log);-}--/// Async-signal-safe (dup2/close only), so the crash and stop paths may call it.-pub fn unmuteStderr() void {- if (builtin.os.tag == .windows) return;- if (real_stderr == -1) return;- _ = std.posix.system.dup2(real_stderr, std.posix.STDERR_FILENO);- _ = std.posix.system.close(real_stderr);- real_stderr = -1;-}--/// Async-signal-safe: raw write + tcsetattr + the stderr un-park, nothing else.-pub fn emergency() void {- if (builtin.os.tag == .windows) return;- unmuteStderr(); // diagnostics after this point must reach the real terminal- if (!armed.swap(false, .acq_rel)) return;- _ = std.posix.system.write(std.posix.STDOUT_FILENO, seq.ptr, seq.len);- std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, saved) catch {};-}--/// Root-level panic hook: `pub const panic = restore.Panic;`. The terminal is-/// put back BEFORE std prints the message and the stack trace, so a crashed-/// session shows its diagnostic on the primary screen instead of having it-/// written into an alt screen the restore sequence then discards (#535).-pub fn onPanic(msg: []const u8, ra: ?usize) noreturn {- emergency();- std.debug.defaultPanic(msg, ra);-}--pub const Panic = std.debug.FullPanic(onPanic);--fn onFatal(sig: std.posix.SIG) callconv(.c) void {- emergency();- var dfl = std.posix.Sigaction{- .handler = .{ .handler = std.posix.SIG.DFL },- .mask = std.posix.sigemptyset(),- .flags = 0,- };- for (fatal, 0..) |s, i| {- if (s != sig) continue;- if (i >= first_fault and prev_saved) {- std.posix.sigaction(sig, &prev_fatal[i], null);- } else {- std.posix.sigaction(sig, &dfl, null);- }- std.posix.raise(sig) catch {};- return;- }- std.posix.sigaction(sig, &dfl, null);- std.posix.raise(sig) catch {};-}--/// Restore the shell, stop for real, then take the terminal back on resume.-/// `raise` returns once SIGCONT arrives, so the whole suspend/continue cycle-/// is this one handler — no SIGCONT hook needed.-fn onStop(sig: std.posix.SIG) callconv(.c) void {- // Only a suspend that interrupted the fullscreen TUI gets the screen back:- // the handlers outlive run(), and re-entering raw mode after the TUI is- // gone would hijack the shell we just handed over.- const was_fullscreen = armed.load(.acquire);- emergency();- var dfl = std.posix.Sigaction{- .handler = .{ .handler = std.posix.SIG.DFL },- .mask = std.posix.sigemptyset(),- .flags = 0,- };- std.posix.sigaction(sig, &dfl, null);- // The kernel blocks the delivered signal for the handler's duration, so a- // bare raise() only marks it PENDING: it would deliver on handler RETURN —- // AFTER installStopHandlers() below re-armed us — and re-enter this- // handler forever (a measured 12 MB/s restore/enable flood at 99% CPU,- // never reaching state T). Unblock it so the raise stops the process HERE.- var only_stop = std.posix.sigemptyset();- std.posix.sigaddset(&only_stop, sig);- std.posix.sigprocmask(std.posix.SIG.UNBLOCK, &only_stop, null);- std.posix.raise(sig) catch {};- // --- genuinely continued here (SIGCONT) ---- installStopHandlers();- if (!was_fullscreen) return;- if (tty.enterRaw()) |_| {}- if (enable.len > 0) _ = std.posix.system.write(std.posix.STDOUT_FILENO, enable.ptr, enable.len);- muteStderr(); // fullscreen again: stderr back to the log (open/dup2 are async-signal-safe)- armed.store(true, .release);- resumed.store(true, .release);-}--test "restore pops kitty before leaving the alt screen, cursor back on" {- const kitty_pop = std.mem.indexOf(u8, seq, "\x1b[<u").?;- const alt_exit = std.mem.indexOf(u8, seq, "\x1b[?1049l").?;- try std.testing.expect(kitty_pop < alt_exit);- try std.testing.expect(std.mem.endsWith(u8, seq, "\x1b[?1049l"));- try std.testing.expect(std.mem.indexOf(u8, seq, "\x1b[?25h") != null);- try std.testing.expect(std.mem.indexOf(u8, seq, "\x1b[?2004l") != null);-}--test "arm and disarm toggle the emergency latch" {- try std.testing.expect(!armed.load(.acquire));- arm(if (builtin.os.tag == .windows) .{} else undefined, "");- try std.testing.expect(armed.load(.acquire));- try std.testing.expect(isArmed());- disarm();- try std.testing.expect(!armed.load(.acquire));-}--test "takeClaim is empty until a claim is owned" {- try std.testing.expect(takeClaim() == null);-}--test "takeClaim hands the raw state over exactly once" {- claim_raw = if (builtin.os.tag == .windows) .{} else undefined;- claim_owned.store(true, .release);- try std.testing.expect(takeClaim() != null);- try std.testing.expect(takeClaim() == null);-}--test "crash signals are hooked, and they hand the signal back, not to SIG_DFL (#535/#547)" {- for ([_]std.posix.SIG{ .SEGV, .BUS, .ILL, .FPE, .TRAP }) |want| {- var found = false;- for (fatal, 0..) |sig, i| {- if (sig != want) continue;- found = true;- // Every crash signal must sit at or after first_fault, or onFatal- // would SIG_DFL over Zig's stack-trace dumper in a safety build.- try std.testing.expect(i >= first_fault);- }- try std.testing.expect(found);- }- // The polite half keeps the plain default-and-re-raise behavior.- try std.testing.expectEqual(std.posix.SIG.TERM, fatal[0]);- try std.testing.expect(first_fault < fatal.len);- // Ctrl+Z / `kill -TSTP` must never stop us on a raw alt screen (#549).- try std.testing.expectEqual(@as(usize, 1), stop_signals.len);- try std.testing.expectEqual(std.posix.SIG.TSTP, stop_signals[0]);-}--test "stderr is parked for the TUI's whole lifetime and unparked on every exit path" {- const run_src = @embedFile("run.zig");- // Early claim (ADR 0042) is taken here so run does not re-arm over raw termios.- try std.testing.expect(std.mem.indexOf(u8, run_src, "takeClaim()") != null);- // Parked right after the fullscreen enable, before the first frame...- const enable_at = std.mem.indexOf(u8, run_src, "w.writeAll(enable_seq) catch {};").?;- const mute_at = std.mem.indexOfPos(u8, run_src, enable_at, "restore_mod.muteStderr();").?;- // ...and unparked in the run loop's exit defer, before the restore bytes.- const defer_unmute = std.mem.indexOfPos(u8, run_src, mute_at, "restore_mod.unmuteStderr();").?;- const defer_restore = std.mem.indexOfPos(u8, run_src, defer_unmute, "w.writeAll(restore_mod.seq) catch {};").?;- try std.testing.expect(defer_unmute < defer_restore);- // The shell hand-over (Ctrl+Z park) unparks before stopping and re-parks after.- const park_at = std.mem.indexOf(u8, run_src, "fn parkToShell").?;- try std.testing.expect(std.mem.indexOfPos(u8, run_src, park_at, "unmuteStderr()") != null);- try std.testing.expect(std.mem.indexOfPos(u8, run_src, park_at, "muteStderr()") != null);- // Crash/stop paths: emergency() unparks FIRST, so panic traces reach the- // real terminal; the SIGCONT re-entry re-parks.- const self_src = @embedFile("restore.zig");- const emergency_at = std.mem.indexOf(u8, self_src, "pub fn emergency() void {").?;- const unmute_in_emergency = std.mem.indexOfPos(u8, self_src, emergency_at, "unmuteStderr();").?;- const write_in_emergency = std.mem.indexOfPos(u8, self_src, emergency_at, "std.posix.system.write").?;- try std.testing.expect(unmute_in_emergency < write_in_emergency);- const cont_at = std.mem.indexOf(u8, self_src, "genuinely continued here").?;- try std.testing.expect(std.mem.indexOfPos(u8, self_src, cont_at, "muteStderr();") != null);-}--test "resumed latch fires exactly once per continue" {- resumed.store(true, .release);- try std.testing.expect(takeResumed());- try std.testing.expect(!takeResumed());-}--test "the window-size latch fires once per resize and starts down" {- // The painter's diff baseline is only as good as the claim that nothing- // else touched the screen; a resize breaks that claim without changing a- // single byte of the frame, so the loop needs an EVENT, not a comparison.- try std.testing.expect(!takeResized());- onWinch(.WINCH);- try std.testing.expect(takeResized());- try std.testing.expect(!takeResized());- try std.testing.expectEqual(@as(usize, 1), size_signals.len);- try std.testing.expectEqual(std.posix.SIG.WINCH, size_signals[0]);-}diff --git a/TUI/resume.zig b/TUI/resume.zigdeleted file mode 100644index 6ec9277b..00000000--- a/TUI/resume.zig+++ /dev/null@@ -1,242 +0,0 @@-//! Fullscreen `/resume` — session list overlay, plus `/resume SOURCE [--branch DEST]`.--const std = @import("std");-const app = @import("app.zig");-const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const models = @import("models.zig");-const panel = @import("panel.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--pub const max_sessions = 512;-pub const visible_rows = 10;-pub const hint = "type to search · ↑↓ move · click or Enter resumes · Esc";--pub const Row = struct { base: []const u8, label: []const u8, desc: []const u8 };--fn parseRow(raw: []const u8) Row {- const t1 = std.mem.indexOfScalar(u8, raw, '\t') orelse return .{ .base = raw, .label = raw, .desc = "" };- const base = raw[0..t1];- const rest = raw[t1 + 1 ..];- const t2 = std.mem.indexOfScalar(u8, rest, '\t') orelse return .{ .base = base, .label = rest, .desc = "" };- const label = rest[0..t2];- return .{ .base = base, .label = if (label.len > 0) label else base, .desc = rest[t2 + 1 ..] };-}--pub fn filterList(list: []const u8, query: []const u8, out: []Row) usize {- var n: usize = 0;- var it = std.mem.splitScalar(u8, list, '\n');- while (it.next()) |raw| {- const line = std.mem.trim(u8, raw, " \t\r");- if (line.len == 0) continue;- const row = parseRow(line);- if (!models.modelMatch(row.base, query) and !models.modelMatch(row.label, query) and !models.modelMatch(row.desc, query)) continue;- if (n >= out.len) break;- out[n] = row;- n += 1;- }- return n;-}--pub fn pick(self: *const Model) ?[]const u8 {- var rows: [max_sessions]Row = undefined;- const n = filterList(self.sessions_cache orelse "", self.overlay_filter, &rows);- if (n == 0) return null;- return rows[self.overlay_sel % n].base;-}--/// Bare `/resume`: load the saved-session list and open the picker.-pub fn open(self: *Model) void {- if (self.sessions_cache) |old| {- self.alloc.free(old);- self.sessions_cache = null;- }- if (engine.g_sessions_fn) |f| self.sessions_cache = f(engine.g_turn_ctx, self.alloc);- self.openOverlay(.sessions);-}--pub fn head(self: *const Model, a: std.mem.Allocator) !panel.Head {- var rows: [max_sessions]Row = undefined;- const list = self.sessions_cache orelse "";- const total = filterList(list, "", &rows);- const n = filterList(list, self.overlay_filter, &rows);- return .{- .title = try std.fmt.allocPrint(a, "Resume session › {s}\u{258B}", .{self.overlay_filter}),- .note = try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total }),- };-}--pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {- const th = self.theme();- var rows: [max_sessions]Row = undefined;- const list = self.sessions_cache orelse "";- const n = filterList(list, self.overlay_filter, &rows);- var out = std.array_list.Managed(u8).init(a);- if (n == 0) {- const why: []const u8 = if (self.sessions_cache == null)- " resume isn't available (offline)"- else if (self.overlay_filter.len > 0)- " no matches — type to filter"- else- " no saved sessions in cwd — /save creates one";- try out.appendSlice(try theme_mod.paint(a, th.muted, why));- try out.append('\n');- return out.items;- }- const sel = self.overlay_sel % n;- const vis = @min(visible_rows, n);- const off = if (sel >= vis) sel - vis + 1 else 0;- var i = off;- while (i < n and i < off + vis) : (i += 1) {- const mark = glyphs.frame(&glyphs.row_mark, @intFromBool(i != sel));- const line = if (rows[i].desc.len > 0)- try std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, rows[i].label, rows[i].desc })- else- try std.fmt.allocPrint(a, "{s}{s}", .{ mark, rows[i].label });- try out.appendSlice(if (i == sel) try theme_mod.paint(a, th.accent, line) else try theme_mod.paint(a, th.muted, line));- try out.append('\n');- }- if (n > vis) try out.appendSlice(try panel.windowRow(a, th, off, vis, n));- return out.items;-}--pub fn run(self: *app.Model, spec: []const u8) void {- if (spec.len == 0) {- open(self);- return;- }- const callback = engine.g_resume_fn orelse {- self.push(.system, "resume isn't available (offline)") catch {};- return;- };- var out: engine.ResumeOut = .{};- if (!callback(engine.g_turn_ctx, self.alloc, spec, &out)) {- if (out.note.len > 0) {- self.push(.err, out.note) catch {};- self.alloc.free(out.note);- } else self.push(.err, "resume failed") catch {};- return;- }- self.clearHistory();- for (out.turns) |turn| {- self.push(if (turn.notification) .system else if (turn.role == .user) .user else .assistant, turn.text) catch {- self.alloc.free(turn.text);- continue;- };- self.history.items[self.history.items.len - 1].notification = turn.notification;- self.alloc.free(turn.text);- }- if (out.turns.len > 0) self.alloc.free(out.turns);- self.turns = self.userTurnCount();- if (self.session_name) |old| self.alloc.free(old);- self.session_name = out.session_name;- if (self.goal) |old| self.alloc.free(old);- self.goal = if (out.goal.len > 0) out.goal else null;- self.strict = out.strict;- self.ultracode = out.ultracode;- if (out.note.len > 0) {- self.push(.system, out.note) catch {};- self.alloc.free(out.note);- }-}--fn fakeSessions(_: ?*anyopaque, gpa: std.mem.Allocator) ?[]const u8 {- return gpa.dupe(u8, "alpha\tAlpha title\t2h ago\nbeta\tbeta\tjust now") catch null;-}--fn fakeResume(_: ?*anyopaque, gpa: std.mem.Allocator, spec: []const u8, out: *engine.ResumeOut) bool {- if (spec.len == 0) return false;- if (!std.mem.eql(u8, spec, "base --branch child")) {- const turns = gpa.alloc(engine.Turn, 1) catch return false;- turns[0] = .{ .role = .user, .text = std.fmt.allocPrint(gpa, "from {s}", .{spec}) catch return false };- out.* = .{- .turns = turns,- .session_name = gpa.dupe(u8, spec) catch return false,- .note = std.fmt.allocPrint(gpa, "resumed {s}", .{spec}) catch return false,- };- return true;- }- const turns = gpa.alloc(engine.Turn, 2) catch return false;- turns[0] = .{ .role = .user, .text = gpa.dupe(u8, "baseline prompt") catch return false };- turns[1] = .{ .role = .assistant, .text = gpa.dupe(u8, "baseline answer") catch return false };- out.* = .{- .turns = turns,- .session_name = gpa.dupe(u8, "child") catch return false,- .note = gpa.dupe(u8, "branched base → child") catch return false,- };- return true;-}--test "fullscreen resume replaces transcript and selects the branch" {- const saved = engine.g_resume_fn;- defer engine.g_resume_fn = saved;- engine.g_resume_fn = fakeResume;- var model: app.Model = undefined;- model.setup(std.testing.allocator);- defer model.deinit();- try model.push(.user, "stale prompt");- run(&model, "base --branch child");- try std.testing.expectEqualStrings("child", model.session_name.?);- try std.testing.expectEqual(@as(usize, 3), model.history.items.len);- try std.testing.expectEqualStrings("baseline prompt", model.history.items[0].text);- try std.testing.expectEqualStrings("baseline answer", model.history.items[1].text);- try std.testing.expectEqualStrings("branched base → child", model.history.items[2].text);-}--test "bare /resume opens a list overlay and Enter resumes the highlighted session" {- engine.g_sessions_fn = fakeSessions;- defer engine.g_sessions_fn = null;- engine.g_resume_fn = fakeResume;- defer engine.g_resume_fn = null;- var m: app.Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "stale");- open(&m);- try std.testing.expectEqual(app.Overlay.sessions, m.overlay);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator());- try std.testing.expect(std.mem.indexOf(u8, text, "Alpha title") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "beta") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "2h ago") != null);- _ = @import("overlays.zig").key(&m, .enter);- try std.testing.expectEqual(app.Overlay.none, m.overlay);- try std.testing.expectEqualStrings("alpha", m.session_name.?);- try std.testing.expectEqualStrings("from alpha", m.history.items[0].text);-}--test "clicking a /resume row selects then confirms" {- engine.g_sessions_fn = fakeSessions;- defer engine.g_sessions_fn = null;- engine.g_resume_fn = fakeResume;- defer engine.g_resume_fn = null;- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = @import("dispatch.zig").applyLine(&term.model, "/resume");- try std.testing.expectEqual(app.Overlay.sessions, term.model.overlay);- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "Alpha title") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "beta") != null);- // Highlight starts on row 0; a click on a different row selects, a second- // click on that same row confirms — the same rule as the other pickers.- try std.testing.expect(try term.clickText("beta"));- try std.testing.expectEqual(app.Overlay.sessions, term.model.overlay);- try std.testing.expectEqualStrings("beta", pick(&term.model).?);- try std.testing.expect(try term.clickText("beta"));- try std.testing.expectEqual(app.Overlay.none, term.model.overlay);- try std.testing.expectEqualStrings("beta", term.model.session_name.?);-}--test "filterList matches title, base, and subsequence" {- var buf: [8]Row = undefined;- const list = "alpha\tAlpha title\t2h ago\nbeta\tbeta\tjust now";- try std.testing.expectEqual(@as(usize, 2), filterList(list, "", &buf));- try std.testing.expectEqual(@as(usize, 1), filterList(list, "alpha", &buf));- try std.testing.expectEqualStrings("alpha", buf[0].base);- try std.testing.expectEqual(@as(usize, 1), filterList(list, "title", &buf));- try std.testing.expectEqualStrings("alpha", buf[0].base);-}diff --git a/TUI/root.zig b/TUI/root.zigdeleted file mode 100644index 96d8cb7a..00000000--- a/TUI/root.zig+++ /dev/null@@ -1,165 +0,0 @@-//! Codegraff fullscreen TUI — Grok Build pager UX, no zigzag.-//! Live entry: `graff tui` and TTY `graff repl`.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const run_mod = @import("run.zig");--pub const Model = app.Model;-pub const Screen = app.Screen;-pub const Focus = app.Focus;-pub const Overlay = app.Overlay;-pub const AgentMode = app.AgentMode;-pub const Effort = engine.Effort;-pub const HudKind = engine.HudKind;-pub const Turn = engine.Turn;-pub const Params = engine.Params;-pub const StreamBuf = engine.StreamBuf;-/// Live bash raw tail the sink writes from the tool pool.-pub fn rawStream() ?*engine.StreamBuf {- return engine.g_raw;-}-pub fn setFollowupFn(f: ?engine.FollowupFn) void {- engine.g_followup_fn = f;-}-pub fn setSteerFns(send: ?engine.SteerSendFn, reclaim: ?engine.SteerReclaimFn) void {- engine.g_steer_send_fn = send;- engine.g_steer_reclaim_fn = reclaim;-}-pub const Event = engine.Event;-pub const EventQueue = engine.EventQueue;-pub const ToolEvent = engine.ToolEvent;-pub const Status = engine.Status;-pub const TurnFn = engine.TurnFn;-pub const ModelFn = engine.ModelFn;-pub const ModelEntry = engine.ModelEntry;-pub const CostClass = engine.CostClass;-pub const Picked = engine.Picked;-pub const CancelFn = engine.CancelFn;-pub const CompactOut = engine.CompactOut;-pub const CompactFn = engine.CompactFn;-pub const HistoryOp = engine.HistoryOp;-pub const HistoryFn = engine.HistoryFn;-pub const ResumeOut = engine.ResumeOut;-pub const ResumeFn = engine.ResumeFn;-pub const SessionState = engine.SessionState;-pub const GoalOp = engine.GoalOp;-pub const StateFn = engine.StateFn;-pub const PeerFn = engine.PeerFn;-pub const ConstraintFn = engine.ConstraintFn;-pub const VersionFn = engine.VersionFn;-pub const UpdateFn = engine.UpdateFn;-pub const RunOpts = run_mod.RunOpts;-pub const run = run_mod.run;-pub fn setCurrentModel(name: []const u8, provider: []const u8) void {- engine.g_model_name = name;- engine.g_model_provider = provider;-}-pub const restore = @import("restore.zig");-pub const enable_seq = run_mod.enable_seq;--/// Claim the alt-screen as soon as the command is `tui`/`repl`, so leftover-/// boot (keys, MCP, AGENTS.md) happens inside the pager. No-op off a TTY.-pub fn claim() bool {- return restore.claimScreen(run_mod.enable_seq);-}-/// Restore the terminal BEFORE std prints a panic, or the alt-screen exit in-/// the restore sequence erases the message and the stack trace (#535).-pub const panic = restore.Panic;-pub const theme = @import("theme.zig");-pub const catalog = @import("catalog.zig");-pub const dump = @import("dump.zig");-pub const sim = @import("sim.zig");--test {- _ = engine;- _ = @import("permission.zig");- _ = @import("events.zig");- _ = theme;- _ = catalog;- _ = app;- _ = @import("app_tests.zig");- _ = @import("dispatch.zig");- _ = @import("model_confirmation_tests.zig");- _ = @import("resume.zig");- _ = @import("peer_cmd.zig");- _ = @import("peer_tests.zig");- _ = @import("prompt_history.zig");- _ = @import("meters.zig");- _ = @import("key.zig");- _ = @import("key_paste.zig");- _ = @import("key_orphan.zig");- _ = @import("key_tests.zig");- _ = @import("spec_terminal_modes_conformance.zig");- _ = @import("key_loop_tests.zig");- _ = @import("issue_537_reviewer_tests.zig");- _ = @import("issue_524_tests.zig");- _ = @import("issue_737_tests.zig");- _ = @import("issue_792_tests.zig");- _ = @import("issue_789_tests.zig");- _ = @import("issue_788_tests.zig");- _ = @import("issue_798_tests.zig");- _ = @import("issue_887_tests.zig");- _ = @import("sanitize.zig");- _ = @import("issue_805_tests.zig");- _ = @import("composer_links.zig");- _ = @import("input.zig");- _ = @import("keys.zig");- _ = @import("nav.zig");- _ = @import("image.zig");- _ = @import("imgproto.zig");- _ = @import("turn.zig");- _ = @import("turn_spawn_tests.zig");- _ = @import("bgop.zig");- _ = @import("welcome.zig");- _ = @import("glyphs.zig");- _ = @import("foldhdr.zig");- _ = @import("mdtable.zig");- _ = @import("tool_card.zig");- _ = @import("scrollback.zig");- _ = @import("layout_cache.zig");- _ = @import("selection.zig");- _ = @import("selection_tests.zig");- _ = @import("issue_845_tests.zig");- _ = @import("issue_883_tests.zig");- _ = @import("theme_tint.zig");- _ = @import("hover.zig");- _ = @import("hover_tests.zig");- _ = @import("click.zig");- _ = @import("click_tests.zig");- _ = @import("osc52.zig");- _ = @import("scrollbar.zig");- _ = @import("scrollbar_tests.zig");- _ = @import("chrome.zig");- _ = @import("panel.zig");- _ = @import("overlaypane.zig");- _ = @import("models.zig");- _ = @import("markdown.zig");- _ = @import("markdown_stream_tests.zig");- _ = @import("syntax.zig");- _ = @import("diff.zig");- _ = @import("dump.zig");- _ = @import("inset.zig");- _ = @import("effort.zig");- _ = @import("sim.zig");- _ = @import("render.zig");- _ = @import("anchor.zig");- _ = @import("tty.zig");- _ = @import("restore.zig");- _ = @import("files.zig");- _ = @import("overlays.zig");- _ = run_mod;- _ = @import("run_tests.zig");- _ = @import("paint.zig");- _ = @import("paint_tests.zig");- _ = @import("scrollpaint.zig");- _ = @import("run_stall.zig");- _ = @import("pacing.zig");- _ = @import("traj.zig");-}--pub fn main(init: std.process.Init) !void {- try run(init.gpa, init.io, init.environ_map, .{ .cwd = "." });-}diff --git a/TUI/run.zig b/TUI/run.zigdeleted file mode 100644index 33f3f1d8..00000000--- a/TUI/run.zig+++ /dev/null@@ -1,494 +0,0 @@-//! Fullscreen loop on term.zig + ANSI. No zigzag, no OpenTUI-via-TS.--const std = @import("std");-const builtin = @import("builtin");-const Io = std.Io;--const app = @import("app.zig");-const bgop = @import("bgop.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const keys = @import("keys.zig");-const paste_mod = @import("key_paste.zig");-const pacing = @import("pacing.zig");-const paint_mod = @import("paint.zig");-const render_mod = @import("render.zig");-const restore_mod = @import("restore.zig");-const stall = @import("run_stall.zig");-const turn = @import("turn.zig");-const tty = @import("tty.zig");-const traj = @import("traj.zig");-const Model = app.Model;--// 1000/1003/1006: click + hover + wheel as buttons 64/65 (not arrows).-// 2004: bracketed paste. 7l: no autowrap into the prompt.-// >11u: kitty disambiguate + event types + all-keys (Cmd+Delete / Super latch).-// >4;2m: xterm modifyOtherKeys so Super+Backspace also arrives as CSI 27;9;127~.-pub const enable_seq = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m";--/// How long the screen may go without a full row-by-row rewrite. Short enough-/// that nobody sits looking at damage, long enough to cost nothing: the frame-/// is unchanged, so the repaint is the same bytes into a synchronized swap.-pub const heal_interval_ms: u64 = 3000;--/// Every seam the frontend is handed, declared with the engine that owns-/// them (engine.RunOpts). Re-exported here because `run` is its only caller.-pub const RunOpts = engine.RunOpts;--pub fn run(- gpa: std.mem.Allocator,- io: Io,- environ_map: *const std.process.Environ.Map,- opts: RunOpts,-) !void {- // Local-only pacing instrumentation. Off unless asked for, never uploaded:- // the pty storm test needs a way to count frames from outside the process.- pacing.stats_on = environ_map.get("GRAFF_TUI_PAINT_STATS") != null;- pacing.resetStats();- engine.g_turn_ctx = opts.turn_ctx;- engine.g_turn_fn = opts.turn_fn;- engine.g_model_fn = opts.model_fn;- engine.g_cancel_fn = opts.cancel_fn;- engine.g_hud_fn = opts.hud_fn;- engine.g_paste_fn = opts.paste_fn;- engine.g_bash_fn = opts.bash_fn;- engine.g_files_fn = opts.files_fn;- engine.g_copy_fn = opts.copy_fn;- engine.g_compact_fn = opts.compact_fn;- engine.g_history_fn = opts.history_fn;- engine.g_resume_fn = opts.resume_fn;- engine.g_sessions_fn = opts.sessions_fn;- engine.g_state_fn = opts.state_fn;- engine.g_idle_wake_fn = opts.idle_wake_fn;- engine.g_peer_fn = opts.peer_fn;- engine.g_constraint_fn = opts.constraint_fn;- engine.g_version_fn = opts.version_fn;- engine.g_update_fn = opts.update_fn;- engine.g_model_name = opts.model_name;- engine.g_model_provider = opts.model_provider;- engine.g_model_entries = opts.model_entries;- engine.g_cwd = opts.cwd;-- var m: Model = undefined;- m.setup(gpa);- defer m.deinit();- defer if (opts.state_fn) |f| f(opts.turn_ctx, .{- .session_name = m.session_name orelse "",- .goal = m.goal orelse "",- .strict = m.strict,- .ultracode = m.ultracode,- });- for (opts.initial_history) |item| m.push(if (item.role == .user) .user else .assistant, item.text) catch {};- m.turns = m.userTurnCount();- if (opts.session_name.len > 0) m.session_name = gpa.dupe(u8, opts.session_name) catch null;- if (opts.initial_goal.len > 0) m.goal = gpa.dupe(u8, opts.initial_goal) catch null;- m.strict = opts.initial_strict;- m.ultracode = opts.initial_ultracode;- if (opts.yolo) m.mode = .always_approve;-- const claimed = restore_mod.takeClaim();- var raw = claimed orelse (tty.enterRaw() orelse return error.NotATty);- if (claimed != null) _ = tty.enterRaw(); // boot may have put the line discipline back- if (claimed == null) restore_mod.arm(raw, enable_seq);- defer restore_mod.disarm();- defer tty.restore(raw);-- var out_buf: [64 * 1024]u8 = undefined;- var stdout = Io.File.stdout().writer(io, &out_buf);- const w = &stdout.interface;- w.writeAll(enable_seq) catch {};- w.writeAll("\x1b]11;?\x07") catch {}; // background query -> auto light/dark (key.zig bg_report)- w.flush() catch {};- // Registered BEFORE the restore below, so LIFO puts the line on the normal- // screen after the alt screen is gone. No-op unless GRAFF_TUI_PAINT_STATS.- defer pacing.report(w);- // Nothing may write to the real terminal around the frame painter: park- // fd 2 on .graff/tui-stderr.log so std.debug.print from any thread (a- // subagent's status card, a worker line) cannot scroll the alt screen and- // bleed stale rows through the diff paint. Every exit path unparks it.- restore_mod.muteStderr();- traj.open(io);- defer {- restore_mod.unmuteStderr();- w.writeAll(restore_mod.seq) catch {};- w.flush() catch {};- }-- // Sized for a momentum storm, not a keystroke: a trackpad fling is ~13- // bytes of SGR per report and the loop now drains every one the tty holds- // into a single tick (see the drain below).- var inbuf: [16 * 1024]u8 = undefined;- var pending_len: usize = 0;- var last_frame_ms: u64 = 0;- // When the last byte of input arrived — the rate side of the storm test.- var last_input_ms: u64 = 0;- var esc_stall: u8 = 0;- var esc_live = false; // operation state latched when a lone ESC arrives- var zero_reads: u8 = 0;- // Clock for the bracketed-paste latch only: refreshed by bytes that could- // plausibly BE paste content, never by mouse-motion noise (see below).- var last_paste_ms: u64 = 0;- var stash_ms: u64 = 0;- var arm_ms: u64 = 0;- var last_hash: u64 = 0;- var last_heal_ms: u64 = 0;- var gfx: @import("imgproto.zig").Slot = .{};- var prev: []u8 = &.{};- var prev_rows: usize = 0;- var prev_cols: usize = 0;- var prev_theme = m.theme_id;- defer if (prev.len != 0) gpa.free(prev);- while (m.running and !m.quit_requested) {- m.now_ms = nowMs(io);- if (restore_mod.takeResumed()) {- // SIGTSTP took the terminal back to the shell and SIGCONT handed- // it over again: the alt screen is blank, so the diff baseline- // would leave the frame half-drawn. Force a full repaint.- last_hash = 0;- if (prev.len != 0) gpa.free(prev);- prev = &.{};- }- if (m.pending) |job| {- if (job.done.load(.acquire)) {- turn.finishJob(&m);- if (turn.drainSteer(&m) == .quit) break;- }- }- if (m.pending == null) turn.maybeJobWake(&m);- // Background engine ops (/compact, !cmd, @-file list) land here too —- // the same poll that keeps a turn from freezing the loop (#533).- bgop.finish(&m);- pacing.ticks += 1;- // At most ONE composed frame per tick, and while input keeps arriving,- // at most one per frame budget (pacing.zig). The storm signal is a- // backlog OR a stream still landing inside the storm window — a check- // for queued bytes alone misses momentum entirely, because on a loop- // this fast every report is read the instant it arrives and finds the- // queue empty behind it. Quiet, the frame is composed on the spot, so a- // single flick pays nothing. A skipped tick falls straight through to- // the drain below, so the frame that does land shows the LATEST scroll- // position — the intermediate ones are never painted at all. A hover- // sweep is the same shape as a momentum flick and rides the same lane.- const more_pending = tty.poll(0);- const painted = pacing.shouldPaint(m.now_ms, last_frame_ms, last_input_ms, more_pending);- if (!painted) {- pacing.frames_skipped += 1;- } else {- last_frame_ms = m.now_ms;- pacing.frames += 1;- frame_blk: {- const cols = @max(tty.cols(), @as(usize, 40));- const rows = @max(tty.rows(), @as(usize, 12));- const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch break :frame_blk;- defer gpa.free(frame);- // A copy landed inside that render (selection.zig commits the- // clipboard from the pass that captured it). OSC 52 asks the- // TERMINAL for its clipboard, which is the only one an SSH user- // can paste from — and it goes out HERE, outside the frame,- // because the frame gets repainted and a clipboard write must- // happen exactly once.- const osc = @import("selection.zig").takeOsc52(&m);- if (osc.len > 0) {- w.writeAll(osc) catch {};- w.flush() catch {};- m.alloc.free(osc); // minted by the model's own allocator- }- const hash = std.hash.Wyhash.hash(0, frame);- // The diff painter trusts `prev` to be what is on screen. Two- // things can make that a lie without changing a single byte of- // the frame: a resize the loop never sees (SIGWINCH between- // tty.cols() and the paint, or one that ends on the dimensions- // it started from — the terminal still reflowed), and any async- // writer over the same tty (a kitty image delete redrawing- // late). Neither moves the hash, so neither would ever be- // repaired. A resize EVENT forces the full clear-and-lay-down;- // the heartbeat forces a cheaper every-row rewrite of the frame- // we already believe is up, which under ?2026 is byte-identical- // output into a synchronized swap — visually a no-op.- const resized = restore_mod.takeResized();- const heal = resized or m.now_ms -| last_heal_ms >= heal_interval_ms;- if (hash != last_hash or heal) {- const has_gfx = std.mem.indexOf(u8, frame, "\x1b_G") != null;- const imgproto = @import("imgproto.zig");- const want_gfx = imgproto.place(&m, cols) != null;- // The theme bg is painted per ROW, not baked into the- // frame, and blank rows are byte-identical across- // themes/widths — the diff path skips them, stranding- // old-bg rows after /theme or the startup OSC-11 polarity- // flip, and stale columns after a width-only resize. Both- // must force a full paint.- const full = prev.len == 0 or rows != prev_rows or cols != prev_cols or m.theme_id != prev_theme or has_gfx or resized;- // Kitty images sit above the cell grid. SU/SD would move- // cells under a still image, so a live overlay skips the- // scroll fast path. Placement is post-paint (imgproto.zig),- // never in the frame, so a preview does not force a wipe.- const hint = if (full or heal or gfx.on or want_gfx) null else m.paint_hint;- w.writeAll("\x1b[?2026h") catch {};- if (has_gfx) w.writeAll(imgproto.clear_all) catch {};- paint_mod.paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg, heal, hint) catch {};- imgproto.sync(w, gpa, &gfx, &m, cols, full or heal);- w.writeAll("\x1b[?2026l") catch {};- w.flush() catch {};- pacing.paints += 1;- if (prev.len != 0) gpa.free(prev);- prev = gpa.dupe(u8, frame) catch &.{};- prev_rows = rows;- prev_cols = cols;- prev_theme = m.theme_id;- last_hash = hash;- // Only a paint that rewrote EVERY row resets the heartbeat.- if (full or heal) last_heal_ms = m.now_ms;- }- }- }-- // Short wait while an unfinished escape sequence is pending: if- // nothing follows, the lone ESC was a real Escape keypress (#94).- var wait: i32 = if (pending_len > 0) 25 else if (m.pending != null or m.bg != null) 50 else 200;- // A deferred frame is a debt: come back for it when the budget is up,- // through the poll timeout the loop already has. Only when a frame is- // owed AND no escape head is pending, so an idle loop keeps its long- // cheap waits and #94's stall clock keeps its 25ms tick exactly.- if (!painted and pending_len == 0) wait = pacing.waitCap(m.now_ms, last_frame_ms, wait);- if (!tty.poll(wait)) {- if (key_mod.inPaste() and m.now_ms -| last_paste_ms >= stall.paste_idle_ms) {- // A `CSI 200~` whose `CSI 201~` never arrives latches the- // composer into literal mode for the rest of the session:- // Enter only inserts a newline, and Escape, Tab and every- // slash command are swallowed. Close it out once the terminal- // has been quiet far longer than any paste keeps streaming- // (#532/#536/#548).- closePaste(&m);- last_paste_ms = m.now_ms;- if (pending_len > 0) {- // Whatever was stuck mid-sequence belongs to the paste- // window this sweep just declared broken — debris, by- // definition. Handing it back to the stall path let it be- // re-classified as a KEY: a lone pending ESC (the head of- // the `CSI 201~` that never came) became the Escape key the- // instant the sweep cleared `in_paste`, cancelling a live- // turn and wiping the composer with no user keypress at- // all. Carry it for a late tail, arm the sweeper for a- // headless one, and never let it become a keystroke.- key_mod.abandonSequence(inbuf[0..pending_len], .dropped);- stash_ms = m.now_ms;- arm_ms = m.now_ms;- pending_len = 0;- esc_stall = 0;- }- }- if (pending_len > 0) {- esc_stall +|= 1;- switch (stall.stallVerdict(inbuf[0..pending_len], esc_stall, .{- .operation_live = esc_live or m.pending != null or m.bg != null,- .in_paste = key_mod.inPaste(),- })) {- .wait => {},- .escape_key => {- // Keep the ESC. If the next read is this sequence's- // body after all, the two rejoin and it parses as the- // arrow / mouse report / OSC reply it always was- // instead of spraying `[<35;80;24M` into the composer- // (#530).- key_mod.abandonSequence(inbuf[0..pending_len], .escape);- stash_ms = m.now_ms;- arm_ms = m.now_ms;- pending_len = 0;- esc_stall = 0;- if (keys.handle(&m, .escape) == .quit) m.running = false;- },- .escape_pair => {- // A genuine double Escape is still two Escape keys;- // only an unfinished legacy Alt CSI reaches here.- key_mod.abandonSequence(inbuf[0..pending_len], .none);- pending_len = 0;- esc_stall = 0;- if (keys.handle(&m, .escape) == .quit) m.running = false;- if (m.running and keys.handle(&m, .escape) == .quit) m.running = false;- },- .drop => {- // A sequence the terminal never finished, waited out.- // Carry the head so a late tail can still rejoin it,- // and tell key.zig to expect orphan debris otherwise.- key_mod.abandonSequence(inbuf[0..pending_len], .dropped);- stash_ms = m.now_ms;- arm_ms = m.now_ms;- pending_len = 0;- esc_stall = 0;- closePaste(&m);- },- }- }- continue;- }- esc_stall = 0;- if (pending_len == inbuf.len) {- key_mod.abandonSequence(inbuf[0..pending_len], .dropped);- stash_ms = m.now_ms;- arm_ms = m.now_ms;- esc_live = false;- }- pending_len = stall.clearFullWedge(pending_len, inbuf.len);- var filled = pending_len;- const got = tty.readStdin(inbuf[filled..]);- pacing.reads += 1;- if (got == 0) {- // poll says readable but read gives nothing: hangup or transient- // error. Three in a row means the TTY is gone.- zero_reads += 1;- if (zero_reads >= 3) m.running = false;- continue;- }- zero_reads = 0;- filled += got;- last_input_ms = m.now_ms;- // Take EVERYTHING the tty already holds into THIS tick before any- // dispatch. Trackpad momentum arrives a few reports at a time, and- // servicing one read per frame is exactly what makes the scroll trail- // the fingers and then jump when the backlog drains. Bounded twice — by- // the buffer, and by the frame budget, so a flood that never stops- // still yields a frame every ~8ms instead of never.- while (filled < inbuf.len and tty.poll(0)) {- if (pacing.drainExpired(nowMs(io), m.now_ms)) break;- const more = tty.readStdin(inbuf[filled..]);- pacing.reads += 1;- if (more == 0) break;- filled += more;- }- traj.note(io, m.now_ms, inbuf[pending_len..filled]);- // ?1003h is on for image-chip hover, so a pointer merely RESTING over- // the terminal emits a motion report roughly twice a second. Counting- // those as paste activity postponed the idle sweep above forever: a- // wedged paste never released while the mouse sat still anywhere over- // the window. Only bytes that could be paste content run the clock —- // and a wheel storm is likewise all mouse reports, so it cannot hold a- // broken paste open either.- if (!stall.onlyMouseReports(inbuf[pending_len..filled])) last_paste_ms = m.now_ms;- // A genuine Escape's exact carry is short; a non-lone head actually- // dropped after its stall budget keeps its framing for the full arm- // interval. Either kind is still one-shot on the first new read.- if (stall.escapeCarryExpired(m.now_ms, stash_ms)) key_mod.expireOrphanHead();- if (stall.armExpired(m.now_ms, arm_ms)) key_mod.armOrphan(false);- const n = key_mod.joinOrphanHead(&inbuf, filled);- // A paste bigger than one read arrives as several back to back. Judge- // the whole run, not each chunk: otherwise a chunk that ends at a line- // boundary reads as Enter and sends half the paste (#737).- paste_mod.setBurstRead(paste_mod.burstRead(inbuf[0..n], m.now_ms));- // Everything this tick drained is applied as ONE batch, with runs of- // consecutive wheel reports folded into a single accumulated delta- // (pacing.zig). Order is preserved and a keystroke BREAKS the run at- // its exact position, so typing is never starved behind a flood — and- // because only one frame follows the whole batch, no intermediate- // scroll position is ever painted.- var i: usize = 0;- var batch: @import("input_batch.zig").Decoder = .{};- batches: while (batch.next(inbuf[0..n], &i)) |items| {- for (items) |item| {- if (item == .wheel) pacing.wheel_batches += 1;- const effect = keys.handleBatchItem(&m, item);- switch (effect) {- .stay => {},- .quit => {- m.running = false;- break :batches;- },- .background => {- parkToShell(io, w, &raw);- // Full repaint after fg — the diff baseline is stale.- last_hash = 0;- if (prev.len != 0) gpa.free(prev);- prev = &.{};- },- }- }- }- if (i < n) {- const rest = n - i;- std.mem.copyForwards(u8, inbuf[0..rest], inbuf[i..n]);- pending_len = rest;- } else pending_len = 0;- // Capture operation state before it can complete between polls. Keep- // that bounded grace when a lone ESC grows into a legacy Alt prefix.- if (pending_len == 0) esc_live = false else if (!esc_live and (m.pending != null or m.bg != null)) esc_live = true;- }- // Quitting with a turn still live: cancel FIRST — Ctrl+Q (nav.zig) and the- // palette's /quit never did — then wait for the thread here, with the alt- // screen still up and a frame explaining the wait, instead of joining from- // Model.deinit after the terminal has already been handed back (#534).- if (m.pending != null or m.bg != null) {- turn.cancelTurn(&m);- bgop.cancel(&m);- m.push(.system, "■ stopping…") catch {};- const cols = @max(tty.cols(), @as(usize, 40));- const rows = @max(tty.rows(), @as(usize, 12));- if (render_mod.render(&m, gpa, cols, rows, m.now_ms)) |frame| {- defer gpa.free(frame);- paint_mod.paint(w, frame, rows, cols, &.{}, m.theme().bg, true, null) catch {};- w.flush() catch {};- } else |_| {}- const start = m.now_ms;- var forced = false;- while (!forced and (turn.quitStep(&m, m.now_ms -| start) == .wait or- bgop.quitStep(&m, m.now_ms -| start) == .wait))- {- if (tty.poll(50)) {- const got = tty.readStdin(&inbuf);- // A second Ctrl+C / Esc during the wait means "go now".- for (inbuf[0..got]) |b| {- if (b == 0x03 or b == 0x1b) forced = true;- }- }- m.now_ms = nowMs(io);- }- const elapsed = if (forced) turn.quit_drain_ms else m.now_ms -| start;- const stuck = turn.quitStep(&m, elapsed) == .abandon or bgop.quitStep(&m, elapsed) == .abandon;- if (!stuck) {- turn.finishJob(&m);- bgop.finish(&m);- } else {- turn.abandonJob(&m);- bgop.abandon(&m);- // The threads are still writing into the job and the op, so the- // process must not outlive the restore: put the terminal back with- // the same bytes the defers would have written, then leave.- if (opts.emergency_fn) |f| f(opts.turn_ctx);- w.flush() catch {};- restore_mod.emergency();- std.process.exit(0);- }- }- if (prev.len != 0) {- const vis = @import("dump.zig").visible(gpa, prev) catch prev;- defer if (vis.ptr != prev.ptr) gpa.free(vis);- traj.snap(io, m.now_ms, vis);- }-}--fn nowMs(io: Io) u64 {- return @intCast(@divTrunc(@max(@as(i128, 0), Io.Timestamp.now(io, .real).nanoseconds), 1_000_000));-}--/// Close a bracketed paste we can no longer finish. The parser latch and the-/// model flag are both cleared through the SAME event the terminal would have-/// sent, so there is exactly one teardown path (image attach, focus restore).-fn closePaste(m: *Model) void {- if (!key_mod.inPaste()) return;- key_mod.endPaste();- _ = keys.handle(m, .paste_end);-}--fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {- restore_mod.unmuteStderr(); // the shell we hand over to owns the real terminal- w.writeAll(restore_mod.seq) catch {};- w.flush() catch {};- tty.restore(raw.*);- if (builtin.os.tag != .windows) {- std.posix.raise(std.posix.SIG.TSTP) catch {};- }- raw.* = tty.enterRaw() orelse raw.*;- w.writeAll(enable_seq) catch {};- w.writeAll("\x1b]11;?\x07") catch {}; // background query -> auto light/dark (key.zig bg_report)- w.flush() catch {};- restore_mod.muteStderr(); // fullscreen again: stderr goes back to the log- _ = io;-}diff --git a/TUI/run_stall.zig b/TUI/run_stall.zigdeleted file mode 100644index 367bf21f..00000000--- a/TUI/run_stall.zig+++ /dev/null@@ -1,264 +0,0 @@-//! Input-stall policy for run.zig's read loop, parked here under the 600-line-//! ceiling.-//!-//! Everything in this file is a PURE decision about bytes that are stuck-//! mid-sequence, plus the clocks that bound how long the loop is allowed to-//! hold on to them. The rule throughout is grok-build's `XT_MAX_HOLD`: every-//! hold is bounded, because an unbounded latch is how a terminal hiccup turns-//! into a session that never accepts input again.--const std = @import("std");--pub const StallVerdict = enum { wait, escape_key, escape_pair, drop };--pub const StallCtx = struct {- /// A model turn or background operation was live when this ESC head- /// arrived. The read loop latches that fact: a fast completion between- /// quiet polls must not shorten the head's ambiguity window.- operation_live: bool = false,- /// Inside a bracketed paste: a lone ESC is far more likely to be the head- /// of the closing `CSI 201~` than the Escape key, and giving up on that- /// marker wedges the composer.- in_paste: bool = false,-};--/// ~25ms a stall. Twelve idle polls (~300ms) cover the reported 50–250ms-/// splits. A live operation waits the full bounded dropped-head recovery-/// window: cancelling sooner is irreversible if the bytes become `CSI 200~`.-const esc_grace_idle: u8 = 12;-pub const live_escape_stalls: u8 = 40; // 1s; Ctrl-C and CSI-u Esc bypass it-/// A paste marker is worth ~2s before we conclude it is never coming.-const paste_marker_stalls: u8 = 80;-/// ...but a LONE ESC inside that window gets ~300ms, not the full 2s: see-/// `stallVerdict`.-const esc_grace_paste: u8 = 12;-/// Input silence that ends a bracketed paste nothing else can close.-pub const paste_idle_ms: u64 = 2000;-/// Short exact-carry window after a lone ESC was delivered as a genuine key.-/// That ambiguity must not let the ESC glue itself onto human input for the-/// whole recovery interval. A non-lone sequence actually dropped after its-/// stall budget is stronger evidence: key_orphan retains and accumulates that-/// exact framing until `arm_window_ms`, bounded by its small head buffer.-const escape_carry_window_ms: u64 = 400;-/// How long the orphan-debris sweeper stays armed. The arm says "the loop-/// really did drop a head just now", and that claim goes stale: latched with no-/// clock at all it ate the first token of whatever the user typed NEXT, at any-/// later time (`3u apples` -> ` apples` twelve seconds after the drop). This is-/// also the full exact-head interval for a dropped non-lone sequence.-const arm_window_ms: u64 = 1000;--/// What to do with input bytes stuck mid-sequence after quiet polls (~25ms-/// each). A lone ESC is the Escape key after the #94 grace; a legacy Alt-/// prefix resolves as a genuine pair. A longer prefix is a truncated CSI/OSC-/// split by link latency (ssh/tmux):-/// delivering Escape cancelled live turns and typing the late tail sprayed-/// "2;39M"-style debris into the transcript — wait for the tail instead, and-/// only silently drop once it is clearly never coming.-pub fn stallVerdict(pending: []const u8, stalls: u8, ctx: StallCtx) StallVerdict {- if (pending.len == 0) return .wait;- if (isLegacyAltPrefix(pending)) {- const grace = if (ctx.operation_live) live_escape_stalls else esc_grace_idle;- return if (stalls >= grace) .escape_pair else .wait;- }- const lone_esc = isLoneEscape(pending);- if (ctx.in_paste and isPasteMarkerPrefix(pending)) {- // ESC is a proper prefix of `CSI 201~`, so the marker budget also- // swallowed the ONE in-band way out of a wedged paste for ~2s on every- // terminal that does not send kitty CSI-u (where Escape arrives as- // `CSI 27 u` and never looked like a marker). A lone ESC that has sat- // there through several quiet polls without growing a body is the user- // reaching for that hatch, not a terminator in flight; an ESC with- // bytes behind it still gets the full marker wait.- const grace = if (ctx.operation_live) live_escape_stalls else esc_grace_paste;- if (lone_esc and stalls >= grace) return .escape_key;- return if (stalls >= paste_marker_stalls) .drop else .wait;- }- if (lone_esc) {- const grace = if (ctx.operation_live) live_escape_stalls else esc_grace_idle;- return if (stalls >= grace) .escape_key else .wait;- }- return if (stalls >= 20) .drop else .wait;-}--pub fn isLoneEscape(pending: []const u8) bool {- return pending.len == 1 and pending[0] == 0x1b;-}--/// A legacy Alt navigation prefix: ESC ESC followed by an incomplete CSI.-pub fn isLegacyAltPrefix(pending: []const u8) bool {- if (pending.len < 2 or pending[0] != 0x1b or pending[1] != 0x1b) return false;- if (pending.len == 2) return true;- if (pending[2] != '[') return false;- for (pending[3..]) |c| if (c < 0x20 or c > 0x3f) return false;- return true;-}--/// A proper prefix of either bracketed-paste marker.-pub fn isPasteMarkerPrefix(pending: []const u8) bool {- return std.mem.startsWith(u8, "\x1b[201~", pending) or- std.mem.startsWith(u8, "\x1b[200~", pending);-}--pub fn escapeCarryExpired(now_ms: u64, stash_ms: u64) bool {- return now_ms -| stash_ms > escape_carry_window_ms;-}--pub fn armExpired(now_ms: u64, arm_ms: u64) bool {- return now_ms -| arm_ms > arm_window_ms;-}--/// A stuck CSI/OSC head that filled the read buffer is a parser wedge, not a-/// hangup. Drop it so the next `read` is not a zero-length "TTY gone" (#517).-pub fn clearFullWedge(pending_len: usize, buf_len: usize) usize {- return if (pending_len == buf_len) 0 else pending_len;-}--/// Is this read nothing but complete SGR or X10 mouse reports?-///-/// ?1003h is on by default for image-chip hover, and a pointer merely RESTING-/// over the window makes the terminal emit a motion report roughly twice a-/// second. Those bytes are not paste content and must not count as paste-/// activity: while they did, a mouse sitting still over the terminal postponed-/// the #548 idle recovery indefinitely and an unterminated paste NEVER-/// released. Deliberately strict — only whole SGR or three-byte-body X10-/// reports, so a read carrying any real pasted byte keeps the latch alive.-pub fn onlyMouseReports(bytes: []const u8) bool {- if (bytes.len == 0) return false;- var i: usize = 0;- while (i < bytes.len) {- if (i + 3 > bytes.len or bytes[i] != 0x1b or bytes[i + 1] != '[') return false;- if (bytes[i + 2] == 'M') {- if (i + 6 > bytes.len or std.mem.indexOfScalar(u8, bytes[i + 3 .. i + 6], 0x1b) != null) return false;- i += 6;- continue;- }- if (bytes[i + 2] != '<') return false;- var j = i + 3;- while (j < bytes.len and ((bytes[j] >= '0' and bytes[j] <= '9') or bytes[j] == ';')) : (j += 1) {}- if (j >= bytes.len or (bytes[j] != 'M' and bytes[j] != 'm')) return false;- i = j + 1;- }- return true;-}--test "a truncated CSI never becomes Escape or typed debris; a lone ESC still does (#94)" {- const idle: StallCtx = .{};- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 11, idle));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 12, idle));- // Split SGR mouse / kitty CSI-u: never Escape, wait for the tail...- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<65;2;3", 2, idle));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[5744", 19, idle));- // ...and silently drop once it is clearly lost, so it is never typed.- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20, idle));- // Half-arrived shapes from 1003 hover tracking — never the Escape key.- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[", 20, idle));- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1bO", 20, idle));- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("39;7", 20, idle));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("", 5, idle));-}--test "bounded lone-ESC grace covers splits without preempting live recovery (#537)" {- // Idle Escape remains ~300ms; a live call gets the full documented 1s.- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 2, .{}));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 10, .{}));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 11, .{}));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 12, .{}));- const live: StallCtx = .{ .operation_live = true };- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 16, live));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", live_escape_stalls - 1, live));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", live_escape_stalls, live));-}--test "a late body stays a sequence, never a second Escape decision (#537)" {- // Once a head has a body, the pure policy never classifies it as the- // Escape key. This is the policy half of the orphan join: run.zig/key.zig- // may carry the head until its tail arrives, but a late CSI body cannot- // cancel a turn or become typed debris through this decision point.- const live: StallCtx = .{ .operation_live = true };- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[", 2, live));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[", 8, live));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<35;80;24", 19, live));- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<35;80;24", 20, live));- // The same invariant holds while an operation is cancellable in the- // background, and while idle: only a lone ESC can become Escape.- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[", 2, .{ .operation_live = true }));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[", 2, .{}));-}--test "the genuine-Escape carry expires before it can reach a human keystroke (#530)" {- // A delivered Escape is weak evidence: its exact carry stays short even- // though narrow, self-identifying recovery remains armed for one second.- try std.testing.expect(!escapeCarryExpired(1000, 1000));- try std.testing.expect(!escapeCarryExpired(1400, 1000));- try std.testing.expect(escapeCarryExpired(1401, 1000));- try std.testing.expect(escapeCarryExpired(9000, 1000));- // A clock that never ran (no stash yet) is expired, not live.- try std.testing.expect(escapeCarryExpired(100_000, 0));-}--test "the debris arm expires too, so it can never eat a later keystroke" {- // Unbounded, the arm swallowed the first token of whatever was typed next- // at ANY later time — `3u apples` reached the composer as ` apples` twelve- // seconds after the head was dropped.- try std.testing.expect(!armExpired(1000, 1000));- try std.testing.expect(!armExpired(2000, 1000));- try std.testing.expect(armExpired(2001, 1000));- try std.testing.expect(armExpired(13_000, 1000));- // Outlives the genuine-Escape carry; dropped exact framing remains live.- try std.testing.expect(escapeCarryExpired(1600, 1000) and !armExpired(1600, 1000));-}--test "a paste marker is never abandoned on the #94 timescale (#532)" {- // Both give-up routes strand `in_paste` forever, so every prefix of either- // marker gets ~2s — including a lone ESC on the #94 timescale.- const p: StallCtx = .{ .in_paste = true };- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 2, p));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[201", 20, p));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[20", 79, p));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[200", 79, p));- // Then give up for real — run.zig synthesizes the paste_end on that drop.- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[201", 80, p));- // Anything that is not a marker prefix keeps the ordinary budget.- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20, p));- try std.testing.expect(isPasteMarkerPrefix("\x1b[201~"));- try std.testing.expect(!isPasteMarkerPrefix("\x1b[202"));-}--test "a resting mouse is not paste activity (#548 starvation)" {- // Hover reports under ?1003h arrive while the pointer does not move at all.- try std.testing.expect(onlyMouseReports("\x1b[<35;80;24M"));- try std.testing.expect(onlyMouseReports("\x1b[<35;80;24M\x1b[<35;80;24M"));- try std.testing.expect(onlyMouseReports("\x1b[<0;4;9m"));- try std.testing.expect(onlyMouseReports("\x1b[M !!\x1b[M#%%"));- // Anything that could be paste content keeps the latch's clock running.- try std.testing.expect(!onlyMouseReports(""));- try std.testing.expect(!onlyMouseReports("hello"));- try std.testing.expect(!onlyMouseReports("\x1b[<35;80;24Mhello"));- try std.testing.expect(!onlyMouseReports("hello\x1b[<35;80;24M"));- try std.testing.expect(!onlyMouseReports("\x1b[<35;80;24")); // split: not complete- try std.testing.expect(!onlyMouseReports("\x1b[M !"));- try std.testing.expect(!onlyMouseReports("\x1b[M \x1b[201~"));- try std.testing.expect(!onlyMouseReports("\x1b[201~"));- try std.testing.expect(!onlyMouseReports("\x1b[A"));-}--test "a lone ESC inside a latched paste stays bounded" {- // Idle paste hatch: ~300ms. With live work, marker ambiguity wins for 1s.- const p: StallCtx = .{ .in_paste = true };- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 11, p));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 12, p));- const live: StallCtx = .{ .in_paste = true, .operation_live = true };- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", live_escape_stalls - 1, live));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", live_escape_stalls, live));- // An ESC with a body behind it is still a terminator in flight: full wait.- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[", 12, p));- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[201", 79, p));- try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 12, .{}));-}--test "a buffer-filling parser wedge is dropped, not treated as hangup (#517)" {- try std.testing.expectEqual(@as(usize, 0), clearFullWedge(4096, 4096));- try std.testing.expectEqual(@as(usize, 12), clearFullWedge(12, 4096));- try std.testing.expectEqual(@as(usize, 0), clearFullWedge(0, 4096));- try std.testing.expectEqual(@as(usize, 1), clearFullWedge(1, 2));-}diff --git a/TUI/run_tests.zig b/TUI/run_tests.zigdeleted file mode 100644index 3a847457..00000000--- a/TUI/run_tests.zig+++ /dev/null@@ -1,115 +0,0 @@-//! run.zig runtime-loop contract tests.--const std = @import("std");--const restore_mod = @import("restore.zig");-const run = @import("run.zig");-const stall = @import("run_stall.zig");-const heal_interval_ms = run.heal_interval_ms;--test "run loop enables click+hover tracking and bracketed paste" {- const src = @embedFile("run.zig");- const mouse_on = [_]u8{ '?', '1', '0', '0', '0', 'h' };- const sgr_on = [_]u8{ '?', '1', '0', '0', '6', 'h' };- const paste_on = [_]u8{ '?', '2', '0', '0', '4', 'h' };- // 1003 (motion) is back ON for image-chip hover previews. The v0.0.255- // leak (raw SGR typed into the thinking line) stays pinned by key.zig's- // flood/orphan tests; the restore seq must pop it so the shell never- // inherits motion tracking.- const hover_on = [_]u8{ '?', '1', '0', '0', '3', 'h' };- const hover_off = [_]u8{ '?', '1', '0', '0', '3', 'l' };- const kitty_on = [_]u8{ '>', '1', '1', 'u' };- const wrap_off = [_]u8{ '?', '7', 'l' };- try std.testing.expect(std.mem.indexOf(u8, src, &mouse_on) != null);- try std.testing.expect(std.mem.indexOf(u8, src, &sgr_on) != null);- try std.testing.expect(std.mem.indexOf(u8, src, &paste_on) != null);- try std.testing.expect(std.mem.indexOf(u8, src, &hover_on) != null);- try std.testing.expect(std.mem.indexOf(u8, restore_mod.seq, &hover_off) != null);- try std.testing.expect(std.mem.indexOf(u8, src, &[_]u8{ '?', '1', '0', '0', '7', 'h' }) == null);- try std.testing.expect(std.mem.indexOf(u8, src, &kitty_on) != null);- try std.testing.expect(std.mem.indexOf(u8, src, &wrap_off) != null);- try std.testing.expect(std.mem.indexOf(u8, src, "imgproto.clear_all") != null);- try std.testing.expect(std.mem.indexOf(u8, src, "imgproto.sync(") != null);- // The idle paste sweep must DISCARD whatever was stuck mid-sequence before- // the stall path below can see it. Leaving it there let a lone pending ESC- // become the Escape KEY the instant `in_paste` cleared, cancelling a live- // turn and wiping the composer with no keypress at all.- const sweep_at = std.mem.indexOf(u8, src, "closePaste(&m);").?;- const stall_at = std.mem.indexOfPos(u8, src, sweep_at, "esc_stall +|= 1").?;- const sweep_block = src[sweep_at..stall_at];- try std.testing.expect(std.mem.indexOf(u8, sweep_block, "pending_len = 0;") != null);- try std.testing.expect(std.mem.indexOf(u8, sweep_block, ".dropped") != null);- // Both unbounded holds are bounded: a resting mouse must not keep the paste- // latch alive, and the debris arm must go stale on its own clock.- try std.testing.expect(std.mem.indexOf(u8, src, "if (!stall.onlyMouseReports(") != null);- try std.testing.expect(std.mem.indexOf(u8, src, "if (stall.armExpired(") != null);- const drop_at = std.mem.indexOf(u8, src, ".drop => {").?;- try std.testing.expect(std.mem.indexOfPos(u8, src, drop_at, "key_mod.abandonSequence(") != null);-}--// The stall-verdict / carry-window / arm-window battery lives beside the-// policy it pins, in run_stall.zig; the frame painter's own battery (residue,-// glyph torture, row-style isolation, the self-heal) lives in paint.zig.--test "one tick drains the whole tty, coalesces the wheel, and paints once" {- const src = @embedFile("run.zig");- // (a) Every byte the tty already holds joins THIS tick before dispatch —- // one read per frame is what made momentum scrolling lag and then jump.- const read_at = std.mem.indexOf(u8, src, "const got = tty.readStdin(").?;- const dispatch_at = std.mem.indexOfPos(u8, src, read_at, "batch.next(inbuf[0..n]").?;- const drain = src[read_at..dispatch_at];- try std.testing.expect(std.mem.indexOf(u8, drain, "while (filled < inbuf.len and tty.poll(0))") != null);- // ...bounded, or an endless flood would be drained and never painted.- try std.testing.expect(std.mem.indexOf(u8, drain, "pacing.drainExpired(") != null);- // (b) The batch is applied as one unit and the wheel run goes through the- // same door a single report does.- try std.testing.expect(std.mem.indexOf(u8, src, "@import(\"input_batch.zig\").Decoder") != null);- try std.testing.expect(std.mem.indexOf(u8, src, "keys.handleBatchItem(&m, item)") != null);- // (c) The frame is gated on the budget, and the gate sits BEFORE the render- // — gating only the paint would still pay for composing every frame.- const gate_at = std.mem.indexOf(u8, src, "pacing.shouldPaint(").?;- try std.testing.expect(gate_at < std.mem.indexOf(u8, src, "render_mod.render(&m, gpa, cols, rows").?);- // ...and the storm signal is a non-blocking poll OR the arrival RATE, so a- // fast loop that reads each report the instant it lands still paces, and a- // quiet one never waits on the budget for a single flick.- try std.testing.expect(std.mem.indexOf(u8, src, "const more_pending = tty.poll(0);") != null);- try std.testing.expect(std.mem.indexOf(u8, src, "last_input_ms = m.now_ms;") != null);- // A deferred frame comes back through the poll timeout the loop already- // has, and only when one is actually owed.- try std.testing.expect(std.mem.indexOf(u8, src, "if (!painted and pending_len == 0) wait = pacing.waitCap(") != null);-}--test "a wheel storm cannot be mistaken for paste activity" {- // The drained buffer is handed to onlyMouseReports whole: a storm is all- // complete SGR reports, so it never refreshes the paste clock, and a read- // carrying one real keystroke still does.- var buf: [512]u8 = undefined;- var n: usize = 0;- while (n + 10 <= 400) : (n += 10) @memcpy(buf[n .. n + 10], "\x1b[<65;4;4M");- try std.testing.expect(stall.onlyMouseReports(buf[0..n]));- buf[n] = 'k';- try std.testing.expect(!stall.onlyMouseReports(buf[0 .. n + 1]));-}--test "the loop self-heals: a resize EVENT and a periodic sweep force a repaint" {- const src = @embedFile("run.zig");- // A SIGWINCH that starts and ends on the same dimensions is invisible to a- // dimension comparison, and one that lands between tty.cols() and the- // paint leaves the diff baseline describing a screen the terminal has- // already reflowed. Both are covered by the EVENT.- try std.testing.expect(std.mem.indexOf(u8, src, "restore_mod.takeResized()") != null);- // ...and anything else that writes over us (an async kitty image delete,- // a terminal-side redraw) is repaired on the heartbeat, which must be able- // to run even when the frame hash has not moved.- try std.testing.expect(std.mem.indexOf(u8, src, "hash != last_hash or heal") != null);- try std.testing.expect(heal_interval_ms > 0);- // ...and the self-heal must never be served by the scroll fast path, whose- // whole point is to SKIP rows that are already correct — which is exactly- // the set of rows a heal exists to rewrite. Same for `full`, which folds in- // kitty graphics (pixels do not move when cells scroll), resize and theme.- try std.testing.expect(std.mem.indexOf(u8, src, "if (full or heal or gfx.on or want_gfx) null else m.paint_hint") != null);- // Theme bg is painted per row, not baked into the frame. Blank rows are- // byte-identical across themes, so a diff paint would strand the old- // canvas — /theme and the startup OSC-11 flip both force a full paint.- try std.testing.expect(std.mem.indexOf(u8, src, "m.theme_id != prev_theme") != null);-}diff --git a/TUI/sanitize.zig b/TUI/sanitize.zigdeleted file mode 100644index 06566b7b..00000000--- a/TUI/sanitize.zig+++ /dev/null@@ -1,78 +0,0 @@-//! History-entry sanitizer: drop terminal controls and citation PUA (#805).--const std = @import("std");-const theme_mod = @import("theme.zig");--fn citeSkip(text: []const u8, i: usize) usize {- if (i + 2 >= text.len) return i;- if (text[i] != 0xEE or text[i + 1] != 0x88) return i;- const b = text[i + 2];- if (b < 0x80 or b > 0x82) return i;- if (b != 0x80) return i + 3;- var j = i + 3;- while (j + 2 < text.len) {- if (text[j] == 0xEE and text[j + 1] == 0x88 and text[j + 2] == 0x81) return j + 3;- j += 1;- }- return text.len;-}--fn citeContains(text: []const u8) bool {- var i: usize = 0;- while (i < text.len) : (i += 1) {- if (citeSkip(text, i) != i) return true;- }- return false;-}--/// History entries render verbatim inside the alt screen — drop escape-/// sequences, stray C0, and provider citation annotations a model may carry.-pub fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {- var dirty = citeContains(text);- if (!dirty) {- for (text) |c| {- if (c == 0x1b or c == 0x7f or (c < 0x20 and c != '\n' and c != '\t')) {- dirty = true;- break;- }- }- }- if (!dirty) return alloc.dupe(u8, text);- var out = std.array_list.Managed(u8).init(alloc);- errdefer out.deinit();- var i: usize = 0;- while (i < text.len) {- const skipped = citeSkip(text, i);- if (skipped != i) {- i = skipped;- continue;- }- const c = text[i];- if (c == 0x1b) {- i = theme_mod.skipEsc(text, i);- continue;- }- if ((c < 0x20 and c != '\n' and c != '\t') or c == 0x7f) {- i += 1;- continue;- }- try out.append(c);- i += 1;- }- return out.toOwnedSlice();-}--test "citation control markup is stripped from TUI history (#805)" {- const a = std.testing.allocator;- const raw = "hello\u{E200}cite\u{E202}turn0view0\u{E201} world";- const got = try sanitized(a, raw);- defer a.free(got);- try std.testing.expectEqualStrings("hello world", got);-}--test "C0 still drops without touching letters" {- const a = std.testing.allocator;- const got = try sanitized(a, "safe\x07text\rhere");- defer a.free(got);- try std.testing.expectEqualStrings("safetexthere", got);-}diff --git a/TUI/scrollback.zig b/TUI/scrollback.zigdeleted file mode 100644index c9af1b65..00000000--- a/TUI/scrollback.zig+++ /dev/null@@ -1,594 +0,0 @@-//! Conversation scrollback. ANSI only. render() is the uncached full layout-//! that layout_cache.zig memoizes per block and that its tests hold it to.-//! Consecutive tool rows collapse into a Grok-style summary until expanded.--const std = @import("std");--const app = @import("app.zig");-const diff_mod = @import("diff.zig");-const foldhdr = @import("foldhdr.zig");-const glyphs = @import("glyphs.zig");-const livetail = @import("livetail.zig");-const theme_mod = @import("theme.zig");-const tool_card = @import("tool_card.zig");-const Model = app.Model;--pub const liveHasBytes = livetail.liveHasBytes;-pub const liveTail = livetail.liveTail;-pub const strip = livetail.strip;-pub const tail = livetail.tail;--/// Soft pulse so a live turn reads as motion, not a lone spinner glyph.-pub fn render(self: *const Model, a: std.mem.Allocator, width: usize, now_ms: u64) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- var i: usize = 0;- var first = true;- while (i < self.history.items.len) {- const e = self.history.items[i];- if (e.kind == .tool) {- const run = self.toolRun(i);- 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;- }- // Once tokens are on the wire the pending "Thinking" row is a second- // spinner sitting on the answer. Skip it; liveAnswer() is the reply.- if (e.kind == .pending and liveHasBytes(self)) {- i += 1;- continue;- }- if (!first) try out.append('\n');- first = false;- const selected = self.focus == .scrollback and i == self.selected;- try out.appendSlice(try row(self, a, userNo(self, i), e, width, now_ms, selected));- i += 1;- }- if (self.pending) |job| {- if (!self.cancel_requested) {- const raw_bash = job.raw.len.load(.acquire) > 0;- const src = if (raw_bash) &job.raw else &job.stream;- if (src.snapshot(a)) |live| {- if (!first) try out.append('\n');- first = false;- try out.appendSlice(try liveAnswer(self, a, live, raw_bash, width, now_ms));- }- if (self.steer_queue.items.len > 0) {- if (!first) try out.append('\n');- try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try std.fmt.allocPrint(a, " ↳ {d} queued · empty Enter sends now", .{self.steer_queue.items.len})));- }- }- }- return out.items;-}--/// Mid-relative visual row → history index (collapsed group maps to its start).-pub fn indexAtVisual(self: *const Model, visual_row: usize, width: usize) ?usize {- var arena = std.heap.ArenaAllocator.init(self.alloc);- defer arena.deinit();- const a = arena.allocator();- var v: usize = 0;- var i: usize = 0;- while (i < self.history.items.len) {- if (self.history.items[i].kind == .tool) {- const run = self.toolRun(i);- 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;- continue;- }- if (self.history.items[i].kind == .pending and liveHasBytes(self)) {- i += 1;- continue;- }- const s = row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "";- const lines = lineCount(s);- if (visual_row >= v and visual_row < v + lines) return i;- v += lines;- i += 1;- }- return null;-}--/// Total visual rows of the transcript at `width` (mirrors render()).-pub fn totalVisualLines(self: *const Model, width: usize) usize {- var arena = std.heap.ArenaAllocator.init(self.alloc);- defer arena.deinit();- const text = render(self, arena.allocator(), width, self.now_ms) catch return 0;- if (text.len == 0) return 0; // render.zig pops the empty tail; agree with it- return lineCount(text);-}--/// First visual row of entry `idx` (a collapsed group maps to its start).-pub fn visualOfIndex(self: *const Model, idx: usize, width: usize) ?usize {- var arena = std.heap.ArenaAllocator.init(self.alloc);- defer arena.deinit();- const a = arena.allocator();- var v: usize = 0;- var i: usize = 0;- while (i < self.history.items.len) {- if (self.history.items[i].kind == .tool) {- const run = self.toolRun(i);- if (idx >= run.start and idx < run.end) return v;- v += lineCount(runVisual(self, a, run.start, run.end, width, self.now_ms) catch "");- i = run.end;- continue;- }- if (self.history.items[i].kind == .pending and liveHasBytes(self)) {- i += 1;- continue;- }- if (i == idx) return v;- v += lineCount(row(self, a, userNo(self, i), self.history.items[i], width, self.now_ms, false) catch "");- i += 1;- }- return null;-}--/// The last user prompt whose first visual row sits strictly above-/// `top_line` — the grok sticky-header candidate. Same row math as-/// visualOfIndex so the pin agrees with what the viewport actually shows.-pub fn stickyUserAbove(self: *const Model, top_line: usize, width: usize) ?[]const u8 {- if (top_line == 0) return null;- var arena = std.heap.ArenaAllocator.init(self.alloc);- defer arena.deinit();- const a = arena.allocator();- var best: ?[]const u8 = null;- var v: usize = 0;- var i: usize = 0;- while (i < self.history.items.len and v < top_line) {- const e = self.history.items[i];- if (e.kind == .tool) {- const run = self.toolRun(i);- v += lineCount(runVisual(self, a, run.start, run.end, width, self.now_ms) catch "");- i = run.end;- continue;- }- if (e.kind == .pending and liveHasBytes(self)) {- i += 1;- continue;- }- if (e.kind == .user and v < top_line) best = e.text;- v += lineCount(row(self, a, userNo(self, i), e, width, self.now_ms, false) catch "");- i += 1;- }- return best;-}--pub fn lineCount(s: []const u8) usize {- if (s.len == 0) return 1;- return std.mem.count(u8, s, "\n") + 1;-}--/// 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.-/// 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 out.items;-}--/// 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();- 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 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);- 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;-}--pub fn row(self: *const Model, a: std.mem.Allocator, user_no: u32, e: app.Entry, width: usize, now_ms: u64, selected: bool) ![]const u8 {- const th = self.theme();- const mark: []const u8 = switch (e.kind) {- .user => "",- .assistant => glyphs.assistant,- .tool => glyphs.tool,- .system => glyphs.system,- .err => glyphs.assistant,- .pending => thinkingGlyph(now_ms),- };- const color: []const u8 = switch (e.kind) {- .user => th.text,- .assistant, .pending => th.accent,- .tool, .system => th.muted,- .err => th.error_fg,- };- const raw = if (e.kind == .pending)- // A background engine op (/compact, !cmd) names itself; a model turn- // pushes an empty row and gets the generic label.- (if (e.text.len > 0) e.text else thinkingLabel(now_ms))- else if (e.kind == .tool)- try tool_card.toolTitle(a, e, e, now_ms)- else if (e.folded)- firstLine(e.text)- else- e.text;- const body = switch (e.kind) {- .assistant => try @import("markdown.zig").renderThemed(a, raw, th, width -| 4), // the " ● " gutter costs 4 cols- .user => try @import("markdown.zig").renderUser(a, raw, th.accent, th.text),- else => raw,- };- const sel = glyphs.frame(&glyphs.row_mark, @intFromBool(!selected));- if (e.kind == .user) {- const line = try std.fmt.allocPrint(a, "{s}{s}#{d}{s} {s}", .{ sel, th.muted, user_no, theme_mod.reset, body });- return theme_mod.wrapPreferWords(a, line, width);- }- if (e.kind == .pending) {- const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, th.accent, thinkingGlyph(now_ms), theme_mod.reset, th.muted, body, theme_mod.reset });- return theme_mod.wrapPreferWords(a, line, width);- }- const body_fg = if (e.kind == .err) th.error_fg else th.text;- const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body_fg, body, theme_mod.reset });- // Break on a SPACE where there is one: a system row is prose nothing- // pre-wrapped, and at 60 columns the usage line split "$0.0000" into- // "$0.0" and "000" — a different number on each row.- return theme_mod.wrapPreferWords(a, line, width);-}--fn userNo(self: *const Model, idx: usize) u32 {- var n: u32 = 0;- var i: usize = 0;- while (i <= idx and i < self.history.items.len) : (i += 1) {- if (self.history.items[i].kind == .user) n += 1;- }- return if (n == 0) 1 else n;-}--// 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;--const toolTitle = tool_card.toolTitle;--/// The one-line body under a tool card: the outcome's useful detail.-fn toolPreview(e: app.Entry) ?[]const u8 {- const t = e.tool orelse return null;- if (!t.done or t.detail.len == 0) return null;- return t.detail;-}--pub fn toolVisual(- self: *const Model,- a: std.mem.Allocator,- t: usize,- end: usize,- width: usize,- now_ms: u64,- selected: bool,-) ![]const u8 {- const e = self.history.items[t];- const paired = t + 1 < end and isStartTool(e) and isDoneTool(self.history.items[t + 1]);- if (!paired) return row(self, a, 0, e, width, now_ms, selected); // a tool row is never numbered- return toolCard(a, self.theme(), e, self.history.items[t + 1], selected, width, now_ms);-}--fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, call: app.Entry, outcome: app.Entry, selected: bool, width: usize, now_ms: u64) ![]const u8 {- const sel = glyphs.frame(&glyphs.row_mark, @intFromBool(!selected));- const title = try toolTitle(a, call, outcome, now_ms);- const preview = toolPreview(outcome);- const head = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}", .{ sel, if (selected) th.accent else th.muted, glyphs.tool, theme_mod.reset, th.text, title });- if (preview == null) return theme_mod.wrapToWidth(a, head, width);- if (diff_mod.looksLikeUnified(preview.?)) return std.fmt.allocPrint(a, "{s}\n{s}", .{ try theme_mod.wrapToWidth(a, head, width), try diff_mod.renderThemed(a, preview.?, th, width) });- const body = try std.fmt.allocPrint(a, "{s}{s}│ {s}{s}", .{ sel, th.muted, preview.?, theme_mod.reset });- return std.fmt.allocPrint(a, "{s}\n{s}", .{ try theme_mod.wrapToWidth(a, head, width), try theme_mod.wrapToWidth(a, body, width) });-}--fn thinkingGlyph(now_ms: u64) []const u8 {- // A soft 1s blink on the PENDING row only. A fully static frame made- // run.zig's hash-diff suppress every paint for a background op's whole- // duration — 8s of literally zero terminal output read as a freeze. One- // changing glyph on one line keeps the paints flowing while historical- // rows stay byte-identical (the earlier full-transcript pulse bug). The- // frames come from the registry, which pins each to ONE column so the- // label beside them never steps sideways as they tick (glyphs.zig).- return glyphs.frame(&glyphs.thinking, now_ms / 500);-}--fn thinkingLabel(now_ms: u64) []const u8 {- _ = now_ms;- // Grok: static "Thinking" — motion is only the one-column blink.- return "Thinking";-}--fn firstLine(s: []const u8) []const u8 {- if (std.mem.indexOfScalar(u8, s, '\n')) |i| return s[0..i];- return s;-}--/// The growing answer: assistant chrome + themed markdown, not a muted-/// 8-line clip under Thinking. finishJob then swaps this for the settled row.-pub fn liveAnswer(self: *const Model, a: std.mem.Allocator, live: []const u8, raw_bash: bool, width: usize, now_ms: u64) ![]const u8 {- const clean = livetail.strip(a, live);- if (clean.len == 0) return "";- if (raw_bash) return theme_mod.paint(a, self.theme().muted, try livetail.tail(a, clean, width, 4));- const fake: app.Entry = .{ .kind = .assistant, .text = clean };- return row(self, a, 0, fake, width, now_ms, false);-}--test "firstLine stops at newline" {- try std.testing.expectEqualStrings("ab", firstLine("ab\ncd"));-}--test "thinking animation is a one-column blink plus a static Thinking" {- try std.testing.expectEqualStrings("Thinking", thinkingLabel(0));- try std.testing.expectEqualStrings(thinkingLabel(0), thinkingLabel(320));- try std.testing.expectEqualStrings(glyphs.thinking[0], thinkingGlyph(0));- // The glyph must actually FLICKER across a half-period, and be stable- // within one — a fully static pending row suppressed every paint for a- // background op's whole duration (verified live: 8s of zero output).- try std.testing.expectEqualStrings(thinkingGlyph(0), thinkingGlyph(140));- try std.testing.expect(!std.mem.eql(u8, thinkingGlyph(0), thinkingGlyph(500)));-}--test "a live turn never pulses or shifts historical rows" {- const engine = @import("engine.zig");- 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 });- try m.push(.assistant, "done");- try m.push(.pending, "");- var sbuf: [16]u8 = undefined;- var none: [0]engine.Turn = .{};- var job: engine.Job = .{- .gpa = std.testing.allocator,- .history = &none,- .params = .{},- .stream = .{ .buf = &sbuf },- };- m.pending = &job;- defer m.pending = null;- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- 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, "Ran bash") != null) {- saw_summary = true;- try std.testing.expect(std.mem.indexOf(u8, ln, glyphs.thinking[0]) == null);- }- }- try std.testing.expect(saw_summary);- try std.testing.expectEqualStrings(t0, t140);- // Across a blink half-period exactly ONE line — the pending row — may- // 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, 200_500);- var it0 = std.mem.splitScalar(u8, t0, '\n');- var it5 = std.mem.splitScalar(u8, t500, '\n');- var changed: usize = 0;- while (it0.next()) |a0| {- const a5 = it5.next() orelse "";- if (!std.mem.eql(u8, a0, a5)) {- changed += 1;- try std.testing.expect(std.mem.indexOf(u8, a0, "Thinking") != null);- }- }- 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.- try std.testing.expectEqualStrings("memo", displayName("mcp__codedbpro__memo"));- try std.testing.expectEqualStrings("faster_search", displayName("mcp__codedbpro__faster_search"));- try std.testing.expectEqualStrings("bash", displayName("bash"));- try std.testing.expectEqualStrings("read", displayName("read_file"));-}--test {- _ = @import("scrollback_tests.zig");-}--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();- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- try m.push(.assistant, "done");- 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, "#1") != 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);- // 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" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "Hey. I am in /Users/blackfloofie/codegraff on a very long branch name so this must wrap");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try render(&m, arena.allocator(), 40, 0);- var it = std.mem.splitScalar(u8, text, '\n');- while (it.next()) |ln| {- try std.testing.expect(theme_mod.visibleLen(ln) <= 40);- }-}--test "the header's visual row maps back to the tool group" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- 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 text = try render(&m, arena.allocator(), 80, 0);- var vis: usize = 0;- var hit: ?usize = null;- var it = std.mem.splitScalar(u8, text, '\n');- while (it.next()) |ln| : (vis += 1) {- if (std.mem.indexOf(u8, ln, "Ran bash") != null) {- hit = vis;- break;- }- }- try std.testing.expect(hit != null);- try std.testing.expectEqual(@as(usize, 1), indexAtVisual(&m, hit.?, 80).?);-}--test "collapsed search run reads as a search, in past tense" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.pushTool(.{ .name = "grep", .detail = "needle" });- try m.pushTool(.{ .name = "grep", .detail = "3 hits", .done = true });- 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 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);- try std.testing.expect(std.mem.indexOf(u8, open, "needle") != null);-}--test "expanded read card shows the path and preview" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.pushTool(.{ .name = "read_file", .detail = "src/foo.zig" });- try m.pushTool(.{ .name = "read_file", .detail = "const std = @import(\"std\");", .done = true });- m.toggleToolGroup(0);- 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, "src/foo.zig") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "const std") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "│") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "Called") == null);-}diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zigdeleted file mode 100644index 78eb6f7a..00000000--- a/TUI/scrollback_tests.zig+++ /dev/null@@ -1,300 +0,0 @@-//! Behavioral tests for the field-backed tool transcript (#551). They drive-//! `scrollback.render` through the public Model, so they hold the CONTRACT —-//! what a reader sees — rather than any one helper's shape. Split out of-//! scrollback.zig for the 600-line ceiling.--const std = @import("std");--const app = @import("app.zig");-const glyphs = @import("glyphs.zig");-const scrollback = @import("scrollback.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--/// The COLUMN `needle` starts at on its rendered row — SGR and glyph widths-/// resolved, which is the only measure a terminal agrees with.-fn labelCol(text: []const u8, needle: []const u8) ?usize {- var it = std.mem.splitScalar(u8, text, '\n');- while (it.next()) |ln| {- const at = std.mem.indexOf(u8, ln, needle) orelse continue;- return theme_mod.visibleLen(ln[0..at]);- }- return null;-}--test "the pending label holds its column across every blink frame" {- // grok-build's rule: animated chrome is exactly one column, so the label- // and any timer beside it never step sideways as the animation ticks.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.pending, "");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- var col: ?usize = null;- var seen = std.mem.zeroes([glyphs.thinking.len]bool);- // Six samples across three blink periods: more than the four frames the- // live pty proof watches, and enough to see both frames twice.- for ([_]u64{ 0, 500, 1000, 1500, 2000, 2500 }) |now_ms| {- const text = try scrollback.render(&m, arena.allocator(), 80, now_ms);- const at = labelCol(text, "Thinking") orelse return error.NoPendingLabel;- if (col) |want| try std.testing.expectEqual(want, at) else col = at;- for (glyphs.thinking, 0..) |f, i| {- if (std.mem.indexOf(u8, text, f) != null) seen[i] = true;- }- }- for (seen) |s| try std.testing.expect(s); // it really animated- // Two columns of selection field, one of glyph, one of space.- try std.testing.expectEqual(@as(usize, 4), col.?);-}--test "a settled row's body starts in the same column the pending row used" {- // The gutter is shared: the blink is replaced by a static mark when the- // turn lands, and a mark of a different width would jerk the whole answer- // sideways at exactly the moment the reader starts reading it.- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- var live_m: Model = undefined;- live_m.setup(std.testing.allocator);- defer live_m.deinit();- try live_m.push(.pending, "");- const live = try scrollback.render(&live_m, arena.allocator(), 80, 0);- const pending_col = labelCol(live, "Thinking") orelse return error.NoPendingLabel;- var done_m: Model = undefined;- done_m.setup(std.testing.allocator);- defer done_m.deinit();- try done_m.push(.assistant, "Landed");- const done = try scrollback.render(&done_m, arena.allocator(), 80, 0);- try std.testing.expectEqual(pending_col, labelCol(done, "Landed") orelse return error.NoBody);-}--test "classification reads the tool name, not the whole row (#551)" {- // `bash` running a command that merely mentions a search word is a call,- // not a search — the old whole-line substring test got this wrong.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.pushTool(.{ .name = "bash", .detail = "grep -rn needle | head" });- try m.pushTool(.{ .name = "bash", .detail = "found 3", .done = true });- 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, "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);- const open = try scrollback.render(&m, arena.allocator(), 100, 0);- try std.testing.expect(std.mem.indexOf(u8, open, "grep -rn needle | head") != null);-}--test "an mcp run summarises as MCP tools, off the name prefix" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "note" });- try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "saved", .done = true });- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try scrollback.render(&m, arena.allocator(), 80, 0);- // 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)" {- // The phantom-row bug: turn.zig used to harvest any streamed line starting- // "✓ " into the transcript as a tool. Answer text is answer text.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "did it work?");- try m.push(.assistant, "✓ all three checks passed");- 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, "all three checks passed") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "Called") == null);- for (m.history.items) |e| try std.testing.expect(e.kind != .tool);-}--test "a legacy text-only tool row still renders (session migration)" {- // Rows restored from a session written before the typed contract carry no- // fields. They must still show up — just without pairing or a preview.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.tool, "⚙ bash");- try m.push(.tool, "✓ bash | ok");- for (m.history.items) |e| try std.testing.expect(e.tool == null);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const folded = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, folded, "Called 2") != null);- m.toggleToolGroup(0);- const open = try scrollback.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, "✓ bash | ok") != null);-}--test "a failed call is marked, a refused one is marked differently" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.pushTool(.{ .name = "bash", .detail = "false" });- try m.pushTool(.{ .name = "bash", .detail = "exit 1", .done = true, .is_error = true });- try m.pushTool(.{ .name = "write_file", .detail = "/etc/passwd" });- try m.pushTool(.{ .name = "write_file", .detail = "refused by plan mode", .done = true, .is_error = true, .denied = true });- m.toggleToolGroup(0);- 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, "✗ bash") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "⊘ write") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "refused by plan mode") != null);-}--test "an edit result that is a unified diff renders banded, not quoted (#diff)" {- const diff = @import("diff.zig");- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const patch = "@@ -1,2 +1,2 @@\n const keep = 0;\n-const old = 1;\n+const new = 2;";- try m.pushTool(.{ .name = "edit_file", .detail = "TUI/run.zig" });- try m.pushTool(.{ .name = "edit_file", .detail = patch, .done = true });- m.toggleToolGroup(0);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const th = m.theme();- const text = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, text, diff.addBg(false)) != null);- try std.testing.expect(std.mem.indexOf(u8, text, diff.delBg(false)) != null);- // Banded, so the quoted-body rail is not used for this card.- try std.testing.expect(std.mem.indexOf(u8, text, "│ @@") == null);- var it = std.mem.splitScalar(u8, text, '\n');- while (it.next()) |ln| {- if (std.mem.indexOf(u8, ln, diff.delBg(false)) == null) continue;- // Every banded row closes: the card's own rows and the transcript- // under it must not inherit the wash.- try std.testing.expect(std.mem.endsWith(u8, ln, theme_mod.reset));- try std.testing.expect(std.mem.indexOf(u8, ln, th.bg) != null);- }- // A plain result is untouched — still the quoted body. It needs its own- // run, or the toggle below folds the diff card with it.- try m.push(.assistant, "and then");- try m.pushTool(.{ .name = "bash", .detail = "ls" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.toggleToolGroup(3);- const plain = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, plain, "│ ok") != null);-}--test "end to end: a wrapped diff keeps its band and bleeds onto nothing (#diff)" {- // The whole pipeline — markdown → row() → theme.wrapToWidth — at a width- // that forces the deletion to fold. wrapToWidth re-opens whatever SGR is- // active at a break, so a band left open at EOL is what used to paint the- // equal line (and the prose) under a long deletion.- const diff = @import("diff.zig");- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "here is the patch\n```diff\n@@ -1,2 +1,2 @@\n-const message = try std.fmt.allocPrint(gpa, \"a very long deleted line\", .{});\n const equal = 1;\n```\ntail prose");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const text = try scrollback.render(&m, arena.allocator(), 40, 0);- var it = std.mem.splitScalar(u8, text, '\n');- var del_rows: usize = 0;- var folds: usize = 0;- while (it.next()) |ln| {- try std.testing.expect(theme_mod.visibleLen(ln) <= 40);- if (std.mem.indexOf(u8, ln, diff.delBg(false)) != null) {- del_rows += 1;- folds += @intFromBool(std.mem.indexOf(u8, ln, diff.gutter) != null);- try std.testing.expect(std.mem.endsWith(u8, ln, theme_mod.reset));- continue;- }- // Nothing else in the transcript wears the deletion wash.- try std.testing.expect(std.mem.indexOf(u8, ln, "const equal") == null or- std.mem.indexOf(u8, ln, diff.delBg(false)) == null);- }- try std.testing.expect(del_rows > 1); // the deletion really did fold- try std.testing.expectEqual(del_rows - 1, folds); // every fold is marked-}--test "a long system row breaks on a space, never through a token" {- // The /usage line at 60 columns: hard wrapping cut "$0.0000" in half, so- // the transcript showed "$0.0" with "000" on the row below it.- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.system, "3 api call(s) · 300 in (0 cached) + 30 out tokens · $0.0000 · 3 subscription call(s), flat-rate");- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- for ([_]usize{ 40, 52, 60, 72 }) |w| {- const rows = try scrollback.render(&m, arena.allocator(), w, 0);- var it = std.mem.splitScalar(u8, rows, '\n');- var n: usize = 0;- while (it.next()) |ln| : (n += 1) {- try std.testing.expect(theme_mod.visibleLen(ln) <= w);- // No row may END in the middle of the amount, and none may open- // with the tail of one.- try std.testing.expect(!std.mem.endsWith(u8, std.mem.trimEnd(u8, ln, " "), "$0.0"));- }- try std.testing.expect(std.mem.indexOf(u8, rows, "$0.0000") != null);- try std.testing.expect(n > 1); // it really did wrap- }-}--test "long blockquote completion keeps every word after terminal wrapping" {- const quote = "This is a deliberately long copy-ready sentence that should continue across multiple terminal rows without losing any words from the completion.";- const source = "> " ++ quote ++ "\n\nFollowing section.";- for ([_]theme_mod.Id{ .night, .day }) |id| {- for ([_]usize{ 40, 60, 80 }) |width| {- var term: @import("sim.zig").Term = undefined;- term.init(std.testing.allocator, width, 30);- defer term.deinit();- term.model.theme_id = id;- try term.model.push(.assistant, source);- const screen = try term.screen();- defer std.testing.allocator.free(screen);- var words = std.mem.tokenizeScalar(u8, quote, ' ');- var pos: usize = 0;- while (words.next()) |word| {- const at = std.mem.indexOfPos(u8, screen, pos, word) orelse return error.MissingQuoteWord;- pos = at + word.len;- }- try std.testing.expect(std.mem.indexOfPos(u8, screen, pos, "Following section.") != null);- }- }-}--test "live prose tail paints markdown; raw bash stays plain" {- const engine = @import("engine.zig");- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- var sbuf: [256]u8 = undefined;- var rbuf: [256]u8 = undefined;- var job: engine.Job = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{ .buf = &sbuf },- .raw = .{ .buf = &rbuf },- .threaded = false,- };- job.stream.appendBytes("- first\n**bold** word\n");- try m.push(.pending, "");- m.pending = &job;- defer m.pending = null;- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const prose = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, prose, "•") != null);- try std.testing.expect(std.mem.indexOf(u8, prose, "**bold**") == null);- try std.testing.expect(std.mem.indexOf(u8, prose, "bold") != null);-- job.raw.appendBytes("**not markdown**\n- also raw\n");- const bash = try scrollback.render(&m, arena.allocator(), 80, 0);- try std.testing.expect(std.mem.indexOf(u8, bash, "**not markdown**") != null);- try std.testing.expect(std.mem.indexOf(u8, bash, "- also raw") != null);-}diff --git a/TUI/scrollbar.zig b/TUI/scrollbar.zigdeleted file mode 100644index cf169bbe..00000000--- a/TUI/scrollbar.zig+++ /dev/null@@ -1,326 +0,0 @@-//! The transcript's scroll position indicator — a one-column thumb on the right-//! edge of the viewport.-//!-//! Presentation state, end to end. The geometry comes from the band render.zig-//! already publishes on the Model (which rows scroll, which slice of the cached-//! layout they show, how many lines that layout holds); nothing here reads a-//! transcript entry, and nothing here re-parses a rendered row.-//!-//! Three rules, and every branch below serves one of them.-//!-//! * **It appears only when it means something.** Scrolled off the tail, it-//! is the only thing on screen that says how far. Parked at the tail it is-//! noise, so it fades: visible for `fade_ms` after the last scroll event-//! and then gone. A transcript that fits the viewport has no thumb at all.-//! * **It never destroys content.** The overlay replaces the LAST column of-//! the rows it covers, and it is applied to the composed frame — so when it-//! hides, the row is simply composed without it and paint.zig's row diff-//! rewrites exactly those rows. There is no separate "erase the scrollbar"-//! path that could fall out of step, and a forced full repaint of the same-//! frame lands on the same cells (paint.zig's own equality proof).-//! * **The selection band outranks it.** The band owns inverse video across-//! whole rows and captures the text under it; a thumb inside that rectangle-//! would be painted over, and — worse — would be a glyph the capture never-//! asked for. While a drag is live the thumb hides.-//!-//! The glyph is `glyphs.scroll_thumb`, registered narrow-class: one column in-//! every terminal, including one configured to draw ambiguous-width glyphs-//! double. A two-column thumb on the last column would push itself off the row.--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 thumb lingers after the last scroll event while parked at the-/// tail. Same 1.5s the copy toast uses — one dwell constant for the chrome.-pub const fade_ms: u64 = 1500;--pub const Thumb = struct {- /// Rows into the track, 0-based.- top: usize,- /// Rows tall, never zero.- len: usize,-};--/// Thumb geometry for a `track`-row gutter showing `view` of `total` visual-/// lines with `off` lines above the viewport. Null when there is nothing to-/// indicate: no track, or a transcript that already fits.-///-/// Proportional, with two clamps that matter. The length rounds to nearest but-/// never below one row, so a 20k-line transcript still shows a thumb rather-/// than nothing. The position maps `off` over `[0, total - view]` onto-/// `[0, track - len]`, so the extremes are exact: at the top the thumb sits on-/// row 0, at the tail its last row is the track's last row. An off-by-one in-/// either clamp is what makes a scrollbar look like it never quite arrives.-pub fn thumb(track: usize, view: usize, total: usize, off: usize) ?Thumb {- if (track == 0 or view == 0 or total <= view) return null;- const len = @min(track, @max(1, (track * view + total / 2) / total));- const span = track - len;- const max_off = total - view;- const at = @min(off, max_off);- const top = if (span == 0 or max_off == 0) 0 else (span * at + max_off / 2) / max_off;- return .{ .top = @min(top, span), .len = len };-}--/// Whether the thumb shows at all. `scroll` is the model's distance from the-/// tail, so a non-zero one means the user is looking at history and the-/// indicator is load-bearing; at the tail it is only the fade window.-pub fn visible(self: *const Model) bool {- if (self.sel.active or self.sel.pressed) return false;- if (!self.band.live or self.band.len == 0) return false;- if (self.band.total <= self.band.len) return false;- if (self.scroll != 0) return true;- if (self.scroll_seen_ms == 0) return false; // nothing has ever scrolled- return self.now_ms -| self.scroll_seen_ms < fade_ms;-}--/// The thumb this frame wants, or null. Split out from `paint` so the geometry-/// is testable without composing a frame.-pub fn current(self: *const Model) ?Thumb {- if (!visible(self)) return null;- return thumb(self.band.len, self.band.len, self.band.total, self.band.off);-}--/// Post-pass over the COMPOSED frame, after selection.paint: the row builders-/// stay unaware of the gutter, and the selection capture never sees the glyph.-/// Returns `frame` untouched whenever the thumb is hidden, which is what makes-/// hiding self-healing rather than a second code path.-///-/// While it IS showing, EVERY band row gets the gutter shape — content cut to-/// `width - 1`, padded to it, then the cell — and rows off the thumb carry a-/// space there. That uniformity is not cosmetic: it is what lets the painter's-/// scroll fast path keep working. A hardware scroll slides the whole row, but-/// the gutter's position comes from the scroll OFFSET and does not travel with-/// the lines under it; with every band row the same shape, scrollpaint.zig can-/// compare the content halves (which do slide) and patch the one cell that-/// does not. Reshape only the thumb rows and every notch would look like a-/// band whose rows changed for their own reasons, and the fast path would be-/// refused on exactly the frames it exists for.-pub fn paint(self: *Model, a: std.mem.Allocator, frame: []const u8, width: usize) ![]const u8 {- if (width < 2) return frame;- const t = current(self) orelse {- self.gutter_on = false;- return frame;- };- self.gutter_on = true;- const first = self.band.top + t.top;- const last = first + t.len; // exclusive- var out = std.array_list.Managed(u8).init(a);- var row: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- const style = self.theme().muted;- while (it.next()) |ln| : (row += 1) {- if (row > 0) try out.append('\n');- if (row < self.band.top or row >= self.band.top + self.band.len) {- try out.appendSlice(ln);- continue;- }- try gutterRow(&out, ln, width, style, row >= first and row < last);- }- return out.items;-}--/// One band row in the gutter shape: `content ++ pad ++ reset ++ style ++ cell`.-/// The reset is the SPLIT MARKER the painter looks for (scrollpaint.zig takes-/// everything from the last one as the cell), and it also stops the gutter's-/// colour leaking into the next row a diff paint touches.-fn gutterRow(out: *std.array_list.Managed(u8), ln: []const u8, width: usize, style: []const u8, thumb_here: bool) !void {- const keep = width - 1;- const body = theme_mod.takeCols(ln, keep);- try out.appendSlice(body);- var pad = keep - theme_mod.visibleLen(body);- while (pad > 0) : (pad -= 1) try out.append(' ');- try out.appendSlice(theme_mod.reset);- try out.appendSlice(style);- try out.appendSlice(if (thumb_here) glyphs.scroll_thumb else " ");-}--// ------------------------------------------------------------------ tests--const testing = std.testing;--test "a transcript that fits the viewport has no thumb" {- try testing.expect(thumb(10, 10, 10, 0) == null);- try testing.expect(thumb(10, 10, 3, 0) == null);- try testing.expect(thumb(0, 10, 100, 0) == null);-}--test "the thumb is proportional and its extremes are exact" {- // Half the transcript on screen: half the track, at the top and then at- // the bottom. The tail case is the one that goes wrong first — a thumb- // that stops one row short reads as "there is still more below".- const top = thumb(10, 10, 20, 0).?;- try testing.expectEqual(@as(usize, 0), top.top);- try testing.expectEqual(@as(usize, 5), top.len);- const tail = thumb(10, 10, 20, 10).?;- try testing.expectEqual(@as(usize, 5), tail.top);- try testing.expectEqual(@as(usize, 5), tail.len);- try testing.expectEqual(@as(usize, 10), tail.top + tail.len);- // ...and the middle is the middle.- const mid = thumb(10, 10, 20, 5).?;- try testing.expectEqual(@as(usize, 3), mid.top);-}--test "a huge transcript still shows one row, and it still reaches the end" {- // 20k lines in a 24-row viewport: the proportional length rounds to zero,- // and a zero-row thumb is an invisible one.- const t = thumb(24, 24, 20_000, 0).?;- try testing.expectEqual(@as(usize, 1), t.len);- try testing.expectEqual(@as(usize, 0), t.top);- const end = thumb(24, 24, 20_000, 19_976).?;- try testing.expectEqual(@as(usize, 1), end.len);- try testing.expectEqual(@as(usize, 23), end.top);-}--test "the thumb never leaves the track, at any length or offset" {- // The invariant a scrollbar is allowed exactly one of: every reachable- // offset must produce a thumb wholly inside the gutter. Off by one here- // and the glyph lands on the composer or on the row above the viewport.- for ([_]usize{ 1, 2, 3, 7, 24, 60 }) |track| {- for ([_]usize{ 1, 2, 5, 40, 999, 20_000 }) |extra| {- const total = track + extra;- var off: usize = 0;- while (off <= extra) : (off += @max(1, extra / 17)) {- const t = thumb(track, track, total, off).?;- try testing.expect(t.len >= 1);- try testing.expect(t.len <= track);- try testing.expect(t.top + t.len <= track);- }- // The very last offset, exactly.- const last = thumb(track, track, total, extra).?;- try testing.expectEqual(track, last.top + last.len);- const first = thumb(track, track, total, 0).?;- try testing.expectEqual(@as(usize, 0), first.top);- }- }-}--test "an offset past the end is clamped, never wrapped" {- const t = thumb(10, 10, 20, 999).?;- try testing.expectEqual(@as(usize, 10), t.top + t.len);-}--fn scrolledModel(m: *Model) void {- m.band = .{ .live = true, .top = 2, .len = 10, .off = 30, .total = 100 };- m.scroll = 7;- m.now_ms = 10_000;- m.scroll_seen_ms = 10_000;-}--test "the hide rules: tail fade, no band, and a live selection" {- var m: Model = undefined;- m.setup(testing.allocator);- defer m.deinit();- scrolledModel(&m);- try testing.expect(visible(&m));- // At the tail it lingers for the fade window and then goes.- m.scroll = 0;- m.now_ms = 10_000 + fade_ms - 1;- try testing.expect(visible(&m));- m.now_ms = 10_000 + fade_ms;- try testing.expect(!visible(&m));- // ...but scrolled off the tail it is unconditional, however stale.- m.scroll = 3;- m.now_ms = 10_000_000;- try testing.expect(visible(&m));- // A drag owns those rows.- m.sel.pressed = true;- try testing.expect(!visible(&m));- m.sel.pressed = false;- m.sel.active = true;- try testing.expect(!visible(&m));- m.sel.active = false;- try testing.expect(visible(&m));- // No band at all (welcome pane, an overlay body) means no gutter.- m.band.live = false;- try testing.expect(!visible(&m));- // A transcript that fits shows nothing even mid-scroll.- m.band.live = true;- m.band.total = 4;- try testing.expect(!visible(&m));- // Nothing has ever scrolled: no thumb before the user asks for one.- m.band.total = 100;- m.scroll = 0;- m.scroll_seen_ms = 0;- try testing.expect(!visible(&m));-}--test "the overlay lands on the last column of exactly the thumb's rows" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- // Track rows 2..12 of the screen, half the transcript on view, parked at- // the tail: the thumb is the bottom half of the track.- m.band = .{ .live = true, .top = 2, .len = 10, .off = 10, .total = 20 };- m.scroll = 1;- const t = current(&m).?;- try testing.expectEqual(@as(usize, 5), t.top);- try testing.expectEqual(@as(usize, 5), t.len);- var frame = std.array_list.Managed(u8).init(ar);- for (0..16) |i| {- if (i > 0) try frame.append('\n');- try frame.appendSlice("row body");- }- const width: usize = 20;- const out = try paint(&m, ar, frame.items, width);- var row: usize = 0;- var it = std.mem.splitScalar(u8, out, '\n');- while (it.next()) |ln| : (row += 1) {- const marked = std.mem.indexOf(u8, ln, glyphs.scroll_thumb) != null;- const want = row >= 7 and row < 12; // band.top + [5,10)- try testing.expectEqual(want, marked);- if (!marked) continue;- // Exactly `width` columns, with the glyph on the last one.- try testing.expectEqual(width, theme_mod.visibleLen(ln));- try testing.expect(std.mem.endsWith(u8, ln, glyphs.scroll_thumb));- }- try testing.expectEqual(@as(usize, 16), row);-}--test "hiding restores the frame byte for byte" {- // The no-residue promise, at the source: with the thumb hidden the pass is- // the identity, so the row the painter rewrites is the row the composer- // built. Nothing has to remember to erase a gutter.- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- const frame = "alpha\nbeta\ngamma\ndelta";- m.band = .{ .live = true, .top = 0, .len = 2, .off = 1, .total = 4 };- m.scroll = 1;- const shown = try paint(&m, ar, frame, 12);- try testing.expect(!std.mem.eql(u8, frame, shown));- m.scroll = 0;- m.scroll_seen_ms = 0;- const hidden = try paint(&m, ar, frame, 12);- try testing.expectEqualStrings(frame, hidden);-}--test "a row already at full width keeps its width when the thumb lands on it" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- m.band = .{ .live = true, .top = 0, .len = 1, .off = 1, .total = 8 };- m.scroll = 1;- // A full row, a short row, and a row ending in a double-width glyph that- // would straddle the gutter column.- for ([_][]const u8{ "0123456789", "ab", "12345678\u{1F409}" }) |body| {- const out = try paint(&m, ar, body, 10);- try testing.expectEqual(@as(usize, 10), theme_mod.visibleLen(out));- try testing.expect(std.mem.endsWith(u8, out, glyphs.scroll_thumb));- }-}diff --git a/TUI/scrollbar_tests.zig b/TUI/scrollbar_tests.zigdeleted file mode 100644index ce85395b..00000000--- a/TUI/scrollbar_tests.zig+++ /dev/null@@ -1,312 +0,0 @@-//! The scroll gutter and the OSC 52 clipboard channel, driven through the REAL-//! model — render.zig composing frames, keys.zig moving the viewport,-//! selection.zig capturing a drag — rather than through hand-written frames.-//!-//! Both features are post-passes over a composed frame, and both are only-//! honest if the composer, the painter and the capture agree about which rows-//! they own. That agreement is what these tests hold.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const glyphs = @import("glyphs.zig");-const keys = @import("keys.zig");-const osc52 = @import("osc52.zig");-const paint_mod = @import("paint.zig");-const render_mod = @import("render.zig");-const scrollbar = @import("scrollbar.zig");-const selection = @import("selection.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--const testing = std.testing;-const W: usize = 60;-const H: usize = 20;--fn longTranscript(m: *Model) !void {- var buf: [64]u8 = undefined;- for (0..40) |i| {- const s = try std.fmt.bufPrint(&buf, "transcript row {d} with a little body text", .{i});- try m.push(.assistant, s);- }-}--fn frameAt(m: *Model, now_ms: u64) ![]const u8 {- return render_mod.render(m, testing.allocator, W, H, now_ms);-}--/// Rows carrying the thumb, and the column it landed on.-const Marks = struct { rows: std.array_list.Managed(usize), col: usize };--fn marks(a: std.mem.Allocator, frame: []const u8) !Marks {- var out = Marks{ .rows = std.array_list.Managed(usize).init(a), .col = 0 };- var row: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (row += 1) {- const at = std.mem.indexOf(u8, ln, glyphs.scroll_thumb) orelse continue;- try out.rows.append(row);- out.col = theme_mod.visibleLen(ln[0..at]);- }- return out;-}--test "scrolling a real transcript raises a thumb inside the viewport" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try longTranscript(&m);-- // Parked at the tail, nothing has scrolled yet: no gutter.- const tail = try frameAt(&m, 1_000);- defer a.free(tail);- try testing.expect(std.mem.indexOf(u8, tail, glyphs.scroll_thumb) == null);-- // Scroll up. The thumb has to be inside the band, on the LAST column, and- // the same number of rows the geometry says.- keys.scrollBy(&m, 9);- const up = try frameAt(&m, 1_000);- defer a.free(up);- const got = try marks(ar, up);- try testing.expect(got.rows.items.len > 0);- try testing.expectEqual(W - 1, got.col);- const t = scrollbar.current(&m).?;- try testing.expectEqual(t.len, got.rows.items.len);- try testing.expectEqual(m.band.top + t.top, got.rows.items[0]);- try testing.expect(got.rows.items[got.rows.items.len - 1] < m.band.top + m.band.len);- // Contiguous — a gutter with a hole in it is a bug, not a style.- for (got.rows.items, 0..) |r, i| try testing.expectEqual(got.rows.items[0] + i, r);- // Every marked row still measures exactly the terminal width, so the- // painter's full/short branch sees what it expects.- var it = std.mem.splitScalar(u8, up, '\n');- var row: usize = 0;- while (it.next()) |ln| : (row += 1) {- if (std.mem.indexOf(u8, ln, glyphs.scroll_thumb) == null) continue;- try testing.expectEqual(W, theme_mod.visibleLen(ln));- }-}--test "the thumb travels down the track as the viewport approaches the tail" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try longTranscript(&m);- const far = try frameAt(&m, 1_000); // lays down the band- a.free(far);-- keys.scrollBy(&m, 30);- const high = try frameAt(&m, 1_000);- defer a.free(high);- keys.scrollBy(&m, -20);- const low = try frameAt(&m, 1_000);- defer a.free(low);-- const h = try marks(ar, high);- const l = try marks(ar, low);- try testing.expect(h.rows.items.len > 0 and l.rows.items.len > 0);- // Scrolled back TOWARD the tail: the thumb moved down, never up.- try testing.expect(l.rows.items[0] > h.rows.items[0]);-}--test "back at the tail the gutter fades, and the row repaints clean" {- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try longTranscript(&m);- const before = try frameAt(&m, 1_000);- defer a.free(before);- try testing.expect(std.mem.indexOf(u8, before, glyphs.scroll_thumb) == null);-- keys.scrollBy(&m, 8);- const banded = try frameAt(&m, 1_000);- defer a.free(banded);- try testing.expect(std.mem.indexOf(u8, banded, glyphs.scroll_thumb) != null);-- // Back to the tail. Inside the fade window it lingers...- keys.scrollBy(&m, -8);- const lingering = try frameAt(&m, 1_000);- defer a.free(lingering);- try testing.expect(std.mem.indexOf(u8, lingering, glyphs.scroll_thumb) != null);- // ...and past it the frame is byte-for-byte the one before any of this.- const clean = try frameAt(&m, 1_000 + scrollbar.fade_ms);- defer a.free(clean);- try testing.expect(std.mem.indexOf(u8, clean, glyphs.scroll_thumb) == null);- try testing.expectEqualStrings(before, clean);-- // The painter's side of the promise: a diff paint from the gutter frame to- // the clean one rewrites exactly the rows the thumb was on, and a FORCED- // full repaint of the clean frame carries no thumb either — so the two- // paths agree about what the screen shows.- const diff = try paintTo(ar, clean, banded, false);- try testing.expect(std.mem.indexOf(u8, diff, glyphs.scroll_thumb) == null);- const had = try marks(ar, banded);- var buf: [16]u8 = undefined;- for (had.rows.items) |r| {- const cup = try std.fmt.bufPrint(&buf, "\x1b[{d};1H", .{r + 1});- try testing.expect(std.mem.indexOf(u8, diff, cup) != null);- }- const full = try paintTo(ar, clean, clean, true);- try testing.expect(std.mem.indexOf(u8, full, glyphs.scroll_thumb) == null);-}--fn paintTo(a: std.mem.Allocator, frame: []const u8, prev: []const u8, force: bool) ![]u8 {- var aw = std.Io.Writer.Allocating.init(a);- try paint_mod.paint(&aw.writer, frame, H, W, prev, "\x1b[48;2;20;20;20m", force, null);- return aw.toOwnedSlice();-}--test "a live drag hides the gutter — the band owns those rows" {- const a = testing.allocator;- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try longTranscript(&m);- const first = try frameAt(&m, 1_000);- a.free(first);- keys.scrollBy(&m, 8);- const scrolled = try frameAt(&m, 1_000);- defer a.free(scrolled);- try testing.expect(std.mem.indexOf(u8, scrolled, glyphs.scroll_thumb) != null);- // Press and drag inside the transcript: the thumb goes, the band arrives.- const top = m.mid_origin + m.sticky_rows;- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 2), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 30, .y = @intCast(top + 4), .down = true } });- const dragging = try frameAt(&m, 1_000);- defer a.free(dragging);- try testing.expect(std.mem.indexOf(u8, dragging, "\x1b[7m") != null);- try testing.expect(std.mem.indexOf(u8, dragging, glyphs.scroll_thumb) == null);- // ...and the capture is text, with no gutter glyph smuggled into it.- try testing.expect(std.mem.indexOf(u8, m.sel_text, glyphs.scroll_thumb) == null);-}--// ---------------------------------------------------------------- OSC 52--var copied: [4096]u8 = undefined;-var copied_len: usize = 0;-var copy_ok: bool = true;--fn fakeCopy(_: ?*anyopaque, text: []const u8) bool {- if (!copy_ok) return false;- copied_len = @min(text.len, copied.len);- @memcpy(copied[0..copied_len], text[0..copied_len]);- return true;-}--fn expectPayload(seq: []const u8, want: []const u8) !void {- try testing.expect(std.mem.startsWith(u8, seq, osc52.prefix));- try testing.expect(std.mem.endsWith(u8, seq, osc52.terminator));- const body = seq[osc52.prefix.len .. seq.len - osc52.terminator.len];- const enc = std.base64.standard.Encoder;- const b64 = try testing.allocator.alloc(u8, enc.calcSize(want.len));- defer testing.allocator.free(b64);- _ = enc.encode(b64, want);- try testing.expectEqualStrings(b64, body);-}--test "a drag-copy arms OSC 52 with the exact base64 of the captured rows" {- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copy_ok = true;- copied_len = 0;- const a = testing.allocator;- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try m.push(.assistant, "OSCME alpha line");- try m.push(.assistant, "OSCME beta line");- const first = try frameAt(&m, 0);- a.free(first);- const top = m.mid_origin + m.sticky_rows;- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 1), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 40, .y = @intCast(top + 2), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 40, .y = @intCast(top + 2), .down = false } });- const after = try frameAt(&m, 0);- defer a.free(after);- // The escape is NOT in the frame: a frame is repainted, a clipboard write- // happens once.- try testing.expect(std.mem.indexOf(u8, after, osc52.prefix) == null);- const seq = selection.takeOsc52(&m);- defer a.free(seq);- try testing.expect(seq.len > 0);- try expectPayload(seq, m.sel_text);- try testing.expect(std.mem.indexOf(u8, m.sel_text, "OSCME alpha") != null);- // Both channels carried it, so the toast says so without qualification.- try testing.expectEqualStrings(m.sel_text, copied[0..copied_len]);- try testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);- try testing.expect(std.mem.indexOf(u8, m.toast, "OSC 52") == null);- // Taking it clears it: the next paint owes the terminal nothing.- try testing.expectEqual(@as(usize, 0), selection.takeOsc52(&m).len);-}--test "with no local clipboard the copy still succeeds, via OSC 52" {- // The SSH case: pbcopy/xclip are absent or fail, and the only channel that- // reaches the user's machine is the escape.- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copy_ok = false;- defer copy_ok = true;- const a = testing.allocator;- var m: Model = undefined;- m.setup(a);- defer m.deinit();- try m.push(.assistant, "REMOTE alpha line");- try m.push(.assistant, "REMOTE beta line");- const first = try frameAt(&m, 0);- a.free(first);- const top = m.mid_origin + m.sticky_rows;- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 1, .y = @intCast(top + 1), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 32, .x = 40, .y = @intCast(top + 2), .down = true } });- _ = keys.handle(&m, .{ .mouse = .{ .btn = 0, .x = 40, .y = @intCast(top + 2), .down = false } });- const after = try frameAt(&m, 0);- defer a.free(after);- const seq = selection.takeOsc52(&m);- defer a.free(seq);- try expectPayload(seq, m.sel_text);- try testing.expect(std.mem.indexOf(u8, m.toast, "copied (OSC 52)") != null);-}--test "past the cap the local copy still lands and the toast says why not" {- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copy_ok = true;- copied_len = 0;- const a = testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- var m: Model = undefined;- m.setup(a);- defer m.deinit();- // A frame far larger than the cap, with the band over all of it. Going- // through selection.paint means the capture is the real one, not a string- // handed to the encoder.- const row = try ar.alloc(u8, 120);- @memset(row, 'y');- const rows = (osc52.max_bytes / row.len) + 40;- var frame = std.array_list.Managed(u8).init(ar);- for (0..rows) |i| {- if (i > 0) try frame.append('\n');- try frame.appendSlice(row);- }- m.last_term_width = row.len;- m.sel = .{ .active = true, .copy_pending = true, .a_row = 0, .a_col = 0, .h_row = rows - 1, .h_col = row.len - 1 };- _ = try selection.paint(&m, ar, frame.items, row.len);- try testing.expect(m.sel_text.len > osc52.max_bytes);- try testing.expectEqual(@as(usize, 0), selection.takeOsc52(&m).len);- try testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);- try testing.expect(std.mem.indexOf(u8, m.toast, "too big for OSC 52") != null);- // The local clipboard is unaffected by the cap — it took the whole thing.- try testing.expect(copied_len > 0);-}diff --git a/TUI/scrollpaint.zig b/TUI/scrollpaint.zigdeleted file mode 100644index a6bd563f..00000000--- a/TUI/scrollpaint.zig+++ /dev/null@@ -1,591 +0,0 @@-//! Scroll-aware painting: the fast path out of the diff painter.-//!-//! The diff painter compares screen row i to the PREVIOUS frame's row i. That-//! is exactly right for a token arriving or a spinner ticking, and exactly-//! wrong for a wheel event: sliding the transcript by one line makes every row-//! of the viewport differ from the row above it, so a one-line scroll repaints-//! the entire screen. At 3 lines per wheel notch and a notch every few-//! milliseconds that is the whole frame, over and over, down the pty.-//!-//! A terminal can do the sliding itself. Set a scroll region over the band-//! that actually moved (DECSTBM), emit SU/SD, drop the region, and only the-//! rows the scroll EXPOSED need bytes — plus whatever chrome legitimately-//! changed, which the ordinary row diff still handles.-//!-//! The danger is emitting a hardware scroll when the screen did not, in fact,-//! merely scroll. So this module never trusts the hint on its own: render.zig-//! reports the delta it believes the band moved by, and `plan` VERIFIES it-//! against the bytes of both frames — every row that would survive the shift-//! must already hold what the new frame wants there. Anything else in the band-//! (a fold toggling, a tool row finishing, a rewrap, a live token, an image-//! card resizing the viewport) breaks that equality and the caller falls back-//! to the full diff. Cases the verification cannot see — a self-heal repaint,-//! a resize, kitty images on screen, a live selection band anchored to SCREEN-//! rows rather than to content — are refused before we get here.--const std = @import("std");-const Io = std.Io;--const paint = @import("paint.zig");-const theme_mod = @import("theme.zig");--/// What render.zig believes the last two frames did to the scrollable band.-/// `delta` counts CONTENT lines: positive means the viewport moved further-/// down the transcript, so the band's content slides UP the screen (SU).-pub const Hint = struct {- /// First screen row of the band, 0-based. Sticky header rows are chrome- /// and sit ABOVE this; the composer and status bar sit below the end.- top: usize,- len: usize,- delta: isize,- /// Both frames carry the scroll gutter (scrollbar.zig), so every band row- /// on both is shaped `content ++ reset ++ style ++ cell`. The content half- /// slides with the scroll; the gutter cell does NOT, because its position- /// comes from the scroll offset rather than from the lines under it. So- /// the verification compares content halves and the paint patches the one- /// cell per row, on the two or three rows the thumb actually moved across.- /// False means ordinary whole-row comparison — including the frame the- /// gutter appears on and the frame it leaves, where the shapes differ and- /// the caller correctly falls back to a full diff.- gutter: bool = false,-};--/// Terminals taller than this fall back to the diff path rather than grow the-/// stack. Nothing in the TUI is fast enough to care at that size anyway.-const max_rows = 256;--const Plan = struct {- /// Band rows the scroll exposes, as absolute screen rows.- first_exposed: usize,- count: usize,- up: bool,-};--/// Frame lines indexed once. The diff painter's nthLine rescans from byte 0-/// for every row, which is O(rows x frame) per paint; the verification below-/// touches every row, so it does the split once instead.-const Lines = struct {- buf: [max_rows][]const u8 = undefined,- n: usize = 0,-- fn index(s: []const u8, rows: usize) Lines {- var l: Lines = .{};- var it = std.mem.splitScalar(u8, s, '\n');- while (it.next()) |ln| {- if (l.n >= rows or l.n >= max_rows) break;- l.buf[l.n] = ln;- l.n += 1;- }- return l;- }-- fn at(self: *const Lines, i: usize) []const u8 {- return if (i < self.n) self.buf[i] else "";- }-};--/// Everything about a hint that can be judged from the hint alone, so the two-/// line indexes below are never built for a frame that cannot use them.-fn viable(rows: usize, h: Hint) bool {- if (h.delta == 0 or h.len < 2 or rows > max_rows) return false;- if (h.top + h.len > rows) return false;- // A scroll that clears the whole band exposes every row of it: the region- // dance would be pure overhead on top of the same repaint.- return @abs(h.delta) < h.len;-}--/// A gutter row splits at its LAST reset: everything before is the content the-/// scroll carries, everything from it (`reset ++ style ++ cell`) is the one-/// column that does not. scrollbar.zig appends that suffix after every band-/// row, so the last reset is always the split — and the suffix is-/// self-contained, which is what lets the patch below write it straight onto-/// the last cell.-fn content(row: []const u8) []const u8 {- const at = std.mem.lastIndexOf(u8, row, theme_mod.reset) orelse return row;- return row[0..at];-}--fn cell(row: []const u8) []const u8 {- const at = std.mem.lastIndexOf(u8, row, theme_mod.reset) orelse return "";- return row[at..];-}--/// Decide, writing nothing. Returns the exposed-row plan when a hardware-/// scroll is provably equivalent to repainting the band, and null otherwise —-/// a null here is never a correctness risk, only a missed optimisation.-fn plan(rows: usize, h: Hint, cur: *const Lines, old: *const Lines) ?Plan {- if (!viable(rows, h)) return null;- const mag: usize = @abs(h.delta);- const up = h.delta > 0;- const kept = h.len - mag;- var j: usize = 0;- while (j < kept) : (j += 1) {- const dst = if (up) j else j + mag;- const src = if (up) j + mag else j;- const want = cur.at(h.top + dst);- const have = old.at(h.top + src);- if (h.gutter) {- if (!std.mem.eql(u8, content(want), content(have))) return null;- } else if (!std.mem.eql(u8, want, have)) return null;- }- return .{- .first_exposed = h.top + (if (up) kept else 0),- .count = mag,- .up = up,- };-}--/// Paint `frame` over `prev` as a scroll plus its exposed rows. Returns false-/// WITHOUT writing a byte when the hint does not hold up, so the caller can-/// fall through to the ordinary diff.-pub fn tryPaint(- w: *Io.Writer,- frame: []const u8,- rows: usize,- cols: usize,- prev: []const u8,- bg: []const u8,- h: Hint,-) !bool {- if (!viable(rows, h)) return false;- const cur = Lines.index(frame, rows);- const old = Lines.index(prev, rows);- const p = plan(rows, h, &cur, &old) orelse return false;-- // The rows the scroll opens up are filled with the ACTIVE background, not- // the theme's, so establish it before the region moves. (Under ?2026 the- // whole thing swaps atomically, but a terminal without it would flash.)- try w.writeAll(paint.row_prologue);- try w.writeAll(bg);- // DECSTBM is 1-based and inclusive. It also homes the cursor, which costs- // nothing here: every row painted below addresses itself with CUP.- try w.print("\x1b[{d};{d}r", .{ h.top + 1, h.top + h.len });- if (p.up) try w.print("\x1b[{d}S", .{p.count}) else try w.print("\x1b[{d}T", .{p.count});- // Drop the region immediately. Left set, an LF anywhere later — a panic- // message, the restore sequence — would scroll inside it instead of the- // screen, and the margins survive the alt-screen exit.- try w.writeAll("\x1b[r");-- var e: usize = 0;- while (e < p.count) : (e += 1) {- const r = p.first_exposed + e;- try w.print("\x1b[{d};1H", .{r + 1});- try paint.paintRow(w, cur.at(r), cols, bg);- }- // The gutter rode the scroll along with the content, but its position- // comes from the scroll OFFSET, so on the rows the thumb moved across the- // terminal is now showing the wrong cell. Patch that one column, and only- // where it actually differs — a notch moves the thumb by about a row, so- // this is two cells, not a band. (Exposed rows were just written whole.)- if (h.gutter) {- const kept = h.len - p.count;- var j: usize = 0;- while (j < kept) : (j += 1) {- const dst = if (p.up) j else j + p.count;- const src = if (p.up) j + p.count else j;- const want = cell(cur.at(h.top + dst));- if (std.mem.eql(u8, want, cell(old.at(h.top + src)))) continue;- try w.print("\x1b[{d};{d}H", .{ h.top + dst + 1, cols });- try w.writeAll(paint.row_prologue);- try w.writeAll(bg);- try w.writeAll(want);- }- }- // The band moved; nothing else did. Chrome that changed for its own- // reasons — the sticky header now pinning a different prompt, a scroll- // indicator, the composer — is still an ordinary row diff.- var r: usize = 0;- while (r < rows) : (r += 1) {- if (r >= h.top and r < h.top + h.len) continue;- if (std.mem.eql(u8, cur.at(r), old.at(r))) continue;- try w.print("\x1b[{d};1H", .{r + 1});- try paint.paintRow(w, cur.at(r), cols, bg);- }- try w.flush();- return true;-}--// ------------------------------------------------------------------ tests--const test_bg = "\x1b[48;2;20;20;20m";--fn emit(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8, h: Hint) !?[]u8 {- var aw = Io.Writer.Allocating.init(a);- errdefer aw.deinit();- if (!try tryPaint(&aw.writer, frame, rows, cols, prev, test_bg, h)) {- aw.deinit();- return null;- }- return try aw.toOwnedSlice();-}--/// A frame with two chrome rows on top, a scrollable band, and two chrome rows-/// at the bottom. `off` is the content offset of the band's first row.-fn frameAt(a: std.mem.Allocator, off: usize, rows: usize, band_top: usize, band_len: usize, chrome: []const u8) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- var r: usize = 0;- while (r < rows) : (r += 1) {- if (r > 0) try out.append('\n');- const line = if (r >= band_top and r < band_top + band_len)- try std.fmt.allocPrint(a, "content line {d} of the transcript", .{off + r - band_top})- else- try std.fmt.allocPrint(a, "{s} chrome row {d}", .{ chrome, r });- try out.appendSlice(line);- }- return out.items;-}--test "a one-line scroll costs one SU and the rows it exposed, not the screen" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const rows: usize = 24;- const cols: usize = 80;- const top: usize = 3; // top bar + sticky header + separator- const len: usize = 18;- const before = try frameAt(ar, 100, rows, top, len, "same");- const after = try frameAt(ar, 101, rows, top, len, "same");- const scrolled = (try emit(ar, after, rows, cols, before, .{ .top = top, .len = len, .delta = 1 })).?;- // Exactly one scroll, in the right direction, over the right region.- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[1S"));- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, scrolled, "\x1b[1T"));- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[4;21r"));- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[r"));- // ...and exactly one row of cells: the one the scroll exposed at the bottom.- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, "\x1b[21;1H"));- // ...and that is the ONLY row addressed at all: the other 23 kept their cells.- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, scrolled, ";1H"));- // The budget. A full repaint of the same frame is the thing this replaces.- var aw = Io.Writer.Allocating.init(ar);- try paint.paint(&aw.writer, after, rows, cols, before, test_bg, true, null);- const full = aw.written();- try std.testing.expect(full.len > 1000); // sanity: a real 80x24 repaint- if (scrolled.len * 4 >= full.len) {- std.debug.print("scroll paint {d} bytes vs full repaint {d}\n", .{ scrolled.len, full.len });- return error.ScrollPaintTooExpensive;- }-}--test "scrolling the other way is a single SD over the same region" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const before = try frameAt(ar, 100, 24, 3, 18, "same");- const after = try frameAt(ar, 97, 24, 3, 18, "same");- const out = (try emit(ar, after, 24, 80, before, .{ .top = 3, .len = 18, .delta = -3 })).?;- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\x1b[3T"));- try std.testing.expectEqual(@as(usize, 0), std.mem.count(u8, out, "S"));- // Three rows exposed, and they are the TOP three of the band.- for ([_][]const u8{ "\x1b[4;1H", "\x1b[5;1H", "\x1b[6;1H" }) |cup| {- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, cup));- }- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7;1H") == null);-}--test "chrome that changed on the same frame is still repainted" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- // The sticky header now pins a different prompt and the status bar moved:- // both live OUTSIDE the band, so the scroll cannot carry them.- const before = try frameAt(ar, 100, 24, 3, 18, "old");- const after = try frameAt(ar, 101, 24, 3, 18, "new");- const out = (try emit(ar, after, 24, 80, before, .{ .top = 3, .len = 18, .delta = 1 })).?;- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\x1b[1S"));- for ([_][]const u8{ "\x1b[1;1H", "\x1b[2;1H", "\x1b[3;1H", "\x1b[22;1H", "\x1b[23;1H", "\x1b[24;1H" }) |cup| {- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, cup));- }- try std.testing.expect(std.mem.indexOf(u8, out, "new chrome row 0") != null);-}--test "a hint the frames do not bear out is refused without writing a byte" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const before = try frameAt(ar, 100, 24, 3, 18, "same");- const after = try frameAt(ar, 101, 24, 3, 18, "same");- // Wrong magnitude, wrong direction, a band the frame never moved, a delta- // that clears the band, a band running off the screen: all refused.- for ([_]Hint{- .{ .top = 3, .len = 18, .delta = 2 },- .{ .top = 3, .len = 18, .delta = -1 },- .{ .top = 3, .len = 18, .delta = 18 },- .{ .top = 3, .len = 18, .delta = 0 },- .{ .top = 3, .len = 30, .delta = 1 },- .{ .top = 2, .len = 18, .delta = 1 },- }) |h| {- try std.testing.expect((try emit(ar, after, 24, 80, before, h)) == null);- }- // A fold toggling inside the band on the same frame as the scroll: the- // rows that "survive" no longer match, so the scroll is off the table.- var folded = std.array_list.Managed(u8).init(ar);- var it = std.mem.splitScalar(u8, after, '\n');- var r: usize = 0;- while (it.next()) |ln| : (r += 1) {- if (r > 0) try folded.append('\n');- try folded.appendSlice(if (r == 9) "the tool run just expanded" else ln);- }- try std.testing.expect((try emit(ar, folded.items, 24, 80, before, .{ .top = 3, .len = 18, .delta = 1 })) == null);-}--test "a selection band dropped by the same wheel notch blocks the scroll" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- // The wheel CLEARS the drag band and scrolls in one event (keys.zig): the- // band is anchored to screen rows, so it cannot ride the scroll. render.zig- // refuses the hint while a band is live, but the frame AFTER it clears is- // an ordinary frame with an ordinary hint — and the screen it is painted- // over still has inverse video on rows the scroll would carry. Bytes catch- // it: an SGR-only difference is a difference.- const clean_prev = try frameAt(ar, 100, 24, 3, 18, "same");- var banded = std.array_list.Managed(u8).init(ar);- var it = std.mem.splitScalar(u8, clean_prev, '\n');- var r: usize = 0;- while (it.next()) |ln| : (r += 1) {- if (r > 0) try banded.append('\n');- if (r >= 6 and r <= 8) try banded.appendSlice("\x1b[7m");- try banded.appendSlice(ln);- if (r >= 6 and r <= 8) try banded.appendSlice("\x1b[27m");- }- const after = try frameAt(ar, 101, 24, 3, 18, "same");- const h: Hint = .{ .top = 3, .len = 18, .delta = 1 };- // Over the CLEAN screen the scroll is fine; over the banded one it is not.- try std.testing.expect((try emit(ar, after, 24, 80, clean_prev, h)) != null);- try std.testing.expect((try emit(ar, after, 24, 80, banded.items, h)) == null);-}--/// The same frame with every band row in the gutter shape scrollbar.zig gives-/// it: content, then `reset ++ style ++ cell`, with the thumb on `thumb_len`-/// rows starting `thumb_top` into the band.-fn withGutter(a: std.mem.Allocator, frame: []const u8, band_top: usize, band_len: usize, thumb_top: usize, thumb_len: usize, cols: usize) ![]const u8 {- var out = std.array_list.Managed(u8).init(a);- var r: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (r += 1) {- if (r > 0) try out.append('\n');- if (r < band_top or r >= band_top + band_len) {- try out.appendSlice(ln);- continue;- }- const body = theme_mod.takeCols(ln, cols - 1);- try out.appendSlice(body);- var pad = cols - 1 - theme_mod.visibleLen(body);- while (pad > 0) : (pad -= 1) try out.append(' ');- try out.appendSlice(theme_mod.reset);- try out.appendSlice("\x1b[38;2;90;90;90m");- const on = r >= band_top + thumb_top and r < band_top + thumb_top + thumb_len;- try out.appendSlice(if (on) "\u{275A}" else " ");- }- return out.items;-}--test "the scroll gutter rides the fast path and is patched a cell at a time" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const rows: usize = 24;- const cols: usize = 80;- const top: usize = 3;- const len: usize = 18;- // A notch: the content slid one line AND the thumb moved one row down.- const before = try withGutter(ar, try frameAt(ar, 100, rows, top, len, "same"), top, len, 4, 6, cols);- const after = try withGutter(ar, try frameAt(ar, 101, rows, top, len, "same"), top, len, 5, 6, cols);- const h: Hint = .{ .top = top, .len = len, .delta = 1, .gutter = true };- // Without the gutter flag the frames look like a band that changed for its- // own reasons, and the fast path is refused — that is the regression this- // pins, and it is why the flag exists.- try std.testing.expect((try emit(ar, after, rows, cols, before, .{ .top = top, .len = len, .delta = 1 })) == null);- const out = (try emit(ar, after, rows, cols, before, h)).?;- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, "\x1b[1S"));- // A handful of cells, not a band. The thumb is a RANGE, and the content- // slid up by one while the thumb moved down by one, so it is displaced by- // two rows relative to what the terminal just carried: the two rows at- // each end. Each is addressed at the LAST column, never at column 1.- try std.testing.expectEqual(@as(usize, 4), std.mem.count(u8, out, ";80H"));- // One whole row: the one the scroll exposed at the bottom of the band.- try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, out, ";1H"));- // Cheap: a gutter notch must stay in the same class as a plain one.- var aw = Io.Writer.Allocating.init(ar);- try paint.paint(&aw.writer, after, rows, cols, before, test_bg, true, null);- try std.testing.expect(out.len * 4 < aw.written().len);-}--test "a gutter frame whose content did NOT slide is still refused" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const top: usize = 3;- const len: usize = 18;- const before = try withGutter(ar, try frameAt(ar, 100, 24, top, len, "same"), top, len, 4, 6, 80);- // Same offset the hint claims, but a row inside the band changed: the- // content comparison has to catch it even though the gutter halves agree.- const raw = try frameAt(ar, 101, 24, top, len, "same");- var folded = std.array_list.Managed(u8).init(ar);- var it = std.mem.splitScalar(u8, raw, '\n');- var r: usize = 0;- while (it.next()) |ln| : (r += 1) {- if (r > 0) try folded.append('\n');- try folded.appendSlice(if (r == 9) "the tool run just expanded" else ln);- }- const after = try withGutter(ar, folded.items, top, len, 5, 6, 80);- try std.testing.expect((try emit(ar, after, 24, 80, before, .{ .top = top, .len = len, .delta = 1, .gutter = true })) == null);-}--/// A terminal that also knows DECSTBM / SU / SD — the two sequences the diff-/// painter's own screen model never had to understand.-const Screen = struct {- rows: usize,- cols: usize,- cells: []u8,- row: usize = 0,- col: usize = 0,- top: usize = 0,- bot: usize,-- fn init(a: std.mem.Allocator, rows: usize, cols: usize) !Screen {- const cells = try a.alloc(u8, rows * cols);- @memset(cells, ' ');- return .{ .rows = rows, .cols = cols, .cells = cells, .bot = rows - 1 };- }-- fn at(self: *Screen, r: usize, c: usize) *u8 {- return &self.cells[r * self.cols + c];- }-- fn rowSlice(self: *Screen, r: usize) []u8 {- return self.cells[r * self.cols ..][0..self.cols];- }-- fn scroll(self: *Screen, n: usize, up: bool) void {- var k: usize = 0;- while (k < n) : (k += 1) {- if (up) {- var r = self.top;- while (r < self.bot) : (r += 1) @memcpy(self.rowSlice(r), self.rowSlice(r + 1));- @memset(self.rowSlice(self.bot), ' ');- } else {- var r = self.bot;- while (r > self.top) : (r -= 1) @memcpy(self.rowSlice(r), self.rowSlice(r - 1));- @memset(self.rowSlice(self.top), ' ');- }- }- }-- fn feed(self: *Screen, s: []const u8) void {- var i: usize = 0;- while (i < s.len) {- if (s[i] == 0x1b) {- const e = @import("theme.zig").skipEsc(s, i);- self.control(s[i..e]);- i = e;- continue;- }- if (s[i] == '\r') {- self.col = 0;- } else if (s[i] == '\n') {- self.row += 1;- } else if (self.row < self.rows and self.col < self.cols) {- self.at(self.row, self.col).* = s[i];- self.col += 1;- }- i += 1;- }- }-- fn control(self: *Screen, seq: []const u8) void {- if (seq.len < 3 or seq[1] != '[') return;- const final = seq[seq.len - 1];- const body = seq[2 .. seq.len - 1];- var it = std.mem.splitScalar(u8, body, ';');- const p0 = std.fmt.parseInt(usize, it.first(), 10) catch 0;- switch (final) {- 'H' => {- self.row = if (p0 > 0) p0 - 1 else 0;- self.col = 0;- },- 'J' => if (std.mem.eql(u8, body, "2")) {- @memset(self.cells, ' ');- self.row = 0;- self.col = 0;- },- 'K' => if (self.row < self.rows) {- var c = self.col;- while (c < self.cols) : (c += 1) self.at(self.row, c).* = ' ';- },- 'r' => {- const p1 = std.fmt.parseInt(usize, it.next() orelse "", 10) catch 0;- self.top = if (p0 > 0) p0 - 1 else 0;- self.bot = if (p1 > 0 and p1 <= self.rows) p1 - 1 else self.rows - 1;- self.row = self.top;- self.col = 0;- },- 'S' => self.scroll(@max(p0, 1), true),- 'T' => self.scroll(@max(p0, 1), false),- else => {},- }- }-};--test "a scroll storm leaves the screen exactly where a full repaint would" {- const a = std.testing.allocator;- var arena = std.heap.ArenaAllocator.init(a);- defer arena.deinit();- const ar = arena.allocator();- const rows: usize = 24;- const cols: usize = 80;- const top: usize = 3;- const len: usize = 18;- var screen = try Screen.init(ar, rows, cols);- var off: usize = 200;- var cur = try frameAt(ar, off, rows, top, len, "same");- // Lay the first frame down in full, then scroll it around.- {- var aw = Io.Writer.Allocating.init(ar);- try paint.paint(&aw.writer, cur, rows, cols, "", test_bg, false, null);- screen.feed(aw.written());- }- var took: usize = 0;- for ([_]isize{ 3, 3, 3, -1, -3, 7, -7, 1, 1, 1, 1, -17, 17, 2, -2 }) |d| {- const next_off: usize = @intCast(@as(isize, @intCast(off)) + d);- const next = try frameAt(ar, next_off, rows, top, len, "same");- const out = try emit(ar, next, rows, cols, cur, .{ .top = top, .len = len, .delta = d });- if (out) |bytes| {- screen.feed(bytes);- took += 1;- } else {- // The fallback the caller would take.- var aw = Io.Writer.Allocating.init(ar);- try paint.paint(&aw.writer, next, rows, cols, cur, test_bg, false, null);- screen.feed(aw.written());- }- off = next_off;- cur = next;- }- // Most of the storm really did take the scroll path...- try std.testing.expect(took >= 10);- // ...and a forced full repaint of the final frame changes nothing at all.- var truth = try Screen.init(ar, rows, cols);- {- var aw = Io.Writer.Allocating.init(ar);- try paint.paint(&aw.writer, cur, rows, cols, "", test_bg, false, null);- truth.feed(aw.written());- }- var r: usize = 0;- while (r < rows) : (r += 1) {- if (std.mem.eql(u8, screen.rowSlice(r), truth.rowSlice(r))) continue;- std.debug.print("row {d}:\n screen {s}\n truth {s}\n", .{ r, screen.rowSlice(r), truth.rowSlice(r) });- return error.ScrollStormLeftResidue;- }- // And the scroll region is back to the whole screen, so nothing later- // scrolls inside a stale margin.- try std.testing.expectEqual(@as(usize, 0), screen.top);- try std.testing.expectEqual(rows - 1, screen.bot);-}diff --git a/TUI/selection.zig b/TUI/selection.zigdeleted file mode 100644index d3a019d0..00000000--- a/TUI/selection.zig+++ /dev/null@@ -1,584 +0,0 @@-//! In-app drag selection (#529). Mouse tracking (?1000/?1003/?1006) swallows-//! the terminal's own selection gesture, so the TUI owns it: drag paints an-//! inverse-video band over the composed frame, release copies the covered text-//! to the system clipboard, and any other input drops the band.-//!-//! Granularity is grok's: whole rows, with column bounds on the FIRST and LAST-//! row only. Character precision inside a styled, wrapped row would have to-//! agree with every row builder in scrollback.zig/markdown.zig; row bands agree-//! with the rendered frame by construction — the band and the copied text come-//! out of the same pass over the same bytes.-//!-//! What the band COVERS and what it CAPTURES differ on purpose: the band is a-//! rectangle, but a screen row of nothing but layout padding is not text (see-//! `Capture`), so a drag that overshoots into the empty screen below the-//! transcript copies the transcript, not the emptiness.-//!-//! Presentation state only. This renders the engine's transcript; it does not-//! fork engine behaviour, and nothing here reaches a provider.--const std = @import("std");-const builtin = @import("builtin");--const app = @import("app.zig");-const engine = @import("engine.zig");-const key_mod = @import("key.zig");-const osc52 = @import("osc52.zig");-const theme_mod = @import("theme.zig");-const Model = app.Model;--/// Anchor/head live in SCREEN coordinates: the band belongs to the frame it was-/// drawn over, and it is cleared by the next non-drag input, so it can never-/// drift onto content that scrolled underneath it.-pub const Sel = struct {- /// A drag has happened — the band paints and `Model.sel_text` is live.- active: bool = false,- /// Button is down inside the transcript; motion may still turn it into a drag.- pressed: bool = false,- a_row: usize = 0,- a_col: usize = 0,- h_row: usize = 0,- h_col: usize = 0,- /// Tool group the press expanded/collapsed. Reverted the instant motion- /// proves the gesture was a drag, so selecting text never folds a group.- undo_idx: ?usize = null,- /// Release seen; the copy runs in the next paint. A terminal delivers a- /// whole flick of the mouse in one read, and run.zig drains every event in- /// that read before rendering — copying at release time would then ship the- /// text of a frame the last motion never reached.- copy_pending: bool = false,- /// Rows of the last capture that actually carried text. The toast counts- /// these, not the newlines in `sel_text`: collapsed blank runs are spacing,- /// and calling them "lines copied" would inflate the number the user reads.- text_rows: usize = 0,- /// setToast BORROWS its slice — the copy toast has to outlive this call, so- /// it is formatted into model-owned storage. Wide enough for the longest- /// shape: a six-figure line count plus the OSC 52 note.- toast_buf: [64]u8 = undefined,-};--pub const Range = struct { r0: usize, c0: usize, r1: usize, c1: usize };--/// True when the event belonged to the drag gesture and nothing else should see-/// it. A press is only RECORDED: a click keeps its existing meaning (tool-group-/// expand, composer focus) until motion proves otherwise.-pub fn mouse(self: *Model, ev: key_mod.Mouse) bool {- // SGR and X10 agree on 32 = motion with the left button held.- if (ev.btn == 32 and ev.down) {- extend(self, ev);- return true;- }- // Release: SGR reports the button with a final 'm', X10 reports button 3.- if (!ev.down and (ev.btn == 0 or ev.btn == 3)) return finish(self);- if (ev.down and ev.btn == 0) begin(self, ev);- return false;-}--fn begin(self: *Model, ev: key_mod.Mouse) void {- clear(self);- // A press with an overlay up means "close it" (keys.zig) — the frame the- // band would be measured against is gone by the next motion.- if (self.overlay != .none) return;- const p = point(self, ev, false) orelse return;- self.sel.pressed = true;- self.sel.a_row = p.row;- self.sel.a_col = p.col;- self.sel.h_row = p.row;- self.sel.h_col = p.col;-}--fn extend(self: *Model, ev: key_mod.Mouse) void {- if (!self.sel.pressed) return;- const p = point(self, ev, true) orelse return;- if (self.sel.undo_idx) |i| {- self.toggleToolGroup(i);- self.sel.undo_idx = null;- }- self.sel.h_row = p.row;- self.sel.h_col = p.col;- self.sel.active = true;- // This gesture MOVED, so it is a drag and not a click — it can never be- // half of a double click either. hover.zig is told rather than left to- // re-derive the same distinction from the same reports.- @import("hover.zig").dragged(self);-}--/// Mouse-up arms the copy. The band itself KEEPS painting: the user sees-/// exactly what landed on the clipboard until the next keystroke or click.-fn finish(self: *Model) bool {- if (!self.sel.pressed) return true; // a release we never anchored- self.sel.pressed = false;- self.sel.undo_idx = null;- if (self.sel.active) self.sel.copy_pending = true;- return true;-}--/// Runs inside the paint that captured the text, so the clipboard and the band-/// can never disagree about which frame was selected. A band over nothing but-/// padding captures no text: the clipboard is left exactly as the user had it-/// and no toast claims a copy that never happened.-fn commit(self: *Model) void {- self.sel.copy_pending = false;- const text = self.sel_text;- if (text.len == 0) {- clear(self);- return;- }- const lines = self.sel.text_rows;- // Two channels, always both attempted, because they reach different- // machines. The local tool writes the clipboard of the host graff runs on;- // OSC 52 writes the clipboard of the TERMINAL, which over SSH is the only- // one the user can paste from. Neither is a fallback for the other — the- // local tool is what a clipboard manager sees, and OSC 52 is what survives- // the hop — so the emission is not gated on the local attempt failing.- const local = copyText(text);- const remote = armOsc52(self, text);- if (!local and !remote) {- self.setToast("copy failed");- return;- }- // What the toast has to be honest about: which channel actually carried- // it. "copied" with no local clipboard would be a lie on a plain terminal;- // "(OSC 52)" tells an SSH user their laptop has it. A selection past the- // cap is the one case that copies locally and NOT to the terminal.- const note: []const u8 = if (!local) " (OSC 52)" else if (!remote) " (too big for OSC 52)" else "";- const s = std.fmt.bufPrint(&self.sel.toast_buf, "{d} line{s} copied{s}", .{- lines,- if (lines == 1) "" else "s",- note,- }) catch "copied";- self.setToast(s);-}--/// Hand the run loop the escape to write. Presentation state, not a frame: a-/// frame gets repainted and a clipboard write must happen exactly once, so it-/// travels on its own one-shot slot (app.Model.osc_pending). Returns false-/// when the payload is past the cap and nothing will be emitted.-fn armOsc52(self: *Model, text: []const u8) bool {- const seq = (osc52.sequence(self.alloc, text) catch return false) orelse return false;- if (self.osc_pending.len > 0) self.alloc.free(self.osc_pending);- self.osc_pending = seq;- return true;-}--/// The one-shot the run loop owes the tty, handed over and cleared. Returns an-/// empty slice when nothing is owed; the caller frees what it takes.-pub fn takeOsc52(self: *Model) []const u8 {- const seq = self.osc_pending;- self.osc_pending = "";- return seq;-}--pub fn clear(self: *Model) void {- self.sel.active = false;- self.sel.pressed = false;- self.sel.undo_idx = null;- self.sel.copy_pending = false;- if (self.sel_text.len > 0) {- self.alloc.free(self.sel_text);- self.sel_text = "";- }-}--const Point = struct { row: usize, col: usize };--/// Screen cell under the pointer, restricted to the transcript viewport. A-/// press outside it anchors nothing (`clamp = false`); a drag that runs off the-/// edge keeps selecting the edge row (`clamp = true`).-fn point(self: *const Model, ev: key_mod.Mouse, clamp: bool) ?Point {- if (self.prompt_origin <= self.mid_origin) return null;- const last_row = self.prompt_origin - 1;- const last_col = if (self.last_term_width > 0) self.last_term_width - 1 else 0;- var y: usize = if (ev.y > 0) ev.y - 1 else 0;- var x: usize = if (ev.x > 0) ev.x - 1 else 0;- if (y < self.mid_origin or y > last_row) {- if (!clamp) return null;- y = std.math.clamp(y, self.mid_origin, last_row);- }- if (x > last_col) x = last_col;- return .{ .row = y, .col = x };-}--/// Normalized band: [r0,c0] inclusive to [r1,c1) exclusive, so the cell under-/// the pointer is part of the selection.-pub fn ordered(self: *const Model) ?Range {- if (!self.sel.active) return null;- const s = self.sel;- const fwd = s.a_row < s.h_row or (s.a_row == s.h_row and s.a_col <= s.h_col);- return .{- .r0 = if (fwd) s.a_row else s.h_row,- .c0 = if (fwd) s.a_col else s.h_col,- .r1 = if (fwd) s.h_row else s.a_row,- .c1 = (if (fwd) s.h_col else s.a_col) + 1,- };-}--/// What the band COVERS and what it CAPTURES are deliberately different. The-/// band is a rectangle over the frame, so it swallows the blank cells the-/// layout uses for spacing; the capture is the text under it. A row with no-/// glyphs contributes nothing, the blank rows at either end of the drag fall-/// off, and a run of blank rows between two text rows collapses to a single-/// empty line — paragraph separation survives, screens of padding do not.-const Capture = struct {- text: *std.array_list.Managed(u8),- /// Rows that carried text. Blank rows, kept or dropped, never count.- rows: usize = 0,- /// A blank run is pending. It only becomes an empty line once a later row- /// proves it was INTERIOR, which is what drops the trailing blanks.- gap: bool = false,-- fn push(self: *Capture, line: []const u8) !void {- if (line.len == 0) {- self.gap = self.rows > 0; // leading blanks never open the capture- return;- }- if (self.rows > 0) try self.text.append('\n');- if (self.gap) {- try self.text.append('\n');- self.gap = false;- }- try self.text.appendSlice(line);- self.rows += 1;- }-};--/// Post-pass over the COMPOSED frame: the row builders in scrollback.zig stay-/// untouched, and the captured text is the same bytes the band covers.-pub fn paint(self: *Model, a: std.mem.Allocator, frame: []const u8, width: usize) ![]const u8 {- const r = ordered(self) orelse return frame;- var out = std.array_list.Managed(u8).init(a);- var text = std.array_list.Managed(u8).init(a);- var line = std.array_list.Managed(u8).init(a);- var cap: Capture = .{ .text = &text };- var row: usize = 0;- var it = std.mem.splitScalar(u8, frame, '\n');- while (it.next()) |ln| : (row += 1) {- if (row > 0) try out.append('\n');- const c0 = if (row == r.r0) r.c0 else 0;- const c1 = @min(if (row == r.r1) r.c1 else width, width);- if (row < r.r0 or row > r.r1 or c1 <= c0) {- try out.appendSlice(ln);- continue;- }- line.clearRetainingCapacity();- try band(&out, &line, ln, c0, c1);- // Every row, column-bounded ends included, loses its trailing blanks —- // a row of nothing but them is then empty, and contributes nothing.- try cap.push(std.mem.trimEnd(u8, line.items, " \t"));- }- setText(self, text.items);- self.sel.text_rows = cap.rows;- if (self.sel.copy_pending) commit(self);- return out.items;-}--fn setText(self: *Model, s: []const u8) void {- const owned = self.alloc.dupe(u8, s) catch return;- if (self.sel_text.len > 0) self.alloc.free(self.sel_text);- self.sel_text = owned;-}--/// One row: verbatim up to `c0`, inverse video across [c0,c1), verbatim after.-/// SGR inside the band is dropped so the highlight is uniform (a stray `0m`-/// would otherwise cancel it mid-band) and re-emitted at the far edge, or the-/// rest of the row would paint in whatever style the band swallowed.-///-/// `text` is this ROW's capture buffer, emptied by the caller — the glyphs the-/// band covers, and nothing the band merely pads over.-fn band(out: *std.array_list.Managed(u8), text: *std.array_list.Managed(u8), ln: []const u8, c0: usize, c1: usize) !void {- var sgr: theme_mod.Sgr = .{};- var i: usize = 0;- var col: usize = 0;- while (i < ln.len and col < c0) {- if (ln[i] == 0x1b) {- const e = theme_mod.skipEsc(ln, i);- sgr.note(ln[i..e]);- try out.appendSlice(ln[i..e]);- i = e;- continue;- }- const c = cpAt(ln, i);- if (col + c.w > c0) break; // a wide glyph never straddles the edge- try out.appendSlice(ln[i .. i + c.n]);- col += c.w;- i += c.n;- }- try pad(out, c0 -| col);- col = @max(col, c0);- try out.appendSlice("\x1b[7m");- while (i < ln.len and col < c1) {- if (ln[i] == 0x1b) {- const e = theme_mod.skipEsc(ln, i);- sgr.note(ln[i..e]);- i = e;- continue;- }- const c = cpAt(ln, i);- if (col + c.w > c1) break;- try out.appendSlice(ln[i .. i + c.n]);- try text.appendSlice(ln[i .. i + c.n]);- col += c.w;- i += c.n;- }- // The band covers blank cells too, exactly like a terminal's own selection.- // Those pad columns are painted, never captured.- try pad(out, c1 -| col);- try out.appendSlice("\x1b[27m");- var buf: [theme_mod.Sgr.max_render]u8 = undefined;- try out.appendSlice(sgr.render(&buf));- if (i < ln.len) try out.appendSlice(ln[i..]);-}--fn pad(out: *std.array_list.Managed(u8), n: usize) !void {- var left = n;- while (left > 0) : (left -= 1) try out.append(' ');-}--const Cp = struct { w: usize, n: usize };--/// Columns and bytes of the codepoint at `i` — theme_mod.charWidth plus the-/// VS16 promotion, so the band measures the same cells visibleLen does.-fn cpAt(s: []const u8, i: usize) Cp {- const len = std.unicode.utf8ByteSequenceLength(s[i]) catch return .{ .w = 1, .n = 1 };- const n = @min(@as(usize, len), s.len - i);- const cp = std.unicode.utf8Decode(s[i .. i + n]) catch return .{ .w = 1, .n = n };- const w: usize = theme_mod.charWidth(cp);- if (w == 1 and i + n + 3 <= s.len and std.mem.eql(u8, s[i + n .. i + n + 3], "\u{FE0F}")) return .{ .w = 2, .n = n };- return .{ .w = w, .n = n };-}--/// The session's clipboard callback when there is one (/copy's path), else the-/// platform tool directly — the TUI also runs without a live session.-pub fn copyText(text: []const u8) bool {- if (text.len == 0) return false;- if (engine.g_copy_fn) |f| return f(engine.g_turn_ctx, text);- const argv: []const []const u8 = switch (builtin.os.tag) {- .macos => &.{"pbcopy"},- .linux => &.{ "xclip", "-selection", "clipboard" },- else => return false,- };- const io = std.Io.Threaded.global_single_threaded.io();- var child = std.process.spawn(io, .{- .argv = argv,- .stdin = .pipe,- .stdout = .ignore,- .stderr = .ignore,- }) catch return false;- if (child.stdin) |*s| {- var wbuf: [4096]u8 = undefined;- var w = s.writerStreaming(io, &wbuf);- w.interface.writeAll(text) catch {};- w.interface.flush() catch {};- s.close(io);- child.stdin = null;- }- const term = child.wait(io) catch return false;- return term == .exited and term.exited == 0;-}--// ---------------------------------------------------------------- tests--const keys = @import("keys.zig");-const render_mod = @import("render.zig");--var copied: [4096]u8 = undefined;-var copied_len: usize = 0;--fn fakeCopy(_: ?*anyopaque, text: []const u8) bool {- copied_len = @min(text.len, copied.len);- @memcpy(copied[0..copied_len], text[0..copied_len]);- return true;-}--fn press(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = true } });-}--fn drag(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 32, .x = x, .y = y, .down = true } });-}--fn release(m: *Model, x: u16, y: u16) void {- _ = keys.handle(m, .{ .mouse = .{ .btn = 0, .x = x, .y = y, .down = false } });-}--fn frameOf(m: *Model) ![]const u8 {- return render_mod.render(m, std.testing.allocator, 80, 24, 0);-}--test "a drag paints an inverse band and copies the covered rows (#529)" {- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copied_len = 0;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "SELECTME alpha line");- try m.push(.assistant, "SELECTME beta line");- const first = try frameOf(&m);- std.testing.allocator.free(first);- // Find the painted row of the first entry, then drag across both.- const top = m.mid_origin + m.sticky_rows;- press(&m, 1, @intCast(top + 1));- drag(&m, 40, @intCast(top + 2));- const dragging = try frameOf(&m);- defer std.testing.allocator.free(dragging);- try std.testing.expect(std.mem.indexOf(u8, dragging, "\x1b[7m") != null);- try std.testing.expect(std.mem.indexOf(u8, dragging, "\x1b[27m") != null);- try std.testing.expect(std.mem.indexOf(u8, m.sel_text, "SELECTME alpha") != null);- release(&m, 40, @intCast(top + 2));- // The band survives the release so the user sees what was copied...- const after = try frameOf(&m);- defer std.testing.allocator.free(after);- try std.testing.expect(m.sel.active);- try std.testing.expect(std.mem.indexOf(u8, after, "\x1b[7m") != null);- try std.testing.expect(std.mem.indexOf(u8, copied[0..copied_len], "SELECTME alpha") != null);- try std.testing.expect(std.mem.indexOf(u8, m.toast, "copied") != null);- // The capture never opens or closes on the transcript's blank spacing rows,- // and the toast counts the rows that carried text.- try std.testing.expect(!std.mem.startsWith(u8, m.sel_text, "\n"));- try std.testing.expect(!std.mem.endsWith(u8, m.sel_text, "\n"));- var cnt: [8]u8 = undefined;- const head = try std.fmt.bufPrint(&cnt, "{d} line", .{m.sel.text_rows});- try std.testing.expect(std.mem.startsWith(u8, m.toast, head));- // ...and the next ordinary keystroke drops it.- _ = keys.handle(&m, .{ .char = 'x' });- try std.testing.expect(!m.sel.active);- const clean = try frameOf(&m);- defer std.testing.allocator.free(clean);- try std.testing.expect(std.mem.indexOf(u8, clean, "\x1b[7m") == null);-}--test "click on a folded tool row still expands it, and paints no band" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.last_term_height = 24;- m.last_term_width = 80;- m.mid_origin = 1;- m.mid_skip = 0;- m.prompt_origin = 20;- try std.testing.expect(m.history.items[1].folded);- press(&m, 4, 3);- release(&m, 4, 3);- try std.testing.expect(!m.history.items[1].folded);- try std.testing.expect(!m.sel.active);- try std.testing.expect(m.sel_text.len == 0);-}--test "click on blank padding selects and toggles nothing (#519)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.last_term_height = 24;- m.last_term_width = 80;- m.mid_origin = 0;- m.mid_skip = 0;- m.prompt_origin = 20;- try std.testing.expect(m.history.items[1].folded);- press(&m, 2, 15);- try std.testing.expect(m.history.items[1].folded);- try std.testing.expectEqual(app.Focus.scrollback, m.focus);-}--test "a drag that starts on a tool group leaves the group as it was" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- try m.pushTool(.{ .name = "bash" });- try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- m.last_term_height = 24;- m.last_term_width = 80;- m.mid_origin = 1;- m.prompt_origin = 20;- try std.testing.expect(m.history.items[1].folded);- press(&m, 4, 3);- drag(&m, 30, 5);- try std.testing.expect(m.history.items[1].folded); // the expand was undone- try std.testing.expect(m.sel.active);-}--test "a press outside the transcript never anchors a band" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 80;- m.mid_origin = 2;- m.prompt_origin = 20;- press(&m, 5, 21); // composer row- drag(&m, 40, 10);- try std.testing.expect(!m.sel.active);- try std.testing.expectEqual(app.Focus.prompt, m.focus);-}--test "the wheel scrolls and drops the band instead of extending it" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 80;- m.last_term_height = 24;- m.mid_origin = 1;- m.prompt_origin = 20;- press(&m, 2, 3);- drag(&m, 40, 6);- try std.testing.expect(m.sel.active);- _ = keys.handle(&m, .{ .mouse = .{ .btn = 64, .x = 40, .y = 6, .down = true } });- try std.testing.expect(!m.sel.active);- try std.testing.expect(!m.follow);-}--test "a drag over blank rows leaves the clipboard and the toast alone" {- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- // Seeded, not zeroed: the contract is that the user's clipboard SURVIVES a- // drag that found no text, not merely that nothing new was appended.- copied_len = @min("KEEPME".len, copied.len);- @memcpy(copied[0..copied_len], "KEEPME");- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 80;- m.mid_origin = 1;- m.prompt_origin = 20;- press(&m, 4, 5);- drag(&m, 40, 8);- release(&m, 40, 8);- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- _ = try paint(&m, arena.allocator(), "\n\n\n\n\n \n\n\n\n", 80);- try std.testing.expectEqualStrings("KEEPME", copied[0..copied_len]);- try std.testing.expectEqualStrings("", m.toast);- try std.testing.expect(!m.sel.active);-}--test "a drag whose motion and release arrive in ONE read still copies" {- // Terminals batch mouse reports, and run.zig drains every event in a read- // before it renders — so the copy has to be taken from the paint that- // follows, not from whatever text the previous frame happened to hold.- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copied_len = 0;- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.assistant, "BATCHED alpha");- try m.push(.assistant, "BATCHED beta");- const first = try frameOf(&m);- std.testing.allocator.free(first);- const top = m.mid_origin + m.sticky_rows;- press(&m, 1, @intCast(top + 1));- drag(&m, 60, @intCast(top + 2));- release(&m, 60, @intCast(top + 2));- try std.testing.expectEqual(@as(usize, 0), copied_len); // nothing yet...- const frame = try frameOf(&m);- defer std.testing.allocator.free(frame);- try std.testing.expect(std.mem.indexOf(u8, copied[0..copied_len], "BATCHED alpha") != null);- try std.testing.expectEqualStrings(m.sel_text, copied[0..copied_len]);-}diff --git a/TUI/selection_tests.zig b/TUI/selection_tests.zigdeleted file mode 100644index 7c4a5ad0..00000000--- a/TUI/selection_tests.zig+++ /dev/null@@ -1,151 +0,0 @@-//! Capture-contract tests for the drag band (#529). They drive `selection.paint`-//! over a hand-written frame, so they hold what lands on the CLIPBOARD rather-//! than any one helper's shape. Split out of selection.zig for the 600-line-//! ceiling.-//!-//! The contract: the band is a rectangle over the frame, the capture is the-//! text under it. Blank rows contribute nothing, the blanks at either end of-//! the drag fall off, an interior run of them collapses to one empty line, and-//! every row loses its trailing blanks.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const selection = @import("selection.zig");-const Model = app.Model;--const paint = selection.paint;--var copied: [4096]u8 = undefined;-var copied_len: usize = 0;--fn fakeCopy(_: ?*anyopaque, text: []const u8) bool {- copied_len = @min(text.len, copied.len);- @memcpy(copied[0..copied_len], text[0..copied_len]);- return true;-}--test "column bounds hold on the first and last row; middle rows are whole" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 10;- m.mid_origin = 0;- m.prompt_origin = 5;- m.sel = .{ .active = true, .a_row = 0, .a_col = 3, .h_row = 2, .h_col = 4 };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const out = try paint(&m, arena.allocator(), "abcdefghij\nklmnopqrst\nuvwxyz\nTAIL", 10);- // First row starts at column 3, last row ends after column 4.- try std.testing.expect(std.mem.indexOf(u8, out, "abc\x1b[7mdefghij") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7muvwxy\x1b[27m") != null);- try std.testing.expect(std.mem.indexOf(u8, out, "TAIL") != null);- try std.testing.expectEqualStrings("defghij\nklmnopqrst\nuvwxy", m.sel_text);- try std.testing.expectEqual(@as(usize, 3), m.sel.text_rows);- // A row shorter than the band is padded, and the pad is not text.- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 9 };- const short = try paint(&m, arena.allocator(), "hi", 10);- try std.testing.expect(std.mem.indexOf(u8, short, "\x1b[7mhi \x1b[27m") != null);- try std.testing.expectEqualStrings("hi", m.sel_text);-}--test "the band drops SGR inside it and restores the style after it" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 12;- m.mid_origin = 0;- m.prompt_origin = 4;- m.sel = .{ .active = true, .a_row = 0, .a_col = 2, .h_row = 0, .h_col = 5 };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const out = try paint(&m, arena.allocator(), "ab\x1b[31mcdef\x1b[0mgh", 12);- // No reset survives inside the band...- const b0 = std.mem.indexOf(u8, out, "\x1b[7m").?;- const b1 = std.mem.indexOf(u8, out, "\x1b[27m").?;- try std.testing.expect(std.mem.indexOf(u8, out[b0..b1], "\x1b[") == 0);- try std.testing.expect(std.mem.indexOf(u8, out[b0 + 4 .. b1], "\x1b[") == null);- try std.testing.expectEqualStrings("cdef", m.sel_text);-}--test "a wide glyph never straddles a band edge" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 10;- m.mid_origin = 0;- m.prompt_origin = 4;- // "a" + 世 (2 cols) + "b": a band ending mid-glyph must leave it out.- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 0, .h_col = 1 };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const out = try paint(&m, arena.allocator(), "a\u{4e16}b", 10);- try std.testing.expectEqualStrings("a", m.sel_text);- // The excluded glyph leaves a pad column so the band still measures 2, and- // the glyph itself paints outside it, whole.- try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[7ma \x1b[27m") != null);- try std.testing.expect(std.mem.endsWith(u8, out, "\u{4e16}b"));-}--test "blank rows at the ends drop and an interior run collapses to one line" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 12;- m.mid_origin = 0;- m.prompt_origin = 9;- // The drag covers all eight rows: two of leading padding, a text row, a- // three-row gap, another text row, then the empty screen below.- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 7, .h_col = 11 };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const frame = "\n \nalpha one\n\n \n\nbeta two\n ";- const out = try paint(&m, arena.allocator(), frame, 12);- // The band still PAINTS every covered row — only the capture is text-only.- try std.testing.expectEqual(@as(usize, 8), std.mem.count(u8, out, "\x1b[7m"));- try std.testing.expectEqualStrings("alpha one\n\nbeta two", m.sel_text);- try std.testing.expectEqual(@as(usize, 2), m.sel.text_rows);-}--test "every captured row is trimmed, column-bounded first and last included" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 16;- m.mid_origin = 0;- m.prompt_origin = 4;- // First row bounded at column 2, last row bounded after column 11 — both- // end inside a run of spaces, and neither may carry them out.- m.sel = .{ .active = true, .a_row = 0, .a_col = 2, .h_row = 2, .h_col = 11 };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- const out = try paint(&m, arena.allocator(), "xxfirst \nmid \nlast zzzz", 16);- try std.testing.expectEqualStrings("first\nmid\nlast", m.sel_text);- try std.testing.expectEqual(@as(usize, 3), m.sel.text_rows);- // The painted band keeps its full width; only the capture is trimmed.- try std.testing.expect(std.mem.indexOf(u8, out, "xx\x1b[7mfirst ") != null);- try std.testing.expect(std.mem.endsWith(u8, out, "zzzz"));-}--test "a band over nothing but padding copies nothing and shows no toast" {- engine.g_copy_fn = fakeCopy;- defer engine.g_copy_fn = null;- copied_len = @min("SENTINEL".len, copied.len);- @memcpy(copied[0..copied_len], "SENTINEL");- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- m.last_term_width = 12;- m.mid_origin = 0;- m.prompt_origin = 5;- m.sel = .{ .active = true, .a_row = 0, .a_col = 0, .h_row = 3, .h_col = 11, .copy_pending = true };- var arena = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena.deinit();- _ = try paint(&m, arena.allocator(), "\n \n\n \nTAIL", 12);- try std.testing.expectEqualStrings("SENTINEL", copied[0..copied_len]);- try std.testing.expectEqual(@as(usize, 0), m.sel_text.len);- try std.testing.expectEqual(@as(usize, 0), m.sel.text_rows);- try std.testing.expectEqualStrings("", m.toast);- try std.testing.expect(!m.sel.active);-}diff --git a/TUI/sim.zig b/TUI/sim.zigdeleted file mode 100644index 16c1a119..00000000--- a/TUI/sim.zig+++ /dev/null@@ -1,594 +0,0 @@-//! Headless Ghostty-shaped pager. Agents drive this instead of a PTY.-//!-//! Same path the live app uses: `key.next` (CSI-u / SGR mouse / paste) →-//! `keys.handle` → `render` → `dump.visible`. No TTY, no Ghostty window.-//!-//! var term: Term = undefined;-//! term.init(alloc, 80, 24);-//! defer term.deinit();-//! _ = term.typeText("/help");-//! _ = term.enter();-//! const vis = try term.screen(); // glyphs a user would see-//! _ = try term.clickText("Called");-//!-//! Ghostty wire bytes go through `feed`:-//! click ESC [ < 0 ; COL ; ROW M (1-based cells)-//! hover ESC [ < 35 ; COL ; ROW M-//! paste ESC [ 200 ~ … ESC [ 201 ~-//! CSI-u ESC [ unicode ; mods u (Ctrl+P is ESC [ 112 ; 5 u)--const std = @import("std");-const app = @import("app.zig");-const dump = @import("dump.zig");-const engine_mod = @import("engine.zig");-const key_mod = @import("key.zig");-const keys = @import("keys.zig");-const render_mod = @import("render.zig");-const stall = @import("run_stall.zig");-const theme_mod = @import("theme.zig");-const turn = @import("turn.zig");--const Model = app.Model;-const Effect = app.Effect;-const Key = key_mod.Key;--pub const Hit = struct { x: u16, y: u16 };--pub const Term = struct {- alloc: std.mem.Allocator,- model: Model = undefined,- cols: usize = 80,- rows: usize = 24,- now_ms: u64 = 0,- last_effect: Effect = .stay,- inbuf: [16 * 1024]u8 = undefined,- pending: usize = 0,- esc_stall: u8 = 0,- esc_live: bool = false,- stash_ms: u64 = 0,- arm_ms: u64 = 0,-- pub fn init(self: *Term, alloc: std.mem.Allocator, cols: usize, rows: usize) void {- self.alloc = alloc;- self.cols = if (cols < 40) 80 else cols;- self.rows = if (rows < 12) 24 else rows;- self.now_ms = 0;- self.last_effect = .stay;- self.pending = 0;- self.esc_stall = 0;- self.esc_live = false;- self.stash_ms = 0;- self.arm_ms = 0;- key_mod.resetInputState();- self.model.setup(alloc);- }-- pub fn deinit(self: *Term) void {- self.model.deinit();- }-- /// Raw Ghostty/xterm bytes. Incomplete sequences carry between bounded- /// chunks exactly like repeated production reads. A non-stay effect stops- /// this synchronous call: bytes not yet supplied to the parser are- /// discarded because Term has no tty queue; any parser tail already copied- /// into `inbuf` remains pending for the next feed.- pub fn feed(self: *Term, bytes: []const u8) Effect {- if (bytes.len == 0) return self.last_effect;- var offset: usize = 0;- while (offset < bytes.len) {- if (self.pending == self.inbuf.len) self.abandonPending(.dropped);- const take = @min(bytes.len - offset, self.inbuf.len - self.pending);- self.feedChunk(bytes[offset .. offset + take]);- if (self.last_effect != .stay) return self.last_effect;- offset += take;- }- return self.last_effect;- }-- fn feedChunk(self: *Term, bytes: []const u8) void {- self.esc_stall = 0;- if (stall.escapeCarryExpired(self.now_ms, self.stash_ms)) key_mod.expireOrphanHead();- if (stall.armExpired(self.now_ms, self.arm_ms)) key_mod.armOrphan(false);- @memcpy(self.inbuf[self.pending .. self.pending + bytes.len], bytes);- const n = key_mod.joinOrphanHead(&self.inbuf, self.pending + bytes.len);- var i: usize = 0;- const last = @import("sim_batch.zig").apply(&self.model, self.inbuf[0..n], &i, self.now_ms);- self.pending = if (i < n) blk: {- const rest = n - i;- std.mem.copyForwards(u8, self.inbuf[0..rest], self.inbuf[i..n]);- break :blk rest;- } else 0;- // Latch before a fast operation can complete on a later quiet tick.- if (self.pending == 0) self.esc_live = false else if (!self.esc_live and (self.model.pending != null or self.model.bg != null)) self.esc_live = true;- self.last_effect = last;- }-- /// One deterministic ~25ms quiet-poll tick from run.zig.- pub fn stallTimeout(self: *Term) stall.StallVerdict {- self.esc_stall +|= 1;- const verdict = stall.stallVerdict(self.inbuf[0..self.pending], self.esc_stall, .{- .operation_live = self.esc_live or self.model.pending != null or self.model.bg != null,- .in_paste = key_mod.inPaste(),- });- switch (verdict) {- .wait => {},- .escape_key => {- self.abandonPending(.escape);- self.last_effect = keys.handle(&self.model, .escape);- },- .escape_pair => {- self.abandonPending(.none);- self.last_effect = keys.handle(&self.model, .escape);- if (self.last_effect == .stay) self.last_effect = keys.handle(&self.model, .escape);- },- .drop => self.stallDropPending(),- }- return verdict;- }-- /// The live loop gives up on a pending sequence that never finished: it- /// carries the head for one more read, arms the debris sweeper, and — if- /// the casualty was a bracketed-paste marker — synthesizes the paste_end- /// the terminal never sent (run.zig's stall path).- pub fn stallDropPending(self: *Term) void {- if (self.pending == 0) return;- self.abandonPending(.dropped);- if (key_mod.inPaste()) {- key_mod.endPaste();- _ = keys.handle(&self.model, .paste_end);- }- }-- /// run.zig's `paste_idle_ms` sweep: the terminal has gone quiet far longer- /// than any paste keeps streaming, so the latch is force-closed. Anything- /// still stuck mid-sequence belongs to the paste window this just declared- /// broken — it is carried as DEBRIS and never handed back to the stall- /// path, which would re-classify it as a key.- pub fn idlePasteSweep(self: *Term) void {- if (!key_mod.inPaste()) return;- key_mod.endPaste();- _ = keys.handle(&self.model, .paste_end);- if (self.pending == 0) return;- self.abandonPending(.dropped);- }-- fn abandonPending(self: *Term, recovery: key_mod.SequenceRecovery) void {- key_mod.abandonSequence(self.inbuf[0..self.pending], recovery);- self.stash_ms = self.now_ms;- self.arm_ms = self.now_ms;- self.pending = 0;- self.esc_stall = 0;- self.esc_live = false;- }-- pub fn press(self: *Term, k: Key) Effect {- const last = keys.handle(&self.model, k);- self.last_effect = last;- return last;- }-- pub fn typeText(self: *Term, s: []const u8) Effect {- return self.feed(s);- }-- pub fn enter(self: *Term) Effect {- return self.feed("\r");- }-- /// 1-based cell, left-button down — the SGR Ghostty sends for a click.- pub fn clickAt(self: *Term, x: u16, y: u16) Effect {- return self.sgr(0, x, y, true);- }-- /// 1-based cell, any-motion (btn 35) — hover for image chips.- pub fn hoverAt(self: *Term, x: u16, y: u16) Effect {- return self.sgr(35, x, y, true);- }-- fn sgr(self: *Term, btn: u16, x: u16, y: u16, down: bool) Effect {- var buf: [40]u8 = undefined;- const seq = std.fmt.bufPrint(&buf, "\x1b[<{d};{d};{d}{c}", .{- btn,- if (x == 0) 1 else x,- if (y == 0) 1 else y,- @as(u8, if (down) 'M' else 'm'),- }) catch return .stay;- return self.feed(seq);- }-- /// Paint, strip SGR, return the glyphs. Caller frees.- pub fn screen(self: *Term) ![]u8 {- const frame = try render_mod.render(&self.model, self.alloc, self.cols, self.rows, self.now_ms);- defer self.alloc.free(frame);- return dump.visible(self.alloc, frame);- }-- /// `screen` with ` 12|` row prefixes so an agent can pick click coordinates.- pub fn annotated(self: *Term) ![]u8 {- const vis = try self.screen();- defer self.alloc.free(vis);- var out = std.array_list.Managed(u8).init(self.alloc);- var y: u16 = 1;- var it = std.mem.splitScalar(u8, vis, '\n');- while (it.next()) |ln| : (y += 1) {- var nbuf: [8]u8 = undefined;- const num = std.fmt.bufPrint(&nbuf, "{d:3}|", .{y}) catch unreachable;- try out.appendSlice(num);- try out.appendSlice(ln);- try out.append('\n');- }- return out.toOwnedSlice();- }-- pub fn layout(self: *Term) ![]u8 {- const frame = try render_mod.render(&self.model, self.alloc, self.cols, self.rows, self.now_ms);- defer self.alloc.free(frame);- return dump.layout(self.alloc, &self.model);- }-- pub fn find(self: *Term, needle: []const u8) !?Hit {- const vis = try self.screen();- defer self.alloc.free(vis);- return locate(vis, needle);- }-- pub fn clickText(self: *Term, needle: []const u8) !bool {- const hit = try self.find(needle) orelse return false;- _ = self.clickAt(hit.x, hit.y);- return true;- }-- pub fn hoverText(self: *Term, needle: []const u8) !bool {- const hit = try self.find(needle) orelse return false;- _ = self.hoverAt(hit.x, hit.y);- return true;- }-};--/// 1-based cell of the middle glyph of the first `needle` on the dump.-pub fn locate(vis: []const u8, needle: []const u8) ?Hit {- if (needle.len == 0) return null;- var y: u16 = 1;- var it = std.mem.splitScalar(u8, vis, '\n');- while (it.next()) |ln| : (y += 1) {- if (std.mem.indexOf(u8, ln, needle)) |at| {- const prefix = theme_mod.visibleLen(ln[0..at]);- const w = theme_mod.visibleLen(needle);- const x: u16 = @intCast(prefix + 1 + w / 2);- return .{ .x = if (x == 0) 1 else x, .y = y };- }- }- return null;-}--test "typeText lands in the composer dump" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("hello");- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "hello") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "›") != null);-}--test "#692: terminal API diagnostics survive job finish and the composer recovers" {- const a = std.testing.allocator;- var term: Term = undefined;- term.init(a, 80, 24);- defer term.deinit();-- try term.model.push(.user, "trigger a provider rejection");- try term.model.push(.pending, "");- const job = try a.create(engine_mod.Job);- job.* = .{- .gpa = a,- .history = &.{},- .params = .{},- .stream = .{},- .raw = .{},- .threaded = false,- .result = try a.dupe(u8, "codex api error [invalid_request_error]: mock bad request"),- };- job.events.attach(a);- job.done.store(true, .release);- term.model.pending = job;- turn.finishJob(&term.model);-- const failed = try term.screen();- defer a.free(failed);- try std.testing.expect(std.mem.indexOf(u8, failed, "invalid_request_error") != null);- try std.testing.expect(std.mem.indexOf(u8, failed, "check /model and your API key") == null);-- _ = term.typeText("continue");- const recovered = try term.screen();- defer a.free(recovered);- try std.testing.expect(std.mem.indexOf(u8, recovered, "continue") != null);- try std.testing.expect(std.mem.indexOf(u8, recovered, "›") != null);-}--test "assistant markdown shows lists, quotes, tasks, and rules" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.assistant, "# Title\n1. first\n> quoted\n- [x] done\n- [ ] todo\n- item\n---\n_italic_");- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "Title") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "1.") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "│") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "quoted") != 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, "•") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "────────") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "italic") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "_italic_") == null);-}--test "running tool row shows live elapsed from start" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- term.model.now_ms = 0;- try term.model.pushTool(.{ .name = "bash", .detail = "sleep 2" });- term.model.history.items[0].folded = false;- term.now_ms = 1500;- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "1.5s") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "sleep 2") != null);-}--test "clickText on the verb header expands the folded tools" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.assistant, "working");- try term.model.pushTool(.{ .name = "bash" });- try term.model.pushTool(.{ .name = "bash", .detail = "ok", .done = true });- const before = try term.screen();- defer std.testing.allocator.free(before);- // 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);- // 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" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- 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("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);- try std.testing.expect(!term.model.history.items[0].folded);-}--test "type /help then enter opens the help overlay" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("/help");- _ = term.enter();- try std.testing.expectEqual(app.Overlay.help, term.model.overlay);- const vis = try term.screen();- defer std.testing.allocator.free(vis);- // A sheet opens at its FIRST row — it used to open at its last, so the- // only part of /help you ever saw was the tail of the command list.- try std.testing.expect(std.mem.indexOf(u8, vis, "Shortcuts") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "Tab prompt / scrollback") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "/quit") == null);- // ...and paging it reaches the rest.- var i: usize = 0;- while (i < 4) : (i += 1) _ = term.feed("\x1b[6~");- const paged = try term.screen();- defer std.testing.allocator.free(paged);- try std.testing.expect(std.mem.indexOf(u8, paged, "/vim-mode") != null);-}--test "type /cache then enter opens the observability overlay" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("/cache");- _ = term.enter();- try std.testing.expectEqual(app.Overlay.debug, term.model.overlay);-}--test "hoverText on an image chip opens the preview" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.user, "@[/tmp/shot.png] look");- try std.testing.expect(try term.hoverText("[Image #1]"));- try std.testing.expectEqual(app.Overlay.image, term.model.overlay);- try std.testing.expectEqualStrings("/tmp/shot.png", term.model.preview_path);-}--test "a 1003 hover flood during a live turn never types itself into the frame" {- const engine = @import("engine.zig");- key_mod.armOrphan(false);- defer key_mod.armOrphan(false);- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.user, "explain this");- const job = try std.testing.allocator.create(engine.Job);- defer std.testing.allocator.destroy(job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- };- try term.model.push(.pending, "");- term.model.pending = job;- defer term.model.pending = null;-- // The exact bytes off the user's terminal: SGR motion reports under- // ?1003h, arriving in ragged chunks while a slow frame paints, with the- // loop giving up on the head that never finished.- const flood = "\x1b[<39;7;32M\x1b[<39;4;32M\x1b[<39;3;33M\x1b[<39;1;33M";- var cut: usize = 1;- while (cut < flood.len) : (cut += 1) {- _ = term.feed(flood[0..cut]);- _ = term.feed(flood[cut..]);- term.stallDropPending();- _ = term.feed(flood);- }- try std.testing.expectEqualStrings("", term.model.input.getValue());- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- // A half-arrived report must not read as Escape either — that cancelled- // the turn under the user.- try std.testing.expect(!term.model.cancel_requested);- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "39;7;32M") == null);- try std.testing.expect(std.mem.indexOf(u8, vis, ";32M") == null);- try std.testing.expect(std.mem.indexOf(u8, vis, "Enter:queue") != null);-}--test "annotated dump prefixes 1-based rows" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("abc");- const ann = try term.annotated();- defer std.testing.allocator.free(ann);- try std.testing.expect(std.mem.indexOf(u8, ann, " 1|") != null);- try std.testing.expect(std.mem.indexOf(u8, ann, "abc") != null);-}--test "a dropped sequence does not turn bare Backspace into delete-to-start" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("draft");- key_mod.held = 8; // a lost Super release leaves the old latch behind- _ = term.feed("\x1b[57444;1:3");- term.stallDropPending();- _ = term.feed("\x7f");- try std.testing.expectEqualStrings("draf", term.model.input.getValue());-}--test "a paste that never terminates does not wedge the composer (#536/#548)" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- // The terminator is lost in flight: `pasting` latches and swallows Enter,- // Tab, the slash menu and every overlay — the 'TUI froze' report.- _ = term.feed("\x1b[200~/help");- try std.testing.expect(term.model.pasting);- _ = term.press(.enter);- try std.testing.expect(term.model.pasting);- // Escape is the in-band hatch: it breaks the latch instead of vanishing.- _ = term.press(.escape);- try std.testing.expect(!term.model.pasting);- try std.testing.expect(!key_mod.inPaste());- // ...and the composer works again: Tab moves focus, Escape reaches esc().- _ = term.press(.tab);- try std.testing.expectEqual(app.Focus.scrollback, term.model.focus);-}--test "giving up on a split paste terminator closes the paste, tail and all (#532)" {- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.feed("\x1b[200~hello");- _ = term.feed("\x1b[201");- try std.testing.expect(key_mod.inPaste());- key_mod.held = 8;- term.stallDropPending(); // the loop waited the marker out- try std.testing.expect(!key_mod.inPaste());- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- try std.testing.expect(!term.model.pasting);- // The late `~` rejoins its carried head instead of typing itself.- _ = term.feed("~");- try std.testing.expectEqualStrings("hello ", term.model.input.getValue());-}--test "the idle paste sweep never fires a phantom Escape at a live turn" {- const engine = @import("engine.zig");- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- defer key_mod.armOrphan(false);- try term.model.push(.user, "!sleep 30");- const job = try std.testing.allocator.create(engine.Job);- defer std.testing.allocator.destroy(job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- };- try term.model.push(.pending, "");- term.model.pending = job;- defer term.model.pending = null;-- // A paste opens, its terminator is cut in flight, and the ESC that opened- // `CSI 201~` is left sitting in the pending buffer.- _ = term.feed("\x1b[200~draft text");- _ = term.feed("\x1b");- try std.testing.expect(key_mod.inPaste());- try std.testing.expectEqual(@as(usize, 1), term.pending);-- // Two seconds of quiet: the sweep closes the paste. The pending ESC must- // go with it. Handing it back to the stall path re-classified it as the- // Escape KEY the instant `in_paste` cleared, cancelling the live turn at- // t=2.03s with no user keypress at all — and the same path wiped a- // composer that had a draft in it.- key_mod.held = 8;- term.idlePasteSweep();- try std.testing.expect(!key_mod.inPaste());- try std.testing.expectEqual(@as(u32, 0), key_mod.held);- try std.testing.expect(!term.model.pasting);- try std.testing.expect(!term.model.cancel_requested);- try std.testing.expectEqual(@as(usize, 0), term.pending);- try std.testing.expectEqualStrings("draft text ", term.model.input.getValue());-- // ...and the late terminator still rejoins its carried head rather than- // typing `[201~` on the end of the draft.- _ = term.feed("[201~");- try std.testing.expectEqualStrings("draft text ", term.model.input.getValue());-}--test "live prose tail paints markdown before the turn settles" {- const engine = @import("engine.zig");- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- try term.model.push(.user, "list them");- var sbuf: [256]u8 = undefined;- const job = try std.testing.allocator.create(engine.Job);- defer std.testing.allocator.destroy(job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{ .buf = &sbuf },- .threaded = false,- };- job.stream.appendBytes("- first item\nthis is **bold** text\n");- try term.model.push(.pending, "");- term.model.pending = job;- defer term.model.pending = null;- const vis = try term.screen();- defer std.testing.allocator.free(vis);- try std.testing.expect(std.mem.indexOf(u8, vis, "•") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "**bold**") == null);- try std.testing.expect(std.mem.indexOf(u8, vis, "bold") != null);- try std.testing.expect(std.mem.indexOf(u8, vis, "- first") == null);-}diff --git a/TUI/sim_batch.zig b/TUI/sim_batch.zigdeleted file mode 100644index fdd9e59b..00000000--- a/TUI/sim_batch.zig+++ /dev/null@@ -1,18 +0,0 @@-//! Simulator input uses the production parser, read-burst latch, bounded-//! pacing batch and handleBatchItem seam (run.zig), not direct key dispatch.-const app = @import("app.zig");-const keys = @import("keys.zig");-const paste = @import("key_paste.zig");--pub fn apply(m: *app.Model, bytes: []const u8, i: *usize, now_ms: u64) app.Effect {- paste.setBurstRead(paste.burstRead(bytes, now_ms));- var last: app.Effect = .stay;- var batch: @import("input_batch.zig").Decoder = .{};- while (batch.next(bytes, i)) |items| {- for (items) |item| {- last = keys.handleBatchItem(m, item);- if (last != .stay) return last;- }- }- return last;-}diff --git a/TUI/spec_terminal_modes_conformance.zig b/TUI/spec_terminal_modes_conformance.zigdeleted file mode 100644index bd0caef7..00000000--- a/TUI/spec_terminal_modes_conformance.zig+++ /dev/null@@ -1,130 +0,0 @@-//! Impl half of TerminalModes: the LIVE enable/restore constants (run.zig-//! enable_seq, restore.zig seq) are parsed into mode ops and folded with a-//! mirror of the model; the fixture pins both the byte strings and the-//! folded outcomes, so drift in either the constants or the model trips.--const std = @import("std");-const Value = std.json.Value;-const run = @import("run.zig");-const restore = @import("restore.zig");--const fixtures_json = @embedFile("spec_terminal_modes");--const default_on = [_]u32{ 7, 25 };--const Fold = struct {- // mode -> final op (true = h). Tiny domains; linear scan is fine.- modes: [16]struct { n: u32, v: bool } = undefined,- len: usize = 0,- depth: u32 = 0,-- fn setFinal(self: *@This(), n: u32, v: bool) void {- for (self.modes[0..self.len]) |*m| if (m.n == n) {- m.v = v;- return;- };- self.modes[self.len] = .{ .n = n, .v = v };- self.len += 1;- }-- fn isDefaultOn(n: u32) bool {- for (default_on) |d| if (d == n) return true;- return false;- }-- fn deviations(self: *const @This(), out: []u32) []u32 {- var k: usize = 0;- for (self.modes[0..self.len]) |m| if (m.v != isDefaultOn(m.n)) {- out[k] = m.n;- k += 1;- };- std.mem.sort(u32, out[0..k], {}, std.sort.asc(u32));- return out[0..k];- }-};--/// Scan a byte stream for DEC private-mode ops and kitty push/pop, in order.-fn fold(stream: []const u8) Fold {- var f: Fold = .{};- var i: usize = 0;- while (i + 2 < stream.len) : (i += 1) {- if (stream[i] != 0x1b or stream[i + 1] != '[') continue;- var j = i + 2;- if (stream[j] == '?') {- j += 1;- while (j < stream.len and ((stream[j] >= '0' and stream[j] <= '9') or stream[j] == ';')) j += 1;- if (j < stream.len and (stream[j] == 'h' or stream[j] == 'l')) {- // Apply the final h/l to every ';'-separated parameter.- const v = stream[j] == 'h';- var k = i + 3;- var m: u32 = 0;- while (k <= j) : (k += 1) {- const c = stream[k];- if (c >= '0' and c <= '9') {- m = m * 10 + (c - '0');- } else {- f.setFinal(m, v);- m = 0;- }- }- i = j;- }- } else if (stream[j] == '>' or stream[j] == '<') {- const open = stream[j];- j += 1;- while (j < stream.len and ((stream[j] >= '0' and stream[j] <= '9') or stream[j] == ';')) j += 1;- if (j < stream.len and stream[j] == 'u') {- if (open == '>') f.depth += 1 else f.depth -|= 1;- i = j;- }- }- }- return f;-}--test "spec/terminal_modes: the live constants equal the fixture's byte strings" {- const gpa = std.testing.allocator;- var parsed = try std.json.parseFromSlice(Value, gpa, fixtures_json, .{});- defer parsed.deinit();- try std.testing.expectEqualStrings(parsed.value.object.get("graff_enable").?.string, run.enable_seq);- try std.testing.expectEqualStrings(parsed.value.object.get("graff_restore").?.string, restore.seq);-}--test "spec/terminal_modes: every fixture stream folds to its recorded outcome" {- const gpa = std.testing.allocator;- var parsed = try std.json.parseFromSlice(Value, gpa, fixtures_json, .{});- defer parsed.deinit();- const cells = parsed.value.object.get("cells").?.array.items;- try std.testing.expectEqual(@as(usize, 14), cells.len);- for (cells) |cell_v| {- const cell = cell_v.object;- const name = cell.get("name").?.string;- var f = fold(cell.get("stream").?.string);- var buf: [16]u32 = undefined;- const devs = f.deviations(&buf);- const want_devs = cell.get("deviations").?.array.items;- const want_depth: u32 = @intCast(cell.get("depth").?.integer);- const want_balanced = cell.get("balanced").?.bool;- const balanced = devs.len == 0 and f.depth == 0;- var match = devs.len == want_devs.len and f.depth == want_depth and balanced == want_balanced;- if (match) for (devs, want_devs) |g, w| {- if (g != @as(u32, @intCast(w.integer))) match = false;- };- if (!match) {- std.debug.print("\ncounterexample {s}: depth {}/{} devs {any}\n", .{ name, want_depth, f.depth, devs });- return error.CatalogMismatch;- }- }-}--test "spec/terminal_modes: graff's lifecycle balances and its restore leaves the alt-screen last" {- var enable_then_restore = std.ArrayList(u8).empty;- defer enable_then_restore.deinit(std.testing.allocator);- try enable_then_restore.appendSlice(std.testing.allocator, run.enable_seq);- try enable_then_restore.appendSlice(std.testing.allocator, restore.seq);- var f = fold(enable_then_restore.items);- var buf: [16]u32 = undefined;- try std.testing.expectEqual(@as(usize, 0), f.deviations(&buf).len);- try std.testing.expectEqual(@as(u32, 0), f.depth);- try std.testing.expect(std.mem.endsWith(u8, restore.seq, "\x1b[?1049l"));-}diff --git a/TUI/syntax.zig b/TUI/syntax.zigdeleted file mode 100644index 63de62bd..00000000--- a/TUI/syntax.zig+++ /dev/null@@ -1,361 +0,0 @@-//! Code-fence syntax highlighting — grok-build's token classes and colors-//! (grok-night / grok-day tmThemes), driven by a small line-resumable lexer-//! instead of syntect. One `State` threads across a fence's lines so block-//! comments and multiline strings survive line breaks; clone it for a-//! streaming tail the way grok's open-fence cache does.--const std = @import("std");--pub const Class = enum { text, comment, string, escape, number, keyword, type_name, builtin, function, operator, bracket, property };--/// grok-night (dark) token colors, verbatim from the tmTheme.-fn darkColor(c: Class) []const u8 {- return switch (c) {- .text => "\x1b[38;2;200;200;200m", // #c8c8c8- .comment => "\x1b[38;2;81;89;125m", // #51597d- .string => "\x1b[38;2;158;206;106m", // #9ece6a- .escape => "\x1b[38;2;137;221;255m", // #89ddff- .number => "\x1b[38;2;255;158;100m", // #ff9e64- .keyword => "\x1b[38;2;187;154;247m", // #bb9af7- .type_name => "\x1b[38;2;13;185;215m", // #0db9d7- .builtin => "\x1b[38;2;13;185;215m", // #0db9d7- .function => "\x1b[38;2;122;162;247m", // #7aa2f7- .operator => "\x1b[38;2;137;221;255m", // #89ddff- .bracket => "\x1b[38;2;154;189;245m", // #9abdf5- .property => "\x1b[38;2;125;207;255m", // #7dcfff- };-}--/// grok-day (light) token colors, verbatim from the tmTheme.-fn lightColor(c: Class) []const u8 {- return switch (c) {- .text => "\x1b[38;2;68;68;68m", // #444444- .comment => "\x1b[38;2;144;144;144m", // #909090- .string => "\x1b[38;2;55;142;35m", // #378E23- .escape => "\x1b[38;2;85;128;168m", // #5580A8- .number => "\x1b[38;2;195;105;30m", // #C3691E- .keyword => "\x1b[38;2;125;75;198m", // #7D4BC6- .type_name => "\x1b[38;2;15;135;162m", // #0F87A2- .builtin => "\x1b[38;2;15;135;162m", // #0F87A2- .function => "\x1b[38;2;47;100;210m", // #2F64D2- .operator => "\x1b[38;2;85;128;168m", // #5580A8- .bracket => "\x1b[38;2;74;114;176m", // #4A72B0- .property => "\x1b[38;2;0;130;170m", // #0082AA- };-}--pub fn color(c: Class, light: bool) []const u8 {- return if (light) lightColor(c) else darkColor(c);-}--/// Code-block background band (grok `md_code_bg`): #1c1c1c dark / #e4e4e4 light.-pub fn codeBg(light: bool) []const u8 {- return if (light) "\x1b[48;2;228;228;228m" else "\x1b[48;2;28;28;28m";-}--pub const Lang = struct {- names: []const []const u8, // fence tokens AND file extensions- line_comment: []const u8,- block_open: []const u8 = "",- block_close: []const u8 = "",- keywords: []const []const u8,- types: []const []const u8,- builtins: []const []const u8 = &.{},- hash_types_upper: bool = false, // Capitalized identifiers are types (Zig/Rust/Go style)-};--const zig_lang: Lang = .{- .names = &.{ "zig", "ziglang" },- .line_comment = "//",- .keywords = &.{ "const", "var", "fn", "pub", "return", "if", "else", "while", "for", "switch", "defer", "errdefer", "try", "catch", "orelse", "break", "continue", "struct", "enum", "union", "error", "test", "comptime", "inline", "export", "extern", "and", "or", "unreachable", "usingnamespace", "async", "await", "threadlocal", "packed", "volatile", "align", "callconv", "noalias" },- .types = &.{ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", "f32", "f64", "bool", "void", "type", "anytype", "anyerror", "noreturn", "u21", "c_int", "null", "undefined", "true", "false" },- .hash_types_upper = true,-};-const rust_lang: Lang = .{- .names = &.{ "rust", "rs" },- .line_comment = "//",- .block_open = "/*",- .block_close = "*/",- .keywords = &.{ "fn", "let", "mut", "pub", "use", "mod", "struct", "enum", "impl", "trait", "return", "if", "else", "while", "for", "loop", "match", "break", "continue", "move", "ref", "where", "async", "await", "dyn", "unsafe", "extern", "crate", "self", "Self", "super", "static", "const", "type", "in", "as" },- .types = &.{ "u8", "u16", "u32", "u64", "usize", "i8", "i16", "i32", "i64", "isize", "f32", "f64", "bool", "str", "String", "Vec", "Option", "Result", "Box", "true", "false", "None", "Some", "Ok", "Err" },- .hash_types_upper = true,-};-const py_lang: Lang = .{- .names = &.{ "python", "py", "python3" },- .line_comment = "#",- .keywords = &.{ "def", "class", "return", "if", "elif", "else", "while", "for", "in", "import", "from", "as", "with", "try", "except", "finally", "raise", "pass", "break", "continue", "lambda", "yield", "global", "nonlocal", "assert", "del", "not", "and", "or", "is", "async", "await", "match", "case" },- .types = &.{ "int", "float", "str", "bool", "list", "dict", "set", "tuple", "bytes", "None", "True", "False", "self", "object" },- .builtins = &.{ "print", "len", "range", "open", "enumerate", "zip", "map", "filter", "sorted", "isinstance", "super", "type", "getattr", "setattr", "hasattr" },-};-const js_lang: Lang = .{- .names = &.{ "javascript", "js", "typescript", "ts", "jsx", "tsx", "mjs", "cjs" },- .line_comment = "//",- .block_open = "/*",- .block_close = "*/",- .keywords = &.{ "function", "const", "let", "var", "return", "if", "else", "while", "for", "of", "in", "class", "extends", "new", "import", "export", "from", "default", "async", "await", "try", "catch", "finally", "throw", "switch", "case", "break", "continue", "typeof", "instanceof", "delete", "yield", "static", "get", "set", "interface", "implements", "enum", "declare", "readonly", "as", "satisfies" },- .types = &.{ "string", "number", "boolean", "object", "any", "unknown", "never", "undefined", "null", "true", "false", "this", "void", "Promise", "Array", "Map", "Set" },- .builtins = &.{ "console", "require", "module", "process", "JSON", "Math", "Object", "window", "document" },- .hash_types_upper = true,-};-const go_lang: Lang = .{- .names = &.{ "go", "golang" },- .line_comment = "//",- .block_open = "/*",- .block_close = "*/",- .keywords = &.{ "func", "var", "const", "type", "struct", "interface", "map", "chan", "return", "if", "else", "for", "range", "switch", "case", "default", "break", "continue", "go", "defer", "select", "package", "import", "fallthrough", "goto" },- .types = &.{ "string", "int", "int8", "int16", "int32", "int64", "uint", "uint8", "uint16", "uint32", "uint64", "byte", "rune", "float32", "float64", "bool", "error", "any", "nil", "true", "false", "iota" },- .builtins = &.{ "make", "len", "cap", "append", "copy", "new", "delete", "panic", "recover", "print", "println" },- .hash_types_upper = true,-};-const c_lang: Lang = .{- .names = &.{ "c", "h", "cpp", "cc", "cxx", "hpp", "c++" },- .line_comment = "//",- .block_open = "/*",- .block_close = "*/",- .keywords = &.{ "if", "else", "while", "for", "return", "break", "continue", "switch", "case", "default", "struct", "enum", "union", "typedef", "static", "extern", "const", "inline", "sizeof", "goto", "do", "class", "public", "private", "protected", "template", "typename", "namespace", "using", "new", "delete", "virtual", "override", "nullptr", "auto", "constexpr" },- .types = &.{ "int", "char", "long", "short", "unsigned", "signed", "float", "double", "void", "bool", "size_t", "uint8_t", "uint16_t", "uint32_t", "uint64_t", "int8_t", "int16_t", "int32_t", "int64_t", "true", "false", "NULL" },- .hash_types_upper = true,-};-const sh_lang: Lang = .{- .names = &.{ "bash", "sh", "shell", "zsh", "console" },- .line_comment = "#",- .keywords = &.{ "if", "then", "else", "elif", "fi", "for", "while", "do", "done", "case", "esac", "function", "return", "local", "export", "source", "in", "select", "until", "declare", "readonly", "shift", "exit", "set", "unset", "trap" },- .types = &.{"true"},- .builtins = &.{ "echo", "cd", "ls", "grep", "sed", "awk", "cat", "curl", "git", "rm", "cp", "mv", "mkdir", "printf", "read", "test", "which", "find", "xargs", "sort", "head", "tail" },-};-const json_lang: Lang = .{- .names = &.{"json"},- .line_comment = "",- .keywords = &.{},- .types = &.{ "true", "false", "null" },-};-const yaml_lang: Lang = .{- .names = &.{ "yaml", "yml" },- .line_comment = "#",- .keywords = &.{},- .types = &.{ "true", "false", "null", "yes", "no" },-};-const sql_lang: Lang = .{- .names = &.{ "sql", "sqlite", "postgres", "mysql" },- .line_comment = "--",- .block_open = "/*",- .block_close = "*/",- .keywords = &.{ "select", "from", "where", "insert", "into", "values", "update", "set", "delete", "create", "table", "index", "join", "left", "right", "inner", "outer", "on", "group", "by", "order", "having", "limit", "offset", "as", "and", "or", "not", "in", "is", "like", "between", "union", "all", "distinct", "primary", "key", "foreign", "references", "drop", "alter", "add", "SELECT", "FROM", "WHERE", "INSERT", "INTO", "VALUES", "UPDATE", "SET", "DELETE", "CREATE", "TABLE", "INDEX", "JOIN", "LEFT", "RIGHT", "INNER", "OUTER", "ON", "GROUP", "BY", "ORDER", "HAVING", "LIMIT", "AS", "AND", "OR", "NOT", "IN", "IS", "LIKE", "UNION", "PRIMARY", "KEY", "DROP", "ALTER", "ADD" },- .types = &.{ "integer", "text", "real", "blob", "varchar", "boolean", "date", "timestamp", "INTEGER", "TEXT", "REAL", "BLOB", "VARCHAR", "BOOLEAN", "NULL" },-};--const langs = [_]*const Lang{ &zig_lang, &rust_lang, &py_lang, &js_lang, &go_lang, &c_lang, &sh_lang, &json_lang, &yaml_lang, &sql_lang };--/// Fence-info resolution, grok order: `start:end:path` citation form first-/// (extension lookup), then the whole info string as a token. Unknown → null-/// (the fence still gets the background band, just uncolored text).-pub fn resolve(fence_info: []const u8) ?*const Lang {- const info = std.mem.trim(u8, fence_info, " \t\r"); // CRLF fences must still resolve- if (info.len == 0) return null;- blk: {- var it = std.mem.splitScalar(u8, info, ':');- const a = it.next() orelse break :blk;- const b = it.next() orelse break :blk;- const path = it.rest();- if (a.len == 0 or b.len == 0 or path.len == 0) break :blk;- for (a) |ch| if (!std.ascii.isDigit(ch)) break :blk;- for (b) |ch| if (!std.ascii.isDigit(ch)) break :blk;- const dot = std.mem.lastIndexOfScalar(u8, path, '.') orelse break :blk;- if (byName(path[dot + 1 ..])) |l| return l;- break :blk;- }- return byName(info);-}--fn byName(token: []const u8) ?*const Lang {- var buf: [24]u8 = undefined;- if (token.len == 0 or token.len > buf.len) return null;- const lower = std.ascii.lowerString(&buf, token);- for (&langs) |l| {- for (l.names) |n| if (std.mem.eql(u8, lower, n)) return l;- }- return null;-}--/// Lexer state threaded across a fence's lines.-pub const State = struct {- in_block_comment: bool = false,-};--fn isIdent(c: u8) bool {- return std.ascii.isAlphanumeric(c) or c == '_' or c == '@';-}--fn listHas(list: []const []const u8, word: []const u8) bool {- for (list) |w| if (std.mem.eql(u8, w, word)) return true;- return false;-}--/// Highlight one line into `out` as SGR spans. Emits fg colors only — the-/// caller owns the background band and the trailing reset.-pub fn highlightLine(out: *std.array_list.Managed(u8), line: []const u8, lang: *const Lang, st: *State, light: bool) !void {- var i: usize = 0;- var cls: ?Class = null;- while (i < line.len) {- if (st.in_block_comment) {- const close = std.mem.indexOf(u8, line[i..], lang.block_close);- const end = if (close) |c| i + c + lang.block_close.len else line.len;- try emit(out, &cls, .comment, line[i..end], light);- if (close != null) st.in_block_comment = false;- i = end;- continue;- }- const c = line[i];- // comments- if (lang.line_comment.len > 0 and std.mem.startsWith(u8, line[i..], lang.line_comment)) {- try emit(out, &cls, .comment, line[i..], light);- break;- }- if (lang.block_open.len > 0 and std.mem.startsWith(u8, line[i..], lang.block_open)) {- st.in_block_comment = true;- try emit(out, &cls, .comment, line[i .. i + lang.block_open.len], light);- i += lang.block_open.len;- continue;- }- // strings (single-line; escapes highlighted inside)- if (c == '"' or c == '\'' or c == '`') {- const quote = c;- var j = i + 1;- try emit(out, &cls, .string, line[i .. i + 1], light);- while (j < line.len) {- if (line[j] == '\\') {- // A trailing backslash (shell continuation) has no pair —- // consume it alone or the scanner loops forever (P0: froze- // the whole TUI at 100% CPU on `echo "a \` fences).- const esc_end = @min(j + 2, line.len);- try emit(out, &cls, .escape, line[j..esc_end], light);- j = esc_end;- continue;- }- if (line[j] == quote) break;- const k = std.mem.indexOfAnyPos(u8, line, j, &.{ '\\', quote }) orelse line.len;- try emit(out, &cls, .string, line[j..k], light);- j = k;- }- if (j < line.len) {- try emit(out, &cls, .string, line[j .. j + 1], light);- j += 1;- }- i = j;- continue;- }- // numbers- if (std.ascii.isDigit(c)) {- var j = i + 1;- while (j < line.len and (std.ascii.isHex(line[j]) or line[j] == '.' or line[j] == 'x' or line[j] == '_' or line[j] == 'o' or line[j] == 'b')) j += 1;- try emit(out, &cls, .number, line[i..j], light);- i = j;- continue;- }- // identifiers- if (std.ascii.isAlphabetic(c) or c == '_' or c == '@') {- var j = i + 1;- while (j < line.len and isIdent(line[j])) j += 1;- const word = line[i..j];- const wc: Class = if (listHas(lang.keywords, word))- .keyword- else if (listHas(lang.types, word))- .type_name- else if (listHas(lang.builtins, word))- .builtin- else if (word[0] == '@')- .builtin- else if (j < line.len and line[j] == '(')- .function- else if (lang.hash_types_upper and std.ascii.isUpper(word[0]))- .type_name- else if (j < line.len and line[j] == ':' and lang == &json_lang)- .property- else- .text;- try emit(out, &cls, wc, word, light);- i = j;- continue;- }- // brackets vs operators vs plain- const oc: Class = switch (c) {- '(', ')', '[', ']', '{', '}' => .bracket,- '+', '-', '*', '/', '=', '<', '>', '!', '&', '|', '^', '%', '~', '?', ';', ':', ',', '.' => .operator,- else => .text,- };- try emit(out, &cls, oc, line[i .. i + 1], light);- i += 1;- }-}--fn emit(out: *std.array_list.Managed(u8), current: *?Class, cls: Class, text: []const u8, light: bool) !void {- if (text.len == 0) return;- if (current.* != cls) {- try out.appendSlice(color(cls, light));- current.* = cls;- }- try out.appendSlice(text);-}--test "zig line: keywords, types, strings, numbers, comment take grok-night colors" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- var st: State = .{};- try highlightLine(&out, "const x: u32 = 0x1f; // note \"quoted\"", &zig_lang, &st, false);- const s = out.items;- try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;187;154;247mconst") != null); // keyword- try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;13;185;215mu32") != null); // type- try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;255;158;100m0x1f") != null); // number- try std.testing.expect(std.mem.indexOf(u8, s, "\x1b[38;2;81;89;125m// note \"quoted\"") != null); // comment eats the rest-}--test "block comment state survives across lines" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- var st: State = .{};- try highlightLine(&out, "let a = 1; /* open", &js_lang, &st, false);- try std.testing.expect(st.in_block_comment);- out.clearRetainingCapacity();- try highlightLine(&out, "still comment */ let b = 2;", &js_lang, &st, false);- try std.testing.expect(!st.in_block_comment);- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;81;89;125mstill comment */") != null);- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;187;154;247mlet") != null);-}--test "fence info resolution: token, citation path, unknown" {- try std.testing.expect(resolve("rust") == &rust_lang);- try std.testing.expect(resolve("py") == &py_lang);- try std.testing.expect(resolve("37:65:crates/foo/src/bar.rs") == &rust_lang);- try std.testing.expect(resolve("rust title=x") == null); // whole-string token, grok semantics- try std.testing.expect(resolve("") == null);- try std.testing.expect(resolve("madeuplang") == null);-}--test "light polarity swaps to grok-day colors" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- var st: State = .{};- try highlightLine(&out, "def f():", &py_lang, &st, true);- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;125;75;198mdef") != null); // #7D4BC6-}--test "strings color their escapes separately" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- var st: State = .{};- try highlightLine(&out, "s = \"a\\nb\"", &py_lang, &st, false);- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;137;221;255m\\n") != null);- // the opening quote and 'a' share one string span; 'b' re-opens it after the escape- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106m\"a") != null);- try std.testing.expect(std.mem.indexOf(u8, out.items, "\x1b[38;2;158;206;106mb") != null);-}--test "P0 regression: a trailing backslash inside a string terminates" {- var out = std.array_list.Managed(u8).init(std.testing.allocator);- defer out.deinit();- var st: State = .{};- try highlightLine(&out, "echo \"hello \\", &sh_lang, &st, false);- try highlightLine(&out, "s = 'unterminated \\", &py_lang, &st, false);- try std.testing.expect(out.items.len > 0);- try std.testing.expect(resolve("zig\r") == &zig_lang);-}diff --git a/TUI/theme.zig b/TUI/theme.zigdeleted file mode 100644index 4efb0f20..00000000--- a/TUI/theme.zig+++ /dev/null@@ -1,593 +0,0 @@-//! Theme slots as fixed SGR string literals (never padded rgb buffers).--const std = @import("std");--pub const Id = enum {- night,- day,- tokyo,- rose,- oscura,-- pub fn label(self: Id) []const u8 {- return switch (self) {- .night => "Grok Night",- .day => "Grok Day",- .tokyo => "Tokyo Night",- .rose => "Rosé Pine",- .oscura => "Oscura Midnight",- };- }-- pub fn aliases(self: Id) []const []const u8 {- return switch (self) {- .night => &.{ "night", "dark", "groknight", "codegraff" },- .day => &.{ "day", "light", "grokday" },- .tokyo => &.{ "tokyo", "tokyonight", "tokyo-night" },- .rose => &.{ "rose", "rosepine", "rose-pine" },- .oscura => &.{ "oscura", "oscura-midnight" },- };- }-};--pub const Theme = struct {- id: Id,- accent: []const u8,- text: []const u8,- muted: []const u8,- error_fg: []const u8,- ok: []const u8,- border: []const u8,- /// Focused prompt border (Grok `prompt_border_active`).- focus: []const u8,- /// Truecolor background. Applied once per line so the pager is one field.- bg: []const u8,-};--/// Reset fg/weight only — never 49 — so the theme background stays put.-pub const reset = "\x1b[39;22;23;24m";-pub const bold = "\x1b[1m";-pub const dim = "\x1b[2m";--// Grok Night tokens — used by tests and as the default pager palette.-pub const grok_magenta = "\x1b[38;2;187;154;247m"; // #bb9af7-pub const grok_red = "\x1b[38;2;247;118;142m"; // #f7768e-pub const emerald = grok_magenta; // markdown tests pass this as the accent-pub const zinc200 = "\x1b[38;2;225;225;225m"; // Grok FG #e1e1e1-pub const zinc400 = "\x1b[38;2;108;108;108m"; // Grok COMMENT #6c6c6c-pub const zinc500 = "\x1b[38;2;80;80;88m";-pub const coral = grok_red;-pub const mint = "\x1b[38;2;158;206;106m"; // #9ece6a-pub const white = zinc200;-pub const bright = zinc400;--pub const all = [_]Id{ .night, .day, .tokyo, .rose, .oscura };--pub fn of(id: Id) Theme {- return switch (id) {- // xai-grok-pager-render groknight / grokday / tokyonight / rosepine / oscura.- .night => .{ .id = .night, .accent = grok_magenta, .text = "\x1b[38;2;225;225;225m", .muted = "\x1b[38;2;108;108;108m", .error_fg = grok_red, .ok = "\x1b[38;2;158;206;106m", .border = "\x1b[38;2;50;50;55m", .focus = "\x1b[38;2;80;80;88m", .bg = "\x1b[48;2;20;20;20m" },- .day => .{ .id = .day, .accent = "\x1b[38;2;5;150;105m", .text = "\x1b[38;2;32;37;34m", .muted = "\x1b[38;2;98;107;101m", .error_fg = "\x1b[38;2;190;52;71m", .ok = "\x1b[38;2;4;120;87m", .border = "\x1b[38;2;205;212;207m", .focus = "\x1b[38;2;5;150;105m", .bg = "\x1b[48;2;248;249;247m" },- .tokyo => .{ .id = .tokyo, .accent = grok_magenta, .text = "\x1b[38;2;192;202;245m", .muted = "\x1b[38;2;86;95;137m", .error_fg = grok_red, .ok = "\x1b[38;2;158;206;106m", .border = "\x1b[38;2;50;62;100m", .focus = "\x1b[38;2;75;92;140m", .bg = "\x1b[48;2;36;40;59m" },- .rose => .{ .id = .rose, .accent = "\x1b[38;2;196;167;231m", .text = "\x1b[38;2;224;222;244m", .muted = "\x1b[38;2;110;106;134m", .error_fg = "\x1b[38;2;235;111;146m", .ok = "\x1b[38;2;156;207;216m", .border = "\x1b[38;2;68;65;99m", .focus = "\x1b[38;2;86;82;110m", .bg = "\x1b[48;2;35;33;54m" },- .oscura => .{ .id = .oscura, .accent = "\x1b[38;2;155;126;206m", .text = "\x1b[38;2;228;228;228m", .muted = "\x1b[38;2;129;134;143m", .error_fg = "\x1b[38;2;220;90;100m", .ok = "\x1b[38;2;80;180;140m", .border = "\x1b[38;2;36;32;52m", .focus = "\x1b[38;2;52;48;72m", .bg = "\x1b[48;2;3;3;4m" },- };-}--pub fn paint(a: std.mem.Allocator, sgr: []const u8, text: []const u8) ![]const u8 {- return std.fmt.allocPrint(a, "{s}{s}{s}", .{ sgr, text, reset });-}--pub fn parse(name: []const u8) ?Id {- if (name.len == 0 or name.len > 32) return null;- var buf: [32]u8 = undefined;- const lower = std.ascii.lowerString(&buf, name);- for (all) |id| {- for (id.aliases()) |al| {- if (std.mem.eql(u8, lower, al)) return id;- }- }- return null;-}--pub fn next(id: Id) Id {- return @enumFromInt((@intFromEnum(id) + 1) % all.len);-}--/// grok's polarity test: BT.709 luminance over sRGB-linearized channels,-/// light at >= 0.5. Only the 1-bit answer is kept — the palette stays fixed.-pub fn classifyLight(r: u8, g: u8, b: u8) bool {- const lum = 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);- return lum >= 0.5;-}--fn linear(c: u8) f64 {- const s = @as(f64, @floatFromInt(c)) / 255.0;- return if (s <= 0.04045) s / 12.92 else std.math.pow(f64, (s + 0.055) / 1.055, 2.4);-}--test "classifyLight: grok-night bg is dark, grok-day bg is light" {- try std.testing.expect(!classifyLight(0x14, 0x14, 0x14));- try std.testing.expect(!classifyLight(0x24, 0x28, 0x3b)); // tokyo storm- try std.testing.expect(classifyLight(0xf6, 0xf6, 0xf6));- try std.testing.expect(classifyLight(0xee, 0xee, 0xee));-}--/// Index just past the escape sequence starting at `start` (s[start] == 0x1b).-/// Skips CSI, OSC/DCS/APC/PM/SOS (to BEL or ST), SS3, and ESC+char — a-/// truncation mid-sequence would emit broken escapes into the frame.-pub fn skipEsc(s: []const u8, start: usize) usize {- var i = start + 1;- if (i >= s.len) return i;- switch (s[i]) {- '[' => {- i += 1;- while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}- if (i < s.len) i += 1;- },- ']', 'P', '_', '^', 'X' => {- i += 1;- while (i < s.len) : (i += 1) {- if (s[i] == 0x07) {- i += 1;- break;- }- if (s[i] == 0x1b) {- i += if (i + 1 < s.len and s[i + 1] == '\\') 2 else 1;- break;- }- }- },- 'O' => i = @min(i + 2, s.len),- else => i += 1,- }- return i;-}--/// Terminal column width of one codepoint: 2 for East Asian Wide/Fullwidth and-/// for emoji whose DEFAULT presentation is emoji, 0 for combining marks and-/// zero-width joiners, 1 otherwise. Every box border and pad in the TUI keys on-/// this — counting 🚀 as one column pushed the composer's right wall two cells-/// past its corners.-///-/// The symbol blocks are enumerated, never taken wholesale. U+2600..U+27BF and-/// U+2B00..U+2BFF are mostly East-Asian-Ambiguous glyphs that terminals draw in-/// ONE cell, and the TUI paints five of them itself (⚙ ✓ ✗ ❙ ❯). Claiming two-/// columns for those under-padded every chrome row by one and — because-/// run.zig skips the pad AND the erase once a row measures full — stranded the-/// previous frame's last cell. Only Emoji_Presentation=Yes is wide here; the-/// text-presentation symbols reach two columns via a VS16 selector (see cpAt).-pub fn charWidth(cp: u21) u2 {- return switch (cp) {- 0x0300...0x036F, 0x1AB0...0x1AFF, 0x1DC0...0x1DFF, 0x20D0...0x20FF, 0xFE20...0xFE2F => 0, // combining- 0x200B...0x200D, 0xFE0E...0xFE0F, 0x2060 => 0, // zero-width + variation selectors- 0x1100...0x115F, 0x2E80...0x303E, 0x3041...0x33FF, 0x3400...0x4DBF, 0x4E00...0x9FFF, 0xA000...0xA4CF, 0xAC00...0xD7A3, 0xF900...0xFAFF, 0xFE30...0xFE4F, 0xFF00...0xFF60, 0xFFE0...0xFFE6 => 2, // East Asian Wide- 0x1F300...0x1FAFF, 0x20000...0x3FFFD => 2, // emoji planes + supplementary ideographs- // Emoji_Presentation=Yes inside the BMP symbol blocks.- 0x231A...0x231B, 0x23E9...0x23EC, 0x23F0, 0x23F3, 0x25FD...0x25FE => 2,- 0x2614...0x2615, 0x2648...0x2653, 0x267F, 0x2693, 0x26A1 => 2,- 0x26AA...0x26AB, 0x26BD...0x26BE, 0x26C4...0x26C5, 0x26CE, 0x26D4 => 2,- 0x26EA, 0x26F2...0x26F3, 0x26F5, 0x26FA, 0x26FD => 2,- 0x2705, 0x270A...0x270B, 0x2728, 0x274C, 0x274E => 2,- 0x2753...0x2755, 0x2757, 0x2795...0x2797, 0x27B0, 0x27BF => 2,- 0x2B1B...0x2B1C, 0x2B50, 0x2B55 => 2,- else => 1,- };-}--/// Width and byte length of the codepoint at `i`, honouring a trailing VS16:-/// `✓\u{FE0F}` asks for emoji presentation and does take two cells, while a-/// bare `✓` takes one. The selector itself stays zero-width, so the pair still-/// measures two in total.-pub fn cpAt(s: []const u8, i: usize) struct { w: u2, step: usize } {- const len = std.unicode.utf8ByteSequenceLength(s[i]) catch return .{ .w = 1, .step = 1 };- const step = @min(@as(usize, len), s.len - i);- const cp = std.unicode.utf8Decode(s[i .. i + step]) catch return .{ .w = 1, .step = step };- const w = charWidth(cp);- if (w == 1 and emojiPresentationNext(s, i + step)) return .{ .w = 2, .step = step };- return .{ .w = w, .step = step };-}--fn emojiPresentationNext(s: []const u8, at: usize) bool {- if (at + 3 > s.len) return false;- return std.mem.eql(u8, s[at .. at + 3], "\u{FE0F}");-}--/// Columns in `s`, skipping SGR; CJK/emoji count 2, combining marks 0.-pub fn visibleLen(s: []const u8) usize {- var n: usize = 0;- var i: usize = 0;- while (i < s.len) {- if (s[i] == 0x1b) {- i = skipEsc(s, i);- continue;- }- const c = cpAt(s, i);- i += c.step;- n += c.w;- }- return n;-}--pub fn takeCols(s: []const u8, max: usize) []const u8 {- var n: usize = 0;- var i: usize = 0;- while (i < s.len) {- if (s[i] == 0x1b) {- i = skipEsc(s, i);- continue;- }- const c = cpAt(s, i);- if (n + c.w > max) break; // a wide glyph that would straddle the edge stays out- i += c.step;- n += c.w;- }- return s[0..i];-}--test "parse: grok aliases and unknown" {- try std.testing.expectEqual(Id.night, parse("dark").?);- try std.testing.expectEqual(Id.tokyo, parse("TokyoNight").?);- try std.testing.expect(parse("not-a-theme") == null);-}--test "next wraps the palette" {- try std.testing.expectEqual(Id.day, next(.night));- try std.testing.expectEqual(Id.night, next(.oscura));-}--test "every theme ships a truecolor background" {- for (all) |id| {- try std.testing.expect(std.mem.startsWith(u8, of(id).bg, "\x1b[48;2;"));- try std.testing.expect(std.mem.startsWith(u8, of(id).focus, "\x1b[38;2;"));- }- try std.testing.expect(std.mem.indexOf(u8, reset, "49") == null);-}--test "night is Grok Night (bg #141414, accent #bb9af7, error #f7768e)" {- const th = of(.night);- try std.testing.expectEqualStrings("\x1b[48;2;20;20;20m", th.bg);- try std.testing.expectEqualStrings("\x1b[38;2;187;154;247m", th.accent);- try std.testing.expectEqualStrings("\x1b[38;2;247;118;142m", th.error_fg);- try std.testing.expectEqualStrings("\x1b[38;2;225;225;225m", th.text);- try std.testing.expectEqualStrings("\x1b[38;2;50;50;55m", th.border);- try std.testing.expectEqualStrings("\x1b[38;2;80;80;88m", th.focus);-}--test "day uses the Codegraff light palette; dark themes match their tokens" {- try std.testing.expectEqualStrings("\x1b[48;2;248;249;247m", of(.day).bg);- try std.testing.expectEqualStrings("\x1b[38;2;5;150;105m", of(.day).accent);- try std.testing.expectEqualStrings("\x1b[38;2;32;37;34m", of(.day).text);- try std.testing.expectEqualStrings("\x1b[38;2;98;107;101m", of(.day).muted);- try std.testing.expectEqualStrings("\x1b[48;2;36;40;59m", of(.tokyo).bg);- try std.testing.expectEqualStrings("\x1b[48;2;35;33;54m", of(.rose).bg);- try std.testing.expectEqualStrings("\x1b[48;2;3;3;4m", of(.oscura).bg);- try std.testing.expectEqualStrings("\x1b[38;2;155;126;206m", of(.oscura).accent);-}--/// Active-SGR tracker for the wrappers: remember styling since the last reset-/// so an inserted line break can re-open it — the diff painter repaints rows-/// independently, so a continuation row with no SGR of its own renders in-/// whatever style the previous paint left behind.-///-/// State is kept PER CATEGORY, last writer wins. Concatenating the raw-/// sequences instead grew without bound, so it needed a byte cap — and the cap-/// CLEARED the tracker rather than trimming it. The background is set first on-/// a code fence, so it was always the first casualty: a syntax-highlighted line-/// carries a colour per token, and by the wrap point the band was long gone and-/// the continuation row painted on the plain canvas.-pub const Sgr = struct {- fg: Slot = .{},- bg: Slot = .{},- weight: Slot = .{},- italic: Slot = .{},- underline: Slot = .{},-- /// Longest parameter list a slot holds: "48;2;255;255;255".- const Slot = struct {- buf: [20]u8 = undefined,- len: u8 = 0,-- fn set(s: *Slot, p: []const u8) void {- if (p.len == 0 or p.len > s.buf.len) return;- @memcpy(s.buf[0..p.len], p);- s.len = @intCast(p.len);- }- fn drop(s: *Slot) void {- s.len = 0;- }- fn params(s: *const Slot) []const u8 {- return s.buf[0..s.len];- }- };-- /// Five slots at "\x1b[" + 16 params + "m" apiece, rounded up.- pub const max_render = 5 * 20;-- pub fn clear(self: *Sgr) void {- self.* = .{};- }-- /// Re-emit the active state into `buf`. Background first so a continuation- /// row establishes its canvas before anything paints on it.- pub fn render(self: *const Sgr, buf: *[max_render]u8) []const u8 {- var n: usize = 0;- const order = [_]*const Slot{ &self.bg, &self.fg, &self.weight, &self.italic, &self.underline };- for (order) |slot| {- const p = slot.params();- if (p.len == 0) continue;- buf[n] = 0x1b;- buf[n + 1] = '[';- n += 2;- @memcpy(buf[n .. n + p.len], p);- n += p.len;- buf[n] = 'm';- n += 1;- }- return buf[0..n];- }-- /// Fold one escape sequence into the state. Non-SGR escapes (OSC links,- /// kitty graphics, ESC[K) are ignored: they carry no style.- pub fn note(self: *Sgr, seq: []const u8) void {- if (seq.len < 3 or seq[1] != '[' or seq[seq.len - 1] != 'm') return;- const body = seq[2 .. seq.len - 1];- if (body.len == 0) { // "\x1b[m" is "\x1b[0m"- self.clear();- return;- }- var parts: [16][]const u8 = undefined;- var n: usize = 0;- var it = std.mem.splitScalar(u8, body, ';');- while (it.next()) |p| {- if (n == parts.len) return; // pathological: leave the state alone- parts[n] = p;- n += 1;- }- var i: usize = 0;- while (i < n) : (i += 1) {- const code = std.fmt.parseInt(u16, parts[i], 10) catch continue;- switch (code) {- 0 => self.clear(),- 1, 2 => self.weight.set(parts[i]),- 3 => self.italic.set(parts[i]),- 4 => self.underline.set(parts[i]),- 22 => self.weight.drop(),- 23 => self.italic.drop(),- 24 => self.underline.drop(),- 39 => self.fg.drop(),- 49 => self.bg.drop(),- 30...37, 90...97 => self.fg.set(parts[i]),- 40...47, 100...107 => self.bg.set(parts[i]),- 38, 48 => {- // 38/48 own the parameters that follow: ";5;n" or ";2;r;g;b".- const want: usize = if (i + 1 < n and std.mem.eql(u8, parts[i + 1], "5")) 2 else 4;- if (i + want >= n) return;- const start = @intFromPtr(parts[i].ptr) - @intFromPtr(body.ptr);- const last = parts[i + want];- const end = @intFromPtr(last.ptr) - @intFromPtr(body.ptr) + last.len;- const slot = if (code == 38) &self.fg else &self.bg;- slot.set(body[start..end]);- i += want;- },- else => {},- }- }- }-};--/// Wrap `s` so no row is wider than `width` columns. SGR is preserved AND-/// re-emitted on continuation rows; wide glyphs never straddle the edge.-pub fn wrapToWidth(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u8 {- if (width == 0) return a.dupe(u8, s);- var out = std.array_list.Managed(u8).init(a);- var active: Sgr = .{};- var sgr_buf: [Sgr.max_render]u8 = undefined;- var col: usize = 0;- var i: usize = 0;- while (i < s.len) {- if (s[i] == '\n') {- try out.append('\n');- try out.appendSlice(active.render(&sgr_buf));- col = 0;- i += 1;- continue;- }- if (s[i] == 0x1b) {- const start = i;- i = skipEsc(s, i);- try out.appendSlice(s[start..i]);- active.note(s[start..i]);- continue;- }- const c = cpAt(s, i);- if (col + c.w > width and col > 0) {- try out.append('\n');- try out.appendSlice(active.render(&sgr_buf));- col = 0;- }- try out.appendSlice(s[i .. i + c.step]);- col += c.w;- i += c.step;- }- return out.toOwnedSlice();-}--/// Like wrapToWidth, but breaks at the last space on the line when it can.-pub fn wrapPreferWords(a: std.mem.Allocator, s: []const u8, width: usize) ![]const u8 {- if (width == 0) return a.dupe(u8, s);- var out = std.array_list.Managed(u8).init(a);- var active: Sgr = .{};- var sgr_buf: [Sgr.max_render]u8 = undefined;- var col: usize = 0;- var last_sp: ?usize = null;- var i: usize = 0;- while (i < s.len) {- if (s[i] == '\n') {- try out.append('\n');- try out.appendSlice(active.render(&sgr_buf));- col = 0;- last_sp = null;- i += 1;- continue;- }- if (s[i] == 0x1b) {- const start = i;- i = skipEsc(s, i); // full skip: hand-rolled CSI-only parsing broke a \n INTO an OSC hyperlink- try out.appendSlice(s[start..i]);- active.note(s[start..i]);- continue;- }- const c = cpAt(s, i);- // `col > 0` matches wrapToWidth: a glyph wider than the whole width has- // nowhere to go, and breaking before it only opened with a blank row.- if (col + c.w > width and col > 0) {- if (last_sp) |sp| {- out.items[sp] = '\n';- try out.insertSlice(sp + 1, active.render(&sgr_buf));- col = visibleLen(out.items[sp + 1 ..]);- last_sp = null;- } else {- try out.append('\n');- try out.appendSlice(active.render(&sgr_buf));- col = 0;- }- }- if (s[i] == ' ') last_sp = out.items.len;- try out.appendSlice(s[i .. i + c.step]);- col += c.w;- i += c.step;- }- return out.toOwnedSlice();-}--test "visibleLen counts glyphs not UTF-8 bytes or SGR" {- try std.testing.expectEqual(@as(usize, 3), visibleLen("\x1b[32mhi!\x1b[0m"));- try std.testing.expectEqual(@as(usize, 3), visibleLen("a ·"));-}--test "wrapPreferWords breaks on spaces not mid-word" {- const got = try wrapPreferWords(std.testing.allocator, "little bit weird", 10);- defer std.testing.allocator.free(got);- try std.testing.expect(std.mem.indexOf(u8, got, "bit") != null);- try std.testing.expect(std.mem.indexOf(u8, got, "b\nit") == null);-}--test "wrapToWidth splits a long line and keeps SGR" {- const got = try wrapToWidth(std.testing.allocator, "\x1b[32mabcdefghij\x1b[0m", 4);- defer std.testing.allocator.free(got);- try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, got, "\n"));- try std.testing.expect(std.mem.indexOf(u8, got, "\x1b[32m") != null);- var it = std.mem.splitScalar(u8, got, '\n');- while (it.next()) |ln| {- try std.testing.expect(visibleLen(ln) <= 4);- }-}--test "visibleLen/wrapToWidth count CJK and emoji as two columns (#518)" {- try std.testing.expectEqual(@as(usize, 4), visibleLen("日本"));- try std.testing.expectEqual(@as(usize, 7), visibleLen("ab 🐉 c"));- try std.testing.expectEqualStrings("日", takeCols("日本", 3));- const got = try wrapToWidth(std.testing.allocator, "日本語のテキスト", 6);- defer std.testing.allocator.free(got);- try std.testing.expect(std.mem.count(u8, got, "\n") >= 1);- var it = std.mem.splitScalar(u8, got, '\n');- while (it.next()) |ln| {- try std.testing.expect(visibleLen(ln) <= 6);- }-}--test "visibleLen and takeCols treat OSC/APC as invisible" {- try std.testing.expectEqual(@as(usize, 4), visibleLen("\x1b]8;;http://x\x07link\x1b]8;;\x07"));- try std.testing.expectEqual(@as(usize, 2), visibleLen("\x1b_Ga=d,d=A\x1b\\ok"));- const cut = takeCols("\x1b]8;;u\x07ab", 1);- try std.testing.expectEqualStrings("\x1b]8;;u\x07a", cut);-}--test "charWidth: the TUI's own glyphs measure one cell" {- // ⚙ ✓ ✗ ❙ ❯ are painted by scrollback/render themselves and are ambiguous- // width: terminals give them one cell. A blanket 2600..27BF range called- // them two, which under-padded every chrome row and — once a row measured- // full — cost it both the pad and the erase-to-EOL in run.zig.- for ([_]u21{ '⚙', '✓', '✗', '❙', '❯', '⊘', '●', '◆', '·', '›', '…', '│', '╭', '─', '▏', '↳', '→' }) |cp| {- try std.testing.expectEqual(@as(u2, 1), charWidth(cp));- }- // Real emoji and CJK stay two.- for ([_]u21{ '🚀', '✅', '❌', '⭐', '⌚', '你', '한' }) |cp| {- try std.testing.expectEqual(@as(u2, 2), charWidth(cp));- }- try std.testing.expectEqual(@as(usize, 20), visibleLen(" \u{2713} bash finished ok"));-}--test "charWidth: a VS16 selector promotes a text-presentation symbol" {- try std.testing.expectEqual(@as(usize, 1), visibleLen("\u{2713}"));- try std.testing.expectEqual(@as(usize, 2), visibleLen("\u{2713}\u{FE0F}"));- try std.testing.expectEqual(@as(usize, 1), visibleLen("\u{2713}\u{FE0E}")); // VS15 stays text- try std.testing.expectEqualStrings("", takeCols("\u{2713}\u{FE0F}", 1)); // never half a cell-}--test "Sgr keeps the background through a colour-heavy line" {- // One bg then six token colours: concatenating these passed 96 bytes, and- // the cap CLEARED the tracker, so the continuation row of a wrapped code- // fence lost its band. Per-slot tracking cannot lose the oldest slot.- const s = "\x1b[48;2;28;28;28m" ++- "\x1b[38;2;101;101;101m\x1b[38;2;102;102;102m\x1b[38;2;103;103;103m" ++- "\x1b[38;2;104;104;104m\x1b[38;2;105;105;105m\x1b[38;2;106;106;106m" ++- "ABCDEFGHIJ";- const got = try wrapToWidth(std.testing.allocator, s, 4);- defer std.testing.allocator.free(got);- var it = std.mem.splitScalar(u8, got, '\n');- var n: usize = 0;- while (it.next()) |ln| : (n += 1) {- if (n == 0) continue;- try std.testing.expect(std.mem.startsWith(u8, ln, "\x1b[48;2;28;28;28m"));- try std.testing.expect(std.mem.indexOf(u8, ln, "\x1b[38;2;106;106;106m") != null);- }- try std.testing.expect(n > 1);-}--test "Sgr: each reset code drops only its own slot" {- var st: Sgr = .{};- var buf: [Sgr.max_render]u8 = undefined;- st.note("\x1b[48;2;1;2;3m");- st.note("\x1b[38;5;9m");- st.note("\x1b[1m");- try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m\x1b[38;5;9m\x1b[1m", st.render(&buf));- st.note(reset); // 39;22;23;24 — fg and weight go, the background stays- try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m", st.render(&buf));- st.note("\x1b[31m");- try std.testing.expectEqualStrings("\x1b[48;2;1;2;3m\x1b[31m", st.render(&buf));- st.note("\x1b[0m");- try std.testing.expectEqualStrings("", st.render(&buf));- st.note("\x1b[K"); // not SGR: ignored- try std.testing.expectEqualStrings("", st.render(&buf));-}--test "wrapPreferWords does not open with a blank row for an oversized glyph" {- const got = try wrapPreferWords(std.testing.allocator, "\u{1F680}ab", 1);- defer std.testing.allocator.free(got);- try std.testing.expect(got[0] != '\n');-}--test "wide glyphs: 2 columns, never straddling a wrap or a takeCols edge" {- try std.testing.expectEqual(@as(usize, 2), visibleLen("\u{1F680}"));- try std.testing.expectEqual(@as(usize, 4), visibleLen("\u{4F60}\u{597D}"));- try std.testing.expectEqual(@as(usize, 1), visibleLen("e\u{0301}"));- try std.testing.expectEqualStrings("a", takeCols("a\u{1F680}", 2)); // rocket won't fit in 1 col-}--test "wrap re-emits active SGR on continuation rows" {- const got = try wrapToWidth(std.testing.allocator, "\x1b[32mabcdefgh\x1b[0m", 4);- defer std.testing.allocator.free(got);- var it = std.mem.splitScalar(u8, got, '\n');- _ = it.next();- const row2 = it.next().?;- try std.testing.expect(std.mem.startsWith(u8, row2, "\x1b[32m"));-}--test "wrapPreferWords keeps OSC strings intact" {- const link = "\x1b]8;;http://example.com/long/url\x07go\x1b]8;;\x07 tail words here";- const got = try wrapPreferWords(std.testing.allocator, link, 10);- defer std.testing.allocator.free(got);- try std.testing.expect(std.mem.indexOf(u8, got, "http://example.com/long/url") != null); // URL unbroken-}diff --git a/TUI/theme_tint.zig b/TUI/theme_tint.zigdeleted file mode 100644index f3f0b34c..00000000--- a/TUI/theme_tint.zig+++ /dev/null@@ -1,119 +0,0 @@-//! Backgrounds DERIVED from a palette's own canvas, as tokens.-//!-//! This is theme.zig's material — it lives next door only because that file-//! sits at the 600-line ceiling. Nothing here is a hand-picked colour: every-//! value is computed from `theme.of(id).bg`, so a new palette gets its hover-//! tint for free and no two palettes can drift out of step.-//!-//! POLARITY. A dark canvas is LIFTED toward white and a light canvas is SUNK-//! toward black, decided by the same BT.709 rule theme.classifyLight uses for-//! the OSC-11 reply. One step, both polarities, no second table.-//!-//! WEIGHT. The step is deliberately small. The drag-selection band is full-//! inverse video (`\x1b[7m`) and CLAIMS a region; a hover tint only ANNOUNCES-//! that the row under the pointer is a target, so it has to read as quieter-//! than the band from across the room. `hover_step` is asserted below to be a-//! small fraction of a channel, and the tint is asserted never to be inverse.--const std = @import("std");--const theme = @import("theme.zig");--/// Channel step between the canvas and a hovered row, out of 255. Large enough-/// to see on an OLED black (oscura's bg is 3,3,4), small enough that a sweep-/// across the transcript never reads as a selection.-pub const hover_step: u8 = 16;--/// The hover background for a palette. Comptime-folded per theme, so this is a-/// switch over string literals at runtime — no allocation, no formatting.-pub fn hoverBg(id: theme.Id) []const u8 {- return switch (id) {- inline else => |tag| comptime step(theme.of(tag).bg, hover_step),- };-}--pub const Rgb = struct { r: u8, g: u8, b: u8 };--/// The channels of a `\x1b[48;2;R;G;Bm` background, or null for any other-/// shape. Every palette's bg is written that way; a future one that is not-/// falls back to its own canvas rather than to a wrong colour.-pub fn parseBg(sgr: []const u8) ?Rgb {- const head = "\x1b[48;2;";- if (!std.mem.startsWith(u8, sgr, head)) return null;- if (!std.mem.endsWith(u8, sgr, "m")) return null;- var it = std.mem.splitScalar(u8, sgr[head.len .. sgr.len - 1], ';');- var ch: [3]u8 = undefined;- for (&ch) |*c| {- const p = it.next() orelse return null;- c.* = std.fmt.parseInt(u8, p, 10) catch return null;- }- if (it.next() != null) return null;- return .{ .r = ch[0], .g = ch[1], .b = ch[2] };-}--/// `bg` moved one step away from its own polarity, as an SGR literal. Comptime-/// only: the result is a literal folded into the binary, never a formatted-/// buffer a frame has to own.-pub fn step(comptime bg: []const u8, comptime by: u8) []const u8 {- const parsed = comptime parseBg(bg);- if (parsed == null) return bg;- const c = comptime parsed.?;- const lift = comptime !theme.classifyLight(c.r, c.g, c.b);- const r: u8 = comptime if (lift) c.r +| by else c.r -| by;- const g: u8 = comptime if (lift) c.g +| by else c.g -| by;- const b: u8 = comptime if (lift) c.b +| by else c.b -| by;- return std.fmt.comptimePrint("\x1b[48;2;{d};{d};{d}m", .{ r, g, b });-}--// ------------------------------------------------------------------ tests--const testing = std.testing;--test "every palette's hover tint is derived from its own canvas and differs from it" {- for (theme.all) |id| {- const bg = theme.of(id).bg;- const hov = hoverBg(id);- try testing.expect(!std.mem.eql(u8, bg, hov));- const base = parseBg(bg).?;- const tint = parseBg(hov).?;- // One step, in the direction the canvas's own polarity asks for.- const lift = !theme.classifyLight(base.r, base.g, base.b);- if (lift) {- try testing.expect(tint.r >= base.r and tint.g >= base.g and tint.b >= base.b);- } else {- try testing.expect(tint.r <= base.r and tint.g <= base.g and tint.b <= base.b);- }- // ...and never more than one step, on any channel, in either polarity.- const dr = if (tint.r > base.r) tint.r - base.r else base.r - tint.r;- const dg = if (tint.g > base.g) tint.g - base.g else base.g - tint.g;- const db = if (tint.b > base.b) tint.b - base.b else base.b - tint.b;- try testing.expect(dr <= hover_step and dg <= hover_step and db <= hover_step);- }-}--test "the hover tint is quieter than the selection band, and never inverse" {- // The band is `\x1b[7m` — it inverts the whole cell. A tint that reached- // for inverse video, or for a step big enough to read as one, would make- // hover and selection say the same thing.- for (theme.all) |id| {- const hov = hoverBg(id);- try testing.expect(std.mem.indexOf(u8, hov, "\x1b[7m") == null);- try testing.expect(std.mem.startsWith(u8, hov, "\x1b[48;2;"));- }- // A tenth of a channel or less: visible, never a claim.- try testing.expect(hover_step > 0 and hover_step <= 25);-}--test "a background that is not truecolor keeps its own bytes" {- try testing.expectEqualStrings("\x1b[44m", step("\x1b[44m", 16));- try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;2;1;2m"));- try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;2;1;2;3;4m"));- try testing.expectEqual(@as(?Rgb, null), parseBg("\x1b[48;5;12m"));-}--test "the step saturates instead of wrapping at either end of a channel" {- // A pure-black canvas cannot sink and a pure-white one cannot lift; both- // used to be where a wrapping subtract turned the tint into its opposite.- try testing.expectEqualStrings("\x1b[48;2;16;16;16m", comptime step("\x1b[48;2;0;0;0m", 16));- try testing.expectEqualStrings("\x1b[48;2;239;239;239m", comptime step("\x1b[48;2;255;255;255m", 16));-}diff --git a/TUI/tool_card.zig b/TUI/tool_card.zigdeleted file mode 100644index 57d5a9aa..00000000--- a/TUI/tool_card.zig+++ /dev/null@@ -1,72 +0,0 @@-//! Tool-row title + live elapsed. Split from scrollback.zig so the 600-line-//! ceiling has room for the duration suffix without a scrollback/card cycle.--const std = @import("std");--const app = @import("app.zig");-const foldhdr = @import("foldhdr.zig");-const glyphs = @import("glyphs.zig");--const displayName = foldhdr.displayName;--/// Elapsed for a running row (`now - at`) or a finished one (`recorded_ms`).-/// Hidden under 100ms so a fast read does not flicker `0ms`.-pub fn timingSuffix(buf: []u8, done: bool, recorded_ms: u64, now_ms: u64, at_ms: u64) []const u8 {- const ms: u64 = if (done) recorded_ms else now_ms -| at_ms;- if (ms < 100) return "";- return formatElapsed(buf, ms);-}--pub fn formatElapsed(buf: []u8, ms: u64) []const u8 {- if (ms < 1000) return std.fmt.bufPrint(buf, "{d}ms", .{ms}) catch "";- const s = ms / 1000;- if (s < 60) {- const tenths = (ms / 100) % 10;- if (tenths == 0) return std.fmt.bufPrint(buf, "{d}s", .{s}) catch "";- return std.fmt.bufPrint(buf, "{d}.{d}s", .{ s, tenths }) catch "";- }- return std.fmt.bufPrint(buf, "{d}m{d:0>2}s", .{ s / 60, s % 60 }) catch "";-}--/// The head of a tool row: `[status mark] name [argument preview] [elapsed]`.-pub fn toolTitle(a: std.mem.Allocator, named: app.Entry, status: app.Entry, now_ms: u64) ![]const u8 {- const t = named.tool orelse return named.text;- const mark: []const u8 = if (status.tool) |s|- (if (s.denied) glyphs.denied ++ " " else if (s.is_error) glyphs.failed ++ " " else "")- else- "";- const name = displayName(t.name);- const args = if (t.done) "" else t.detail;- const recorded = if (status.tool) |s| s.ms else t.ms;- const done = t.done or if (status.tool) |s| s.done else false;- var tbuf: [16]u8 = undefined;- const timing = timingSuffix(&tbuf, done, recorded, now_ms, named.at_ms);- if (args.len == 0 and timing.len == 0)- return if (mark.len == 0) name else std.fmt.allocPrint(a, "{s}{s}", .{ mark, name });- if (args.len == 0)- return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, timing });- if (timing.len == 0)- return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, args });- return std.fmt.allocPrint(a, "{s}{s} {s} {s}", .{ mark, name, args, timing });-}--test "timingSuffix hides sub-100ms, then shows live and recorded" {- var buf: [16]u8 = undefined;- try std.testing.expectEqualStrings("", timingSuffix(&buf, false, 0, 50, 0));- try std.testing.expectEqualStrings("120ms", timingSuffix(&buf, false, 0, 120, 0));- try std.testing.expectEqualStrings("1.2s", timingSuffix(&buf, true, 1200, 0, 0));- try std.testing.expectEqualStrings("3s", timingSuffix(&buf, true, 3000, 0, 0));-}--test "toolTitle appends elapsed on a running row" {- const e: app.Entry = .{- .kind = .tool,- .text = "ls",- .at_ms = 0,- .tool = .{ .name = "bash", .detail = "ls -la", .done = false },- };- const title = try toolTitle(std.testing.allocator, e, e, 1500);- defer std.testing.allocator.free(title);- try std.testing.expect(std.mem.indexOf(u8, title, "bash") != null);- try std.testing.expect(std.mem.indexOf(u8, title, "1.5s") != null);-}diff --git a/TUI/traj.zig b/TUI/traj.zigdeleted file mode 100644index 1cdbdb3d..00000000--- a/TUI/traj.zig+++ /dev/null@@ -1,112 +0,0 @@-//! Append-only TUI input log so a leak or cancelled turn can be replayed.-//! `.graff/tui-traj.jsonl` — raw stdin hex, no prompts, no model text.--const std = @import("std");-const Io = std.Io;--pub const path = ".graff/tui-traj.jsonl";-const cap: u64 = 512 * 1024;-const chunk_max: usize = 256;--var ready: bool = false;-var test_path: ?[]const u8 = null;--fn dest() []const u8 {- return test_path orelse path;-}--pub fn open(io: Io) void {- Io.Dir.cwd().createDirPath(io, ".graff") catch {};- ready = true;-}--pub fn note(io: Io, now_ms: u64, bytes: []const u8) void {- if (!ready or bytes.len == 0) return;- const slice = if (bytes.len > chunk_max) bytes[0..chunk_max] else bytes;- var hex: [chunk_max * 2]u8 = undefined;- const hexed = toHex(slice, &hex);- var line_buf: [64 + chunk_max * 2]u8 = undefined;- const line = std.fmt.bufPrint(&line_buf, "{{\"t\":{d},\"n\":{d},\"hex\":\"{s}\"}}\n", .{- now_ms, bytes.len, hexed,- }) catch return;- append(io, line);-}--pub fn snap(io: Io, now_ms: u64, visible: []const u8) void {- if (!ready) return;- const slice = if (visible.len > chunk_max) visible[visible.len - chunk_max ..] else visible;- var esc: [chunk_max * 2]u8 = undefined;- const n = jsonEscape(slice, &esc);- var line_buf: [80 + chunk_max * 2]u8 = undefined;- const line = std.fmt.bufPrint(&line_buf, "{{\"t\":{d},\"vis\":\"{s}\"}}\n", .{ now_ms, esc[0..n] }) catch return;- append(io, line);-}--fn append(io: Io, line: []const u8) void {- rotateIfHuge(io);- const f = Io.Dir.cwd().createFile(io, dest(), .{ .truncate = false }) catch return;- defer f.close(io);- const st = f.stat(io) catch return;- f.writePositionalAll(io, line, st.size) catch {};-}--fn rotateIfHuge(io: Io) void {- const st = Io.Dir.cwd().statFile(io, dest(), .{}) catch return;- if (st.size < cap) return;- Io.Dir.cwd().deleteFile(io, dest()) catch {};-}--fn toHex(src: []const u8, out: []u8) []const u8 {- const hex = "0123456789abcdef";- var i: usize = 0;- while (i < src.len) : (i += 1) {- out[i * 2] = hex[src[i] >> 4];- out[i * 2 + 1] = hex[src[i] & 0xf];- }- return out[0 .. src.len * 2];-}--fn jsonEscape(src: []const u8, out: []u8) usize {- var o: usize = 0;- for (src) |c| {- if (o + 2 >= out.len) break;- if (c == '"' or c == '\\') {- out[o] = '\\';- o += 1;- out[o] = c;- o += 1;- } else if (c == '\n') {- out[o] = '\\';- o += 1;- out[o] = 'n';- o += 1;- } else if (c >= 32 and c < 127) {- out[o] = c;- o += 1;- } else {- if (o + 1 >= out.len) break;- out[o] = '?';- o += 1;- }- }- return o;-}--test "note writes hex stdin and snap writes visible tail" {- const io = std.Io.Threaded.global_single_threaded.io();- const tmp = "TUI/testdata-tui-traj.jsonl";- test_path = tmp;- defer {- test_path = null;- Io.Dir.cwd().deleteFile(io, tmp) catch {};- }- Io.Dir.cwd().deleteFile(io, tmp) catch {};- ready = true;- note(io, 42, "\x1b[57444;9u");- snap(io, 43, "thinking.\n3u7444;9u");- const text = Io.Dir.cwd().readFileAlloc(io, tmp, std.testing.allocator, .limited(4096)) catch return error.TestUnexpectedResult;- defer std.testing.allocator.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "1b5b35373434343b3975") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "3u7444;9u") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "\"t\":42") != null);-}diff --git a/TUI/tty.zig b/TUI/tty.zigdeleted file mode 100644index cabf2107..00000000--- a/TUI/tty.zig+++ /dev/null@@ -1,178 +0,0 @@-//! Minimal raw-mode + size + stdin poll for the fullscreen TUI.-//! Kept inside TUI/ so we do not share src/term.zig across modules.-//! Windows console APIs are duplicated here (not `@import("../src/win_api.zig")`)-//! because a file may belong to only one Zig 0.17 module.--const std = @import("std");-const builtin = @import("builtin");--const is_windows = builtin.os.tag == .windows;--/// Windows console leaf used only on that OS. Mirrors src/win_api.zig's UTF-8-/// + VT bits so the fullscreen TUI can switch CP 65001 (#607) without sharing-/// the file with the harness module.-const w = if (is_windows) struct {- const HANDLE = *anyopaque;- const BOOL = i32;- const DWORD = u32;- const UINT = u32;- const WORD = u16;- const SHORT = i16;- const STD_OUTPUT_HANDLE: DWORD = 0xFFFFFFF5;- const ENABLE_PROCESSED_OUTPUT: DWORD = 0x0001;- const ENABLE_VIRTUAL_TERMINAL_PROCESSING: DWORD = 0x0004;- const CP_UTF8: UINT = 65001;- const COORD = extern struct { X: SHORT, Y: SHORT };- const SMALL_RECT = extern struct { Left: SHORT, Top: SHORT, Right: SHORT, Bottom: SHORT };- const CONSOLE_SCREEN_BUFFER_INFO = extern struct {- dwSize: COORD,- dwCursorPosition: COORD,- wAttributes: WORD,- srWindow: SMALL_RECT,- dwMaximumWindowSize: COORD,- };- extern "kernel32" fn GetStdHandle(nStdHandle: DWORD) callconv(.winapi) HANDLE;- extern "kernel32" fn GetConsoleMode(hConsoleHandle: HANDLE, lpMode: *DWORD) callconv(.winapi) BOOL;- extern "kernel32" fn SetConsoleMode(hConsoleHandle: HANDLE, dwMode: DWORD) callconv(.winapi) BOOL;- extern "kernel32" fn GetConsoleScreenBufferInfo(hConsoleOutput: HANDLE, lpInfo: *CONSOLE_SCREEN_BUFFER_INFO) callconv(.winapi) BOOL;- extern "kernel32" fn GetConsoleOutputCP() callconv(.winapi) UINT;- extern "kernel32" fn SetConsoleOutputCP(wCodePageID: UINT) callconv(.winapi) BOOL;- extern "kernel32" fn GetConsoleCP() callconv(.winapi) UINT;- extern "kernel32" fn SetConsoleCP(wCodePageID: UINT) callconv(.winapi) BOOL;-} else struct {};--pub const RawState = if (is_windows) struct {- output_cp: u32 = 0,- input_cp: u32 = 0,-} else std.posix.termios;--/// Clear the line-discipline bits that steal keys the TUI owns (#523).-/// Extracted so tests can mutate a termios-shaped value without a real tty.-pub fn surrenderLineDiscipline(raw: anytype) void {- raw.lflag.ICANON = false;- raw.lflag.ECHO = false;- raw.lflag.ISIG = false;- raw.lflag.IEXTEN = false; // ^V (0x16) reaches us, not the tty's lnext- raw.iflag.IXON = false; // ^S/^Q are keys, not XOFF/XON flow control-}--pub fn enterRaw() ?RawState {- if (is_windows) {- const h = w.GetStdHandle(w.STD_OUTPUT_HANDLE);- var mode: u32 = 0;- if (w.GetConsoleMode(h, &mode) != 0) {- _ = w.SetConsoleMode(h, mode | w.ENABLE_VIRTUAL_TERMINAL_PROCESSING | w.ENABLE_PROCESSED_OUTPUT);- }- // #607: Windows TUI must UTF-8 the console; this path never did,- // so PowerShell 5.1 decoded box-drawing as CP437. Restore the prior CPs- // on the way out so the parent shell keeps its OEM page.- const orig: RawState = .{- .output_cp = w.GetConsoleOutputCP(),- .input_cp = w.GetConsoleCP(),- };- _ = w.SetConsoleOutputCP(w.CP_UTF8);- _ = w.SetConsoleCP(w.CP_UTF8);- return orig;- }- const fd = std.posix.STDIN_FILENO;- const orig = std.posix.tcgetattr(fd) catch return null;- var raw = orig;- surrenderLineDiscipline(&raw);- raw.cc[@intFromEnum(std.posix.V.MIN)] = 0;- raw.cc[@intFromEnum(std.posix.V.TIME)] = 0;- std.posix.tcsetattr(fd, .NOW, raw) catch return null;- return orig;-}--pub fn restore(state: RawState) void {- if (is_windows) {- if (state.output_cp != 0) _ = w.SetConsoleOutputCP(state.output_cp);- if (state.input_cp != 0) _ = w.SetConsoleCP(state.input_cp);- return;- }- std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, state) catch {};-}--pub fn poll(timeout_ms: i32) bool {- if (is_windows) return false;- var fds = [_]std.posix.pollfd{.{ .fd = std.posix.STDIN_FILENO, .events = std.posix.POLL.IN, .revents = 0 }};- const n = std.posix.poll(&fds, timeout_ms) catch return false;- return n > 0;-}--pub fn readStdin(buf: []u8) usize {- if (is_windows) return 0;- return std.posix.read(std.posix.STDIN_FILENO, buf) catch 0;-}--test "raw mode surrenders ^V and ^S to the app, not the line discipline (#523)" {- var raw = struct {- lflag: struct { ICANON: bool = true, ECHO: bool = true, ISIG: bool = true, IEXTEN: bool = true } = .{},- iflag: struct { IXON: bool = true } = .{},- }{};- surrenderLineDiscipline(&raw);- try std.testing.expect(!raw.lflag.IEXTEN);- try std.testing.expect(!raw.iflag.IXON);- try std.testing.expect(!raw.lflag.ICANON);- try std.testing.expect(!raw.lflag.ECHO);- try std.testing.expect(!raw.lflag.ISIG);-}--test "Windows enterRaw switches the console to UTF-8 and restore puts the CPs back (#607)" {- const src = @embedFile("tty.zig");- try std.testing.expect(std.mem.indexOf(u8, src, "CP_UTF8: UINT = 65001") != null);- const enter_at = std.mem.indexOf(u8, src, "pub fn enterRaw() ?RawState {").?;- const enter = src[enter_at..std.mem.indexOf(u8, src, "pub fn restore(").?];- try std.testing.expect(std.mem.indexOf(u8, enter, "SetConsoleOutputCP(w.CP_UTF8)") != null);- try std.testing.expect(std.mem.indexOf(u8, enter, "SetConsoleCP(w.CP_UTF8)") != null);- const restore_at = std.mem.indexOf(u8, src, "pub fn restore(state: RawState) void {").?;- const rest = src[restore_at..std.mem.indexOf(u8, src, "pub fn poll(").?];- try std.testing.expect(std.mem.indexOf(u8, rest, "SetConsoleOutputCP(state.output_cp)") != null);- try std.testing.expect(std.mem.indexOf(u8, rest, "SetConsoleCP(state.input_cp)") != null);-}--fn consoleSize() ?struct { cols: usize, rows: usize } {- if (is_windows) {- var info: w.CONSOLE_SCREEN_BUFFER_INFO = undefined;- if (w.GetConsoleScreenBufferInfo(w.GetStdHandle(w.STD_OUTPUT_HANDLE), &info) == 0) return null;- const width = @as(i32, info.srWindow.Right) - info.srWindow.Left + 1;- const height = @as(i32, info.srWindow.Bottom) - info.srWindow.Top + 1;- return .{- .cols = if (width <= 0) 80 else @intCast(width),- .rows = if (height <= 0) 24 else @intCast(height),- };- }- return null;-}--pub fn cols() usize {- if (is_windows) {- const c = (consoleSize() orelse return 80).cols;- if (c == 0) return 80;- if (c > 400) return 400;- return c;- }- var wsz: std.posix.winsize = undefined;- const rc = std.posix.system.ioctl(std.posix.STDOUT_FILENO, std.posix.T.IOCGWINSZ, @intFromPtr(&wsz));- if (std.posix.errno(rc) != .SUCCESS) return 80;- const c = wsz.col;- if (c == 0) return 80;- if (c > 400) return 400;- return c;-}--pub fn rows() usize {- if (is_windows) {- const r = (consoleSize() orelse return 24).rows;- if (r == 0) return 24;- if (r > 200) return 200;- return r;- }- var wsz: std.posix.winsize = undefined;- const rc = std.posix.system.ioctl(std.posix.STDOUT_FILENO, std.posix.T.IOCGWINSZ, @intFromPtr(&wsz));- if (std.posix.errno(rc) != .SUCCESS) return 24;- const r = wsz.row;- if (r == 0) return 24;- if (r > 200) return 200;- return r;-}diff --git a/TUI/turn.zig b/TUI/turn.zigdeleted file mode 100644index 631bb179..00000000--- a/TUI/turn.zig+++ /dev/null@@ -1,598 +0,0 @@-//! Background turn lifecycle — same thread+stream pattern as `graff repl`,-//! so a grok-style spinner can animate while the engine works.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const Model = app.Model;-const Effect = app.Effect;-/// What the session is currently asking the engine to do. Shared by a model-/// turn and by `!cmd` (bgop), because both run under the SAME policy — a /plan-/// that only reached one of them is the #551 bug in miniature.-pub fn paramsOf(self: *const Model) engine.Params {- return .{- .effort = self.effort,- .fast = self.fast,- .thinking = self.thinking_show,- .ultracode = self.ultracode or self.effort == .ultra,- .mode = self.mode,- .strict = self.strict,- .goal = self.goal orelse "",- };-}-pub fn startJob(self: *Model) void {- var turns = std.array_list.Managed(engine.Turn).init(self.alloc);- for (self.history.items) |e| {- const role: ?engine.Turn.Role = if (e.notification) .user else switch (e.kind) {- .user => .user,- .assistant => .assistant,- else => null,- };- if (role) |r| {- const t = self.alloc.dupe(u8, e.text) catch continue;- turns.append(.{ .role = r, .text = t, .notification = e.notification }) catch {- self.alloc.free(t);- continue;- };- }- }- const job = self.alloc.create(engine.Job) catch {- for (turns.items) |t| self.alloc.free(t.text);- turns.deinit();- self.push(.err, "out of memory") catch {};- return;- };- job.* = .{- .gpa = self.alloc,- .history = turns.toOwnedSlice() catch &.{},- // Policy travels WITH the turn (#551): the engine applies the plan gate- // and the strict prompt from these, so the footer and the run can no- // longer disagree.- .params = paramsOf(self),- .stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },- .raw = .{ .buf = self.alloc.alloc(u8, 64 * 1024) catch &.{} },- };- engine.g_raw = &job.raw;- // The queue must own its copies before the turn thread can push: the- // engine's payloads live in a per-turn arena that dies with the turn.- job.events.attach(self.alloc);- self.push(.pending, "") catch {};- self.pending = job;- if (engine.spawnJob(job)) |th| {- job.thread = th;- } else |_| {- // Never move provider, tool, or automatic-compaction work onto the- // render/input thread. The normal finish path reports and reaps it.- job.threaded = false;- job.start_failed = true;- job.done.store(true, .release);- }-}-/// grok-build notify: a finished background job starts a turn while idle.-pub fn maybeJobWake(self: *Model) void {- if (self.pending != null or self.bg != null) return;- if (self.input.getValue().len > 0 or self.images.items.len > 0 or self.steer_queue.items.len > 0) return;- const f = engine.g_idle_wake_fn orelse return;- var buf: [4096]u8 = undefined;- const text = f(engine.g_turn_ctx, &buf) orelse return;- self.push(.system, text) catch return;- self.history.items[self.history.items.len - 1].notification = true;- startJob(self);-}-pub fn finishJob(self: *Model) void {- const job = self.pending orelse return;- if (!job.done.load(.acquire)) return;- engine.joinJob(job);-- // Whatever the engine emitted after the last frame — the tail of the tool- // run, a closing notice — before the answer row goes in, so the transcript- // keeps its order.- drainEvents(self);- _ = removePendingRows(self);- if (job.start_failed) {- self.push(.err, "model turn failed to start — retry your prompt") catch {};- } else if (job.result) |r| {- self.push(.assistant, r) catch {};- self.alloc.free(r);- } else if (self.cancel_requested) {- if (!hasInterrupted(self)) self.push(.system, "■ interrupted") catch {};- } else {- self.push(.err, "model call failed — check /model and your API key") catch {};- }- for (job.history) |t| self.alloc.free(t.text);- self.alloc.free(job.history);- if (engine.g_raw == &job.raw) engine.g_raw = null;- if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);- if (job.raw.buf.len > 0) self.alloc.free(job.raw.buf);- job.events.deinit();- self.alloc.destroy(job);- self.pending = null;- if (engine.g_steer_reclaim_fn) |f| f(self.alloc, &self.steer_queue); // undelivered follow-ups run next- @import("owned_images.zig").collect(self);- self.cancel_requested = false;- self.scroll = 0;- self.follow = true;-}--/// How long quit waits for a cancelled turn to unwind. The cancel normally-/// lands between two SSE chunks (~50-250 ms), so this only bites on a socket-/// that has stopped delivering bytes entirely.-pub const quit_drain_ms: u64 = 3000;--pub const QuitStep = enum { wait, reap, abandon };--/// One step of the quit-time settle. The TUI must never join a live turn-/// thread from Model.deinit: deinit runs AFTER the terminal defers have left-/// the alt screen and restored termios, so that join made graff look exited-/// while it silently held the tty for the rest of a stalled call (#534).-pub fn quitStep(self: *Model, elapsed_ms: u64) QuitStep {- const job = self.pending orelse return .reap;- if (!job.threaded or job.done.load(.acquire)) return .reap;- return if (elapsed_ms >= quit_drain_ms) .abandon else .wait;-}--/// Give up on a turn thread that ignored the cancel. The job, its history and-/// its stream buffer are deliberately LEAKED: the detached thread still writes-/// job.result and job.done into them, so freeing here would hand it a-/// dangling pointer. The caller exits the process immediately after.-pub fn abandonJob(self: *Model) void {- self.pending = null;- self.cancel_requested = false;-}--pub fn drainSteer(self: *Model) Effect {- if (self.steer_queue.items.len == 0) return .stay;- const text = self.steer_queue.orderedRemove(0);- defer self.alloc.free(text);- return @import("dispatch.zig").applyLine(self, text);-}--pub fn steerEnter(self: *Model) void {- const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");- if (v.len > 0 or self.images.items.len > 0) {- @import("dispatch.zig").steerLine(self, v);- } else if (self.steer_queue.items.len > 0) {- cancelTurn(self);- self.push(.system, "↳ force › interrupting…") catch {};- }-}--pub fn cancelTurn(self: *Model) void {- if (self.pending == null) return;- self.cancel_requested = true;- if (engine.g_cancel_fn) |f| f(engine.g_turn_ctx);- collapseThinking(self);-}--fn collapseThinking(self: *Model) void {- const n = self.history.items.len;- if (n == 0 or self.history.items[n - 1].kind != .pending) return;- self.freeEntry(self.history.items[n - 1]);- const text = self.alloc.dupe(u8, "■ interrupted") catch {- self.history.shrinkRetainingCapacity(n - 1);- return;- };- self.history.items[n - 1] = .{ .kind = .system, .text = text, .folded = false };-}--/// Did this turn already say it was interrupted? Scans back to the prompt-/// rather than looking only at the last row: a cancel collapses the pending-/// row immediately, and events that were already in flight land AFTER it, so-/// "is it the last row" would have written a second notice (#551).-fn hasInterrupted(self: *const Model) bool {- var i = self.history.items.len;- while (i > 0) {- i -= 1;- const e = self.history.items[i];- if (e.kind == .user) return false;- if (std.mem.eql(u8, e.text, "■ interrupted")) return true;- }- return false;-}--/// Apply everything the engine has emitted for the live turn. Called from the-/// render loop's poll point every frame, so tool rows, notices and failovers-/// appear *during* the turn and not only at finishJob.-///-/// This replaced the old harvestLiveTools, which reconstructed tool activity by-/// matching "⚙ /✓ /✗ /⊘ " prefixes in the sink's rendered bytes — an assistant-/// answer whose line began "✓ " became a phantom tool row, and every re-scan-/// re-counted the rows it had already made (#551).-pub fn drainEvents(self: *Model) void {- const job = self.pending orelse return;- const evs = job.events.drain();- defer job.events.free(evs);- if (evs.len == 0) return;- // Events land BEFORE the live "Thinking" row, which is a presentation- // artifact rather than transcript content.- const had_pending = removePendingRows(self);- for (evs) |ev| applyEvent(self, ev);- if (had_pending) self.push(.pending, "") catch {};-}--fn applyEvent(self: *Model, ev: engine.Event) void {- switch (ev) {- .tool_started => |t| {- if (std.mem.startsWith(u8, t.name, "internal_")) return;- self.pushTool(.{ .name = t.name, .summary = t.detail, .detail = t.detail }) catch {};- },- .tool_finished => |t| {- if (std.mem.startsWith(u8, t.name, "internal_")) return;- self.pushTool(.{- .name = t.name,- .summary = t.detail,- .detail = t.detail,- .done = true,- .is_error = t.is_error,- .ms = t.ms,- }) catch {};- },- .tool_rejected => |t| {- if (std.mem.startsWith(u8, t.name, "internal_")) return;- self.pushTool(.{- .name = t.name,- .summary = t.detail,- .detail = t.detail,- .done = true,- .is_error = true,- .denied = true,- }) catch {};- },- .notice => |s| self.push(.system, s) catch {},- .status => |st| self.setStatus(st),- .model_changed => |m| self.adoptFailover(m),- }-}--/// Remove every .pending row wherever it sits. Steering pushes "↳ queued"-/// rows after the pending entry, so "pending is last" is not an invariant —-/// assuming it stranded a permanent thinking row in the transcript (#520).-pub fn removePendingRows(self: *Model) bool {- var had = false;- var i: usize = self.history.items.len;- while (i > 0) {- i -= 1;- if (self.history.items[i].kind == .pending) {- self.freeEntry(self.history.items[i]);- _ = self.history.orderedRemove(i);- had = true;- }- }- return had;-}--test "startJob without a turn_fn finishes as a failed call" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- engine.g_turn_fn = null;- try m.push(.user, "hi");- startJob(&m);- const job = m.pending orelse return error.NoJob;- while (!job.done.load(.acquire)) std.Thread.yield() catch {};- finishJob(&m);- try std.testing.expect(m.pending == null);- try std.testing.expect(m.history.items[m.history.items.len - 1].kind == .err);-}--test "finishJob turns queued events into field-backed tool rows" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- // Prose and structure arrive on SEPARATE channels now: the answer text- // that happens to contain a "✓ " line is only ever an answer.- const live = "hello\n✓ all good\nmore text";- const buf = try std.testing.allocator.dupe(u8, live);- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{ .buf = buf },- .threaded = false,- .result = try std.testing.allocator.dupe(u8, "all done"),- };- job.stream.len.store(live.len, .release);- job.events.attach(std.testing.allocator);- job.events.push(.{ .tool_started = .{ .name = "bash", .detail = "ls -la" } });- job.events.push(.{ .tool_finished = .{ .name = "bash", .detail = "4 files" } });- job.done.store(true, .release);- try m.push(.pending, "");- m.pending = job;- finishJob(&m);- try std.testing.expect(m.pending == null);- try std.testing.expectEqual(@as(usize, 3), m.history.items.len);- try std.testing.expectEqual(app.EntryKind.tool, m.history.items[0].kind);- // The row carries FIELDS, not a rendered line to be taken apart again.- const call = m.history.items[0].tool orelse return error.NotFieldBacked;- try std.testing.expectEqualStrings("bash", call.name);- try std.testing.expectEqualStrings("ls -la", call.detail);- try std.testing.expect(!call.done);- const outcome = m.history.items[1].tool orelse return error.NotFieldBacked;- try std.testing.expectEqualStrings("4 files", outcome.detail);- try std.testing.expect(outcome.done);- try std.testing.expect(!outcome.is_error);- try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[2].kind);- try std.testing.expectEqualStrings("all done", m.history.items[2].text);-}--test "a streamed line starting with a status glyph never becomes a tool row (#551)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- // Exactly the shape that produced phantom rows: the model's own answer,- // formatted as a checklist, streaming through the live buffer.- const live = "✓ tests pass\n✗ lint fails\n⚙ retrying\n";- const buf = try std.testing.allocator.dupe(u8, live);- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{ .buf = buf },- .threaded = false,- .result = try std.testing.allocator.dupe(u8, "✓ tests pass\n✗ lint fails\n⚙ retrying"),- };- job.stream.len.store(live.len, .release);- job.events.attach(std.testing.allocator);- job.done.store(true, .release);- try m.push(.pending, "");- m.pending = job;- finishJob(&m);- var tools: usize = 0;- for (m.history.items) |e| {- if (e.kind == .tool) tools += 1;- }- try std.testing.expectEqual(@as(usize, 0), tools);- try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[m.history.items.len - 1].kind);- // And the answer is stored ONCE — the old harvest left a copy behind as- // tool rows and then pushed the same text again as the answer.- var copies: usize = 0;- for (m.history.items) |e| {- if (std.mem.indexOf(u8, e.text, "tests pass") != null) copies += 1;- }- try std.testing.expectEqual(@as(usize, 1), copies);-}--test "a refusal and a failover reach the transcript instead of vanishing" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = false,- .result = try std.testing.allocator.dupe(u8, "ok"),- };- job.events.attach(std.testing.allocator);- job.events.push(.{ .tool_rejected = .{- .name = "write_file",- .detail = "plan mode forbids writes",- .is_error = true,- .denied = true,- } });- job.events.push(.{ .notice = "loaded 2 saved approval(s)" });- job.events.push(.{ .model_changed = .{ .model = "sonnet", .provider = "anthropic" } });- job.done.store(true, .release);- try m.push(.pending, "");- m.pending = job;- finishJob(&m);- const refused = m.history.items[0].tool orelse return error.NotFieldBacked;- try std.testing.expect(refused.denied);- try std.testing.expect(refused.is_error);- try std.testing.expect(refused.done);- try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);- try std.testing.expectEqualStrings("loaded 2 saved approval(s)", m.history.items[1].text);- // The failover updates what the status bar reads, not just the transcript.- try std.testing.expectEqualStrings("sonnet", engine.g_model_name);- // ...and the PROVIDER moves with it. Updating only the name left the new- // model paired with the old provider id, so models.isCurrent marked a seat- // that no longer served the turn.- try std.testing.expectEqualStrings("anthropic", engine.g_model_provider);- try std.testing.expect(std.mem.indexOf(u8, m.history.items[2].text, "sonnet") != null);-}--test "a live tool row is visible mid-turn, straight off the event queue" {- const scrollback = @import("scrollback.zig");- const Hold = struct {- var started: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, stream: *engine.StreamBuf, events: *engine.EventQueue) ?[]const u8 {- // The turn thread pushes structure and streams prose, exactly as- // the real sink does.- events.push(.{ .tool_started = .{ .name = "bash", .detail = "ls" } });- stream.appendBytes("working…\n");- started.store(true, .release);- while (!release.load(.acquire)) std.Thread.yield() catch {};- return gpa.dupe(u8, "all done") catch null;- }- };- Hold.started.store(false, .release);- Hold.release.store(false, .release);- engine.g_turn_fn = Hold.f;- defer {- Hold.release.store(true, .release);- engine.g_turn_fn = null;- }-- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "run it");- startJob(&m);- const job = m.pending orelse return error.NoJob;- var spins: usize = 0;- while (!Hold.started.load(.acquire)) : (spins += 1) {- if (spins > 100_000) return error.TurnNeverPublishedStream;- std.Thread.yield() catch {};- }- try std.testing.expect(!job.done.load(.acquire));- const snap = job.stream.snapshot(std.testing.allocator) orelse return error.LiveTailEmpty;- defer std.testing.allocator.free(snap);- // Prose only in the live buffer — the tool row is on the other channel.- try std.testing.expect(std.mem.indexOf(u8, snap, "working") != null);- try std.testing.expect(std.mem.indexOf(u8, snap, "bash") == null);- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- drainEvents(&m);- const harvested = try scrollback.render(&m, arena_state.allocator(), 80, 0);- // 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;- while (!job.done.load(.acquire)) : (spins += 1) {- if (spins > 100_000) return error.TurnNeverFinished;- std.Thread.yield() catch {};- }- finishJob(&m);- try std.testing.expectEqual(app.EntryKind.tool, m.history.items[m.history.items.len - 2].kind);- try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[m.history.items.len - 1].kind);-}--test "Ctrl+C during a turn cancels once then quits" {- var m: @import("app.zig").Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .threaded = false,- .gpa = std.testing.allocator,- .history = try std.testing.allocator.alloc(engine.Turn, 0),- .params = .{},- .stream = .{},- };- m.pending = job;- const keys = @import("keys.zig");- try std.testing.expectEqual(@import("app.zig").Effect.stay, keys.handle(&m, .{ .ctrl = 'c' }));- try std.testing.expect(m.cancel_requested);- try std.testing.expect(m.pending != null);- try std.testing.expectEqual(@import("app.zig").Effect.quit, keys.handle(&m, .{ .ctrl = 'c' }));-}--test "cancelTurn collapses thinking immediately" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{ .buf = &.{} },- .threaded = false,- .done = std.atomic.Value(bool).init(false),- };- try m.push(.pending, "");- m.pending = job;- cancelTurn(&m);- try std.testing.expect(m.cancel_requested);- try std.testing.expect(m.history.items.len == 1);- try std.testing.expect(m.history.items[0].kind == .system);- try std.testing.expectEqualStrings("■ interrupted", m.history.items[0].text);- // Events already in flight when the cancel landed still arrive, and they- // land after the notice — which must not make finishJob write a second one.- job.events.attach(std.testing.allocator);- job.events.push(.{ .tool_finished = .{ .name = "bash", .detail = "cancelled", .is_error = true } });- job.done.store(true, .release);- finishJob(&m);- try std.testing.expect(m.pending == null);- var n: usize = 0;- for (m.history.items) |e| {- if (std.mem.eql(u8, e.text, "■ interrupted")) n += 1;- }- try std.testing.expectEqual(@as(usize, 1), n);-}--test "quit waits for a live turn, then abandons it instead of joining forever (#534)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- const job = try std.testing.allocator.create(engine.Job);- defer std.testing.allocator.destroy(job); // the real path leaks it on purpose- job.* = .{- .gpa = std.testing.allocator,- .history = &.{},- .params = .{},- .stream = .{},- .threaded = true, // pretend a thread is still in the provider call- };- m.pending = job;- // Inside the drain window the quit path keeps painting instead of joining.- try std.testing.expectEqual(QuitStep.wait, quitStep(&m, 0));- try std.testing.expectEqual(QuitStep.wait, quitStep(&m, quit_drain_ms - 1));- // Past it the job is given up on, never joined.- try std.testing.expectEqual(QuitStep.abandon, quitStep(&m, quit_drain_ms));- abandonJob(&m);- try std.testing.expect(m.pending == null);- // A turn that DID unwind is reaped normally, however long quit waited.- m.pending = job;- job.done.store(true, .release);- try std.testing.expectEqual(QuitStep.reap, quitStep(&m, quit_drain_ms * 10));- m.pending = null;-}--test "Model.deinit never joins a running turn thread (#534)" {- const Hold = struct {- var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- var started: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, _: *engine.StreamBuf, _: *engine.EventQueue) ?[]const u8 {- started.store(true, .release);- while (!release.load(.acquire)) std.Thread.yield() catch {};- return gpa.dupe(u8, "late") catch null;- }- };- Hold.release.store(false, .release);- Hold.started.store(false, .release);- engine.g_turn_fn = Hold.f;- var m: Model = undefined;- m.setup(std.testing.allocator);- try m.push(.user, "hi");- startJob(&m);- const job = m.pending orelse return error.NoJob;- var spins: usize = 0;- while (!Hold.started.load(.acquire)) : (spins += 1) {- if (spins > 1_000_000) return error.TurnNeverStarted;- std.Thread.yield() catch {};- }- // deinit must return while the turn thread is still inside the call.- m.deinit();- try std.testing.expect(!job.done.load(.acquire));- // Now let the thread finish and clean up what deinit deliberately left.- Hold.release.store(true, .release);- job.thread.join();- engine.g_turn_fn = null;- if (job.result) |r| std.testing.allocator.free(r);- for (job.history) |t| std.testing.allocator.free(t.text);- std.testing.allocator.free(job.history);- if (job.stream.buf.len > 0) std.testing.allocator.free(job.stream.buf);- if (job.raw.buf.len > 0) std.testing.allocator.free(job.raw.buf);- std.testing.allocator.destroy(job);-}--test "finishJob strips a pending row buried under steer echoes (#520)" {- var m: Model = undefined;- m.setup(std.testing.allocator);- defer m.deinit();- try m.push(.user, "hi");- try m.push(.pending, "");- try m.push(.system, "↳ queued (1 waiting)");- const job = try std.testing.allocator.create(engine.Job);- job.* = .{- .threaded = false,- .gpa = std.testing.allocator,- .history = try std.testing.allocator.alloc(engine.Turn, 0),- .params = .{},- .stream = .{},- };- job.done.store(true, .release);- m.pending = job;- finishJob(&m);- try std.testing.expect(m.pending == null);- for (m.history.items) |e| try std.testing.expect(e.kind != .pending);-}diff --git a/TUI/turn_spawn_tests.zig b/TUI/turn_spawn_tests.zigdeleted file mode 100644index 700d06fd..00000000--- a/TUI/turn_spawn_tests.zig+++ /dev/null@@ -1,181 +0,0 @@-//! Spawn-failure coverage for every fullscreen-TUI turn entry path.--const std = @import("std");--const app = @import("app.zig");-const engine = @import("engine.zig");-const turn = @import("turn.zig");-const Term = @import("sim.zig").Term;--const Fake = struct {- var turn_calls: usize = 0;- var join_calls: usize = 0;- var wake_calls: usize = 0;-- fn reset() void {- turn_calls = 0;- join_calls = 0;- wake_calls = 0;- }-- fn spawn(_: *engine.Job) anyerror!std.Thread {- return error.InjectedSpawnFailure;- }-- fn joined() void {- join_calls += 1;- }-- fn modelWork(_: ?*anyopaque, _: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, _: *engine.StreamBuf, _: *engine.EventQueue) ?[]const u8 {- // This callback encloses the TUI's provider, tools, and automatic- // compaction. A spawn failure must not enter any of it.- turn_calls += 1;- return null;- }-- fn wake(_: ?*anyopaque, buf: []u8) ?[]const u8 {- if (wake_calls != 0) return null;- wake_calls += 1;- const text = "automatic follow-up";- @memcpy(buf[0..text.len], text);- return buf[0..text.len];- }-};--fn install() void {- Fake.reset();- engine.g_turn_fn = Fake.modelWork;- engine.setJobThreadHooksForTesting(Fake.spawn, Fake.joined);-}--fn uninstall() void {- engine.setJobThreadHooksForTesting(null, null);- engine.g_turn_fn = null;- engine.g_idle_wake_fn = null;-}--fn expectFailedStart(term: *Term) !void {- const job = term.model.pending orelse return error.NoPendingJob;- try std.testing.expect(job.start_failed);- try std.testing.expect(!job.threaded);- try std.testing.expect(job.done.load(.acquire));- try std.testing.expectEqual(turn.QuitStep.reap, turn.quitStep(&term.model, 0));- try std.testing.expectEqual(@as(usize, 0), Fake.turn_calls);- try std.testing.expectEqual(@as(usize, 0), Fake.join_calls);-}--fn finishFailedStart(term: *Term) !void {- turn.finishJob(&term.model);- try std.testing.expect(term.model.pending == null);- try std.testing.expect(engine.g_raw == null);- try std.testing.expect(!term.model.cancel_requested);- const last = term.model.history.items[term.model.history.items.len - 1];- try std.testing.expectEqual(app.EntryKind.err, last.kind);- try std.testing.expectEqualStrings("model turn failed to start — retry your prompt", last.text);- for (term.model.history.items) |entry| try std.testing.expect(entry.kind != .pending);- try std.testing.expectEqual(@as(usize, 0), Fake.turn_calls);- try std.testing.expectEqual(@as(usize, 0), Fake.join_calls);-}--test "turn spawn failure stays off-thread for initial, queued, and subsequent TUI prompts (#537)" {- install();- defer uninstall();- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();-- // Initial prompt takes dispatch.applyLine -> turn.startJob.- _ = term.typeText("initial prompt");- _ = term.enter();- try expectFailedStart(&term);- const first = term.model.pending.?;-- // Before the next poll reaps the failed start, paint and input still work;- // Enter follows the normal live-turn path and queues this draft.- _ = term.typeText("queued follow-up");- try std.testing.expectEqualStrings("queued follow-up", term.model.input.getValue());- const visible = try term.screen();- defer std.testing.allocator.free(visible);- try std.testing.expect(std.mem.indexOf(u8, visible, "queued follow-up") != null);- _ = term.enter();- try std.testing.expect(term.model.pending.? == first);- try std.testing.expectEqual(@as(usize, 1), term.model.steer_queue.items.len);-- // The render-loop poll reports and frees the first Job, then its FIFO drain- // starts the queued turn through the same failing spawn seam.- try finishFailedStart(&term);- try std.testing.expectEqual(app.Effect.stay, turn.drainSteer(&term.model));- try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);- try expectFailedStart(&term);- try finishFailedStart(&term);-- // A later ordinary prompt is the same trajectory after pending cleared.- _ = term.typeText("subsequent prompt");- _ = term.enter();- try expectFailedStart(&term);- try finishFailedStart(&term);- try std.testing.expectEqual(@as(usize, 0), Fake.turn_calls);- try std.testing.expectEqual(@as(usize, 0), Fake.join_calls);-}--test "idle wake spawn failure is reapable without a thread or model work (#537)" {- install();- defer uninstall();- engine.g_idle_wake_fn = Fake.wake;- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- var deinited = false;- defer if (!deinited) term.deinit();-- turn.maybeJobWake(&term.model);- try std.testing.expectEqual(@as(usize, 1), Fake.wake_calls);- try expectFailedStart(&term);- try std.testing.expectEqualStrings("automatic follow-up", term.model.history.items[0].text);- try std.testing.expectEqual(app.EntryKind.system, term.model.history.items[0].kind);- try std.testing.expect(term.model.pending.?.history[0].notification);-- // Model.deinit's alternate cleanup path also sees threaded=false: the- // undefined thread handle is never joined, and all Job ownership is freed.- term.deinit();- deinited = true;- try std.testing.expect(engine.g_raw == null);- try std.testing.expectEqual(@as(usize, 0), Fake.turn_calls);- try std.testing.expectEqual(@as(usize, 0), Fake.join_calls);-}--test "#1136 idle wake does not start a turn while one is already in flight" {- install();- defer uninstall();- engine.g_idle_wake_fn = Fake.wake;- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("in flight");- _ = term.enter();- try expectFailedStart(&term);- turn.maybeJobWake(&term.model);- try std.testing.expectEqual(@as(usize, 0), Fake.wake_calls);- try finishFailedStart(&term);-}--test "completion wake waits for drafts and queued user input" {- install();- defer uninstall();- engine.g_idle_wake_fn = Fake.wake;- var term: Term = undefined;- term.init(std.testing.allocator, 80, 24);- defer term.deinit();- _ = term.typeText("my unfinished prompt");- turn.maybeJobWake(&term.model);- try std.testing.expectEqual(@as(usize, 0), Fake.wake_calls);- try std.testing.expectEqualStrings("my unfinished prompt", term.model.input.getValue());- try term.model.input.setValue("");- try term.model.steer_queue.append(try std.testing.allocator.dupe(u8, "next task"));- turn.maybeJobWake(&term.model);- try std.testing.expectEqual(@as(usize, 0), Fake.wake_calls);- std.testing.allocator.free(term.model.steer_queue.orderedRemove(0));- turn.maybeJobWake(&term.model);- try std.testing.expectEqual(@as(usize, 1), Fake.wake_calls);- try expectFailedStart(&term);- try finishFailedStart(&term);-}diff --git a/TUI/welcome.zig b/TUI/welcome.zigdeleted file mode 100644index 9f7de6b1..00000000--- a/TUI/welcome.zig+++ /dev/null@@ -1,18 +0,0 @@-//! Welcome pane. ANSI only.--const std = @import("std");--const app = @import("app.zig");-const Model = app.Model;--/// Idle mid-pane is empty — Grok's pager is a blank field over the composer.-pub fn render(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {- _ = self;- _ = a;- _ = width;- return "";-}--test "idle welcome is empty" {- try std.testing.expectEqualStrings("", try render(undefined, std.testing.allocator, 80));-}diff --git a/build.zig b/build.zigindex e70c18c2..0bdb3610 100644--- a/build.zig+++ b/build.zig@@ -59,30 +59,20 @@ pub fn build(b: *std.Build) void {const http_zig_dep = b.dependency("http_zig", .{ .target = target, .optimize = optimize });const http_zig_mod = http_zig_dep.module("http_zig");exe.root_module.addImport("http_zig", http_zig_mod);- // Shared by the line-REPL picker and the TUI overlay so they cannot- // drift: a file import from both modules is illegal in Zig 0.17.+ // Shared model-ranking module used by the line-REPL picker.const models_rank_mod = b.createModule(.{.root_source_file = b.path("src/models_rank.zig"),.target = target,.optimize = optimize,});exe.root_module.addImport("models_rank", models_rank_mod);- // Same reason: one nearest-command speller for the REPL/ACP catalog and- // the TUI catalog (#1275).+ // Shared nearest-command speller for the REPL/ACP catalog.const slash_suggest_mod = b.createModule(.{.root_source_file = b.path("src/slash_suggest.zig"),.target = target,.optimize = optimize,});exe.root_module.addImport("slash_suggest", slash_suggest_mod);- const tui_mod = b.createModule(.{- .root_source_file = b.path("TUI/root.zig"),- .target = target,- .optimize = optimize,- });- tui_mod.addImport("models_rank", models_rank_mod);- tui_mod.addImport("slash_suggest", slash_suggest_mod);- exe.root_module.addImport("tui", tui_mod);const install_graff = b.addInstallArtifact(exe, .{});b.getInstallStep().dependOn(&install_graff.step);const graff_step = b.step("graff", "Build and install only the release CLI");@@ -117,7 +107,6 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addImport("http_zig", http_zig_mod);unit_tests.root_module.addImport("models_rank", models_rank_mod);unit_tests.root_module.addImport("slash_suggest", slash_suggest_mod);- unit_tests.root_module.addImport("tui", tui_mod);// spec/ fixtures live outside src/; importing them here makes @embedFile// legal and rebuilds the suite when the exported semantics change.exe.root_module.addAnonymousImport("ui_theme", .{ .root_source_file = b.path("src/ui_theme.css") });@@ -260,40 +249,9 @@ pub fn build(b: *std.Build) void {unit_tests.root_module.addAnonymousImport(asset.import, .{ .root_source_file = b.path(asset.path) });}- const tui_exe = b.addExecutable(.{- .name = "graff-tui",- .root_module = b.createModule(.{- .root_source_file = b.path("TUI/root.zig"),- .target = target,- .optimize = optimize,- .strip = lean_release,- .link_libc = true,- }),- });- tui_exe.root_module.addImport("models_rank", models_rank_mod);- tui_exe.root_module.addImport("slash_suggest", slash_suggest_mod);- b.installArtifact(tui_exe);-- const tui_tests = b.addTest(.{- .root_module = b.createModule(.{- .root_source_file = b.path("TUI/root.zig"),- .target = target,- .optimize = optimize,- // The dump/bench helpers read GRAFF_TUI_DUMP / GRAFF_TUI_BENCH- // through std.c.getenv. Without libc those tests do not compile- // on Linux, so the painter battery never ran here.- .link_libc = true,- }),- // Same -Dtest-filter as `zig build test`: the layout benchmark needs to- // be runnable on its own, ReleaseFast, without the rest of the suite.- .filters = test_filters,- });- tui_tests.root_module.addImport("models_rank", models_rank_mod);- tui_tests.root_module.addImport("slash_suggest", slash_suggest_mod);- tui_tests.root_module.addAnonymousImport("spec_terminal_modes", .{ .root_source_file = b.path("spec/kernels/terminal_modes.json") });-- const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");- tui_test_step.dependOn(&b.addRunArtifact(tui_tests).step);+ const external_tui_test = b.addSystemCommand(&.{ "python3", "scripts/test-external-tui.py" });+ external_tui_test.addArtifactArg(exe);+ test_step.dependOn(&external_tui_test.step);// In-process ACP (fx-shaped embed). Off the default install so the// tagged CLI cut does not grow a .so / .wasm. `zig build libgraff`diff --git a/docs/adr/0240-fullscreen-tui-is-an-external-client.md b/docs/adr/0240-fullscreen-tui-is-an-external-client.mdnew file mode 100644index 00000000..29258559--- /dev/null+++ b/docs/adr/0240-fullscreen-tui-is-an-external-client.md@@ -0,0 +1,23 @@+# 0240. Fullscreen TUI is an external client++Status: accepted 2026-10-02++Supersedes ADR 0041, ADR 0042 and the fullscreen portion of ADR 0142.++## Context++The fullscreen terminal UI is maintained separately. Keeping its former Zig renderer and in-process adapters here leaves a second implementation to build, test and maintain alongside the engine and line REPL.++## Decision++Remove the embedded `TUI/` implementation, its `src/tui*` adapters, build targets and UI-specific regression tooling. Keep shared engine behavior, ACP, the line REPL and its terminal checks here; rendering coverage belongs with the separate client.++`graff tui [args...]` launches an installed `graff-tui` before argument parsing, credentials, MCP or session creation. Resolve beside the running executable first, then on `PATH`, and forward the remaining arguments unchanged. POSIX uses process replacement; Windows inherits standard handles and waits for the child. Missing installations fail with installation guidance, without downloads or engine startup. `graff -p "tui"` remains a prompt.++TTY `graff repl` uses the normal line REPL; piped `graff repl` keeps its scripted model. No engine path claims the fullscreen client's alternate screen.++## Consequences++The default build installs only `graff`, and `tui-test` is retired. Launcher subprocess tests use fake executables to cover lookup order, argument and standard-stream forwarding, process replacement, exit status and missing installations without starting a real UI.++The unit-count floor is adjusted for removed adapter tests, not weakened to hide unreachable engine tests. Automatic verified downloads and compatibility negotiation from #1444 remain separate work: no release-asset contract is invented here, and the installed-only launcher works offline.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c7d8791f..c62ceebb 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -266,6 +266,7 @@ record only when you need the evidence or the edge cases.| [0237](0237-deepseek-thinks-at-its-low-level-by-default.md) | DeepSeek's default effort (`medium`) sends `reasoning_effort: low` with thinking enabled; `/effort low` still turns thinking off (ADR 0054), and `high` and above are unchanged. || [0238](0238-rlm-binds-keep-the-whole-mcp-result.md) | An MCP call inside an rlm script binds the whole result; `print()` shows the slim view (each item of an `each()` bind cut on its own), `project(x, field)` reads any field (`n`/`latest_author` through a comment list's fold), and `write_file` saves the whole result; inside rlm, `read_tool_result("tr_N")` with no range binds a stored result whole. || [0239](0239-saved-workspaces-have-durable-discovery.md) | Remember saved workspace roots locally; remote picker targets are workspace-qualified, and resume must enter the selected tree before restoring it. |+| [0240](0240-fullscreen-tui-is-an-external-client.md) | The fullscreen UI is maintained separately; `graff tui` launches installed `graff-tui` before engine startup, sibling first then PATH, without downloading. TTY `graff repl` uses the line REPL. Supersedes 0041, 0042 and the fullscreen portion of 0142. |## When to write onediff --git a/docs/architecture.md b/docs/architecture.mdindex d998f2a4..8568666a 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -1,7 +1,8 @@# Architecture-Codegraff is a coding agent built with Zig 0.17. The terminal pager is-first-party (`TUI/`); the desktop app is+Codegraff is a coding agent built with Zig 0.17. The fullscreen terminal UI is+maintained separately: `graff tui` launches an installed `graff-tui` sibling+executable, falling back to `PATH`, without downloading it. The desktop app is[Harness](https://github.com/justrach/harness), an ACP client. The harness talks toLLM providers, runs tools (including subagents and MCP servers) inparallel, and compacts its own context. This document explains how thediff --git a/docs/local-learning.md b/docs/local-learning.mdindex c2f608a6..a82c95c7 100644--- a/docs/local-learning.md+++ b/docs/local-learning.md@@ -11,7 +11,7 @@ active parent → deterministic mutation seeds → paired evaluation## Nothing to run-Learning is on by default for an interactive session. The first REPL/TUI/ACP+Learning is on by default for an interactive session. The first REPL/ACPsession in a workspace that does real model work (at least 5 calls, so aone-off question never triggers it) sets the workspace up on its way out.`-p` and `--json` never do this — those exits are not a workspace optingdiff --git a/docs/yxlyx-leftovers.md b/docs/yxlyx-leftovers.mdindex faf4d0cb..4c017ebb 100644--- a/docs/yxlyx-leftovers.md+++ b/docs/yxlyx-leftovers.md@@ -1,6 +1,8 @@# yxlyx leftovers (279 continuation)-What still exists in this repo versus what is parked. No new product mode.+Historical status at the v0.0.282 cut: what existed in this repo versus what+was parked. This is not a current issue inventory; the embedded TUI and its+simulator have since moved out of this repository. No new product mode.Landed on [v0.0.282](releases/v0.0.282.md): `#674` atomic paste spans,`#693` Codex WS `type:error`, `#694` HTTP client generations (ADR 0048),diff --git a/lean-proofs/Graff.lean b/lean-proofs/Graff.leanindex 9007b4e6..57661541 100644--- a/lean-proofs/Graff.lean+++ b/lean-proofs/Graff.lean@@ -7,7 +7,6 @@ import Graff.Shapeimport Graff.Scoreimport Graff.BashPolicyimport Graff.StructuredOutput-import Graff.TerminalModesimport Graff.PromptCacheimport Graff.PromptPrefiximport Graff.PromptStablediff --git a/lean-proofs/Graff/TerminalModes.lean b/lean-proofs/Graff/TerminalModes.leandeleted file mode 100644index b06b1170..00000000--- a/lean-proofs/Graff/TerminalModes.lean+++ /dev/null@@ -1,108 +0,0 @@-/-- Terminal-mode lifecycle (the tuiguard invariant, grok-build's ModeTracker- as a kernel): a TUI session is a stream of DEC private-mode ops and kitty- keyboard pushes/pops; restore must return every mode to the TERMINAL- DEFAULT and the kitty depth to zero, with the alt-screen leave (1049)- ordered last so nothing paints on the user's real screen.-- Modes 7 (autowrap) and 25 (cursor visible) default ON — their restore- direction is `set`, everything else restores by `reset`. Kitty pops floor- at zero (grok-build floors the same way, so over-popping cannot go- negative). The two concrete theorems at the bottom pin graff's ACTUAL- enable/restore byte sequences (TUI/run.zig enable_seq, TUI/restore.zig- seq) as op lists: their composition is balanced, and restore leaves the- alt-screen last.-- Process kernel, not a Turing machine: `Op` is the event, `step` is the- transition (mode map + kitty depth). The 14 named sequences are the- snapshot. Enable then restore returns to defaults; restore leaves the- alt-screen last; kitty pop floors at zero.-- Executable port: spec/ref/terminal_modes.py (also the semantics behind- scripts/tui-pty-guard.py). Impl anchor: TUI/spec_terminal_modes_conformance.zig- parses the real constants and diffs them against the fixture.--/--namespace Graff.TerminalModes--inductive Op- | set (n : Nat) | reset (n : Nat) | push | pop-deriving DecidableEq, Repr--/-- Events are the DEC/kitty ops. -/-abbrev Event := Op--def defaultOn : List Nat := [7, 25]--/-- Last-op-wins mode map plus the kitty push/pop depth (floored at 0). -/-def setFinal (m : List (Nat × Bool)) (n : Nat) (v : Bool) : List (Nat × Bool) :=- (n, v) :: m.filter (fun p => p.1 ≠ n)--def step (s : List (Nat × Bool) × Nat) : Op → List (Nat × Bool) × Nat- | .set n => (setFinal s.1 n true, s.2)- | .reset n => (setFinal s.1 n false, s.2)- | .push => (s.1, s.2 + 1)- | .pop => (s.1, s.2 - 1)--def fold (ops : List Op) : List (Nat × Bool) × Nat := ops.foldl step ([], 0)--def isDefault (n : Nat) (v : Bool) : Bool := v == defaultOn.contains n--/-- Modes whose final state differs from the terminal default. -/-def deviations (m : List (Nat × Bool)) : List Nat :=- (m.filter fun p => !isDefault p.1 p.2).map (·.1)--def balanced (ops : List Op) : Bool :=- let (m, d) := fold ops- (deviations m).isEmpty && d == 0--/-- Restore for a session: pop the kitty depth, flip every deviant mode back- to its default, and leave the alt-screen (1049) LAST. -/-def restoreOps (ops : List Op) : List Op :=- let (m, d) := fold ops- let devs := deviations m- let flips := (devs.filter (· ≠ 1049)).map fun n =>- if defaultOn.contains n then Op.set n else Op.reset n- let alt : List Op := if devs.contains 1049 then [.reset 1049] else []- (List.replicate d .pop) ++ flips ++ alt--/-- graff's boot sequence (TUI/run.zig enable_seq) as ops, in byte order. -/-def graffEnable : List Op :=- [.set 1049, .reset 25, .set 2004, .set 1000, .set 1003, .set 1006, .reset 7, .push]--/-- graff's restore sequence (TUI/restore.zig seq) as ops, in byte order.- (The non-DEC `ESC[>4;0m` modifyOtherKeys reset carries no mode number- and is outside this model, exactly as in the executable port.) -/-def graffRestore : List Op :=- [.reset 2026, .pop, .set 7, .reset 1006, .reset 1003, .reset 1000, .reset 2004, .set 25, .reset 1049]--/-- Kitty pops floor at zero: over-popping can never underflow the depth. -/-theorem pop_floors : (fold [.pop, .pop, .push]).2 = 1 := by decide--/-- An untouched terminal is balanced (byte transparency's base case). -/-theorem empty_balanced : balanced [] = true := by decide--/-- THE lifecycle theorem, on the real sequences: booting graff's TUI and- running its restore returns the terminal exactly to defaults. -/-theorem graff_lifecycle_balanced : balanced (graffEnable ++ graffRestore) = true := by decide--/-- The restore's final op leaves the alt-screen — nothing may paint after. -/-theorem graff_restore_alt_last : graffRestore.getLast? = some (.reset 1049) := by decide--/-- restore of a restored session is a no-op list (grok-build's- byte-transparency e2e, as a theorem on the model). -/-theorem restore_idempotent :- restoreOps (graffEnable ++ graffRestore) = [] := by decide--/-- The generated restore also balances the real boot state — the model's- restoreOps and graff's committed sequence agree on the outcome. -/-theorem generated_restore_balances :- balanced (graffEnable ++ restoreOps graffEnable) = true := by decide--/-- Pop on an untouched terminal stays at depth 0 (Nat floors). -/-theorem pop_from_zero : (step ([], 0) .pop).2 = 0 := by decide--/-- Enable alone is not balanced — restore is what returns to defaults. -/-theorem enable_unbalanced : balanced graffEnable = false := by decide--end Graff.TerminalModesdiff --git a/lean-proofs/KERNELS.md b/lean-proofs/KERNELS.mdindex 1de86a30..e21dc96c 100644--- a/lean-proofs/KERNELS.md+++ b/lean-proofs/KERNELS.md@@ -17,9 +17,7 @@ root partition), `PromptPrefix` (names + triggers, pinned once; skillload/list/rescan do not rewrite the prefix), `PromptStable` (OpenGaussmust-nots: skills/schemas in history, no clock/toolset-rewrite/memoryreload in the prefix; compact re-pins — showcase with-`python3 spec/conformance.py --showcase`), `TerminalModes` (`Op`/`step`-mode map + kitty depth; enable++restore returns to Idle; pop floors;-alt-screen leave is last), `PathConfine` (component walk: Escaped and+`python3 spec/conformance.py --showcase`), `PathConfine` (component walk: Escaped andAbsolute absorb), `Transport` (a sub never takes WS; only one live rootResponses cell does), and `Score` (`attempt` never files; `capture`after the join files one stage row). They are not Turing machines: no@@ -53,7 +51,6 @@ not a skip: TUI, prompts, and SSE bytes stay out of Lean on purpose.| `PromptCache` | 48 cells + `Event`/`step` | provider cache HIT, uuid5 cwd bytes, vision pin || `PromptPrefix` | 6 cells + `Event`/`step` | catalog wording, provider HIT, compaction || `PromptStable` | 20 cells + `Event`/`step` | Anthropic `cache_control` bytes, compact summary wording |-| `TerminalModes` | 14 named sequences + `Op`/`step` | TUI layout, glyphs, the emulator font || `PathConfine` | 16 lexical paths + 80 lease cells + `Event`/`step` | OS errno, Windows drives, live symlink walk || `Shape` | 1728 ladder cells | `admit`, learned override, ε-explore, `observe` || `Score` | 1210 filing cells (240 filed) + `Event`/`step`; 11 titles; 16 class samples | HMAC, providerClass price fallback |diff --git a/scripts/bench-tui-layout.sh b/scripts/bench-tui-layout.shdeleted file mode 100755index 5a673921..00000000--- a/scripts/bench-tui-layout.sh+++ /dev/null@@ -1,20 +0,0 @@-#!/usr/bin/env bash-# The TUI layout cache, measured. ReleaseFast only: a Debug build inflates-# these numbers by ~50x and every figure off one is a fiction (AGENTS.md).-#-# scripts/bench-tui-layout.sh-#-# Builds the TUI test artifact optimized, runs the benchmark test alone with a-# 10k-display-line transcript, and prints:-# * p95 frame BUILD time while scrolling (target: < 1 ms)-# * worst cold rebuild after a width change (target: < 10 ms)-# * the uncached full layout it replaces, for scale-set -euo pipefail--repo_root=$(git -C "$(dirname "${BASH_SOURCE[0]}")/.." rev-parse --show-toplevel)-cd "$repo_root"--exec env GRAFF_TUI_BENCH=1 zig build tui-test \- -Doptimize=ReleaseFast \- -Dtest-filter="layout cache benchmark" \- --summary alldiff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex ceeaf1d2..4bc44e0a 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -3,7 +3,7 @@# and free. No provider calls, no network, no model in the loop. This is what# the pre-push hook runs, so it has to stay honest and it has to stay fast:# a warm fmt/reach/sdk subset is seconds; a post-src run rebuilds zig and-# the PTY pool (minutes, see #641).+# the engine integration probes (minutes).## Tier 2 is the model-backed behavioral eval set (scripts/eval-tier2.py). It is# deliberately NOT in the hook: it spends turns and it is slower.@@ -11,7 +11,7 @@# scripts/eval-tier1.sh run every check# scripts/eval-tier1.sh --list show the check names# scripts/eval-tier1.sh --only sdk run one check-# scripts/eval-tier1.sh --only tui,tuiguard run a comma-separated list (#641)+# scripts/eval-tier1.sh --only fmt,reach run a comma-separated list (#641)#set -uo pipefail@@ -27,7 +27,7 @@ cd "$repo_root"# processes discover their repo from their cwd like they expect.unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_COMMON_DIR GIT_OBJECT_DIRECTORY GIT_PREFIX-CHECKS=(fmt lines spec reach build shell tests tui tuiguard invariants sdk)+CHECKS=(fmt lines spec reach build shell tests terminal invariants sdk)usage() {cat <<'EOF'@@ -41,9 +41,7 @@ checks, in order:build zig buildshell durable shell IDs and stale-handle isolation after a crashtests zig build test, and the suite count never shrinks- tui zig build tui-test (the TUI suite was ungated until the 2026-08 bug wave)- tuiguard real-binary pty probes: lifecycle invariants (tui-pty-guard.py)- and virtual-screen checks (test-tui-screenstate.py)+ terminal PTY cleanup integrity and line-REPL prompt reflowinvariants the named goal/loop/todo tests actually ran, not just compiledsdk the committed SDKs match `graff --schema`EOF@@ -261,33 +259,14 @@ if wanted tests; thenfifi-# --- tui ----------------------------------------------------------------if wanted tui; then+# --- terminal ----------------------------------------------------------+if wanted terminal; thenif ((!build_ok)); then- skip_dependent tui+ skip_dependent terminalelse- announce tui "zig build tui-test — the TUI parser/render suite"- out=$(zig build tui-test --summary all 2>&1)- if (($? != 0)); then- printf '%s\n' "$out" | tail -8- record_fail tui- else- printf '%s\n' "$out" | sed -n 's/.*Build Summary: .*; \([0-9/]* tests passed.*\)/ \1/p' | tail -1- fi- fi-fi--# --- tuiguard -----------------------------------------------------------if wanted tuiguard; then- if ((!build_ok)); then- skip_dependent tuiguard- else- announce tuiguard "19 PTY probes in a 4–8 process pool (#641 / #704 / #537)"- # Original 17 plus the ESC-split and line-REPL prompt-reflow regressions.- # Each owns its pty/tmp/mock; the pool is the wall-time win. Deadlines- # (#704) are checked first so a wedged probe cannot hang pre-push.- if python3 scripts/eval/test_pty_cleanup.py && python3 scripts/eval/test_tier1_tuiguard.py && python3 scripts/eval/tier1_tuiguard.py zig-out/bin/graff; then :; else- record_fail tuiguard+ announce terminal "PTY cleanup integrity and line-REPL prompt reflow"+ if python3 scripts/eval/test_pty_cleanup.py && python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-repl-prompt-reflow.py zig-out/bin/graff; then :; else+ record_fail terminalfififidiff --git a/scripts/eval/clipboard_fixture.py b/scripts/eval/clipboard_fixture.pydeleted file mode 100644index aa92443b..00000000--- a/scripts/eval/clipboard_fixture.py+++ /dev/null@@ -1,43 +0,0 @@-"""Private clipboard command boundary for offline PTY probes.--The probe and its Graff child share these commands through PATH. Direct probe-runs still exercise the OS clipboard; the parallel gate must neither race with-other probes nor read or replace the user's clipboard.-"""-from contextlib import contextmanager-import os-from pathlib import Path-import shlex-import sys-import tempfile---@contextmanager-def private_clipboard():- with tempfile.TemporaryDirectory(prefix="tuiguard-clipboard-") as directory:- root = Path(directory)- clipboard = root / "clipboard"- clipboard.write_bytes(b"")- handler = root / "clipboard.py"- handler.write_text(- "import os, pathlib, select, sys\n"- "path = pathlib.Path(__file__).with_name('clipboard')\n"- "args = sys.argv[1:]\n"- "reading = args[:1] == ['pbpaste'] or '-o' in args or '-out' in args\n"- "writing = '-i' in args or '-in' in args or args[:1] == ['pbcopy']\n"- "if reading or (not writing and not select.select([sys.stdin], [], [], 0.05)[0]):\n"- " sys.stdout.buffer.write(path.read_bytes())\n"- "else:\n"- " temporary = path.with_name('write-' + str(os.getpid()))\n"- " temporary.write_bytes(sys.stdin.buffer.read())\n"- " temporary.replace(path)\n",- encoding="utf-8",- )- for command in ("pbcopy", "pbpaste", "xclip"):- wrapper = root / command- wrapper.write_text(- f"#!/bin/sh\nexec {shlex.quote(sys.executable)} {shlex.quote(str(handler))} {command} \"$@\"\n",- encoding="utf-8",- )- wrapper.chmod(0o700)- yield {**os.environ, "PATH": str(root) + os.pathsep + os.environ.get("PATH", "")}diff --git a/scripts/eval/hover_baseline_cases.py b/scripts/eval/hover_baseline_cases.pydeleted file mode 100644index f9e326cf..00000000--- a/scripts/eval/hover_baseline_cases.py+++ /dev/null@@ -1,70 +0,0 @@-"""Deterministic frame-clock coverage for the terminal hover baseline."""-import importlib.util-from pathlib import Path-import unittest--probe_path = Path(__file__).resolve().parents[1] / "test-tui-hover.py"-spec = importlib.util.spec_from_file_location("tui_hover_probe", probe_path)-probe = importlib.util.module_from_spec(spec)-spec.loader.exec_module(probe)-from ptyharness import Cell---class Frames:- cols, rows = 40, 6- canvas, flash = (20, 20, 20), (36, 36, 36)-- def __init__(self, style):- self.now = 0.0- self.style = style-- def pump(self, seconds):- self.now += seconds-- def screen_lines(self):- return ["", "› Read 1 file" if self.style(self.now) != "missing" else "", "", "", "", ""]-- def cell(self, x, y):- text = self.screen_lines()[y].ljust(self.cols)- style = self.style(self.now)- colored = y == 1 and (style == "uniform" or (style == "flash" and 1 <= x < self.cols - 1))- return Cell(text[x], bg=self.flash if colored else self.canvas)---class HoverBaselineTests(unittest.TestCase):- def wait(self, frames, timeout=2.0):- return probe.wait_for_resting_row(frames, timeout, lambda: frames.now)-- def test_completion_flash_must_end_before_baseline(self):- frames = Frames(lambda t: "flash" if t < 1.0 else "canvas")- self.assertEqual(self.wait(frames), 1)- self.assertGreaterEqual(frames.now, 1.1)- self.assertLess(frames.now, 1.3)-- def test_one_transitional_canvas_frame_does_not_satisfy_stability(self):- frames = Frames(lambda t: "canvas" if t < 0.05 or t >= 1.0 else "flash")- self.assertEqual(self.wait(frames), 1)- self.assertGreaterEqual(frames.now, 1.1)-- def test_uniform_non_canvas_tint_is_not_a_valid_baseline(self):- frames = Frames(lambda _: "uniform")- with self.assertRaisesRegex(TimeoutError, "canvas"):- self.wait(frames)- self.assertAlmostEqual(frames.now, 2.0)-- def test_permanent_mixed_background_still_fails(self):- frames = Frames(lambda _: "flash")- with self.assertRaisesRegex(TimeoutError, "did not settle"):- self.wait(frames)- self.assertAlmostEqual(frames.now, 2.0)-- def test_missing_header_fails_at_the_deadline(self):- frames = Frames(lambda _: "missing")- with self.assertRaisesRegex(TimeoutError, "no folded tool summary"):- self.wait(frames)- self.assertAlmostEqual(frames.now, 2.0)-- def test_already_settled_row_needs_only_a_stable_frame_interval(self):- frames = Frames(lambda _: "canvas")- self.assertEqual(self.wait(frames), 1)- self.assertAlmostEqual(frames.now, 0.1)diff --git a/scripts/eval/test_tier1_tuiguard.py b/scripts/eval/test_tier1_tuiguard.pydeleted file mode 100644index c3294c85..00000000--- a/scripts/eval/test_tier1_tuiguard.py+++ /dev/null@@ -1,237 +0,0 @@-#!/usr/bin/env python3-"""Integrity tests for the tuiguard pool deadlines (#704)."""--from __future__ import annotations--import importlib.util-import os-from pathlib import Path-import shutil-import subprocess-import sys-import tempfile-import time-import unittest-from concurrent.futures import ThreadPoolExecutor-from threading import Barrier-from unittest import mock-from hover_baseline_cases import HoverBaselineTests---RUNNER_PATH = Path(__file__).with_name("tier1_tuiguard.py")-SPEC = importlib.util.spec_from_file_location("tier1_tuiguard", RUNNER_PATH)-if SPEC is None or SPEC.loader is None:- raise RuntimeError(f"cannot import {RUNNER_PATH}")-tuiguard = importlib.util.module_from_spec(SPEC)-SPEC.loader.exec_module(tuiguard)---class DeadlineTests(unittest.TestCase):- @mock.patch.dict(os.environ, {"GRAFF_TUIGUARD_PROBE_TIMEOUT": ""})- def test_probe_timeout_uses_long_list_and_env(self) -> None:- self.assertEqual(tuiguard.probe_timeout("test-tui-click.py"), 90.0)- self.assertEqual(tuiguard.probe_timeout("tui-pty-guard.py"), 60.0)- with mock.patch.dict(os.environ, {"GRAFF_TUIGUARD_PROBE_TIMEOUT": "0.4"}):- self.assertEqual(tuiguard.probe_timeout("test-tui-click.py"), 0.4)-- def test_parent_budget_is_waves_times_longest_plus_slack(self) -> None:- names = ("a.py", "b.py", "c.py")- with mock.patch.object(tuiguard, "probe_timeout", return_value=10.0):- # 3 probes / 2 workers = 2 waves → 20 + 60- self.assertEqual(tuiguard.parent_budget(2, names), 80.0)-- def test_run_command_kills_a_wedged_child(self) -> None:- status, blob, elapsed, timed_out = tuiguard.run_command(- [sys.executable, "-c", "import time; time.sleep(30)"],- timeout=0.3,- )- self.assertTrue(timed_out)- self.assertEqual(status, 124)- self.assertLess(elapsed, 5.0)- self.assertGreaterEqual(elapsed, 0.25)- _ = blob-- def test_run_command_kills_the_process_group(self) -> None:- if not hasattr(os, "fork") or not hasattr(os, "kill"):- self.skipTest("posix process groups")- scratch = tempfile.TemporaryDirectory(prefix="tuiguard-pg-")- self.addCleanup(scratch.cleanup)- marker = Path(scratch.name) / "pids"- child = r"""-import os, sys, time-from pathlib import Path-marker = Path(sys.argv[1])-g = os.fork()-if g == 0:- time.sleep(60)- os._exit(0)-marker.write_text(f"{os.getpid()}\n{g}\n", encoding="utf-8")-time.sleep(60)-"""- status, _, elapsed, timed_out = tuiguard.run_command(- [sys.executable, "-c", child, str(marker)],- timeout=0.4,- )- self.assertTrue(timed_out)- self.assertEqual(status, 124)- self.assertLess(elapsed, 5.0)- time.sleep(0.1)- pids = [int(x) for x in marker.read_text(encoding="utf-8").split() if x.strip()]- self.assertEqual(len(pids), 2)- for pid in pids:- with self.assertRaises(OSError):- os.kill(pid, 0)-- def test_run_pool_names_still_running_on_parent_deadline(self) -> None:- def hang(script: str, binary: str, timeout: float):- time.sleep(5)- return script, 0, "", 5.0, False-- with mock.patch.object(tuiguard, "run_probe", side_effect=hang):- with mock.patch("builtins.print") as printer:- rc = tuiguard.run_pool(- "/nonexistent/graff",- probes=("test-tui-hover.py",),- jobs=1,- parent_seconds=0.2,- )- self.assertEqual(rc, 1)- joined = " ".join(- str(call.args[0]) for call in printer.call_args_list if call.args- )- self.assertIn("still running: test-tui-hover.py", joined)--[email protected](os.name == "posix", "POSIX clipboard wrappers")-class ClipboardTests(unittest.TestCase):- def clipboard(self, env, command, data=None):- fixture_dir = Path(env["PATH"].split(os.pathsep)[0])- executable = shutil.which(command[0], path=env["PATH"])- self.assertIsNotNone(executable)- self.assertEqual(Path(executable).parent, fixture_dir)- return subprocess.run(- command, input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,- env=env, check=True, timeout=5,- ).stdout-- def test_copy_paste_preserves_exact_bytes(self) -> None:- payload = b"\x00\xffclipboard\r\nUTF-8: \xe2\x98\x83\n\n"- with tuiguard.private_clipboard() as env:- for copy, paste in (- (["pbcopy"], ["pbpaste"]),- (["xclip", "-selection", "clipboard"],- ["xclip", "-selection", "clipboard", "-o"]),- (["pbcopy"], ["xclip", "-selection", "clipboard", "-o"]),- (["xclip", "-selection", "clipboard"], ["pbpaste"]),- ):- for data in (payload, b""):- with self.subTest(copy=copy, paste=paste, data=data):- self.clipboard(env, copy, data)- self.assertEqual(self.clipboard(env, paste), data)-- def test_xclip_quiet_stdin_reads_instead_of_blocking(self) -> None:- # Hover (and any probe that only finds xclip) invokes it with a quiet- # stdin. Treat that as a read; blocking on stdin hung the paint sweep.- with tuiguard.private_clipboard() as env:- self.clipboard(env, ["pbcopy"], b"seeded")- read_end, write_end = os.pipe()- try:- # Keep the writer open: a blocking stdin read cannot complete.- # The subprocess deadline proves bounded completion without- # treating interpreter startup on a busy host as a benchmark.- out = subprocess.run(- ["xclip", "-selection", "clipboard"],- stdin=read_end,- stdout=subprocess.PIPE,- stderr=subprocess.PIPE,- env=env,- check=True,- timeout=2,- ).stdout- self.assertEqual(out, b"seeded")- finally:- os.close(read_end)- os.close(write_end)-- def test_concurrent_contexts_do_not_interfere(self) -> None:- barrier = Barrier(2)-- def roundtrip(payload):- with tuiguard.private_clipboard() as env:- self.clipboard(env, ["pbcopy"], payload)- barrier.wait(timeout=10)- self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)- return env["PATH"]-- with ThreadPoolExecutor(max_workers=2) as pool:- futures = [pool.submit(roundtrip, data) for data in (b"first", b"second")]- paths = [future.result(timeout=20) for future in futures]- self.assertNotEqual(*paths)-- def test_context_cleanup_and_process_path_unchanged(self) -> None:- original_path = os.environ.get("PATH")- for exceptional in (False, True):- with self.subTest(exceptional=exceptional):- try:- with tuiguard.private_clipboard() as env:- fixture_dir = Path(env["PATH"].split(os.pathsep)[0])- self.assertTrue(fixture_dir.is_dir())- self.assertEqual(os.environ.get("PATH"), original_path)- self.clipboard(env, ["pbcopy"], b"cleanup")- if exceptional:- raise RuntimeError("context exit")- except RuntimeError as exc:- self.assertEqual(str(exc), "context exit")- self.assertFalse(fixture_dir.exists())- self.assertEqual(os.environ.get("PATH"), original_path)-- def test_nested_run_probe_environments_remain_separate(self) -> None:- original_path = os.environ.get("PATH")- environments = []-- def run_command(argv, timeout, *, env):- environments.append(env)- payload = Path(argv[1]).name.encode()- self.clipboard(env, ["pbcopy"], payload)- if len(environments) == 1:- tuiguard.run_probe("inner.py", "/nonexistent/graff", timeout)- self.assertIsNot(env, environments[1])- self.assertNotEqual(env["PATH"], environments[1]["PATH"])- self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)- self.assertEqual(os.environ.get("PATH"), original_path)- return 0, "", 0.0, False-- with mock.patch.object(tuiguard, "run_command", side_effect=run_command):- tuiguard.run_probe("outer.py", "/nonexistent/graff", 1.0)- self.assertEqual(len(environments), 2)- for env in environments:- self.assertFalse(Path(env["PATH"].split(os.pathsep)[0]).exists())- self.assertEqual(os.environ.get("PATH"), original_path)-- def test_parallel_run_probe_environments_remain_separate(self) -> None:- original_path = os.environ.get("PATH")- barrier = Barrier(2)-- def run_command(argv, timeout, *, env):- payload = Path(argv[1]).name.encode()- self.clipboard(env, ["pbcopy"], payload)- barrier.wait(timeout=10)- self.assertEqual(self.clipboard(env, ["pbpaste"]), payload)- self.assertEqual(os.environ.get("PATH"), original_path)- return 0, env["PATH"], 0.0, False-- with mock.patch.object(tuiguard, "run_command", side_effect=run_command):- with ThreadPoolExecutor(max_workers=2) as pool:- futures = [- pool.submit(tuiguard.run_probe, name, "/nonexistent/graff", 1.0)- for name in ("first.py", "second.py")- ]- results = [future.result(timeout=20) for future in futures]- self.assertNotEqual(results[0][2], results[1][2])- for result in results:- self.assertFalse(Path(result[2].split(os.pathsep)[0]).exists())- self.assertEqual(os.environ.get("PATH"), original_path)---if __name__ == "__main__":- raise SystemExit(unittest.main())diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 963deeda..d77da252 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -12,10 +12,9 @@],"test_roots": ["src/main.zig",- "src/repl.zig",- "TUI/root.zig"+ "src/repl.zig"],- "test_count_baseline": 3175,+ "test_count_baseline": 3126,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/eval/tier1_tuiguard.py b/scripts/eval/tier1_tuiguard.pydeleted file mode 100755index 61cfe542..00000000--- a/scripts/eval/tier1_tuiguard.py+++ /dev/null@@ -1,214 +0,0 @@-#!/usr/bin/env python3-"""Run the 19 tuiguard PTY probes as a process pool (#641 / #704 / #537).--Each probe owns its own pty/tmp/mock and is independent of the others. The-serial loop in eval-tier1.sh was the dominant post-src wall (2–4 min). A 4–8-worker pool brings that to roughly one long probe (fold-headers / hover).--A wedged child used to keep the pool (and therefore pre-push) alive for-hours: `subprocess.run` and `as_completed` had no deadline (#704). Each-probe now has an explicit timeout that kills its process group, the parent-has a wave-budget deadline, and a timeout names the still-running scripts.--Usage: python3 scripts/eval/tier1_tuiguard.py [path/to/graff]-Exit 0 when every probe passes (or skips itself); 1 if any fails.-GRAFF_TUIGUARD_JOBS overrides the pool size (default: min(8, cpu_count)).-GRAFF_TUIGUARD_PROBE_TIMEOUT overrides every per-probe deadline (seconds).-"""--from __future__ import annotations--import math-import os-import signal-import subprocess-import sys-import time-from concurrent.futures import FIRST_COMPLETED, ThreadPoolExecutor, wait-from pathlib import Path-from clipboard_fixture import private_clipboard--ROOT = Path(__file__).resolve().parents[2]-SCRIPTS = ROOT / "scripts"--PROBES = (- "tui-pty-guard.py",- "test-repl-prompt-reflow.py",- "test-tui-escape-split.py",- "test-tui-selection.py",- "test-tui-typed-events.py",- "test-tui-painter.py",- "test-tui-layout-cache.py",- "test-tui-resize-anchor.py",- "test-tui-chrome-width.py",- "test-tui-scroll-paint.py",- "test-tui-event-pacing.py",- "test-tui-screenstate.py",- "test-tui-fold-headers.py",- "test-tui-stream-markdown.py",- "test-tui-hover.py",- "test-tui-click.py",- "test-tui-scrollbar-osc52.py",- "test-tui-overlay-panels.py",- "test-tui-model-picker.py",-)--# Warm-run walls from a green 4-worker pool: click ~35s, hover ~20s,-# model-picker ~19s. 90s is ~2.5× the longest; the rest stay at 60s.-DEFAULT_TIMEOUT = 60.0-LONG_TIMEOUT = 90.0-PARENT_SLACK = 60.0-PROBE_TIMEOUTS = {- "test-tui-click.py": LONG_TIMEOUT,- "test-tui-hover.py": LONG_TIMEOUT,- "test-tui-fold-headers.py": LONG_TIMEOUT,- "test-tui-model-picker.py": LONG_TIMEOUT,- "test-tui-layout-cache.py": LONG_TIMEOUT,- "test-tui-resize-anchor.py": LONG_TIMEOUT,- "test-tui-overlay-panels.py": LONG_TIMEOUT,- # Sequential ESC/paste gaps plus a live `!sleep 2` bash op (#537).- "test-tui-escape-split.py": LONG_TIMEOUT,-}---def _jobs() -> int:- raw = os.environ.get("GRAFF_TUIGUARD_JOBS", "").strip()- if raw.isdigit() and int(raw) > 0:- return int(raw)- cpus = os.cpu_count() or 4- return max(1, min(8, cpus, len(PROBES)))---def probe_timeout(script: str) -> float:- raw = os.environ.get("GRAFF_TUIGUARD_PROBE_TIMEOUT", "").strip()- if raw:- return float(raw)- return PROBE_TIMEOUTS.get(script, DEFAULT_TIMEOUT)---def parent_budget(jobs: int, names: tuple[str, ...] = PROBES) -> float:- """Worst-case wall: ceil(n/jobs) waves of the longest probe, plus slack."""- workers = max(1, jobs)- waves = math.ceil(len(names) / workers)- longest = max(probe_timeout(n) for n in names) if names else DEFAULT_TIMEOUT- return waves * longest + PARENT_SLACK---def terminate_group(proc: subprocess.Popen[str]) -> None:- if proc.poll() is not None:- return- if os.name == "posix":- try:- os.killpg(proc.pid, signal.SIGKILL)- return- except OSError:- pass- proc.kill()---def run_command(argv: list[str], timeout: float, cwd: Path | None = None, env: dict[str, str] | None = None) -> tuple[int, str, float, bool]:- """Run argv in its own session. On timeout, kill the whole group."""- t0 = time.monotonic()- proc = subprocess.Popen(- argv,- cwd=str(cwd or ROOT),- env=env,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- errors="replace",- start_new_session=True,- )- try:- out, _ = proc.communicate(timeout=timeout)- elapsed = time.monotonic() - t0- return proc.returncode or 0, (out or "").rstrip(), elapsed, False- except subprocess.TimeoutExpired:- terminate_group(proc)- leftover, _ = proc.communicate()- elapsed = time.monotonic() - t0- blob = (leftover or "").rstrip()- return 124, blob, elapsed, True---def run_probe(script: str, binary: str, timeout: float) -> tuple[str, int, str, float, bool]:- # Each probe and its child use a private command-backed clipboard. A pool- # lock alone cannot protect the user's clipboard from another test process.- with private_clipboard() as env:- status, blob, elapsed, timed_out = run_command(- [sys.executable, str(SCRIPTS / script), binary],- timeout,- env=env,- )- return script, status, blob, elapsed, timed_out---def run_pool(- binary: str,- probes: tuple[str, ...] = PROBES,- jobs: int | None = None,- parent_seconds: float | None = None,-) -> int:- workers = jobs if jobs is not None else _jobs()- print(f" {len(probes)} probes, {workers} workers")- failed: list[str] = []- raw_parent = os.environ.get("GRAFF_TUIGUARD_PARENT_TIMEOUT", "").strip()- if parent_seconds is not None:- budget = parent_seconds- elif raw_parent:- budget = float(raw_parent)- else:- budget = parent_budget(workers, probes)- deadline = time.monotonic() + budget- # Threads wait on per-probe Popen; the probe is already a process group.- # A process pool hid child output until join and could not abandon a- # wedged worker without waiting on the context manager (#704).- pool = ThreadPoolExecutor(max_workers=max(1, workers))- try:- futs = {- pool.submit(run_probe, name, binary, probe_timeout(name)): name- for name in probes- }- pending = set(futs)- while pending:- remaining = deadline - time.monotonic()- if remaining <= 0:- stuck = ", ".join(sorted(futs[f] for f in pending))- print(f" tuiguard: parent deadline; still running: {stuck}")- return 1- done, pending = wait(- pending, timeout=min(remaining, 0.25), return_when=FIRST_COMPLETED- )- for fut in done:- script, status, blob, elapsed, timed_out = fut.result()- if blob:- for line in blob.splitlines():- print(f" [{script}] {line}")- print(f" [{script}] {elapsed:.1f}s")- if timed_out:- failed.append(script)- print(f" FAIL {script} (timeout after {elapsed:.1f}s)")- elif status != 0:- failed.append(script)- print(f" FAIL {script} (exit {status})")- else:- print(f" ok {script}")- finally:- pool.shutdown(wait=False, cancel_futures=True)- if failed:- print(f" {len(failed)}/{len(probes)} probes failed: {', '.join(failed)}")- return 1- print(f" all {len(probes)} probes passed")- return 0---def main() -> int:- binary = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")- if not os.path.isfile(binary):- print(f" tuiguard: no binary at {binary}", file=sys.stderr)- return 1- return run_pool(binary)---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/pre-push.sh b/scripts/pre-push.shindex 3f3742ed..bf0bdbe2 100755--- a/scripts/pre-push.sh+++ b/scripts/pre-push.sh@@ -1,7 +1,7 @@#!/usr/bin/env bash# The pre-push gate. Runs tier 1 of the internal eval set (scripts/eval-tier1.sh):# deterministic, offline, no model calls. Warm fmt/reach/sdk is seconds;-# a post-src run rebuilds zig and the tuiguard pool (minutes, see #641).+# a post-src run rebuilds zig and the engine integration probes (minutes).## Install it once: scripts/install-hooks.sh# Skip it once: git push --no-verifydiff --git a/scripts/test-external-tui.py b/scripts/test-external-tui.pynew file mode 100644index 00000000..815e5508--- /dev/null+++ b/scripts/test-external-tui.py@@ -0,0 +1,83 @@+#!/usr/bin/env python3+"""Offline subprocess coverage of graff's external-TUI launcher boundary."""+import json+import os+from pathlib import Path+import shutil+import subprocess+import sys+import tempfile+++def fixture(path, label):+ path.write_text(+ f"#!{sys.executable}\n"+ "import json, os, sys\n"+ f"print(json.dumps({{'label': {label!r}, 'args': sys.argv[1:], "+ "'pid': os.getpid(), 'stdin': sys.stdin.read()}))\n"+ "print('ui-stderr', file=sys.stderr)\n"+ "sys.exit(23)\n"+ )+ path.chmod(0o755)+++def run(binary, args, env):+ proc = subprocess.Popen(+ [str(binary), *args], env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True,+ )+ try:+ out, err = proc.communicate("ui-input", timeout=15)+ except subprocess.TimeoutExpired:+ proc.kill()+ proc.communicate()+ raise+ return proc.pid, proc.returncode, out, err+++def main():+ if os.name == "nt":+ print("external TUI: POSIX exec fixture skipped on Windows")+ return+ with tempfile.TemporaryDirectory(prefix="graff-external-ui-") as tmp:+ root = Path(tmp)+ install, path_dir = root / "install", root / "path"+ install.mkdir()+ path_dir.mkdir()+ binary = install / "graff"+ shutil.copy2(Path(sys.argv[1]).resolve(), binary)+ env = {+ "HOME": str(root), "PATH": str(path_dir),+ "GRAFF_NO_TELEMETRY": "1", "NO_COLOR": "1",+ # A forwarded UI command must run even when engine setup would fail.+ "GRAFF_MAX_MODEL_CALLS": "not-an-engine-invocation",+ }+ sibling = install / "graff-tui"+ fixture(sibling, "sibling")+ fixture(path_dir / "graff-tui", "path")+ args = ["tui", "--help", "--ui-only-flag", "two words", ""]+ for expected in ("sibling", "path"):+ pid, code, out, err = run(binary, args, env)+ assert code == 23, (code, out, err)+ payload = json.loads(out)+ assert payload == {+ "label": expected, "args": args[1:],+ "pid": pid, "stdin": "ui-input",+ }, payload+ assert err == "ui-stderr\n", err+ if expected == "sibling":+ sibling.unlink()+ (path_dir / "graff-tui").unlink()+ _, code, out, err = run(binary, ["tui"], env)+ assert code != 0 and "graff-tui is not installed" in err, (code, out, err)+ assert "No files were downloaded" in err, err+ assert not (root / ".graff").exists()+ fixture(sibling, "not-a-prompt")+ env.pop("GRAFF_MAX_MODEL_CALLS")+ _, code, out, err = run(binary, ["-p", "tui", "--help"], env)+ assert code == 0 and "not-a-prompt" not in out, (code, out, err)+ print("external TUI: sibling precedence, PATH fallback, argv/stdio/exec status, missing install, and prompt escape passed")+++if __name__ == "__main__":+ main()diff --git a/scripts/test-tui-chrome-width.py b/scripts/test-tui-chrome-width.pydeleted file mode 100755index 11debbb9..00000000--- a/scripts/test-tui-chrome-width.py+++ /dev/null@@ -1,210 +0,0 @@-#!/usr/bin/env python3-"""Live proof that animated chrome is exactly one terminal column.--grok-build's discipline: every animated glyph — spinner frames, status dots,-accent bars, chevrons, selection bars — draws in ONE cell, so the label or timer-beside it never steps sideways while the animation ticks. TUI/glyphs.zig pins-that for the frame sets; this probe pins it for the pixels, against the real-binary under a pty.-- 1. boots `graff tui --yolo` in a scratch cwd with an EMPTY MCP config,- 2. starts a long `!sleep` so the PENDING row is live with no model call,- 3. reads the repaints of that one row out of the diff stream,- 4. asserts at least four distinct animation frames went by,- 5. asserts the label kept the SAME column in every one of them,- 6. asserts the animated cell itself is East-Asian-Neutral/Narrow — one column- in every terminal, including one that draws ambiguous glyphs double-width.--Usage: python3 scripts/test-tui-chrome-width.py [path/to/graff]-Exit 0 = pass. Skips (exit 0, notice) when the binary is absent or there is no-pty here.-"""-import os-import re-import sys-import tempfile-import time-import unicodedata-from pty_cleanup import close_pty--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-LABEL = "running" # the pending label bgop.zig pushes for `!cmd`-ROWS, COLS = 30, 100-WATCH_S = 5.0-MIN_FRAMES = 4---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read would hang- # the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0 and the TUI clamps to its floor.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-chrome-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- try:- os.write(fd, b"\x1b") # cancel the background op first- drain(fd, 0.5)- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- close_pty(pid, (fd,))---def plain(b):- """Bytes minus OSC/APC strings and CSI/SGR sequences."""- s = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", b)- s = re.sub(rb"\x1b_[^\x1b]*\x1b\\", b"", s)- s = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", s)- return s.decode(errors="replace")---def cols_of(s):- """Terminal columns of `s` — the measure the TUI's own visibleLen models."""- n = 0- for ch in s:- if unicodedata.combining(ch):- continue- n += 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1- return n---def row_repaints(stream):- """{screen row -> [rendered text, ...]} from run.zig's diff paints.-- Between frames the TUI rewrites only the rows that changed, addressing each- with CSI row;1H — so a row's animation history is exactly the segments that- follow its own address.- """- out = {}- parts = re.split(rb"\x1b\[(\d+);1H", stream)- for i in range(1, len(parts) - 1, 2):- row = int(parts[i])- out.setdefault(row, []).append(plain(parts[i + 1]))- return out---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- try:- boot(fd)- # A long shell command: the pending row is live, with a blinking glyph- # and a static label, and no provider is involved.- os.write(fd, b"!sleep 20\r")- started = drain(fd, 2.0)- if LABEL.encode() not in started:- return f"the pending row never showed {LABEL!r} (no background op)"- stream = drain(fd, WATCH_S)- frames = [- (row, text)- for row, texts in row_repaints(stream).items()- for text in texts- if LABEL in text- ]- if len(frames) < MIN_FRAMES:- return f"only {len(frames)} repaint(s) of the pending row in {WATCH_S}s — the animation is not ticking"- rows = {row for row, _ in frames}- if len(rows) != 1:- return f"the pending row moved between screen rows {sorted(rows)}"- cols = set()- glyphs = set()- for _, text in frames:- at = text.index(LABEL)- cols.add(cols_of(text[:at]))- gutter = text[:at].strip()- if len(gutter) != 1:- return f"the gutter held {gutter!r}, not a single animated glyph"- glyphs.add(gutter)- if len(cols) != 1:- return f"the label sat at columns {sorted(cols)} across {len(frames)} frames — animated chrome is shifting it"- if len(glyphs) < 2:- return f"only one distinct frame {glyphs} — the row is static, not animated"- for g in glyphs:- if cols_of(g) != 1:- return f"frame {g!r} draws {cols_of(g)} columns"- if unicodedata.east_asian_width(g) not in ("N", "Na"):- return (- f"frame {g!r} is East_Asian_Width "- f"{unicodedata.east_asian_width(g)} — two columns in an ambiguous-wide terminal"- )- print(- f" ✓ chrome width: {len(frames)} frames, {sorted(glyphs)} each 1 col, "- f"label fixed at column {cols.pop()}"- )- return None- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-chrome-width: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-chrome-width: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ chrome width: {err}")- return 1- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-click.py b/scripts/test-tui-click.pydeleted file mode 100755index 0948dca6..00000000--- a/scripts/test-tui-click.py+++ /dev/null@@ -1,376 +0,0 @@-#!/usr/bin/env python3-"""Live proof that a SINGLE click does something.--Hover, the wheel, drag-copy and the scroll thumb all shipped before this; the-press itself still only focused the composer, toggled a fold, or dismissed-whatever overlay was up. Every list on screen looked clickable and was not.-This probe drives the real binary under a pty, renders its output into a-VIRTUAL SCREEN (scripts/ptyharness.py) and reads CELLS back, so each assertion-is about what a terminal would actually show:-- 1. click-vs-drag a press and a release on the SAME cell with no motion in- between paints no inverse-video band and copies nothing —- a click is not a one-cell selection — while the SAME press- with motion in it does paint one,- 2. gutter seek a press on the last column jumps the viewport toward that- position, and never anchors a selection there,- 3. gutter drag holding the button and moving down the track walks the- viewport continuously, still without a band,- 4. list rows a click on an overlay row moves the highlight to it, a- second click on that row confirms it like Enter, and a- click on the backdrop below the panel dismisses it,- 5. slash menu a click on the highlighted completion row runs it.--The tool fold's own click lives in scripts/test-tui-hover.py, which already-runs a real tool loop and asserts a single click expands the group and a double-click is one net toggle.--Nothing here needs a model: `!cmd` lines run in-session, so the transcript is-known exactly and nothing streams while the mouse is moving.--Usage: python3 scripts/test-tui-click.py [path/to/graff]-Exit 0 = pass, or a skip when there is no pty.-"""--from __future__ import annotations--import os-import re-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--from ptyharness import PtyHarness # noqa: E402--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-COLS, ROWS = 100, 30-THUMB = "❚" # glyphs.scroll_thumb-MARK = "CLICKMARK_QX"-BAND = b"\x1b[7m" # the drag-selection band's inverse video-OSC52 = re.compile(rb"\x1b\]52;c;([A-Za-z0-9+/=]*)\x07")-WHEEL_UP = b"\x1b[<64;40;10M"-WHEEL_DOWN = b"\x1b[<65;40;10M"---# ----------------------------------------------------------------- helpers---def sgr(btn, col, row, press=True):- return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()---def click(h, col, row, settle=0.45):- """A CLICK: press and release on one cell, with nothing in between."""- h.inject_keys(sgr(0, col, row))- h.pump(0.12)- h.inject_keys(sgr(0, col, row, press=False))- h.pump(settle)---def thumb_rows(h):- return [y for y in range(ROWS) if h.cell(COLS - 1, y).ch == THUMB]---def fill(h, blocks=9):- for tag in range(blocks):- body = "%s filler %d-%d padded out so the transcript outruns the viewport"- lines = "".join((body % (MARK, tag, k)) + r"\n" for k in range(4))- h.inject_keys((r"!printf '" + lines + r"'" + "\r").encode())- h.pump(0.9)- h.pump(1.2)---def workspace():- ws = tempfile.mkdtemp(prefix="tui-click-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w", encoding="utf-8") as fh:- fh.write('{"mcpServers": {}}')- env = {- "GRAFF_MCP_CONFIG": empty,- "GRAFF_LEARN_AUTO": "off",- "GRAFF_NO_TELEMETRY": "1",- }- for name in list(os.environ):- if (name.startswith("GRAFF_") or name == "NO_COLOR") and name not in env:- env[name] = None- return ws, env---# ------------------------------------------------------------------ checks---def check_click_is_not_drag(h):- """(1) A motionless press+release selects nothing and copies nothing."""- rows = [i for i, ln in enumerate(h.screen_lines()) if MARK in ln]- if len(rows) < 2:- return f"no {MARK} rows to click on\n{h.screen_contents()}"- seen = len(h.raw)- click(h, 8, rows[1] + 1, settle=1.2)- after = bytes(h.raw[seen:])- if BAND in after:- return "a motionless click painted a selection band"- if OSC52.search(after):- return "a motionless click wrote the clipboard"- if "copied" in h.screen_contents():- return "a motionless click claimed it copied something"- # ...and the control: the SAME press, moved, is a selection.- seen = len(h.raw)- h.inject_keys(sgr(0, 8, rows[0] + 1))- h.pump(0.2)- h.inject_keys(sgr(32, 60, rows[1] + 1))- h.pump(0.5)- if BAND not in bytes(h.raw[seen:]):- return "a press that MOVED painted no band — the control never engaged"- h.inject_keys(sgr(0, 60, rows[1] + 1, press=False))- h.pump(0.8)- h.inject_keys(b"\x1b") # drop the band before anything else runs- h.pump(0.4)- return None---def track(h):- """The gutter's first and last row, calibrated off the thumb's extremes."""- for _ in range(60):- h.inject_keys(WHEEL_UP)- h.pump(0.02)- h.pump(0.8)- top = thumb_rows(h)- if not top:- return None, "scrolling to the top raised no thumb"- for _ in range(80):- h.inject_keys(WHEEL_DOWN)- h.pump(0.02)- h.pump(0.8)- bottom = thumb_rows(h)- if not bottom:- return None, "the thumb vanished before the tail was reached"- return (top[0], bottom[-1]), None---def to_tail(h):- for _ in range(80):- h.inject_keys(WHEEL_DOWN)- h.pump(0.02)- h.pump(0.8)---def check_gutter_seek(h, first, last):- """(2) A press on the track jumps the viewport, and anchors no band.-- Both directions start from the far end, so neither assertion can pass- because the viewport happened to already be where it was aimed."""- to_tail(h)- at_tail = thumb_rows(h)- if not at_tail or at_tail[-1] != last:- return f"the wheel did not park the viewport at the tail: {at_tail}"- seen = len(h.raw)- click(h, COLS, first + 1, settle=0.9)- if BAND in bytes(h.raw[seen:]):- return "a press on the gutter anchored a selection band"- rows = thumb_rows(h)- if not rows:- return "the gutter disappeared after a press on its own track"- if rows[0] != first:- return f"a press on the top of the track left the thumb at {rows[0]}, wanted {first}"- if f"{MARK} filler 0-0" not in h.screen_contents():- return f"the top of the track did not show the top of the transcript\n{h.screen_contents()}"- click(h, COLS, last + 1, settle=0.9)- rows = thumb_rows(h)- if not rows or rows[-1] != last:- return f"a press on the bottom of the track left the thumb at {rows[-1:]}, wanted {last}"- if f"{MARK} filler 8-3" not in h.screen_contents():- return "the bottom of the track did not show the tail of the transcript"- return None---def check_gutter_drag(h, first, last):- """(3) Holding the button and moving walks the viewport, band-free."""- to_tail(h)- seen = len(h.raw)- h.inject_keys(sgr(0, COLS, first + 1))- h.pump(0.3)- started = thumb_rows(h)- if not started or started[0] != first:- return f"the drag's opening press did not take the thumb to the top: {started}"- walked = [started[:1]]- step = first- while step < last:- step += max(1, (last - first) // 5)- h.inject_keys(sgr(32, COLS, min(step, last) + 1))- h.pump(0.25)- rows = thumb_rows(h)- if not rows:- return "the gutter vanished mid-drag"- walked.append(rows[:1])- h.inject_keys(sgr(0, COLS, last + 1, press=False))- h.pump(0.6)- if BAND in bytes(h.raw[seen:]):- return "a gutter drag painted a selection band"- tops = [w[0] for w in walked]- if tops != sorted(tops):- return f"the drag did not walk the thumb monotonically down: {tops}"- if tops[-1] <= tops[0]:- return f"the drag never moved the thumb: {tops}"- return None---def unwall(line):- """A panel body row with its side walls taken off."""- s = line.strip()- if s.startswith("\u2502"):- s = s[1:]- if s.endswith("\u2502"):- s = s[:-1]- return s---def panel_rows(h, title):- """(row, text) of every body row of the open panel named `title`.-- The name lives in the panel's TOP EDGE (`\u256d\u2500 Theme \u2500\u2500\u256e`), not in a body- row of its own, so the header is found on the border and the rows are the- walled lines under it, up to the closing edge.- """- lines = h.screen_lines()- head = next(- (i for i, ln in enumerate(lines) if ln.lstrip().startswith("\u256d") and title in ln),- None,- )- if head is None:- return None- out = []- for i in range(head + 1, ROWS):- raw = lines[i].strip()- if raw.startswith("\u2570"): # the closing edge ends the panel- break- if not raw.startswith("\u2502"):- break- text = unwall(lines[i]).strip()- if not text:- continue- if text.startswith("\u203a"):- text = text[1:].strip()- # The "\u2026 N below" window marker is chrome, not a pickable row.- if text.startswith("\u2026"):- continue- out.append((i, text.split(" (current)")[0].strip()))- return out---def check_list_rows(h):- """(4) Select, confirm, dismiss — the three things a panel owes a click."""- h.inject_keys(b"/theme\r")- h.pump(1.0)- rows = panel_rows(h, "Theme")- if not rows or len(rows) < 3:- return f"the theme panel did not open\n{h.screen_contents()}"- row, label = rows[2]- click(h, 4, row + 1, settle=0.7)- if panel_rows(h, "Theme") is None:- return "the first click on a row closed the panel instead of selecting"- marked = [ln for ln in h.screen_lines() if "›" in ln and label in ln]- if not marked:- return f"the first click did not move the highlight onto {label!r}"- click(h, 4, row + 1, settle=0.9)- if panel_rows(h, "Theme") is not None:- return "the second click on the highlighted row did not confirm it"- if label not in h.screen_contents():- return f"confirming did not report the picked row {label!r}"- # ...and the backdrop dismisses it, like Esc. The panel DOCKS to the- # composer, so the empty band is ABOVE it, not below.- h.inject_keys(b"/theme\r")- h.pump(1.0)- rows = panel_rows(h, "Theme")- if not rows:- return "the theme panel did not reopen"- top = rows[0][0] - 1 # the panel's top edge- above = top - 2- if above < 1:- return f"no backdrop above the panel to click (top edge at {top})"- click(h, 4, above + 1, settle=0.8)- if panel_rows(h, "Theme") is not None:- return "a click on the backdrop above the panel left it open"- return None---def check_slash_row(h):- """(5) The completion menu's highlighted row runs on a click."""- h.inject_keys(b"/theme")- h.pump(0.8)- lines = h.screen_lines()- hit = next((i for i, ln in enumerate(lines) if "›" in ln and "/theme" in ln), None)- if hit is None:- return f"the completion menu never offered /theme\n{h.screen_contents()}"- click(h, 4, hit + 1, settle=1.0)- if panel_rows(h, "Theme") is None:- return "a click on the highlighted completion row did not run it"- h.inject_keys(b"\x1b")- h.pump(0.4)- return None---# --------------------------------------------------------------------- run---def run():- ws, env = workspace()- h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=ws, env=env)- try:- if not h.wait_for_boot():- return f"the session never reached the alt screen\n{h.screen_contents()}"- fill(h)- err = check_click_is_not_drag(h)- if err:- return err- bounds, err = track(h)- if err:- return err- first, last = bounds- if last - first < 4:- return f"the gutter track is too short to aim at: rows {first}..{last}"- err = check_gutter_seek(h, first, last)- if err:- return err- err = check_gutter_drag(h, first, last)- if err:- return err- err = check_list_rows(h)- if err:- return err- return check_slash_row(h)- finally:- h.close()---def main():- if not os.path.exists(BIN):- print(f"tui-click: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-click: no pty support here — skipping")- return 0- started = time.time()- try:- err = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-click: pty unavailable ({e}) — skipping")- return 0- if err:- print(f" ✗ click: {err}")- return 1- print(- " ✓ click: a motionless click selects nothing, the gutter seeks and drags without a "- f"band, a list row selects then confirms, the backdrop dismisses ({time.time() - started:.0f}s)"- )- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-escape-split.py b/scripts/test-tui-escape-split.pydeleted file mode 100755index 9360871a..00000000--- a/scripts/test-tui-escape-split.py+++ /dev/null@@ -1,240 +0,0 @@-#!/usr/bin/env python3-"""Real-PTY regression for #537's split Escape ambiguity, fully offline.--A 70ms exact-CSI gap and 250ms X10 gap stay terminal sequences inside the main-grace. A live bash op gives a possible paste-start Escape the bounded one-second-window, while controls in the completed paste stay inert. A dropped non-lone-head accumulates a secondary late read without losing its exact framing.-Ambiguous CSI/SS3 and byte-read prose stay text. Every split is verified in the-TUI trajectory log as a separate input read.-"""--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 ptyharness import PtyHarness, PtyTimeout # noqa: E402--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-MARKER = "ESC_SPLIT_DRAFT"-DROPPED_BODY = "DROPPED_HEAD_OK"-DROPPED_CONTROL = "DROPPED_CONTROL_SAFE"-LATE_BODY = "LATE_BODY_OK"-LATE_CONTROL = "LATE_CONTROL_SAFE"-LIVE_BASH = "LIVE_BASH_ESCAPE_SAFE"-HUMAN_TEXT = "HUMAN:[Alice] [Home] [Down] 3u apples"---def trajectory_reads(tmp: str) -> list[bytes]:- path = os.path.join(tmp, ".graff", "tui-traj.jsonl")- try:- with open(path, encoding="utf-8") as fh:- rows = [json.loads(line) for line in fh if line.strip()]- except (FileNotFoundError, json.JSONDecodeError):- return []- return [bytes.fromhex(row["hex"]) for row in rows if "hex" in row]---class ReadEvidence:- """Synchronize on traj.note: the next write was its own TUI input batch."""-- def __init__(self, pty: PtyHarness, tmp: str):- self.pty = pty- self.tmp = tmp- self.seen = len(trajectory_reads(tmp))-- def inject(self, data: bytes, gap: float = 0.0) -> None:- self.pty.inject_keys(data)- deadline = time.monotonic() + 3.0- while time.monotonic() < deadline:- self.pty.pump(0.02)- reads = trajectory_reads(self.tmp)- if len(reads) <= self.seen:- continue- fresh = reads[self.seen :]- self.seen = len(reads)- if fresh != [data]:- raise PtyTimeout(- f"expected one TUI read {data.hex()}, got {[part.hex() for part in fresh]}"- )- if gap:- self.pty.pump(gap)- return- raise PtyTimeout(f"TUI trajectory never recorded input read {data.hex()}")---def workspace(tmp: str) -> dict[str, str | None]:- empty = os.path.join(tmp, "empty-mcp.json")- with open(empty, "w", encoding="utf-8") as fh:- json.dump({"mcpServers": {}}, 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)- env = {- name: None- for name in os.environ- if name.startswith(("GRAFF_", "CODEX_"))- or name.endswith("_API_KEY")- }- env.update(- {- "HOME": tmp,- "GRAFF_MCP_CONFIG": empty,- "GRAFF_LEARN_AUTO": "off",- "GRAFF_FLEET": "off",- "GRAFF_NO_TELEMETRY": "1",- # Baked catalog + loopback endpoint: startup and any accidental- # request have no real-provider or remote catalog route.- "LMSTUDIO_API_KEY": "offline-escape-split-probe",- }- )- return env---def run() -> str | None:- with tempfile.TemporaryDirectory(prefix="tui-escape-split-") as tmp:- with PtyHarness(- [BIN, "tui", "--yolo", "--model", "lmstudio", "--no-telemetry"],- cols=90,- rows=28,- cwd=tmp,- env=workspace(tmp),- ) as pty:- if not pty.wait_for_boot():- return "TUI did not enter the alternate screen"- reads = ReadEvidence(pty, tmp)- reads.inject(MARKER.encode())- pty.wait_for_text(MARKER, timeout=5.0)-- # Arm two-Escape clear. Trajectory synchronization proves the- # split head and body reached different TUI input batches.- reads.inject(b"\x1b", 0.80)- reads.inject(b"\x1b", 0.070)- reads.inject(b"[A", 0.4)- if MARKER not in pty.screen_contents():- return "70ms ESC/arrow split dispatched a phantom Escape\n" + pty.screen_contents()-- # X10 is CSI M plus three raw bytes; protect the reported 250ms gap.- reads.inject(b"\x1b", 0.80)- reads.inject(b"\x1b", 0.250)- reads.inject(b"[M !!", 0.4)- screen = pty.screen_contents()- if MARKER not in screen or "[M !!" in screen:- return "250ms ESC/X10 split escaped or typed its body\n" + screen-- # A lone ESC during real background work may still be paste start.- # At 800ms the live op must remain uncancelled; explicit C0 controls- # in the completed paste are then inert.- reads.inject(b"\x15", 0.2)- reads.inject(b"!sleep 2\n", 0.2)- pty.wait_for_text("$ sleep 2", timeout=5.0)- reads.inject(b"\x1b", 0.80)- reads.inject(b"[200~" + LIVE_BASH.encode() + b"\x11\x03\nSAFE")- pty.wait_for_text(LIVE_BASH, timeout=5.0, settle=0.2)- reads.inject(b"\x1b[201~\x15", 1.3)- if "interrupted" in pty.screen_contents().lower():- return "800ms possible paste-start Escape cancelled live bash\n" + pty.screen_contents()-- # A non-lone paste head is dropped after ~500ms, then its tail- # lands as TWO reads inside the one-second dropped-head interval.- # SGR and X10 wheels share the reconstructed marker's production- # batch and stay paste-inert.- reads.inject(b"\x1b[20", 1.10)- reads.inject(b"0", 0.10)- dropped = (- b"~"- + DROPPED_BODY.encode()- + 2 * b"\x1b[<64;4;4M"- + 2 * b"\x1b[M`$$"- + b"\x11\x03\n"- + DROPPED_CONTROL.encode()- )- reads.inject(dropped)- pty.wait_for_text(DROPPED_CONTROL, timeout=5.0, settle=0.2)- screen = pty.screen_contents()- if "0~" in screen or DROPPED_BODY not in screen:- return "dropped paste head lost its exact 401-999ms framing\n" + screen-- # A genuine Escape remains different: its exact head expires at- # 400ms, while narrow self-identifying recovery remains for 1s.- reads.inject(b"\x1b[201~\x05\x15", 0.25)- reads.inject(b"\x1b", 0.80)- paste = b"[200~" + LATE_BODY.encode() + b"\x11\x03\n" + LATE_CONTROL.encode()- reads.inject(paste)- pty.wait_for_text(LATE_CONTROL, timeout=5.0, settle=0.2)- screen = pty.screen_contents()- if "[200~" in screen:- return "late paste marker typed after the carried ESC expired"- if LATE_BODY not in screen:- return "late paste payload was not retained"-- # Beyond carry, exact CSI/SS3 is prose-ambiguous and remains text.- reads.inject(b"\x1b[201~\x05\x15", 0.25)- reads.inject(b"EXACT:\x1b", 0.80)- reads.inject(b"[D")- reads.inject(b" \x1b", 0.80)- reads.inject(b"OD", 0.2)- pty.wait_for_text("EXACT:[D OD", timeout=5.0, settle=0.2)-- # Parameterized kitty remains distinguishable and is a real Left.- reads.inject(b"\x05\x15", 0.25)- reads.inject(b"ab\x1b", 0.80)- reads.inject(b"[57350;1u")- reads.inject(b"X\x05")- pty.wait_for_text("aXb", timeout=5.0, settle=0.2)-- # BEL makes the OSC body self-identifying even with same-read text.- reads.inject(b"\x15", 0.4)- reads.inject(b"OSC:\x1b", 0.80)- reads.inject(b"]11;rgb:f6/f6/f6\x07_OK")- pty.wait_for_text("OSC:_OK", timeout=5.0, settle=0.2)- if "]11;rgb:" in pty.screen_contents():- return "terminated late OSC tail typed into the composer"-- # Give every ambiguous spelling its own expired genuine Escape,- # and force every prose byte through a distinct read with >=50ms.- reads.inject(b"\x05\x15", 0.4)- reads.inject(b"HUMAN:")- tokens = (b"[Alice]", b"[Home]", b"[Down]", b"3u apples")- for index, token in enumerate(tokens):- reads.inject(b"\x1b", 0.80)- for byte in token:- reads.inject(bytes([byte]), 0.050)- if index + 1 < len(tokens):- reads.inject(b" ")- pty.wait_for_text(HUMAN_TEXT, timeout=5.0, settle=0.2)- if HUMAN_TEXT not in pty.screen_contents():- return "50ms byte-read human text after genuine Escape was changed"-- if pty.quit() is None:- return "TUI did not quit cleanly"- return None---def main() -> int:- if not os.path.isfile(BIN):- print(f"tui-escape-split: {BIN} not built — skipping")- return 0- try:- err = run()- except PtyTimeout as exc:- err = str(exc)- except OSError as exc:- print(f"tui-escape-split: pty unavailable ({exc}) — skipping")- return 0- if err:- print(f"tui-escape-split: FAIL: {err}")- return 1- print("tui-escape-split: ok")- return 0---if __name__ == "__main__":- raise SystemExit(main())diff --git a/scripts/test-tui-event-pacing.py b/scripts/test-tui-event-pacing.pydeleted file mode 100644index 8f96c40e..00000000--- a/scripts/test-tui-event-pacing.py+++ /dev/null@@ -1,440 +0,0 @@-#!/usr/bin/env python3-"""Live proof that a trackpad wheel storm is COALESCED and BUDGETED, not queued.--Trackpad momentum fires wheel reports far faster than a frame can be composed-and painted. Serviced one report per frame the loop queues work it can never-catch up on: the scroll trails the fingers and then jumps. The fix is in-run.zig's tick (drain everything, fold consecutive wheel reports into one-delta, one frame per tick, at most one per ~8ms while input keeps arriving).--Everything else about that lives in unit tests over pure functions. This probe-puts a real `graff tui` under a pty and measures the loop from OUTSIDE, using-the local-only counters GRAFF_TUI_PAINT_STATS=1 prints on exit:-- A. baseline The completed paints before the storm in that same session,- counted from synchronized-update boundaries on the wire.- Independently booted sessions can have different paint totals.- B. storm 500 SGR wheel reports pushed in under a second. The paint- count above its own baseline must be BUDGETED (~one per- 8ms of storm), not one per report, and the 500 reports must- collapse into a handful of applied scroll deltas.- C. responsive A marker typed straight after the storm must echo within- 50ms — keys are never starved behind the flood.- D. no lag tax A SINGLE wheel report on an idle session must paint at once.- The budget exists for storms; it may not tax one flick.--Usage: python3 scripts/test-tui-event-pacing.py [path/to/graff]-Exit 0 = pass (or a skip when no pty is available).-"""-import os-import re-import select-import sys-import tempfile-import time-from ptyharness import Screen--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-ROWS, COLS = 30, 100--UP = b"\x1b[<64;20;10M"-DOWN = b"\x1b[<65;20;10M"-FLINGS, PER_FLING = 10, 50-STORM_N = FLINGS * PER_FLING-# How long the PACED storm is spread over — 500 reports in under a second, the-# rate a trackpad fling really sustains.-PACED_S = 0.9--MARK = b"PACEMARK"-ECHO_BUDGET_MS = 50.0-# One report on an idle loop must paint immediately; this is a generous ceiling-# on "immediately" for a loaded CI box, and still an order below a queued loop.-SINGLE_BUDGET_MS = 50.0-# run.zig's pacing.frame_budget_ms. A storm that takes `t` ms may paint about-# t/8 times; the slack absorbs the idle self-heal and a loaded machine.-FRAME_BUDGET_MS = 8.0--STATS = re.compile(rb"tui-paint-stats:((?: \w+=\d+)+)")-PAINT_START = b"\x1b[?2026h"-OUTPUT = bytearray()---def read_output(fd):- chunk = os.read(fd, 65536)- OUTPUT.extend(chunk)- return chunk---def visible_lines():- screen = Screen(ROWS, COLS)- screen.feed(bytes(OUTPUT))- return tuple(int(n) for n in re.findall(r"PACELINE(\d{3})", screen.screen_contents()))---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read would hang- # the probe on exactly the wedged states it exists to catch.- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = read_output(fd)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.monotonic() + BOOT_MAX- while time.monotonic() < end:- out += drain(fd, min(0.1, max(0, end - time.monotonic())))- frame = out.rfind(b"\x1b[2J\x1b[H")- # ADR 0042: the early alt-screen claim precedes engine construction.- if b"\x1b[?2004h" in out and frame >= 0 and b"\x1b[?2026l" in out[frame:]:- return True- return False---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0 and the TUI clamps to its floor.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-pacing-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {- "GRAFF_MCP_CONFIG": empty,- "GRAFF_LEARN_AUTO": "off",- "GRAFF_TUI_PAINT_STATS": "1",- }---def quit_and_stats(pid, fd):- """Escalating quit, then the counters the loop prints after the restore."""- import signal- tail = b""- try:- os.write(fd, b"\x11") # Ctrl+Q- end = time.time() + 4.0- while time.time() < end:- tail += drain(fd, 0.3)- if STATS.search(tail):- break- except OSError:- pass- for sig in (signal.SIGTERM, signal.SIGKILL):- try:- os.kill(pid, sig)- except OSError:- break- time.sleep(0.05)- try:- os.waitpid(pid, 0)- except OSError:- pass- m = STATS.search(tail)- if not m:- return None- out = {}- for pair in m.group(1).split():- k, v = pair.decode().split("=")- out[k] = int(v)- return out---def fill_transcript(fd):- """A transcript tall enough that scrolling always changes the frame — a- storm over an empty screen would compose the same bytes every time and- prove nothing about paints."""- for block in range(5):- first, last = block * 40, block * 40 + 39- args = " ".join(str(i) for i in range(first, last + 1))- os.write(fd, (r"!printf 'PACELINE%03d\n' " + args + "\r").encode())- # Only the output carries the formatted marker. Keep the old 1.6s- # setup budget, but never send another command while this one is busy.- if wait_for(fd, f"PACELINE{last:03d}".encode(), 1.6) is None:- return f"setup block {block} never printed its final output line"- drain(fd, 0.5)- return None---def push_paced(fd, data_units, total_s):- """Deliver reports SPREAD OVER TIME, the way trackpad momentum really- arrives. This is the case a backlog check cannot see: the loop reads each- report the instant it lands, finds nothing queued behind it, and — without- a rate-based budget — paints once per report. Returns (seconds, sent)."""- gap = total_s / len(data_units)- start = time.perf_counter()- sent = 0- os.set_blocking(fd, False)- try:- for i, unit in enumerate(data_units):- target = start + i * gap- while True:- left = target - time.perf_counter()- if left <= 0:- break- # Drain output while waiting: the child's output queue is a few- # KB and a child blocked writing is not a child under storm.- r, _, _ = select.select([fd], [], [], min(left, 0.002))- if r:- try:- read_output(fd)- except (BlockingIOError, OSError):- pass- for _ in range(200):- try:- os.write(fd, unit)- sent += 1- break- except BlockingIOError:- select.select([], [fd], [], 0.002)- except OSError:- return time.perf_counter() - start, sent- finally:- os.set_blocking(fd, True)- return time.perf_counter() - start, sent---def push(fd, data, deadline=5.0):- """Write while reading. The pty's input queue is ~1KB and the child's output- queue is a few KB, so a write-only loop deadlocks against a child that is- painting. The master goes NON-BLOCKING for the burst: select reports the fd- writable when there is *any* room, and a blocking write of a full chunk then- parks in the kernel until the whole chunk fits. Returns (seconds, output)."""- out = b""- i = 0- start = time.time()- os.set_blocking(fd, False)- try:- while i < len(data) and time.time() - start < deadline:- r, wl, _ = select.select([fd], [fd], [], 0.1)- if fd in r:- try:- out += read_output(fd)- except BlockingIOError:- pass- except OSError:- break- if fd in wl:- try:- i += os.write(fd, data[i : i + 512])- except BlockingIOError:- continue- except OSError:- break- finally:- os.set_blocking(fd, True)- return time.time() - start, out---def wait_for(fd, needle, budget_s):- """Seconds until `needle` shows up in the pty output, or None."""- out = b""- start = time.time()- while time.time() - start < budget_s:- r, _, _ = select.select([fd], [], [], 0.005)- if not r:- continue- try:- out += read_output(fd)- except OSError:- break- if needle in out:- return time.time() - start- return None---def session(mode):- """One measured pty session: "burst" or "paced". Returns (stats, err, extras)."""- ws, env = fresh_ws()- OUTPUT.clear()- pid, fd = spawn(ws, env)- extras = {}- stopped = False- try:- if not boot(fd):- return None, "the TUI never completed its first interactive frame", extras- error = fill_transcript(fd)- if error:- return None, error, extras- before = visible_lines()- if not before or before[-1] != 199:- return None, "the setup transcript is not following its final output line", extras- extras[f"{mode}_baseline"] = OUTPUT.count(PAINT_START)- reports = []- for f in range(FLINGS):- reports += [UP if f % 2 == 0 else DOWN] * PER_FLING- # Equal opposing flings can legitimately coalesce to no movement.- # Keep 500 reports, with a net upward displacement and room for one flick.- reports[-1] = UP- if mode == "burst":- secs, _ = push(fd, b"".join(reports))- extras["burst_s"] = secs- if secs >= 1.0:- return None, f"the {STORM_N}-report burst took {secs:.2f}s, not <1s", extras- elif mode == "paced":- secs, sent = push_paced(fd, reports, PACED_S)- extras["paced_s"] = secs- if sent < STORM_N:- return None, f"only {sent}/{STORM_N} paced reports were written", extras- if mode in ("burst", "paced"):- # C: typing straight after the storm, while the loop is still- # settling. A key must never sit behind the flood.- os.write(fd, MARK)- echo = wait_for(fd, MARK, ECHO_BUDGET_MS / 1000.0 * 4)- extras["echo_ms"] = None if echo is None else echo * 1000.0- os.write(fd, b"\x15") # Ctrl+U: leave the composer empty again- drain(fd, 0.4)- after = visible_lines()- extras[f"{mode}_moved"] = bool(after and after[0] < before[0])- # D: one lone report on a quiet loop must paint on the spot — the- # budget exists for storms and may not tax a single flick.- t0 = time.time()- os.write(fd, UP)- r, _, _ = select.select([fd], [], [], SINGLE_BUDGET_MS / 1000.0 * 4)- extras["single_ms"] = (time.time() - t0) * 1000.0 if r else None- if r:- read_output(fd)- drain(fd, 0.4)- stats = quit_and_stats(pid, fd)- stopped = True- if stats and stats["paints"] != OUTPUT.count(PAINT_START):- return None, "observed paint boundaries do not match the session's paint counter", extras- return stats, None, extras- finally:- if not stopped:- quit_and_stats(pid, fd)- try:- os.close(fd)- except OSError:- pass---def check_storm(name, stats, extras, elapsed_s, min_batches, max_batches):- seen = stats["wheel_events"]- batches = stats["wheel_batches"]- extra_paints = stats["paints"] - extras[f"{name}_baseline"]- extras[f"{name}_events"] = seen- extras[f"{name}_deltas"] = batches- extras[f"{name}_paints"] = extra_paints- if seen < STORM_N * 0.95:- return f"{name}: only {seen}/{STORM_N} wheel reports reached the loop — lost, not paced"- # A storm that moved nothing would make "few paints" the trivial answer.- if not extras[f"{name}_moved"]:- return f"{name}: the storm did not move the visible transcript toward older lines"- # THE claim: paints are budgeted by the clock, not by the report count.- ceiling = max(20, int(elapsed_s * 1000.0 / FRAME_BUDGET_MS) + 25)- if extra_paints > ceiling:- return f"{name}: {seen} reports cost {extra_paints} paints over {elapsed_s * 1000:.0f}ms (the ~8ms budget allows ~{ceiling})"- if not (min_batches <= batches <= max_batches):- return f"{name}: {seen} reports applied as {batches} scroll deltas (expected {min_batches}..{max_batches})"- if extras.get("echo_ms") is None:- return f"{name}: a marker typed after the storm never echoed — typing was starved"- if extras["echo_ms"] > ECHO_BUDGET_MS:- return f"{name}: the marker took {extras['echo_ms']:.1f}ms to echo (budget {ECHO_BUDGET_MS:.0f}ms)"- if extras.get("single_ms") is None:- return f"{name}: a single wheel report on an idle loop never painted"- if extras["single_ms"] > SINGLE_BUDGET_MS:- return f"{name}: one report on an idle loop took {extras['single_ms']:.1f}ms — the budget is taxing single ticks"- return None---def run():- extras = {}- # A: all at once. The tty hands the loop a backlog, so the reports fold- # into a handful of deltas and cost a handful of paints.- stats, err, ex = session("burst")- extras.update(ex)- if err:- return err, extras- if stats is None:- return "the burst session printed no tui-paint-stats line", extras- # +1 delta for the single-flick probe at the end of the session.- err = check_storm("burst", stats, extras, extras["burst_s"], 2, 40)- if err:- return err, extras-- # B: spread over ~1s, the way momentum actually arrives. Nothing is ever- # queued behind a report here, so ONLY the rate-based budget bounds the- # paints — this is the case that fails if the budget looks at the backlog.- stats, err, ex = session("paced")- extras.update(ex)- if err:- return err, extras- if stats is None:- return "the paced session printed no tui-paint-stats line", extras- # Nothing to fold when the reports arrive further apart than the loop takes- # to service one, so the delta count is not the claim here — the paint count- # is. The window only rules out an implementation that dropped reports.- return check_storm("paced", stats, extras, extras["paced_s"], 2, STORM_N + 5), extras---def main():- if not os.path.exists(BIN):- print(f"tui-pacing: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-pacing: no pty support here — skipping")- return 0- extras = None- try:- err, extras = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-pacing: pty unavailable ({e}) — skipping")- return 0- if extras:- print(- " "- + " ".join(- f"{k}={v:.1f}" if isinstance(v, float) else f"{k}={v}"- for k, v in extras.items()- if v is not None- )- )- if err:- print(f" ✗ pacing: {err}")- return 1- print(- f" ✓ pacing: {extras['burst_events']} reports at once → "- f"{extras['burst_deltas']} deltas / {extras['burst_paints']} paints; "- f"{extras['paced_events']} over {extras['paced_s'] * 1000:.0f}ms → "- f"{extras['paced_paints']} paints (~{FRAME_BUDGET_MS:.0f}ms budget, not one per report); "- f"typing echoed in {extras['echo_ms']:.1f}ms, one flick painted in {extras['single_ms']:.1f}ms"- )- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-fold-headers.py b/scripts/test-tui-fold-headers.pydeleted file mode 100644index d07831ce..00000000--- a/scripts/test-tui-fold-headers.py+++ /dev/null@@ -1,272 +0,0 @@-#!/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):- # grok-build outer_hpad (2/2): the settle field is the inner row. The- # gutter cells stay on the canvas and must not count as a second bg.- left, right = 2, 2- return {pty.cell(x, y).bg for x in range(left, max(left + 1, pty.cols - right))}---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-hover.py b/scripts/test-tui-hover.pydeleted file mode 100644index a5ad7e39..00000000--- a/scripts/test-tui-hover.py+++ /dev/null@@ -1,422 +0,0 @@-#!/usr/bin/env python3-"""Live proof that a clickable row LOOKS clickable before it is clicked.--?1003h motion reports already reach the loop (they drive the image-chip-preview); until TUI/hover.zig every one that missed a chip was dropped. This-probe drives the real binary under a pty, renders its output into a VIRTUAL-SCREEN (scripts/ptyharness.py) and reads CELLS back — glyph plus the pen that-wrote it — so every assertion is about what a terminal would actually show:-- 1. a real tool loop against the codex mock (no network, no model) leaves one- COLLAPSED fold header on screen (its › disclosure chevron is always- there — foldhdr.zig owns it, hover does not reveal it),- 2. a motion report over that row repaints it: its cells take the theme's- hover background, one step off the canvas, and its TEXT is untouched —- hover changes a row's colour and never its glyphs,- 3. the row BELOW it is untouched — hover highlights a row, not a region,- 4. moving the pointer away restores the row cell for cell,- 5. a SINGLE click still expands the group, exactly as before,- 6. a DOUBLE click is ONE net toggle rather than an expand followed by a- collapse — which is what two presses used to add up to,- 7. and a hover SWEEP across 30 rows costs a bounded number of paints, read- off the loop's own counters (GRAFF_TUI_PAINT_STATS=1), not one per row.--Usage: python3 scripts/test-tui-hover.py [path/to/graff]-Exit 0 = pass, or a skip when there is no pty.-"""--from __future__ import annotations--import json-import os-import re-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--from ptyharness import PtyHarness # noqa: E402--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-ROWS, COLS = 34, 100-ANSWER_MAX = 30.0-NOTE_BODY = "hover-probe payload"-FINAL_REPLY = "HOVER_OK the run is done"--TOOL_MARK = "◆" # ◆ glyphs.tool — the marks on the OPEN card's rows-EXPAND_MARK = "›" # › glyphs.expand — the closed header's disclosure chevron-CHEV_OPEN = "⌄" # U+2304 — the open header's chevron (foldhdr.zig)-HEADER = "Read 1 file" # the settled verb header for this session's one read-STATS = re.compile(r"tui-paint-stats:((?: \w+=\d+)+)")--# TUI/theme_tint.zig: one step per channel, in the direction the canvas's own-# polarity asks for. Kept here as a NUMBER so a change to the constant that was-# never meant to be visible shows up as a failure rather than as a silent-# repaint of nothing.-HOVER_STEP = 16---# ----------------------------------------------------------------- helpers---def motion(h, x, y):- """A pure ?1003h motion report — button 35, no button held. 1-based."""- h.inject_keys(f"\x1b[<35;{x};{y}M".encode())---def click(h, x, y, settle=0.6):- h.inject_keys(f"\x1b[<0;{x};{y}M".encode())- h.pump(0.15)- h.inject_keys(f"\x1b[<0;{x};{y}m".encode())- h.pump(settle)---def row_cells(h, y):- return [h.cell(x, y) for x in range(h.cols)]---def row_bgs(h, y):- """The distinct backgrounds on row `y`, ignoring cells nothing painted."""- return {c.bg for c in row_cells(h, y) if c.bg is not None}---def summary_row(h):- """The FOLDED header's row, or None while the group is open (⌄) or gone."""- for i, ln in enumerate(h.screen_lines()):- if HEADER in ln:- return None if CHEV_OPEN in ln else i- return None---def stepped(base, tint):- """`tint` is `base` moved one step, saturating, in one consistent direction."""- if not (isinstance(base, tuple) and isinstance(tint, tuple)):- return False- deltas = [t - b for b, t in zip(base, tint)]- if all(d == 0 for d in deltas):- return False- if not (all(d >= 0 for d in deltas) or all(d <= 0 for d in deltas)):- return False- return all(abs(d) <= HOVER_STEP for d in deltas)---# ------------------------------------------------------------- mock session---def message_item(text, item_id):- return {- "type": "message",- "id": item_id,- "status": "completed",- "role": "assistant",- "content": [{"type": "output_text", "text": text, "annotations": []}],- }---def response_events(item, response_id):- 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):- if request.ordinal == 1:- return response_events(- {- "type": "function_call",- "id": "fc_hover_read",- "call_id": "call_hover_read",- "name": "read_file",- "arguments": json.dumps({"path": "note.txt"}),- "status": "completed",- },- "resp_hover_read",- )- return response_events(message_item(FINAL_REPLY, "msg_hover_done"), "resp_hover_done")---def workspace(tmp, port):- with open(os.path.join(tmp, "note.txt"), "w", encoding="utf-8") as fh:- fh.write(NOTE_BODY)- 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": "hover-mock", "account_id": "acct-hover"}}, 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",- }- # Everything else the developer's shell might be exporting is UNSET (None),- # not blanked: an empty string is a value graff would read.- 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 wait_for_resting_row(h, timeout=3.0, clock=None):- """Observe the end of the completion flash, not a guessed wall delay.-- The untouched row below supplies the canvas color independently of the- header. A uniform flash must not become the baseline either. Require a- short stable interval and retain a bounded failure for permanent styling.- """- clock = clock or time.monotonic- deadline = clock() + timeout- previous, stable_since = None, None- detail = "no folded tool summary on screen"- while clock() < deadline:- y = summary_row(h)- if y is not None and y + 1 < h.rows:- colors, canvas = row_bgs(h, y), row_bgs(h, y + 1)- detail = f"resting row backgrounds {colors}, canvas {canvas}"- frame = (y, tuple(c.tuple() for c in row_cells(h, y)))- if len(canvas) == 1 and colors == canvas and EXPAND_MARK in h.screen_lines()[y]:- if frame != previous:- previous, stable_since = frame, clock()- elif clock() - stable_since >= 0.1:- return y- else:- previous, stable_since = None, None- else:- previous, stable_since = None, None- h.pump(min(0.05, max(0, deadline - clock())))- raise TimeoutError(f"hover baseline did not settle within {timeout:g}s: {detail}")---def check_affordance(h):- """(2)-(6): the tint, the mark swap, the neighbour, and the two gestures."""- try:- y = wait_for_resting_row(h)- except TimeoutError as error:- return f"{error}\n{h.screen_contents()}"- line = h.screen_lines()[y]- if EXPAND_MARK not in line:- return f"the folded header carries no disclosure chevron: {line!r}"- base_bgs = row_bgs(h, y)- if len(base_bgs) != 1:- return f"the resting row has {len(base_bgs)} backgrounds, expected the canvas alone: {base_bgs}"- base = next(iter(base_bgs))- below = summary_row(h) + 1- below_before = [c.tuple() for c in row_cells(h, below)]-- # (2) the pointer lands on the row.- motion(h, 5, y + 1)- h.pump(0.6)- warm = row_bgs(h, y)- if len(warm) != 1:- return f"the hovered row has {len(warm)} backgrounds: {warm}"- tint = next(iter(warm))- if not stepped(base, tint):- return f"the hovered row's background is not one step off the canvas: {base} -> {tint}"- hot_line = h.screen_lines()[y]- if hot_line != line:- return f"hover edited the row's text:\n was {line!r}\n now {hot_line!r}"-- # (3) a row is a row: the one under it is untouched, cell for cell.- if [c.tuple() for c in row_cells(h, below)] != below_before:- return "hovering one row repainted its neighbour too"-- # (4) leaving restores it.- motion(h, 5, h.rows - 1)- h.pump(0.6)- cold = row_bgs(h, y)- if cold != {base}:- return f"the row kept its hover background after the pointer left: {cold}"- if h.screen_lines()[y] != line:- return f"the row did not come back as it was:\n was {line!r}\n now {h.screen_lines()[y]!r}"-- # (5) a single click still expands the group. Unchanged behaviour.- click(h, 5, y + 1)- if summary_row(h) is not None:- return "a single click no longer expands the tool group"- # ...and a single click on the open card folds it again.- head = next((i for i, ln in enumerate(h.screen_lines()) if TOOL_MARK in ln and "read" in ln), None)- if head is None:- return f"the expanded card has no field-backed head\n{h.screen_contents()}"- click(h, 5, head + 1)- if summary_row(h) is None:- return "a single click on the open card no longer folds it"-- # (6) a double click is ONE net toggle: it opens and STAYS open. Two- # presses used to expand and then collapse, so the gesture looked inert.- y = summary_row(h)- h.inject_keys(f"\x1b[<0;5;{y + 1}M".encode())- h.pump(0.05)- h.inject_keys(f"\x1b[<0;5;{y + 1}m".encode())- h.pump(0.05)- h.inject_keys(f"\x1b[<0;5;{y + 1}M".encode())- h.pump(0.05)- h.inject_keys(f"\x1b[<0;5;{y + 1}m".encode())- h.pump(0.8)- if summary_row(h) is not None:- return "a double click expanded the group and collapsed it again — no net effect"- return None---# ------------------------------------------------------------ storm session---def storm_paints(tmp):- """(7) A hover sweep rides the frame budget. Returns (err, control, swept)."""- empty_mcp = os.path.join(tmp, "empty-mcp.json")- with open(empty_mcp, "w", encoding="utf-8") as fh:- fh.write('{"mcpServers": {}}')- env = {- "GRAFF_MCP_CONFIG": empty_mcp,- "GRAFF_LEARN_AUTO": "off",- "GRAFF_NO_TELEMETRY": "1",- "GRAFF_TUI_PAINT_STATS": "1",- }-- def one(sweeps):- h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=tmp, env=env)- try:- if not h.wait_for_boot():- raise RuntimeError(f"the storm session never reached the alt screen\n{h.screen_contents()}")- # A transcript worth hovering: without one every row is blank and a- # sweep would compose the same bytes and prove nothing.- h.inject_keys(b"!seq 1 60\r")- h.pump(2.0)- for _ in range(sweeps):- for y in range(2, 32):- motion(h, 5, y)- h.pump(0.004)- h.pump(0.6)- h.inject_keys(b"\x11") # Ctrl+Q — the counters print after restore- h.pump(2.0)- m = STATS.search(h.raw.decode(errors="replace"))- return None if not m else {- k: int(v) for k, v in (p.split("=") for p in m.group(1).split())- }- finally:- h.close()-- control = one(0)- if control is None:- return "the control session printed no tui-paint-stats line", None, None- swept = one(4)- if swept is None:- return "the sweep session printed no tui-paint-stats line", None, None- extra = swept["paints"] - control["paints"]- rows_swept = 4 * 30- if extra < 2:- return f"the sweep repainted {extra} times — it never highlighted anything", control, swept- if swept["events"] - control["events"] < rows_swept * 0.9:- return (- f"only {swept['events'] - control['events']}/{rows_swept} motion reports reached the loop",- control,- swept,- )- # THE claim: bounded by the frame budget, not by the report count. A loop- # that painted per report would land at ~120 here.- if extra > rows_swept // 2:- return (- f"{rows_swept} hover reports cost {extra} paints — the frame budget is not folding them",- control,- swept,- )- # ...and the budget is what bounded it: frames the loop WANTED and deferred.- if swept["skipped"] <= control["skipped"]:- return (- "the sweep deferred no frames at all — the paint count is low for some other reason",- control,- swept,- )- return None, control, swept---# --------------------------------------------------------------------- run---def run():- from codex_ws_mock import CodexMock-- mock = CodexMock(events_for_request=events)- port = mock.start()- try:- with tempfile.TemporaryDirectory(prefix="graff-hover-") as tmp:- h = PtyHarness(- [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"],- cols=COLS,- rows=ROWS,- cwd=tmp,- env=workspace(tmp, port),- )- try:- h.wait_for_boot()- h.inject_keys(b"read note.txt then report\r")- h.wait_for_text("HOVER_OK", timeout=ANSWER_MAX, settle=1.0)- err = check_affordance(h)- if err:- return err, None- finally:- h.close()- with tempfile.TemporaryDirectory(prefix="graff-hover-storm-") as tmp:- err, control, swept = storm_paints(tmp)- if err:- return err, None- return None, (control, swept)- finally:- mock.stop()---def main():- if not os.path.exists(BIN):- print(f"tui-hover: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-hover: no pty support here — skipping")- return 0- started = time.time()- try:- err, stats = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err, stats = "pty EIO — the graff process died mid-check", None- else:- print(f"tui-hover: pty unavailable ({e}) — skipping")- return 0- if err:- print(f" ✗ hover: {err}")- return 1- control, swept = stats- print(- f" ✓ hover: the row tints under the pointer with its text untouched, restores on leave, "- f"single click expands and a double click is one net toggle; "- f"120 hover reports cost {swept['paints'] - control['paints']} paints "- f"({time.time() - started:.0f}s)"- )- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-layout-cache.py b/scripts/test-tui-layout-cache.pydeleted file mode 100755index 49a89964..00000000--- a/scripts/test-tui-layout-cache.py+++ /dev/null@@ -1,265 +0,0 @@-#!/usr/bin/env python3-"""Live proof: scrolling is a viewport SLICE of one layout, not a re-layout.--TUI/layout_cache.zig keeps every history entry's wrapped display lines and a-prefix sum of where each block starts in virtual-Y, so a wheel tick is a binary-search plus a screenful of slices. The failure modes a cache introduces are all-visible on screen: a stale block, a line served from the wrong offset, a-duplicated or skipped row after a width change. This probe drives the real-binary under a pty and reads the screen back:-- 1. boots `graff tui --yolo` in a scratch cwd with an EMPTY MCP config,- 2. fills the transcript with numbered marker lines printed through a printf- FORMAT, so the echoed command line never contains a marker itself (the- sticky header pins the last prompt, and a marker there is chrome),- 3. scrolls up one line at a time and asserts, on every frame, that the- markers on screen are a CONTIGUOUS ASCENDING run — no gap, no repeat —- and that the run walks strictly backwards through the transcript,- 4. changes width mid-scroll and asserts the same thing at the new width,- which is the cold-rebuild path,- 5. reports the wall clock per scroll step for scale.--Usage: python3 scripts/test-tui-layout-cache.py [path/to/graff]- (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.-"""-import os-import re-import sys-import tempfile-import time--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-ROWS, COLS = 30, 100-BLOCKS = 8-PER_BLOCK = 10-MARK = re.compile(r"LC(\d{4})")-STEPS = 20---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read here would- # hang the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0; the TUI would clamp to its 40x12- # floor and every row index below would be measured against the wrong frame.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-layout-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- import signal- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 3.0)- except OSError:- pass- for sig in (signal.SIGTERM, signal.SIGKILL):- try:- os.kill(pid, sig)- except OSError:- pass- try:- os.waitpid(pid, 0)- except OSError:- pass---def parse(stream):- """Screen rows, in order, out of the last FULL repaint in `stream`.-- Between repaints the TUI rewrites only the rows that changed, addressing- each with CSI row;1H — stripping those out of a diff stream gives row- indices that are plausible and wrong. Any resize invalidates run.zig's diff- baseline, so what follows one is a whole frame, top row first.- """- frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(frame) < 2:- return None- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---def frame_at(fd, rows, cols, settle=1.2):- resize(fd, rows, cols)- return parse(drain(fd, settle))---def reread(fd, cols=COLS):- """A full frame at the current width, via a HEIGHT-only jiggle."""- resize(fd, ROWS - 1, cols)- drain(fd, 0.4)- return frame_at(fd, ROWS, cols)---def marks(rows):- """Marker numbers in screen order, ignoring the sticky-header chrome row."""- out = []- for ln in rows or []:- if "❯" in ln: # ❯ — the pinned prompt, not the transcript- continue- for m in MARK.finditer(ln):- out.append(int(m.group(1)))- return out---def contiguous(seq):- return all(b == a + 1 for a, b in zip(seq, seq[1:]))---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- try:- boot(fd)- # Marker lines via a printf FORMAT: the echoed command carries "LC%04d"- # and bare integers, never a marker, so a hit on screen is transcript.- # `!cmd` is a single background op: send the next only after this block's- # last marker has been painted, or the rest bounce as "engine still running".- for b in range(BLOCKS):- last = b * PER_BLOCK + PER_BLOCK - 1- needle = f"LC{last:04d}".encode()- args = " ".join(str(b * PER_BLOCK + k) for k in range(PER_BLOCK))- cmd = (- r"!printf 'LC%04d filler text long enough that it rewraps at "- r"every width this probe drives\n' " + args- )- os.write(fd, (cmd + "\r").encode())- got = b""- end = time.time() + 8.0- while time.time() < end:- got += drain(fd, 0.3)- if needle in got:- break- else:- return f"block {b} never painted LC{last:04d} (no `!` output)"--- total = BLOCKS * PER_BLOCK- seen = marks(reread(fd))- if not seen:- return "the transcript never showed a marker line (no `!` output)"- if not contiguous(seen):- return f"the bottom frame is not a contiguous slice: {seen}"- if seen[-1] != total - 1:- return f"follow mode is not at the bottom: last marker {seen[-1]} of {total - 1}"-- # --- scroll up one line at a time ------------------------------------ started = time.time()- top = seen[0]- walked = 0- for step in range(STEPS):- os.write(fd, b"\x0b") # Ctrl+K: one line towards older text- drain(fd, 0.2)- cur = marks(reread(fd))- if not cur:- return f"step {step} showed no markers at all"- if not contiguous(cur):- return f"step {step} served a non-contiguous slice: {cur}"- if cur[0] > top:- return f"step {step} scrolled the wrong way: {cur[0]} > {top}"- walked += top - cur[0]- top = cur[0]- if walked == 0:- return "scrolling up never moved the viewport"- per_step = (time.time() - started) / STEPS-- # --- width change mid-scroll: the cold rebuild ----------------------- for w in (72, 58, 92, COLS):- rows = frame_at(fd, ROWS, w)- if rows is None:- return f"no full repaint at width {w}"- cur = marks(rows)- if not cur:- return f"width {w} lost the transcript entirely"- if not contiguous(cur):- return f"width {w} served a non-contiguous slice: {cur}"-- # --- back to the bottom ---------------------------------------------- for _ in range(8):- os.write(fd, b"\x1b[6~") # PgDn: back towards the live tail- drain(fd, 0.2)- drain(fd, 1.0)- cur = marks(reread(fd))- if not contiguous(cur) or cur[-1] != total - 1:- return f"scrolling back down did not return to the tail: {cur}"-- print(- f" {total} marker lines, walked {walked} rows up and back, "- f"{per_step * 1000:.0f} ms per probe step (resize/settle waits, "- f"not frame time — see scripts/bench-tui-layout.sh for that)"- )- return None- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-layout-cache: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-layout-cache: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ layout-cache: {err}")- return 1- print(" ✓ layout-cache: every frame was a contiguous slice of one layout")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-model-picker.py b/scripts/test-tui-model-picker.pydeleted file mode 100755index 1bcb5d9f..00000000--- a/scripts/test-tui-model-picker.py+++ /dev/null@@ -1,340 +0,0 @@-#!/usr/bin/env python3-"""Live proof that the TUI model picker says WHO serves each model (#560).--The report: "i cant see who the provider is when i use /models ... being codex-(free) vs codegraff(paid) vs openai(paid) is mad diff". The picker rendered-bare model names, so one model served by three providers drew three identical-rows and the pick resolved by name.--This probe drives the real binary under a pty, renders its output into a-VIRTUAL SCREEN (scripts/ptyharness.py) and reads CELLS back, so every assertion-is about what a terminal would actually show:-- 1. opening the picker shows a provider AND a cost badge on every row, with- the three classes from the report visible at once — a plan seat (codex),- a credits seat (codegraff) and a metered api seat (openai),- 2. one model name that several providers serve appears once per provider and- those rows are distinguishable,- 3. typing a PROVIDER name filters to that provider's seats,- 4. a provider with no credential still has rows, marked with — rather than- dropped, and- 5. Esc closes the picker without switching anything.--Usage: python3 scripts/test-tui-model-picker.py [path/to/graff]-Exit 0 = pass, or a skip when there is no pty.-"""--from __future__ import annotations--import faulthandler-import json-import os-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--from ptyharness import PtyHarness # noqa: E402--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-ROWS, COLS = 40, 110---def workspace(tmp):- 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": "picker-mock", "account_id": "acct-picker"}}, 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,- # One metered key and one gateway credential, so all three cost- # classes the user named are on screen at the same time.- "OPENAI_API_KEY": "sk-picker-test",- "CODEGRAFF_API_KEY": "cg_sk_picker_test",- "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---BADGES = ("plan", "credits", "api", "local")---def unwall(line):- """A panel body row with its side walls taken off.-- The picker is framed now (panel.zig), so every catalog row arrives as- `\u2502 name provider \u00b7 badge \u2502` and the walls have to come off before the- row can be read as a seat.- """- s = line.strip()- if s.startswith("\u2502"):- s = s[1:]- if s.endswith("\u2502"):- s = s[:-1]- return s---def picker_rows(h):- """Screen lines that are catalog rows: `name provider \u00b7 badge [marker]`."""- out = []- for ln in h.screen_lines():- s = unwall(ln).rstrip()- if not (s.startswith(" ") or s.startswith("\u203a ") or s.startswith(" \u203a ")):- continue- head, sep, tail = s.partition(" \u00b7 ")- if not sep or not head.strip():- continue- words = tail.split()- if not words or words[0] not in BADGES:- continue- out.append(s)- return out---def open_picker(h, query=b""):- h.inject_keys(b"/models\r")- h.pump(1.0)- if query:- for ch in query:- h.inject_keys(bytes([ch]))- h.pump(0.9)- return picker_rows(h)---def close_picker(h):- h.inject_keys(b"\x1b")- # Escape decoding and the next paint are asynchronous under runner load.- # Wait for the visible transition, with a hard bound, rather than one frame.- deadline = time.monotonic() + 2.0- while "Model \u203a" in h.screen_contents() and time.monotonic() < deadline:- h.pump(0.05)---def sgr(btn, col, row, press=True):- return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()---def click(h, col, row, settle=0.5):- """A CLICK: press and release on one cell, with nothing in between."""- h.inject_keys(sgr(0, col, row))- h.pump(0.12)- h.inject_keys(sgr(0, col, row, press=False))- h.pump(settle)---def row_index_of(h, want_name, want_provider):- """0-based screen row of the picker row for one exact seat."""- for i, ln in enumerate(h.screen_lines()):- s = unwall(ln).rstrip()- if not (s.startswith(" ") or s.startswith("\u203a ") or s.startswith(" \u203a ")):- continue- if " \u00b7 " not in s:- continue- name, provider, _ = seat(s)- if name == want_name and provider == want_provider:- return i- return None---def highlighted_provider(h, name):- """Which provider's row for `name` currently carries the \u203a highlight."""- for ln in h.screen_lines():- s = unwall(ln).rstrip()- if not s.startswith("\u203a ") or " \u00b7 " not in s:- continue- got_name, provider, _ = seat(s.split(" (current)")[0])- if got_name == name:- return provider- return None---def current_provider_of(h, name):- """Which provider's row wears `(current)`, for the seats named `name`."""- for ln in h.screen_lines():- s = unwall(ln).rstrip()- if "(current)" not in s or " \u00b7 " not in s:- continue- got_name, provider, _ = seat(s.split(" (current)")[0])- if got_name == name:- return provider- return None---def seat(row):- """(name, provider, badge) off a rendered picker row."""- head, _, tail = row.partition(" \u00b7 ")- parts = head.split()- provider = parts[-1] if parts else ""- name = " ".join(parts[:-1]).lstrip("\u203a ").strip()- badge = tail.split()[0] if tail.split() else ""- return name, provider, badge---def check(h):- # (1) the resting picker: every row names a provider and a cost class.- rows = open_picker(h)- if "Model \u203a" not in h.screen_contents():- return f"the picker never opened\n{h.screen_contents()}"- if len(rows) < 8:- return f"only {len(rows)} picker rows carry a provider column\n{h.screen_contents()}"- for row in rows:- name, provider, badge = seat(row)- if not name or not provider:- return f"a picker row has no provider column: {row!r}"- if badge not in ("plan", "credits", "api", "local"):- return f"a picker row has no cost badge: {row!r}"-- # Signed-in plan seats sit above credits / api on the empty list (ADR 0017).- badges_in_order = [seat(r)[2] for r in rows]- if "plan" in badges_in_order and "credits" in badges_in_order:- if badges_in_order.index("plan") > badges_in_order.index("credits"):- return f"signed-in plan seats sit below credits\n{chr(10).join(rows)}"-- # (4) a provider with no credential keeps its rows, marked rather than gone.- # Keyed plan/credits now fill the first page, so filter to a keyless- # provider instead of requiring an em-dash on the resting window.- close_picker(h)- bare = open_picker(h, b"anthropic")- if not any(r.rstrip().endswith("\u2014") for r in bare):- return f"no keyless row is marked\n{chr(10).join(bare)}"- # (2) THE report: one model, three providers, three different bills, and- # three rows a human can tell apart.- close_picker(h)- shared = open_picker(h, b"gpt-5.5")- seats = [seat(r) for r in shared if seat(r)[0] == "gpt-5.5"]- providers = {p for _, p, _ in seats}- badges = {p: b for _, p, b in seats}- for want, cost in (("codex", "plan"), ("openai", "api"), ("codegraff", "credits")):- if want not in providers:- return f"gpt-5.5 has no {want} row — providers seen: {providers}\n{chr(10).join(shared)}"- if badges[want] != cost:- return f"gpt-5.5 on {want} is badged {badges[want]!r}, expected {cost!r}"- if len({r.strip() for r in shared}) != len(shared):- return f"two gpt-5.5 rows render identically:\n{chr(10).join(shared)}"-- # (3) typing a PROVIDER filters to it. codegraff appears in no model name,- # so every surviving row must be a codegraff seat.- close_picker(h)- gateway = open_picker(h, b"codegraff")- if not gateway:- return f"typing 'codegraff' emptied the picker\n{h.screen_contents()}"- off = [r for r in gateway if seat(r)[1] != "codegraff" or seat(r)[2] != "credits"]- if off:- return f"the codegraff filter left foreign rows: {off}"-- # ...and the plan seats are reachable the same way.- close_picker(h)- plan = open_picker(h, b"codex")- if not any(seat(r)[1] == "codex" and seat(r)[2] == "plan" for r in plan):- return f"typing 'codex' surfaced no plan seat\n{chr(10).join(plan)}"-- # (5) Esc closes it without switching anything.- close_picker(h)- if "Model \u203a" in h.screen_contents():- return "Esc did not close the picker"-- # (6) THE end-to-end claim, and the one place the two lanes meet: CLICK a- # same-named seat on a DIFFERENT provider and prove the switch actually- # landed on the provider that was clicked. `(current)` is decided by name- # AND provider, so which row wears it is the observable answer - and by- # name alone all three gpt-5.5 rows would have claimed it.- shared = open_picker(h, b"gpt-5.5")- seats = [seat(r) for r in shared if seat(r)[0] == "gpt-5.5"]- was = current_provider_of(h, "gpt-5.5")- # Deliberately NOT the row that already carries the highlight: on that one a- # single click confirms (the picker's one rule), and this check is about a- # click that has to MOVE the highlight before it can confirm.- lit = highlighted_provider(h, "gpt-5.5")- target = next((p for _, p, _ in seats if p != lit and p != was), None)- if target is None:- return f"no unlit gpt-5.5 provider to switch to (lit={lit}, current={was}, seen={seats})"- row = row_index_of(h, "gpt-5.5", target)- if row is None:- return f"the {target} row for gpt-5.5 is not on screen\n{h.screen_contents()}"- # Select, then confirm - the picker's one rule for a click.- click(h, 4, row + 1)- if "Model \u203a" not in h.screen_contents():- return "the first click closed the picker instead of selecting the row"- if highlighted_provider(h, "gpt-5.5") != target:- return (- f"the first click did not move the highlight onto {target!r} "- f"(it is on {highlighted_provider(h, 'gpt-5.5')!r})\n{h.screen_contents()}"- )- click(h, 4, row + 1, settle=1.0)- if "Model \u203a" in h.screen_contents():- return "the second click on the highlighted row did not confirm it"-- reopened = open_picker(h, b"gpt-5.5")- now = current_provider_of(h, "gpt-5.5")- if now != target:- return (- f"picked gpt-5.5 on {target!r} but the current seat is {now!r} "- f"(was {was!r})\n{chr(10).join(reopened)}"- )- if sum("(current)" in r for r in reopened) != 1:- return f"more than one gpt-5.5 row claims to be current\n{chr(10).join(reopened)}"- close_picker(h)- return None---def run():- with tempfile.TemporaryDirectory(prefix="graff-picker-") as tmp:- h = PtyHarness([BIN, "tui", "--yolo", "--no-telemetry"], cols=COLS, rows=ROWS, cwd=tmp, env=workspace(tmp))- try:- if not h.wait_for_boot():- return f"the session never reached the alt screen\n{h.screen_contents()}"- return check(h)- finally:- h.close()---def main():- if not os.path.exists(BIN):- print(f"tui-model-picker: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-model-picker: no pty support here — skipping")- return 0- started = time.time()- faulthandler.dump_traceback_later(45)- try:- err = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-model-picker: pty unavailable ({e}) — skipping")- return 0- finally:- faulthandler.cancel_dump_traceback_later()- if err:- print(f" ✗ model-picker: {err}")- return 1- print(- " ✓ model-picker: every row names its provider and cost class "- f"(plan/credits/api), same-named seats are distinguishable, and typing a "- f"provider filters to it ({time.time() - started:.0f}s)"- )- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-overlay-panels.py b/scripts/test-tui-overlay-panels.pydeleted file mode 100755index f445cfeb..00000000--- a/scripts/test-tui-overlay-panels.py+++ /dev/null@@ -1,242 +0,0 @@-#!/usr/bin/env python3-"""Every overlay is a bordered panel, docked to the composer, opened at its top.--grok-build renders a modal as a BLOCK with borders on all four sides and the-title inlaid in the top rule (`─ <bold title> ─`, dashes in the border colour),-with the keys on a dim footer row; its minimal-mode list panels dock to the-prompt instead of floating mid-screen. graff's overlays used to be bare text-hanging at the top of the pager with a field of blank rows between the list and-the caret choosing from it, and a title that spent a content row.--This drives the REAL binary on a virtual screen (scripts/ptyharness.py) and-reads back what a terminal would show, at three widths, for four surfaces:-- 1. /model — a windowed list: framed, tallied in the top rule, docked one- row above the composer, and honest about the rows it is not- showing ("… N below").- 2. / — the completion menu wears the SAME frame as the palette it- mirrors, so one catalogue reached two ways looks like one- thing.- 3. /help — a sheet taller than the screen OPENS AT ITS FIRST ROW (it used- to open at its last: the only part you ever saw was the tail of- the command list) and pages down to the rest.- 4. composer — the standing row that claimed "Image in clipboard" on every- idle frame is gone, and the paste key lives in the footer hint- with the other keys.--Every panel row is checked against the frame width in CELLS, which is the one-thing a raw-byte grep cannot do: a border that measured one column wide would-be chopped by the terminal and slide every row below it.--Usage: python3 scripts/test-tui-overlay-panels.py [path/to/graff]-Exit 0 = pass. Skips (exit 0, notice) when the binary is absent or there is no-pty here.-"""--from __future__ import annotations--import json-import os-import sys-import tempfile--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--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 = 30-WIDTHS = (60, 80, 120)--TL, TR, BL, BR = "╭", "╮", "╰", "╯"-WALL = "│"---def workspace(tmp: str) -> dict:- empty = os.path.join(tmp, "empty-mcp.json")- with open(empty, "w", encoding="utf-8") as fh:- fh.write('{"mcpServers": {}}')- harness = os.path.join(tmp, ".harness")- os.makedirs(harness, exist_ok=True)- with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:- json.dump({"ai_title": False, "skills": {"codedbpro": False}}, fh)- return {- "HOME": tmp,- "GRAFF_MCP_CONFIG": empty,- "GRAFF_LEARN_AUTO": "off",- "GRAFF_NO_TELEMETRY": "1",- "GRAFF_FLEET": "off",- # No request is ever made: the probe only opens overlays. A key is what- # gets the pager past its "no API key" refusal.- "XAI_API_KEY": "xai-overlay-panel-probe",- }---def cells(pty, y: int) -> str:- return pty.screen_lines()[y].rstrip("\n")---def panel_rows(pty, cols: int):- """(top, bottom) screen rows of the LAST panel above the composer, or None.-- The composer is a box too, so the search runs upward from the composer's own- top edge and takes the first complete frame above it.- """- lines = pty.screen_lines()- tops = [y for y, ln in enumerate(lines) if ln.lstrip().startswith(TL)]- bots = [y for y, ln in enumerate(lines) if ln.lstrip().startswith(BL)]- if len(tops) < 2 or len(bots) < 2:- return None- # The composer is the last pair; the overlay panel is the one before it.- return tops[-2], bots[-2]---def check_frame(pty, top: int, bot: int, cols: int, what: str):- """Every row of the box spans exactly `cols` cells and has both walls."""- problems = []- head = cells(pty, top)- tail = cells(pty, bot)- if not head.startswith(TL) or not head.rstrip().endswith(TR):- problems.append(f"{what}: top rule is not a closed edge: {head!r}")- if not tail.startswith(BL) or not tail.rstrip().endswith(BR):- problems.append(f"{what}: bottom rule is not a closed edge: {tail!r}")- for y in range(top, bot + 1):- row = cells(pty, y)- # The harness grid is exactly `cols` wide; a row that ends before the- # last column means the frame did not reach the wall.- painted = len(row.rstrip())- if painted != cols:- problems.append(f"{what}: row {y} paints {painted} of {cols} cells: {row!r}")- if top < y < bot and not (row.startswith(WALL) and row[cols - 1] == WALL):- problems.append(f"{what}: row {y} is missing a wall: {row!r}")- return problems---def clear(pty):- pty.inject_keys(b"\x1b")- pty.pump(0.3)- pty.inject_keys(b"\x1b")- pty.pump(0.3)- for _ in range(80):- pty.inject_keys(b"\x7f")- pty.pump(0.4)---def run_width(cols: int) -> list[str]:- bad: list[str] = []- with tempfile.TemporaryDirectory(prefix="graff-overlay-panel-") as tmp:- env = workspace(tmp)- argv = [BIN, "tui", "--yolo", "--no-telemetry"]- with PtyHarness(argv, cols=cols, rows=ROWS, cwd=tmp, env=env) as pty:- if not pty.wait_for_boot():- return [f"w={cols}: the TUI never took the alt screen"]-- # 1. the model picker ------------------------------------------- pty.inject_keys(b"/model\r")- try:- pty.wait_for_text("Model", timeout=8.0)- except PtyTimeout as exc:- return [f"w={cols}: /model never opened: {exc}"]- pty.pump(0.5)- found = panel_rows(pty, cols)- if found is None:- bad.append(f"w={cols}: /model drew no bordered panel at all")- else:- top, bot = found- bad += check_frame(pty, top, bot, cols, f"w={cols} /model")- head = cells(pty, top)- if "Model" not in head:- bad.append(f"w={cols}: the panel's top rule does not name it: {head!r}")- tail = cells(pty, bot)- if "Esc" not in tail:- bad.append(f"w={cols}: the panel's bottom rule lost its keys: {tail!r}")- # DOCKED: the panel's bottom rule sits directly on the composer.- composer_top = None- for y in range(bot + 1, ROWS):- # Composer is grok-build-inset (outer_hpad_left=2); the- # overlay panel above it stays full-width and still docks.- if cells(pty, y).lstrip().startswith(TL):- composer_top = y- break- if composer_top != bot + 1:- bad.append(- f"w={cols}: the picker floats — its last row is {bot}, "- f"the composer starts at {composer_top}"- )- # WINDOWED: 14 rows of a longer list must say so.- body = "\n".join(cells(pty, y) for y in range(top, bot + 1))- if "below" not in body and "above" not in body:- bad.append(f"w={cols}: a windowed list gave no more-below marker")- clear(pty)-- # 2. the completion menu wears the same frame -------------------- pty.inject_keys(b"/")- pty.pump(0.6)- found = panel_rows(pty, cols)- if found is None:- bad.append(f"w={cols}: the slash menu drew no bordered panel")- else:- top, bot = found- bad += check_frame(pty, top, bot, cols, f"w={cols} slash")- if "Commands" not in cells(pty, top):- bad.append(f"w={cols}: the slash menu's rule does not name it")- clear(pty)-- # 3. a sheet opens at its FIRST row ------------------------------ pty.inject_keys(b"\x18") # Ctrl+X- try:- pty.wait_for_text("Shortcuts", timeout=8.0)- except PtyTimeout as exc:- return bad + [f"w={cols}: /help never opened: {exc}"]- pty.pump(0.4)- screen = pty.screen_contents()- if "prompt / scrollback" not in screen:- bad.append(f"w={cols}: the shortcut sheet did not open at its first row")- if "/vim-mode" in screen:- bad.append(f"w={cols}: the shortcut sheet opened at its LAST row")- pty.inject_keys(b"\x1b[6~" * 4) # PgDn- pty.pump(0.6)- if "/vim-mode" not in pty.screen_contents():- bad.append(f"w={cols}: paging the shortcut sheet never reached its end")- clear(pty)-- # 4. the composer tells no story about a clipboard it never read- pty.pump(0.4)- screen = pty.screen_contents()- if "Image in clipboard" in screen:- bad.append(f"w={cols}: the composer still claims an image is in the clipboard")- if cols >= 80 and "Ctrl+V:image" not in screen:- bad.append(f"w={cols}: the paste key is not in the footer hint")- # ...and the hint never runs off the edge or ends mid-word.- hint = cells(pty, ROWS - 1)- if len(hint.rstrip()) > cols:- bad.append(f"w={cols}: the footer hint overruns the screen: {hint!r}")- for cut in ("Shift+Enter:newl", "Shift+Tab:mo", "Ctrl+V:im"):- if cut in hint and not hint.rstrip().endswith(("mode", "image", "help", "newline")):- bad.append(f"w={cols}: the footer hint is clipped mid-key: {hint!r}")- pty.quit()- return bad---def main() -> int:- if not os.path.exists(BIN):- print(f"notice: {BIN} not built — skipping")- return 0- try:- import pty as _pty # noqa: F401- except Exception:- print("notice: no pty support here — skipping")- return 0- problems: list[str] = []- for cols in WIDTHS:- problems += run_width(cols)- if problems:- for p in problems:- print(f"FAIL {p}")- return 1- print(f"ok: overlay panels are framed, docked and top-opened at {WIDTHS}")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-painter.py b/scripts/test-tui-painter.pydeleted file mode 100755index 3ba5bb8f..00000000--- a/scripts/test-tui-painter.py+++ /dev/null@@ -1,343 +0,0 @@-#!/usr/bin/env python3-"""Live proof that the fullscreen TUI's screen only ever shows the CURRENT frame.--Everything else in the painter's battery is a unit test over bytes. This probe-puts a real `graff tui` under a pty, plays the two abuses that historically left-stale cells behind, and then reads the SCREEN back — not the byte stream — by-replaying the pty output through a small terminal model (CUP / EL / ED / CR-LF /-text, autowrap off, exactly the subset run.zig emits).-- A. resize-storm TIOCSWINSZ is driven repeatedly mid-stream, then the session- is made to paint DIFFS again (typing, a second shell line).- The modelled screen must then equal a forced full repaint of- the same frame, cell for cell: any cell where they differ is- a cell still showing an older frame.- B. glyph-torture The transcript is filled with the glyphs a terminal is most- likely to measure differently from us (VS16 promotions, CJK,- emoji, box drawing) and the composer — whose border row is- exactly `cols` wide — is retyped over it. Same screen-state- equality check. This is the case where trusting visibleLen- on a "full" row used to strand the last cell.- C. self-heal With no input at all, the loop must still rewrite the screen- on its own clock, and the screen must still equal the frame.--Usage: python3 scripts/test-tui-painter.py [path/to/graff] (default zig-out/bin/graff)-Exit 0 = pass (or a skip when no pty is available).-"""-import os-import re-import sys-import tempfile-import time-import unicodedata--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-ROWS, COLS = 30, 100-# run.zig's heal_interval_ms, plus slack for a loaded machine.-HEAL_MS = 3.0--MARK = "PAINTME"-GLYPHS = "A✓ B✓️ C日本 D\U0001f409 E╭──╮ F ok"---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read would hang- # the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0 and the TUI clamps to its floor.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-paint-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- import signal- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for sig in (signal.SIGKILL,):- try:- os.kill(pid, sig)- except OSError:- pass- try:- os.waitpid(pid, 0)- except OSError:- pass---def cell_width(ch):- if unicodedata.combining(ch) or ch in "︎️":- return 0- if unicodedata.east_asian_width(ch) in ("W", "F"):- return 2- if ord(ch) >= 0x1F300:- return 2- return 1---CSI = re.compile(r"\x1b\[([0-9;?<>]*)([@-~])")---class Screen:- """The subset of a terminal the painter can get wrong: which glyph is in- which cell. Autowrap is off, as run.zig sets it (?7l)."""-- def __init__(self, rows, cols):- self.rows, self.cols = rows, cols- self.cells = [[" "] * cols for _ in range(rows)]- self.r = self.c = 0-- def put(self, ch, w):- if self.r >= self.rows:- return- c = min(self.c, self.cols - 1)- self.cells[self.r][c] = ch- if w == 2 and c + 1 < self.cols:- self.cells[self.r][c + 1] = ""- self.c = min(c + w, self.cols)-- def erase_to_eol(self):- if self.r >= self.rows:- return- for c in range(min(self.c, self.cols - 1), self.cols):- self.cells[self.r][c] = " "-- def clear(self):- self.cells = [[" "] * self.cols for _ in range(self.rows)]- self.r = self.c = 0-- def feed(self, data):- s = data.decode("utf-8", errors="replace")- i = 0- while i < len(s):- ch = s[i]- if ch == "\x1b":- i = self.escape(s, i)- continue- if ch == "\r":- self.c = 0- i += 1- continue- if ch == "\n":- self.r += 1- i += 1- continue- w = cell_width(ch)- if w:- self.put(ch, w)- i += 1- return self-- def escape(self, s, i):- rest = s[i:]- m = CSI.match(rest)- if m:- self.csi(m.group(1), m.group(2))- return i + m.end()- if len(rest) > 1 and rest[1] in "]P_^X":- bel = rest.find("\x07")- st = rest.find("\x1b\\")- ends = [e for e in (bel + 1 if bel >= 0 else -1, st + 2 if st >= 0 else -1) if e > 0]- return i + (min(ends) if ends else len(rest))- return i + 2-- def csi(self, params, final):- if final == "H":- parts = params.split(";")- row = int(parts[0]) if parts and parts[0].isdigit() else 1- col = int(parts[1]) if len(parts) > 1 and parts[1].isdigit() else 1- self.r, self.c = max(row - 1, 0), max(col - 1, 0)- elif final == "J" and params in ("2", "3"):- self.clear()- elif final == "K" and params in ("", "0"):- self.erase_to_eol()-- def text_rows(self):- return ["".join(row).rstrip() for row in self.cells]-- def diff(self, other):- for r, (a, b) in enumerate(zip(self.text_rows(), other.text_rows())):- if a != b:- return f"row {r}: screen has {a!r} but the frame is {b!r}"- return None---def ground_truth(fd, rows, cols):- """A forced full repaint, replayed onto a fresh screen: what the terminal- WOULD show if it were redrawn from nothing right now. A resize invalidates- run.zig's diff baseline, so the tail after the last ED is one whole frame."""- resize(fd, rows - 1, cols)- drain(fd, 0.5)- resize(fd, rows, cols)- stream = drain(fd, 1.5)- if b"\x1b[2J\x1b[H" not in stream:- return None- tail = stream.rsplit(b"\x1b[2J\x1b[H", 1)[1]- truth = Screen(rows, cols)- truth.clear()- return truth.feed(tail)---def check_a_resize_storm(fd, screen):- for r, c in ((24, 80), (40, 120), (20, 60), (34, 110), (ROWS, COLS)):- resize(fd, r, c)- screen.feed(drain(fd, 0.25))- screen.feed(drain(fd, 0.8))- # Make the session paint DIFFS again on top of the post-storm baseline —- # a full repaint right at the end would prove nothing about residue.- os.write(fd, f"typed after the storm {MARK}".encode())- screen.feed(drain(fd, 0.8))- os.write(fd, b"\x15") # Ctrl+U: clear the composer, shrinking that row- screen.feed(drain(fd, 0.8))- truth = ground_truth(fd, ROWS, COLS)- if truth is None:- return "A: no full repaint came back to compare against"- screen.feed(b"") # keep the modelled screen and the truth in the same frame- return screen.diff(truth) and f"A: after a resize storm, {screen.diff(truth)}"---def check_b_glyphs(fd, screen):- os.write(fd, f"!printf '{GLYPHS}\\n{GLYPHS}\\n'\r".encode())- screen.feed(drain(fd, 3.0))- # Retype over it: the composer's border row is exactly `cols` wide, so every- # keystroke repaints a row the painter measures as full.- # The comparison has to happen while those glyphs are still ON the screen:- # clearing the composer first would repaint the row in plain ASCII, which- # is exactly the width both sides agree on, and would scrub the evidence.- for ch in ("✓️", " x", "\U0001f409", " y"):- os.write(fd, ch.encode())- screen.feed(drain(fd, 0.4))- truth = ground_truth(fd, ROWS, COLS)- if truth is None:- return "B: no full repaint came back to compare against"- d = screen.diff(truth)- return d and f"B: with ambiguous-width glyphs on screen, {d}"---def check_d_winch_event(fd, pid, screen):- """A resize EVENT with no dimension change at all. The terminal has- reflowed (or cleared) the screen, but tty.cols()/tty.rows() answer exactly- what they answered last pass and the frame bytes are identical, so a loop- that only compares dimensions repaints nothing and the damage stands. The- forced full repaint is visible as a clear-and-lay-down; the periodic heal- never emits one, so this cannot be mistaken for the heartbeat."""- import signal- drain(fd, 0.4)- os.kill(pid, signal.SIGWINCH)- out = drain(fd, 1.2)- screen.feed(out)- if b"\x1b[2J\x1b[H" not in out:- return "D: a SIGWINCH with unchanged dimensions did not force a full repaint"- return None---def check_c_self_heal(fd, screen):- idle = drain(fd, HEAL_MS + 1.5)- if not idle:- return "C: the loop wrote nothing at all while idle (no self-heal repaint)"- screen.feed(idle)- truth = ground_truth(fd, ROWS, COLS)- if truth is None:- return "C: no full repaint came back to compare against"- d = screen.diff(truth)- return d and f"C: after an idle self-heal, {d}"---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- try:- screen = Screen(ROWS, COLS)- screen.feed(boot(fd))- os.write(fd, f"!printf '{MARK}_ONE\\n{MARK}_TWO\\n'\r".encode())- out = drain(fd, 4.0)- screen.feed(out)- if MARK.encode() not in out:- return f"the transcript never showed {MARK} (bash row missing)"- for check in (check_a_resize_storm, check_b_glyphs, check_c_self_heal):- err = check(fd, screen)- if err:- return err- return check_d_winch_event(fd, pid, screen)- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-painter: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-painter: no pty support here — skipping")- return 0- try:- err = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-painter: pty unavailable ({e}) — skipping")- return 0- if err:- print(f" ✗ painter: {err}")- return 1- print(" ✓ painter: screen == frame after a resize storm and a glyph torture; idle heal and SIGWINCH repaint both fire")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-resize-anchor.py b/scripts/test-tui-resize-anchor.pydeleted file mode 100644index fb4975d8..00000000--- a/scripts/test-tui-resize-anchor.py+++ /dev/null@@ -1,296 +0,0 @@-#!/usr/bin/env python3-"""Live proof: a horizontal resize must not move the transcript under the user.--grok-build holds a LOGICAL scroll anchor across a width rebuild — the entry the-top visible line belongs to, plus that line's ordinal inside the entry — so a-rewrap puts the same content back on top instead of the same ROW NUMBER. This-probe drives the real binary under a pty and proves it end to end:-- 1. boots `graff tui --yolo` in a scratch cwd with an EMPTY MCP config,- 2. fills the transcript from `!printf` lines only (no model call, so the text- on screen is known exactly), with one unique marker in the middle,- 3. vertical sweep FIRST, while the user is tailing: the transcript must keep- following the bottom, so the last line stays on screen at every height,- 4. scrolls up (Ctrl+K) until the marker sits near the top of the viewport,- 5. drives TIOCSWINSZ across five widths and asserts the marker is still on- screen and has barely moved. Without an anchor, `scroll` is a distance- from the bottom of a transcript whose row count just changed, so the- marker slides away and off screen.--Usage: python3 scripts/test-tui-resize-anchor.py [path/to/graff]- (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.-"""-import os-import re-import sys-import tempfile-import time--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-ROWS, COLS = 30, 100-# Printed through a printf FORMAT so the echoed command line never contains the-# marker itself — otherwise the sticky header (which pins the last prompt) would-# satisfy "the marker is on screen" without the transcript being anywhere near.-MARK = "ANCHORMARKKILO"-MARK_CMD = r"!printf 'ANCHOR%sKILO\n' MARK"-TAIL = "TAILROWOMEGA"-# Rewrapping the entries above the anchor can only shift a near-top line by the-# few rows those entries themselves gain or lose; the failure this guards-# against moves it by tens of rows or off screen entirely.-DRIFT = 4---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read here would- # hang the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- # ADR 0042 claims the alt-screen BEFORE constructing the engine. Wait for- # run.zig's input modes and a completed first paint before sending commands;- # otherwise the first command's deadline also includes unfinished boot.- out = b""- end = time.monotonic() + BOOT_MAX- while time.monotonic() < end:- out += drain(fd, min(0.1, max(0, end - time.monotonic())))- frame = out.rfind(b"\x1b[2J\x1b[H")- if b"\x1b[?2004h" in out and frame >= 0 and b"\x1b[?2026l" in out[frame:]:- return True- return False---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0; the TUI would clamp to its 40x12- # floor and every row index below would be measured against the wrong frame.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-anchor-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- import signal- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 3.0)- except OSError:- pass- for sig in (signal.SIGTERM, signal.SIGKILL):- try:- os.kill(pid, sig)- except OSError:- pass- try:- os.waitpid(pid, 0)- except OSError:- pass---def parse(stream):- """Screen rows, in order, out of the last FULL repaint in `stream`.-- Between repaints the TUI rewrites only the rows that changed, addressing- each with CSI row;1H — stripping those out of a diff stream gives row- indices that are plausible and wrong. Any resize invalidates run.zig's diff- baseline, so what follows one is a whole frame, top row first.- """- frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(frame) < 2:- return None- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---def frame_at(fd, rows, cols, settle=1.2):- resize(fd, rows, cols)- return parse(drain(fd, settle))---def stable_frame(fd, rows, cols, budget=1.5):- # #750: a width change can emit two full frames (old wrap, then anchored).- # The first parse is a real frame — it just is not the settled one — so- # the parallel suite saw a marker jump. Wait for two identical parses- # inside the original settle budget. Do not relax DRIFT.- resize(fd, rows, cols)- last = None- deadline = time.time() + budget- while time.time() < deadline:- now = parse(drain(fd, 0.12))- if now is None:- continue- if last is not None and now == last:- return now- last = now- # A height change can emit one valid full frame without a repeated- # identical parse inside the settle budget. Keep that frame; the width- # sweep still re-reads and the DRIFT bound still applies.- return last---def reread(fd):- """A full frame at the current width, via a HEIGHT-only jiggle.-- Vertical resizes never take the anchor path, so reading the screen this way- cannot itself perturb what the width sweep is about to measure.- """- resize(fd, ROWS - 1, COLS)- drain(fd, 0.4)- return frame_at(fd, ROWS, COLS)---def find(rows, needle):- # The sticky header pins the last user prompt at the top of the viewport;- # a hit there is chrome, not the transcript.- for i, ln in enumerate(rows or []):- if needle in ln and "❯" not in ln:- return i- return None---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- try:- if not boot(fd):- return "the TUI never completed its first interactive frame"- def command(cmd, needle, budget=1.5):- # A bang command is asynchronous. Wait for its actual output before- # sending the next, rather than silently losing setup under load.- # Keep the old per-command settle budget; a missing output is now- # reported at its source, not as a scroll-anchor failure later.- os.write(fd, (cmd + "\r").encode())- out = b""- end = time.monotonic() + budget- while time.monotonic() < end:- out += drain(fd, min(0.1, max(0, end - time.monotonic())))- if needle.encode() in out:- return True- return False-- # Transcript content with no model call: `!` lines run in-session. Long- # lines so every width below genuinely rewraps them.- def block(tag):- body = "filler line %s-%d padded out so that it rewraps at every width this probe drives"- # The final marker exists only in output, never the echoed command.- args = " ".join(f"{tag} {k}" for k in range(3))- return command(r"!printf '" + body + r"\n' " + args, f"filler line {tag}-2")-- for i in range(3):- if not block(f"A{i}"):- return f"setup block A{i} never printed its final output line"- if not command(MARK_CMD, MARK):- return f"the anchor command never printed {MARK}"- # Enough transcript AFTER the marker that it starts off the top of the- # viewport: the parking loop below then walks it in from the top edge,- # which is the only way to put it near the anchored row from outside.- for i in range(5):- if not block(f"B{i}"):- return f"setup block B{i} never printed its final output line"- if not command(r"!printf 'TAIL%sOMEGA\n' ROW", TAIL, budget=2.5):- return "the transcript never showed the tail row (no `!` output)"-- # --- vertical only, while tailing: bottom-follow must hold ------------ # Every step must CHANGE the height: an identical winsize is not a- # resize, so no full repaint follows it and there is nothing to read.- for h in (18, 34, 22, ROWS):- rows = stable_frame(fd, h, COLS)- if rows is None:- return f"no full repaint at height {h}"- if find(rows, TAIL) is None:- return f"a vertical resize to {h} rows dropped the tail row: follow broke"-- # --- park the marker near the top of the viewport ---------------------- top = None- for _ in range(30):- os.write(fd, b"\x0b") # Ctrl+K: scroll one line towards older text- drain(fd, 0.25)- at = find(reread(fd), MARK)- if at is not None:- # It has just cleared the top edge. Two more lines put it clear- # of the sticky header, which OCCLUDES the top two content rows- # — a marker parked under the pin is invisible, not misplaced.- os.write(fd, b"\x0b\x0b")- drain(fd, 0.3)- top = find(reread(fd), MARK)- break- if top is None:- return f"scrolling never brought {MARK} into the upper viewport"-- # --- the width sweep --------------------------------------------------- seen = [(COLS, top)]- for w in (76, 58, 44, 92, COLS):- rows = stable_frame(fd, ROWS, w)- if rows is None:- return f"no full repaint at width {w}"- at = find(rows, MARK)- if at is None:- return f"width {w} scrolled {MARK} off screen (anchor lost); seen={seen}"- if abs(at - top) > DRIFT:- again = stable_frame(fd, ROWS, w, budget=1.8)- at2 = find(again, MARK) if again else None- if at2 is None or abs(at2 - top) > DRIFT:- return f"width {w} moved {MARK} from row {top} to {at2 if at2 is not None else at}; seen={seen}"- at = at2- seen.append((w, at))- print(f" widths/rows: {seen}")- return None- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-resize-anchor: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-resize-anchor: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ resize-anchor: {err}")- return 1- print(" ✓ resize-anchor: the marker held its place across five widths")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-screenstate.py b/scripts/test-tui-screenstate.pydeleted file mode 100644index 788c7b02..00000000--- a/scripts/test-tui-screenstate.py+++ /dev/null@@ -1,221 +0,0 @@-#!/usr/bin/env python3-"""Screen-state TUI checks, written against the virtual screen (scripts/ptyharness.py).--Same discipline as tui-pty-guard.py, one level up: instead of grepping raw pty-bytes, every assertion here reads the rows x cols grid a real terminal would-be showing. That makes the checks say what the user sees, and it unlocks a-class of test the byte probes cannot express — corrupting the screen from-OUTSIDE the child and watching whether the TUI paints its way back.-- 0. interpreter ptyharness's own selftest (no pty, no binary)- 1. mode-balance the invariant ported from tui-pty-guard.py check A: every- DEC private mode the TUI latches is back to the terminal- default after a clean quit, and the kitty keyboard- push/pop depth is zero. Read off the interpreter's mode- bookkeeping rather than a regex over the byte stream.- 2. corruption feed_screen() writes straight to the tty, bypassing graff- (a tmux status repaint, an nvim redraw, another process- on the same terminal). The garbage must land on the grid —- this is the harness proving it can SEE the damage.- 3. repaint-heals positive control: a resize forces graff's full repaint,- and the grid must come back clean. Without this, check 4's- failure could just mean "the harness never updates".- 4. self-heal HARD ASSERT. Corrupt the frame, then wait on idle only,- and require screen_contents() to be the pre-corruption- frame. The painter's heal heartbeat (TUI/run.zig, from- fix/tui-painter) rewrites every row on a clock, so- out-of-band damage must not survive it. Check 3 is the- inline control proving the harness itself sees repaints.--Usage: python3 scripts/test-tui-screenstate.py [path/to/graff] (default zig-out/bin/graff)-Exit 0 = pass. Skips (exit 0, notice) when no pty can be allocated.-"""-import os-import signal-import sys-import tempfile--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-COLS, ROWS = 100, 30-MARK = "TMUX_SCRIBBLE_9F2A"-# Row 4 of the transcript area: above every chrome row, below nothing that-# animates, so a diff paint has no reason to rewrite it on its own.-CORRUPT_ROW = 4---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-screen-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def session(PtyHarness):- ws, env = fresh_ws()- return PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=ws, env=env)---def check_mode_balance(PtyHarness):- h = session(PtyHarness)- try:- if not h.wait_for_boot():- return "the TUI never entered the alt screen"- h.wait_for_text("Enter:send", timeout=10)- if not h.modes.get(1049):- return "the alt screen is not latched while the TUI is up"- status = h.quit()- if status is None:- return "quit did not exit within the window"- latched, depth = h.mode_imbalance()- if latched:- return f"modes latched but never reset by clean quit: {latched}"- if depth != 0:- return f"kitty keyboard push/pop unbalanced (depth {depth})"- if h.modes.get(1049):- return "alt-screen entered but never left"- return None- finally:- h.close()---def scribble():- """An inverse-video status bar, the shape tmux and nvim actually paint."""- return f"\x1b[{CORRUPT_ROW + 1};1H\x1b[7m{MARK} ".encode() + b"#" * 40 + b"\x1b[27m"---def inject_corruption(h):- # feed_screen pumps the real tty; a concurrent heal can erase the marker- # during that read. Stop only while installing and observing the damage,- # then resume the painter before testing either recovery path.- os.kill(h.pid, signal.SIGSTOP)- try:- _, status = os.waitpid(h.pid, os.WUNTRACED)- if not os.WIFSTOPPED(status):- raise RuntimeError("TUI exited before corruption could be injected")- h.pump(0.1) # drain any frame emitted before SIGSTOP took effect- h.feed_screen(scribble())- return h.screen_contents(), h.cell(0, CORRUPT_ROW).inverse- finally:- try:- os.kill(h.pid, signal.SIGCONT)- except ProcessLookupError:- pass---def poke(h):- """Make the TUI paint again without changing the resulting frame: a- keystroke the composer then takes back. Any self-heal repaint has every- opportunity to fire here."""- h.inject_keys(b"z")- h.pump(1.0)- h.inject_keys(b"\x7f")- h.pump(1.5)---def check_corruption_and_healing(PtyHarness):- """Returns (hard_error, healed, detail)."""- h = session(PtyHarness)- try:- if not h.wait_for_boot():- return "the TUI never entered the alt screen", False, ""- h.wait_for_text("Enter:send", timeout=10)- h.pump(2.5) # let boot toasts (clipboard hint) age out of the frame- before = h.screen_contents()- before_row = h.screen_lines()[CORRUPT_ROW]-- # Out-of-band repaint: straight to the tty, graff never sees it.- corrupted, inverse = inject_corruption(h)- if MARK not in corrupted:- return "feed_screen did not reach the screen (harness cannot see the damage)", False, ""- if corrupted == before:- return "the grid did not change under corruption", False, ""- # Cell-level styling survives the round trip through the real pty, so a- # test can assert on attributes and not just glyphs.- if not inverse:- return "the scribbled cells lost their inverse attribute", False, ""-- # Positive control: a resize forces graff's full repaint, and the grid- # must come back clean. If this fails, the harness is at fault, not the- # painter.- h.resize(COLS, ROWS - 1)- h.pump(1.0)- h.resize(COLS, ROWS)- h.pump(1.5)- if MARK in h.screen_contents():- return "a forced full repaint did not clear the corruption (harness/grid fault)", False, ""-- # The real question: does ordinary activity heal out-of-band damage?- h.pump(1.0)- before = h.screen_contents()- before_row = h.screen_lines()[CORRUPT_ROW]- corrupted, _ = inject_corruption(h)- if MARK not in corrupted:- return "second corruption never landed", False, ""- poke(h)- after = h.screen_contents()- healed = MARK not in after and h.screen_lines()[CORRUPT_ROW] == before_row- detail = "" if healed else (- f"row {CORRUPT_ROW} is {h.screen_lines()[CORRUPT_ROW]!r}, "- f"was {before_row!r}; frames {'match' if after == before else 'differ'}"- )- return None, healed, detail- finally:- h.close()---def main():- if not os.path.exists(BIN):- print(f"tui-screenstate: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-screenstate: no pty support here — skipping")- return 0- import ptyharness-- if ptyharness._selftest() != 0:- print(" ✗ interpreter: the VT interpreter itself is broken")- print("tui-screenstate: 1 check(s) failed")- return 1- print(" ✓ interpreter: ptyharness VT selftest (--selftest for the full list)")-- failures = []- try:- err = check_mode_balance(ptyharness.PtyHarness)- except OSError as e:- # EIO on a dead pty means the CHILD vanished — a failure, not a skip.- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-screenstate: pty unavailable ({e}) — skipping")- return 0- if err:- failures.append(err)- print(f" ✗ mode-balance: {err}")- else:- print(" ✓ mode-balance: every latched mode is back to default, kitty depth 0")-- err, healed, detail = check_corruption_and_healing(ptyharness.PtyHarness)- if err:- failures.append(err)- print(f" ✗ corruption: {err}")- else:- print(f" ✓ corruption: out-of-band {MARK} landed on the grid, a full repaint clears it")- if healed:- print(" ✓ self-heal: the painter repairs out-of-band damage on its own clock")- else:- failures.append("self-heal")- print(f" ✗ self-heal: a diff paint left out-of-band damage in place: {detail}")-- if failures:- print(f"tui-screenstate: {len(failures)} check(s) failed")- return 1- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-scroll-paint.py b/scripts/test-tui-scroll-paint.pydeleted file mode 100644index f23ea075..00000000--- a/scripts/test-tui-scroll-paint.py+++ /dev/null@@ -1,404 +0,0 @@-#!/usr/bin/env python3-"""Live proof: scrolling the transcript is a terminal-side SCROLL, and it lies-about nothing.--The diff painter compares screen row i to the previous frame's row i, so a-one-line scroll makes EVERY row differ and the whole screen is rewritten per-wheel notch. TUI/scrollpaint.zig instead sets a scroll region over the band that-moved, emits SU/SD, and repaints only the rows the scroll exposed. That is a-correctness risk exactly where it is a performance win: if the region, the-direction or the exposed rows are off by one, the screen quietly stops matching-the frame and NOTHING says so — the next paint diffs against a model of the-screen that is no longer true.--So this probe drives the real binary under a pty and checks both halves:-- A. cheap one wheel notch must cost a small fraction of a full repaint, and- must contain a scroll-region + SU/SD rather than a screenful of- rows. Reported as bytes, measured live.- B. honest after a storm of wheel notches in both directions (plus keyboard- scrolling, a fold toggle mid-storm and a page jump), the modelled- screen — replayed through a terminal that understands DECSTBM /- SU / SD — must equal a FORCED FULL REPAINT of the same frame, cell- for cell. Any cell where they differ is a cell the scroll path- moved somewhere the composer did not.- C. tidy the scroll region must not be left set. A margin that outlives the- paint turns every later LF into a scroll inside it.--Usage: python3 scripts/test-tui-scroll-paint.py [path/to/graff]- (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.-"""-import os-import re-import sys-import tempfile-import time-import unicodedata--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-ROWS, COLS = 30, 100-TAIL = "SCROLLTAILOMEGA"-# One wheel notch is 3 lines out of a ~24-row band: comfortably under a quarter-# of a full repaint even with the sticky header and status bar changing too.-BUDGET = 0.25--WHEEL_UP = b"\x1b[<64;40;10M"-WHEEL_DOWN = b"\x1b[<65;40;10M"---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read here would- # hang the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=ROWS, cols=COLS):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0 and the TUI clamps to its floor.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-scroll-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- import signal- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for sig in (signal.SIGTERM, signal.SIGKILL):- try:- os.kill(pid, sig)- except OSError:- pass- try:- os.waitpid(pid, 0)- except OSError:- pass---def cell_width(ch):- if unicodedata.combining(ch) or ch in "︎️":- return 0- if unicodedata.east_asian_width(ch) in ("W", "F"):- return 2- if ord(ch) >= 0x1F300:- return 2- return 1---CSI = re.compile(r"\x1b\[([0-9;?<>]*)([@-~])")---class Screen:- """The subset of a terminal the painter can get wrong, plus the two- sequences the scroll path adds: DECSTBM margins and SU/SD. Autowrap is off,- as run.zig sets it (?7l)."""-- def __init__(self, rows, cols):- self.rows, self.cols = rows, cols- self.cells = [[" "] * cols for _ in range(rows)]- self.r = self.c = 0- self.top, self.bot = 0, rows - 1- self.margins_seen = 0- self.scrolls = 0-- def put(self, ch, w):- if self.r >= self.rows:- return- c = min(self.c, self.cols - 1)- self.cells[self.r][c] = ch- if w == 2 and c + 1 < self.cols:- self.cells[self.r][c + 1] = ""- self.c = min(c + w, self.cols)-- def erase_to_eol(self):- if self.r >= self.rows:- return- for c in range(min(self.c, self.cols - 1), self.cols):- self.cells[self.r][c] = " "-- def clear(self):- self.cells = [[" "] * self.cols for _ in range(self.rows)]- self.r = self.c = 0-- def scroll(self, n, up):- self.scrolls += 1- blank = [" "] * self.cols- for _ in range(n):- if up:- for r in range(self.top, self.bot):- self.cells[r] = self.cells[r + 1]- self.cells[self.bot] = list(blank)- else:- for r in range(self.bot, self.top, -1):- self.cells[r] = self.cells[r - 1]- self.cells[self.top] = list(blank)-- def feed(self, data):- s = data.decode("utf-8", errors="replace")- i = 0- while i < len(s):- ch = s[i]- if ch == "\x1b":- i = self.escape(s, i)- continue- if ch == "\r":- self.c = 0- i += 1- continue- if ch == "\n":- # Inside the margins an LF at the bottom scrolls; the painter- # only ever emits LF on the full lay-down, with no margins set.- self.r += 1- i += 1- continue- w = cell_width(ch)- if w:- self.put(ch, w)- i += 1- return self-- def escape(self, s, i):- rest = s[i:]- m = CSI.match(rest)- if m:- self.csi(m.group(1), m.group(2))- return i + m.end()- if len(rest) > 1 and rest[1] in "]P_^X":- bel = rest.find("\x07")- st = rest.find("\x1b\\")- ends = [e for e in (bel + 1 if bel >= 0 else -1, st + 2 if st >= 0 else -1) if e > 0]- return i + (min(ends) if ends else len(rest))- return i + 2-- def csi(self, params, final):- if params.startswith(("?", "<", ">")):- return- parts = params.split(";")-- def num(k, dflt):- return int(parts[k]) if len(parts) > k and parts[k].isdigit() else dflt-- if final == "H":- self.r, self.c = max(num(0, 1) - 1, 0), max(num(1, 1) - 1, 0)- elif final == "J" and params in ("2", "3"):- self.clear()- elif final == "K" and params in ("", "0"):- self.erase_to_eol()- elif final == "r":- self.top = max(num(0, 1) - 1, 0)- self.bot = min(num(1, self.rows) - 1, self.rows - 1)- if params:- self.margins_seen += 1- self.r, self.c = self.top, 0- elif final == "S":- self.scroll(max(num(0, 1), 1), True)- elif final == "T":- self.scroll(max(num(0, 1), 1), False)-- def text_rows(self):- return ["".join(row).rstrip() for row in self.cells]-- def diff(self, other):- for r, (a, b) in enumerate(zip(self.text_rows(), other.text_rows())):- if a != b:- return f"row {r}: screen has {a!r} but the frame is {b!r}"- return None---def paints(stream):- """One entry per PAINT. run.zig wraps each in the ?2026 synchronized-update- bracket, which is the only way to tell one paint from the next in a stream- that also carries the 3-second self-heal — and a heal landing inside the- window would otherwise be billed to the wheel notch being measured."""- return re.findall(rb"\x1b\[\?2026h(.*?)\x1b\[\?2026l", stream, re.S)---def ground_truth(fd, rows, cols):- """A forced full repaint, replayed onto a fresh screen: what the terminal- WOULD show if it were redrawn from nothing right now. A resize invalidates- run.zig's diff baseline, so the paint that follows one is a whole frame."""- resize(fd, rows - 1, cols)- drain(fd, 0.5)- resize(fd, rows, cols)- stream = drain(fd, 1.5)- full = [p for p in paints(stream) if b"\x1b[2J\x1b[H" in p]- if not full:- return None, 0- truth = Screen(rows, cols)- truth.clear()- return truth.feed(full[-1]), len(full[-1])---def fill(fd):- """Transcript content with no model call: `!` lines run in-session, so the- text on screen is known exactly and nothing streams while we scroll."""- for tag in range(8):- body = "filler line %d-%d padded out so the transcript is far longer than the viewport"- lines = "".join((body % (tag, k)) + r"\n" for k in range(4))- os.write(fd, (r"!printf '" + lines + r"'" + "\r").encode())- drain(fd, 1.2)- os.write(fd, (r"!printf '" + TAIL + r"\n'" + "\r").encode())- return drain(fd, 2.5)---def check_a_cheap(fd, screen):- truth, full_bytes = ground_truth(fd, ROWS, COLS)- if truth is None:- return "A: no full repaint came back to size the budget against", None- screen.feed(b"")- # Off the bottom first, so the notch measured below is a plain slide with- # transcript on both sides of it rather than a clamp at the tail.- for _ in range(4):- os.write(fd, WHEEL_UP)- screen.feed(drain(fd, 0.35))- os.write(fd, WHEEL_UP)- stream = drain(fd, 0.8)- screen.feed(stream)- # The notch's OWN paint, not whatever else the 0.8s window caught.- scrolled = [p for p in paints(stream) if re.search(rb"\x1b\[\d+[ST]", p)]- if not scrolled:- return "A: a wheel notch emitted no SU/SD — the fast path never fired", None- one = scrolled[-1]- if not re.search(rb"\x1b\[\d+;\d+r", one):- return "A: the scroll was emitted with no DECSTBM region around it", None- if len(one) >= full_bytes * BUDGET:- return (- f"A: a wheel notch cost {len(one)} bytes against a {full_bytes}-byte full repaint "- f"(budget {BUDGET:.0%})"- ), None- return None, (len(one), full_bytes)---def check_b_honest(fd, screen):- storm = (- [WHEEL_UP] * 9- + [WHEEL_DOWN] * 4- + [b"\x0b"] * 3 # Ctrl+K: keyboard scroll, one line at a time- + [WHEEL_UP] * 6- + [b"\x1b[5~"] # PageUp: a jump far larger than the band- + [WHEEL_DOWN] * 5- + [WHEEL_UP] * 2- + [b"\x1b[6~"] # PageDown back- + [WHEEL_DOWN] * 8- + [WHEEL_UP] * 3- )- for ev in storm:- os.write(fd, ev)- screen.feed(drain(fd, 0.18))- screen.feed(drain(fd, 0.8))- if screen.scrolls == 0:- return "B: the storm never took the scroll path at all"- truth, _ = ground_truth(fd, ROWS, COLS)- if truth is None:- return "B: no full repaint came back to compare against"- screen.feed(b"")- d = screen.diff(truth)- return d and f"B: after a scroll storm of {screen.scrolls} scrolls, {d}"---def check_c_tidy(screen):- if (screen.top, screen.bot) != (0, ROWS - 1):- return f"C: the scroll region was left at rows {screen.top}-{screen.bot}"- if screen.margins_seen == 0:- return "C: no DECSTBM was ever set, so nothing was proven about resetting it"- return None---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- try:- screen = Screen(ROWS, COLS)- screen.feed(boot(fd))- out = fill(fd)- screen.feed(out)- if TAIL.encode() not in out:- return f"the transcript never showed {TAIL} (no `!` output)"- err, nums = check_a_cheap(fd, screen)- if err:- return err- print(f" one wheel notch: {nums[0]} bytes vs {nums[1]} for a full repaint "- f"({nums[0] / nums[1]:.1%})")- err = check_b_honest(fd, screen)- if err:- return err- print(f" storm: {screen.scrolls} hardware scrolls, screen == frame")- return check_c_tidy(screen)- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-scroll-paint: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-scroll-paint: no pty support here — skipping")- return 0- try:- err = run()- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-scroll-paint: pty unavailable ({e}) — skipping")- return 0- if err:- print(f" ✗ scroll-paint: {err}")- return 1- print(" ✓ scroll-paint: a wheel notch is a scroll region + SU, and a storm of them leaves the screen == the frame")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-scrollbar-osc52.py b/scripts/test-tui-scrollbar-osc52.pydeleted file mode 100755index cfc72915..00000000--- a/scripts/test-tui-scrollbar-osc52.py+++ /dev/null@@ -1,294 +0,0 @@-#!/usr/bin/env python3-"""Live proof for the scroll gutter and the OSC 52 clipboard channel.--Both features are invisible to a unit test in the way that matters: one is a-glyph that has to land on a specific CELL of a real terminal, the other is a-byte string that has to leave the process. So this probe drives the real binary-under a pty, reads the virtual screen back (scripts/ptyharness.py), and checks:-- A. thumb scroll off the tail and the LAST column of the viewport shows a- contiguous run of thumb glyphs, inside the transcript band and- nowhere else — not on the top bar, not on the composer.- B. travel scrolling back toward the tail moves that run DOWN the track.- C. no residue back at the tail, past the fade window, no thumb survives- anywhere on the grid — and the last column of every row is- identical to what a FORCED FULL REPAINT of the same frame puts- there. A diff paint that skipped the gutter rows would leave a- glyph the full repaint does not, and this is what catches it.- D. osc52 a drag-copy puts `ESC ] 52 ; c ; <base64> BEL` on the wire, and- the base64 decodes to exactly the screen rows the drag covered.- Asserted against the BYTE STREAM, because that is the thing an- SSH client on the far end actually receives.--Usage: python3 scripts/test-tui-scrollbar-osc52.py [path/to/graff]- (default zig-out/bin/graff). Exit 0 = pass; skips (exit 0) with no pty.-"""-import base64-import os-import re-import subprocess-import sys-import tempfile-import time--sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-COLS, ROWS = 100, 30-THUMB = "❚"-MARK = "GUTTERMARK_QX"-FADE = 1.5 # TUI/scrollbar.zig fade_ms-OSC52 = re.compile(rb"\x1b\]52;c;([A-Za-z0-9+/=]*)\x07")--WHEEL_UP = b"\x1b[<64;40;10M"-WHEEL_DOWN = b"\x1b[<65;40;10M"---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-gutter-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def fill(h, blocks=8):- """Transcript content with no model call: `!` lines run in-session, so the- text on screen is known exactly and nothing streams while we scroll."""- for tag in range(blocks):- body = "%s filler %d-%d padded out so the transcript outruns the viewport"- lines = "".join((body % (MARK, tag, k)) + r"\n" for k in range(4))- h.inject_keys((r"!printf '" + lines + r"'" + "\r").encode())- h.pump(1.0)- h.pump(1.5)---def thumb_rows(h):- """Rows whose LAST column carries the thumb."""- return [y for y in range(ROWS) if h.cell(COLS - 1, y).ch == THUMB]---def last_column(h):- return [h.cell(COLS - 1, y).ch for y in range(ROWS)]---def full_repaint(h):- """A resize invalidates run.zig's diff baseline, so what follows is one- whole frame laid down from a cleared screen."""- h.resize(COLS, ROWS - 1)- h.pump(0.6)- h.resize(COLS, ROWS)- h.pump(1.5)---def sgr(btn, col, row, press=True):- return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()---def check_thumb(h):- # Nothing has scrolled yet: no gutter on a tail-parked viewport.- if thumb_rows(h):- return "the gutter is up before anything scrolled", None- for _ in range(5):- h.inject_keys(WHEEL_UP)- h.pump(0.25)- h.pump(0.5)- rows = thumb_rows(h)- if not rows:- return "scrolling off the tail raised no thumb on the last column", None- if rows != list(range(rows[0], rows[0] + len(rows))):- return f"the thumb is not one contiguous run: {rows}", None- # It has to be INSIDE the transcript, not on the chrome. The composer box- # is the last thing on screen and draws its own right wall, so a thumb on- # it would be sitting on that wall.- lines = h.screen_lines()- box_rows = [y for y, ln in enumerate(lines) if "│" in ln or "╰" in ln or "╭" in ln]- if box_rows and rows[-1] >= min(box_rows):- return f"the thumb reached the composer: rows {rows}, box starts at {min(box_rows)}", None- if rows[0] == 0:- return "the thumb is on the top bar, not in the viewport", None- # And it is the ONLY place that glyph appears — a gutter that also printed- # into the body would be indistinguishable from content.- stray = [(x, y) for y in range(ROWS) for x in range(COLS - 1) if h.cell(x, y).ch == THUMB]- if stray:- return f"the thumb glyph appears off the last column at {stray[:3]}", None- return None, rows---def check_travel(h, high):- for _ in range(3):- h.inject_keys(WHEEL_DOWN)- h.pump(0.25)- h.pump(0.5)- low = thumb_rows(h)- if not low:- return "the gutter vanished while still scrolled off the tail", None- if low[0] <= high[0]:- return f"scrolling toward the tail did not move the thumb down ({high} -> {low})", None- return None, low---def check_no_residue(h):- # All the way back to the tail, then past the fade window.- for _ in range(24):- h.inject_keys(WHEEL_DOWN)- h.pump(0.06)- h.pump(FADE + 1.0)- left = thumb_rows(h)- if left:- return f"the gutter never faded at the tail: rows {left}"- everywhere = [(x, y) for y in range(ROWS) for x in range(COLS) if h.cell(x, y).ch == THUMB]- if everywhere:- return f"a thumb glyph survived somewhere on the grid: {everywhere[:3]}"- # The equality check that makes "no residue" mean something: the diff paint- # that took the gutter away must have left the screen where a full repaint- # of the same frame would.- diffed = last_column(h)- full_repaint(h)- fresh = last_column(h)- if diffed != fresh:- bad = [i for i, (a, b) in enumerate(zip(diffed, fresh)) if a != b]- return (- f"the last column differs from a forced full repaint at rows {bad[:5]}: "- f"{[diffed[i] for i in bad[:5]]!r} vs {[fresh[i] for i in bad[:5]]!r}"- )- return None---def check_osc52(h):- """Drag two known rows and read the escape off the wire."""- lines = h.screen_lines()- hits = [i for i, ln in enumerate(lines) if MARK in ln]- if len(hits) < 3:- return f"not enough {MARK} rows on screen to drag ({len(hits)})"- first, last = hits[0], hits[0] + 1- seen = len(h.raw)- h.inject_keys(sgr(0, 1, first + 1))- h.pump(0.35)- h.inject_keys(sgr(32, COLS, last + 1))- h.pump(0.5)- if b"\x1b[7m" not in bytes(h.raw[seen:]):- return "the drag painted no inverse-video band, so nothing was selected"- before_release = len(h.raw)- if OSC52.search(bytes(h.raw[seen:])):- return "an OSC 52 escape went out before the button was released"- h.inject_keys(sgr(0, COLS, last + 1, press=False))- h.pump(1.5)- tail = bytes(h.raw[before_release:])- found = OSC52.findall(tail)- if not found:- return "the release emitted no OSC 52 sequence"- if len(found) > 1:- return f"the release emitted {len(found)} OSC 52 sequences; a clipboard write happens once"- try:- payload = base64.b64decode(found[0], validate=True).decode("utf-8", "replace")- except Exception as e: # noqa: BLE001- return f"the OSC 52 body is not valid base64 ({e})"- # The band survives the release, so the rows on screen right now ARE the- # rows that were copied. Text-only capture: each row loses its padding.- want = "\n".join(h.screen_lines()[first:last + 1]).rstrip()- want = "\n".join(ln.rstrip() for ln in want.split("\n"))- if payload != want:- return f"OSC 52 carried {payload!r}, but the dragged rows read {want!r}"- if MARK not in payload:- return f"the OSC 52 payload does not contain {MARK}: {payload!r}"- return None---def check_heal_does_not_recopy(h):- """The self-heal repaint must not put the clipboard write back on the wire.-- The heartbeat rewrites every row of the frame it already believes is up- (run.zig, heal_interval_ms = 3s). A clipboard write is NOT part of that- frame - it is written out of band, once, on the release - and a heal that- re-emitted it would hand the terminal a second copy of a selection the- user made once, on a timer, forever. Idle across two heartbeats and read- the wire.- """- after_copy = len(h.raw)- h.pump(7.0) # >= two heal intervals- tail = bytes(h.raw[after_copy:])- again = OSC52.findall(tail)- if again:- return f"the self-heal re-emitted {len(again)} OSC 52 sequence(s) while idle"- return None---def run(PtyHarness):- ws, env = fresh_ws()- h = PtyHarness([BIN, "tui", "--yolo"], cols=COLS, rows=ROWS, cwd=ws, env=env)- try:- if not h.wait_for_boot():- return "the TUI never entered the alt screen"- h.wait_for_text("Enter:send", timeout=10)- fill(h)- if MARK not in h.screen_contents():- return f"the transcript never showed {MARK} (no `!` output)"- err, high = check_thumb(h)- if err:- return err- print(f" thumb: rows {high[0]}..{high[-1]} on column {COLS - 1}")- err, low = check_travel(h, high)- if err:- return err- print(f" travel: {high[0]}..{high[-1]} -> {low[0]}..{low[-1]} toward the tail")- err = check_no_residue(h)- if err:- return err- print(" residue: gutter faded, last column == a forced full repaint")- err = check_osc52(h)- if err:- return err- print(" osc52: the wire carried the exact base64 of the dragged rows")- err = check_heal_does_not_recopy(h)- if err:- return err- print(" heal: two heartbeats passed and the clipboard stayed quiet")- return None- finally:- h.close()---def main():- if not os.path.exists(BIN):- print(f"tui-scrollbar-osc52: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-scrollbar-osc52: no pty support here — skipping")- return 0- import ptyharness-- # The local half of the copy writes the real clipboard; put it back.- saved = None- if sys.platform == "darwin":- try:- saved = subprocess.run(["pbpaste"], capture_output=True, check=True).stdout- except Exception: # noqa: BLE001- saved = None- try:- err = run(ptyharness.PtyHarness)- except ptyharness.PtyTimeout as e:- err = str(e).splitlines()[0]- except OSError as e:- if getattr(e, "errno", None) == 5:- err = "pty EIO — the graff process died mid-check"- else:- print(f"tui-scrollbar-osc52: pty unavailable ({e}) — skipping")- return 0- finally:- if saved is not None:- try:- subprocess.run(["pbcopy"], input=saved, check=False)- except Exception: # noqa: BLE001- pass- if err:- print(f" ✗ scrollbar/osc52: {err}")- return 1- print(" ✓ scrollbar/osc52: the gutter tracks the viewport and leaves no residue; a copy reaches the terminal")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-selection.py b/scripts/test-tui-selection.pydeleted file mode 100644index 8edca080..00000000--- a/scripts/test-tui-selection.py+++ /dev/null@@ -1,320 +0,0 @@-#!/usr/bin/env python3-"""Live proof for #529: drag-select in the fullscreen TUI, against the real binary.--Under a pty, with a real session (so the clipboard callback is the session's-own), the probe:-- 1. boots `graff tui --yolo` in a scratch cwd with an EMPTY MCP config,- 2. fills the transcript with a shell line (`!printf ...`) so no model call is- needed and the text on screen is known,- 3. sends an SGR mouse drag over the transcript — press, motions, release,- 4. asserts the frame that comes back carries inverse-video (SGR 7) spans,- 5. asserts the system clipboard now holds exactly the dragged text (pbpaste),- 6. asserts the CAPTURE CONTRACT against the live screen: a drag that runs off- the last text row and down through the blank screen below the transcript- copies the same thing the tight drag did, and a drag that covers nothing- but blank rows leaves a pre-seeded clipboard sentinel untouched, and- 7. asserts a following keystroke clears the band again.--Usage: python3 scripts/test-tui-selection.py [path/to/graff] (default zig-out/bin/graff)-Exit 0 = pass. Skips (exit 0, notice) with no pty or no clipboard tool.-"""-import os-import re-import subprocess-import sys-import tempfile-import time--# Absolutized BEFORE the fork: the child chdirs into its scratch workspace.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 15.0-MARK = "SELECTME_ZULU"-SENTINEL = "CLIPBOARD_SENTINEL_BEFORE_DRAG"-# Returned instead of an error when the environment, not the TUI, is at fault.-SKIP = "skip: the clipboard is being written by another app"---def drain(fd, seconds):- # select-gated: a quiet pty blocks on read, and a blocking read here would- # hang the probe on exactly the wedged states it exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def spawn(cwd, env_extra, rows=30, cols=100):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo"])- # A pty forked without a size reports 0x0; the TUI would clamp to its 40x12- # floor and the drag rows below would land in the composer.- resize(fd, rows, cols)- return pid, fd---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-sel-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- f.write('{"mcpServers": {}}')- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def reap(pid, fd):- import signal- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 3.0)- except OSError:- pass- try:- os.kill(pid, signal.SIGKILL)- except OSError:- pass- try:- os.waitpid(pid, 0)- except OSError:- pass---def clipboard_set(text):- subprocess.run(["pbcopy"], input=text.encode(), check=True)---def clipboard_get():- return subprocess.run(["pbpaste"], capture_output=True, check=True).stdout.decode()---def clipboard_after_copy(prev, tries=10):- """The clipboard once a copy has landed. pbpaste can observe the pasteboard- mid-write and come back empty, which would read as "copied nothing"."""- got = prev- for _ in range(tries):- got = clipboard_get()- if got and got != prev:- return got- time.sleep(0.2)- return got---def seed_clipboard():- """Plant the sentinel and confirm it stuck. A clipboard manager writing in- the background must read as a skip, never as a failure of the TUI."""- for _ in range(3):- clipboard_set(SENTINEL)- if clipboard_get() == SENTINEL:- return True- return False---def sgr(btn, col, row, press=True):- return f"\x1b[<{btn};{col};{row}{'M' if press else 'm'}".encode()---def full_frame(fd, rows, cols):- """Screen rows, in order, from a FORCED full repaint.-- Between repaints the TUI only rewrites the rows that changed, addressing- each with CSI row;1H — stripping those out of a diff stream gives row- indices that are plausible and wrong. A resize invalidates run.zig's diff- baseline, so what follows is one whole frame, top row first.- """- resize(fd, rows - 1, cols)- drain(fd, 0.4)- resize(fd, rows, cols)- stream = drain(fd, 1.2)- frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(frame) < 2:- return None- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---ROWS, COLS = 30, 100---def drag_copy(fd, r0, r1):- """Press on row r0, drag through r1, release. Rows are 1-based, as SGR reports.-- Returns (painted, after) — the stream while the button was down, and the- stream after the release, which is where the copy toast shows up.- """- os.write(fd, sgr(0, 1, r0))- drain(fd, 0.3)- os.write(fd, sgr(32, COLS, (r0 + r1) // 2))- drain(fd, 0.2)- os.write(fd, sgr(32, COLS, r1))- painted = drain(fd, 0.6)- os.write(fd, sgr(0, COLS, r1, press=False))- return painted, drain(fd, 1.0)---def blank_run(rows, start):- """The contiguous run of blank screen rows at `start` — the empty screen- below the transcript, which a drag must be able to overshoot into."""- out = []- i = start- while i < len(rows) and rows[i].strip() == "":- out.append(i)- i += 1- return out---def run():- ws, env = fresh_ws()- pid, fd = spawn(ws, env, ROWS, COLS)- try:- boot(fd)- # Transcript content without a model call: the `!` line runs in-session.- os.write(fd, f"!printf '{MARK}_ONE\\n{MARK}_TWO\\n'\r".encode())- out = drain(fd, 4.0)- if MARK.encode() not in out:- return f"the transcript never showed {MARK} (bash row missing)"- rows = full_frame(fd, ROWS, COLS)- if rows is None:- return "no full repaint to read the screen from"- hit = next((i for i, ln in enumerate(rows) if MARK + "_ONE" in ln), None)- if hit is None:- return f"{MARK}_ONE is not on any screen row of the full frame"- # Baseline: nothing is inverse-video before the drag.- idle = drain(fd, 0.4)- if b"\x1b[7m" in idle:- return "the idle frame already carries an inverse-video band"- # `hit` is the ECHOED command line — it carries the mark inside the- # printf argument. The output block is the rows after it, up to the last- # row still carrying the mark; the echo row is skipped because the TUI- # decorates it with a run marker that changes between frames.- first, last = hit + 1, max(i for i, ln in enumerate(rows) if MARK in ln)- if last <= first:- return "the printf output did not land on its own screen rows"- blanks = blank_run(rows, last + 1)- if len(blanks) < 4:- return "no blank screen region below the transcript to drag into"- if not seed_clipboard():- return SKIP- # A TIGHT drag: press on the marked row, release on the last text row.- # SGR: button 0 press, 32 = motion with the button held, final 'm'.- top = first + 1 # screen rows are 1-based in the SGR report- painted, _ = drag_copy(fd, top, last + 1)- if b"\x1b[7m" not in painted:- return "the drag painted no inverse-video band (no SGR 7 in the frame)"- if b"\x1b[27m" not in painted:- return "the band never emitted its SGR 27 terminator"- tight = clipboard_after_copy(SENTINEL)- if tight == SENTINEL:- return "the release did not reach the clipboard (still the sentinel)"- # Row bytes are asserted by shape, not compared to the pre-drag frame:- # the press moves scrollback focus, which puts a `›` marker in column 0- # of the pressed row. That marker is real screen text and is copied.- lines = tight.split("\n")- if len(lines) != last - first + 1:- return f"a {last - first + 1}-text-row drag copied {len(lines)} line(s): {tight!r}"- if not lines[0].endswith(f"{MARK}_ONE") or not lines[-1].endswith(f"{MARK}_TWO"):- return f"the tight drag copied {tight!r}, not the two marked rows"- if any(ln.strip() == "" for ln in lines):- return f"the tight drag copied a blank line: {tight!r}"- if any(ln != ln.rstrip() for ln in lines):- return f"a copied row kept its trailing padding: {tight!r}"- # OVERSHOOT: the same first row, released far down in the blank screen- # below the transcript. Blank rows are padding, not content, so this- # must land exactly what the tight drag did — no trailing empty lines.- if not seed_clipboard():- return SKIP- drag_copy(fd, top, blanks[-1] + 1) # release deep in the blank screen- loose = clipboard_after_copy(SENTINEL)- if loose != tight:- return f"overshooting into the blank screen copied {loose!r}, wanted {tight!r}"- # BLANK-ONLY: a drag wholly inside the empty screen copies nothing at- # all — the clipboard keeps what the user had, and no toast claims a copy.- drain(fd, 2.0) # let the previous copy toast expire first- if not seed_clipboard():- return SKIP- _, after_blank = drag_copy(fd, blanks[1] + 1, blanks[-2] + 1)- empty = clipboard_get()- if empty != SENTINEL:- return f"a drag over blank rows overwrote the clipboard with {empty!r}"- if b"copied" in after_blank:- return "a drag over blank rows still showed a 'copied' toast"- # A following keystroke drops the band: the repaint that follows must- # rewrite those rows WITHOUT inverse video.- os.write(fd, b"z")- after = drain(fd, 1.0)- if b"\x1b[7m" in after:- return "a keystroke did not clear the band"- return None- finally:- reap(pid, fd)---def main():- if not os.path.exists(BIN):- print(f"tui-selection: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-selection: no pty support here — skipping")- return 0- if sys.platform != "darwin":- print("tui-selection: clipboard probe is macOS-only (pbcopy/pbpaste) — skipping")- return 0- saved = None- try:- saved = clipboard_get()- except Exception:- print("tui-selection: no clipboard access — skipping")- return 0- try:- err = run()- finally:- if saved is not None:- try:- clipboard_set(saved)- except Exception:- pass- if err == SKIP:- print(f"tui-selection: {err[6:]} — skipping")- return 0- if err:- print(f" ✗ drag-select: {err}")- return 1- print(" ✓ drag-select: band painted, clipboard got the text rows and only those")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-steer-gpt6.py b/scripts/test-tui-steer-gpt6.pydeleted file mode 100644index 55f935bb..00000000--- a/scripts/test-tui-steer-gpt6.py+++ /dev/null@@ -1,353 +0,0 @@-#!/usr/bin/env python3-"""GPT-6 mid-turn steering end to end: the real binary under a pty, a mock-Codex socket playing the server's side of `response.steer`.-- 1. continuation: a follow-up typed while the reply streams goes out as a- steer; the server accepts it, ends the reply `incomplete: steered` and- streams a continuation. No rebuilt request, and the next turn's full- input carries the steer once, between the cut reply and the- continuation (the TUI re-anchors every turn on a fresh socket).- 2. pending: a steer that meets a client tool call waits for the tool output.- The tool loop runs at once (no wait for a continuation that never- comes), and the output request does not repeat the steer.- 3. failed: a rejected steer is not lost; it runs as the next message.--Usage: python3 scripts/test-tui-steer-gpt6.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--from codex_ws_mock import USAGE, CodexMock, RecordedRequest--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 20.0-ROWS, COLS = 40, 110-WORDS = [f"STORY_{i:02d} " for i in range(60)]-FOLLOW_UP = "also mention the tests"---def created(rid: str) -> dict:- return {"type": "response.created", "response": {"id": rid, "status": "in_progress"}}---def delta(text: str) -> dict:- return {"type": "response.output_text.delta", "item_id": "msg", "output_index": 0, "content_index": 0, "delta": text}---def message(text: str) -> dict:- return {"type": "response.output_item.done", "item": {- "type": "message", "id": "msg", "status": "completed", "role": "assistant",- "content": [{"type": "output_text", "text": text, "annotations": []}]}}---def ended(rid: str, reason: str | None = None) -> dict:- response = {"id": rid, "status": "incomplete" if reason else "completed", "usage": dict(USAGE)}- if reason:- response["incomplete_details"] = {"reason": reason}- return {"type": "response.incomplete" if reason else "response.completed", "response": response}---def reply(rid: str, text: str) -> list[dict]:- return [created(rid), delta(text), message(text), ended(rid)]---def story(rid: str) -> list[dict]:- return [created(rid)] + [delta(w) for w in WORDS] + [message("".join(WORDS)), ended(rid)]---def drain(fd, seconds):- import select-- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios-- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def wait_for(fd, needle, seconds):- out = b""- end = time.time() + seconds- while time.time() < end:- out += drain(fd, 0.3)- if needle.encode() in out:- return out- return None---def type_line(fd, text):- # Keep reading while typing: a TUI whose pty output nobody drains blocks- # on its next write and never sees the keys.- for ch in text:- os.write(fd, ch.encode())- drain(fd, 0.01)- drain(fd, 0.4) # past the composer's paste-burst window, so Enter sends- os.write(fd, b"\r")---def spawn(cwd, env_extra, unset):- import pty-- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- for name in unset:- os.environ.pop(name, None)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo", "--model", "codex/gpt-6-sol", "--no-telemetry"])- resize(fd, ROWS, COLS)- return pid, fd---def reap(pid, fd):- import signal-- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for call in (lambda: os.kill(pid, signal.SIGKILL), lambda: os.waitpid(pid, 0)):- try:- call()- except OSError:- pass---def workspace(tmp, port):- 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": "steer-mock", "account_id": "acct-steer"}}, 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, "session_recap": 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_FLEET": "off",- "GRAFF_NO_TELEMETRY": "1",- "GRAFF_MCP_CONFIG": empty_mcp,- "GRAFF_LEARN_AUTO": "off",- }- unset = tuple(- name- for name in os.environ- if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")- and name not in env- )- return env, unset---def session(mock: CodexMock, flow) -> str | None:- port = mock.start()- try:- with tempfile.TemporaryDirectory(prefix="graff-tui-steer6-") as tmp:- env, unset = workspace(tmp, port)- pid, fd = spawn(tmp, env, unset)- try:- boot(fd)- return flow(fd)- finally:- reap(pid, fd)- finally:- mock.stop()---def user_texts(body: dict) -> list[str]:- """Every user message in a request's input (either content shape)."""- out = []- for item in body.get("input") or []:- if not isinstance(item, dict) or item.get("role") != "user":- continue- content = item.get("content")- if isinstance(content, str):- out.append(content)- elif isinstance(content, list):- out.extend(part.get("text", "") for part in content if isinstance(part, dict))- return out---def continuation() -> str | None:- def events(r: RecordedRequest) -> list[dict]:- return story("resp_story") if r.ordinal == 1 else reply(f"resp_after_{r.ordinal}", "SECOND_REPLY_OK")-- def on_steer(_r, steer, remaining):- cut = [e for e in remaining if e["type"] != "response.output_text.delta"][:1] # the reply's item, finished- return [{"type": "response.steer.accepted", "steer": {"id": "steer_1", "previous_response_id": steer["previous_response_id"]}}], (- cut + [ended("resp_story", "steered")] + reply("resp_cont", "CONTINUATION_OK"))-- mock = CodexMock(events_for_request=events, on_steer=on_steer, delay_for_request=lambda r: 0.12 if r.ordinal == 1 else 0.0)-- def flow(fd):- type_line(fd, "tell me a story")- if wait_for(fd, "STORY_03", 20.0) is None:- return "the first reply never started streaming"- type_line(fd, FOLLOW_UP)- if wait_for(fd, "CONTINUATION_OK", 30.0) is None:- return "the continuation never reached the screen"- type_line(fd, "what next")- if wait_for(fd, "SECOND_REPLY_OK", 20.0) is None:- return "the next turn never finished"- return None-- err = session(mock, flow)- if err:- return err- if len(mock.steers) != 1 or mock.steers[0].get("previous_response_id") != "resp_story" or mock.steers[0].get("input") != FOLLOW_UP:- return f"expected one steer on resp_story carrying the follow-up, got {mock.steers}"- requests = mock.recorded_requests()- if len(requests) != 2:- return f"expected the story and the next turn (no rebuilt reply), got {len(requests)} requests"- full = requests[1].body- texts = user_texts(full)- if texts.count(FOLLOW_UP) != 1:- return f"the next turn's input carried the steer {texts.count(FOLLOW_UP)} times: {texts}"- items = json.dumps(full.get("input"))- at_story, at_steer, at_cont = items.find("STORY_00"), items.find(FOLLOW_UP), items.find("CONTINUATION_OK")- if not (0 <= at_story < at_steer < at_cont):- return "history does not hold the steer between the cut reply and the continuation"- return None---def pending() -> str | None:- steer_text = "keep it to one line"- thinking = [{"type": "response.reasoning_summary_text.delta", "item_id": "rs", "output_index": 0, "summary_index": 0, "delta": "thinking "}] * 25- call = {"type": "response.output_item.done", "item": {- "type": "function_call", "id": "fc_1", "call_id": "call_todo", "name": "todo_read", "arguments": "{}", "status": "completed"}}-- def events(r: RecordedRequest) -> list[dict]:- if r.ordinal == 1:- return [created("resp_tool")] + thinking + [call, ended("resp_tool")]- return reply(f"resp_after_{r.ordinal}", "PENDING_APPLIED_OK")-- def on_steer(_r, steer, remaining):- held = {"type": "response.steer.pending", "steer": {"id": "steer_1", "previous_response_id": steer["previous_response_id"]},- "reason": "waiting_for_required_input",- "required_input": [{"type": "function_call_output", "call_id": "call_todo", "name": "todo_read"}]}- return [{"type": "response.steer.accepted", "steer": {"id": "steer_1", "previous_response_id": steer["previous_response_id"]}}], remaining + [held]-- mock = CodexMock(events_for_request=events, on_steer=on_steer, delay_for_request=lambda r: 0.15 if r.ordinal == 1 else 0.0)- timing = {}-- def flow(fd):- type_line(fd, "draft a short plan")- drain(fd, 1.2) # the reply is thinking- type_line(fd, steer_text)- timing["steered"] = time.time()- if wait_for(fd, "PENDING_APPLIED_OK", 40.0) is None:- return "the tool output request never finished"- timing["done"] = time.time()- return None-- err = session(mock, flow)- if err:- return err- if len(mock.steers) != 1:- return f"expected one steer, got {len(mock.steers)}"- requests = mock.recorded_requests()- if len(requests) != 2:- return f"expected the tool call and its output request, got {len(requests)} requests"- out = requests[1].body- if out.get("previous_response_id") != "resp_tool":- return f"the tool output chained on {out.get('previous_response_id')!r}, not the steered response"- if "call_todo" not in json.dumps(out.get("input")):- return "the output request did not carry the tool output"- if steer_text in json.dumps(out.get("input")):- return "the output request repeated a steer the server prepends itself"- if timing["done"] - timing["steered"] > 20:- return f"the tool loop waited {timing['done'] - timing['steered']:.0f}s for a continuation that never comes"- return None---def failed() -> str | None:- def events(r: RecordedRequest) -> list[dict]:- return story("resp_story") if r.ordinal == 1 else reply(f"resp_next_{r.ordinal}", "REQUEUED_OK")-- def on_steer(_r, steer, remaining):- return [{"type": "response.steer.failed", "steer": {"previous_response_id": steer["previous_response_id"]},- "error": {"code": "invalid_input", "type": "invalid_request_error", "message": "mock rejection"}}], remaining-- mock = CodexMock(events_for_request=events, on_steer=on_steer, delay_for_request=lambda r: 0.12 if r.ordinal == 1 else 0.0)-- def flow(fd):- type_line(fd, "tell me a story")- if wait_for(fd, "STORY_03", 20.0) is None:- return "the first reply never started streaming"- type_line(fd, FOLLOW_UP)- if wait_for(fd, "REQUEUED_OK", 40.0) is None:- return "the rejected follow-up never ran"- return None-- err = session(mock, flow)- if err:- return err- requests = mock.recorded_requests()- if len(requests) != 2:- return f"expected the story and the follow-up's own request, got {len(requests)}"- if user_texts(requests[1].body).count(FOLLOW_UP) != 1:- return "the follow-up request did not carry the rejected steer exactly once"- return None---def main():- if not os.path.exists(BIN):- print(f"tui-steer-gpt6: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-steer-gpt6: no pty support here — skipping")- return 0- failures = 0- for name, case in (("continuation", continuation), ("pending", pending), ("failed", failed)):- err = case()- if err:- failures += 1- print(f" ✗ gpt-6 steer {name}: {err}")- else:- print(f" ✓ gpt-6 steer {name}")- return 1 if failures else 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-steer-mid-reply.py b/scripts/test-tui-steer-mid-reply.pydeleted file mode 100644index f2a7a405..00000000--- a/scripts/test-tui-steer-mid-reply.py+++ /dev/null@@ -1,235 +0,0 @@-#!/usr/bin/env python3-"""Live proof that a follow-up typed in the TUI while the reply streams joins-the running turn: the streaming reply is superseded and the request rebuilt.--Against the real binary under a pty, with a mock provider streaming slowly:-- 1. boots `graff tui --yolo --model codex` pointed at scripts/codex_ws_mock,- 2. sends a prompt; the first reply streams a long story a word at a time,- 3. mid-stream, types a follow-up and presses Enter,- 4. asserts the second request carries the follow-up and none of the- abandoned partial story, and that its reply reaches the screen.--Usage: python3 scripts/test-tui-steer-mid-reply.py [path/to/graff]-Exit 0 = pass. Skips (exit 0, notice) with no pty support.-"""--from __future__ import annotations--import json-import os-import re-import sys-import tempfile-import time--from codex_ws_mock import USAGE, CodexMock, RecordedRequest, turn_events--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 20.0-ROWS, COLS = 40, 110-WORDS = [f"PARTIAL_STORY_{i:02d} " for i in range(60)]-FOLLOW_UP = "also mention the tests"---def story_events() -> list[dict]:- events: list[dict] = [- {"type": "response.output_text.delta", "item_id": "msg_story", "output_index": 0, "content_index": 0, "delta": w}- for w in WORDS- ]- events.append({- "type": "response.output_item.done",- "item": {- "type": "message",- "id": "msg_story",- "status": "completed",- "role": "assistant",- "content": [{"type": "output_text", "text": "".join(WORDS), "annotations": []}],- },- })- events.append({"type": "response.completed", "response": {"id": "resp_story", "usage": dict(USAGE)}})- return events---def events(request: RecordedRequest) -> list[dict]:- if request.ordinal == 1:- return story_events()- done = turn_events(f"resp_steer_{request.ordinal}")- done[0]["item"]["content"][0]["text"] = "STEERED_REPLY_DONE"- return done---def drain(fd, seconds):- import select-- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios-- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def wait_for(fd, needle, seconds):- out = b""- end = time.time() + seconds- while time.time() < end:- out += drain(fd, 0.3)- if needle.encode() in out:- return out- return None---def spawn(cwd, env_extra, unset):- import pty-- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- for name in unset:- os.environ.pop(name, None)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"])- resize(fd, ROWS, COLS)- return pid, fd---def reap(pid, fd):- import signal-- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for call in (lambda: os.kill(pid, signal.SIGKILL), lambda: os.waitpid(pid, 0)):- try:- call()- except OSError:- pass---def full_frame(fd):- """Screen rows, in order, from a FORCED full repaint (see #529's probe)."""- resize(fd, ROWS - 1, COLS)- drain(fd, 0.4)- resize(fd, ROWS, COLS)- stream = drain(fd, 1.5)- frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(frame) < 2:- return None- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---def workspace(tmp, port):- 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": "steer-mock", "account_id": "acct-steer"}}, 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, "session_recap": 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",- }- unset = tuple(- name- for name in os.environ- if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")- and name not in env- )- return env, unset----def run():- mock = CodexMock(events_for_request=events, delay_for_request=lambda r: 0.12 if r.ordinal == 1 else 0.0)- port = mock.start()- try:- with tempfile.TemporaryDirectory(prefix="graff-tui-steer-") as tmp:- env, unset = workspace(tmp, port)- pid, fd = spawn(tmp, env, unset)- try:- boot(fd)- os.write(fd, b"tell me a story\r")- if wait_for(fd, "PARTIAL_STORY_03", 20.0) is None:- return "the first reply never started streaming"- for ch in FOLLOW_UP:- os.write(fd, ch.encode())- time.sleep(0.01)- os.write(fd, b"\r")- if wait_for(fd, "STEERED_REPLY_DONE", 30.0) is None:- return "the rebuilt reply never reached the screen"- finally:- reap(pid, fd)- requests = mock.recorded_requests()- if len(requests) != 2:- return f"expected the story request and one rebuilt request, got {len(requests)}"- rebuilt = json.dumps(requests[1].body)- if FOLLOW_UP not in rebuilt:- return "the rebuilt request did not carry the follow-up"- if "PARTIAL_STORY_" in rebuilt:- return "the abandoned partial story leaked into the rebuilt request"- return None- finally:- mock.stop()---def main():- if not os.path.exists(BIN):- print(f"tui-steer: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-steer: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ tui steer: {err}")- return 1- print(" ✓ tui steer: a follow-up typed mid-stream joins the turn and rebuilds the reply")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-stream-markdown.py b/scripts/test-tui-stream-markdown.pydeleted file mode 100644index 7ac974a9..00000000--- a/scripts/test-tui-stream-markdown.py+++ /dev/null@@ -1,343 +0,0 @@-#!/usr/bin/env python3-"""Live proof: the fullscreen TUI's markdown pipeline is safe under STREAMING.--Against the real binary, under a pty, with a mock codex backend that streams the-answer as `response.output_text.delta` events split every 1-3 codepoints — so-the splits land mid-word, mid-escape-sequence, mid-code-fence and mid-inline-marker — the probe photographs the screen TWICE:-- * mid-turn, while a slow tool runs, so the PENDING row's live tail is showing- raw model bytes as they arrive, and- * after the turn, when the assistant row has settled through the markdown- renderer.--Both frames must be clean: no carriage return the model sent (a bare CR rewinds-the row and everything after it overwrites), none of the model's OWN escape-sequences (a smuggled SGR repaints the pager), no U+FFFD from a delta that cut a-glyph in half, and no text lost around any of it. The settled frame must also-show the fenced block as code with its markers hidden.--Usage: python3 scripts/test-tui-stream-markdown.py [path/to/graff]-Exit 0 = pass. Skips (exit 0, notice) with no pty support or no binary.-"""--from __future__ import annotations--import json-import os-import re-import sys-import tempfile-import time--from codex_ws_mock import CodexMock, RecordedRequest--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 20.0-ANSWER_MAX = 30.0-ROWS, COLS = 40, 110--# A colour no graff theme paints, so finding it on the wire can only mean the-# model's own escape survived the renderer.-SMUGGLED = "\x1b[38;2;7;7;7m"-# Streamed as deltas and shown by the PENDING row's live tail while a tool runs.-# The hostile bytes sit in the last four lines — that is the tail window.-LIVE = (- "STREAMMD_START\r\n"- "padding prose line\r\n"- "wiped" + SMUGGLED + "byte and a bare\rreturn\r\n"- "日本語 \U0001f680 STREAMMD_LIVE\r\n"-)-# The settled assistant row, rendered through the markdown pipeline.-ANSWER = (- "Here is **bold** and `code` with 日本語 \U0001f680.\r\n"- "\r\n"- "```zig\r\n"- "const answer: u32 = 0x1f; // 日本語 \U0001f680\r\n"- "```\r\n"- "wiped" + SMUGGLED + "byte and a bare\rreturn\r\n"- "STREAMMD_OK\r\n"-)---def deltas(text: str) -> list[dict]:- """Cut the text into 1-3 codepoint deltas — the finest split a JSON event- stream can express. Boundaries land mid-word, mid-escape-sequence, mid-fence- and mid-inline-marker. (A split INSIDE a UTF-8 sequence is a transport-level- event a JSON string cannot carry; the unit suite fuzzes that byte-wise.)"""- out, i, n = [], 0, 1- while i < len(text):- piece = text[i : i + n]- i += n- n = n % 3 + 1- out.append({"type": "response.output_text.delta", "delta": piece})- return out---def completed(response_id: str) -> dict:- return {- "type": "response.completed",- "response": {- "id": response_id,- "usage": {- "input_tokens": 10,- "input_tokens_details": {"cached_tokens": 0},- "output_tokens": 10,- "total_tokens": 20,- },- },- }---def events(request: RecordedRequest) -> list[dict]:- if request.ordinal == 1:- # Prose first, then a slow tool call: the turn stays open long enough to- # photograph the live tail, which is where raw model bytes land.- return [- *deltas(LIVE),- {- "type": "response.output_item.done",- "item": {- "type": "function_call",- "id": "fc_streammd",- "call_id": "call_streammd",- "name": "bash",- "arguments": json.dumps({"command": "sleep 6"}),- "status": "completed",- },- },- completed("resp_streammd_live"),- ]- item = {- "type": "message",- "id": "msg_streammd",- "status": "completed",- "role": "assistant",- "content": [{"type": "output_text", "text": ANSWER, "annotations": []}],- }- return [- *deltas(ANSWER),- {"type": "response.output_item.done", "item": item},- completed("resp_streammd_done"),- ]---def drain(fd, seconds):- import select-- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios-- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def wait_for(fd, needle, seconds):- out = b""- end = time.time() + seconds- while time.time() < end:- out += drain(fd, 0.3)- if needle.encode() in out:- return out- return None---def spawn(cwd, env_extra, unset):- import pty-- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- for name in unset:- os.environ.pop(name, None)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"])- resize(fd, ROWS, COLS)- return pid, fd---def reap(pid, fd):- import signal-- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for call in (lambda: os.kill(pid, signal.SIGKILL), lambda: os.waitpid(pid, 0)):- try:- call()- except OSError:- pass---def full_frame(fd):- """The bytes of one FORCED full repaint, plus its visible rows."""- resize(fd, ROWS - 1, COLS)- drain(fd, 0.4)- resize(fd, ROWS, COLS)- stream = drain(fd, 1.5)- parts = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(parts) < 2:- return None, None- raw = parts[1]- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", raw)- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return raw, [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---def workspace(tmp, port):- 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": "streammd-mock", "account_id": "acct-md"}}, 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",- }- unset = tuple(- name- for name in os.environ- if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")- and name not in env- )- return env, unset---def hostile_clean(raw, body, where):- """The three ways raw model bytes corrupt a row, checked on one frame."""- # 1. no carriage return the model sent — the pager's own row breaks are- # \r\n (doubled to \r\r\n by the pty's ONLCR), so a CR that does not lead- # into a line feed can only have come from the model's text.- if re.search(rb"\r(?!\r*\n)", raw):- return f"{where}: a bare carriage return from the model reached the frame"- # 2. none of the model's own escapes, as bytes or as leftover text.- if SMUGGLED.encode() in raw:- return f"{where}: the model's own SGR escape reached the terminal"- if "[38;2;7;7;7m" in body:- return f"{where}: the model's escape landed as literal text instead"- # 3. every glyph whole on both sides of a delta boundary.- if "�" in body:- return f"{where}: a delta boundary left a replacement character on screen"- for glyph in ("日本語", "\U0001f680"):- if glyph not in body:- return f"{where}: {glyph!r} did not survive the stream"- if "wiped" not in body or "byte and a bare" not in body:- return f"{where}: text around the smuggled escape was lost"- return None---def check_live(raw, rows):- body = "\n".join(rows)- if "STREAMMD_LIVE" not in body:- return f"the live tail never showed the streamed prose: {rows[:12]!r}"- return hostile_clean(raw, body, "live tail")---def check_settled(raw, rows):- body = "\n".join(rows)- if "STREAMMD_OK" not in body:- return f"the streamed answer never settled on screen: {rows[:12]!r}"- err = hostile_clean(raw, body, "settled row")- if err:- return err- # 4. the fence rendered as code: tokens on screen, markers hidden.- if "const answer" not in body.replace(" ", " "):- return "the fenced code line never rendered"- if "```" in body:- return "a raw fence marker leaked onto the screen"- return None---def run():- mock = CodexMock(events_for_request=events)- port = mock.start()- try:- with tempfile.TemporaryDirectory(prefix="graff-stream-md-") as tmp:- env, unset = workspace(tmp, port)- pid, fd = spawn(tmp, env, unset)- try:- boot(fd)- os.write(fd, b"stream some markdown\r")- # Mid-turn: the tool is sleeping, so the live tail is on screen.- if wait_for(fd, "STREAMMD_LIVE", ANSWER_MAX) is None:- return "the live tail never showed the streamed prose"- raw, rows = full_frame(fd)- if rows is None:- return "no full repaint to read the live tail from"- err = check_live(raw, rows)- if err:- return err- # …and then the settled assistant row.- if wait_for(fd, "STREAMMD_OK", ANSWER_MAX) is None:- return "the turn never produced its streamed answer"- drain(fd, 1.0)- raw, rows = full_frame(fd)- if rows is None:- return "no full repaint to read the settled row from"- return check_settled(raw, rows)- finally:- reap(pid, fd)- finally:- mock.stop()---def main():- if not os.path.exists(BIN):- print(f"tui-stream-markdown: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-stream-markdown: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ stream markdown: {err}")- return 1- print(" ✓ stream markdown: live tail AND settled row survive chunked deltas — no CR, no smuggled SGR, glyphs whole")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/test-tui-typed-events.py b/scripts/test-tui-typed-events.pydeleted file mode 100644index eb712859..00000000--- a/scripts/test-tui-typed-events.py+++ /dev/null@@ -1,342 +0,0 @@-#!/usr/bin/env python3-"""Live proof for #551: the fullscreen TUI renders tool activity from the-engine's TYPED events, not from glyphs scraped out of rendered text.--Against the real binary, under a pty, with a mock provider driving a real tool-loop (no network, no model), the probe:-- 1. boots `graff tui --yolo --model codex` in a scratch cwd with an EMPTY MCP- config, pointed at scripts/codex_ws_mock,- 2. sends one prompt; the mock answers with a `read_file` function call and- then a final message whose FIRST LINE STARTS WITH "✓ " — exactly the shape- that used to be harvested into the transcript as a phantom tool row,- 3. forces a full repaint and reads the screen,- 4. asserts the real tool run folded into exactly ONE summary row,- 5. asserts the answer's "✓ " line appears exactly once and never as a tool- row, and that no raw "⚙ /✓ tool | preview" sink line reached the screen.--Usage: python3 scripts/test-tui-typed-events.py [path/to/graff]-Exit 0 = pass. Skips (exit 0, notice) with no pty support.-"""--from __future__ import annotations--import json-import os-import re-import sys-import tempfile-import time--from codex_ws_mock import CodexMock, RecordedRequest--BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_MAX = 20.0-ANSWER_MAX = 30.0-ROWS, COLS = 40, 110--# The answer deliberately opens with a status glyph: this is the phantom-row-# shape. It must render as ANSWER text, once, and never as a tool row.-GLYPH_LINE = "✓ verified TYPEDEV_OK"-FINAL_REPLY = GLYPH_LINE + "\nall three checks passed"-NOTE_BODY = "typed-events-probe payload"---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_typed_read",- "call_id": "call_typed_read",- "name": "read_file",- "arguments": json.dumps({"path": "note.txt"}),- "status": "completed",- },- "resp_typed_read",- )- return response_events(message_item(FINAL_REPLY, "msg_typed_done"), "resp_typed_done")---def drain(fd, seconds):- import select-- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def resize(fd, rows, cols):- import fcntl- import struct- import termios-- fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))---def boot(fd):- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.5)- return out---def wait_for(fd, needle, seconds):- out = b""- end = time.time() + seconds- while time.time() < end:- out += drain(fd, 0.3)- if needle.encode() in out:- return out- return None---def spawn(cwd, env_extra, unset):- import pty-- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- for name in unset:- os.environ.pop(name, None)- os.environ.update(env_extra)- os.execv(BIN, [BIN, "tui", "--yolo", "--model", "codex", "--no-telemetry"])- resize(fd, ROWS, COLS)- return pid, fd---def reap(pid, fd):- import signal-- try:- os.write(fd, b"\x11") # Ctrl+Q- drain(fd, 2.0)- except OSError:- pass- for call in (lambda: os.kill(pid, signal.SIGKILL), lambda: os.waitpid(pid, 0)):- try:- call()- except OSError:- pass---def full_frame(fd):- """Screen rows, in order, from a FORCED full repaint (see #529's probe)."""- resize(fd, ROWS - 1, COLS)- drain(fd, 0.4)- resize(fd, ROWS, COLS)- stream = drain(fd, 1.5)- frame = stream.rsplit(b"\x1b[2J\x1b[H", 1)- if len(frame) < 2:- return None- text = re.sub(rb"\x1b\][^\x07\x1b]*(\x07|\x1b\\)", b"", frame[1])- text = re.sub(rb"\x1b\[[0-9;?<>]*[a-zA-Z]", b"", text)- return [ln.decode(errors="replace") for ln in text.split(b"\r\n")]---def workspace(tmp, port):- with open(os.path.join(tmp, "note.txt"), "w", encoding="utf-8") as fh:- fh.write(NOTE_BODY)- 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": "typed-events-mock", "account_id": "acct-typed"}}, 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",- }- unset = tuple(- name- for name in os.environ- if (name.startswith("GRAFF_") or name.startswith("CODEX_") or name == "NO_COLOR")- and name not in env- )- return env, unset---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):- body = "\n".join(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) 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()- # 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:- return f"the answer's '✓ ' line appears {len(answers)} time(s): {answers!r}"- # 3. ...and it is not the summary row itself.- if GLYPH_LINE in summary:- return "the answer line was folded into the tool summary"- # 4. No raw sink line ("⚙ read note.txt") reached the screen: that is- # hostedEmit's rendering, which the TUI must no longer consume.- for ln in rows:- if ln.strip().startswith("⚙ "):- return f"a raw sink glyph line leaked into the transcript: {ln!r}"- return None---def check_expanded(rows):- """The card the fold opens onto is built from FIELDS: the engine's tool- name, its argument, and the result preview — none of it recovered by- splitting a rendered line."""- 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}"- # The answer stayed outside the card.- if GLYPH_LINE in rows[head] or GLYPH_LINE in rows[head + 1]:- return "the answer line is inside the tool card"- return None---def run():- mock = CodexMock(events_for_request=events)- port = mock.start()- try:- with tempfile.TemporaryDirectory(prefix="graff-typed-events-") as tmp:- env, unset = workspace(tmp, port)- pid, fd = spawn(tmp, env, unset)- try:- boot(fd)- os.write(fd, b"read note.txt then report\r")- if wait_for(fd, "TYPEDEV_OK", ANSWER_MAX) is None:- return "the turn never produced its final answer"- drain(fd, 1.0)- rows = full_frame(fd)- if rows is None:- return "no full repaint to read the screen from"- err = check_folded(rows)- if err:- return err- # Open the group: a plain click on the summary row. What comes- # back is the card composed from the typed fields.- top = summary_rows(rows)[0] + 1 # SGR rows are 1-based- os.write(fd, f"\x1b[<0;5;{top}M".encode())- drain(fd, 0.3)- os.write(fd, f"\x1b[<0;5;{top}m".encode())- drain(fd, 0.6)- opened = full_frame(fd)- if opened is None:- return "no full repaint after expanding the tool group"- err = check_expanded(opened)- if err:- return err- finally:- reap(pid, fd)- requests = mock.recorded_requests()- if len(requests) != 2:- return f"expected a two-request tool loop, got {len(requests)}"- return None- finally:- mock.stop()---def main():- if not os.path.exists(BIN):- print(f"tui-typed-events: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-typed-events: no pty support here — skipping")- return 0- err = run()- if err:- print(f" ✗ typed events: {err}")- return 1- print(" ✓ typed events: one folded tool summary, answer glyph line rendered once, no scraped lines")- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/scripts/tui-pty-guard.py b/scripts/tui-pty-guard.pydeleted file mode 100644index 0316058b..00000000--- a/scripts/tui-pty-guard.py+++ /dev/null@@ -1,314 +0,0 @@-#!/usr/bin/env python3-"""TUI lifecycle guard: real-binary pty checks, grok-build-inspired, no model calls.--Three invariants, each against the actual graff binary under a pty:-- A. mode-balance Every DEC private mode the TUI latches (CSI ? Pm h) is reset- (CSI ? Pm l) by clean quit, the kitty keyboard push/pop depth- is balanced, and the alt-screen leave (?1049l) is emitted in- the restore tail. grok-build proves restore correctness with- a ModeTracker + byte-transparency e2e tests; this is the- same invariant as a gate.- B. hostile-input The historical crasher corpus (10+-digit CSI params #545,- separator-split debris #546, a bracketed paste whose 201~- terminator is split across reads #532/#536/#548) is fed to a- live session; the process must survive, recover the- composer, and still quit cleanly with a balanced restore.- C. kill-restore SIGTERM mid-session still emits the restore tail — the- terminal is never left raw (#535/#547 family).--Usage: python3 scripts/tui-pty-guard.py [path/to/graff] (default zig-out/bin/graff)-Exit 0 = all pass; nonzero prints the failing invariant. Skips (exit 0, notice)-when no pty can be allocated (rare CI sandboxes).--Known limitation: check B's echo probe proves liveness, not paste-latch-semantics (a latched composer still echoes typed bytes). Latch behavior is-pinned by the TUI unit suite (zig build tui-test); this guard owns the-process-level invariants a unit test cannot reach.-"""-import json-import os-import re-import signal-import sys-import tempfile-import time--# Absolutized BEFORE any fork: the child chdirs to its scratch workspace, so a-# relative path resolved there is a silent boot failure, not a graff finding.-BIN = os.path.abspath(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff")-BOOT_WAIT = 3.0-BOOT_MAX = 15.0 # under load (tier-1 right after a test compile) 3s is not enough-QUIT_WAIT = 4.0---def boot(fd):- """Drain until the alt-screen enter proves the TUI is up (readiness, not a- fixed sleep — a loaded machine boots slower than any constant we pick)."""- out = b""- end = time.time() + BOOT_MAX- while time.time() < end:- out += drain(fd, 0.3)- if b"\x1b[?1049h" in out:- return out + drain(fd, 1.0) # let the first full paint land- return out---def spawn(cwd, env_extra, entry="tui"):- import pty- pid, fd = pty.fork()- if pid == 0:- os.chdir(cwd)- os.environ.update(env_extra)- if env_extra.get("GRAFF_TEST_NO_CREDENTIALS"):- for name in PROVIDER_ENV:- os.environ.pop(name, None)- os.execv(BIN, [BIN, entry, "--yolo"])- return pid, fd---def drain(fd, seconds):- # select-gated: a pty fd blocks on read when the child is quiet, and a- # blocking read here would hang the whole guard on any wedged state —- # exactly the states this guard exists to catch.- import select- out = b""- end = time.time() + seconds- while time.time() < end:- r, _, _ = select.select([fd], [], [], min(0.1, max(end - time.time(), 0.01)))- if not r:- continue- try:- chunk = os.read(fd, 65536)- except OSError:- break- if not chunk:- break- out += chunk- return out---def reap(pid, timeout=6.0):- end = time.time() + timeout- while time.time() < end:- r, status = os.waitpid(pid, os.WNOHANG)- if r != 0:- return status- time.sleep(0.1)- os.kill(pid, signal.SIGKILL)- os.waitpid(pid, 0)- return None---MODE_RE = re.compile(rb"\x1b\[\?([0-9;]+)([hl])")-KITTY_PUSH_RE = re.compile(rb"\x1b\[>[0-9;]*u")-KITTY_POP_RE = re.compile(rb"\x1b\[<[0-9;]*u")---# Modes whose TERMINAL DEFAULT is enabled: autowrap (7) and cursor visible-# (25). For these the TUI's restore direction is `h`, so the invariant is-# "final state == default", not "every h has a later l" (grok-build's-# ModeTracker records the same distinction as latched-vs-default).-DEFAULT_ON = {b"7", b"25"}---def mode_imbalance(stream):- """DEC modes whose final state differs from the terminal default, and the kitty push/pop depth."""- final = {}- for m in MODE_RE.finditer(stream):- for num in m.group(1).split(b";"):- final[num] = m.group(2)- wrong = [int(n) for n, op in final.items()- if (op == b"h") != (n in DEFAULT_ON)]- depth = len(KITTY_PUSH_RE.findall(stream)) - len(KITTY_POP_RE.findall(stream))- return sorted(wrong), max(depth, 0)---PROVIDER_ENV = {- "ANTHROPIC_API_KEY", "CODEGRAFF_API_KEY", "DEEPSEEK_API_KEY",- "OPENAI_API_KEY", "MINIMAX_API_KEY", "XIAOMI_API_KEY", "KILO_API_KEY",- "GROQ_API_KEY", "CEREBRAS_API_KEY", "MISTRAL_API_KEY", "KIMI_API_KEY",- "MOONSHOT_API_KEY", "XAI_API_KEY", "ZAI_API_KEY", "AI_GATEWAY_API_KEY",- "OPENROUTER_API_KEY", "FUGU_API_KEY", "FIREWORKS_API_KEY", "MLX_API_KEY",- "LMSTUDIO_API_KEY", "CODEX_DISABLED", "MYROUTER_API_KEY",-}---def fresh_ws():- ws = tempfile.mkdtemp(prefix="tui-guard-")- empty = os.path.join(ws, "empty-mcp.json")- with open(empty, "w") as f:- json.dump({"mcpServers": {}}, f)- return ws, {"GRAFF_MCP_CONFIG": empty, "GRAFF_LEARN_AUTO": "off"}---def fresh_no_credentials():- ws, env = fresh_ws()- home = os.path.join(ws, "home")- os.makedirs(os.path.join(home, ".codex"))- env.update({"HOME": home, "CODEX_HOME": os.path.join(home, ".codex"),- "TERM": "xterm", "GRAFF_TEST_NO_CREDENTIALS": "1"})- if sys.platform == "darwin":- shim_dir = os.path.join(ws, "bin")- os.makedirs(shim_dir)- shim = os.path.join(shim_dir, "security")- with open(shim, "w") as f:- f.write("#!/bin/sh\nexit 44\n")- os.chmod(shim, 0o755)- env["PATH"] = shim_dir + os.pathsep + os.environ.get("PATH", "")- return ws, env---def quit_seq(fd):- os.write(fd, b"\x11") # Ctrl+Q — single byte, parser-independent---def quit_and_reap(fd, pid, collected):- """Escalating quit: Ctrl+Q, then Escape+Ctrl+Q (a toast or composer text- occasionally swallows the first one under load — the ~10% flake), then- double Ctrl+C. Returns (status_or_None, all_bytes)."""- out = collected- for attempt in (b"\x11", b"\x1b\x1b\x11", b"\x03\x03"):- os.write(fd, attempt)- out += drain(fd, QUIT_WAIT)- end = time.time() + 2.0- while time.time() < end:- r, status = os.waitpid(pid, os.WNOHANG)- if r != 0:- return status, out- time.sleep(0.1)- status = reap(pid)- return status, out---def check_a():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- out = boot(fd)- status, out = quit_and_reap(fd, pid, out)- latched, depth = mode_imbalance(out)- if status is None:- return "A: quit did not exit within the window"- if latched:- return f"A: modes latched but never reset by clean quit: {latched}"- if depth != 0:- return f"A: kitty keyboard push/pop unbalanced (depth {depth})"- if b"\x1b[?1049h" in out and b"\x1b[?1049l" not in out:- return "A: alt-screen entered but never left"- return None---HOSTILE = [- b"\x1b[99999999999999999999;1u", # 545: 20-digit CSI-u param- b"\x1b[9999999999;1u", # 545: shortest overflow- b"\x1b[<0;9999999999;5M", # 545: SGR mouse param overflow- b"\x1b[1;", # 546: CSI split at the separator- b"2A", # 546: ...tail arriving alone-]---def check_b():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- boot(fd)- out = b""- for payload in HOSTILE:- os.write(fd, payload)- out += drain(fd, 0.3)- # Split bracketed paste: body in one write, terminator split across two.- os.write(fd, b"\x1b[200~pasted words")- out += drain(fd, 0.3)- os.write(fd, b"\x1b[201")- out += drain(fd, 0.3)- os.write(fd, b"~")- out += drain(fd, 0.5)- # The composer must be functional again: typed text echoes.- os.write(fd, b"MARKER42")- out += drain(fd, 1.0)- alive = True- try:- r, _ = os.waitpid(pid, os.WNOHANG)- alive = r == 0- except ChildProcessError:- alive = False- if not alive:- return "B: process died on the hostile corpus"- if b"MARKER42" not in out:- return "B: composer did not recover after the split paste (echo lost)"- status, out = quit_and_reap(fd, pid, out)- if status is None:- return "B: quit did not exit after hostile input"- latched, depth = mode_imbalance(out)- return None---def check_c():- ws, env = fresh_ws()- pid, fd = spawn(ws, env)- out = boot(fd)- os.kill(pid, signal.SIGTERM)- out += drain(fd, 3.0)- status = reap(pid)- if b"\x1b[?1049h" in out and b"\x1b[?1049l" not in out:- return "C: SIGTERM left the alt-screen latched (terminal stranded)"- if b"\x1b[?2004h" in out and b"\x1b[?2004l" not in out:- return "C: SIGTERM left bracketed paste latched"- return None---def check_d():- """Credential failure after the early pager claim restores the shell."""- for entry in ("tui", "repl"):- ws, env = fresh_no_credentials()- pid, fd = spawn(ws, env, entry)- out = drain(fd, 5.0)- status = reap(pid)- if status is None:- return f"D/{entry}: fatal credential path did not exit"- if b"no API key found" not in out:- return f"D/{entry}: fatal login diagnostic was not visible on the tty"- latched, depth = mode_imbalance(out)- if latched:- return f"D/{entry}: terminal modes remained latched: {latched}"- if depth != 0:- return f"D/{entry}: kitty depth was {depth}"- if b"\x1b[?1049h" in out and b"\x1b[?1049l" not in out:- return f"D/{entry}: alt-screen was not released"- return None---def main():- if not os.path.exists(BIN):- print(f"tui-pty-guard: {BIN} not built — skipping")- return 0- try:- import pty # noqa: F401- except ImportError:- print("tui-pty-guard: no pty support here — skipping")- return 0- failures = []- for name, fn in (("mode-balance", check_a), ("hostile-input", check_b), ("kill-restore", check_c), ("missing-credentials", check_d)):- try:- err = fn()- except OSError as e:- # An OSError mid-check means the CHILD vanished (EIO on a dead pty)- # — that is a failure, not an environment skip. Only a fork-time- # failure counts as "no pty here".- if getattr(e, "errno", None) == 5:- err = f"{name}: pty EIO — the graff process died mid-check"- else:- print(f"tui-pty-guard: {name}: pty unavailable ({e}) — skipping")- continue- if err:- failures.append(err)- print(f" ✗ {name}: {err}")- else:- print(f" ✓ {name}")- if failures:- print(f"tui-pty-guard: {len(failures)} invariant(s) violated")- return 1- return 0---if __name__ == "__main__":- sys.exit(main())diff --git a/spec/README.md b/spec/README.mdindex 691b1d15..ec92a973 100644--- a/spec/README.md+++ b/spec/README.md@@ -48,7 +48,6 @@ properties are load-bearing, and a missed combination is a real bug.| `prompt_cache` | live | Process kernel. 48 cells. Sub never spawns. Child key isolated. Join restores root. || `prompt_prefix` | live | Process kernel. 6 cells. Names-only catalog, pin once. Skill events do not rewrite the prefix. || `prompt_stable` | live | Process kernel. 20 cells. OpenGauss must-nots. 5 keep. Compact re-pins. |-| `terminal_modes` | live | Process kernel. 14 sequences. Enable+restore returns to Idle. Pop floors. Alt last. || `path_confine` | live | Process kernel. Component walk; Escaped/Absolute absorb. 80 leases. || `shape` | live | 1728 cells. Hand ladder + explicit arm. Budget from remaining/cap/floor. || `score` | live | Process kernel. 1210 cells, 240 filed. Attempt never files; capture after join does. |@@ -65,7 +64,6 @@ python3 spec/conformance.py --diagram prompt_cachepython3 spec/conformance.py --diagram prompt_prefixpython3 spec/conformance.py --diagram prompt_stablepython3 spec/conformance.py --showcase # prefix cube + maximizing walk + key machine-python3 spec/conformance.py --diagram terminal_modespython3 spec/conformance.py --diagram path_confinepython3 spec/conformance.py --diagram transportpython3 spec/conformance.py --diagram score@@ -74,7 +72,7 @@ python3 spec/conformance.py --lean # lake build, if installedzig build test --summary none -Dtest-filter="spec/tool_catalog"```-Process kernels (`GoalLoop`, `PromptCache`, `PromptPrefix`, `PromptStable`, `TerminalModes`,+Process kernels (`GoalLoop`, `PromptCache`, `PromptPrefix`, `PromptStable`,`PathConfine`, `Transport`, `Score`) are finite `Event` / `step` diagrams,not Turing machines. Cube kernels (Shape, Provider, ToolCatalog) stay cubes.BashPolicy stays a command cube this turn. The shape of a subagent fleetdiff --git a/spec/conformance.py b/spec/conformance.pyindex 05b4ecc0..b53261d4 100644--- a/spec/conformance.py+++ b/spec/conformance.py@@ -68,10 +68,6 @@ from ref.bash_policy import check_properties as bash_check_propertiesfrom ref.bash_policy import payload as bash_model_payloadfrom ref.structured_output import check_properties as sox_check_propertiesfrom ref.structured_output import payload as sox_model_payload-from ref.terminal_modes import check_properties as term_check_properties-from ref.terminal_modes import payload as term_model_payload-from ref.terminal_modes import write_kernel_md as write_term_md-from ref.terminal_modes import kernel_md as term_kernel_mdROOT = Path(__file__).resolve().parentKERNELS = ROOT / "kernels"@@ -84,7 +80,6 @@ SHAPE_FIXTURE = KERNELS / "shape.json"SCORE_FIXTURE = KERNELS / "score.json"BASH_FIXTURE = KERNELS / "bash_policy.json"SOX_FIXTURE = KERNELS / "structured_output.json"-TERM_FIXTURE = KERNELS / "terminal_modes.json"CACHE_FIXTURE = KERNELS / "prompt_cache.json"PREFIX_FIXTURE = KERNELS / "prompt_prefix.json"LEAN_DIR = ROOT.parent / "lean-proofs"@@ -393,7 +388,6 @@ def check_bash() -> int: return _ref(bash_check_properties, "bash")def check_sox() -> int: return _ref(sox_check_properties, "sox")-def check_term() -> int: return _ref(term_check_properties, "term")def prefixes_first(p: str) -> list[str]:@@ -423,8 +417,6 @@ def export() -> list[Path]:write_score_md(KERNELS / "score.md"),_write(BASH_FIXTURE, bash_payload()),_write(SOX_FIXTURE, sox_model_payload()),- _write(TERM_FIXTURE, term_model_payload()),- write_term_md(KERNELS / "terminal_modes.md"),_write(CACHE_FIXTURE, cache_payload()),write_cache_md(KERNELS / "prompt_cache.md"),_write(PREFIX_FIXTURE, prefix_payload()),@@ -451,7 +443,6 @@ def check_fixtures() -> None:_same(SCORE_FIXTURE, score_payload(), "score")_same(BASH_FIXTURE, bash_payload(), "bash_policy")_same(SOX_FIXTURE, sox_model_payload(), "structured_output")- _same(TERM_FIXTURE, term_model_payload(), "terminal_modes")_same(CACHE_FIXTURE, cache_payload(), "prompt_cache")_same(PREFIX_FIXTURE, prefix_payload(), "prompt_prefix")from ref.prompt_stable import payload as stable_payload, kernel_md as stable_kernel_md@@ -462,7 +453,6 @@ def check_fixtures() -> None:("prompt_cache.md", cache_kernel_md),("prompt_prefix.md", prefix_kernel_md),("prompt_stable.md", stable_kernel_md),- ("terminal_modes.md", term_kernel_md),("path_confine.md", path_kernel_md),("transport.md", transport_kernel_md),("score.md", score_kernel_md),@@ -543,7 +533,6 @@ def main() -> int:mods = {"goal_loop": "ref.goal_loop", "prompt_cache": "ref.prompt_cache","prompt_prefix": "ref.prompt_prefix", "prompt_stable": "ref.prompt_stable",- "terminal_modes": "ref.terminal_modes","path_confine": "ref.path_confine", "transport": "ref.transport", "score": "ref.score",}path = mods.get(args.diagram)@@ -569,18 +558,17 @@ def main() -> int:n_sc = check_score()n_ba = check_bash()n_sx = check_sox()- n_tm = check_term()if args.export:paths = export()rel = ", ".join(p.relative_to(ROOT.parent).as_posix() for p in paths)- print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} cache={n_ck} prefix={n_px} stable={n_ps} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} sox={n_sx} term={n_tm} → {rel}")+ print(f"exported catalog={n_cat} transport={n_tr} provider={n_pr} goal={n_gl} cache={n_ck} prefix={n_px} stable={n_ps} path={n_pc} shape={n_sh} score={n_sc} bash={n_ba} sox={n_sx} → {rel}")else:check_fixtures()print(f"ok tool_catalog {n_cat} transport {n_tr} (1 ws) "f"provider {n_pr} goal_loop {n_gl} prompt_cache {n_ck} prompt_prefix {n_px} prompt_stable {n_ps} path_confine {n_pc} "f"shape {n_sh} score {n_sc} bash {n_ba} "- f"structured_output {n_sx} terminal_modes {n_tm}"+ f"structured_output {n_sx}")if args.lean:try_lean()diff --git a/spec/kernels/terminal_modes.json b/spec/kernels/terminal_modes.jsondeleted file mode 100644index 0f575ee7..00000000--- a/spec/kernels/terminal_modes.json+++ /dev/null@@ -1,127 +0,0 @@-{- "kernel": "terminal_modes",- "graff_enable": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m",- "graff_restore": "\u001b[?2026l\u001b[r\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",- "cells": [- {- "name": "empty",- "stream": "",- "deviations": [],- "depth": 0,- "balanced": true- },- {- "name": "graff-enable",- "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m",- "deviations": [- 7,- 25,- 1000,- 1003,- 1006,- 1049,- 2004- ],- "depth": 1,- "balanced": false- },- {- "name": "graff-lifecycle",- "stream": "\u001b[?1049h\u001b[?25l\u001b[?2004h\u001b[?1000h\u001b[?1003h\u001b[?1006h\u001b[?7l\u001b[>11u\u001b[>4;2m\u001b[?2026l\u001b[r\u001b[>4;0m\u001b[<u\u001b[?7h\u001b[?1006l\u001b[?1003l\u001b[?1000l\u001b[?2004l\u001b[?25h\u001b[?1049l",- "deviations": [],- "depth": 0,- "balanced": true- },- {- "name": "alt-only",- "stream": "\u001b[?1049h",- "deviations": [- 1049- ],- "depth": 0,- "balanced": false- },- {- "name": "paste-only",- "stream": "\u001b[?2004h",- "deviations": [- 2004- ],- "depth": 0,- "balanced": false- },- {- "name": "paste-balanced",- "stream": "\u001b[?2004h\u001b[?2004l",- "deviations": [],- "depth": 0,- "balanced": true- },- {- "name": "cursor-hidden",- "stream": "\u001b[?25l",- "deviations": [- 25- ],- "depth": 0,- "balanced": false- },- {- "name": "autowrap-off",- "stream": "\u001b[?7l",- "deviations": [- 7- ],- "depth": 0,- "balanced": false- },- {- "name": "kitty-unpopped",- "stream": "\u001b[>1u",- "deviations": [],- "depth": 1,- "balanced": false- },- {- "name": "kitty-overpop",- "stream": "\u001b[<u\u001b[<u\u001b[>1u",- "deviations": [],- "depth": 1,- "balanced": false- },- {- "name": "multi-num",- "stream": "\u001b[?1000;1006h\u001b[?1000l",- "deviations": [- 1006- ],- "depth": 0,- "balanced": false- },- {- "name": "relatch",- "stream": "\u001b[?1049h\u001b[?1049l\u001b[?1049h",- "deviations": [- 1049- ],- "depth": 0,- "balanced": false- },- {- "name": "default-noise",- "stream": "\u001b[?2026l\u001b[?25h\u001b[?7h",- "deviations": [],- "depth": 0,- "balanced": true- },- {- "name": "mouse-partial",- "stream": "\u001b[?1000h\u001b[?1003h\u001b[?1003l",- "deviations": [- 1000- ],- "depth": 0,- "balanced": false- }- ]-}diff --git a/spec/kernels/terminal_modes.md b/spec/kernels/terminal_modes.mddeleted file mode 100644index 51fd664c..00000000--- a/spec/kernels/terminal_modes.md+++ /dev/null@@ -1,24 +0,0 @@-# Kernel: terminal modes--Source of truth: `lean-proofs/Graff/TerminalModes.lean`.--Process kernel, not a Turing machine: `Op` / `step` is the mode map-plus kitty depth. The 14 named sequences are the snapshot. Enable then-restore returns to Idle; restore leaves the alt-screen last; pop floors-at zero. TUI layout, glyphs, and the font stay never.--The diagram is the projection of the live Python `step`. Emit it with-`python3 spec/conformance.py --diagram terminal_modes`.--```mermaid-stateDiagram-v2- [*] --> Idle- Active --> Alt: pop- Alt --> Active: push- Alt --> Idle: reset 1049- Deviant --> Idle: reset 2004- Idle --> Kitty: push- Idle --> Alt: set 1049- Idle --> Deviant: set 2004- Kitty --> Idle: pop-```diff --git a/spec/manifest.json b/spec/manifest.jsonindex 7aff0815..b1cfd36e 100644--- a/spec/manifest.json+++ b/spec/manifest.json@@ -101,16 +101,6 @@"cells_floor": 48,"cells_key": "cases"},- {- "id": "terminal_modes",- "lean": "lean-proofs/Graff/TerminalModes.lean",- "ref": "spec/ref/terminal_modes.py",- "fixture": "spec/kernels/terminal_modes.json",- "zig": "TUI/spec_terminal_modes_conformance.zig",- "impl": "TUI/run.zig:enable_seq+TUI/restore.zig:seq",- "cells_floor": 14,- "cells_key": "cells"- },{"id": "prompt_prefix","lean": "lean-proofs/Graff/PromptPrefix.lean",diff --git a/spec/ref/terminal_modes.py b/spec/ref/terminal_modes.pydeleted file mode 100644index e26f6b69..00000000--- a/spec/ref/terminal_modes.py+++ /dev/null@@ -1,247 +0,0 @@-"""Executable port of lean-proofs/Graff/TerminalModes.lean.--Also the semantics behind scripts/tui-pty-guard.py's mode-balance check:-one model gates the fixtures AND the live binary.-"""--from __future__ import annotations--import re-from pathlib import Path--DEFAULT_ON = (7, 25)--MODE_RE = re.compile(r"\x1b\[\?([0-9;]+)([hl])")-KITTY_PUSH_RE = re.compile(r"\x1b\[>[0-9;]*u")-KITTY_POP_RE = re.compile(r"\x1b\[<[0-9;]*u")--# graff's actual sequences (TUI/run.zig enable_seq / TUI/restore.zig seq).-# The Zig conformance test parses the live constants and diffs them against-# the fixture copy of these, so drift in either direction trips.-GRAFF_ENABLE = "\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m"-GRAFF_RESTORE = "\x1b[?2026l\x1b[r\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l"---def parse_ops(stream: str) -> list[tuple[str, int]]:- """Byte stream -> ordered op list: (set|reset, n) | (push|pop, 0)."""- ops: list[tuple[str, int]] = []- events = []- for m in MODE_RE.finditer(stream):- for num in m.group(1).split(";"):- events.append((m.start(), "set" if m.group(2) == "h" else "reset", int(num)))- for m in KITTY_PUSH_RE.finditer(stream):- events.append((m.start(), "push", 0))- for m in KITTY_POP_RE.finditer(stream):- events.append((m.start(), "pop", 0))- for _, kind, n in sorted(events):- ops.append((kind, n))- return ops---# Machine state: last-op-wins mode map + kitty depth (floored at 0).-State = tuple[dict[int, bool], int]-KERNEL_MD = Path(__file__).resolve().parents[1] / "kernels" / "terminal_modes.md"---def step(s: State, op: tuple[str, int]) -> State:- final, depth = s- kind, n = op- out = dict(final)- if kind == "set":- out[n] = True- elif kind == "reset":- out[n] = False- elif kind == "push":- return out, depth + 1- else:- return out, max(depth - 1, 0)- return out, depth---def fold(ops: list[tuple[str, int]]) -> State:- s: State = ({}, 0)- for op in ops:- s = step(s, op)- return s---def deviations(final: dict[int, bool]) -> list[int]:- return sorted(n for n, v in final.items() if v != (n in DEFAULT_ON))---def balanced(ops: list[tuple[str, int]]) -> bool:- final, depth = fold(ops)- return not deviations(final) and depth == 0---def restore_ops(ops: list[tuple[str, int]]) -> list[tuple[str, int]]:- final, depth = fold(ops)- devs = deviations(final)- flips = [("set" if n in DEFAULT_ON else "reset", n) for n in devs if n != 1049]- alt = [("reset", 1049)] if 1049 in devs else []- return [("pop", 0)] * depth + flips + alt---SEQUENCES: tuple[tuple[str, str], ...] = (- ("empty", ""),- ("graff-enable", GRAFF_ENABLE),- ("graff-lifecycle", GRAFF_ENABLE + GRAFF_RESTORE),- ("alt-only", "\x1b[?1049h"),- ("paste-only", "\x1b[?2004h"),- ("paste-balanced", "\x1b[?2004h\x1b[?2004l"),- ("cursor-hidden", "\x1b[?25l"),- ("autowrap-off", "\x1b[?7l"),- ("kitty-unpopped", "\x1b[>1u"),- ("kitty-overpop", "\x1b[<u\x1b[<u\x1b[>1u"),- ("multi-num", "\x1b[?1000;1006h\x1b[?1000l"),- ("relatch", "\x1b[?1049h\x1b[?1049l\x1b[?1049h"),- ("default-noise", "\x1b[?2026l\x1b[?25h\x1b[?7h"),- ("mouse-partial", "\x1b[?1000h\x1b[?1003h\x1b[?1003l"),-)---def check_properties() -> int:- n = 0- for name, stream in SEQUENCES:- n += 1- ops = parse_ops(stream)- # The generated restore always balances any reachable state.- if not balanced(ops + restore_ops(ops)):- raise ValueError(f"restore does not balance {name!r}")- # Restore of a restored stream is empty (byte transparency).- if restore_ops(ops + restore_ops(ops)):- raise ValueError(f"restore not idempotent for {name!r}")- # graff's committed restore balances graff's committed enable...- if not balanced(parse_ops(GRAFF_ENABLE + GRAFF_RESTORE)):- raise ValueError("graff lifecycle unbalanced")- # ...and its restore leaves the alt-screen LAST.- last_mode = list(MODE_RE.finditer(GRAFF_RESTORE))[-1]- if last_mode.group(1) != "1049" or last_mode.group(2) != "l":- raise ValueError("graff restore does not end with the alt-screen leave")- check_diagram()- return n---def payload() -> dict:- rows = []- for name, stream in SEQUENCES:- ops = parse_ops(stream)- final, depth = fold(ops)- rows.append({- "name": name,- "stream": stream,- "deviations": deviations(final),- "depth": depth,- "balanced": balanced(ops),- })- return {- "kernel": "terminal_modes",- "graff_enable": GRAFF_ENABLE,- "graff_restore": GRAFF_RESTORE,- "cells": rows,- }---def project(s: State) -> str:- final, depth = s- alt = bool(final.get(1049))- if depth == 0 and not deviations(final):- return "Idle"- if alt and depth >= 1:- return "Active"- if alt:- return "Alt"- if depth > 0:- return "Kitty"- return "Deviant"---def event_label(op: tuple[str, int]) -> str:- kind, n = op- if kind in ("push", "pop"):- return kind- return f"{kind} {n}"---def walk_ops(start: State, ops: list[tuple[str, int]]) -> list[tuple[State, tuple[str, int], State]]:- s = start- out: list[tuple[State, tuple[str, int], State]] = []- for op in ops:- t = step(s, op)- if t != s:- out.append((s, op, t))- s = t- return out---def diagram_edges() -> list[tuple[str, str, str]]:- found: set[tuple[str, str, str]] = set()- extra: list[tuple[str, int]] = [- ("pop", 0),- ("push", 0),- ("pop", 0),- ("set", 1049),- ("reset", 1049),- ("set", 2004),- ("reset", 2004),- ]- streams = [parse_ops(GRAFF_ENABLE + GRAFF_RESTORE), extra]- for ops in streams:- for s, op, t in walk_ops(({}, 0), ops):- a, b = project(s), project(t)- if a == b:- continue- found.add((a, event_label(op), b))- return sorted(found)---def mermaid() -> str:- lines = ["stateDiagram-v2", " [*] --> Idle"]- for a, lab, b in diagram_edges():- lines.append(f" {a} --> {b}: {lab}")- return "\n".join(lines) + "\n"---def kernel_md() -> str:- body = mermaid().rstrip()- return (- "# Kernel: terminal modes\n"- "\n"- "Source of truth: `lean-proofs/Graff/TerminalModes.lean`.\n"- "\n"- "Process kernel, not a Turing machine: `Op` / `step` is the mode map\n"- "plus kitty depth. The 14 named sequences are the snapshot. Enable then\n"- "restore returns to Idle; restore leaves the alt-screen last; pop floors\n"- "at zero. TUI layout, glyphs, and the font stay never.\n"- "\n"- "The diagram is the projection of the live Python `step`. Emit it with\n"- "`python3 spec/conformance.py --diagram terminal_modes`.\n"- "\n"- "```mermaid\n"- f"{body}\n"- "```\n"- )---def write_kernel_md(path: Path = KERNEL_MD) -> Path:- path.write_text(kernel_md())- return path---def check_diagram() -> None:- s: State = ({}, 0)- for op in parse_ops(GRAFF_ENABLE + GRAFF_RESTORE):- s = step(s, op)- if project(s) != "Idle":- raise ValueError("diagram: enable+restore did not return to Idle")- if step(({}, 0), ("pop", 0))[1] != 0:- raise ValueError("diagram: pop from Idle left depth != 0")- text = mermaid()- if "Idle --> Alt: set 1049" not in text:- raise ValueError("diagram: mermaid missing Idle set-1049→Alt")- if "Alt --> Idle: reset 1049" not in text:- raise ValueError("diagram: mermaid missing Alt reset-1049→Idle")- if "Alt --> Active: push" not in text:- raise ValueError("diagram: mermaid missing Alt push→Active")- if "Idle --> Active: pop" in text:- raise ValueError("diagram: mermaid has Idle pop→Active")diff --git a/src/agent_stream_tests.zig b/src/agent_stream_tests.zigindex 961d07ec..28f5d845 100644--- a/src/agent_stream_tests.zig+++ b/src/agent_stream_tests.zig@@ -5,18 +5,10 @@ const Kind = @import("provider.zig").Provider.Kind;pub fn reasoningBoundaries() !void {const a = std.testing.allocator;- const tui = @import("tui");- const tui_sink = @import("tui_sink.zig");var arena_state = std.heap.ArenaAllocator.init(a);defer arena_state.deinit();var client: std.http.Client = .{ .allocator = a, .io = std.testing.io };defer client.deinit();- var queue: tui.EventQueue = .{};- queue.attach(a);- defer queue.deinit();- var buf: [2048]u8 = undefined;- var stream: @import("repl.zig").StreamBuf = .{ .buf = &buf };- var bridge: tui_sink.Bridge = .{ .queue = &queue, .stream = &stream, .show_thinking = true };var agent: @import("agent.zig").Agent = .{.gpa = a,.arena = arena_state.allocator(),@@ -24,13 +16,11 @@ pub fn reasoningBoundaries() !void {.client = &client,.provider = .{ .id = "test", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "test", .context = 0 },.messages = std.json.Array.init(arena_state.allocator()),- .sink = tui_sink.forBridge(&bridge),.sub = false,.label = "test",.out = null,};- // Also exercise the classic REPL's actual "▼ Thinking" writer, not just- // the fullscreen frontend's live buffer.+ // Exercise the line REPL's actual "▼ Thinking" writer and engine buffer.const engine_sink = @import("engine_sink.zig");const main = @import("main.zig");const tick_gate = @import("tick_gate.zig");@@ -48,12 +38,11 @@ pub fn reasoningBoundaries() !void {engine_sink.hosted_frontend = false;var rendered: std.Io.Writer.Allocating = .init(a);defer rendered.deinit();- var plain_agent = agent;- plain_agent.out = &rendered.writer;- plain_agent.sink = engine_sink.tuiSink(&plain_agent);- plain_agent.show_thinking = true;- defer plain_agent.thinking_text.deinit(a);- const agents = [_]*@import("agent.zig").Agent{ &agent, &plain_agent };+ agent.out = &rendered.writer;+ agent.sink = engine_sink.tuiSink(&agent);+ agent.show_thinking = true;+ defer agent.thinking_text.deinit(a);+ const agents = [_]*@import("agent.zig").Agent{&agent};const dispatch = struct {fn send(receivers: []const *@import("agent.zig").Agent, line: []const u8) void {for (receivers) |receiver| @import("agent_stream.zig").printDelta(receiver, line);@@ -78,42 +67,10 @@ pub fn reasoningBoundaries() !void {}dispatch(&agents, "data: {\"type\":\"response.reasoning_text.delta\",\"delta\":\"synthetic private text\"}");dispatch(&agents, "data: {\"type\":\"response.reasoning_summary_text.done\",\"text\":\"\"}");- const snap = stream.snapshot(a) orelse return error.NoStream;- defer a.free(snap);+ const snap = agent.thinking_text.items;try std.testing.expectEqualStrings("**First heading**\n\n**Second heading**\n\n**Third heading**\n\n**Fourth heading**\n\n", snap);- try std.testing.expectEqualStrings(snap, plain_agent.thinking_text.items);try std.testing.expect(std.mem.indexOf(u8, rendered.written(), "▼ Thinking") != null);try std.testing.expect(std.mem.endsWith(u8, rendered.written(), snap));-- var term: tui.sim.Term = undefined;- term.init(a, 80, 24);- defer term.deinit();- const Job = std.meta.Child(std.meta.Child(@TypeOf(term.model.pending)));- var job: Job = .{- .gpa = a,- .history = &.{},- .params = .{},- .stream = .{ .buf = &buf },- .threaded = false,- };- job.stream.appendBytes(snap);- try term.model.push(.pending, "");- term.model.pending = &job;- defer term.model.pending = null;- const visible = try term.screen();- defer a.free(visible);- var lines = std.mem.splitScalar(u8, visible, '\n');- var seen: usize = 0;- while (lines.next()) |line| {- if (std.mem.indexOf(u8, line, " heading") != null) {- try std.testing.expect(seen < headings.len);- try std.testing.expect(std.mem.indexOf(u8, line, headings[seen]) != null);- try std.testing.expect(std.mem.count(u8, line, " heading") == 1);- try std.testing.expect(std.mem.indexOf(u8, line, "**") == null);- seen += 1;- }- }- try std.testing.expectEqual(headings.len, seen);}pub fn streamEnd(is_stream_end: anytype) !void {diff --git a/src/args.zig b/src/args.zigindex 46b0fe9e..d4f0b440 100644--- a/src/args.zig+++ b/src/args.zig@@ -86,13 +86,6 @@ pub const Flags = struct {/// or `harness -p "..."`), or null when positionals[0] is a subcommand.oneshot_prompt: ?[]const u8 = null,- /// `graff tui` / `graff repl` — fullscreen pager, not the line REPL.- pub fn isPager(self: Flags) bool {- if (self.positionals.items.len == 0) return false;- const c = self.positionals.items[0];- return std.mem.eql(u8, c, "tui") or std.mem.eql(u8, c, "repl");- }-/// One-shot is autonomous by default: -p implies --yolo — the typed-out/// invocation IS the consent, and a no-stdin approval prompt can only/// auto-decline (which stranded unattended coding runs on a policy@@ -278,7 +271,7 @@ pub fn parse(init: std.process.Init) !Flags {// (`harness "say hi"`). Subcommands (login/key) are not prompts.flags.is_subcommand = flags.positionals.items.len > 0 and(std.mem.eql(u8, flags.positionals.items[0], "login") or std.mem.eql(u8, flags.positionals.items[0], "logout") or std.mem.eql(u8, flags.positionals.items[0], "key") or std.mem.eql(u8, flags.positionals.items[0], "mcp") or std.mem.eql(u8, flags.positionals.items[0], "learn") or- std.mem.eql(u8, flags.positionals.items[0], "serve") or std.mem.eql(u8, flags.positionals.items[0], "update") or std.mem.eql(u8, flags.positionals.items[0], "title") or std.mem.eql(u8, flags.positionals.items[0], "repl") or std.mem.eql(u8, flags.positionals.items[0], "tui") or+ std.mem.eql(u8, flags.positionals.items[0], "serve") or std.mem.eql(u8, flags.positionals.items[0], "update") or std.mem.eql(u8, flags.positionals.items[0], "title") or std.mem.eql(u8, flags.positionals.items[0], "repl") or (!flags.print_flag and std.mem.eql(u8, flags.positionals.items[0], "tui")) orstd.mem.eql(u8, flags.positionals.items[0], "worktree") or std.mem.eql(u8, flags.positionals.items[0], "sandboxes") or std.mem.eql(u8, flags.positionals.items[0], "cube") or std.mem.eql(u8, flags.positionals.items[0], "models") orstd.mem.eql(u8, flags.positionals.items[0], "remote-control") or std.mem.eql(u8, flags.positionals.items[0], "remote") or @import("acp.zig").isAcpSubcommand(flags.positionals.items[0])); // `acp` also arms ACP's stdout discipline (json_mode) — see acp.isAcpSubcommandif (!flags.is_subcommand and flags.positionals.items.len > 0) {@@ -345,12 +338,12 @@ test "loginTarget: every ChatGPT name, codex included, is the plan's sign-in; untry std.testing.expect(loginTarget("") == null);}-test "tui and repl are pager subcommands, not one-shot prompts" {+test "tui is a reserved subcommand, not a one-shot prompt" {var tui_pos = std.ArrayList([]const u8).empty;defer tui_pos.deinit(std.testing.allocator);try tui_pos.append(std.testing.allocator, "tui");const tui_flags = Flags{ .positionals = tui_pos, .yolo_flag = true, .is_subcommand = true };- try std.testing.expect(tui_flags.isPager());+ try std.testing.expect(tui_flags.is_subcommand);try std.testing.expect(tui_flags.yolo_flag);try std.testing.expect(tui_flags.oneshot_prompt == null);}diff --git a/src/cli.zig b/src/cli.zigindex e418d832..7b25c364 100644--- a/src/cli.zig+++ b/src/cli.zig@@ -107,7 +107,9 @@ pub const usage_text =\\graff — a minimal agentic coding harness in Zig (zero deps)\\\\usage:- \\ graff [flags] start the REPL+ \\ graff [flags] start the line REPL+ \\ graff repl line REPL (scripted when stdin is piped)+ \\ graff tui [args...] launch installed graff-tui (sibling binary, then PATH)\\ graff [-p] "prompt" one-shot: run the prompt, print the answer, exit\\ graff login get a codegraff key (device-code OAuth)\\ graff login chatgpt ChatGPT sign-in (also: codex, openai)diff --git a/src/external_tui.zig b/src/external_tui.zignew file mode 100644index 00000000..a62ed109--- /dev/null+++ b/src/external_tui.zig@@ -0,0 +1,53 @@+//! Launch the separately installed fullscreen client before engine startup.+const std = @import("std");+const builtin = @import("builtin");++const binary_name = if (builtin.os.tag == .windows) "graff-tui.exe" else "graff-tui";++/// Inspect raw arguments so UI flags (including --help) never reach graff's+/// parser. `graff -p "tui"` remains a normal prompt.+pub fn maybeRun(init: std.process.Init) !bool {+ var it = try std.process.Args.Iterator.initAllocator(init.minimal.args, init.gpa);+ defer it.deinit();+ _ = it.next();+ const command = it.next() orelse return false;+ if (!std.mem.eql(u8, command, "tui")) return false;++ const a = init.arena.allocator();+ var argv: std.ArrayList([]const u8) = .empty;+ try argv.append(a, binary_name);+ while (it.next()) |arg| try argv.append(a, arg);++ // Prefer the companion shipped alongside this executable, then PATH.+ // Do not fetch a binary or initialize credentials, MCP, or a session.+ if (std.process.executableDirPathAlloc(init.io, a) catch null) |dir| {+ argv.items[0] = try std.fs.path.join(a, &.{ dir, binary_name });+ launch(init.io, argv.items) catch |err| switch (err) {+ error.FileNotFound => {},+ else => std.process.fatal("cannot launch {s}: {s}", .{ binary_name, @errorName(err) }),+ };+ }+ argv.items[0] = binary_name;+ launch(init.io, argv.items) catch |err| switch (err) {+ error.FileNotFound => std.process.fatal("{s} is not installed. Install the separate TUI next to graff or on PATH. No files were downloaded.", .{binary_name}),+ else => std.process.fatal("cannot launch {s}: {s}", .{ binary_name, @errorName(err) }),+ };+ unreachable;+}++fn launch(io: std.Io, argv: []const []const u8) !void {+ // POSIX replacement preserves the terminal, process identity, signals,+ // and exit status. Windows has no exec; inherit its handles and wait.+ if (builtin.os.tag != .windows) return std.process.replace(io, .{ .argv = argv });+ var child = try std.process.spawn(io, .{+ .argv = argv,+ .stdin = .inherit,+ .stdout = .inherit,+ .stderr = .inherit,+ });+ const term = try child.wait(io);+ std.process.exit(switch (term) {+ .exited => |code| code,+ else => 1,+ });+}diff --git a/src/idle_wake_sources.zig b/src/idle_wake_sources.zigindex 43210cd3..eaca55c5 100644--- a/src/idle_wake_sources.zig+++ b/src/idle_wake_sources.zig@@ -1,5 +1,5 @@-//! Idle auto-turn sources shared by the line REPL, TUI, and graff acp.-//! Order matches the TUI poll: interactive-subagent, job idle-stop (#199),+//! Idle auto-turn sources shared by the line REPL and graff acp.+//! Poll order: interactive-subagent, job idle-stop (#199),//! schedule, channel-worker, then peer mail (#1001). Accord ping is a side//! drain, not a wake. `subagent_interactive.takeWake` is engine-side (job//! registry + session owner) — it does not need a TTY. The TTY-only path is@@ -47,7 +47,7 @@ fn helperBody() []const u8 {return rest[0 .. end + 1];}-test "idle wake helper polls sources in TUI order" {+test "idle wake helper polls sources in priority order" {const body = helperBody();try expectBefore(body, "subagent_interactive.takeWake", "job_notify.takeIdleWake");try expectBefore(body, "job_notify.takeIdleWake", "schedule.takeWake");@@ -56,26 +56,19 @@ test "idle wake helper polls sources in TUI order" {try expectBefore(body, "presence_accord.takePing", "peer_idle.takeIdleWake");}-test "REPL TUI and ACP idle callbacks delegate to the shared helper" {+test "REPL and ACP idle callbacks delegate to the shared helper" {const helper = "idle_wake_sources.zig";- const tui = @embedFile("tui_launch.zig");const repl = @embedFile("readline.zig");const acp = @embedFile("acp_idle.zig");- try std.testing.expect(std.mem.indexOf(u8, tui, helper) != null);try std.testing.expect(std.mem.indexOf(u8, repl, helper) != null);try std.testing.expect(std.mem.indexOf(u8, acp, helper) != null);- try std.testing.expect(std.mem.indexOf(u8, tui, "takeIdleWake(") != null);try std.testing.expect(std.mem.indexOf(u8, repl, "takeIdleWake(") != null);try std.testing.expect(std.mem.indexOf(u8, acp, "takeIdleWake(") != null);- try std.testing.expect(std.mem.indexOf(u8, tui, "job_notify.takeIdleWake") == null);- try std.testing.expect(std.mem.indexOf(u8, tui, "schedule.takeWake") == null);- try std.testing.expect(std.mem.indexOf(u8, tui, "channel_worker.takeWake") == null);- try std.testing.expect(std.mem.indexOf(u8, tui, "peer_idle.takeIdleWake") == null);try std.testing.expect(std.mem.indexOf(u8, repl, "peer_idle.takeIdleWake") == null);try std.testing.expect(std.mem.indexOf(u8, acp, "peer_idle.takeIdleWake") == null);}-test "ACP frontend exit runs finalizeSession like REPL and TUI" {+test "ACP frontend exit runs finalizeSession like REPL" {const src = @embedFile("session_run.zig");const fn_start = std.mem.indexOf(u8, src, "pub fn runFrontendCommands").?;const body = src[fn_start..];@@ -85,8 +78,6 @@ test "ACP frontend exit runs finalizeSession like REPL and TUI" {const ret = try sourcePin(after_acp, "return true;");try std.testing.expect(finalize < ret);try std.testing.expect(std.mem.indexOf(u8, body[0..acp], "finalizeSession(") != null);- const tui = try sourcePin(body, "tui_launch.maybeRun");- try std.testing.expect(std.mem.indexOf(u8, body[tui..], "finalizeSession(") != null);}test "job notify wins over parked peer mail" {diff --git a/src/main.zig b/src/main.zigindex c0525213..6b5637c4 100644--- a/src/main.zig+++ b/src/main.zig@@ -1,6 +1,5 @@//! Agentic loop: native/MCP tools, parallel agents, compaction, and local traces.const std = @import("std");-pub const panic = @import("tui").restore.Panic; // leave the alt screen BEFORE std prints a panic, or the restore sequence erases the trace (#535)const Io = std.Io;const http_client = @import("http_client.zig");const Value = std.json.Value;@@ -123,7 +122,7 @@ test {_ = session_start;_ = session_run;_ = @import("obs_cost_test.zig");- _ = @import("tui_launch.zig");+ _ = @import("external_tui.zig");_ = provider_mod;_ = .{ @import("named_work.zig"), @import("task_intent.zig") };}@@ -247,6 +246,7 @@ const session_start = @import("session_start.zig");const session_run = @import("session_run.zig");pub fn main(init: std.process.Init) !void {if (init.environ_map.get("GRAFF_AGENT_OBSERVER") != null) return @import("acp_agents.zig").run(init);+ if (try @import("external_tui.zig").maybeRun(init)) return;var boot = startup_timing.Tracker.init(startup_timing.shutdown_trace.arm(init.io, init.environ_map), init.environ_map.get("GRAFF_BOOT_DEBUG") != null); // #364: arm() passes io through, so the teardown below stamps phases without a line of its ownconst gpa = init.gpa;const io = init.io;@@ -559,8 +559,8 @@ const workflow = @import("workflow_test.zig"); // the engine's tests live here (const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)_ = .{ @import("beta_feed.zig"), @import("jev_tool.zig"), @import("jev_model_scope.zig"), @import("jev_provider_switch_tests.zig"), @import("jev_effort_state.zig") };- _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("usage_trace.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig"), @import("acp_permission.zig"), @import("acp_usage.zig") };- _ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };+ _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("usage_trace.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("acp_permission.zig"), @import("acp_usage.zig") };+ _ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig") };_ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig"), @import("session_workspaces.zig"), @import("commands_resume.zig"), @import("peer_live.zig"), @import("presence_tests.zig"), @import("mcp_rpc_tests.zig") };_ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig"), @import("oauth_chatgpt.zig") }; // per-model guidance (Astra, GPT-5.6); ChatGPT plan sign-in_ = .{ @import("agent_empty_completion.zig"), @import("agent_model_loop.zig"), @import("publication_policy_tests.zig"), @import("jobs_completion_tests.zig") };@@ -577,7 +577,6 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("agent_ws_signal.zig");_ = @import("agent_ws_prewarm.zig");_ = .{ @import("http2_pool.zig"), @import("agent_stream_h2.zig"), @import("agent_stream_h2_transport_test.zig") }; // h2 stream path, and graff's request/response contract over the pinned http-zig- _ = @import("tui_acp_updates.zig");_ = @import("acp_preauth.zig"); // credential-free ACP loop must stay in the test root_ = .{ @import("acp_protocol.zig"), @import("acp_v2.zig"), @import("acp_v2_prompt.zig"), @import("acp_elicit.zig"), @import("hot_context.zig"), @import("history_translate.zig"), @import("mcp_notify.zig"), @import("mcp_wait.zig"), @import("mcp_pages.zig"), @import("mcp_mrtr.zig"), @import("ask_user_args.zig"), @import("mcp_add.zig"), @import("mcp_lazy.zig"), @import("mcp_share.zig"), @import("acp_room.zig"), @import("mcp_catalog.zig"), @import("mcp_watch.zig"), @import("acp_engine_test.zig"), @import("subagent_mimo_tests.zig"), @import("mimo_effort_tests.zig"), @import("gateway_picker_catalog.zig"), @import("ask_user_answers.zig"), @import("job_class.zig"), @import("startup_claim.zig") };_ = @import("task_outcome.zig"); // goal-outcome telemetry eventsdiff --git a/src/repl.zig b/src/repl.zigindex 77afe7ae..b3e8d0c5 100644--- a/src/repl.zig+++ b/src/repl.zig@@ -1,6 +1,6 @@//! Scripted `graff repl` Model: conversation history, slash commands, and a-//! pane renderer for piped/CI stdin. TTY `graff repl` is the Grok-style pager-//! (`tui_launch`), not this Model. Styling is local (`repl_style.zig`).+//! pane renderer for piped/CI stdin. TTY `graff repl` uses the ordinary line+//! REPL, not this Model. Styling is local (`repl_style.zig`).//!//! The model call runs on a background thread so the ensō thinking spinner//! can animate while a scripted job is in flight. The whole conversation isdiff --git a/src/repl_bash.zig b/src/repl_bash.zigdeleted file mode 100644index bb321807..00000000--- a/src/repl_bash.zig+++ /dev/null@@ -1,173 +0,0 @@-//! `!cmd` — the user's own shell line, run through the ENGINE (#551).-//!-//! It used to call process_runner.runCapped directly from the TUI glue, which-//! skipped every rail the same command gets when the model asks for it: no-//! approval gate, no plan-mode denial, no hooks, no tracer, no tool-//! accounting. `/plan` then `!rm -rf build` ran the rm. And because the output-//! went straight to a system row, the model never saw what the user had just-//! run, so the next question about it landed with no context.-//!-//! Now it builds the same ToolCall the model's `bash` tool produces, sends it-//! through Agent.gateTool and exec.execTool, and folds the command and its-//! output into the session conversation. Esc still lands: process_runner polls-//! Agent.esc_cancel, which is what the frontend's cancel callback sets.--const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;--const main_mod = @import("main.zig");-const agent_mod = @import("agent.zig");-const Agent = agent_mod.Agent;-const approvals_mod = @import("approvals.zig");-const Approvals = approvals_mod.Approvals;-const exec = @import("exec.zig");-const tools_mod = @import("tools.zig");-const ToolCall = tools_mod.ToolCall;-const repl = @import("repl.zig");-const repl_glue = @import("repl_glue.zig");-const repl_turn = @import("repl_turn.zig");-const ReplCtx = repl_glue.ReplCtx;--/// How much of a `!` command's output the model is shown. The transcript row-/// is already tailed for display; this bound is about the request body, where-/// a 200 KB build log would evict the rest of the conversation.-pub const note_cap: usize = 4000;--/// Run `cmd` exactly as the bash TOOL runs it. Returns the combined output-/// (gpa-owned, the frontend frees it) or the gate's refusal text; null only-/// when the harness could not produce either.-pub fn replBashCb(ctx_ptr: ?*anyopaque, gpa: Allocator, cmd: []const u8, params: repl.Params) ?[]const u8 {- const c: *ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));- // A cancel that ended the PREVIOUS op must not kill this one before it- // starts: esc_cancel is a process-wide latch and a turn clears it the same- // way at its own start.- Agent.esc_cancel.store(false, .release);- var scratch_state = std.heap.ArenaAllocator.init(gpa);- defer scratch_state.deinit();- const arena = scratch_state.allocator();- var discard_buf: [256]u8 = undefined;- var discarding: Io.Writer.Discarding = .init(&discard_buf);-- const policy = repl_turn.Policy.from(params);- const plan_saved = main_mod.plan_mode;- main_mod.plan_mode = policy.plan;- defer main_mod.plan_mode = plan_saved;- var approvals: Approvals = .{ .yolo = policy.yolo };- var agent = repl_turn.turnAgent(c, gpa, arena, params, &discarding.writer, &approvals) catch return null;- defer agent.tools_used.deinit(gpa);-- var input: std.json.ObjectMap = .empty;- input.put(arena, "command", .{ .string = cmd }) catch return null;- const call: ToolCall = .{ .id = "tui-bang", .name = "bash", .input = .{ .object = input } };-- if (agent.gateTool(call)) |maybe_denied| {- if (maybe_denied) |denied| {- // The refusal is the user's answer AND the model's: it explains why- // nothing ran, and the next prompt is usually about that.- noteToModel(c, gpa, cmd, denied.text);- return gpa.dupe(u8, denied.text) catch null;- }- } else |_| return null;-- const result = exec.execTool(.{- .gpa = gpa,- .io = c.io,- .client = c.client,- .provider = c.provider,- .registry = c.registry,- .from_sub = false,- .approvals = &approvals,- .tracer = c.tracer,- .run_budget = c.run_budget,- .tools_used = &agent.tools_used,- }, call);- noteToModel(c, gpa, cmd, result.text);- return result.text; // gpa-owned, exactly what BashFn promises-}--/// Put the command and what it printed into the conversation, so the model can-/// answer "why did that fail?" without being told the whole thing again.-fn noteToModel(c: *ReplCtx, gpa: Allocator, cmd: []const u8, output: []const u8) void {- const cv = c.convo orelse return;- const shown = capped(output, note_cap);- const line = std.fmt.allocPrint(- gpa,- "I ran a shell command myself:\n$ {s}\n\n{s}{s}",- .{ cmd, shown, if (shown.len < output.len) "\n[output truncated]" else "" },- ) catch return;- defer gpa.free(line);- cv.note(line) catch {};-}--/// Head of `text`, at most `cap` bytes and never splitting a UTF-8 sequence —-/// half a codepoint here would be half a codepoint on the wire.-pub fn capped(text: []const u8, cap: usize) []const u8 {- if (text.len <= cap) return text;- var end = cap;- while (end > 0 and text[end] & 0xC0 == 0x80) end -= 1;- return text[0..end];-}--const testing = std.testing;--fn lastNote(convo: *repl_glue.Conversation) []const u8 {- const items = convo.list().items;- if (items.len == 0) return "";- return items[items.len - 1].object.get("content").?.string;-}--test "!cmd runs through the engine's gate, and plan mode refuses it (#551)" {- const gpa = testing.allocator;- var client: std.http.Client = undefined;- var c = repl_turn.testCtx(&client);- var convo = repl_glue.Conversation.init(gpa);- defer convo.deinit();- c.convo = &convo;- const saved_plan = main_mod.plan_mode;- defer main_mod.plan_mode = saved_plan;-- // Plan mode: the command never runs, so its output never appears.- const refused = replBashCb(&c, gpa, "printf bang-sentinel", .{ .mode = .plan }) orelse- return error.NoResult;- defer gpa.free(refused);- try testing.expect(std.mem.indexOf(u8, refused, "plan mode") != null);- try testing.expect(std.mem.indexOf(u8, refused, "bang-sentinel") == null);- // …and the refusal is in the conversation, because the next prompt is- // usually "why didn't that work?".- try testing.expect(std.mem.indexOf(u8, lastNote(&convo), "plan mode") != null);- const after_refusal = convo.len();-- // The same command outside plan mode runs and produces its output.- const ran = replBashCb(&c, gpa, "printf bang-sentinel", .{ .mode = .always_approve }) orelse- return error.NoResult;- defer gpa.free(ran);- try testing.expect(std.mem.indexOf(u8, ran, "bang-sentinel") != null);-- // The model sees the command AND what it printed — the old `!` path put- // the output on a system row the conversation never carried.- try testing.expectEqual(after_refusal + 1, convo.len());- const note = lastNote(&convo);- try testing.expect(std.mem.indexOf(u8, note, "$ printf bang-sentinel") != null);- try testing.expect(std.mem.indexOf(u8, note, "bang-sentinel") != null);- // plan_mode is a process global: the op restores whatever it found.- try testing.expectEqual(saved_plan, main_mod.plan_mode);-}--test "a session with no conversation still runs !cmd and keeps no note" {- const gpa = testing.allocator;- var client: std.http.Client = undefined;- var c = repl_turn.testCtx(&client);- const out = replBashCb(&c, gpa, "printf no-convo", .{ .mode = .always_approve }) orelse- return error.NoResult;- defer gpa.free(out);- try testing.expect(std.mem.indexOf(u8, out, "no-convo") != null);-}--test "capped never splits a multi-byte character" {- try testing.expectEqualStrings("abc", capped("abc", 8));- // "…" is three bytes; a cap landing inside it must drop the whole glyph.- try testing.expectEqualStrings("ab", capped("ab…cd", 3));- try testing.expectEqualStrings("ab…", capped("ab…cd", 5));- try testing.expect(std.unicode.utf8ValidateSlice(capped("ab…cd", 4)));-}diff --git a/src/repl_glue.zig b/src/repl_glue.zigindex 299d90c5..fdaea601 100644--- a/src/repl_glue.zig+++ b/src/repl_glue.zig@@ -577,8 +577,7 @@ pub fn goalCommandArgs(line: []const u8) ?[]const u8 {return std.mem.trim(u8, line[end..], " \t\r\n");}-/// Scripted `graff repl` host commands. The TUI path wires the same actions-/// through tui_launch; this bind is the scripted / headless equivalent.+/// Host commands for scripted `graff repl`.pub fn bindHostCommands() void {repl.g_version_fn = versionCb;repl.g_update_fn = updateCb;diff --git a/src/repl_run.zig b/src/repl_run.zigindex 7bc19997..c1a30e91 100644--- a/src/repl_run.zig+++ b/src/repl_run.zig@@ -1,5 +1,5 @@//! Scripted `graff repl` entry: headless twin of the Model for CI and non-TTY-//! stdin. TTY `graff repl` is `tui_launch`, not this file.+//! stdin. TTY `graff repl` uses the ordinary line REPL, not this file.const std = @import("std");diff --git a/src/session_run.zig b/src/session_run.zigindex 87e4d597..15c494de 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -45,7 +45,6 @@ const engine_events = @import("engine_events.zig");const harness_policy = @import("harness_policy.zig");const title_mod = @import("title.zig");const repl = @import("repl.zig");-const tui_launch = @import("tui_launch.zig");const shapes = @import("shapes.zig"); // applyUltracodeSteering lives here (#326)const repl_glue = @import("repl_glue.zig");const eval_memory = @import("eval_memory.zig");@@ -66,8 +65,8 @@ const commands_privacy = @import("commands_privacy.zig");const prompts = @import("prompts.zig");const local_tools = @import("local_tools.zig");-/// `graff repl`: interactive chat on the Grok-style TUI (same as `graff tui`).-/// Piped/non-TTY stdin still drives the scripted Model so CI+/// `graff repl`: TTY stdin falls through to the ordinary line REPL.+/// Piped/non-TTY stdin drives the scripted Model so CI/// (`printf ... | graff repl`) keeps a stable headless path./// Self-contained — exits after. Moved out of main() (600-line goal)./// `root` is already a stable, fully-constructed main()-owned Agent by the@@ -75,10 +74,7 @@ const local_tools = @import("local_tools.zig");/// only reads through the pointer, it never owns or returns Agent storage).pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags) !bool {if (!(flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "repl"))) return false;- if (Io.File.stdin().isTty(io) catch true) {- try tui_launch.run(gpa, io, environ_map, root, keys, client, arena, main_mod.g_cwd_display, flags.yolo_flag);- return true;- }+ if (Io.File.stdin().isTty(io) catch true) return false;root.ensureStoredKeys(keys);providers.ensureModelQueryCatalogs(root, keys.*, "");// The standalone chat REPL can switch wire formats inside its own model@@ -102,7 +98,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent.registry = root.registry,.tracer = root.tracer,.run_budget = root.run_budget,- // The base, as in tui_launch: each turn's setSystemPrompts composes the+ // Use the base: each turn's setSystemPrompts composes the// constraint block onto it, so root.sys_normal would stack a second copy..sys_normal = if (root.sys_base.len > 0) root.sys_base else root.sys_normal,.tools_anthropic = root.tools_anthropic,@@ -125,14 +121,14 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agentdefer @import("run_idle.zig").enabled = false;try repl.runScripted(gpa, io, environ_map, in, out, &repl_ctx, repl_glue.replTurnCb, repl_glue.replModelCb, repl_glue.replCancelCb, root.provider.model, models_buf.items);// Same stderr footer as `-p`, so evals can score the scripted REPL the- // same way. TTY `graff repl` is the TUI and keeps the restore tail clean.+ // same way. TTY `graff repl` uses the main loop's footer.pricing.printUsageFooter(io);root.messages = try convo.cloneInto(root.arena);root.compaction_window = convo.compaction_window;return true;}-pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags, json_mode: bool, cwd: []const u8, final_io: Io) !bool {+pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_mod.Agent, keys: *provider_mod.Keys, client: *std.http.Client, in: *Io.Reader, out: *Io.Writer, arena: Allocator, flags: args.Flags, json_mode: bool, _: []const u8, final_io: Io) !bool {if (try runReplCommand(gpa, io, environ_map, root, keys, client, in, out, arena, flags)) {try finalizeSession(gpa, final_io, arena, out, root, json_mode);return true;@@ -141,10 +137,6 @@ pub fn runFrontendCommands(gpa: Allocator, io: Io, environ_map: anytype, root: *try finalizeSession(gpa, final_io, arena, out, root, json_mode);return true;}- if (try tui_launch.maybeRun(gpa, io, environ_map, root, keys, client, arena, flags, json_mode, cwd)) {- try finalizeSession(gpa, final_io, arena, out, root, json_mode);- return true;- }return false;}diff --git a/src/session_start.zig b/src/session_start.zigindex c47af0e5..b1f7d062 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -204,9 +204,7 @@ pub fn setupWorktreeAndBanner(} });}- // The pager owns the screen. Dumping the line-REPL banner first makes- // `graff tui --yolo` look like bare `graff` never left.- if (!main_mod.json_mode and flags.oneshot_prompt == null and !flags.isPager()) {+ if (!main_mod.json_mode and flags.oneshot_prompt == null) {sink.emit(io, .{ .session_banner = .{ .cwd = main_mod.g_cwd_display, .trace_path = trace_path } });if (environ_map.get("GRAFF_REPL_DEBUG") != null) if (codex_account) |acct| sink.emit(io, .{ .session_notice = .{.text = try std.fmt.allocPrint(arena, "logged into Codex (ChatGPT account {s}…) — /model codex", .{acct[0..@min(acct.len, 8)]}),diff --git a/src/session_wake.zig b/src/session_wake.zigindex fef87443..ba20138f 100644--- a/src/session_wake.zig+++ b/src/session_wake.zig@@ -124,9 +124,8 @@ test "notification provenance survives saved JSON and conversation adoption withtry std.testing.expect(isNotice(restored.array.items[0]));try std.testing.expect(!@import("session_peer.zig").isHumanUserTurn(restored.array.items[0]));try std.testing.expect(!isNotice(restored.array.items[1]));- const turns = try @import("tui_session.zig").visibleTurns(a, restored.array);- try std.testing.expect(turns[0].notification);- try std.testing.expect(!turns[1].notification);+ try std.testing.expect(@import("session_peer.zig").isHumanUserTurn(restored.array.items[1]));+ try std.testing.expectEqualStrings("wake up", @import("messages.zig").latestUserText(restored.array.items));}test "notification metadata stays off chat, responses and anthropic wires including cache branches" {diff --git a/src/shutdown_trace.zig b/src/shutdown_trace.zigindex 8d4f94df..68d17437 100644--- a/src/shutdown_trace.zig+++ b/src/shutdown_trace.zig@@ -56,9 +56,6 @@ pub fn arm(io: Io, environ_map: *const std.process.Environ.Map) Io {/// tests, `graff repl`, any path that never called `arm`) or when the opt-in/// is off, so a normal exit pays one bool load per phase.pub fn mark(phase: []const u8) void {- // ADR 0042: an early pager claim that never reached `tui.run` still- // owns the alt-screen. Main's first teardown `at()` lands here.- @import("tui").restore.releaseIfOwned();if (!enabled) return;const io = clock orelse return;const cumulative: i64 = @intCast(@max(0, started.untilNow(io, .awake).toMilliseconds()));@@ -99,11 +96,6 @@ test "render degrades to the bare phase name rather than dropping it" {try std.testing.expectEqualStrings("join-elites", render(&tiny, "join-elites", 1, 1));}-test "teardown stamps release an early pager claim" {- const src = @embedFile("shutdown_trace.zig");- try std.testing.expect(std.mem.indexOf(u8, src, "releaseIfOwned") != null);-}-test "an unarmed process prints nothing and `at` stays a pass-through" {setEnabledForTest(false);mark("never-printed");diff --git a/src/startup.zig b/src/startup.zigindex bcbe3715..9f18c3d8 100644--- a/src/startup.zig+++ b/src/startup.zig@@ -255,6 +255,8 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processtry hw.interface.flush();return true;}+ if (flags.oneshot_prompt == null and flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "tui"))+ std.process.fatal("use graff tui [arguments]: put tui before its flags", .{});router_config.load(io, arena) catch |err|std.process.fatal("invalid {s}: {s}", .{ router_config.path, @errorName(err) });// #402: pin THE codex credential directory ($CODEX_HOME, else ~/.codex) before@@ -544,16 +546,5 @@ pub fn runSubcommand(io: Io, gpa: Allocator, arena: Allocator, init: std.processif (!main_mod.json_mode and flags.oneshot_prompt == null)@import("server_diagnostics.zig").warnStartup(arena, io);- // ADR 0042: claim the pager before keys / MCP / prompt so `graff tui`- // (and TTY `graff repl`) do not sit on a blank shell. No-op off a TTY.- if (!main_mod.json_mode and flags.oneshot_prompt == null and flags.isPager()) {- _ = @import("tui").claim();- }return false;}--test "pager commands claim the alt screen before credentials" {- const src = @embedFile("startup.zig");- try std.testing.expect(std.mem.indexOf(u8, src, "flags.isPager()") != null);- try std.testing.expect(std.mem.indexOf(u8, src, ".claim()") != null);-}diff --git a/src/startup_keys.zig b/src/startup_keys.zigindex 7401b214..e516a0fe 100644--- a/src/startup_keys.zig+++ b/src/startup_keys.zig@@ -250,9 +250,6 @@ pub fn resolveKeys(io: Io, gpa: Allocator, arena: Allocator, environ_map: anytyp}fn missingCredentials() noreturn {- // `tui`/TTY `repl` claim the pager before credential resolution. Fatal- // exits do not unwind defers, so release that claim before stderr prints.- @import("tui").restore.releaseIfOwned();std.process.fatal(\\no API key found. quickest fixes:\\ graff login free codegraff key (device-code OAuth)diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 3c08bdc9..23447698 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -31,11 +31,10 @@ const learn_submit = @import("learn_submit.zig");const learn_tournament = @import("learn_tournament.zig");const recipe = @import("recipe.zig");-// Scripted `graff repl` Model (piped/CI). TTY `graff repl` is TUI/.+// Scripted `graff repl` Model (piped/CI).const repl = @import("repl.zig");const repl_markdown = @import("repl_markdown.zig");const repl_parser = @import("repl_parser.zig");-const tui_session = @import("tui_session.zig");// Routing + worker selection.const router_config = @import("router_config.zig");@@ -247,7 +246,6 @@ test {_ = repl;_ = repl_markdown;_ = repl_parser;- _ = tui_session;_ = router_config;_ = subagent_selection;_ = subagent_pin_tests;@@ -366,13 +364,11 @@ test {_ = @import("acp_workspace.zig");_ = @import("acp_images.zig");_ = @import("libgraff.zig");- _ = @import("tui_peer.zig");_ = @import("acp_auth.zig");_ = @import("local_tools.zig");_ = @import("schedule.zig");_ = @import("channel_worker.zig");_ = @import("session_wake.zig");- _ = @import("tui_acp.zig");_ = @import("readline_paste.zig"); // #674: semantic paste spans (not reached via readline.zig's runtime import)_ = @import("readline_image.zig"); // #702: composer image chips sync on delete_ = @import("readline_keys.zig"); // #981: Cmd/Option modified-Backspace decoding@@ -380,7 +376,6 @@ test {_ = @import("commands_resume.zig"); // #697: --resume SOURCE --branch DEST parser_ = @import("session_list.zig"); // #712: device-wide saved-session listing_ = @import("turn_dedup.zig"); // #714: identical user turns do not replay- _ = @import("tui_goal.zig"); // #716: typed TUI /goal is retirable, not standing_ = @import("net_efficiency_test.zig");_ = @import("codex_tool_search.zig"); // hosted tool_search on gpt-5.4+ Codex_ = @import("acp_tool_view.zig"); // #1287/#1289: ACP locations and edit diffsdiff --git a/src/tui_acp.zig b/src/tui_acp.zigdeleted file mode 100644index a2ff3d68..00000000--- a/src/tui_acp.zig+++ /dev/null@@ -1,533 +0,0 @@-//! In-process ACP client for the fullscreen TUI (ADR 0041).-//!-//! Same initialize / session/new / prompt / cancel envelopes as Zed and-//! Harness. Thought, tools, and answer text render from `session/update`.-//! No child `graff acp` — one Agent, one conversation.--const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;-const Value = std.json.Value;--const acp = @import("acp.zig");-const acp_engine = @import("acp_engine.zig");-const acp_stream = @import("acp_stream.zig");-const proto = @import("acp_protocol.zig");-const agent_mod = @import("agent.zig");-const engine_events = @import("engine_events.zig");-const engine_sink = @import("engine_sink.zig");-const label = @import("agent_tool_label.zig");-const main_mod = @import("main.zig");-const obs = @import("obs.zig");-const repl = @import("repl.zig");-const repl_glue = @import("repl_glue.zig");-const telemetry = @import("telemetry.zig");-const tui = @import("tui");-const tui_sink = @import("tui_sink.zig");-const util = @import("util.zig");--threadlocal var tls: ?*Session = null;--pub fn attach(s: *Session) void {- tls = s;-}--pub fn detach() void {- tls = null;-}--pub fn sessionId() ?[]const u8 {- const s = tls orelse return null;- return if (s.session_id.len == 0) null else s.session_id;-}--pub fn cancel() void {- const s = tls orelse return;- var buf: [256]u8 = undefined;- var w: Io.Writer = .fixed(&buf);- var arena_state = std.heap.ArenaAllocator.init(s.gpa);- defer arena_state.deinit();- acp.handleLine(&s.dispatch, arena_state.allocator(), &w, "{\"jsonrpc\":\"2.0\",\"method\":\"session/cancel\"}") catch {};-}--const updates = @import("tui_acp_updates.zig");-pub const Apply = updates.Apply;-pub const applyLine = updates.applyLine;-pub const applyBuffered = updates.applyBuffered;--fn toolTitle(name: []const u8, input: Value) []const u8 {- if (input == .object) {- if (util.strFieldObj(input.object, "path")) |p| return p;- if (util.strFieldObj(input.object, "command")) |c| return c;- if (util.strFieldObj(input.object, "url")) |u| return u;- }- return name;-}--const Transcript = struct {- gpa: Allocator,- session_id: []const u8,- apply: *Apply,-};--const transcript_vt: engine_sink.VTable = .{ .emit = transcriptEmit, .durable = false };--fn transcriptEmit(ctx: *anyopaque, ev: engine_sink.Stamped) void {- const t: *Transcript = @ptrCast(@alignCast(ctx));- // Text carries no JSON-only fields. Use the decoder's normalized path,- // avoiding a writer allocation + JSON parse for each in-process chunk.- switch (ev.event) {- .stream_begin, .stream_complete, .stream_finished, .stream_aborted, .transport_aborted => {- t.apply.reset();- return;- },- .reasoning_delta => |d| return updates.applyChunk(t.apply, true, d.text),- .text_delta, .tool_arg_delta => |d| return updates.applyChunk(t.apply, false, d.text),- else => {},- }- var aw: Io.Writer.Allocating = .init(t.gpa);- defer aw.deinit();- writeUpdate(&aw.writer, t.session_id, ev.event) catch return;- if (aw.writer.buffered().len == 0) return;- applyBuffered(t.apply, t.gpa, aw.writer.buffered());-}--fn writeUpdate(w: *Io.Writer, session_id: []const u8, ev: engine_events.EngineEvent) !void {- switch (ev) {- .reasoning_delta => |d| try acp_stream.writeThought(w, session_id, d.text),- .text_delta, .tool_arg_delta => |d| try acp_stream.writeMessage(w, session_id, d.text),- .tool_call_announced => |c| {- if (label.skipTranscript(c.name)) return;- try proto.writeNotification(w, "session/update", .{- .sessionId = session_id,- .update = .{- .sessionUpdate = "tool_call",- .toolCallId = c.id,- .title = toolTitle(c.name, c.input),- .kind = acp_stream.kindFor(c.name),- .status = "in_progress",- .rawInput = c.input,- .name = c.name,- },- });- },- .tool_result => |r| {- if (label.skipTranscript(r.name)) return;- try writeOutcome(w, session_id, r.id, r.name, r.is_error, false, r.ms, r.text);- },- .tool_rejected => |r| {- if (label.skipTranscript(r.name)) return;- try writeOutcome(w, session_id, r.id, r.name, true, true, 0, r.message);- },- .session_notice => |n| try acp_stream.writeThought(w, session_id, n.text),- else => {},- }-}--fn writeOutcome(w: *Io.Writer, session_id: []const u8, id: []const u8, name: []const u8, failed: bool, denied: bool, ms: i64, text: []const u8) !void {- try proto.writeNotification(w, "session/update", .{- .sessionId = session_id,- .update = .{- .sessionUpdate = "tool_call_update",- .toolCallId = id,- .name = name,- .status = if (failed) "failed" else "completed",- .denied = denied,- .durationMs = @max(0, ms),- .content = .{.{ .type = "content", .content = .{ .type = "text", .text = text } }},- },- });-}--const Fanout = struct {- first: engine_sink.EngineSink,- second: engine_sink.EngineSink,-};--const fan_vt: engine_sink.VTable = .{ .emit = fanEmit, .durable = false };--fn fanEmit(ctx: *anyopaque, ev: engine_sink.Stamped) void {- const f: *Fanout = @ptrCast(@alignCast(ctx));- f.first.vt.emit(f.first.ctx, ev);- f.second.vt.emit(f.second.ctx, ev);-}--const Pending = struct {- ctx: ?*anyopaque,- gpa: Allocator,- history: []const repl.Turn,- params: repl.Params,- stream: *repl.StreamBuf,- result: ?[]const u8 = null,-};--pub const Session = struct {- gpa: Allocator,- dispatch: acp_engine.Dispatch = undefined,- session_id_buf: [80]u8 = undefined,- session_id: []const u8 = "",- next_rpc: u32 = 1,- pending: ?Pending = null,-- pub fn init(self: *Session, gpa: Allocator, seed: u64) void {- self.* = .{- .gpa = gpa,- .dispatch = .{- .turn = dispatchTurn,- .ctx = @ptrCast(self),- .seed = seed,- .bind_session = bindSession,- },- };- }-- pub fn ensure(self: *Session) void {- if (self.session_id.len != 0) return;- acp_engine.implementation_version = main_mod.harness_version;- acp_engine.on_cancel = syncEsc;- acp_engine.extra_cancelled = liveCancelled;- var buf: [2048]u8 = undefined;- var w: Io.Writer = .fixed(&buf);- var arena_state = std.heap.ArenaAllocator.init(self.gpa);- defer arena_state.deinit();- const a = arena_state.allocator();- acp.handleLine(&self.dispatch, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":1}}") catch {};- w = .fixed(&buf);- acp.handleLine(&self.dispatch, a, &w, "{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"session/new\"}") catch {};- if (self.dispatch.session_id) |sid| bindSession(@ptrCast(self), sid);- }-};--fn bindSession(ctx: *anyopaque, sid: []const u8) void {- const s: *Session = @ptrCast(@alignCast(ctx));- const n = @min(sid.len, s.session_id_buf.len);- @memcpy(s.session_id_buf[0..n], sid[0..n]);- s.session_id = s.session_id_buf[0..n];-}--fn syncEsc() void {- @import("cancel_source.zig").cancel(.ui_cancel); // #728-}--fn liveCancelled() bool {- return agent_mod.Agent.esc_cancel.load(.acquire);-}--fn dispatchTurn(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {- _ = arena;- _ = text;- const s: *Session = @ptrCast(@alignCast(ctx));- const p = &(s.pending orelse return "");- p.result = repl_glue.replTurnCb(p.ctx, p.gpa, p.history, p.params, p.stream);- return "";-}--fn liveStream(stream: *tui.StreamBuf) *repl.StreamBuf {- comptime {- if (@sizeOf(tui.StreamBuf) != @sizeOf(repl.StreamBuf) or- @offsetOf(tui.StreamBuf, "buf") != @offsetOf(repl.StreamBuf, "buf") or- @offsetOf(tui.StreamBuf, "len") != @offsetOf(repl.StreamBuf, "len"))- @compileError("tui.StreamBuf and repl.StreamBuf must stay layout-identical");- }- return @ptrCast(stream);-}--fn promptJson(arena: Allocator, id: u32, session_id: []const u8, text: []const u8) ![]const u8 {- var aw: Io.Writer.Allocating = .init(arena);- try aw.writer.print("{{\"jsonrpc\":\"2.0\",\"id\":{d},\"method\":\"session/prompt\",\"params\":{{\"sessionId\":", .{id});- try std.json.Stringify.value(session_id, .{}, &aw.writer);- try aw.writer.writeAll(",\"prompt\":[{\"type\":\"text\",\"text\":");- try std.json.Stringify.value(text, .{}, &aw.writer);- try aw.writer.writeAll("}]}}");- return aw.writer.buffered();-}--/// A TUI model turn: ACP `session/prompt`, transcript from `session/update`.-pub fn turn(- ctx: ?*anyopaque,- gpa: Allocator,- history: []const tui.Turn,- params: tui.Params,- stream: *tui.StreamBuf,- events: *tui.EventQueue,-) ?[]const u8 {- var turns = std.array_list.Managed(repl.Turn).init(gpa);- defer {- for (turns.items) |t| gpa.free(t.text);- turns.deinit();- }- for (history) |t| {- const text = gpa.dupe(u8, t.text) catch continue;- turns.append(.{ .role = switch (t.role) {- .user => .user,- .assistant => .assistant,- }, .text = text, .notification = t.notification }) catch gpa.free(text);- }- var last_len: u32 = 0;- const user_text: []const u8 = if (history.len > 0 and history[history.len - 1].role == .user) blk: {- last_len = @intCast(@min(history[history.len - 1].text.len, std.math.maxInt(u32)));- break :blk history[history.len - 1].text;- } else "";- const model = if (ctx) |p| @as(*repl_glue.ReplCtx, @ptrCast(@alignCast(p))).provider.model else "";- obs.prompt(last_len, model);-- var session_storage: Session = undefined;- const session = tls orelse blk: {- session_storage.init(gpa, 0xac01);- break :blk &session_storage;- };- session.ensure();-- const rstream = liveStream(stream);- var apply: Apply = .{ .queue = events, .stream = rstream, .show_thinking = params.thinking };- defer apply.deinit(gpa);- var transcript: Transcript = .{ .gpa = gpa, .session_id = session.session_id, .apply = &apply };- var bridge: tui_sink.Bridge = .{- .queue = events,- .stream = rstream,- .show_thinking = params.thinking,- .acp_owns_transcript = true,- };- var fan: Fanout = .{- .first = .{ .ctx = @ptrCast(&transcript), .vt = &transcript_vt },- .second = tui_sink.forBridge(&bridge),- };- engine_sink.bindTurnSink(.{ .ctx = @ptrCast(&fan), .vt = &fan_vt });- defer engine_sink.unbindTurnSink();- const permission = @import("engine_permission.zig");- const previous_permission = permission.bind(.{ .ctx = events, .request = requestPermission });- defer _ = permission.bind(previous_permission);-- acp_engine.cancel_flag.store(false, .release);- session.pending = .{- .ctx = ctx,- .gpa = gpa,- .history = turns.items,- .params = .{- .effort = @enumFromInt(@intFromEnum(params.effort)),- .fast = params.fast,- .thinking = params.thinking,- .ultracode = params.ultracode,- .mode = switch (params.mode) {- .normal => .normal,- .plan => .plan,- .always_approve => .always_approve,- },- .strict = params.strict,- .goal = params.goal,- },- .stream = rstream,- };- defer session.pending = null;-- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- const arena = arena_state.allocator();- const line = promptJson(arena, session.next_rpc, session.session_id, user_text) catch {- if (telemetry.g_telem) |t| t.countTurn() else obs.turn(.failed);- return null;- };- session.next_rpc += 1;- var aw: Io.Writer.Allocating = .init(gpa);- defer aw.deinit();- acp.handleLine(&session.dispatch, arena, &aw.writer, line) catch {- obs.turn(.failed);- return null;- };- applyBuffered(&apply, gpa, aw.writer.buffered());- const result = if (session.pending) |p| p.result else null;- if (result != null) {- if (telemetry.g_telem) |t| t.countTurn() else obs.turn(.completed);- } else obs.turn(.failed);- return result;-}--fn echoTurn(_: *anyopaque, arena: Allocator, text: []const u8) anyerror![]const u8 {- return std.fmt.allocPrint(arena, "echo:{s}", .{text});-}--test "transcript sink: tool_call keeps the catalog name, title is the path" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [32]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- var t: Transcript = .{ .gpa = std.testing.allocator, .session_id = "s1", .apply = &a };- const sink: engine_sink.EngineSink = .{ .ctx = @ptrCast(&t), .vt = &transcript_vt };- var input_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer input_state.deinit();- const input = try std.json.parseFromSliceLeaky(Value, input_state.allocator(), "{\"path\":\"note.txt\"}", .{});- sink.emit(undefined, .{ .tool_call_announced = .{ .name = "read_file", .input = input } });- const evs = q.drain();- defer q.free(evs);- try std.testing.expectEqual(@as(usize, 1), evs.len);- try std.testing.expectEqualStrings("read_file", evs[0].tool_started.name);- try std.testing.expectEqualStrings("note.txt", evs[0].tool_started.detail);-}--test "transcript sink: EngineEvent text becomes a session/update on the stream" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- var t: Transcript = .{ .gpa = std.testing.allocator, .session_id = "s1", .apply = &a };- const sink: engine_sink.EngineSink = .{ .ctx = @ptrCast(&t), .vt = &transcript_vt };- sink.emit(undefined, .{ .text_delta = .{ .text = "hello" } });- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("hello", snap);-}--test "session/prompt echo reaches the TUI stream as agent_message_chunk" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- var s: Session = undefined;- s.init(std.testing.allocator, 0xac01);- s.dispatch.turn = echoTurn;- s.ensure();- try std.testing.expect(std.mem.startsWith(u8, s.session_id, "acp-"));- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const line = try promptJson(arena_state.allocator(), 3, s.session_id, "ping");- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- try acp.handleLine(&s.dispatch, arena_state.allocator(), &aw.writer, line);- applyBuffered(&a, std.testing.allocator, aw.writer.buffered());- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("echo:ping", snap);-}--test "session/cancel latches the engine cancel flag" {- var s: Session = undefined;- s.init(std.testing.allocator, 1);- attach(&s);- defer detach();- agent_mod.Agent.esc_cancel.store(false, .release);- acp_engine.cancel_flag.store(false, .release);- cancel();- try std.testing.expect(acp_engine.cancel_flag.load(.acquire));- try std.testing.expect(agent_mod.Agent.esc_cancel.load(.acquire));- agent_mod.Agent.esc_cancel.store(false, .release);- acp_engine.cancel_flag.store(false, .release);-}--test "transcript sink: citations in reasoning answer and completion args reset on boundaries (#874)" {- var q: tui.EventQueue = .{};- var buf: [256]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };- defer a.deinit(std.testing.allocator);- var t: Transcript = .{ .gpa = std.testing.allocator, .session_id = "s1", .apply = &a };- const sink: engine_sink.EngineSink = .{ .ctx = @ptrCast(&t), .vt = &transcript_vt };- sink.emit(undefined, .stream_begin);- const thought = "why\u{E200}cite\u{E202}turn0view0\u{E201}";- for (thought) |c| sink.emit(undefined, .{ .reasoning_delta = .{ .text = &.{c} } });- const answer = "answer\u{E200}cite\u{E202}turn0view0\u{E201}";- for (answer) |c| sink.emit(undefined, .{ .text_delta = .{ .text = &.{c} } });- const args = " args\u{E200}cite\u{E202}turn1view0\u{E201}!";- for (args) |c| sink.emit(undefined, .{ .tool_arg_delta = .{ .text = &.{c} } });- sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}unfinished" } });- sink.emit(undefined, .{ .stream_aborted = .interrupted });- sink.emit(undefined, .stream_begin);- sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}transport tail" } });- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } });- sink.emit(undefined, .{ .text_delta = .{ .text = "fresh" } });- try std.testing.expectEqualStrings("why\nanswer args!fresh", buf[0..stream.len.load(.acquire)]);- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- // The ACP wire itself now carries no markers (acp_citations.zig), so- // every ACP client matches this transcript.- try writeUpdate(&aw.writer, "s1", .{ .text_delta = .{ .text = answer } });- try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "\u{E200}") == null);- try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "answer") != null);-}--test "transcript sink correlates parallel results using original engine call IDs" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [32]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var apply: Apply = .{ .queue = &q, .stream = &stream };- defer apply.deinit(std.testing.allocator);- var transcript: Transcript = .{ .gpa = std.testing.allocator, .session_id = "test", .apply = &apply };- const sink: engine_sink.EngineSink = .{ .ctx = @ptrCast(&transcript), .vt = &transcript_vt };- sink.emit(undefined, .{ .tool_call_announced = .{ .id = "read-a", .name = "read_file", .input = .{ .object = .empty } } });- sink.emit(undefined, .{ .tool_call_announced = .{ .id = "shell-b", .name = "shell", .input = .{ .object = .empty } } });- sink.emit(undefined, .{ .tool_result = .{ .id = "read-a", .name = "read_file", .text = "read output", .is_error = false } });- sink.emit(undefined, .{ .tool_result = .{ .id = "shell-b", .name = "shell", .text = "shell output", .is_error = false, .ms = 42 } });- const events = q.drain();- defer q.free(events);- try std.testing.expectEqual(@as(usize, 4), events.len);- try std.testing.expectEqualStrings("read_file", events[2].tool_finished.name);- try std.testing.expectEqualStrings("read output", events[2].tool_finished.detail);- try std.testing.expectEqualStrings("shell", events[3].tool_finished.name);- try std.testing.expectEqualStrings("shell output", events[3].tool_finished.detail);- try std.testing.expectEqual(@as(u64, 42), events[3].tool_finished.ms);-}--fn requestPermission(ctx: *anyopaque, io: Io, req: @import("engine_permission.zig").Request) @import("engine_permission.zig").Decision {- const queue: *tui.EventQueue = @ptrCast(@alignCast(ctx));- const id = queue.permission.begin(req.description) orelse return .deny;- defer queue.permission.retire(id);- while (!liveCancelled() and !acp_engine.cancel_flag.load(.acquire)) {- if (queue.permission.poll(id)) |answer| return switch (answer) {- .allow_once => .allow_once,- .deny => .deny,- };- io.sleep(.fromMilliseconds(20), .awake) catch return .deny;- }- return .deny;-}--test "TUI permission wait resumes once and cancellation retires the request" {- const Fixture = struct {- queue: tui.EventQueue = .{},- decision: @import("engine_permission.zig").Decision = .deny,- done: std.atomic.Value(bool) = .init(false),- fn run(self: *@This()) void {- self.decision = requestPermission(&self.queue, std.testing.io, .{ .call_id = "call", .tool = "write_file", .description = "write a file" });- self.done.store(true, .release);- }- };- const old_esc = agent_mod.Agent.esc_cancel.swap(false, .acq_rel);- defer agent_mod.Agent.esc_cancel.store(old_esc, .release);- const old_cancel = acp_engine.cancel_flag.swap(false, .acq_rel);- defer acp_engine.cancel_flag.store(old_cancel, .release);- for ([_]bool{ false, true }) |cancelled| {- acp_engine.cancel_flag.store(false, .release);- var fixture: Fixture = .{};- const thread = try std.Thread.spawn(.{}, Fixture.run, .{&fixture});- defer thread.join();- defer acp_engine.cancel_flag.store(true, .release);- var request_id: ?u64 = null;- for (0..1000) |_| {- if (fixture.queue.permission.peek()) |request| {- request_id = request.id;- break;- }- try std.testing.io.sleep(.fromMilliseconds(1), .awake);- }- const id = request_id orelse return error.PermissionNotDelivered;- if (cancelled) acp_engine.cancel_flag.store(true, .release) else try std.testing.expect(fixture.queue.permission.respond(id, .allow_once));- for (0..1000) |_| {- if (fixture.done.load(.acquire)) break;- try std.testing.io.sleep(.fromMilliseconds(1), .awake);- }- try std.testing.expect(fixture.done.load(.acquire));- try std.testing.expectEqual(if (cancelled) @import("engine_permission.zig").Decision.deny else .allow_once, fixture.decision);- try std.testing.expect(fixture.queue.permission.peek() == null);- acp_engine.cancel_flag.store(false, .release);- }-}diff --git a/src/tui_acp_updates.zig b/src/tui_acp_updates.zigdeleted file mode 100644index 3f49cd75..00000000--- a/src/tui_acp_updates.zig+++ /dev/null@@ -1,298 +0,0 @@-//! ACP transcript decoding, independent of live session and Agent lifecycle.-const std = @import("std");-const Allocator = std.mem.Allocator;-const Value = std.json.Value;-const tui = @import("tui");-const repl = @import("repl.zig");-const util = @import("util.zig");-const label = @import("agent_tool_label.zig");-const citations = @import("cite_markup.zig");--/// Maps one ACP `session/update` line onto the TUI stream / event queue.-pub const Apply = struct {- queue: *tui.EventQueue,- stream: *repl.StreamBuf,- show_thinking: bool = false,- reasoning_open: bool = false,- reasoning_citations: citations.Stream = .{},- answer_citations: citations.Stream = .{},- pending: std.StringHashMapUnmanaged([]u8) = .empty,-- pub fn deinit(self: *Apply, gpa: Allocator) void {- var it = self.pending.iterator();- while (it.next()) |entry| {- gpa.free(entry.key_ptr.*);- gpa.free(entry.value_ptr.*);- }- self.pending.deinit(gpa);- }-- pub fn reset(self: *Apply) void {- self.reasoning_citations = .{};- self.answer_citations = .{};- self.reasoning_open = false;- }-};--pub fn applyBuffered(a: *Apply, gpa: Allocator, bytes: []const u8) void {- var it = std.mem.splitScalar(u8, bytes, '\n');- while (it.next()) |line| applyLine(a, gpa, line);-}--pub fn applyLine(a: *Apply, gpa: Allocator, line: []const u8) void {- const trimmed = std.mem.trim(u8, line, " \t\r\n");- if (trimmed.len == 0) return;- var parsed = std.json.parseFromSlice(Value, gpa, trimmed, .{}) catch return;- defer parsed.deinit();- if (parsed.value != .object) return;- const method = util.strFieldObj(parsed.value.object, "method") orelse return;- if (!std.mem.eql(u8, method, "session/update")) return;- const params = parsed.value.object.get("params") orelse return;- if (params != .object) return;- const update = params.object.get("update") orelse return;- if (update != .object) return;- const kind = util.strFieldObj(update.object, "sessionUpdate") orelse return;- if (std.mem.eql(u8, kind, "agent_thought_chunk") or std.mem.eql(u8, kind, "agent_message_chunk")) {- applyChunk(a, std.mem.eql(u8, kind, "agent_thought_chunk"), contentText(update.object) orelse return);- return;- }- if (std.mem.eql(u8, kind, "tool_call")) {- const title = util.strFieldObj(update.object, "title") orelse "tool";- const name = util.strFieldObj(update.object, "name") orelse title;- if (label.skipTranscript(name)) return;- const id = util.strFieldObj(update.object, "toolCallId") orelse "";- if (a.pending.contains(id) or a.pending.count() >= tui.EventQueue.cap) return;- const owned_id = gpa.dupe(u8, id) catch return;- const owned_name = gpa.dupe(u8, name) catch {- gpa.free(owned_id);- return;- };- a.pending.put(gpa, owned_id, owned_name) catch {- gpa.free(owned_id);- gpa.free(owned_name);- return;- };- a.queue.push(.{ .tool_started = .{ .name = name, .detail = cap(title, 160) } });- return;- }- if (std.mem.eql(u8, kind, "tool_call_update")) {- if (tui.rawStream()) |raw| raw.len.store(0, .release);- const status = util.strFieldObj(update.object, "status") orelse return;- if (!std.mem.eql(u8, status, "completed") and !std.mem.eql(u8, status, "failed")) return;- const id = util.strFieldObj(update.object, "toolCallId") orelse "";- const entry = a.pending.fetchRemove(id);- defer if (entry) |item| {- gpa.free(item.key);- gpa.free(item.value);- };- const denied = if (update.object.get("denied")) |v| v == .bool and v.bool else false;- const name = if (entry) |item| item.value else if (denied)- (util.strFieldObj(update.object, "name") orelse return)- else- return;- if (label.skipTranscript(name)) return;- const tool: tui.ToolEvent = .{- .name = name,- .detail = cap(updateText(update.object), 80),- .is_error = std.mem.eql(u8, status, "failed"),- .denied = denied,- .ms = @intCast(@max(0, util.intFieldObj(update.object, "durationMs", 0))),- };- a.queue.push(if (denied) .{ .tool_rejected = tool } else .{ .tool_finished = tool });- }-}--fn contentText(update: std.json.ObjectMap) ?[]const u8 {- const content = update.get("content") orelse return null;- if (content != .object) return null;- return util.strFieldObj(content.object, "text");-}--fn updateText(update: std.json.ObjectMap) []const u8 {- const content = update.get("content") orelse return "";- if (content != .array or content.array.items.len == 0) return "";- const first = content.array.items[0];- if (first != .object) return "";- const inner = first.object.get("content") orelse return "";- if (inner != .object) return "";- return util.strFieldObj(inner.object, "text") orelse "";-}--fn cap(s: []const u8, n: usize) []const u8 {- const line = if (std.mem.indexOfScalar(u8, s, '\n')) |i| s[0..i] else s;- return util.utf8Prefix(line, n);-}--/// The in-process transport can pass text directly; wire clients decode into this same path.-pub fn applyChunk(a: *Apply, thinking: bool, text: []const u8) void {- if (text.len == 0 or (thinking and !a.show_thinking)) return;- const filter = if (thinking) &a.reasoning_citations else &a.answer_citations;- // Batch visible bytes: the live tail publishes atomically on each append.- var visible: [1024]u8 = undefined;- var len: usize = 0;- for (text) |c| {- var scratch: [3]u8 = undefined;- const clean = filter.byte(c, &scratch);- if (clean.len == 0) continue;- if (thinking) {- a.reasoning_open = true;- } else if (a.reasoning_open) {- a.reasoning_open = false;- a.stream.appendBytes("\n");- }- if (len + clean.len > visible.len) {- a.stream.appendBytes(visible[0..len]);- len = 0;- }- @memcpy(visible[len..][0..clean.len], clean);- len += clean.len;- }- if (len != 0) a.stream.appendBytes(visible[0..len]);-}--test "applyLine: thought then text land on the live tail" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };- defer a.deinit(std.testing.allocator);- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"type\":\"text\",\"text\":\"why\"}}}}");- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"type\":\"text\",\"text\":\"hi\"}}}}");- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("why\nhi", snap);-}--test "applyLine: tool_call then tool_call_update become typed rows" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [32]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call\",\"name\":\"read_file\",\"title\":\"note.txt\",\"kind\":\"read\",\"status\":\"in_progress\"}}}");- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call_update\",\"status\":\"completed\",\"content\":[{\"type\":\"content\",\"content\":{\"type\":\"text\",\"text\":\"ok\\nmore\"}}]}}}");- const evs = q.drain();- defer q.free(evs);- try std.testing.expectEqual(@as(usize, 2), evs.len);- try std.testing.expectEqualStrings("read_file", evs[0].tool_started.name);- try std.testing.expectEqualStrings("note.txt", evs[0].tool_started.detail);- try std.testing.expectEqualStrings("ok", evs[1].tool_finished.detail);- try std.testing.expect(!evs[1].tool_finished.is_error);-}--test "direct chunks match ACP wire decoding without allocations" {- var q: tui.EventQueue = .{};- var direct_buf: [128]u8 = undefined;- var wire_buf: [128]u8 = undefined;- var direct: repl.StreamBuf = .{ .buf = &direct_buf };- var wire: repl.StreamBuf = .{ .buf = &wire_buf };- var a: Apply = .{ .queue = &q, .stream = &direct, .show_thinking = true };- defer a.deinit(std.testing.allocator);- var b: Apply = .{ .queue = &q, .stream = &wire, .show_thinking = true };- defer b.deinit(std.testing.allocator);- applyChunk(&a, true, "why日");- applyChunk(&a, false, "hello🚀");- applyLine(&b, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"text\":\"why日\"}}}}");- applyLine(&b, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_message_chunk\",\"content\":{\"text\":\"hello🚀\"}}}}");- try std.testing.expectEqualStrings(wire.buf[0..wire.len.load(.acquire)], direct.buf[0..direct.len.load(.acquire)]);- try std.testing.expectEqual(b.reasoning_open, a.reasoning_open);-}--test "hidden reasoning and empty chunks do not alter transcript" {- var q: tui.EventQueue = .{};- var buf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- applyChunk(&a, true, "hidden");- applyChunk(&a, false, "");- applyChunk(&a, false, "visible");- try std.testing.expectEqualStrings("visible", stream.buf[0..stream.len.load(.acquire)]);- try std.testing.expect(!a.reasoning_open);-}--test "ACP citation display filters every byte split and independent channels (#874)" {- const raw = "before日\u{E200}cite\u{E202}turn0view0\u{E201}after\u{E202}🚀\u{E201}";- for (0..raw.len + 1) |split| {- var q: tui.EventQueue = .{};- var buf: [256]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };- defer a.deinit(std.testing.allocator);- applyChunk(&a, true, "why\u{E200}cite");- applyChunk(&a, false, raw[0..split]);- applyChunk(&a, false, raw[split..]);- applyChunk(&a, true, "hidden\u{E201}done");- try std.testing.expectEqualStrings("why\nbefore日after🚀done", buf[0..stream.len.load(.acquire)]);- }-}--test "ACP citation-only chunks do not add reasoning separators and reset drops partial spans (#874)" {- var q: tui.EventQueue = .{};- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };- defer a.deinit(std.testing.allocator);- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"text\":\"\\ue200cite\\ue202turn0view0\\ue201\"}}}}");- applyChunk(&a, false, "ok");- applyChunk(&a, true, "\xee\x88");- applyChunk(&a, false, "\u{E200}unterminated");- a.reset();- applyChunk(&a, true, "fresh");- applyChunk(&a, false, "answer");- try std.testing.expectEqualStrings("okfresh\nanswer", buf[0..stream.len.load(.acquire)]);-}--test "ACP interleaved tool IDs retain names and ignore duplicate and nonterminal results" {- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [32]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- const lines = [_][]const u8{- "{\"sessionUpdate\":\"tool_call\",\"toolCallId\":\"read-a\",\"name\":\"read_file\",\"title\":\"a.txt\"}",- "{\"sessionUpdate\":\"tool_call\",\"toolCallId\":\"shell-b\",\"name\":\"shell\",\"title\":\"printf done\"}",- "{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"read-a\",\"status\":\"in_progress\"}",- "{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"read-a\",\"status\":\"completed\"}",- "{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"read-a\",\"status\":\"completed\"}",- "{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"unknown\",\"status\":\"failed\"}",- "{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"shell-b\",\"status\":\"failed\"}",- };- for (lines) |line| {- const wire = try std.fmt.allocPrint(std.testing.allocator, "{{\"method\":\"session/update\",\"params\":{{\"update\":{s}}}}}", .{line});- defer std.testing.allocator.free(wire);- applyLine(&a, std.testing.allocator, wire);- }- const events = q.drain();- defer q.free(events);- try std.testing.expectEqual(@as(usize, 4), events.len);- try std.testing.expectEqualStrings("read_file", events[2].tool_finished.name);- try std.testing.expect(!events[2].tool_finished.is_error);- try std.testing.expectEqualStrings("shell", events[3].tool_finished.name);- try std.testing.expect(events[3].tool_finished.is_error);- try std.testing.expectEqual(@as(u32, 0), a.pending.count());-}--test "ACP tool previews preserve UTF8 and unannounced rejection retains its identity" {- try std.testing.expectEqualStrings("a", cap("a日", 3));- try std.testing.expectEqualStrings("a日", cap("a日", 4));- var q: tui.EventQueue = .{};- q.attach(std.testing.allocator);- defer q.deinit();- var buf: [32]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var a: Apply = .{ .queue = &q, .stream = &stream };- defer a.deinit(std.testing.allocator);- applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"tool_call_update\",\"toolCallId\":\"blocked\",\"name\":\"shell\",\"status\":\"failed\",\"denied\":true}}}");- const events = q.drain();- defer q.free(events);- try std.testing.expectEqual(@as(usize, 1), events.len);- try std.testing.expectEqualStrings("shell", events[0].tool_rejected.name);- try std.testing.expect(events[0].tool_rejected.denied);-}diff --git a/src/tui_constraint.zig b/src/tui_constraint.zigdeleted file mode 100644index 2d79b821..00000000--- a/src/tui_constraint.zig+++ /dev/null@@ -1,34 +0,0 @@-//! Host side of TUI `/never` / `/constraint`: the pager delegates to the-//! existing user-owned playbook command instead of duplicating ledger rules.--const std = @import("std");-const Allocator = std.mem.Allocator;-const Io = std.Io;--const Agent = @import("agent.zig").Agent;-const playbook_glue = @import("playbook_glue.zig");-const repl_glue = @import("repl_glue.zig");--/// Run a constraint command without entering the line-REPL picker: the-/// fullscreen TUI owns stdin, so bare `/never` returns the scoped text list.-/// Caller frees the returned text.-pub fn runSlash(root: *Agent, gpa: Allocator, line: []const u8) ?[]const u8 {- var scratch_state = std.heap.ArenaAllocator.init(gpa);- defer scratch_state.deinit();- var aw: Io.Writer.Allocating = .init(gpa);- errdefer aw.deinit();- const saved_in = root.in;- root.in = null;- defer root.in = saved_in;- const handled = playbook_glue.commandWithPromptAllocator(root, scratch_state.allocator(), root.arena, line, &aw.writer) catch- return gpa.dupe(u8, "constraint command failed; rerun /never to verify ledger state") catch null;- if (!handled) return null;- return aw.toOwnedSlice() catch null;-}--/// `engine.ConstraintFn` — reaches the live root through `ReplCtx.root`.-pub fn constraintCb(ctx: ?*anyopaque, gpa: Allocator, line: []const u8) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- const root = c.root orelse return gpa.dupe(u8, "constraint review needs a live session") catch null;- return runSlash(root, gpa, line);-}diff --git a/src/tui_goal.zig b/src/tui_goal.zigdeleted file mode 100644index 7f5c1132..00000000--- a/src/tui_goal.zig+++ /dev/null@@ -1,152 +0,0 @@-//! Host-side `/goal` lifecycle for the fullscreen TUI (#716).-//!-//! The pager publishes a `GoalOp`; this module applies the same transitions-//! the line REPL uses (`goal_flow.applyGoalSet`, pause/resume/clear). Typed-//! TUI goals stay non-standing so `attempt_completion` can retire them.-//! Reached through `test_hooks.zig` — without that import these tests compile-//! to nothing and the suite still reports green.--const std = @import("std");-const Allocator = std.mem.Allocator;--const agent_mod = @import("agent.zig");-const goal_flow = @import("goal_flow.zig");-const goal_state = @import("goal_state.zig");-const prompts = @import("prompts.zig");-const repl_glue = @import("repl_glue.zig");-const session = @import("session.zig");-const Agent = agent_mod.Agent;--pub const Op = enum { none, set, clear, pause, unpause };--/// Apply one published TUI `/goal` verb to the live root. `.none` is a no-op-/// so `/strict` and the exit snapshot cannot mint or wipe a goal.-pub fn apply(root: *Agent, op: Op, text: []const u8, now_ms: i64) void {- switch (op) {- .none => {},- .set => {- const trimmed = std.mem.trim(u8, text, " \t\r\n");- if (trimmed.len == 0) return;- const owned = root.arena.dupe(u8, trimmed) catch return;- _ = goal_flow.applyGoalSet(root, owned, now_ms);- prompts.pinStandingGoal(root, root.arena);- },- .clear => {- if (root.goal == null) return;- root.goal = null;- goal_state.resetCompletionGate(root);- root.goal_note_fp = 0;- prompts.pinStandingGoal(root, root.arena);- },- .pause => {- if (root.goal) |*g| {- g.status = .paused;- g.updated_ms = now_ms;- prompts.pinStandingGoal(root, root.arena);- }- },- .unpause => {- if (root.goal) |*g| {- g.status = .active;- g.updated_ms = now_ms;- root.goal_note_fp = 0;- prompts.pinStandingGoal(root, root.arena);- }- },- }-}--fn flowRoot(arena: Allocator) Agent {- var root: Agent = undefined;- root.arena = arena;- root.sys_base = ""; // undefined would skip the empty check in pinStandingGoal- root.sub = false;- root.review_mode = false;- root.todos = .empty;- root.goal = null;- root.todos_dirty = false;- root.completion_gate_armed = false;- root.completion_refused = false;- root.completed = null;- root.goal_note_fp = 0;- root.pending_goal_note = null;- root.history_rewrites = 0;- root.tool_calls_this_turn = 0;- root.loop_deadline_ms = null;- return root;-}--/// The loadSession goal slice: parse the saved object, then reconcile.-fn resumeGoal(arena: Allocator, root: *Agent, json: []const u8) !void {- const parsed = try std.json.parseFromSliceLeaky(std.json.Value, arena, json, .{ .allocate = .alloc_always });- root.goal = if (parsed.object.get("goal")) |v| session.goalFromValue(v, 1_000) else null;- root.todos.clearRetainingCapacity();- if (parsed.object.get("todos")) |tv| try session.appendTodosFromValue(arena, &root.todos, tv);- root.todos_dirty = false;- root.completion_gate_armed = false;- root.completion_refused = false;- _ = goal_state.reconcileRestored(root);-}--test "#716 typed TUI /goal is retirable and does not steer after resume" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const ar = arena_state.allocator();- var root = flowRoot(ar);-- apply(&root, .set, "ship it", 5_000);- try std.testing.expect(root.goal != null);- try std.testing.expect(!root.goal.?.standing);- try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);- try std.testing.expect((try repl_glue.goalSteeringNote(ar, root.goal)).len > 0);-- // The old host callback minted standing=true, so this returned false and- // the objective stayed active across /resume.- try std.testing.expect(goal_state.retireOnCompletion(&root, 9_000));- try std.testing.expectEqual(agent_mod.GoalStatus.complete, root.goal.?.status);- try std.testing.expectEqualStrings("", try repl_glue.goalSteeringNote(ar, root.goal));-- const saved = try std.fmt.allocPrint(ar,- \\{{"goal":{{"objective":"{s}","status":"{s}","epoch":{d},"standing":{s},"created_ms":{d},"updated_ms":{d}}},"todos":[]}}- , .{- root.goal.?.objective,- @tagName(root.goal.?.status),- root.goal.?.epoch,- if (root.goal.?.standing) "true" else "false",- root.goal.?.created_ms,- root.goal.?.updated_ms,- });- var resumed = flowRoot(ar);- try resumeGoal(ar, &resumed, saved);- try std.testing.expect(resumed.goal != null);- try std.testing.expect(!resumed.goal.?.standing);- try std.testing.expectEqual(agent_mod.GoalStatus.complete, resumed.goal.?.status);- try std.testing.expectEqualStrings("", try repl_glue.goalSteeringNote(ar, resumed.goal));-}--test "#716 TUI /goal pause stops steering; none does not mint a standing goal" {- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const ar = arena_state.allocator();- var root = flowRoot(ar);-- apply(&root, .none, "ship it", 1);- try std.testing.expect(root.goal == null);-- apply(&root, .set, "ship it", 2);- apply(&root, .none, "", 3);- try std.testing.expect(root.goal != null);- try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);-- apply(&root, .pause, "ship it", 4);- try std.testing.expectEqual(agent_mod.GoalStatus.paused, root.goal.?.status);- try std.testing.expectEqualStrings("", try repl_glue.goalSteeringNote(ar, root.goal));-- apply(&root, .unpause, "ship it", 5);- try std.testing.expectEqual(agent_mod.GoalStatus.active, root.goal.?.status);- try std.testing.expect((try repl_glue.goalSteeringNote(ar, root.goal)).len > 0);-- apply(&root, .clear, "", 6);- try std.testing.expect(root.goal == null);- try std.testing.expectEqualStrings("", try repl_glue.goalSteeringNote(ar, root.goal));-}diff --git a/src/tui_launch.zig b/src/tui_launch.zigdeleted file mode 100644index b6d7c4d7..00000000--- a/src/tui_launch.zig+++ /dev/null@@ -1,599 +0,0 @@-//! Glue: launch the Grok-style TUI against the real agent loop.-//! Adapts TUI engine types onto `repl_glue` so we do not duplicate runTurn.--const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;-const args = @import("args.zig");-const agent_mod = @import("agent.zig");-const provider_mod = @import("provider.zig");-const billing = @import("billing.zig");-const pricing = @import("pricing.zig");-const providers = @import("providers.zig");-const process_runner = @import("process_runner.zig");-const repl = @import("repl.zig");-const version_status = @import("version_status.zig");-const update_cmd = @import("update_cmd.zig");-const repl_bash = @import("repl_bash.zig");-const repl_glue = @import("repl_glue.zig");-const session = @import("session.zig");-const tui = @import("tui");-const tui_peer = @import("tui_peer.zig");-const tui_constraint = @import("tui_constraint.zig");-const tui_session = @import("tui_session.zig");-const engine_sink = @import("engine_sink.zig");-const tui_sink = @import("tui_sink.zig");-const tui_acp = @import("tui_acp.zig");-const idle_wake = @import("idle_wake_sources.zig");-const job_wait = @import("job_wait.zig");-const util = @import("util.zig");-const obs = @import("obs.zig");-const vision = @import("vision.zig");-const doctor = @import("doctor.zig");-const tui_goal = @import("tui_goal.zig");-const builtin = @import("builtin");--/// Live root for `/doctor`. The HUD callback has no ctx argument.-var g_doctor_root: ?*agent_mod.Agent = null;--/// `graff tui` (and TTY `graff repl`). Bare `graff` stays the default session.-pub fn wantsTui(flags: args.Flags, json_mode: bool) bool {- if (json_mode or flags.oneshot_prompt != null) return false;- return flags.positionals.items.len > 0 and std.mem.eql(u8, flags.positionals.items[0], "tui");-}--pub fn maybeRun(- gpa: Allocator,- io: Io,- environ_map: anytype,- root: *agent_mod.Agent,- keys: *provider_mod.Keys,- client: *std.http.Client,- arena: Allocator,- flags: args.Flags,- json_mode: bool,- cwd: []const u8,-) !bool {- if (!wantsTui(flags, json_mode)) return false;- run(gpa, io, environ_map, root, keys, client, arena, cwd, flags.yolo_flag) catch |err| {- if (err == error.NotATty) {- var buf: [256]u8 = undefined;- var w = Io.File.stderr().writer(io, &buf);- w.interface.writeAll("graff tui needs a real terminal (stdout is not a TTY).\n") catch {};- w.interface.flush() catch {};- return true;- }- return err;- };- return true;-}--pub fn run(- gpa: Allocator,- io: Io,- environ_map: anytype,- root: *agent_mod.Agent,- keys: *provider_mod.Keys,- client: *std.http.Client,- arena: Allocator,- cwd: []const u8,- yolo: bool,-) !void {- @import("subagent_interactive.zig").configure(true);- defer @import("subagent_interactive.zig").configure(false);- root.ensureStoredKeys(keys);- providers.ensureModelQueryCatalogs(root, keys.*, "");- try root.ensureRootTools(.anthropic);- try root.ensureRootTools(.openai);- try root.ensureRootTools(.responses);- var repl_ctx = repl_glue.ReplCtx{- .io = io,- .client = client,- .keys = keys.*,- .home = root.home,- .provider = root.provider,- .fallback_allow = root.fallback_allow,- .fallback_active = root.fallback_active,- .fallback_blocked = root.fallback_blocked,- .registry = root.registry,- .tracer = root.tracer,- .run_budget = root.run_budget,- // Keep the uncomposed base: each turn reads the live ledger once.- // Reusing root.sys_normal here would retain retired rules and stack- // another playbook block when repl_turn calls setSystemPrompts.- .sys_normal = if (root.sys_base.len > 0) root.sys_base else root.sys_normal,- .tools_anthropic = root.tools_anthropic,- .tools_openai = root.tools_openai,- .tools_responses = root.tools_responses,- .root = root,- };- // #551: the session's conversation belongs to the engine and outlives every- // turn, so tool_use/tool_result blocks accumulate the way mainloop's root- // messages do instead of being rebuilt from rendered rows each turn. It is- // created here, on the frame that owns the whole TUI session.- var convo = repl_glue.Conversation.init(gpa);- defer convo.deinit();- try tui_session.seed(&convo, root);- repl_ctx.convo = &convo;- const initial_history = try tui_session.visibleTurns(arena, root.messages);- const entries = modelEntries(arena, keys.*);- engine_sink.hosted_frontend = true;- defer engine_sink.hosted_frontend = false;- obs.ensureSession();- g_doctor_root = root;- defer g_doctor_root = null;- var acp_session: tui_acp.Session = undefined;- acp_session.init(gpa, @as(u64, @bitCast(util.unixMs(io))));- tui_acp.attach(&acp_session);- defer tui_acp.detach();- acp_session.ensure();- tui.setFollowupFn(noteFollowupCb);- defer tui.setFollowupFn(null);- tui.setSteerFns(@import("steer_now.zig").send, @import("steer_now.zig").reclaim);- defer tui.setSteerFns(null, null);- try tui.run(gpa, io, environ_map, .{- .turn_ctx = &repl_ctx,- .turn_fn = turnCb,- .model_fn = modelCb,- .cancel_fn = cancelCb,- .model_name = root.provider.model,- .model_provider = root.provider.id,- .initial_history = initial_history,- .session_name = root.session_name,- .initial_goal = if (root.goal) |goal| goal.objective else "",- .initial_strict = root.strict,- .initial_ultracode = root.ultracode_mode,- .model_entries = entries,- .cwd = cwd,- .yolo = yolo,- .hud_fn = hudCb,- .paste_fn = pasteCb,- .bash_fn = bashCb,- .files_fn = filesCb,- .copy_fn = copyCb,- .compact_fn = compactCb,- .history_fn = historyCb,- .resume_fn = tui_session.resumeCb,- .sessions_fn = tui_session.sessionsCb,- .state_fn = stateCb,- .emergency_fn = emergencyCb,- .idle_wake_fn = idleWakeCb,- .peer_fn = tui_peer.peerCb,- .constraint_fn = tui_constraint.constraintCb,- .version_fn = versionCb,- .update_fn = updateCb,- });- try tui_session.syncRoot(&convo, root);-}--fn stateCb(ctx: ?*anyopaque, state: tui.SessionState) void {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return));- const root = c.root orelse return;- root.strict = state.strict;- root.ultracode_mode = state.ultracode;- if (state.session_name.len > 0 and !std.mem.eql(u8, state.session_name, root.session_name))- root.session_name = root.arena.dupe(u8, state.session_name) catch root.session_name;- // Typed `/goal` is retirable (applyGoalSet, standing=false). `/strict` and- // the exit snapshot publish `.none` and must not mint a standing flag (#716).- const op: tui_goal.Op = switch (state.goal_op) {- .none => .none,- .set => .set,- .clear => .clear,- .pause => .pause,- .unpause => .unpause,- };- tui_goal.apply(root, op, state.goal, util.unixMs(root.io));- if (state.goal_op != .none)- session.saveSession(root, root.arena, root.session_name) catch {};-}--fn emergencyCb(_: ?*anyopaque) void {- session.flushSaves();-}--/// The transcript was cut, so cut the conversation the same way: /new starts-/// over, /rewind takes back the last prompt and everything the engine did for-/// it. Compaction does NOT come through here — it rewrites the conversation-/// rather than discarding it.-fn historyCb(ctx: ?*anyopaque, op: tui.HistoryOp) void {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return));- const convo = c.convo orelse return;- switch (op) {- .reset => {- convo.reset();- @import("rlm_spec.zig").resetBindsSession(c.io);- },- .rewind => convo.rewind(),- }-}--fn updateCb(ctx: ?*anyopaque, gpa: Allocator, action: []const u8) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- return update_cmd.hostAction(c.io, gpa, c.home, action);-}--fn idleWakeCb(ctx: ?*anyopaque, buf: []u8) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- const name = if (c.root) |root| root.session_name else "";- return idle_wake.takeIdleWake(c.io, name, buf);-}--fn versionCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- return version_status.commandText(c.io, gpa, @import("build_options").version) catch null;-}--/// Overlay the TUI preview buffer as a repl.StreamBuf so replTurnCb's-/// appendBytes publish `stream.len` as bytes arrive. Layout is identical-/// (buf + atomic len); a copy would hide the live tail until the turn ends.-fn liveStream(stream: *tui.StreamBuf) *repl.StreamBuf {- comptime {- if (@sizeOf(tui.StreamBuf) != @sizeOf(repl.StreamBuf) or- @offsetOf(tui.StreamBuf, "buf") != @offsetOf(repl.StreamBuf, "buf") or- @offsetOf(tui.StreamBuf, "len") != @offsetOf(repl.StreamBuf, "len"))- @compileError("tui.StreamBuf and repl.StreamBuf must stay layout-identical");- }- return @ptrCast(stream);-}--fn turnCb(- ctx: ?*anyopaque,- gpa: Allocator,- history: []const tui.Turn,- params: tui.Params,- stream: *tui.StreamBuf,- events: *tui.EventQueue,-) ?[]const u8 {- // ADR 0041: the pager is an in-process ACP client. Thought / tool / text- // arrive as session/update; meters and notices stay on tui_sink.- return tui_acp.turn(ctx, gpa, history, params, stream, events);-}--/// The catalog the picker draws, with the provider column the TUI used to be-/// blind to. Rows for providers with no credential are KEPT — the catalog is-/// the map of what exists — and marked so the picker can dim them.-///-/// The cost class is classified HERE, on the src side, because it is a fact-/// about credentials (src/billing.zig owns the rule); the TUI is handed the-/// answer. The two enums are mapped by hand so a new class on either side is a-/// compile error rather than a badge that quietly means nothing.-pub fn modelEntries(arena: Allocator, keys: provider_mod.Keys) []const tui.ModelEntry {- var out = std.array_list.Managed(tui.ModelEntry).init(arena);- for (pricing.models()) |mi| {- if (mi.name.len == 0) continue;- out.append(.{- .name = mi.name,- .provider = mi.provider,- .has_key = keys.get(mi.provider) != null,- .cost = switch (billing.costFor(mi.provider, keys.source(mi.provider))) {- .plan => .plan,- .credits => .credits,- .api => .api,- .local => .local,- },- }) catch break;- }- return out.items;-}--/// A picker row names its provider; a typed `/model <name>` does not and is-/// routed by name, exactly as before.-fn modelCb(ctx: ?*anyopaque, gpa: Allocator, provider: []const u8, name: []const u8) ?tui.Picked {- const picked = repl_glue.replModelPick(ctx, gpa, provider, name) orelse return null;- obs.modelSwitch(picked.model);- return .{ .model = picked.model, .provider = picked.provider };-}--fn compactCb(ctx: ?*anyopaque, gpa: Allocator, history: []const tui.Turn, out: *tui.CompactOut) bool {- var turns = std.array_list.Managed(repl.Turn).init(gpa);- defer {- for (turns.items) |t| gpa.free(t.text);- turns.deinit();- }- for (history) |t| {- const text = gpa.dupe(u8, t.text) catch continue;- turns.append(.{ .role = switch (t.role) {- .user => .user,- .assistant => .assistant,- }, .text = text, .notification = t.notification }) catch gpa.free(text);- }- var raw: @import("repl_compact.zig").CompactOut = .{};- const ok = @import("repl_compact.zig").replCompactCb(ctx, gpa, turns.items, &raw);- out.note = raw.note;- if (raw.turns.len == 0) {- out.turns = &.{};- return ok;- }- const converted = gpa.alloc(tui.Turn, raw.turns.len) catch {- for (raw.turns) |t| gpa.free(t.text);- gpa.free(raw.turns);- return ok;- };- for (raw.turns, 0..) |t, i| {- converted[i] = .{ .role = switch (t.role) {- .user => .user,- .assistant => .assistant,- }, .text = t.text, .notification = t.notification };- }- gpa.free(raw.turns);- out.turns = converted;- return ok;-}--fn noteFollowupCb() void {- job_wait.noteFollowup();-}--fn cancelCb(ctx: ?*anyopaque) void {- tui_acp.cancel();- repl_glue.replCancelCb(ctx);-}--fn pasteCb(ctx: ?*anyopaque, dest: []u8, owned: *bool) isize {- owned.* = false;- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return pasteErr(dest, "no session")));- if (!vision.visionCapable(c.provider)) return pasteErr(dest, vision.no_vision_message);- if (builtin.os.tag != .macos) return pasteErr(dest, "clipboard image paste is macOS-only — use /image <path>");- const gpa = std.heap.page_allocator;- const grab = switch (vision.grabClipboardImage(c.io, gpa)) {- .ok => |g| g,- .empty => return 0,- .failed => |kind| return pasteErr(dest, vision.pasteFailMessage(kind)),- };- const result = @import("tui_paste_transfer.zig").transfer(grab, c.io, gpa, dest) orelse- return pasteErr(dest, "clipboard image path is too long");- owned.* = result.owned;- return @intCast(result.len);-}--fn pasteErr(dest: []u8, msg: []const u8) isize {- const n = @min(msg.len, dest.len);- @memcpy(dest[0..n], msg[0..n]);- return -@as(isize, @intCast(n));-}--/// `!cmd` bash mode — the engine's bash tool, gate and all (repl_bash.zig).-/// It used to call process_runner directly, which is how `/plan` + `!rm -rf`-/// ran the rm and how the model never learned what the user had run (#551).-fn bashCb(ctx: ?*anyopaque, gpa: Allocator, cmd: []const u8, params: tui.Params) ?[]const u8 {- return repl_bash.replBashCb(ctx, gpa, cmd, .{- .effort = @enumFromInt(@intFromEnum(params.effort)),- .fast = params.fast,- .thinking = params.thinking,- .ultracode = params.ultracode,- .mode = switch (params.mode) {- .normal => .normal,- .plan => .plan,- .always_approve => .always_approve,- },- .strict = params.strict,- .goal = params.goal,- });-}--/// @-mention source: tracked+untracked files (gitignore honored), find fallback.-fn filesCb(ctx: ?*anyopaque, gpa: Allocator) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- if (builtin.os.tag == .windows) return null;- const cmd = "(git ls-files --cached --others --exclude-standard 2>/dev/null || find . -type f -not -path '*/.*' 2>/dev/null | sed 's|^\\./||') | head -3000";- const run_res = process_runner.runCapped(gpa, c.io, &.{ "/bin/sh", "-c", cmd }, 512 * 1024, 4 * 1024, 10_000) catch return null;- gpa.free(run_res.stderr);- if (run_res.stdout.len == 0) {- gpa.free(run_res.stdout);- return null;- }- return run_res.stdout;-}--fn copyCb(ctx: ?*anyopaque, text: []const u8) bool {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return false));- const argv: []const []const u8 = switch (builtin.os.tag) {- .macos => &.{"pbcopy"},- .linux => &.{ "xclip", "-selection", "clipboard" },- else => return false,- };- var child = std.process.spawn(c.io, .{- .argv = argv,- .stdin = .pipe,- .stdout = .ignore,- .stderr = .ignore,- }) catch return false;- var wbuf: [4096]u8 = undefined;- var fw = child.stdin.?.writerStreaming(c.io, &wbuf);- fw.interface.writeAll(text) catch {};- fw.interface.flush() catch {};- child.stdin.?.close(c.io);- child.stdin = null;- const term = child.wait(c.io) catch return false;- return term == .exited and term.exited == 0;-}--fn writeDoctor(w: *Io.Writer) void {- const root = g_doctor_root orelse {- w.writeAll("doctor unavailable (no live session)\n") catch {};- return;- };- var scratch: [8192]u8 = undefined;- var fba = std.heap.FixedBufferAllocator.init(&scratch);- const arena = fba.allocator();- const st = doctor.snapshotWithLive(arena, root, util.unixMs(root.io)) catch {- w.writeAll("doctor snapshot failed\n") catch {};- return;- };- const checks = doctor.run(arena, st) catch {- w.writeAll("doctor run failed\n") catch {};- return;- };- const text = doctor.render(arena, checks) catch {- w.writeAll("doctor render failed\n") catch {};- return;- };- w.writeAll(text) catch {};-}--fn hudCb(kind: tui.HudKind, buf: []u8) usize {- var w: Io.Writer = .fixed(buf);- switch (kind) {- .debug => obs.renderHud(&w) catch {},- .usage => obs.renderUsage(&w) catch {},- .doctor => writeDoctor(&w),- }- if (kind == .debug) {- if (tui_acp.sessionId()) |sid| w.print(" acp {s}\n", .{sid}) catch {};- }- return w.buffered().len;-}--test {- _ = tui;- _ = tui_sink;- _ = tui_acp;- _ = repl_bash;- _ = tui_peer;-}--test "debug HUD names the in-process ACP session" {- var s: tui_acp.Session = undefined;- s.init(std.testing.allocator, 1);- tui_acp.attach(&s);- defer tui_acp.detach();- s.ensure();- var buf: [2048]u8 = undefined;- const n = hudCb(.debug, &buf);- try std.testing.expect(std.mem.indexOf(u8, buf[0..n], s.session_id) != null);-}--test "hudCb doctor without a live root says so" {- g_doctor_root = null;- var buf: [256]u8 = undefined;- const n = hudCb(.doctor, &buf);- try std.testing.expect(std.mem.indexOf(u8, buf[0..n], "no live session") != null);-}--test "hudCb usage/debug use the cost-tally renderer, not chars" {- const io = std.testing.io;- const c = &pricing.g_cost;- c.mutex.lockUncancelable(io);- c.usd = 0;- c.in_tokens = 0;- c.cache_tokens = 0;- c.cache_write_tokens = 0;- c.out_tokens = 0;- c.api_calls = 0;- c.sub_calls = 0;- c.unpriced_calls = 0;- c.missing_usage_calls = 0;- c.unreported_failed_attempts = 0;- c.mutex.unlock(io);- defer {- c.mutex.lockUncancelable(io);- c.usd = 0;- c.in_tokens = 0;- c.cache_tokens = 0;- c.out_tokens = 0;- c.api_calls = 0;- c.sub_calls = 0;- c.unpriced_calls = 0;- c.missing_usage_calls = 0;- c.unreported_failed_attempts = 0;- c.mutex.unlock(io);- }- obs.reset();- defer obs.reset();- obs.attach(io);- pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 0, 50);- obs.turn(.completed);-- var cost_buf: [256]u8 = undefined;- var cost_w: Io.Writer = .fixed(&cost_buf);- try pricing.CostTally.render(pricing.g_cost.snap(io), &cost_w);- const cost = cost_w.buffered();-- var usage_buf: [512]u8 = undefined;- const un = hudCb(.usage, &usage_buf);- var debug_buf: [2048]u8 = undefined;- const dn = hudCb(.debug, &debug_buf);- try std.testing.expect(std.mem.indexOf(u8, usage_buf[0..un], cost) != null);- try std.testing.expect(std.mem.indexOf(u8, debug_buf[0..dn], cost) != null);- try std.testing.expect(std.mem.indexOf(u8, debug_buf[0..dn], "turns") != null);- try std.testing.expect(std.mem.indexOf(u8, usage_buf[0..un], "chars sent") == null);- try std.testing.expect(std.mem.indexOf(u8, debug_buf[0..dn], "offline") == null);-}--test "wantsTui: only the tui subcommand" {- try std.testing.expect(!wantsTui(.{}, false));- try std.testing.expect(!wantsTui(.{ .oneshot_prompt = "hi" }, false));- var tui_pos = std.ArrayList([]const u8).empty;- defer tui_pos.deinit(std.testing.allocator);- try tui_pos.append(std.testing.allocator, "tui");- try std.testing.expect(wantsTui(.{ .positionals = tui_pos }, false));- try std.testing.expect(!wantsTui(.{ .positionals = tui_pos }, true));-}--test "liveStream publishes len as appendBytes arrive" {- var buf: [64]u8 = undefined;- var tstream: tui.StreamBuf = .{ .buf = &buf };- const rstream = liveStream(&tstream);- try std.testing.expectEqual(@as(usize, 0), tstream.len.load(.acquire));- rstream.appendBytes("⚙ bash\n");- try std.testing.expectEqual(@as(usize, "⚙ bash\n".len), tstream.len.load(.acquire));- const snap = tstream.snapshot(std.testing.allocator) orelse return error.TestUnexpectedResult;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("⚙ bash\n", snap);- rstream.appendBytes("✓ bash\n");- try std.testing.expect(std.mem.endsWith(u8, tstream.buf[0..tstream.len.load(.acquire)], "✓ bash\n"));-}--test "modelEntries carries the provider column the picker was blind to" {- var keys: provider_mod.Keys = .{ .values = @splat(null) };- _ = keys.set("codex", "tok", .login);- _ = keys.set("openai", "sk-test", .environment);- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- const entries = modelEntries(arena_state.allocator(), keys);- try std.testing.expect(entries.len > 0);- try std.testing.expectEqual(pricing.models().len, entries.len);-- var codex: ?tui.ModelEntry = null;- var openai: ?tui.ModelEntry = null;- var unkeyed: ?tui.ModelEntry = null;- for (entries) |e| {- try std.testing.expect(e.provider.len > 0);- if (codex == null and std.mem.eql(u8, e.provider, "codex")) codex = e;- if (openai == null and std.mem.eql(u8, e.provider, "openai")) openai = e;- if (unkeyed == null and std.mem.eql(u8, e.provider, "anthropic")) unkeyed = e;- }- // The three classes from the report: a plan seat, a metered seat, and a- // seat with no credential that stays on the list so the user can see it.- try std.testing.expectEqual(tui.CostClass.plan, codex.?.cost);- try std.testing.expect(codex.?.has_key);- try std.testing.expectEqual(tui.CostClass.api, openai.?.cost);- try std.testing.expect(openai.?.has_key);- try std.testing.expectEqual(tui.CostClass.api, unkeyed.?.cost);- try std.testing.expect(!unkeyed.?.has_key);-}--test "the same model under two providers is two distinguishable entries" {- // gpt-5.5 is served by codex, openai and codegraff. Before this the picker- // had three rows reading "gpt-5.5" and no way to tell them apart.- var keys: provider_mod.Keys = .{ .values = @splat(null) };- _ = keys.set("codex", "tok", .login);- _ = keys.set("codegraff", "cg", .login);- var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);- defer arena_state.deinit();- var seen: usize = 0;- var costs: [8]tui.CostClass = undefined;- for (modelEntries(arena_state.allocator(), keys)) |e| {- if (!std.mem.eql(u8, e.name, "gpt-5.5")) continue;- if (seen < costs.len) costs[seen] = e.cost;- seen += 1;- }- try std.testing.expect(seen >= 2);- var has_plan = false;- var has_credits = false;- for (costs[0..@min(seen, costs.len)]) |c| {- if (c == .plan) has_plan = true;- if (c == .credits) has_credits = true;- }- try std.testing.expect(has_plan and has_credits);-}diff --git a/src/tui_paste_transfer.zig b/src/tui_paste_transfer.zigdeleted file mode 100644index 2fd61477..00000000--- a/src/tui_paste_transfer.zig+++ /dev/null@@ -1,51 +0,0 @@-//! Transfer clipboard file ownership across the TUI's bounded callback buffer.-const std = @import("std");-const clip = @import("vision_clipboard.zig");-const Transfer = struct { len: usize, owned: bool };--pub fn transfer(grab: clip.Grab, io: std.Io, gpa: std.mem.Allocator, dest: []u8) ?Transfer {- if (grab.path.len > dest.len) {- grab.release(io, gpa);- return null;- }- @memcpy(dest[0..grab.path.len], grab.path);- defer gpa.free(grab.path);- return .{ .len = grab.path.len, .owned = grab.owned };-}--test "TUI clipboard transfer preserves ownership and leaves the exported pixels readable" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- for ([_]bool{ true, false }) |owned| {- try tmp.dir.writeFile(io, .{ .sub_path = "pixels.png", .data = "pixels" });- const original = try tmp.dir.realPathFileAlloc(io, "pixels.png", gpa);- defer gpa.free(original);- var dest: [4096]u8 = undefined;- const result = transfer(.{ .path = try gpa.dupe(u8, original), .owned = owned, .flavor = .png }, io, gpa, &dest).?;- try std.testing.expectEqual(owned, result.owned);- const pixels = try std.Io.Dir.cwd().openFile(io, dest[0..result.len], .{});- pixels.close(io);- }-}--test "a TUI clipboard path that does not fit releases an owned export but preserves an original" {- const gpa = std.testing.allocator;- const io = std.testing.io;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- for ([_]bool{ true, false }) |owned| {- try tmp.dir.writeFile(io, .{ .sub_path = "pixels.png", .data = "pixels" });- const original = try tmp.dir.realPathFileAlloc(io, "pixels.png", gpa);- defer gpa.free(original);- var dest: [1]u8 = undefined;- try std.testing.expect(transfer(.{ .path = try gpa.dupe(u8, original), .owned = owned, .flavor = .png }, io, gpa, &dest) == null);- if (owned) {- try std.testing.expectError(error.FileNotFound, tmp.dir.openFile(io, "pixels.png", .{}));- } else {- const pixels = try tmp.dir.openFile(io, "pixels.png", .{});- pixels.close(io);- }- }-}diff --git a/src/tui_peer.zig b/src/tui_peer.zigdeleted file mode 100644index 6e3d69df..00000000--- a/src/tui_peer.zig+++ /dev/null@@ -1,69 +0,0 @@-//! Host side of TUI `/tell` / `/peek`: the pager is a thin client; this-//! calls the existing mailbox (`tellCommand` / `peekCommand`) on the live-//! agent. Wired from `tui_launch` as `engine.PeerFn`.--const std = @import("std");-const Io = std.Io;-const Allocator = std.mem.Allocator;--const agent_mod = @import("agent.zig");-const peer_channel = @import("peer_channel.zig");-const presence = @import("presence.zig");-const proc_identity = @import("proc_identity.zig");-const repl_glue = @import("repl_glue.zig");--const Agent = agent_mod.Agent;--/// Run a `/tell` or `/peek` line against `root`. Caller frees the returned-/// text. Null only when the line is not a peer slash or allocation failed.-pub fn runSlash(root: *Agent, gpa: Allocator, line: []const u8) ?[]const u8 {- const trimmed = std.mem.trim(u8, line, " \t\r\n");- const is_tell = std.mem.startsWith(u8, trimmed, "/tell") and- (trimmed.len == 5 or trimmed[5] == ' ' or trimmed[5] == '\t');- const is_peek = std.mem.startsWith(u8, trimmed, "/peek") and- (trimmed.len == 5 or trimmed[5] == ' ' or trimmed[5] == '\t');- if (!is_tell and !is_peek) return null;-- var arena_state = std.heap.ArenaAllocator.init(gpa);- defer arena_state.deinit();- var buf: [8192]u8 = undefined;- var w: Io.Writer = .fixed(&buf);- const ok = if (is_tell)- peer_channel.tellCommand(root, arena_state.allocator(), trimmed, &w)- else- peer_channel.peekCommand(root, arena_state.allocator(), trimmed, &w);- _ = ok catch return gpa.dupe(u8, "peer talk failed") catch null;- return gpa.dupe(u8, w.buffered()) catch null;-}--/// `engine.PeerFn` — reads the live agent off `ReplCtx.root`.-pub fn peerCb(ctx: ?*anyopaque, gpa: Allocator, line: []const u8) ?[]const u8 {- const c: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx orelse return null));- const root = c.root orelse return gpa.dupe(u8, "peer talk needs a live session") catch null;- return runSlash(root, gpa, line);-}--test "TUI /tell all appends a device-room line the other session would hear" {- const io = std.testing.io;- const gpa = std.testing.allocator;- var tmp = std.testing.tmpDir(.{});- defer tmp.cleanup();- const dir_path = try std.fmt.allocPrint(gpa, ".zig-cache/tmp/{s}", .{std.mem.sliceTo(&tmp.sub_path, 0)});- defer gpa.free(dir_path);-- presence.bindForTest(dir_path, "/repo/.git", "s-tui", proc_identity.selfRecord(io));- defer presence.unbindForTest();-- var root: Agent = undefined;- root.io = io;- const text = runSlash(&root, gpa, "/tell all hold the tree from the pager") orelse- return error.ExpectedPosted;- defer gpa.free(text);- try std.testing.expect(std.mem.indexOf(u8, text, "posted") != null);-- const room = tmp.dir.readFileAlloc(io, presence.device_room, gpa, .limited(4096)) catch- return error.ExpectedRoomFile;- defer gpa.free(room);- try std.testing.expect(std.mem.indexOf(u8, room, "hold the tree from the pager") != null);- try std.testing.expect(std.mem.indexOf(u8, room, "\"from_user\":true") != null);-}diff --git a/src/tui_session.zig b/src/tui_session.zigdeleted file mode 100644index a62119b2..00000000--- a/src/tui_session.zig+++ /dev/null@@ -1,182 +0,0 @@-//! Durable-session projection for the fullscreen in-process ACP client.--const std = @import("std");-const Allocator = std.mem.Allocator;-const Value = std.json.Value;--const agent_mod = @import("agent.zig");-const repl_glue = @import("repl_glue.zig");-const session = @import("session.zig");-const session_branch = @import("session_branch.zig");-const tui = @import("tui");--pub fn seed(convo: *repl_glue.Conversation, root: *agent_mod.Agent) !void {- try convo.seed(root.messages);- convo.compaction_window = root.compaction_window;-}--pub fn syncRoot(convo: *repl_glue.Conversation, root: *agent_mod.Agent) !void {- root.messages = try convo.cloneInto(root.arena);- root.compaction_window = convo.compaction_window;-}--pub fn visibleTurns(arena: Allocator, messages: std.json.Array) ![]tui.Turn {- var turns: std.ArrayList(tui.Turn) = .empty;- for (messages.items) |message| {- if (@import("additional_tools.zig").isItem(message)) continue; // tool definitions for the model, not a turn- const role = visibleRole(message) orelse continue;- const text = try visibleText(arena, message);- if (text.len == 0) continue;- try turns.append(arena, .{ .role = role, .text = text, .notification = @import("session_wake.zig").isNotice(message) });- }- return try turns.toOwnedSlice(arena);-}--fn visibleRole(message: Value) ?tui.Turn.Role {- if (message != .object) return null;- const role = message.object.get("role") orelse return null;- if (role != .string) return null;- if (std.mem.eql(u8, role.string, "user")) {- if (message.object.get("content")) |content| if (content == .array) for (content.array.items) |block| {- if (block != .object) continue;- const ty = block.object.get("type") orelse continue;- if (ty == .string and std.mem.eql(u8, ty.string, "tool_result")) return null;- };- return .user;- }- if (std.mem.eql(u8, role.string, "assistant")) return .assistant;- return null;-}--fn visibleText(arena: Allocator, message: Value) ![]const u8 {- const content = message.object.get("content") orelse return "";- if (content == .string) return arena.dupe(u8, content.string);- if (content != .array) return "";- var out: std.ArrayList(u8) = .empty;- for (content.array.items) |block| {- if (block != .object) continue;- const text = block.object.get("text") orelse continue;- if (text != .string or text.string.len == 0) continue;- if (out.items.len > 0) try out.append(arena, '\n');- try out.appendSlice(arena, text.string);- }- return try out.toOwnedSlice(arena);-}--fn failure(gpa: Allocator, out: *tui.ResumeOut, err: anyerror) bool {- out.note = std.fmt.allocPrint(gpa, "resume failed: {t}", .{err}) catch &.{};- return false;-}--pub fn resumeCb(ctx_ptr: ?*anyopaque, gpa: Allocator, raw: []const u8, out: *tui.ResumeOut) bool {- const ctx: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return failure(gpa, out, error.NoSession)));- const root = ctx.root orelse return failure(gpa, out, error.NoSession);- const spec = session_branch.parseSpec(raw) orelse return failure(gpa, out, error.InvalidSessionName);- if (spec.source.len == 0) return failure(gpa, out, error.InvalidSessionName);-- if (ctx.convo) |convo| {- syncRoot(convo, root) catch |err| return failure(gpa, out, err);- session.saveSession(root, root.arena, root.session_name) catch |err| return failure(gpa, out, err);- }- const resumed = session_branch.restore(root, &ctx.keys, root.arena, spec.source, spec.branch, null) catch |err| {- if (err == error.FileNotFound) {- const note = @import("commands_resume.zig").missingMessage(root, root.arena, spec.source) catch return failure(gpa, out, err);- out.note = gpa.dupe(u8, note) catch &.{};- return false;- }- return failure(gpa, out, err);- };- if (ctx.convo) |convo| seed(convo, root) catch |err| return failure(gpa, out, err);- ctx.provider = root.provider;- ctx.last_context_tokens = root.last_context_tokens;- ctx.context_local_tokens = root.context_local_tokens;- ctx.last_cache_read = root.last_cache_read;- tui.setCurrentModel(root.provider.model, root.provider.id);- out.turns = visibleTurns(gpa, root.messages) catch |err| return failure(gpa, out, err);- out.session_name = gpa.dupe(u8, resumed.target) catch return failure(gpa, out, error.OutOfMemory);- out.goal = if (root.goal) |goal| gpa.dupe(u8, goal.objective) catch return failure(gpa, out, error.OutOfMemory) else "";- out.strict = root.strict;- out.ultracode = root.ultracode_mode;- out.note = resumeNote(gpa, resumed);- return true;-}--fn resumeNote(gpa: Allocator, resumed: session_branch.Result) []const u8 {- if (resumed.enter_failed) return std.fmt.allocPrint(gpa, "resumed {s}; saved workspace unavailable, tools remain in the current directory", .{resumed.target}) catch &.{};- return if (resumed.branched)- std.fmt.allocPrint(gpa, "branched {s} → {s}", .{ resumed.source, resumed.target }) catch &.{}- else if (resumed.entered)- std.fmt.allocPrint(gpa, "resumed {s} at {s}", .{ resumed.source, resumed.workspace }) catch &.{}- else- std.fmt.allocPrint(gpa, "resumed {s}", .{resumed.source}) catch &.{};-}--test "TUI resume reports a missing workspace instead of implying tools moved" {- const note = resumeNote(std.testing.allocator, .{ .source = "old", .target = "restored", .branched = true, .workspace = "/missing", .enter_failed = true });- defer std.testing.allocator.free(note);- try std.testing.expectEqualStrings("resumed restored; saved workspace unavailable, tools remain in the current directory", note);-}--pub fn sessionsCb(ctx_ptr: ?*anyopaque, gpa: Allocator) ?[]const u8 {- const ctx: *repl_glue.ReplCtx = @ptrCast(@alignCast(ctx_ptr orelse return null));- const root = ctx.root orelse return null;- var arena_inst = std.heap.ArenaAllocator.init(gpa);- defer arena_inst.deinit();- const arena = arena_inst.allocator();- const entries = session.listSavedSessionsAll(root, arena);- if (entries.items.len == 0) return gpa.dupe(u8, "") catch null;- var out: std.ArrayList(u8) = .empty;- for (entries.items, 0..) |e, i| {- if (i > 0) out.append(gpa, '\n') catch {- out.deinit(gpa);- return null;- };- const age = session.sessionAge(arena, root.io, e.updated_ms);- const title = e.title orelse e.base;- const where = if (e.local) "" else session.displayWorkspace(arena, e.workspace, root.home);- const desc = blk: {- if (!e.local and where.len > 0) {- if (age.len > 0) break :blk std.fmt.allocPrint(arena, "{s} · {s} · {s}", .{ age, e.base, where }) catch e.base;- break :blk std.fmt.allocPrint(arena, "{s} · {s}", .{ e.base, where }) catch e.base;- }- if (e.title == null) break :blk age;- if (age.len > 0) break :blk std.fmt.allocPrint(arena, "{s} · {s}", .{ age, e.base }) catch e.base;- break :blk e.base;- };- const target = @import("session_workspaces.zig").target(arena, e) catch continue;- const line = std.fmt.allocPrint(arena, "{s}\t{s}\t{s}", .{ target, title, desc }) catch continue;- out.appendSlice(gpa, line) catch {- out.deinit(gpa);- return null;- };- }- return out.toOwnedSlice(gpa) catch null;-}--test "visible turns keep human text and omit provider tool envelopes" {- const arena = std.testing.allocator;- var messages = std.json.Array.init(arena);- defer messages.deinit();- var user: std.json.ObjectMap = .empty;- defer user.deinit(arena);- try user.put(arena, "role", .{ .string = "user" });- try user.put(arena, "content", .{ .string = "baseline" });- try messages.append(.{ .object = user });- var tool_result: std.json.ObjectMap = .empty;- defer tool_result.deinit(arena);- try tool_result.put(arena, "type", .{ .string = "tool_result" });- try tool_result.put(arena, "content", .{ .string = "secret tool output" });- var tool_content = std.json.Array.init(arena);- defer tool_content.deinit();- try tool_content.append(.{ .object = tool_result });- var provider_user: std.json.ObjectMap = .empty;- defer provider_user.deinit(arena);- try provider_user.put(arena, "role", .{ .string = "user" });- try provider_user.put(arena, "content", .{ .array = tool_content });- try messages.append(.{ .object = provider_user });- const turns = try visibleTurns(arena, messages);- defer arena.free(turns);- defer arena.free(turns[0].text);- try std.testing.expectEqual(@as(usize, 1), turns.len);- try std.testing.expectEqualStrings("baseline", turns[0].text);-}diff --git a/src/tui_sink.zig b/src/tui_sink.zigdeleted file mode 100644index 22fba1a4..00000000--- a/src/tui_sink.zig+++ /dev/null@@ -1,590 +0,0 @@-//! The fullscreen TUI's EngineSink (#551, the #422 epic).-//!-//! This is the one place that speaks both vocabularies: the engine's-//! `engine_events.EngineEvent` on one side, the frontend-agnostic-//! `tui.Event` on the other. Before it existed the TUI had no sink at all —-//! `engine_sink.hostedEmit` rendered the tool cluster into "⚙ /✓ /✗ " lines,-//! dropped every other event through an `else => {}`, and the TUI recovered-//! what it could by scanning those lines back out of the stream.-//!-//! The split here is deliberate and is the contract the TUI renders from:-//!-//! - PROSE (answer text, meta-tool argument prose, and — with /thinking on —-//! reasoning) streams into the live text buffer the pending row tails.-//! - STRUCTURE (tool calls, outcomes, refusals, notices, failover) is pushed-//! as a typed event with fields. Nothing is rendered here for a frontend-//! to parse again.-//!-//! Every EngineEvent variant is handled explicitly. The ones with no TUI-//! surface today are grouped and say WHY they are ignored — a bare `else` is-//! how the reasoning stream went missing for as long as it did.--const std = @import("std");--const engine_events = @import("engine_events.zig");-const EngineEvent = engine_events.EngineEvent;-const engine_sink = @import("engine_sink.zig");-const repl = @import("repl.zig");-const tui = @import("tui");-const label = @import("agent_tool_label.zig");-const working = @import("agent_working.zig");-const citations = @import("cite_markup.zig");--/// Result previews are one line, capped — the same budget hostedEmit used, so-/// a row's body stays a body and a 20 KB tool result never reaches the queue.-const preview_cap: usize = 80;-/// Arguments get more room: a path or a command IS the row's identity, and-/// truncating one at 80 columns is how a reader loses which file was touched.-const arg_cap: usize = 160;--/// One line of `text`, at most `cap` bytes, ending on a UTF-8 boundary. A byte-/// cap alone can split a multi-byte codepoint, and half a glyph in the-/// transcript is a rendering bug the reader gets to see.-fn capLine(text: []const u8, cap: usize) []const u8 {- return dropPartialTail(engine_sink.firstLineCap(text, cap));-}--/// Drop a trailing INCOMPLETE UTF-8 sequence, and nothing else — a whole-/// multi-byte character at the end must survive.-fn dropPartialTail(s: []const u8) []const u8 {- var i = s.len;- var back: usize = 0;- while (i > 0 and back < 4) : (back += 1) {- i -= 1;- const b = s[i];- if (b & 0x80 == 0) return s; // ASCII tail: nothing is half-written- if (b & 0xC0 != 0x80) {- // A lead byte: keep the character only if all of it is here.- const need = std.unicode.utf8ByteSequenceLength(b) catch return s[0..i];- return if (i + need <= s.len) s else s[0..i];- }- }- return s;-}--/// The per-turn wiring a TUI turn hands the engine. Lives on the turn caller's-/// frame (tui_launch.turnCb) for exactly as long as the turn runs.-pub const Bridge = struct {- /// Typed events for the transcript. Lock-guarded, so the parallel tool- /// pool may push from its own threads.- queue: *tui.EventQueue,- /// The live prose buffer the pending row tails. Single-writer by contract:- /// only the streaming reader (the turn thread) writes deltas.- stream: *repl.StreamBuf,- /// /thinking — whether reasoning belongs in the live tail at all.- show_thinking: bool = false,- /// Reasoning has been written and no answer text has followed it yet, so- /// the first visible byte should break the line first.- reasoning_open: bool = false,- /// ADR 0041: thought / tool / text rows come from ACP `session/update`.- /// This sink still handles meters, notices, raw bash, and failover.- acp_owns_transcript: bool = false,- reasoning_citations: citations.Stream = .{},- answer_citations: citations.Stream = .{},-- fn resetProse(self: *Bridge) void {- self.reasoning_citations = .{};- self.answer_citations = .{};- self.reasoning_open = false;- }-- fn appendProse(self: *Bridge, text: []const u8, reasoning: bool) void {- const filter = if (reasoning) &self.reasoning_citations else &self.answer_citations;- for (text) |byte| {- var buf: [3]u8 = undefined;- const visible = filter.byte(byte, &buf);- if (visible.len == 0) continue;- if (reasoning) {- self.reasoning_open = true;- } else if (self.reasoning_open) {- self.reasoning_open = false;- self.stream.appendBytes("\n");- }- self.stream.appendBytes(visible);- }- }-};--const vtable: engine_sink.VTable = .{ .emit = emit, .durable = false };--pub fn forBridge(b: *Bridge) engine_sink.EngineSink {- return .{ .ctx = @ptrCast(b), .vt = &vtable };-}--fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {- const b: *Bridge = @ptrCast(@alignCast(ctx));- switch (ev.event) {- // ── prose: into the live tail ────────────────────────────────────- .reasoning_delta => |d| if (!b.acp_owns_transcript and b.show_thinking) {- b.appendProse(d.text, true);- },- .text_delta, .tool_arg_delta => |d| if (!b.acp_owns_transcript) {- b.appendProse(d.text, false);- },- // grok-build RawTerminal: bash bytes go to the dedicated raw buf,- // never the prose stream (that mixing is what #551 took apart).- .tool_output_delta => |d| if (tui.rawStream()) |raw| raw.appendBytes(d.text),- // A meta tool owns this text's layout, so it arrives whole.- .completion_text => |t| {- b.stream.appendBytes(t.text);- b.stream.appendBytes("\n");- },- .todo_list_updated => |t| {- var aw: std.Io.Writer.Allocating = .init(std.heap.page_allocator);- defer aw.deinit();- working.writeFromTodoText(&aw.writer, "work", t.text);- b.stream.appendBytes(aw.writer.buffered());- },-- // ── structure: typed rows ────────────────────────────────────────- .tool_call_announced => |t| {- if (b.acp_owns_transcript or label.skipTranscript(t.name)) return;- b.queue.push(.{ .tool_started = .{- .name = t.name,- .detail = capLine(engine_sink.compactArg(t.input), arg_cap),- } });- },- .tool_result => |r| {- if (tui.rawStream()) |raw| raw.len.store(0, .release);- if (b.acp_owns_transcript or label.skipTranscript(r.name)) return;- b.queue.push(.{ .tool_finished = .{- .name = r.name,- .detail = capLine(r.text, preview_cap),- .is_error = r.is_error,- .ms = @intCast(@max(0, r.ms)),- } });- },- // The harness refused the call before it ran. hostedEmit dropped this- // outright, so the row simply never closed and the user watched a tool- // that looked stuck.- .tool_rejected => |r| if (!b.acp_owns_transcript) b.queue.push(.{ .tool_rejected = .{- .name = r.name,- .detail = capLine(r.message, preview_cap),- .is_error = true,- .denied = true,- } }),-- // ── notices: system rows ─────────────────────────────────────────- .job_completed => |j| {- var buf: [64]u8 = undefined;- const msg = if (j.killed)- std.fmt.bufPrint(&buf, "job {d} killed", .{j.id})- else if (j.exit_code) |c|- std.fmt.bufPrint(&buf, "job {d} exited {d}", .{ j.id, c })- else- std.fmt.bufPrint(&buf, "job {d} ended", .{j.id});- b.queue.push(.{ .notice = msg catch "job ended" });- },- .session_notice => |n| {- // A notice may open with an emphasized badge ("⚠ YOLO"); the TUI's- // system row has one style, so the two halves are joined here- // rather than half of it being dropped. The queue copies, so a- // stack buffer is enough and nothing is allocated on this path.- var buf: [512]u8 = undefined;- const line = if (n.lead.len == 0)- n.text- else- std.fmt.bufPrint(&buf, "{s}{s}", .{ n.lead, n.text }) catch n.lead;- b.queue.push(.{ .notice = line });- },- .transport_aborted => |t| {- b.resetProse();- // Mid-turn cuts are the reconnect ladder (ADR 0021). The pager- // already shows Thinking / tool rows; a ⚠ here is what made- // people hit Esc on a turn that was still recovering.- if (!t.turn_ending) return;- switch (t.reason) {- .interrupted, .steered => {},- .stalled => b.queue.push(.{ .notice = "⚠ stream stalled — ending turn" }),- .dropped => b.queue.push(.{ .notice = "⚠ connection dropped — response ended early" }),- }- },- .stream_aborted => |reason| {- b.resetProse();- switch (reason) {- .interrupted => {},- .stalled => b.queue.push(.{ .notice = "⚠ stream stalled — ending turn" }),- .dropped => b.queue.push(.{ .notice = "⚠ connection dropped — response ended early" }),- .steered => b.queue.push(.{ .notice = "↳ follow-up received — restarting the reply" }),- }- },- // The status bar's model name is a TUI-owned global; a mid-turn- // failover is the one thing that can change it behind the frontend's- // back, so the event carries the substitute and the TUI adopts it.- .provider_fallback => |f| b.queue.push(.{ .model_changed = .{ .model = f.to_model, .provider = f.to_provider } }),-- // ── consciously ignored, with the reason ─────────────────────────- // Live-stream bookkeeping: the TUI's pending row IS the spinner, and- // its fold state is frontend-owned, so none of these need a surface.- .stream_begin, .stream_complete, .stream_finished => b.resetProse(),- .thinking_fold_toggle => {},- // The engine's own call brackets. tool_call_announced/tool_result are- // the pair a transcript row is built from; these two are the timing- // brackets a supervisor uses and would double every row here.- .tool_call_started, .tool_call_finished => {},- // Tool-run colour the compact transcript deliberately does not draw:- // batch fan-out/join tallies, the completion-gate refusal, and a- // retired standing goal. Each is a candidate for its own row later;- // none has one today.- .parallel_batch_started, .parallel_batch_finished, .completion_deferred, .goal_completed => {},- // Session lifecycle that happens OUTSIDE a turn: by the time a turn's- // sink exists the banner, worktree entry, checkout-owner warning and- // saved-model substitution have all already been decided, and the MCP- // consent prompt still reads stdin at its emit site (#422 phase 1b).- .session_banner,- .worktree_entered,- .shared_worktree_owner,- .saved_model_unavailable,- .mcp_consent_prompt,- .session_saved,- .run_finished,- => {},- // The engine's own meters. The TUI kept character counters and called- // them a context meter; these are the real numbers, and they are the- // only ones that know about compaction, cached tokens and cost.- .prompt_ready => |st| b.queue.push(.{ .status = .{- .model = st.model,- .provider_id = st.provider_id,- .has_context = st.context != null,- .tokens = if (st.context) |meter| meter.tokens else 0,- .window = if (st.context) |meter| meter.window else 0,- .compact_at = if (st.context) |meter| meter.compact_at else 0,- .cache_read = st.cache_read,- .cost = switch (st.cost) {- .hidden => .hidden,- .subscription => .subscription,- .unpriced => .unpriced,- .usd => |v| .{ .usd = v },- },- .fast = st.fast,- .fallback = st.fallback,- .plan = st.plan,- .strict = st.strict,- .ultracode = st.ultracode,- } }),- }-}--test "prose streams into the live tail; structure never does" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [256]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- const sink = forBridge(&bridge);-- sink.emit(undefined, .{ .text_delta = .{ .text = "hello" } });- sink.emit(undefined, .{ .tool_call_announced = .{ .name = "bash", .input = .null } });- sink.emit(undefined, .{ .tool_output_delta = .{ .name = "bash", .text = "ls\n" } });- sink.emit(undefined, .{ .tool_result = .{ .name = "bash", .text = "ok\nmore", .is_error = false } });- sink.emit(undefined, .{ .text_delta = .{ .text = " world" } });-- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- // Tool *structure* left no bytes in the prose buffer. Live bash output- // is the terminal projection (grok-build bash_output_chunk) and does.- try std.testing.expectEqualStrings("hello world", snap);-- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(usize, 2), evs.len);- try std.testing.expectEqualStrings("bash", evs[0].tool_started.name);- try std.testing.expectEqualStrings("ok", evs[1].tool_finished.detail);- try std.testing.expect(!evs[1].tool_finished.is_error);-}--test "tool_finished carries the engine's measured ms" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- forBridge(&bridge).emit(undefined, .{ .tool_result = .{- .name = "read_file",- .text = "ok",- .is_error = false,- .ms = 240,- } });- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(u64, 240), evs[0].tool_finished.ms);-}--test "reasoning reaches the tail only with /thinking on" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var off_buf: [64]u8 = undefined;- var off_stream: repl.StreamBuf = .{ .buf = &off_buf };- var off: Bridge = .{ .queue = &qbuf, .stream = &off_stream, .show_thinking = false };- forBridge(&off).emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });- try std.testing.expect(off_stream.snapshot(std.testing.allocator) == null);-- var on_buf: [64]u8 = undefined;- var on_stream: repl.StreamBuf = .{ .buf = &on_buf };- var on: Bridge = .{ .queue = &qbuf, .stream = &on_stream, .show_thinking = true };- const sink = forBridge(&on);- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "because" } });- sink.emit(undefined, .{ .text_delta = .{ .text = "answer" } });- const snap = on_stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- // The answer breaks the line the reasoning was on rather than running into it.- try std.testing.expectEqualStrings("because\nanswer", snap);-}--test "a refusal and a failover reach the frontend instead of being dropped" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .tool_rejected = .{- .name = "bash",- .input = .null,- .reason = "budget",- .message = "tool-call budget spent",- } });- sink.emit(undefined, .{ .session_notice = .{ .text = "loaded 2 saved approval(s)", .tone = .dim } });- sink.emit(undefined, .{ .provider_fallback = .{- .from_provider = "codex",- .from_model = "gpt-5.5",- .to_provider = "anthropic",- .to_model = "sonnet",- .to_context = 200_000,- .context_note = "context kept",- } });- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(usize, 3), evs.len);- try std.testing.expect(evs[0].tool_rejected.denied);- try std.testing.expectEqualStrings("tool-call budget spent", evs[0].tool_rejected.detail);- try std.testing.expectEqualStrings("loaded 2 saved approval(s)", evs[1].notice);- try std.testing.expectEqualStrings("sonnet", evs[2].model_changed.model);- try std.testing.expectEqualStrings("anthropic", evs[2].model_changed.provider);-}--test "the engine's meters reach the frontend instead of being dropped (#551)" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [8]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- forBridge(&bridge).emit(undefined, .{ .prompt_ready = .{- .model = "gpt-5.6",- .provider_id = "codex",- .cwd = "~/src/graff",- .privacy_label = "Privacy:Aggregate",- .privacy = .aggregate,- .effort = .high,- .context = .{ .tokens = 12_345, .window = 200_000, .compact_at = 160_000 },- .cache_read = 2048,- .cost = .subscription,- .plan = true,- } });- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(usize, 1), evs.len);- const st = evs[0].status;- try std.testing.expectEqualStrings("gpt-5.6", st.model);- try std.testing.expectEqualStrings("codex", st.provider_id);- try std.testing.expect(st.has_context);- try std.testing.expectEqual(@as(u64, 12_345), st.tokens);- try std.testing.expectEqual(@as(u64, 160_000), st.compact_at);- try std.testing.expectEqual(@as(u64, 2048), st.cache_read);- try std.testing.expectEqual(@as(u64, 6), st.percent());- try std.testing.expect(st.cost == .subscription);- try std.testing.expect(st.plan);-}--test "a status with no usage yet says so rather than reporting a zero context" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [8]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- forBridge(&bridge).emit(undefined, .{ .prompt_ready = .{- .model = "local",- .provider_id = "lmstudio",- .cwd = ".",- .privacy_label = "",- .privacy = .local,- .cost = .unpriced,- } });- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expect(!evs[0].status.has_context);- try std.testing.expectEqual(@as(u64, 0), evs[0].status.percent());- try std.testing.expect(evs[0].status.cost == .unpriced);-}--test "a capped preview never ends mid-character" {- // 80 bytes of ASCII then a 3-byte glyph straddling the cap.- var buf: [128]u8 = undefined;- @memset(buf[0..79], 'x');- @memcpy(buf[79..86], "…tail");- const long = buf[0..86];- const cut = capLine(long, preview_cap);- try std.testing.expectEqual(@as(usize, 79), cut.len);- try std.testing.expect(std.unicode.utf8ValidateSlice(cut));- // A whole multi-byte character that FITS is kept, not shaved off.- try std.testing.expectEqualStrings("a…", capLine("a…\nrest", preview_cap));- try std.testing.expectEqualStrings("plain", capLine(" plain \nmore", preview_cap));-}--test "the turn-sink binding is thread-local and released after the turn" {- var qbuf: tui.EventQueue = .{};- var sbuf: [8]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- try std.testing.expect(engine_sink.turnSink() == null);- engine_sink.bindTurnSink(forBridge(&bridge));- try std.testing.expect(engine_sink.turnSink() != null);-- // A pool thread building its own Agent must NOT inherit the frontend's- // sink: a subagent's output is not the transcript.- const Probe = struct {- fn f(seen: *bool) void {- seen.* = engine_sink.turnSink() != null;- }- };- var seen = true;- const th = try std.Thread.spawn(.{}, Probe.f, .{&seen});- th.join();- try std.testing.expect(!seen);-- engine_sink.unbindTurnSink();- try std.testing.expect(engine_sink.turnSink() == null);-}--test "mid-turn transport cuts stay off the pager (ADR 0021)" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = false } });- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .dropped, .turn_ending = false } });- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = true } });- {- const silent = qbuf.drain();- defer qbuf.free(silent);- try std.testing.expectEqual(@as(usize, 0), silent.len);- }- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } });- sink.emit(undefined, .{ .transport_aborted = .{ .reason = .dropped, .turn_ending = true } });- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(usize, 2), evs.len);- try std.testing.expectEqualStrings("⚠ stream stalled — ending turn", evs[0].notice);- try std.testing.expectEqualStrings("⚠ connection dropped — response ended early", evs[1].notice);-}--test "acp_owns_transcript leaves thought/tool/text to session/update" {- var qbuf: tui.EventQueue = .{};- qbuf.attach(std.testing.allocator);- defer qbuf.deinit();- var sbuf: [64]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &sbuf };- var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream, .show_thinking = true, .acp_owns_transcript = true };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });- sink.emit(undefined, .{ .text_delta = .{ .text = "hi" } });- sink.emit(undefined, .{ .tool_call_announced = .{ .name = "bash", .input = .null } });- try std.testing.expect(stream.snapshot(std.testing.allocator) == null);- const evs = qbuf.drain();- defer qbuf.free(evs);- try std.testing.expectEqual(@as(usize, 0), evs.len);-}--test "legacy bridge citations survive every pair of chunk boundaries" {- const raw = "a\u{E200}cite\u{E202}ref\u{E201}b\u{E202}c\u{E201}\u{E203}!";- for (0..raw.len + 1) |i| {- for (i..raw.len + 1) |j| {- var queue: tui.EventQueue = .{};- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var bridge: Bridge = .{ .queue = &queue, .stream = &stream };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .text_delta = .{ .text = raw[0..i] } });- sink.emit(undefined, .{ .tool_arg_delta = .{ .text = raw[i..j] } });- sink.emit(undefined, .{ .text_delta = .{ .text = raw[j..] } });- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("abc\u{E203}!", snap);- }- }-}--test "legacy bridge citation filtering leaves structured and whole tool output unchanged" {- var queue: tui.EventQueue = .{};- queue.attach(std.testing.allocator);- defer queue.deinit();- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var bridge: Bridge = .{ .queue = &queue, .stream = &stream };- const sink = forBridge(&bridge);- const raw = "raw\u{E200}cite\u{E202}ref\u{E201}";- sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}unclosed" } });- sink.emit(undefined, .{ .tool_result = .{ .name = "bash", .text = raw, .is_error = false } });- sink.emit(undefined, .{ .completion_text = .{ .text = raw } });- const evs = queue.drain();- defer queue.free(evs);- try std.testing.expectEqualStrings(raw, evs[0].tool_finished.detail);- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings(raw ++ "\n", snap);-}--test "legacy bridge citation channels stay independent" {- var queue: tui.EventQueue = .{};- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var bridge: Bridge = .{ .queue = &queue, .stream = &stream, .show_thinking = true };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "\u{E200}unclosed" } });- sink.emit(undefined, .{ .text_delta = .{ .text = "answer" } });- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "\u{E201}thought" } });- sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}hidden" } });- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "!" } });- sink.emit(undefined, .{ .tool_arg_delta = .{ .text = "\u{E201}tail" } });- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("answerthought!\ntail", snap);-}--test "legacy bridge citation lifecycle drops unclosed spans and split prefixes" {- const boundaries = [_]EngineEvent{- .stream_begin,- .{ .stream_complete = .{ .streamed_text = true } },- .stream_finished,- .{ .stream_aborted = .interrupted },- .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = false } },- .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = true } },- };- for (boundaries) |boundary| {- for ([_][]const u8{ "\u{E200}unclosed", "\xee", "\xee\x88" }) |unfinished| {- var queue: tui.EventQueue = .{};- var buf: [128]u8 = undefined;- var stream: repl.StreamBuf = .{ .buf = &buf };- var bridge: Bridge = .{ .queue = &queue, .stream = &stream, .show_thinking = true };- const sink = forBridge(&bridge);- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });- sink.emit(undefined, .{ .reasoning_delta = .{ .text = unfinished } });- sink.emit(undefined, .{ .text_delta = .{ .text = unfinished } });- sink.emit(undefined, boundary);- sink.emit(undefined, .{ .text_delta = .{ .text = "next" } });- sink.emit(undefined, .{ .reasoning_delta = .{ .text = "thought" } });- const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;- defer std.testing.allocator.free(snap);- try std.testing.expectEqualStrings("whynextthought", snap);- }- }-}