graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(tui): Grok-style fullscreen pager for `graff tui`
Rach Pradhanb5df50b38b6c
diff --git a/AGENTS.md b/AGENTS.mdindex 948e1e6a..e3465010 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -6,6 +6,43 @@- **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| ◆ Called 2 tools"+_ = try term.clickText("Called"); // 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)`.++`/debug` stays the observability HUD; `term.layout()` is how you see why a+click missed (overlay, prompt-origin, mid-origin).+## File size- Keep every hand-written source file at or below 600 lines of code.diff --git a/TUI/app.zig b/TUI/app.zignew file mode 100644index 00000000..809c150d--- /dev/null+++ b/TUI/app.zig@@ -0,0 +1,303 @@+//! 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");++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 };+pub const AgentMode = enum { normal, plan, always_approve };+pub const EscArm = enum { none, clear, rewind };+pub const EntryKind = enum { user, assistant, tool, system, err, pending };++pub const Entry = struct {+ kind: EntryKind,+ text: []const u8,+ folded: bool = false,+};++pub const Effect = enum { stay, quit, background };++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),+ steer_queue: std.array_list.Managed([]const u8),+ images: std.array_list.Managed([]const u8),+ pending: ?*engine.Job = 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,+ 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,+ scroll: usize = 0,+ selected: usize = 0,+ turns: usize = 0,+ chars_in: usize = 0,+ chars_out: usize = 0,+ 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,+ now_ms: u64 = 0,+ hist_idx: ?usize = 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,+ 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),+ .steer_queue = std.array_list.Managed([]const u8).init(alloc),+ .images = std.array_list.Managed([]const u8).init(alloc),+ .chat = engine.g_turn_fn != null,+ };+ self.input.setPlaceholder("");+ }++ pub fn deinit(self: *Model) void {+ if (self.pending) |job| self.destroyJob(job);+ for (self.history.items) |e| self.alloc.free(e.text);+ self.history.deinit();+ for (self.prompt_hist.items) |s| self.alloc.free(s);+ self.prompt_hist.deinit();+ 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);+ if (self.overlay_filter.len > 0) self.alloc.free(self.overlay_filter);+ self.input.deinit();+ }++ pub fn destroyJob(self: *Model, job: *engine.Job) void {+ if (job.threaded) job.thread.join();+ if (job.result) |r| self.alloc.free(r);+ for (job.history) |t| self.alloc.free(t.text);+ self.alloc.free(job.history);+ if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);+ self.alloc.destroy(job);+ self.pending = null;+ }++ 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 self.alloc.dupe(u8, text);+ errdefer self.alloc.free(owned);+ try self.history.append(.{ .kind = kind, .text = owned, .folded = kind == .tool });+ if (kind == .user or kind == .assistant) {+ self.screen = .agent;+ self.follow = true;+ self.scroll = 0;+ }+ }++ pub fn pushFmt(self: *Model, kind: EntryKind, comptime fmt: []const u8, args: anytype) !void {+ const text = try std.fmt.allocPrint(self.alloc, fmt, args);+ errdefer self.alloc.free(text);+ try self.history.append(.{ .kind = kind, .text = text });+ }++ 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 {+ for (self.history.items) |e| self.alloc.free(e.text);+ self.history.clearRetainingCapacity();+ self.turns = 0;+ self.chars_in = 0;+ self.chars_out = 0;+ self.selected = 0;+ self.scroll = 0;+ self.screen = .welcome;+ }++ 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 => "always-approve",+ };+ }++ /// 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.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;+ 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;+ }+};++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);+}diff --git a/TUI/catalog.zig b/TUI/catalog.zignew file mode 100644index 00000000..1a965989--- /dev/null+++ b/TUI/catalog.zig@@ -0,0 +1,101 @@+//! 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 = "/home", .desc = "Return to the welcome screen", .aliases = &.{"/welcome"} },+ .{ .name = "/compact", .desc = "Compress conversation history" },+ .{ .name = "/context", .desc = "Show context-window use" },+ .{ .name = "/session-info", .desc = "Session details", .aliases = &.{ "/status", "/info" } },+ .{ .name = "/usage", .desc = "Token usage and cost", .aliases = &.{"/cost"} },+ .{ .name = "/debug", .desc = "Live observability HUD" },+ .{ .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 a standing objective" },+ .{ .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 = "/help", .desc = "List commands" },+ .{ .name = "/doctor", .desc = "Health check" },+ .{ .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;+}++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("/cost") != 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] == '/');+}diff --git a/TUI/chrome.zig b/TUI/chrome.zignew file mode 100644index 00000000..490bc4a2--- /dev/null+++ b/TUI/chrome.zig@@ -0,0 +1,389 @@+//! Top bar, prompt box, status, overlays. ANSI only.++const std = @import("std");++const app = @import("app.zig");+const catalog = @import("catalog.zig");+const engine = @import("engine.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;+ const inner = if (cols > 4) cols - 4 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);+ if (self.input.getValue().len == 0 and self.images.items.len == 0 and engine.g_paste_fn != null) {+ try out.appendSlice(try theme_mod.paint(a, th.muted, " Image in clipboard · ctrl+v to paste"));+ try out.append('\n');+ }+ 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("› ");+ if (self.images.items.len > 0) {+ try body.appendSlice(try imageChips(self, a));+ try body.appendSlice(" ");+ }+ try body.appendSlice(try self.input.view(a));+ const wrapped = try theme_mod.wrapToWidth(a, body.items, inner);+ 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);+ const max_body: usize = 8;+ const start: usize = if (lines.items.len > max_body) lines.items.len - max_body else 0;+ for (lines.items[start..]) |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 label = try std.fmt.allocPrint(a, " {s} ({s}) · {s} ", .{ model, @tagName(self.effort), self.modeSlug() });+ try out.appendSlice(try footer(a, border, th.muted, label, inner));+ return out.items;+}++fn imageChips(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ var chips = std.array_list.Managed(u8).init(a);+ for (self.images.items, 0..) |_, i| {+ if (i > 0) try chips.append(' ');+ var buf: [24]u8 = undefined;+ try chips.appendSlice(try std.fmt.bufPrint(&buf, "[Image #{d}]", .{i + 1}));+ }+ 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, self.toast);+ }+ _ = width;+ if (self.pending != null) {+ return std.fmt.allocPrint(a, "{s} Enter:queue | Shift+Tab:mode | Esc:cancel | {s}[stop]{s}", .{+ th.muted, th.error_fg, theme_mod.reset,+ });+ }+ return theme_mod.paint(a, th.muted, " Enter:send now | Shift+Tab:mode | Esc");+}++pub fn overlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {+ return switch (self.overlay) {+ .none => "",+ .palette => try listOverlay(self, a, width),+ .theme => try themeOverlay(self, a),+ .help => try helpOverlay(self, a),+ .rewind => try std.fmt.allocPrint(a, "{s}{s}Rewind last turn?{s}\n{s}Enter rewind · Esc cancel{s}\n", .{ theme_mod.bold, self.theme().accent, theme_mod.reset, self.theme().muted, theme_mod.reset }),+ .debug => try debugOverlay(self, a),+ .model => try @import("models.zig").render(self, a),+ .effort => try @import("effort.zig").render(self, a),+ .settings => try settingsOverlay(self, a),+ .image => try @import("image.zig").render(self, a, width),+ .slash => "",+ };+}++pub fn slashMenu(self: *const Model, a: std.mem.Allocator, width: usize) ![]const u8 {+ const v = self.input.getValue();+ if (self.focus != .prompt or v.len == 0 or v[0] != '/') return "";+ var idx: [catalog.items.len]usize = undefined;+ const n = catalog.filter(v, &idx);+ if (n == 0) return "";+ const th = self.theme();+ var out = std.array_list.Managed(u8).init(a);+ const show = @min(n, @as(usize, 8));+ const sel = if (n == 0) 0 else self.slash_sel % n;+ var i: usize = 0;+ while (i < show) : (i += 1) {+ const it = catalog.items[idx[i]];+ const mark: []const u8 = if (i == sel) "› " else " ";+ 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');+ }+ _ = width;+ return out.items;+}++fn listOverlay(self: *const Model, a: std.mem.Allocator, width: usize) ![]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);+ try out.appendSlice(try theme_mod.paint(a, th.accent, "Commands"));+ try out.append('\n');+ const show = @min(n, @as(usize, 12));+ if (show == 0) {+ try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches\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: []const u8 = if (i == sel) "› " else " ";+ 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');+ }+ _ = width;+ return out.items;+}++fn themeOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ const th = self.theme();+ var out = std.array_list.Managed(u8).init(a);+ try out.appendSlice(try theme_mod.paint(a, th.accent, "Theme"));+ try out.append('\n');+ const sel = self.overlay_sel % theme_mod.all.len;+ for (theme_mod.all, 0..) |id, i| {+ const mark: []const u8 = if (i == sel) "› " else " ";+ 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 helpOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ return theme_mod.paint(a, self.theme().text,+ \\Shortcuts+ \\+ \\ 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 · y copy · Enter open+ \\ Shift+← → prev / next user turn+ \\ Ctrl+J / K scroll one line+ \\ Ctrl+N N new session+ \\ Ctrl+Q quit+ \\ Shift+drag copy (native selection)+ \\ 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+ \\+ \\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+ \\ /debug observability HUD+ \\ /plan toggle plan mode+ \\ /always-approve skip permission prompts+ \\ /import-claude copy Claude and Cursor MCP + skills+ );+}++test "help overlay names the advertised pager commands" {+ 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 overlay(&m, arena.allocator(), 80);+ for ([_][]const u8{+ "/quit", "/help", "/new", "/home", "/model", "/settings", "/usage", "/debug", "/plan", "/always-approve",+ "Shift+Tab", "PgUp", "PgDn",+ "←",+ "→",+ "Tab", "Enter", "Esc",+ }) |name| {+ try std.testing.expect(std.mem.indexOf(u8, text, name) != null);+ }+}++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), "always-approve") != null);+ try std.testing.expect(std.mem.indexOf(u8, try statusBar(&m, a, 80), "Enter:send now") != null);+ try std.testing.expect(std.mem.indexOf(u8, try statusBar(&m, a, 80), "|") != 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);+}++test "model overlay lists engine.g_models" {+ engine.g_models = "grok-4, gpt-5.5";+ engine.g_model_name = "grok-4";+ defer {+ engine.g_models = "";+ engine.g_model_name = "";+ }+ 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);+ try std.testing.expect(std.mem.indexOf(u8, text, "Model ›") != 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(std.testing.allocator);+ defer m.deinit();+ m.openOverlay(.debug);+ const text = try overlay(&m, std.testing.allocator, 80);+ defer std.testing.allocator.free(text);+ try std.testing.expect(std.mem.indexOf(u8, text, "offline") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "usage") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "overlay debug") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "prompt-origin") != null);+}++pub const splitModels = @import("models.zig").splitModels;++fn settingsOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ const th = self.theme();+ var out = std.array_list.Managed(u8).init(a);+ try out.appendSlice(try theme_mod.paint(a, th.accent, "Settings"));+ try out.appendSlice("\n\n");+ 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: []const u8 = if (i == sel) "› " else " ";+ 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');+ }+ try out.append('\n');+ try out.appendSlice(try theme_mod.paint(a, th.muted, "Enter change · type /model to search · Esc"));+ try out.append('\n');+ return out.items;+}++fn debugOverlay(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ const th = self.theme();+ var buf: [2048]u8 = undefined;+ const body: []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);+ return std.fmt.allocPrint(a, "{s}{s}Observability{s}\n{s}{s}{s}\n{s}Esc close{s}\n", .{+ theme_mod.bold, th.text, theme_mod.reset, th.text, body, lay, th.muted, theme_mod.reset,+ });+}++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);+}diff --git a/TUI/dispatch.zig b/TUI/dispatch.zignew file mode 100644index 00000000..e5b4d83b--- /dev/null+++ b/TUI/dispatch.zig@@ -0,0 +1,426 @@+//! 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 catalog = @import("catalog.zig");+const engine = @import("engine.zig");+const theme_mod = @import("theme.zig");+const turn = @import("turn.zig");+const Model = app.Model;+const Effect = app.Effect;++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) rememberPrompt(self, line);+ if (line.len > 0 and line[0] == '/') return runCommand(self, line);+ const prefix = self.takeImagesPrefix(self.alloc);+ const payload = if (prefix.len == 0) line else (std.fmt.allocPrint(self.alloc, "{s}{s}", .{ prefix, line }) catch line);+ if (prefix.len > 0) self.alloc.free(prefix);+ self.push(.user, payload) catch {};+ if (payload.ptr != line.ptr) self.alloc.free(payload);+ if (self.chat) {+ self.turns += 1;+ self.chars_in += line.len;+ 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 {+ if (self.alloc.dupe(u8, line)) |dup| {+ self.prompt_hist.append(dup) catch self.alloc.free(dup);+ } else |_| {}+ self.hist_idx = null;+}++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;++ if (std.mem.eql(u8, canon, "/quit")) {+ self.quit_requested = true;+ return .quit;+ } else if (std.mem.eql(u8, canon, "/new")) {+ self.clearHistory();+ self.push(.system, "started a new conversation") catch {};+ self.screen = .welcome;+ } 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.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 (engine.g_model_fn) |f| {+ if (f(engine.g_turn_ctx, self.alloc, arg)) |nm| {+ engine.g_model_name = nm;+ self.pushFmt(.system, "switched to {s}", .{nm}) 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) {+ 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;+ };+ 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;+ self.pushFmt(.system, "ultracode: {s}", .{onOff(self.ultracode)}) catch {};+ } else if (std.mem.eql(u8, canon, "/strict")) {+ self.strict = !self.strict;+ self.pushFmt(.system, "strict: {s}", .{onOff(self.strict)}) catch {};+ } else if (std.mem.eql(u8, canon, "/goal")) {+ if (self.goal) |g| self.alloc.free(g);+ self.goal = if (arg.len > 0) (self.alloc.dupe(u8, arg) catch null) else null;+ if (self.goal) |g| self.pushFmt(.system, "goal set: {s}", .{g}) catch {} else self.push(.system, "goal cleared") 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;+ self.pushFmt(.system, "session: {s}", .{self.session_name orelse "untitled"}) catch {};+ } else if (std.mem.eql(u8, canon, "/session-info")) {+ self.pushFmt(.system, "{s} · {s} · {d} turn(s) · ~{d} in / ~{d} out · {s}", .{ self.modeLabel(), engine.g_model_name, self.turns, self.chars_in, self.chars_out, engine.g_cwd }) catch {};+ } else if (std.mem.eql(u8, canon, "/debug")) {+ self.openOverlay(.debug);+ } 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")) {+ self.pushFmt(.system, "context: {d} chars sent, {d} received this session", .{ self.chars_in, self.chars_out }) catch {};+ } 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")) {+ self.pushFmt(.system, "ok · model={s} · cwd={s} · theme={s} · vim={s}", .{ engine.g_model_name, engine.g_cwd, @tagName(self.theme_id), onOff(self.vim_mode) }) 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 {+ self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};+ }+ return if (self.quit_requested) .quit else .stay;+}++pub fn rewind(self: *Model) void {+ 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.alloc.free(self.history.items[j - 1].text);+ self.history.shrinkRetainingCapacity(i - 1);+ self.push(.system, "rewound the last turn") catch {};+}++pub fn compact(self: *Model) void {+ const keep = 6;+ const n = self.history.items.len;+ if (n <= keep) {+ self.push(.system, "nothing to compact") catch {};+ return;+ }+ const drop_to = n - keep;+ var k: usize = 0;+ while (k < drop_to) : (k += 1) self.alloc.free(self.history.items[k].text);+ std.mem.copyForwards(app.Entry, self.history.items[0..], self.history.items[drop_to..]);+ self.history.shrinkRetainingCapacity(n - drop_to);+ self.push(.system, "compacted — kept recent turns") catch {};+}++pub fn recallPrev(self: *Model) void {+ if (self.prompt_hist.items.len == 0) return;+ 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;+ self.input.setValue(self.prompt_hist.items[next_i]) catch {};+}++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;+ self.input.setValue("") catch {};+ return;+ }+ self.hist_idx = i + 1;+ self.input.setValue(self.prompt_hist.items[i + 1]) catch {};+}++pub fn pasteClipboard(self: *Model) void {+ if (engine.g_paste_fn) |f| {+ var buf: [1024]u8 = undefined;+ const n = f(engine.g_turn_ctx, &buf);+ if (n > 0) {+ self.attachImage(buf[0..@intCast(n)]);+ } 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 onOff(v: bool) []const u8 {+ return if (v) "on" else "off";+}++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 "/usage is not a char-count view" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ m.chars_in = 99;+ m.chars_out = 88;+ _ = 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();+ m.chars_in = 99;+ _ = 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 "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 "/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);+}diff --git a/TUI/dump.zig b/TUI/dump.zignew file mode 100644index 00000000..58fbd4ce--- /dev/null+++ b/TUI/dump.zig@@ -0,0 +1,104 @@+//! 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.zignew file mode 100644index 00000000..dbe9f79b--- /dev/null+++ b/TUI/effort.zig@@ -0,0 +1,90 @@+//! 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 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",+ };+}++pub fn filter(query: []const u8, out: []engine.Effort) usize {+ var n: usize = 0;+ for (all) |e| {+ 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];+}++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);+ const q = self.overlay_filter;+ try out.appendSlice(try theme_mod.paint(a, th.accent, try std.fmt.allocPrint(a, "Effort › {s}▋", .{q})));+ try out.append('\n');+ try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, all.len })));+ try out.appendSlice("\n\n");+ if (n == 0) {+ try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches — Esc to close\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');+ }+ try out.append('\n');+ try out.appendSlice(try theme_mod.paint(a, th.muted, "type to filter · ↑↓ move · Enter pick · Esc"));+ 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 "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, text, "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.zignew file mode 100644index 00000000..9c376308--- /dev/null+++ b/TUI/engine.zig@@ -0,0 +1,88 @@+//! 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");++pub const Effort = enum { low, medium, high, xhigh, max, ultra };++pub const Turn = struct {+ role: Role,+ text: []const u8,+ pub const Role = enum { user, assistant };+};++pub const Params = struct {+ effort: Effort = .medium,+ fast: bool = false,+ thinking: bool = false,+ ultracode: bool = false,+ goal: []const u8 = "",+};++/// Lock-free single-writer / single-reader preview buffer (same contract as+/// the zigzag 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;+ const n = @min(bytes.len, self.buf.len - cur);+ @memcpy(self.buf[cur .. cur + n], bytes[0..n]);+ self.len.store(cur + n, .release);+ }++ 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;+ }+};++pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf) ?[]const u8;+pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?[]const u8;+pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;+/// Fill dest with a staged image path (return >0) or an error line (return <0).+pub const PasteFn = *const fn (turn_ctx: ?*anyopaque, dest: []u8) isize;++pub const Job = struct {+ thread: std.Thread = undefined,+ threaded: bool = true,+ done: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),+ result: ?[]const u8 = null,+ gpa: std.mem.Allocator,+ history: []Turn,+ params: Params,+ stream: StreamBuf,+};++pub const HudKind = enum { debug, usage };+pub const HudFn = *const fn (kind: HudKind, buf: []u8) usize;++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_model_name: []const u8 = "";+pub var g_models: []const u8 = "";+pub var g_cwd: []const u8 = ".";++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) else null;+ job.result = reply;+ job.done.store(true, .release);+}++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));+}diff --git a/TUI/image.zig b/TUI/image.zignew file mode 100644index 00000000..908577b2--- /dev/null+++ b/TUI/image.zig@@ -0,0 +1,517 @@+//! [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;++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');+ }+ // Pixels stay out of the cell stream: Kitty images sit above the grid and+ // survived scroll as a gray slab. Metadata + open is enough to inspect.+ _ = width;+ try out.appendSlice(try theme_mod.paint(a, th.muted, " 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) null else @import("scrollback.zig").indexAtVisual(self, y -| self.mid_origin + self.mid_skip, self.last_term_width);+ const path = pathForChip(self, n, hist);+ show(self, path, n, click);+ return true;+}++fn chipAt(self: *const Model, x: usize, y: usize) ?u32 {+ if (self.images.items.len > 0 and y == self.prompt_origin + 1) {+ const box_pad: usize = 4;+ 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;+ const vis = y - self.mid_origin + self.mid_skip;+ const idx = @import("scrollback.zig").indexAtVisual(self, vis, self.last_term_width) orelse return null;+ if (self.history.items[idx].kind != .user) return null;+ if (pathInUserText(self.history.items[idx].text, 1) == null) return null;+ return parseChipOnUser(self, idx, x);+}++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;+ }+ return false;+}++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 {+ if (path.len == 0) return;+ const io = ioHandle();+ var child = std.process.spawn(io, .{+ .argv = &.{"pbcopy"},+ .stdin = .pipe,+ .stdout = .ignore,+ .stderr = .ignore,+ }) catch return;+ if (child.stdin) |*s| {+ var wbuf: [4096]u8 = undefined;+ var w = s.writerStreaming(io, &wbuf);+ w.interface.writeAll(path) catch {};+ w.interface.flush() catch {};+ s.close(io);+ child.stdin = null;+ }+ _ = child.wait(io) catch {};+}++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];+}++const Box = struct { cols: usize, rows: usize };++/// 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 };+}++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 "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 "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 "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 "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.prompt_origin = 10;+ try std.testing.expect(mouse(&m, .{ .btn = 35, .x = 5, .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);+}diff --git a/TUI/input.zig b/TUI/input.zignew file mode 100644index 00000000..44056236--- /dev/null+++ b/TUI/input.zig@@ -0,0 +1,187 @@+//! Composer buffer. Soft-wrap lives in chrome; undo is Ctrl/Cmd+Z.++const std = @import("std");+const Key = @import("key.zig").Key;++const Snap = struct { text: []u8, cursor: usize };++pub const Input = struct {+ alloc: std.mem.Allocator,+ buf: std.array_list.Managed(u8),+ undo_stack: std.array_list.Managed(Snap),+ cursor: usize = 0,+ placeholder: []const u8 = "",++ pub fn init(alloc: std.mem.Allocator) Input {+ return .{+ .alloc = alloc,+ .buf = std.array_list.Managed(u8).init(alloc),+ .undo_stack = std.array_list.Managed(Snap).init(alloc),+ };+ }++ pub fn deinit(self: *Input) void {+ for (self.undo_stack.items) |sn| self.alloc.free(sn.text);+ self.undo_stack.deinit();+ self.buf.deinit();+ }++ fn pushUndo(self: *Input) void {+ const text = self.alloc.dupe(u8, self.buf.items) catch return;+ self.undo_stack.append(.{ .text = text, .cursor = self.cursor }) catch {+ self.alloc.free(text);+ return;+ };+ if (self.undo_stack.items.len > 64) {+ const old = self.undo_stack.orderedRemove(0);+ self.alloc.free(old.text);+ }+ }++ /// 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 self.alloc.free(snap.text);+ self.buf.clearRetainingCapacity();+ self.buf.appendSlice(snap.text) catch {};+ self.cursor = @min(snap.cursor, self.buf.items.len);+ return true;+ }++ pub fn getValue(self: *const Input) []const u8 {+ return self.buf.items;+ }++ pub fn setValue(self: *Input, text: []const u8) !void {+ if (!std.mem.eql(u8, self.buf.items, text)) self.pushUndo();+ self.buf.clearRetainingCapacity();+ try self.buf.appendSlice(text);+ self.cursor = self.buf.items.len;+ }++ pub fn insertSlice(self: *Input, text: []const u8) void {+ if (text.len == 0) return;+ self.pushUndo();+ self.buf.insertSlice(self.cursor, text) catch return;+ self.cursor += text.len;+ }++ pub fn setPlaceholder(self: *Input, text: []const u8) void {+ self.placeholder = text;+ }++ pub fn handle(self: *Input, k: Key) void {+ switch (k) {+ .char => |c| {+ self.pushUndo();+ self.buf.insert(self.cursor, c) catch return;+ self.cursor += 1;+ },+ .backspace => {+ if (self.cursor == 0) return;+ self.pushUndo();+ _ = self.buf.orderedRemove(self.cursor - 1);+ self.cursor -= 1;+ },+ .left => self.cursor -|= 1,+ .right => {+ if (self.cursor < self.buf.items.len) self.cursor += 1;+ },+ .home => self.cursor = 0,+ .end => self.cursor = self.buf.items.len,+ .word_left => self.cursor = prevWord(self.buf.items, self.cursor),+ .word_right => self.cursor = nextWord(self.buf.items, self.cursor),+ .delete_word => self.killTo(prevWord(self.buf.items, self.cursor)),+ .delete_to_start => self.killTo(0),+ .delete_to_end => self.killRange(self.cursor, self.buf.items.len),+ .delete => self.killRange(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.killRange(self.cursor, self.buf.items.len),+ 'u' => self.killTo(0),+ 'w' => self.killTo(prevWord(self.buf.items, self.cursor)),+ 'd' => self.killRange(self.cursor, if (self.cursor < self.buf.items.len) self.cursor + 1 else self.cursor),+ else => {},+ },+ else => {},+ }+ }++ fn killTo(self: *Input, at: usize) void {+ self.killRange(at, self.cursor);+ self.cursor = at;+ }++ fn killRange(self: *Input, from: usize, to: usize) void {+ if (from >= to or to > self.buf.items.len) return;+ self.pushUndo();+ var i = to;+ while (i > from) {+ i -= 1;+ _ = self.buf.orderedRemove(i);+ }+ }++ pub fn view(self: *const Input, a: std.mem.Allocator) ![]const u8 {+ var out = std.array_list.Managed(u8).init(a);+ if (self.buf.items.len == 0) {+ try out.appendSlice(self.placeholder);+ try out.appendSlice("▋");+ return out.items;+ }+ try out.appendSlice(self.buf.items[0..self.cursor]);+ try out.appendSlice("▋");+ try out.appendSlice(self.buf.items[self.cursor..]);+ return out.items;+ }+};++fn prevWord(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 nextWord(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());+}diff --git a/TUI/key.zig b/TUI/key.zignew file mode 100644index 00000000..6f87a5cd--- /dev/null+++ b/TUI/key.zig@@ -0,0 +1,282 @@+//! Keyboard tokens. Understands classic CSI and kitty CSI-u (Ghostty).++const std = @import("std");++/// Super/alt currently held, from kitty modifier-key events (Ghostty Cmd+Delete+/// often arrives as a bare DEL after Super-down).+var held: u32 = 0;++pub const Key = union(enum) {+ char: 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.* >= bytes.len) return null;+ const b = bytes[i.*];+ i.* += 1;+ if (b == 0x1b) return escapeSeq(bytes, i);+ if (b == 0x0d or b == 0x0a) 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) return .escape;+ 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;+ }+ if (c0 != '[') return .escape;+ i.* += 1;+ const start = i.*;+ while (i.* < bytes.len) : (i.* += 1) {+ const c = bytes[i.*];+ if (c >= 0x40 and c <= 0x7e) {+ const final = c;+ const params = bytes[start..i.*];+ i.* += 1;+ return decodeCsi(params, final);+ }+ }+ // Incomplete CSI (split paste / arrow) — rewind so the next read can finish it.+ i.* = start - 2;+ return null;+}++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;+ 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,+ 200 => .paste_start,+ 201 => .paste_end,+ 27 => fixterms(params),+ else => .escape,+ },+ 'u' => kitty(params),+ 'P' => .f1,+ 'Q' => .f2,+ 'M', 'm' => sgrMouse(params, final == 'M'),+ else => .escape,+ };+}++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;+}++/// CSI unicode ; mods u — kitty/ghostty. mods bit 2 = ctrl, 1 = shift.+fn kitty(params: []const u8) Key {+ const code = leadingInt(params);+ var mods: u32 = 0;+ if (std.mem.indexOfScalar(u8, params, ';')) |s| {+ mods = leadingInt(params[s + 1 ..]);+ if (mods > 0) mods -= 1; // kitty encodes mods+1+ }+ const ev = kittyEvent(params);+ if (code == 57444 or code == 57448) {+ if (ev == 3) held &= ~@as(u32, 8) else held |= 8;+ return .ignore;+ }+ if (code == 57443 or code == 57447) {+ if (ev == 3) held &= ~@as(u32, 2) else held |= 2;+ return .ignore;+ }+ if (code >= 57441 and code <= 57448) return .ignore;+ if (ev == 3) return .ignore;+ return mapCode(code, mods);+}++fn kittyEvent(params: []const u8) u32 {+ const s = std.mem.indexOfScalar(u8, params, ';') orelse return 1;+ const rest = params[s + 1 ..];+ const c = std.mem.indexOfScalar(u8, rest, ':') orelse return 1;+ return leadingInt(rest[c + 1 ..]);+}++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) 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 };+ return .{ .char = ch };+ }+ return .escape;+}++fn sgrMouse(params: []const u8, down: bool) Key {+ if (params.len == 0 or params[0] != '<') return .escape;+ 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,+ } };+}++fn leadingInt(s: []const u8) u32 {+ var n: u32 = 0;+ for (s) |c| {+ if (c < '0' or c > '9') break;+ n = n * 10 + (c - '0');+ }+ return n;+}++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).?);+ 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;+ 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).?);+ held = 0;+}diff --git a/TUI/keys.zig b/TUI/keys.zignew file mode 100644index 00000000..fd9306ad--- /dev/null+++ b/TUI/keys.zig@@ -0,0 +1,595 @@+//! Grok Build key bindings. Returns Effect — no zigzag Cmd.++const std = @import("std");++const app = @import("app.zig");+const catalog = @import("catalog.zig");+const dispatch = @import("dispatch.zig");+const scrollback = @import("scrollback.zig");+const engine = @import("engine.zig");+const key_mod = @import("key.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 (@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 (k == .mouse) return mouseKey(self, k.mouse);+ if (k == .paste_start) {+ self.pasting = true;+ self.focus = .prompt;+ return .stay;+ }+ if (k == .paste_end) {+ self.pasting = false;+ const v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");+ if (@import("image.zig").attachDropped(self, v)) {+ self.input.setValue("") catch {};+ }+ return .stay;+ }+ if (self.pasting) {+ switch (k) {+ .enter => self.input.handle(.{ .char = '\n' }),+ .char => |c| self.input.handle(.{ .char = c }),+ else => {},+ }+ return .stay;+ }++ if (self.overlay != .none) return overlayKey(self, k);+ if (slashOpen(self) and slashKey(self, k)) return .stay;++ 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;+ }+ }+ 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 {+ 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 == .ctrl) {+ self.focus = .prompt;+ return promptKey(self, k);+ }+ }+ return .stay;+}++fn lastToolIdx(self: *const Model) ?usize {+ var i = self.history.items.len;+ while (i > 0) {+ i -= 1;+ if (self.history.items[i].kind == .tool) return i;+ }+ return null;+}++fn mouseKey(self: *Model, ev: key_mod.Mouse) Effect {+ if (ev.btn == 64) {+ scrollBy(self, 3);+ return .stay;+ }+ if (ev.btn == 65) {+ scrollBy(self, -3);+ return .stay;+ }+ if (@import("image.zig").mouse(self, ev)) return .stay;+ if (!ev.down or ev.btn != 0) return .stay;+ if (self.overlay != .none) {+ self.closeOverlay();+ return .stay;+ }+ const y: usize = if (ev.y > 0) ev.y - 1 else 0;+ if (y >= self.prompt_origin) {+ self.focus = .prompt;+ return .stay;+ }+ if (y < self.mid_origin) return .stay;+ const vis = y - self.mid_origin + self.mid_skip;+ const idx = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse lastToolIdx(self);+ self.focus = .scrollback;+ if (idx) |i| {+ self.selected = i;+ if (self.history.items[i].kind == .tool) self.toggleToolGroup(i);+ }+ return .stay;+}++fn overlayKey(self: *Model, k: Key) Effect {+ if (@import("image.zig").key(self, k)) return .stay;+ if (k == .escape) {+ self.closeOverlay();+ return .stay;+ }+ if (k == .up) {+ self.overlay_sel -|= 1;+ return .stay;+ }+ if (k == .down) {+ self.overlay_sel += 1;+ return .stay;+ }+ if (k == .enter) return activateOverlay(self);+ if (self.overlay == .model or self.overlay == .effort) {+ 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;+}++fn activateOverlay(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 names: [models.max_models][]const u8 = undefined;+ const n = models.filterModels(engine.g_models, self.overlay_filter, &names);+ const sel = if (n == 0) 0 else self.overlay_sel % n;+ self.closeOverlay();+ if (n == 0) return .stay;+ const pick = names[sel];+ if (engine.g_model_fn) |f| {+ if (f(engine.g_turn_ctx, self.alloc, pick)) |nm| {+ engine.g_model_name = nm;+ self.setToast(nm);+ } else self.setToast("couldn't switch");+ } else {+ engine.g_model_name = pick;+ self.setToast(pick);+ }+ },+ .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),+ }+ },+ else => self.closeOverlay(),+ }+ 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) {+ 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;+ }+ if (self.pending != null) {+ turn.cancelTurn(self);+ self.setToast("cancelled");+ return .stay;+ }+ const empty = std.mem.trim(u8, self.input.getValue(), " \t\r\n").len == 0;+ 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.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;+}++fn ctrlC(self: *Model) Effect {+ 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 "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 "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);+}++test "model overlay Enter picks the selected name" {+ engine.g_models = "grok-4, gpt-5.5";+ engine.g_model_name = "grok-4";+ defer {+ engine.g_models = "";+ engine.g_model_name = "";+ 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);+}++test "model overlay type-to-search picks the filtered name" {+ engine.g_models = "grok-4, gpt-5.5, deepseek-v4-pro";+ engine.g_model_name = "grok-4";+ defer {+ engine.g_models = "";+ engine.g_model_name = "";+ 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);+}++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);+}++test "click on a folded tool row expands it" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "hi");+ try m.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ m.last_term_height = 24;+ m.last_term_width = 80;+ m.mid_origin = 1;+ m.mid_skip = 0;+ try std.testing.expect(m.history.items[1].folded);+ _ = handle(&m, .{ .mouse = .{ .btn = 0, .x = 4, .y = 3, .down = true } });+ try std.testing.expect(!m.history.items[1].folded);+}++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());+}diff --git a/TUI/markdown.zig b/TUI/markdown.zignew file mode 100644index 00000000..a73e778a--- /dev/null+++ b/TUI/markdown.zig@@ -0,0 +1,307 @@+//! Compact ANSI markdown for the pager. No zigzag — SGR only.++const std = @import("std");+const theme_mod = @import("theme.zig");++/// Headers, fences, bullets, `code`, **bold**, 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);+}++pub fn renderTinted(a: std.mem.Allocator, src: []const u8, accent: []const u8, muted: []const u8, text: []const u8) ![]const u8 {+ var lines = std.array_list.Managed([]const u8).init(a);+ defer lines.deinit();+ var split = std.mem.splitScalar(u8, src, '\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 (tableLen(lines.items[i..])) |n| {+ try emitTable(&out, a, lines.items[i .. i + n], accent, muted, text);+ i += n;+ continue;+ }+ if (std.mem.startsWith(u8, t, "#")) {+ var h = t;+ while (h.len > 0 and h[0] == '#') h = h[1..];+ try out.appendSlice(theme_mod.bold);+ try out.appendSlice(accent);+ try out.appendSlice(std.mem.trimStart(u8, h, " "));+ try out.appendSlice(theme_mod.reset);+ i += 1;+ continue;+ }+ try out.appendSlice(text);+ var rest = line;+ if (std.mem.startsWith(u8, t, "- ") or std.mem.startsWith(u8, t, "* ")) {+ try out.appendSlice(accent);+ try out.appendSlice(" • ");+ try out.appendSlice(text);+ rest = t[2..];+ }+ try inlineSpans(&out, rest, accent, 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 {+ var out = std.array_list.Managed(u8).init(a);+ try out.appendSlice(text);+ var img_n: u32 = 0;+ var i: usize = 0;+ while (i < src.len) {+ if (std.mem.startsWith(u8, src[i..], "@[")) {+ if (std.mem.indexOfScalarPos(u8, src, i + 2, ']')) |close| {+ img_n += 1;+ var chip: [24]u8 = undefined;+ const label = std.fmt.bufPrint(&chip, "[Image #{d}]", .{img_n}) catch "[Image]";+ try out.appendSlice(accent);+ try out.appendSlice(label);+ try out.appendSlice(text);+ i = close + 1;+ if (i < src.len and src[i] == ' ') i += 1;+ continue;+ }+ }+ if (src[i] == '/' and (i == 0 or isBreak(src[i - 1]))) {+ var j = i + 1;+ while (j < src.len and (std.ascii.isAlphanumeric(src[j]) or src[j] == '-')) j += 1;+ if (j > i + 1) {+ try out.appendSlice(accent);+ try out.appendSlice(src[i..j]);+ try out.appendSlice(text);+ i = j;+ continue;+ }+ }+ try out.append(src[i]);+ i += 1;+ }+ return out.toOwnedSlice();+}++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] == '`') {+ 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(text);+ i = end + 2;+ continue;+ }+ }+ try out.append(line[i]);+ i += 1;+ }+}++const max_table_cols: usize = 8;++fn isTableRow(line: []const u8) bool {+ const t = std.mem.trim(u8, line, " \t");+ if (t.len < 3 or t[0] != '|') return false;+ return std.mem.indexOfScalar(u8, t[1..], '|') != null;+}++fn isSepRow(line: []const u8) bool {+ if (!isTableRow(line)) return false;+ var buf: [max_table_cols][]const u8 = undefined;+ const n = splitCells(line, &buf);+ if (n == 0) return false;+ for (buf[0..n]) |c| {+ if (c.len == 0) return false;+ for (c) |ch| {+ if (ch != '-' and ch != ':' and ch != ' ') return false;+ }+ }+ return true;+}++fn tableLen(lines: []const []const u8) ?usize {+ if (lines.len < 2 or !isTableRow(lines[0]) or !isSepRow(lines[1])) return null;+ var n: usize = 2;+ while (n < lines.len and isTableRow(lines[n]) and !isSepRow(lines[n])) n += 1;+ return n;+}++fn splitCells(line: []const u8, out: [][]const u8) usize {+ var t = std.mem.trim(u8, line, " \t");+ if (t.len > 0 and t[0] == '|') t = t[1..];+ if (t.len > 0 and t[t.len - 1] == '|') t = t[0 .. t.len - 1];+ var n: usize = 0;+ var it = std.mem.splitScalar(u8, t, '|');+ while (it.next()) |raw| {+ if (n >= out.len) break;+ out[n] = std.mem.trim(u8, raw, " \t");+ n += 1;+ }+ return n;+}++fn cellWidth(s: []const u8) usize {+ var n: usize = 0;+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == '`') {+ i += 1;+ continue;+ }+ if (s[i] == '*' and i + 1 < s.len and s[i + 1] == '*') {+ i += 2;+ continue;+ }+ const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;+ i += @min(w, s.len - i);+ n += 1;+ }+ return n;+}++fn emitRule(out: *std.array_list.Managed(u8), muted: []const u8, widths: []const usize, left: []const u8, mid: []const u8, right: []const u8) !void {+ try out.appendSlice(muted);+ try out.appendSlice(left);+ for (widths, 0..) |w, i| {+ if (i > 0) try out.appendSlice(mid);+ var n: usize = 0;+ while (n < w + 2) : (n += 1) try out.appendSlice("─");+ }+ try out.appendSlice(right);+ try out.appendSlice(theme_mod.reset);+}++fn emitTable(+ out: *std.array_list.Managed(u8),+ a: std.mem.Allocator,+ rows: []const []const u8,+ accent: []const u8,+ muted: []const u8,+ text: []const u8,+) !void {+ _ = a;+ 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(cells[c]), @as(usize, 36));+ if (w > widths[c]) widths[c] = w;+ }+ }+ if (ncol == 0) return;+ const cols = widths[0..ncol];+ 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 "";+ if (ri == 0) {+ try out.appendSlice(theme_mod.bold);+ try out.appendSlice(accent);+ try inlineSpans(out, cell, accent, accent);+ try out.appendSlice(theme_mod.reset);+ } else {+ try out.appendSlice(text);+ try inlineSpans(out, cell, accent, text);+ }+ const vis = cellWidth(cell);+ const want = cols[c];+ if (vis < want) {+ var p: usize = 0;+ while (p < want - vis) : (p += 1) try out.append(' ');+ }+ try out.append(' ');+ }+ try out.appendSlice(muted);+ try out.appendSlice("│");+ try out.appendSlice(theme_mod.reset);+ try out.append('\n');+ }+ try emitRule(out, muted, cols, "└", "┴", "┘");+}++fn isBreak(c: u8) bool {+ return c == ' ' or c == '\t' or c == '\n' or c == '(' or c == '[';+}++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 "renderUser chips @[path] and paints slash commands" {+ const text = try renderUser(std.testing.allocator, "@[/tmp/a.png] /goal look at this", 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, "/tmp/a.png") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "/goal") != null);+}++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);+}diff --git a/TUI/models.zig b/TUI/models.zignew file mode 100644index 00000000..59530bcb--- /dev/null+++ b/TUI/models.zig@@ -0,0 +1,134 @@+//! 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 theme_mod = @import("theme.zig");+const Model = app.Model;++pub const max_models = 256;+const visible_rows = 14;++/// Case-insensitive substring, else fzf-style subsequence ("gpt56" → gpt-5.6).+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;+ }+ return qi == query.len;+}++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;+}++/// Split `engine.g_models` (", "-joined) and keep names matching `query`.+pub fn filterModels(list: []const u8, query: []const u8, out: [][]const u8) usize {+ var n: usize = 0;+ var it = std.mem.splitSequence(u8, list, ", ");+ while (it.next()) |raw| {+ const name = std.mem.trim(u8, raw, " \t");+ if (name.len == 0) continue;+ if (!modelMatch(name, query)) continue;+ if (n >= out.len) break;+ out[n] = name;+ n += 1;+ }+ return n;+}++/// Unfiltered split (empty query). Kept so callers that do not search still work.+pub fn splitModels(list: []const u8, out: [][]const u8) usize {+ return filterModels(list, "", out);+}++pub fn render(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ const th = self.theme();+ var names: [max_models][]const u8 = undefined;+ const total = splitModels(engine.g_models, &names);+ const n = filterModels(engine.g_models, self.overlay_filter, &names);+ var out = std.array_list.Managed(u8).init(a);++ const q = self.overlay_filter;+ const title = try std.fmt.allocPrint(a, "Model › {s}▋", .{q});+ try out.appendSlice(try theme_mod.paint(a, th.accent, title));+ try out.append('\n');+ try out.appendSlice(try theme_mod.paint(a, th.muted, try std.fmt.allocPrint(a, "{d}/{d}", .{ n, total })));+ try out.appendSlice("\n\n");++ if (n == 0) {+ try out.appendSlice(try theme_mod.paint(a, th.muted, "no matches — type to filter, Esc to close\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 cur: []const u8 = if (std.mem.eql(u8, names[i], engine.g_model_name)) " (current)" else "";+ const shown = tailId(names[i]);+ const line = try std.fmt.allocPrint(a, "{s}{s}{s}", .{ mark, shown, 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');+ }+ try out.append('\n');+ try out.appendSlice(try theme_mod.paint(a, th.muted, "type to search · ↑↓ move · Enter pick · Esc"));+ try out.append('\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("accounts/fireworks/models/deepseek-v4-pro", "deepseek"));+ try std.testing.expect(!modelMatch("gpt-5.6", "claude"));+}++test "filterModels ranks by query, not the first 32 only" {+ const list = "aaa, bbb, ccc, accounts/fireworks/models/deepseek-v4-pro, gpt-5.6";+ var buf: [8][]const u8 = undefined;+ const n = filterModels(list, "deepseek", &buf);+ try std.testing.expectEqual(@as(usize, 1), n);+ try std.testing.expectEqualStrings("accounts/fireworks/models/deepseek-v4-pro", buf[0]);+ try std.testing.expectEqual(@as(usize, 5), filterModels(list, "", &buf));+}++test "model overlay typed query is a filtered list, not the dump" {+ engine.g_models = "grok-4, gpt-5.5, accounts/fireworks/models/deepseek-v4-pro";+ engine.g_model_name = "grok-4";+ defer {+ engine.g_models = "";+ 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.5") == null);+ try std.testing.expect(std.mem.indexOf(u8, text, "1/3") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "Model › deepseek") != null);+}diff --git a/TUI/nav.zig b/TUI/nav.zignew file mode 100644index 00000000..2e50cc28--- /dev/null+++ b/TUI/nav.zig@@ -0,0 +1,123 @@+//! 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.clearHistory();+ self.new_arm_until_ms = 0;+ self.setToast("new session");+ return;+ }+ self.new_arm_until_ms = self.now_ms + 1000;+ self.setToast("press Ctrl+N again to start a new session");+}++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/render.zig b/TUI/render.zignew file mode 100644index 00000000..36cfce83--- /dev/null+++ b/TUI/render.zig@@ -0,0 +1,230 @@+//! 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 app = @import("app.zig");+const chrome = @import("chrome.zig");+const engine = @import("engine.zig");+const scrollback = @import("scrollback.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 {+ self.last_term_width = width;+ self.last_term_height = height;+ self.now_ms = now_ms;+ @import("turn.zig").harvestLiveTools(self);++ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const top = try chrome.topBar(self, a, width);+ const image_card = if (self.overlay == .image)+ try chrome.overlay(self, a, width)+ else+ "";+ const mid = if (self.overlay != .none and self.overlay != .image)+ try chrome.overlay(self, a, width)+ else if (self.screen == .welcome and self.userTurnCount() == 0)+ try welcome.render(self, a, width)+ else+ try scrollback.render(self, a, width, now_ms);+ const slash = try chrome.slashMenu(self, a, width);+ const prompt = try chrome.promptBox(self, a, width);+ const status = try chrome.statusBar(self, a, width);++ 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 bottom.appendSlice(prompt);+ if (prompt.len == 0 or prompt[prompt.len - 1] != '\n') try bottom.append('\n');+ try bottom.appendSlice(status);++ const bottom_lines = countLines(bottom.items);+ const top_lines = countLines(top);+ const card_lines = countLines(image_card);+ 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;+ const view_h: usize = if (height > used) height - used else 1;++ var mid_lines = std.array_list.Managed([]const u8).init(a);+ var it = std.mem.splitScalar(u8, mid, '\n');+ while (it.next()) |ln| try mid_lines.append(ln);+ if (mid_lines.items.len > 0 and mid_lines.items[mid_lines.items.len - 1].len == 0) _ = mid_lines.pop();++ var out = std.array_list.Managed(u8).init(a);+ try out.appendSlice(top);+ if (top.len > 0 and top[top.len - 1] != '\n') try out.append('\n');++ const n = mid_lines.items.len;+ if (n <= view_h) {+ self.scroll = 0;+ self.mid_skip = 0;+ for (mid_lines.items) |ln| {+ try out.appendSlice(ln);+ try out.append('\n');+ }+ var pad: usize = view_h - n;+ while (pad > 0) : (pad -= 1) try out.append('\n');+ } else {+ const max_scroll = n - view_h;+ if (self.follow) self.scroll = 0;+ if (self.scroll > max_scroll) self.scroll = max_scroll;+ const start = max_scroll - self.scroll;+ self.mid_skip = start;+ for (mid_lines.items[start .. start + view_h]) |ln| {+ try out.appendSlice(ln);+ 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.items);+ return gpa.dupe(u8, out.items);+}++fn countLines(s: []const u8) usize {+ if (s.len == 0) return 0;+ return std.mem.count(u8, s, "\n") + 1;+}++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 "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);+}++test "click on a painted Called row 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.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ 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, "Called") != 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, Called, 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.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ const frame = try render(&m, std.testing.allocator, 80, 24, 0);+ defer std.testing.allocator.free(frame);+ const dump_mod = @import("dump.zig");+ const vis = try dump_mod.visible(std.testing.allocator, frame);+ defer std.testing.allocator.free(vis);+ try std.testing.expect(std.mem.indexOf(u8, vis, "[Image #1]") != null);+ try std.testing.expect(std.mem.indexOf(u8, vis, "Called") != null);+ try std.testing.expect(std.mem.indexOf(u8, vis, "╭") != 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);+ const dbg = try chrome.overlay(&m, std.testing.allocator, 80);+ defer std.testing.allocator.free(dbg);+ 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.push(.tool, "⚙ bash");+ const frame = try render(&m, std.testing.allocator, 80, 24, 0);+ defer std.testing.allocator.free(frame);+ m.openOverlay(.debug);+ const text = try chrome.overlay(&m, std.testing.allocator, 80);+ defer std.testing.allocator.free(text);+ 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);+}diff --git a/TUI/root.zig b/TUI/root.zignew file mode 100644index 00000000..156d8f1d--- /dev/null+++ b/TUI/root.zig@@ -0,0 +1,57 @@+//! 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;+pub const TurnFn = engine.TurnFn;+pub const ModelFn = engine.ModelFn;+pub const CancelFn = engine.CancelFn;+pub const RunOpts = run_mod.RunOpts;+pub const run = run_mod.run;+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;+ _ = theme;+ _ = catalog;+ _ = app;+ _ = @import("dispatch.zig");+ _ = @import("key.zig");+ _ = @import("input.zig");+ _ = @import("keys.zig");+ _ = @import("nav.zig");+ _ = @import("image.zig");+ _ = @import("turn.zig");+ _ = @import("welcome.zig");+ _ = @import("scrollback.zig");+ _ = @import("chrome.zig");+ _ = @import("models.zig");+ _ = @import("markdown.zig");+ _ = @import("dump.zig");+ _ = @import("effort.zig");+ _ = @import("sim.zig");+ _ = @import("render.zig");+ _ = @import("tty.zig");+ _ = run_mod;+}++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.zignew file mode 100644index 00000000..1d2f2307--- /dev/null+++ b/TUI/run.zig@@ -0,0 +1,232 @@+//! 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 engine = @import("engine.zig");+const key_mod = @import("key.zig");+const keys = @import("keys.zig");+const render_mod = @import("render.zig");+const theme_mod = @import("theme.zig");+const turn = @import("turn.zig");+const tty = @import("tty.zig");+const Model = app.Model;++pub const RunOpts = struct {+ turn_ctx: ?*anyopaque = null,+ turn_fn: ?engine.TurnFn = null,+ model_fn: ?engine.ModelFn = null,+ cancel_fn: ?engine.CancelFn = null,+ model_name: []const u8 = "",+ models: []const u8 = "",+ cwd: []const u8 = ".",+ yolo: bool = false,+ hud_fn: ?engine.HudFn = null,+ paste_fn: ?engine.PasteFn = null,+};++pub fn run(+ gpa: std.mem.Allocator,+ io: Io,+ environ_map: *const std.process.Environ.Map,+ opts: RunOpts,+) !void {+ _ = environ_map;+ 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_model_name = opts.model_name;+ engine.g_models = opts.models;+ engine.g_cwd = opts.cwd;++ var m: Model = undefined;+ m.setup(gpa);+ defer m.deinit();+ if (opts.yolo) m.mode = .always_approve;++ var raw = tty.enterRaw() orelse return error.NotATty;+ defer tty.restore(raw);++ var out_buf: [64 * 1024]u8 = undefined;+ var stdout = Io.File.stdout().writer(io, &out_buf);+ const w = &stdout.interface;+ // 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~.+ w.writeAll("\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m") catch {};+ w.flush() catch {};+ defer {+ w.writeAll("\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l") catch {};+ w.flush() catch {};+ }++ var inbuf: [4096]u8 = undefined;+ var pending_len: usize = 0;+ var last_hash: u64 = 0;+ var saw_gfx: bool = false;+ var prev: []u8 = &.{};+ var prev_rows: usize = 0;+ defer if (prev.len != 0) gpa.free(prev);+ while (m.running and !m.quit_requested) {+ m.now_ms = @intCast(@divTrunc(@max(@as(i128, 0), Io.Timestamp.now(io, .real).nanoseconds), 1_000_000));+ if (m.pending) |job| {+ if (job.done.load(.acquire)) {+ turn.finishJob(&m);+ if (turn.drainSteer(&m) == .quit) break;+ }+ }+ const cols = @max(tty.cols(), @as(usize, 40));+ const rows = @max(tty.rows(), @as(usize, 12));+ // Always drop leftover Kitty layers — they outlive cell redraws.+ w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};+ w.flush() catch {};+ const frame = render_mod.render(&m, gpa, cols, rows, m.now_ms) catch "tui: render error";+ defer gpa.free(frame);+ const hash = std.hash.Wyhash.hash(0, frame);+ if (hash != last_hash) {+ const has_gfx = std.mem.indexOf(u8, frame, "\x1b_G") != null;+ const full = prev.len == 0 or rows != prev_rows or saw_gfx or has_gfx;+ // Kitty images sit above the cell grid and survive \x1b[K / dirty+ // paints — delete before every redraw that might have shown one.+ if (saw_gfx or has_gfx) w.writeAll("\x1b_Ga=d,d=A,q=2\x1b\\") catch {};+ paint(w, frame, rows, cols, if (full) &.{} else prev, m.theme().bg) catch {};+ if (prev.len != 0) gpa.free(prev);+ prev = gpa.dupe(u8, frame) catch &.{};+ prev_rows = rows;+ last_hash = hash;+ saw_gfx = has_gfx;+ }++ const wait: i32 = if (m.pending != null) 50 else 200;+ if (!tty.poll(wait)) continue;+ const got = tty.readStdin(inbuf[pending_len..]);+ const n = pending_len + got;+ if (n == 0) {+ pending_len = 0;+ continue;+ }+ var i: usize = 0;+ while (key_mod.next(inbuf[0..n], &i)) |k| {+ switch (keys.handle(&m, k)) {+ .stay => {},+ .quit => {+ m.running = false;+ break;+ },+ .background => parkToShell(io, w, &raw),+ }+ }+ if (i < n) {+ const rest = n - i;+ std.mem.copyForwards(u8, inbuf[0..rest], inbuf[i..n]);+ pending_len = rest;+ } else pending_len = 0;+ }+}++fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {+ w.writeAll("\x1b[>4;0m\x1b[<u\x1b[?7h\x1b[?1006l\x1b[?1003l\x1b[?1000l\x1b[?2004l\x1b[?25h\x1b[?1049l") 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("\x1b[?1049h\x1b[?25l\x1b[?2004h\x1b[?1000h\x1b[?1003h\x1b[?1006h\x1b[?7l\x1b[>11u\x1b[>4;2m") catch {};+ w.flush() catch {};+ _ = io;+}++/// Rewrite only rows that changed so a drag-select on older transcript survives+/// a live token / thinking tick. Empty `prev` forces a full home+repaint.+fn paint(w: *Io.Writer, frame: []const u8, rows: usize, cols: usize, prev: []const u8, bg: []const u8) !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 (it.next()) |ln| {+ if (row >= rows) break;+ try w.writeAll(bg);+ try w.writeAll(ln);+ try fillRow(w, ln, cols);+ try w.writeAll(bg);+ try w.writeAll("\x1b[K");+ if (row + 1 < rows) try w.writeAll("\r\n");+ row += 1;+ }+ while (row < rows) {+ try w.writeAll(bg);+ try w.writeAll("\x1b[K");+ if (row + 1 < rows) try w.writeAll("\r\n");+ row += 1;+ }+ try w.flush();+ return;+ }+ var row: usize = 0;+ while (row < rows) : (row += 1) {+ if (!rowChanged(prev, frame, row)) continue;+ try w.print("\x1b[{d};1H", .{row + 1});+ try w.writeAll(bg);+ const ln = nthLine(frame, row);+ try w.writeAll(ln);+ try fillRow(w, ln, cols);+ try w.writeAll(bg);+ try w.writeAll("\x1b[K");+ }+ try w.flush();+}++fn fillRow(w: *Io.Writer, ln: []const u8, cols: usize) !void {+ const vis = theme_mod.visibleLen(ln);+ if (vis >= cols) return;+ var n = cols - vis;+ while (n > 0) : (n -= 1) try w.writeByte(' ');+}++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 "";+}++fn rowChanged(prev: []const u8, frame: []const u8, row: usize) bool {+ return !std.mem.eql(u8, nthLine(prev, row), nthLine(frame, row));+}++test "run loop enables click 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' };+ const hover_on = [_]u8{ '?', '1', '0', '0', '3', 'h' };+ 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, 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, "a=d,d=A") != null);+}++test "rowChanged only flags the line that actually moved" {+ const prev = "top\nmiddle\nbottom";+ const next = "top\nmiddle\nBOTTOM";+ try std.testing.expect(!rowChanged(prev, next, 0));+ try std.testing.expect(!rowChanged(prev, next, 1));+ try std.testing.expect(rowChanged(prev, next, 2));+ try std.testing.expect(!rowChanged(prev, prev, 2));+}diff --git a/TUI/scrollback.zig b/TUI/scrollback.zignew file mode 100644index 00000000..094c3776--- /dev/null+++ b/TUI/scrollback.zig@@ -0,0 +1,440 @@+//! Conversation scrollback. ANSI only.+//! Consecutive tool rows collapse into a Grok-style summary until expanded.++const std = @import("std");++const app = @import("app.zig");+const theme_mod = @import("theme.zig");+const Model = app.Model;++/// 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);+ const collapsed = self.history.items[run.start].folded;+ if (collapsed) {+ if (!first) try out.append('\n');+ first = false;+ const selected = self.focus == .scrollback and self.selected >= run.start and self.selected < run.end;+ try out.appendSlice(try summary(self, a, run.start, run.end, selected));+ i = run.end;+ continue;+ }+ var t = run.start;+ while (t < run.end) {+ if (!first) try out.append('\n');+ first = false;+ const selected = self.focus == .scrollback and t == self.selected;+ try out.appendSlice(try toolVisual(self, a, t, run.end, width, now_ms, selected));+ t = nextTool(self, t, run.end);+ }+ i = run.end;+ 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, i, e, width, now_ms, selected));+ i += 1;+ }+ if (self.pending) |job| {+ if (job.stream.snapshot(a)) |live| {+ if (!first) try out.append('\n');+ first = false;+ try out.appendSlice(try theme_mod.paint(a, self.theme().muted, try tail(a, strip(a, live), width, 4)));+ }+ 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 collapsed = self.history.items[run.start].folded;+ var lines: usize = 0;+ if (collapsed) {+ const s = summary(self, a, run.start, run.end, false) catch "";+ lines = lineCount(s);+ } else {+ var t = run.start;+ while (t < run.end) {+ const s = toolVisual(self, a, t, run.end, width, self.now_ms, false) catch "";+ lines += lineCount(s);+ t = nextTool(self, t, run.end);+ }+ }+ if (visual_row >= v and visual_row < v + lines) return run.start;+ v += lines;+ i = run.end;+ continue;+ }+ const s = row(self, a, 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;+}++fn lineCount(s: []const u8) usize {+ if (s.len == 0) return 1;+ return std.mem.count(u8, s, "\n") + 1;+}++fn isSearch(text: []const u8) bool {+ return containsIgnoreCase(text, "search") or containsIgnoreCase(text, "grep") or containsIgnoreCase(text, "find");+}++fn isMcp(text: []const u8) bool {+ return std.mem.indexOf(u8, text, "mcp__") != null or containsIgnoreCase(text, "mcp");+}++fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {+ if (needle.len > hay.len) return false;+ var i: usize = 0;+ while (i + needle.len <= hay.len) : (i += 1) {+ if (std.ascii.eqlIgnoreCase(hay[i .. i + needle.len], needle)) return true;+ }+ return false;+}++fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, selected: bool) ![]const u8 {+ const th = self.theme();+ var searches: usize = 0;+ var calls: usize = 0;+ var mcp_n: usize = 0;+ var i = start;+ while (i < end) : (i += 1) {+ const t = self.history.items[i].text;+ if (isMcp(t)) mcp_n += 1;+ if (isSearch(t)) searches += 1 else calls += 1;+ }+ const sel: []const u8 = if (selected) "› " else " ";+ const live = if (self.pending != null)+ try std.fmt.allocPrint(a, "{s}❙{s} ", .{ if (flickerOn(self.now_ms)) th.accent else th.muted, theme_mod.reset })+ else+ "";+ var out = std.array_list.Managed(u8).init(a);+ if (calls > 0) {+ const label = if (mcp_n == calls + searches)+ try std.fmt.allocPrint(a, "{s}{s}◆ Called {d} MCP tool{s}", .{ sel, live, calls, if (calls == 1) "" else "s" })+ else+ try std.fmt.allocPrint(a, "{s}{s}◆ Called {d} tool{s}", .{ sel, live, calls, if (calls == 1) "" else "s" });+ try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));+ }+ if (searches > 0) {+ if (out.items.len > 0) try out.append('\n');+ const label = try std.fmt.allocPrint(a, "{s}{s}◆ Searched {d} MCP tool{s}", .{ sel, live, searches, if (searches == 1) "" else "s" });+ try out.appendSlice(try theme_mod.paint(a, if (selected) th.accent else th.muted, label));+ }+ return out.items;+}++fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width: usize, now_ms: u64, selected: bool) ![]const u8 {+ const th = self.theme();+ const mark: []const u8 = switch (e.kind) {+ .user => "",+ .assistant => "●",+ .tool => "◆",+ .system => "·",+ .err => "●",+ .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)+ thinkingLabel(now_ms)+ else if (e.kind == .tool)+ try toolTitle(a, e.text)+ else if (e.folded)+ firstLine(e.text)+ else+ e.text;+ const body = switch (e.kind) {+ .assistant => try @import("markdown.zig").renderTinted(a, raw, th.accent, th.muted, th.text),+ .user => try @import("markdown.zig").renderUser(a, raw, th.accent, th.text),+ else => raw,+ };+ const sel: []const u8 = if (selected) "› " else " ";+ if (e.kind == .user) {+ const line = try std.fmt.allocPrint(a, "{s}{s}#{d}{s} {s}", .{ sel, th.muted, userNo(self, idx), theme_mod.reset, body });+ return theme_mod.wrapToWidth(a, line, width);+ }+ if (e.kind == .pending) {+ const fg = if (flickerOn(now_ms)) th.accent else th.muted;+ const line = try std.fmt.allocPrint(a, "{s}{s}❙{s} {s}{s}", .{ sel, fg, theme_mod.reset, body, theme_mod.reset });+ return theme_mod.wrapToWidth(a, line, width);+ }+ const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body, theme_mod.reset });+ return theme_mod.wrapToWidth(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;+}++fn prettyTool(text: []const u8) []const u8 {+ var s = std.mem.trim(u8, text, " \t");+ const prefixes = [_][]const u8{ "⚙ ", "✓ ", "✗ ", "⊘ " };+ for (prefixes) |p| {+ if (std.mem.startsWith(u8, s, p)) s = s[p.len..];+ }+ if (std.mem.startsWith(u8, s, "mcp__")) {+ if (std.mem.lastIndexOf(u8, s, "__")) |u| {+ if (u + 2 < s.len) return s[u + 2 ..];+ }+ }+ return s;+}++fn isStartTool(text: []const u8) bool {+ return std.mem.startsWith(u8, std.mem.trim(u8, text, " \t"), "⚙ ");+}++fn isDoneTool(text: []const u8) bool {+ const s = std.mem.trim(u8, text, " \t");+ return std.mem.startsWith(u8, s, "✓ ") or std.mem.startsWith(u8, s, "✗ ") or std.mem.startsWith(u8, s, "⊘ ");+}++fn nextTool(self: *const Model, t: usize, end: usize) usize {+ if (t + 1 < end and isStartTool(self.history.items[t].text) and isDoneTool(self.history.items[t + 1].text))+ return t + 2;+ return t + 1;+}++fn shortToolName(name: []const u8) []const u8 {+ if (std.mem.eql(u8, name, "read_file")) return "read";+ if (std.mem.eql(u8, name, "write_file")) return "write";+ return name;+}++fn toolTitle(a: std.mem.Allocator, text: []const u8) ![]const u8 {+ const pretty = prettyTool(text);+ const cut = std.mem.indexOf(u8, pretty, " | ") orelse pretty.len;+ const head = pretty[0..cut];+ const sp = std.mem.indexOfScalar(u8, head, ' ') orelse return shortToolName(head);+ const name = shortToolName(head[0..sp]);+ const rest = std.mem.trim(u8, head[sp + 1 ..], " \t");+ if (rest.len == 0) return name;+ return std.fmt.allocPrint(a, "{s} {s}", .{ name, rest });+}++fn toolPreview(text: []const u8) ?[]const u8 {+ const pretty = prettyTool(text);+ const at = std.mem.indexOf(u8, pretty, " | ") orelse return null;+ const body = std.mem.trim(u8, pretty[at + 3 ..], " \t");+ return if (body.len == 0) null else body;+}++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.text) and isDoneTool(self.history.items[t + 1].text);+ if (!paired) return row(self, a, t, e, width, now_ms, selected);+ return toolCard(a, self.theme(), e.text, self.history.items[t + 1].text, selected, width);+}++fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, start_text: []const u8, done_text: []const u8, selected: bool, width: usize) ![]const u8 {+ const sel: []const u8 = if (selected) "› " else " ";+ const title = try toolTitle(a, start_text);+ const preview = toolPreview(done_text);+ const head = try std.fmt.allocPrint(a, "{s}{s}◆{s} {s}", .{ sel, if (selected) th.accent else th.muted, theme_mod.reset, title });+ if (preview == null) return theme_mod.wrapToWidth(a, head, width);+ const body = try std.fmt.allocPrint(a, "{s}{s}│ {s}{s}", .{ sel, th.muted, preview.?, theme_mod.reset });+ const joined = try std.fmt.allocPrint(a, "{s}\n{s}", .{ try theme_mod.wrapToWidth(a, head, width), try theme_mod.wrapToWidth(a, body, width) });+ return joined;+}++fn flickerOn(now_ms: u64) bool {+ return (now_ms / 140) % 2 == 0;+}++fn thinkingGlyph(now_ms: u64) []const u8 {+ _ = now_ms;+ return "❙";+}++fn thinkingLabel(now_ms: u64) []const u8 {+ const frames = [_][]const u8{ "thinking ", "thinking. ", "thinking.. ", "thinking..." };+ return frames[(now_ms / 320) % frames.len];+}++fn firstLine(s: []const u8) []const u8 {+ if (std.mem.indexOfScalar(u8, s, '\n')) |i| return s[0..i];+ return s;+}++fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {+ var out = std.array_list.Managed(u8).init(a);+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == 0x1b) {+ i += 1;+ if (i < s.len and s[i] == '[') {+ i += 1;+ while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}+ if (i < s.len) i += 1;+ }+ continue;+ }+ out.append(s[i]) catch {};+ i += 1;+ }+ return out.items;+}++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');+ while (it.next()) |ln| {+ const t = std.mem.trim(u8, ln, " \t\r");+ if (@import("turn.zig").isToolLine(t)) continue;+ 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;+}++test "firstLine stops at newline" {+ try std.testing.expectEqualStrings("ab", firstLine("ab\ncd"));+}++test "thinking animation is a word, not a lone spinner" {+ try std.testing.expect(std.mem.startsWith(u8, thinkingLabel(0), "thinking"));+ try std.testing.expect(!std.mem.eql(u8, thinkingLabel(0), thinkingLabel(320)));+ try std.testing.expectEqualStrings("❙", thinkingGlyph(0));+ try std.testing.expect(flickerOn(0) != flickerOn(140));+}++test "prettyTool strips mcp prefix" {+ try std.testing.expectEqualStrings("memo", prettyTool("✓ mcp__codedbpro__memo"));+ try std.testing.expectEqualStrings("faster_search", prettyTool("⚙ mcp__codedbpro__faster_search"));+ try std.testing.expectEqualStrings("bash", prettyTool("⚙ bash"));+}++test "collapsed tool run is one Called summary" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "hi");+ try m.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ 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);+ try std.testing.expect(std.mem.indexOf(u8, text, "Called 2") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "⚙ bash") == null);+ m.toggleToolGroup(1);+ const open = try render(&m, arena.allocator(), 80, 0);+ try std.testing.expect(std.mem.indexOf(u8, open, "bash") != null);+ try std.testing.expect(std.mem.indexOf(u8, open, "Called 2") == null);+}++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 "Called summary 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.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ 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, "Called") != 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 is one Searched summary" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.tool, "⚙ grep needle");+ try m.push(.tool, "✓ grep needle");+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const text = try render(&m, arena.allocator(), 80, 0);+ try std.testing.expect(std.mem.indexOf(u8, text, "Searched 2") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "⚙ 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.push(.tool, "⚙ read src/foo.zig");+ try m.push(.tool, "✓ read | const std = @import(\"std\");");+ 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/sim.zig b/TUI/sim.zignew file mode 100644index 00000000..f507448b--- /dev/null+++ b/TUI/sim.zig@@ -0,0 +1,240 @@+//! 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 key_mod = @import("key.zig");+const keys = @import("keys.zig");+const render_mod = @import("render.zig");+const theme_mod = @import("theme.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,++ 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.model.setup(alloc);+ }++ pub fn deinit(self: *Term) void {+ self.model.deinit();+ }++ /// Raw Ghostty/xterm bytes. Incomplete CSI is left unconsumed (same as the live loop).+ pub fn feed(self: *Term, bytes: []const u8) Effect {+ var i: usize = 0;+ var last: Effect = .stay;+ while (key_mod.next(bytes, &i)) |k| {+ last = keys.handle(&self.model, k);+ if (last != .stay) break;+ }+ self.last_effect = last;+ return last;+ }++ 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 "clickText on Called 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.push(.tool, "⚙ bash");+ try term.model.push(.tool, "✓ bash");+ const before = try term.screen();+ defer std.testing.allocator.free(before);+ try std.testing.expect(std.mem.indexOf(u8, before, "Called") != null);+ try std.testing.expect(try term.clickText("Called"));+ try std.testing.expect(!term.model.history.items[1].folded);+ const after = try term.screen();+ defer std.testing.allocator.free(after);+ try std.testing.expect(std.mem.indexOf(u8, after, "Called") == null);+}++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.push(.tool, "⚙ bash");+ try term.model.push(.tool, "✓ bash");+ const hit = try term.find("Called") orelse return error.NoCalled;+ 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);+ try std.testing.expect(std.mem.indexOf(u8, vis, "/quit") != null);+}++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 "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);+}diff --git a/TUI/theme.zig b/TUI/theme.zignew file mode 100644index 00000000..a29adef9--- /dev/null+++ b/TUI/theme.zig@@ -0,0 +1,230 @@+//! 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);+}++/// Columns in `s`, skipping SGR. Assumes 1-col codepoints (no CJK/emoji width).+pub fn visibleLen(s: []const u8) usize {+ var n: usize = 0;+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == 0x1b) {+ i += 1;+ if (i < s.len and s[i] == '[') {+ i += 1;+ while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}+ if (i < s.len) i += 1;+ }+ continue;+ }+ const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;+ i += @min(w, s.len - i);+ n += 1;+ }+ return n;+}++pub fn takeCols(s: []const u8, max: usize) []const u8 {+ var n: usize = 0;+ var i: usize = 0;+ while (i < s.len and n < max) {+ if (s[i] == 0x1b) {+ i += 1;+ if (i < s.len and s[i] == '[') {+ i += 1;+ while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}+ if (i < s.len) i += 1;+ }+ continue;+ }+ const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;+ const step = @min(w, s.len - i);+ i += step;+ n += 1;+ }+ 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);+}++/// Wrap `s` so no row is wider than `width` columns. SGR is preserved.+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 col: usize = 0;+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == '\n') {+ try out.append('\n');+ col = 0;+ i += 1;+ continue;+ }+ if (s[i] == 0x1b) {+ const start = i;+ i += 1;+ if (i < s.len and s[i] == '[') {+ i += 1;+ while (i < s.len and (s[i] < 0x40 or s[i] > 0x7e)) : (i += 1) {}+ if (i < s.len) i += 1;+ }+ try out.appendSlice(s[start..i]);+ continue;+ }+ const w = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;+ const step = @min(w, s.len - i);+ if (col >= width) {+ try out.append('\n');+ col = 0;+ }+ try out.appendSlice(s[i .. i + step]);+ col += 1;+ i += 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 "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);+ }+}diff --git a/TUI/tty.zig b/TUI/tty.zignew file mode 100644index 00000000..4eb8728c--- /dev/null+++ b/TUI/tty.zig@@ -0,0 +1,60 @@+//! Minimal raw-mode + size + stdin poll for the fullscreen TUI.+//! Kept inside TUI/ so we do not share src/term.zig across modules.++const std = @import("std");+const builtin = @import("builtin");++pub const RawState = if (builtin.os.tag == .windows) struct { dummy: u8 = 0 } else std.posix.termios;++pub fn enterRaw() ?RawState {+ if (builtin.os.tag == .windows) return .{};+ const fd = std.posix.STDIN_FILENO;+ const orig = std.posix.tcgetattr(fd) catch return null;+ var raw = orig;+ raw.lflag.ICANON = false;+ raw.lflag.ECHO = false;+ raw.lflag.ISIG = false;+ 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 (builtin.os.tag == .windows) return;+ std.posix.tcsetattr(std.posix.STDIN_FILENO, .NOW, state) catch {};+}++pub fn poll(timeout_ms: i32) bool {+ if (builtin.os.tag == .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 (builtin.os.tag == .windows) return 0;+ return std.posix.read(std.posix.STDIN_FILENO, buf) catch 0;+}++pub fn cols() usize {+ if (builtin.os.tag == .windows) return 80;+ 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 (builtin.os.tag == .windows) return 24;+ 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.zignew file mode 100644index 00000000..ca8ed2b2--- /dev/null+++ b/TUI/turn.zig@@ -0,0 +1,276 @@+//! 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;++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 = 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);+ 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 &.{},+ .params = .{+ .effort = self.effort,+ .fast = self.fast,+ .thinking = self.thinking_show,+ .ultracode = self.ultracode or self.effort == .ultra,+ .goal = self.goal orelse "",+ },+ .stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },+ };+ self.push(.pending, "") catch {};+ self.pending = job;+ if (std.Thread.spawn(.{}, engine.jobRun, .{job})) |th| {+ job.thread = th;+ } else |_| {+ job.threaded = false;+ engine.jobRun(job);+ }+}++pub fn finishJob(self: *Model) void {+ const job = self.pending orelse return;+ if (!job.done.load(.acquire)) return;+ if (job.threaded) job.thread.join();++ const n = self.history.items.len;+ if (n > 0 and self.history.items[n - 1].kind == .pending) {+ self.alloc.free(self.history.items[n - 1].text);+ self.history.shrinkRetainingCapacity(n - 1);+ }+ // The live stream carries ⚙/✓/✗ lines; the result is only the final+ // answer. Keep the tool rows so they don't vanish with the pending entry.+ if (job.stream.snapshot(self.alloc)) |live| {+ defer self.alloc.free(live);+ persistToolLines(self, live);+ }+ if (job.result) |r| {+ self.chars_out += r.len;+ self.push(.assistant, r) catch {};+ self.alloc.free(r);+ } else if (self.cancel_requested) {+ 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 (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);+ self.alloc.destroy(job);+ self.pending = null;+ self.cancel_requested = false;+ self.scroll = 0;+ self.follow = true;+}++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) {+ if (self.alloc.dupe(u8, v)) |dup| {+ self.steer_queue.append(dup) catch self.alloc.free(dup);+ self.input.setValue("") catch {};+ self.pushFmt(.system, "↳ queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};+ } else |_| {}+ } 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);+}++pub fn isToolLine(line: []const u8) bool {+ return std.mem.startsWith(u8, line, "⚙ ") or+ std.mem.startsWith(u8, line, "✓ ") or+ std.mem.startsWith(u8, line, "✗ ") or+ std.mem.startsWith(u8, line, "⊘ ");+}++/// Pull new ⚙/✓/✗ lines out of the live stream so they become clickable+/// folded history *during* the turn, not only after finishJob.+pub fn harvestLiveTools(self: *Model) void {+ const job = self.pending orelse return;+ const live = job.stream.snapshot(self.alloc) orelse return;+ defer self.alloc.free(live);+ var held: ?app.Entry = null;+ const n = self.history.items.len;+ if (n > 0 and self.history.items[n - 1].kind == .pending) {+ held = self.history.items[n - 1];+ self.history.shrinkRetainingCapacity(n - 1);+ }+ persistToolLines(self, live);+ if (held) |e| self.history.append(e) catch {};+}++fn persistToolLines(self: *Model, stream: []const u8) void {+ var have: usize = 0;+ var hi = self.history.items.len;+ while (hi > 0) {+ hi -= 1;+ if (self.history.items[hi].kind == .user) break;+ if (self.history.items[hi].kind == .tool) have += 1;+ }+ var seen: usize = 0;+ var it = std.mem.splitScalar(u8, stream, '\n');+ while (it.next()) |raw| {+ const line = std.mem.trim(u8, raw, " \t\r");+ if (line.len == 0 or !isToolLine(line)) continue;+ if (seen < have) {+ seen += 1;+ continue;+ }+ self.push(.tool, line) catch {};+ seen += 1;+ }+}++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 keeps tool lines from the live stream" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ const live = "hello\n⚙ bash\n✓ bash\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.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);+ try std.testing.expectEqualStrings("⚙ bash", m.history.items[0].text);+ try std.testing.expectEqual(app.EntryKind.tool, m.history.items[1].kind);+ try std.testing.expectEqualStrings("✓ bash", m.history.items[1].text);+ try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[2].kind);+ try std.testing.expectEqualStrings("all done", m.history.items[2].text);+}++test "hosted tool line is visible on the live tail before finishJob" {+ 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) ?[]const u8 {+ stream.appendBytes("⚙ bash\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);+ 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();+ harvestLiveTools(&m);+ const harvested = try scrollback.render(&m, arena_state.allocator(), 80, 0);+ try std.testing.expect(std.mem.indexOf(u8, harvested, "Called") != 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' }));+}diff --git a/TUI/welcome.zig b/TUI/welcome.zignew file mode 100644index 00000000..9f7de6b1--- /dev/null+++ b/TUI/welcome.zig@@ -0,0 +1,18 @@+//! 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 c8a5b975..fea2fd44 100644--- a/build.zig+++ b/build.zig@@ -54,6 +54,12 @@ pub fn build(b: *std.Build) void {// standalone graff-repl exe below). The repo's first dependency.const zigzag = b.dependency("zigzag", .{ .target = target, .optimize = optimize });exe.root_module.addImport("zigzag", zigzag.module("zigzag"));+ const tui_mod = b.createModule(.{+ .root_source_file = b.path("TUI/root.zig"),+ .target = target,+ .optimize = optimize,+ });+ 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");@@ -84,6 +90,7 @@ pub fn build(b: *std.Build) void {});unit_tests.root_module.addOptions("build_options", opts);unit_tests.root_module.addImport("zigzag", zigzag.module("zigzag"));+ unit_tests.root_module.addImport("tui", tui_mod);const run_tests = b.addRunArtifact(unit_tests);const test_step = b.step("test", "Run unit tests");test_step.dependOn(&run_tests.step);@@ -147,4 +154,26 @@ pub fn build(b: *std.Build) void {repl_tests.root_module.addImport("zigzag", zigzag.module("zigzag"));const repl_test_step = b.step("repl-test", "Run zigzag REPL unit tests");repl_test_step.dependOn(&b.addRunArtifact(repl_tests).step);++ 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,+ }),+ });+ 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,+ }),+ });++ const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");+ tui_test_step.dependOn(&b.addRunArtifact(tui_tests).step);}diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex f10b869f..570fa0aa 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -12,7 +12,8 @@],"test_roots": ["src/main.zig",- "src/repl.zig"+ "src/repl.zig",+ "TUI/root.zig"],"test_count_baseline": 1264,"test_count_slack": 25,diff --git a/src/adopt.zig b/src/adopt.zignew file mode 100644index 00000000..de5e8093--- /dev/null+++ b/src/adopt.zig@@ -0,0 +1,438 @@+//! Copy MCP servers and skills from Claude Code / Cursor into graff's own+//! folders (`~/.codegraff/mcp.json`, `.mcp.json`, `~/.codegraff/skills`,+//! `.harness/skills`). Same idea as Grok's `/import-claude`: scan their files,+//! write ours, never overwrite a name that is already configured.++const std = @import("std");+const Io = std.Io;+const Value = std.json.Value;+const Allocator = std.mem.Allocator;++const mcp_config = @import("mcp_config.zig");+const skill_docs = @import("skill_docs.zig");++const reserved = "smolify";+const file_cap: std.Io.Limit = .limited(2 << 20);+const max_copy_depth: u8 = 6;+/// Written after the first adopt so startup does not rescan Claude every launch.+pub const marker_rel = ".codegraff/adopted";++pub const Report = struct {+ added_user: usize = 0,+ added_project: usize = 0,+ skipped: usize = 0,+ skills: usize = 0,+ hooks: usize = 0,+ rules: usize = 0,+ sources: usize = 0,+};++/// `graff mcp import` / `graff import-claude`. Always allowed after first-run.+pub fn command(io: Io, arena: Allocator, home: []const u8, cwd: []const u8, out: *Io.Writer) !void {+ const r = try run(io, arena, home, cwd);+ markAdopted(io, arena, home);+ if (r.added_user + r.added_project + r.skills == 0 and r.skipped == 0) {+ try out.writeAll("nothing to adopt: no Claude/Cursor MCP servers or skills found.\n");+ try out.flush();+ return;+ }+ try out.print("adopted {d} user MCP → ~/" ++ mcp_config.global_rel_path ++ "\n", .{r.added_user});+ try out.print("adopted {d} project MCP → .mcp.json\n", .{r.added_project});+ if (r.skipped > 0) try out.print("skipped {d} already configured\n", .{r.skipped});+ try out.print("copied {d} skill(s) → ~/.codegraff/skills and .harness/skills\n", .{r.skills});+ if (r.hooks > 0) try out.print("copied {d} hook(s) → ~/.codegraff/hooks (PreToolUse Read/Edit skipped)\n", .{r.hooks});+ if (r.rules > 0) try out.print("copied {d} rule file(s) → .harness/\n", .{r.rules});+ try out.writeAll("new MCP servers still need /mcp trust or --yolo to connect.\n");+ try out.flush();+}++pub fn trySlash(io: Io, arena: Allocator, home: []const u8, line: []const u8, out: *Io.Writer) !bool {+ const cmd = std.mem.trim(u8, line, " \t");+ if (!(std.mem.eql(u8, cmd, "/import-claude") or std.mem.eql(u8, cmd, "/mcp import") or std.mem.eql(u8, cmd, "/adopt")))+ return false;+ var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = Io.Dir.cwd().realPath(io, &cwd_buf) catch 0;+ const cwd = if (n > 0) cwd_buf[0..n] else ".";+ try command(io, arena, home, cwd, out);+ return true;+}++/// One-shot at session start: copy Claude/Cursor MCP + skills into graff folders+/// if we have never done so. Later re-runs go through `command`.+pub fn maybeFirstRun(io: Io, arena: Allocator, home: []const u8, cwd: []const u8) !?Report {+ if (home.len == 0) return null;+ if (alreadyAdopted(io, arena, home)) return null;+ const r = try run(io, arena, home, cwd);+ markAdopted(io, arena, home);+ return r;+}++pub fn alreadyAdopted(io: Io, arena: Allocator, home: []const u8) bool {+ const path = markerPath(arena, home) orelse return false;+ return (Io.Dir.cwd().statFile(io, path, .{}) catch null) != null;+}++fn markAdopted(io: Io, arena: Allocator, home: []const u8) void {+ const path = markerPath(arena, home) orelse return;+ if (std.fs.path.dirname(path)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = "1\n" }) catch {};+}++fn markerPath(arena: Allocator, home: []const u8) ?[]const u8 {+ if (home.len == 0) return null;+ return std.fmt.allocPrint(arena, "{s}/" ++ marker_rel, .{home}) catch null;+}++pub fn run(io: Io, arena: Allocator, home: []const u8, cwd: []const u8) !Report {+ var r: Report = .{};+ var user_add: std.json.ObjectMap = .empty;+ var proj_add: std.json.ObjectMap = .empty;++ if (home.len > 0) {+ takeFile(io, arena, &user_add, &r, try std.fmt.allocPrint(arena, "{s}/.claude.json", .{home}), .user_root, cwd);+ takeFile(io, arena, &user_add, &r, try std.fmt.allocPrint(arena, "{s}/.claude/settings.json", .{home}), .plain, cwd);+ takeFile(io, arena, &user_add, &r, try std.fmt.allocPrint(arena, "{s}/.claude/settings.local.json", .{home}), .plain, cwd);+ takeFile(io, arena, &user_add, &r, try std.fmt.allocPrint(arena, "{s}/.cursor/mcp.json", .{home}), .plain, cwd);+ if (builtin_desktop(arena, home)) |p| takeFile(io, arena, &user_add, &r, p, .plain, cwd);+ }+ takeFile(io, arena, &proj_add, &r, join(arena, cwd, ".claude/settings.json"), .plain, cwd);+ takeFile(io, arena, &proj_add, &r, join(arena, cwd, ".claude/settings.local.json"), .plain, cwd);+ takeFile(io, arena, &proj_add, &r, join(arena, cwd, ".cursor/mcp.json"), .plain, cwd);+ if (home.len > 0) {+ takeFile(io, arena, &proj_add, &r, try std.fmt.allocPrint(arena, "{s}/.claude.json", .{home}), .user_project, cwd);+ }++ const user_path = if (home.len > 0)+ try std.fmt.allocPrint(arena, "{s}/" ++ mcp_config.global_rel_path, .{home})+ else+ null;+ if (user_path) |p| r.added_user = try mergeWrite(io, arena, p, user_add, &r.skipped);+ r.added_project = try mergeWrite(io, arena, join(arena, cwd, ".mcp.json"), proj_add, &r.skipped);++ if (home.len > 0) {+ r.skills += copySkillDir(+ io,+ arena,+ try std.fmt.allocPrint(arena, "{s}/.claude/skills", .{home}),+ try std.fmt.allocPrint(arena, "{s}/.codegraff/skills", .{home}),+ );+ }+ r.skills += copySkillDir(io, arena, join(arena, cwd, skill_docs.compat_dir), join(arena, cwd, skill_docs.project_dir));+ r.hooks += adoptHooks(io, arena, home, cwd);+ r.rules += adoptRules(io, arena, cwd);+ return r;+}++const Kind = enum { plain, user_root, user_project };++fn takeFile(io: Io, arena: Allocator, dest: *std.json.ObjectMap, r: *Report, path: []const u8, kind: Kind, cwd: []const u8) void {+ const text = Io.Dir.cwd().readFileAlloc(io, path, arena, file_cap) catch return;+ const parsed = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch return;+ if (parsed != .object) return;+ r.sources += 1;+ switch (kind) {+ .plain => harvest(arena, dest, parsed.object.get("mcpServers")),+ .user_root => harvest(arena, dest, parsed.object.get("mcpServers")),+ .user_project => harvestProject(arena, dest, parsed.object.get("projects"), cwd),+ }+}++fn harvestProject(arena: Allocator, dest: *std.json.ObjectMap, projects: ?Value, cwd: []const u8) void {+ const obj = if (projects) |v| (if (v == .object) v.object else return) else return;+ var it = obj.iterator();+ while (it.next()) |e| {+ if (!pathEq(e.key_ptr.*, cwd)) continue;+ if (e.value_ptr.* != .object) continue;+ harvest(arena, dest, e.value_ptr.object.get("mcpServers"));+ }+}++fn harvest(arena: Allocator, dest: *std.json.ObjectMap, servers: ?Value) void {+ const obj = if (servers) |v| (if (v == .object) v.object else return) else return;+ var it = obj.iterator();+ while (it.next()) |e| {+ if (std.mem.eql(u8, e.key_ptr.*, reserved)) continue;+ if (dest.get(e.key_ptr.*) != null) continue;+ const n = normalize(arena, e.value_ptr.*) orelse continue;+ dest.put(arena, e.key_ptr.*, n) catch {};+ }+}++fn normalize(arena: Allocator, v: Value) ?Value {+ if (v != .object) return null;+ var out: std.json.ObjectMap = .empty;+ if (v.object.get("url")) |u| if (u == .string and u.string.len > 0) {+ out.put(arena, "url", u) catch return null;+ if (v.object.get("headers")) |h| if (h == .object) out.put(arena, "headers", h) catch {};+ return .{ .object = out };+ };+ const cmd = v.object.get("command") orelse return null;+ if (cmd != .string or cmd.string.len == 0) return null;+ out.put(arena, "command", cmd) catch return null;+ if (v.object.get("args")) |a| if (a == .array) out.put(arena, "args", a) catch {};+ if (v.object.get("env")) |e| if (e == .object) out.put(arena, "env", e) catch {};+ return .{ .object = out };+}++fn mergeWrite(io: Io, arena: Allocator, path: []const u8, incoming: std.json.ObjectMap, skipped: *usize) !usize {+ if (incoming.count() == 0) return 0;+ var root: std.json.ObjectMap = .empty;+ if (Io.Dir.cwd().readFileAlloc(io, path, arena, file_cap)) |text| {+ if (std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always })) |v| {+ if (v == .object) root = v.object;+ } else |_| {}+ } else |_| {}+ var servers: std.json.ObjectMap = .empty;+ if (root.get("mcpServers")) |m| {+ if (m == .object) servers = m.object;+ }+ var added: usize = 0;+ var it = incoming.iterator();+ while (it.next()) |e| {+ if (servers.get(e.key_ptr.*) != null) {+ skipped.* += 1;+ continue;+ }+ servers.put(arena, e.key_ptr.*, e.value_ptr.*) catch continue;+ added += 1;+ }+ if (added == 0) return 0;+ root.put(arena, "mcpServers", .{ .object = servers }) catch return added;+ if (std.fs.path.dirname(path)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };+ s.write(Value{ .object = root }) catch return added;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = aw.writer.buffered() }) catch return 0;+ return added;+}++fn copySkillDir(io: Io, arena: Allocator, src: []const u8, dest_root: []const u8) usize {+ var dir = Io.Dir.cwd().openDir(io, src, .{ .iterate = true }) catch return 0;+ defer dir.close(io);+ var n: usize = 0;+ var it = dir.iterate();+ while (it.next(io) catch null) |e| {+ const from = std.fmt.allocPrint(arena, "{s}/{s}", .{ src, e.name }) catch continue;+ const to = std.fmt.allocPrint(arena, "{s}/{s}", .{ dest_root, e.name }) catch continue;+ switch (e.kind) {+ .directory => {+ const md = std.fmt.allocPrint(arena, "{s}/SKILL.md", .{to}) catch continue;+ if (Io.Dir.cwd().statFile(io, md, .{}) catch null) |_| continue;+ copyTree(io, arena, from, to, 0) catch continue;+ n += 1;+ },+ .file => {+ if (!std.mem.endsWith(u8, e.name, ".md")) continue;+ if (Io.Dir.cwd().statFile(io, to, .{}) catch null) |_| continue;+ Io.Dir.cwd().createDirPath(io, dest_root) catch continue;+ Io.Dir.cwd().copyFile(from, Io.Dir.cwd(), to, io, .{}) catch continue;+ n += 1;+ },+ else => {},+ }+ }+ return n;+}++fn copyTree(io: Io, arena: Allocator, src: []const u8, dest: []const u8, depth: u8) !void {+ if (depth > max_copy_depth) return;+ try Io.Dir.cwd().createDirPath(io, dest);+ var dir = try Io.Dir.cwd().openDir(io, src, .{ .iterate = true });+ defer dir.close(io);+ var it = dir.iterate();+ while (it.next(io) catch null) |e| {+ const from = std.fmt.allocPrint(arena, "{s}/{s}", .{ src, e.name }) catch continue;+ const to = std.fmt.allocPrint(arena, "{s}/{s}", .{ dest, e.name }) catch continue;+ switch (e.kind) {+ .file, .sym_link => Io.Dir.cwd().copyFile(from, Io.Dir.cwd(), to, io, .{}) catch continue,+ .directory => copyTree(io, arena, from, to, depth + 1) catch continue,+ else => {},+ }+ }+}++fn join(arena: Allocator, cwd: []const u8, rel: []const u8) []const u8 {+ if (cwd.len == 0 or std.mem.eql(u8, cwd, ".")) return rel;+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ cwd, rel }) catch rel;+}++fn pathEq(a: []const u8, b: []const u8) bool {+ if (std.mem.eql(u8, a, b)) return true;+ const aa = if (a.len > 0 and a[a.len - 1] == '/') a[0 .. a.len - 1] else a;+ const bb = if (b.len > 0 and b[b.len - 1] == '/') b[0 .. b.len - 1] else b;+ if (std.mem.eql(u8, aa, bb)) return true;+ // Worktrees and moved checkouts: match if either path ends with the other.+ if (aa.len > bb.len) return std.mem.endsWith(u8, aa, bb) and aa[aa.len - bb.len - 1] == '/';+ if (bb.len > aa.len) return std.mem.endsWith(u8, bb, aa) and bb[bb.len - aa.len - 1] == '/';+ return false;+}++/// Claude PreToolUse that matches Read/Edit/Write would brick graff's native tools.+fn skipMatcher(m: []const u8) bool {+ return std.mem.indexOf(u8, m, "Read") != null or std.mem.indexOf(u8, m, "Edit") != null or std.mem.indexOf(u8, m, "Write") != null;+}++fn mapMatcher(arena: Allocator, m: []const u8) []const u8 {+ if (m.len == 0) return "*";+ var out = std.array_list.Managed(u8).init(arena);+ var it = std.mem.splitScalar(u8, m, '|');+ var first = true;+ while (it.next()) |raw| {+ const p = std.mem.trim(u8, raw, " ");+ const mapped: []const u8 = if (std.mem.eql(u8, p, "Bash")) "bash" else if (std.mem.eql(u8, p, "Read")) "read_file" else if (std.mem.eql(u8, p, "Edit")) "edit_file" else if (std.mem.eql(u8, p, "Write")) "write_file" else p;+ if (!first) out.append('|') catch {};+ first = false;+ out.appendSlice(mapped) catch {};+ }+ return if (out.items.len == 0) "*" else out.items;+}++fn adoptHooks(io: Io, arena: Allocator, home: []const u8, cwd: []const u8) usize {+ _ = cwd;+ if (home.len == 0) return 0;+ const paths = [_][]const u8{+ std.fmt.allocPrint(arena, "{s}/.claude/settings.json", .{home}) catch return 0,+ std.fmt.allocPrint(arena, "{s}/.claude/settings.local.json", .{home}) catch return 0,+ };+ var n: usize = 0;+ var graff: std.json.ObjectMap = .empty;+ for (paths) |p| {+ const text = Io.Dir.cwd().readFileAlloc(io, p, arena, file_cap) catch continue;+ const parsed = std.json.parseFromSliceLeaky(Value, arena, text, .{ .allocate = .alloc_always }) catch continue;+ if (parsed != .object) continue;+ const hooks = parsed.object.get("hooks") orelse continue;+ if (hooks != .object) continue;+ n += harvestClaudeHooks(arena, &graff, hooks.object);+ }+ if (n == 0) return 0;+ var root: std.json.ObjectMap = .empty;+ root.put(arena, "hooks", .{ .object = graff }) catch return n;+ const dest = std.fmt.allocPrint(arena, "{s}/.codegraff/hooks/imported-from-claude.json", .{home}) catch return n;+ if (std.fs.path.dirname(dest)) |dir| Io.Dir.cwd().createDirPath(io, dir) catch {};+ var aw: Io.Writer.Allocating = .init(arena);+ var s: std.json.Stringify = .{ .writer = &aw.writer, .options = .{ .whitespace = .indent_2 } };+ s.write(Value{ .object = root }) catch return n;+ Io.Dir.cwd().writeFile(io, .{ .sub_path = dest, .data = aw.writer.buffered() }) catch {};+ return n;+}++fn harvestClaudeHooks(arena: Allocator, dest: *std.json.ObjectMap, hooks: std.json.ObjectMap) usize {+ var n: usize = 0;+ n += takeClaudeEvent(arena, dest, hooks, "PreToolUse", "pre_tool");+ n += takeClaudeEvent(arena, dest, hooks, "PostToolUse", "post_tool");+ n += takeClaudeEvent(arena, dest, hooks, "Stop", "turn_end");+ return n;+}++fn takeClaudeEvent(arena: Allocator, dest: *std.json.ObjectMap, hooks: std.json.ObjectMap, claude_name: []const u8, graff_name: []const u8) usize {+ const ev = hooks.get(claude_name) orelse return 0;+ if (ev != .array) return 0;+ var list = if (dest.get(graff_name)) |v| (if (v == .array) v.array else std.json.Array.init(arena)) else std.json.Array.init(arena);+ var added: usize = 0;+ for (ev.array.items) |item| {+ if (item != .object) continue;+ const matcher = if (item.object.get("matcher")) |m| (if (m == .string) m.string else "") else "";+ if (std.mem.eql(u8, claude_name, "PreToolUse") and skipMatcher(matcher)) continue;+ const inner = item.object.get("hooks") orelse continue;+ if (inner != .array) continue;+ for (inner.array.items) |h| {+ if (h != .object) continue;+ const cmd = h.object.get("command") orelse continue;+ if (cmd != .string or cmd.string.len == 0) continue;+ var entry: std.json.ObjectMap = .empty;+ entry.put(arena, "match", .{ .string = mapMatcher(arena, matcher) }) catch continue;+ entry.put(arena, "command", cmd) catch continue;+ list.append(.{ .object = entry }) catch continue;+ added += 1;+ }+ }+ if (added > 0) dest.put(arena, graff_name, .{ .array = list }) catch {};+ return added;+}++fn adoptRules(io: Io, arena: Allocator, cwd: []const u8) usize {+ var n: usize = 0;+ const dest_dir = join(arena, cwd, ".harness");+ const pairs = [_][2][]const u8{+ .{ join(arena, cwd, "CLAUDE.md"), join(arena, dest_dir, "CLAUDE.md") },+ .{ join(arena, cwd, ".claude/CLAUDE.md"), join(arena, dest_dir, "CLAUDE.md") },+ };+ for (pairs) |pair| {+ if (Io.Dir.cwd().statFile(io, pair[1], .{}) catch null) |_| continue;+ Io.Dir.cwd().copyFile(pair[0], Io.Dir.cwd(), pair[1], io, .{}) catch continue;+ n += 1;+ break;+ }+ return n;+}++fn builtin_desktop(arena: Allocator, home: []const u8) ?[]const u8 {+ if (builtin.os.tag == .macos) {+ return std.fmt.allocPrint(arena, "{s}/Library/Application Support/Claude/claude_desktop_config.json", .{home}) catch null;+ }+ return std.fmt.allocPrint(arena, "{s}/.config/Claude/claude_desktop_config.json", .{home}) catch null;+}++const builtin = @import("builtin");+const testing = std.testing;++test "adopt writes missing Claude MCP into graff folders and skips existing names" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = testing.io;+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});+ const cwd = try std.fmt.allocPrint(arena, "{s}/proj", .{base});++ try Io.Dir.cwd().createDirPath(io, try std.fmt.allocPrint(arena, "{s}/.claude/skills/demo", .{home}));+ try Io.Dir.cwd().createDirPath(io, cwd);+ const payload = try std.fmt.allocPrint(+ arena,+ "{{\"mcpServers\":{{\"codedb\":{{\"command\":\"/bin/codedb\",\"args\":[]}},\"smolify\":{{\"command\":\"x\"}},\"deepwiki\":{{\"url\":\"https://mcp.deepwiki.com/mcp\"}}}},\"projects\":{{\"{s}\":{{\"mcpServers\":{{\"relay\":{{\"command\":\"relay\",\"args\":[\"-s\"]}}}}}}}}}}",+ .{cwd},+ );+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/.claude.json", .{home}), .data = payload });+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/.claude/skills/demo/SKILL.md", .{home}), .data = "---\nname: demo\ndescription: d\n---\nbody\n" });+ try Io.Dir.cwd().writeFile(io, .{ .sub_path = try std.fmt.allocPrint(arena, "{s}/.mcp.json", .{cwd}), .data = "{\"mcpServers\":{\"deepwiki\":{\"url\":\"https://keep.example/mcp\"}}}" });++ const r = try run(io, arena, home, cwd);+ try testing.expectEqual(@as(usize, 2), r.added_user);+ try testing.expectEqual(@as(usize, 1), r.added_project);+ try testing.expectEqual(@as(usize, 0), r.skipped);+ try testing.expectEqual(@as(usize, 1), r.skills);++ const global = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/.codegraff/mcp.json", .{home}), arena, file_cap);+ try testing.expect(std.mem.indexOf(u8, global, "codedb") != null);+ try testing.expect(std.mem.indexOf(u8, global, "smolify") == null);+ const project = try Io.Dir.cwd().readFileAlloc(io, try std.fmt.allocPrint(arena, "{s}/.mcp.json", .{cwd}), arena, file_cap);+ try testing.expect(std.mem.indexOf(u8, project, "relay") != null);+ try testing.expect(std.mem.indexOf(u8, project, "keep.example") != null);++ const again = try run(io, arena, home, cwd);+ try testing.expectEqual(@as(usize, 0), again.added_user);+ try testing.expectEqual(@as(usize, 0), again.added_project);+ try testing.expect(again.skipped >= 2);+}++test "first-run adopt writes a marker and does not run again" {+ var tmp = testing.tmpDir(.{});+ defer tmp.cleanup();+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ const io = testing.io;+ var real_buf: [std.fs.max_path_bytes]u8 = undefined;+ const base = real_buf[0..try tmp.dir.realPath(io, &real_buf)];+ const home = try std.fmt.allocPrint(arena, "{s}/home", .{base});+ try Io.Dir.cwd().createDirPath(io, home);++ try testing.expect(!alreadyAdopted(io, arena, home));+ const first = try maybeFirstRun(io, arena, home, try std.fmt.allocPrint(arena, "{s}/proj", .{base}));+ try testing.expect(first != null);+ try testing.expect(alreadyAdopted(io, arena, home));+ try testing.expect(try maybeFirstRun(io, arena, home, ".") == null);+}diff --git a/src/args.zig b/src/args.zigindex 02f95e07..5ddd1377 100644--- a/src/args.zig+++ b/src/args.zig@@ -69,13 +69,20 @@ pub const Flags = struct {new_session_flag: bool = false, // start a fresh autosaved sessionpositionals: std.ArrayList([]const u8) = .empty,/// True when positionals[0] is a known subcommand (login/key/mcp/serve/- /// update/title/repl/acp/worktree/sandboxes/cube) — those aren't a one-shot+ /// update/title/repl/tui/acp/worktree/sandboxes/cube) — those aren't a one-shot/// prompt even with no --print/-p flag.is_subcommand: bool = false,/// The joined positional args as a one-shot prompt (`harness "say hi"`/// 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@@ -226,7 +233,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], "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], "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") 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") 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) {flags.oneshot_prompt = try std.mem.join(arena, " ", flags.positionals.items);@@ -242,6 +249,16 @@ pub fn parse(init: std.process.Init) !Flags {return flags;}+test "tui and repl are pager subcommands, not one-shot prompts" {+ 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.yolo_flag);+ try std.testing.expect(tui_flags.oneshot_prompt == null);+}+test "effectiveYolo: -p implies yolo, --safe opts out, interactive untouched" {try std.testing.expect(Flags.effectiveYolo(.{ .yolo_flag = true }));try std.testing.expect(Flags.effectiveYolo(.{ .oneshot_prompt = "fix it" }));diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex 600d7554..8a330e53 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -73,6 +73,7 @@ pub const commands = [_]Item{.{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },.{ .name = "/fleet", .usage = "/fleet [on|off]", .desc = "federated DGM contribution (propose/submit/elite_pull)" },.{ .name = "/mcp", .usage = "/mcp [add …]", .desc = "list MCP servers/tools; /mcp add <name> <cmd> [args...] connects one live" },+ .{ .name = "/import-claude", .desc = "copy Claude/Cursor MCP servers and skills into ~/.codegraff and this repo" },.{ .name = "/help", .desc = "list every command" },};diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex d477e4ca..b7001af7 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -156,6 +156,7 @@ fn ownedSessionName(arena: Allocator, arg: []const u8, fallback: []const u8) All/// `line` doesn't match any command in this file — the caller falls through/// to handleRest() for the unknown-command/help terminal stage.pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {+ if (try @import("adopt.zig").trySlash(root.io, arena, root.home, line, out)) return true;if (try commands_privacy.tryHandle(root, line, out)) return true;if (try playbook_glue.command(root, arena, line, out)) return true; // #381 /never | /constraintif (try side_question.command(root, arena, line, out)) return true; // #415 /btwdiff --git a/src/engine_sink.zig b/src/engine_sink.zigindex a930264e..4313a8bc 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -292,11 +292,20 @@ fn hostedEmit(a: *Agent, ev: EngineEvent) void {w.flush() catch {};},.tool_call_announced => |t| {- w.print("⚙ {s}\n", .{t.name}) catch {};+ const arg = compactArg(t.input);+ if (arg.len > 0)+ w.print("⚙ {s} {s}\n", .{ shortTool(t.name), arg }) catch {}+ else+ w.print("⚙ {s}\n", .{shortTool(t.name)}) catch {};w.flush() catch {};},.tool_result => |r| {- w.print("{s} {s}\n", .{ if (r.is_error) "✗" else "✓", r.name }) catch {};+ const mark: []const u8 = if (r.is_error) "✗" else "✓";+ const preview = firstLineCap(r.text, 80);+ if (preview.len > 0)+ w.print("{s} {s} | {s}\n", .{ mark, shortTool(r.name), preview }) catch {}+ else+ w.print("{s} {s}\n", .{ mark, shortTool(r.name) }) catch {};w.flush() catch {};},else => {},@@ -360,6 +369,32 @@ fn jsonLine(w: *Io.Writer, cursor: engine_events.Cursor, payload: anytype) voidw.flush() catch return;}+fn shortTool(name: []const u8) []const u8 {+ if (std.mem.eql(u8, name, "read_file")) return "read";+ if (std.mem.eql(u8, name, "write_file")) return "write";+ return name;+}++fn compactArg(input: std.json.Value) []const u8 {+ const obj = switch (input) {+ .object => |o| o,+ else => return "",+ };+ const keys = [_][]const u8{ "path", "target_file", "file", "filename", "command", "cmd", "query", "q", "pattern", "url", "symbol" };+ for (keys) |k| {+ const v = obj.get(k) orelse continue;+ if (v == .string and v.string.len > 0) return v.string;+ }+ return "";+}++fn firstLineCap(text: []const u8, cap: usize) []const u8 {+ var s = std.mem.trim(u8, text, " \t\r\n");+ if (std.mem.indexOfScalar(u8, s, '\n')) |i| s = std.mem.trim(u8, s[0..i], " \t\r");+ if (s.len > cap) return s[0..cap];+ return s;+}+test {_ = @import("engine_sink_tests.zig");}diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zigindex 079a890f..39a13277 100644--- a/src/engine_sink_tests.zig+++ b/src/engine_sink_tests.zig@@ -387,3 +387,22 @@ test "slice 2: forSession picks the wire in --json and the caller's writer othera.sink = .{ .ctx = &rec, .vt = &vt };try std.testing.expectEqual(@as(*const VTable, &vt), engine_sink.forSession(&a, null).vt);}++test "hosted frontend announces read path and result preview" {+ const saved = engine_sink.hosted_frontend;+ engine_sink.hosted_frontend = true;+ defer engine_sink.hosted_frontend = saved;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ const sink = tuiSink(&a);+ const input = try std.json.parseFromSliceLeaky(std.json.Value, arena_state.allocator(), "{\"path\":\"src/foo.zig\"}", .{});+ sink.emit(undefined, .{ .tool_call_announced = .{ .name = "read_file", .input = input } });+ sink.emit(undefined, .{ .tool_result = .{ .name = "read_file", .text = "const std = @import(\"std\");\nmore", .is_error = false } });+ const got = aw.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, got, "⚙ read src/foo.zig") != null);+ try std.testing.expect(std.mem.indexOf(u8, got, "✓ read | const std") != null);+ try std.testing.expect(std.mem.indexOf(u8, got, "read_file") == null);+}diff --git a/src/help.zig b/src/help.zigindex 654e03bb..7b787398 100644--- a/src/help.zig+++ b/src/help.zig@@ -32,7 +32,7 @@ pub const sections = [_]Section{.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek" }, .blurb = peers_blurb },- .{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/privacy", "/mcp", "/skills", "/agents", "/hooks", "/tools", "/fleet" } },+ .{ .title = "your setup", .names = &.{ "/login", "/key", "/cost", "/usage", "/privacy", "/mcp", "/import-claude", "/skills", "/agents", "/hooks", "/tools", "/fleet" } },.{ .title = "context & history", .names = &.{ "/compact", "/btw", "/doctor", "/debug", "/trace", "/trajectory" } },.{ .title = "shell & images", .names = &.{ "/bash", "/image", "/images", "/paste" } },.{ .title = "look & feel", .names = &.{ "/theme", "/animation", "/title" } },diff --git a/src/main.zig b/src/main.zigindex d95cccc2..8a1842be 100644--- a/src/main.zig+++ b/src/main.zig@@ -81,6 +81,7 @@ test { // unit_tests' root is main.zig only, so reference every split-out module_ = title_mod;_ = serde;_ = mcp_cli;+ _ = @import("adopt.zig");_ = cli;_ = prompts;_ = session;@@ -118,12 +119,11 @@ test { // unit_tests' root is main.zig only, so reference every split-out module_ = session_start;_ = session_run;_ = @import("obs_cost_test.zig");+ _ = @import("tui_launch.zig");_ = provider_mod;_ = agent_mod;}-// System-prompt text (main_system_prompt, strict_note, main_system_prompt_strict, sub_system_prompt, compact_instruction) lives in prompts.zig.const prompts = @import("prompts.zig");-// Tool-schema + provider-tool JSON emission lives in schema.zig; serve.zig/startup.zig import it directly. Kept here to pull in its test{} block.const schema = @import("schema.zig");// The provider/keys core (ProviderSpec/provider_specs, Provider, Keys) lives in provider.zig; provider_specs/Keys stay local aliases for main()'s credential setup and tests.const provider_mod = @import("provider.zig");@@ -482,9 +482,9 @@ pub fn main(init: std.process.Init) !void {// Closing the learning loop: this session counts toward the next trial.defer session_run.startBackgroundLearning(gpa, arena, startup_timing.shutdown_trace.at(io, "background-learning"), init.environ_map, &invocation_budget, !flags.no_telemetry_flag);- // `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL agent loop — each prompt runs a full root turn (tools + MCP) via- // replTurnCb. `graff acp` (acp.zig) is the same idea over Zed's stdio Agent Client Protocol. Both self-contained — each exits after.- if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags) or try @import("acp.zig").runAcpCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags)) return;+ // `graff` is the default session. TTY `graff repl` / `graff tui` open the Grok-style pager.+ // `graff acp` (acp.zig) is the same idea over Zed's stdio Agent Client Protocol. Both self-contained — each exits after.+ if (try session_run.runReplCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags) or try @import("acp.zig").runAcpCommand(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, in, out, arena, flags) or try @import("tui_launch.zig").maybeRun(gpa, io, init.environ_map, &root, @import("bench_priors.zig").noteKeys(&keys), &client, arena, flags, json_mode, g_cwd_display)) return;// One-shot print mode: run the single prompt to completion, print the final text to stdout, exit.if (flags.oneshot_prompt) |prompt_text| {try session_run.runOneshotPrompt(gpa, io, arena, &root, @import("bench_priors.zig").noteKeys(&keys), &tracer, out, prompt_text); // one-shot exits before loop_ctx below — capture keys for sub-first routing here too@@ -581,7 +581,7 @@ const workflow = @import("workflow_test.zig"); // the engine's tests live here (const exec = @import("exec.zig");// ── Unit tests (`zig build test`) ──────────────────────────────────────────test { // pull in tests from imported modules (mcp.zig)- _ = mcp;+ _ = @import("mcp.zig");_ = @import("mcp_rpc.zig");_ = @import("main_test.zig");// A module whose tests must run needs an explicit reference here (a plain @import elsewhere compiles to nothing); scripts/eval-tier1.sh --only reach catches one.diff --git a/src/mcp_cli.zig b/src/mcp_cli.zigindex 5882bb53..099208ad 100644--- a/src/mcp_cli.zig+++ b/src/mcp_cli.zig@@ -145,6 +145,7 @@ fn mcpCliUsage(w: *Io.Writer) !void {try w.writeAll(\\usage:\\ graff mcp list servers in .mcp.json + ~/.codegraff/mcp.json+ \\ graff mcp import copy Claude/Cursor MCP + skills into graff folders\\ graff mcp add <name> --url <https://...> [--header KEY=VALUE ...]\\ graff mcp login <name> OAuth login for a remote server\\ graff mcp add <name> [--env KEY=VALUE ...] -- <command> [args...]@@ -167,6 +168,14 @@ pub fn mcpCommand(io: Io, gpa: Allocator, arena: Allocator, home: []const u8, en// Reads (list/login) see project + global; writes stay project-local.const global_path = mcp_config.globalPath(arena, home, environ_map);+ if (args.len > 0 and (std.mem.eql(u8, args[0], "import") or std.mem.eql(u8, args[0], "import-claude") or std.mem.eql(u8, args[0], "adopt"))) {+ var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = Io.Dir.cwd().realPath(io, &cwd_buf) catch 0;+ const cwd = if (n > 0) cwd_buf[0..n] else ".";+ try @import("adopt.zig").command(io, arena, home, cwd, &out.interface);+ return;+ }+if (args.len == 0 or std.mem.eql(u8, args[0], "list")) {const merged = mcp_config.load(io, arena, Io.Dir.cwd(), mcp_config_path, global_path);try mcp_config.reportInvalid(merged, &out.interface, mcp_config_path, global_path, "", "");diff --git a/src/session_run.zig b/src/session_run.zigindex 146aaa17..4117ae3c 100644--- a/src/session_run.zig+++ b/src/session_run.zig@@ -45,6 +45,7 @@ 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");@@ -64,15 +65,19 @@ const learning_privacy = @import("learning_privacy.zig");const commands_privacy = @import("commands_privacy.zig");const prompts = @import("prompts.zig");-/// `graff repl`: interactive chat REPL on the zigzag TUI, backed by the REAL-/// agent loop — each prompt runs a full root turn (tools + MCP) via-/// replTurnCb, reusing the root agent's tool set + registry + system prompt.+/// `graff repl`: interactive chat on the Grok-style TUI (same as `graff tui`).+/// Piped/non-TTY stdin still drives the old scripted zigzag 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/// time this is called, so taking its address here is safe (this helper/// 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;+ }root.ensureStoredKeys(keys);providers.ensureModelQueryCatalogs(root, keys.*, "");// The standalone chat REPL can switch wire formats inside its own model@@ -103,10 +108,7 @@ pub fn runReplCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agentif (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};models_buf.appendSlice(mi.name) catch {};}- if (Io.File.stdin().isTty(io) catch true)- try repl.run(gpa, io, environ_map, &repl_ctx, repl_glue.replTurnCb, repl_glue.replModelCb, repl_glue.replCancelCb, root.provider.model, models_buf.items)- else- 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);+ 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);return true;}diff --git a/src/session_start.zig b/src/session_start.zigindex 2865bb2b..7fc3f065 100644--- a/src/session_start.zig+++ b/src/session_start.zig@@ -41,6 +41,7 @@ const skills = @import("skills.zig");const mcp = @import("mcp.zig");const mcp_cli = @import("mcp_cli.zig");const mcp_config = @import("mcp_config.zig");+const adopt = @import("adopt.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: the eager-vs-deferred policy for MCP tool schemasconst jobs = @import("jobs.zig");const tool_spill = @import("tool_spill.zig"); // #409: where an over-cap tool output's full bytes go@@ -143,7 +144,9 @@ pub fn setupWorktreeAndBanner(// pre-#409 plain truncation.tool_spill.enable(.{ .io = io, .dir = .cwd(), .base_abs = main_mod.g_cwd_display });- if (!main_mod.json_mode and flags.oneshot_prompt == null) {+ // 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()) {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)]}),@@ -381,6 +384,19 @@ pub fn leanMode(effective_lean: bool, environ_map: anytype) bool {pub fn initRegistryConsent(io: Io, gpa: Allocator, arena: Allocator, out: *Io.Writer, in: *Io.Reader, flags: args.Flags, mcp_config_path: []const u8, home: []const u8, use_color: bool, json_mode: bool, environ_map: anytype) !mcp.Registry {const global_path = mcp_config.globalPath(arena, home, environ_map);const sink = engine_sink.writerSink(out);+ // First interactive session copies Claude/Cursor MCP into ~/.codegraff once.+ // One-shots/--json skip it so CI does not rewrite a checkout. Re-run with+ // `graff mcp import` / `/import-claude`. GRAFF_NO_ADOPT=1 disables.+ if (!json_mode and flags.oneshot_prompt == null and environ_map.get("GRAFF_NO_ADOPT") == null) {+ var cwd_buf: [std.fs.max_path_bytes]u8 = undefined;+ const cwd_n = Io.Dir.cwd().realPath(io, &cwd_buf) catch 0;+ const cwd = if (cwd_n > 0) cwd_buf[0..cwd_n] else ".";+ if (adopt.maybeFirstRun(io, arena, home, cwd) catch null) |r| {+ if (r.added_user + r.added_project + r.skills > 0) {+ sink.emit(io, dimNotice(try std.fmt.allocPrint(arena, "adopted {d} Claude/Cursor MCP server(s) into ~/" ++ mcp_config.global_rel_path ++ " — /mcp trust to connect (or graff mcp import to refresh)", .{r.added_user + r.added_project})));+ }+ }+ }// --json's stdout is a JSONL stream and a one-shot's is the answer; neither// can carry chatter. With a global config `mcp_count > 0` in every project,// so an unguarded line here would corrupt the head of every --json run.diff --git a/src/skill_docs.zig b/src/skill_docs.zigindex 24c9d980..9e510b77 100644--- a/src/skill_docs.zig+++ b/src/skill_docs.zig@@ -157,7 +157,7 @@ fn scan(io: Io, arena: Allocator, home: ?[]const u8) []const Skill {fn collect(io: Io, arena: Allocator, home: ?[]const u8) std.ArrayList(Skill) {var list: std.ArrayList(Skill) = .empty;list.appendSlice(arena, &builtins) catch {};- if (home) |h| for ([_][]const u8{ compat_dir, project_dir }) |dir| {+ if (home) |h| for ([_][]const u8{ compat_dir, ".codegraff/skills", project_dir }) |dir| {const path = std.fmt.allocPrint(arena, "{s}/{s}", .{ h, dir }) catch continue;loadDir(io, arena, &list, path, .personal);};diff --git a/src/tui_launch.zig b/src/tui_launch.zignew file mode 100644index 00000000..3b71446c--- /dev/null+++ b/src/tui_launch.zig@@ -0,0 +1,274 @@+//! 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 pricing = @import("pricing.zig");+const providers = @import("providers.zig");+const repl = @import("repl.zig");+const repl_glue = @import("repl_glue.zig");+const tui = @import("tui");+const engine_sink = @import("engine_sink.zig");+const obs = @import("obs.zig");+const telemetry = @import("telemetry.zig");+const vision = @import("vision.zig");+const builtin = @import("builtin");++/// `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 {+ 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,+ .sys_normal = root.sys_normal,+ .tools_anthropic = root.tools_anthropic,+ .tools_openai = root.tools_openai,+ .tools_responses = root.tools_responses,+ };+ var models_buf = std.array_list.Managed(u8).init(arena);+ for (pricing.models()) |mi| {+ if (mi.name.len == 0) continue;+ if (models_buf.items.len != 0) models_buf.appendSlice(", ") catch {};+ models_buf.appendSlice(mi.name) catch {};+ }+ engine_sink.hosted_frontend = true;+ defer engine_sink.hosted_frontend = false;+ obs.ensureSession();+ 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,+ .models = models_buf.items,+ .cwd = cwd,+ .yolo = yolo,+ .hud_fn = hudCb,+ .paste_fn = pasteCb,+ });+}++/// 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,+) ?[]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 }) catch gpa.free(text);+ }+ var last_len: u32 = 0;+ if (history.len > 0 and history[history.len - 1].role == .user) {+ last_len = @intCast(@min(history[history.len - 1].text.len, std.math.maxInt(u32)));+ }+ const model = if (ctx) |p| @as(*repl_glue.ReplCtx, @ptrCast(@alignCast(p))).provider.model else "";+ obs.prompt(last_len, model);+ // Same buf AND the same atomic len — a fresh repl.StreamBuf around+ // stream.buf left job.stream.len at 0 for the whole turn, so the live+ // tail never showed hosted tool lines until finishJob copied them.+ const result = repl_glue.replTurnCb(ctx, gpa, turns.items, .{+ .effort = @enumFromInt(@intFromEnum(params.effort)),+ .fast = params.fast,+ .thinking = params.thinking,+ .ultracode = params.ultracode,+ .goal = params.goal,+ }, liveStream(stream));+ if (result != null) {+ if (telemetry.g_telem) |t| t.countTurn() else obs.turn(.completed);+ } else obs.turn(.failed);+ return result;+}++fn modelCb(ctx: ?*anyopaque, gpa: Allocator, name: []const u8) ?[]const u8 {+ const nm = repl_glue.replModelCb(ctx, gpa, name);+ if (nm) |n| obs.modelSwitch(n);+ return nm;+}++fn cancelCb(ctx: ?*anyopaque) void {+ repl_glue.replCancelCb(ctx);+}++fn pasteCb(ctx: ?*anyopaque, dest: []u8) isize {+ 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 = vision.grabClipboardImage(c.io, gpa) orelse return 0;+ const n = @min(grab.path.len, dest.len);+ @memcpy(dest[0..n], grab.path[0..n]);+ if (grab.owned) {+ gpa.free(grab.path);+ } else grab.release(c.io, gpa);+ return @intCast(n);+}++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));+}++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 {},+ }+ return w.buffered().len;+}++test {+ _ = tui;+}++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.out_tokens = 0;+ c.api_calls = 0;+ c.sub_calls = 0;+ c.unpriced_calls = 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.mutex.unlock(io);+ }+ obs.reset();+ defer obs.reset();+ obs.attach(io);+ pricing.g_cost.add(io, .priced, "gpt-5.5", 1000, 200, 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"));+}