graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Merge PR #127: markdown pipe tables in the REPL TUI and GUI chat
justrach16c9db70fd6f
diff --cc src/repl.zigindex 10fb8d45,5fc70d50..3342ed0f--- a/src/repl.zig+++ b/src/repl.zig@@@ -383,9 -862,10 +384,10 @@@ pub const HELP_CALC/// Render a markdown string to ANSI for display — approximates the harness's/// streamed renderer: fenced code blocks (left bar), inline `code`, **bold**,- /// # headers, and - bullets. Temporaries live in a local arena; the result is- /// owned by `gpa`.- pub fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8) ![]const u8 {+ /// # headers, - bullets, and | pipe tables (box-drawing, wrapped to fit+ /// `width_hint` columns; 0 = assume 100). Temporaries live in a local arena;+ /// the result is owned by `gpa`.-fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8, width_hint: usize) ![]const u8 {++pub fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8, width_hint: usize) ![]const u8 {var arena_state = std.heap.ArenaAllocator.init(gpa);defer arena_state.deinit();const a = arena_state.allocator();@@@ -425,12 -919,426 +441,249 @@@return gpa.dupe(u8, out.items);}+ fn isTableRow(t: []const u8) bool {+ return t.len >= 2 and t[0] == '|';+ }++ /// `|---|:--:|` style alignment row: pipes/colons/spaces only, dashes required.+ fn isTableSep(t: []const u8) bool {+ if (t.len == 0 or t[0] != '|') return false;+ var dash = false;+ for (t) |c| switch (c) {+ '|', ':', ' ', '\t' => {},+ '-' => dash = true,+ else => return false,+ };+ return dash;+ }++ /// Inline markdown with `code`/**bold** markers stripped — exactly what+ /// renderInline makes visible, unstyled. Cell layout is computed from this.+ fn plainInline(a: std.mem.Allocator, line: []const u8) ![]const u8 {+ var out = std.array_list.Managed(u8).init(a);+ var i: usize = 0;+ while (i < line.len) {+ const c = line[i];+ if (c == '`') {+ if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {+ try out.appendSlice(line[i + 1 .. end]);+ i = end + 1;+ continue;+ }+ } else if (c == '*' and i + 1 < line.len and line[i + 1] == '*') {+ if (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {+ try out.appendSlice(line[i + 2 .. end]);+ i = end + 2;+ continue;+ }+ }+ try out.append(c);+ i += 1;+ }+ return out.items;+ }++ fn dispWidth(s: []const u8) usize {+ var n: usize = 0;+ var i: usize = 0;+ while (i < s.len) {+ i += std.unicode.utf8ByteSequenceLength(s[i]) catch 1;+ n += 1;+ }+ return n;+ }++ /// Word-wrap `s` to `w` display columns; words longer than `w` hard-split at+ /// codepoint boundaries. Never emits leading/trailing spaces on a line.+ fn wrapCell(a: std.mem.Allocator, s: []const u8, w: usize) ![]const []const u8 {+ var lines = std.array_list.Managed([]const u8).init(a);+ var cur = std.array_list.Managed(u8).init(a);+ var cur_w: usize = 0;+ var words = std.mem.tokenizeScalar(u8, s, ' ');+ while (words.next()) |word| {+ var rem = word;+ while (dispWidth(rem) > w) {+ if (cur_w > 0) {+ try lines.append(try a.dupe(u8, cur.items));+ cur.clearRetainingCapacity();+ cur_w = 0;+ }+ var bytes: usize = 0;+ var cnt: usize = 0;+ while (cnt < w and bytes < rem.len) {+ bytes += std.unicode.utf8ByteSequenceLength(rem[bytes]) catch 1;+ cnt += 1;+ }+ try lines.append(try a.dupe(u8, rem[0..bytes]));+ rem = rem[bytes..];+ }+ const ww = dispWidth(rem);+ if (ww == 0) continue;+ if (cur_w > 0 and cur_w + 1 + ww > w) {+ try lines.append(try a.dupe(u8, cur.items));+ cur.clearRetainingCapacity();+ cur_w = 0;+ }+ if (cur_w > 0) {+ try cur.append(' ');+ cur_w += 1;+ }+ try cur.appendSlice(rem);+ cur_w += ww;+ }+ if (cur_w > 0 or lines.items.len == 0) try lines.append(try a.dupe(u8, cur.items));+ return lines.items;+ }++ fn tableRule(out: *std.array_list.Managed(u8), a: std.mem.Allocator, widths: []const usize, l: []const u8, m: []const u8, r: []const u8) !void {+ var buf = std.array_list.Managed(u8).init(a);+ try buf.appendSlice(l);+ for (widths, 0..) |w, i| {+ for (0..w + 2) |_| try buf.appendSlice("─");+ try buf.appendSlice(if (i + 1 == widths.len) r else m);+ }+ try out.appendSlice(try (zz.Style{}).fg(.brightBlack).render(a, buf.items));+ }++ /// Narrow-table fallback: one record per data row — bold `Header: value`+ /// lines with wrapped continuations indented, a brightBlack rule between+ /// records. Used when the box form cannot fit `budget` columns.+ fn renderRecords(out: *std.array_list.Managed(u8), a: std.mem.Allocator, rows: []const []const []const u8, budget: usize) !void {+ const header = rows[0];+ var rule_buf = std.array_list.Managed(u8).init(a);+ const rule_w = @max(@as(usize, 16), @min(budget, 40));+ for (0..rule_w) |_| try rule_buf.appendSlice("─");+ var first_line = true;+ for (rows[1..], 0..) |cells, ri| {+ if (ri > 0) {+ try out.append('\n');+ try out.appendSlice(try (zz.Style{}).fg(.brightBlack).render(a, rule_buf.items));+ }+ for (header, 0..) |label, i| {+ const value = if (i < cells.len) cells[i] else "";+ const lw = dispWidth(label);+ const segs = try wrapCell(a, value, @max(@as(usize, 16), budget -| (lw + 2)));+ if (!first_line) try out.append('\n');+ first_line = false;+ try out.appendSlice(try (zz.Style{}).bold(true).render(a, label));+ try out.appendSlice(": ");+ if (segs.len > 0) try out.appendSlice(segs[0]);+ if (segs.len > 1) for (segs[1..]) |seg| {+ try out.append('\n');+ try out.appendSlice(" ");+ try out.appendSlice(seg);+ };+ }+ }+ }+++ /// Render `| a | b |` source rows (row 1 = alignment separator) as a+ /// box-drawing table: bold header, ├─┼─┤ rules between rows, cells+ /// word-wrapped so the whole table fits `width_hint` columns.+ fn renderTable(out: *std.array_list.Managed(u8), a: std.mem.Allocator, raw_rows: []const []const u8, width_hint: usize) !void {+ var rows = std.array_list.Managed([]const []const u8).init(a);+ for (raw_rows, 0..) |raw, ri| {+ if (ri == 1) continue; // alignment separator row+ var body = std.mem.trim(u8, raw, " \t");+ if (body.len > 0 and body[0] == '|') body = body[1..];+ if (body.len > 0 and body[body.len - 1] == '|') body = body[0 .. body.len - 1];+ var cells = std.array_list.Managed([]const u8).init(a);- var cit = std.mem.splitScalar(u8, body, '|');- while (cit.next()) |c| try cells.append(try plainInline(a, std.mem.trim(u8, c, " \t")));++ var cell = std.array_list.Managed(u8).init(a);++ var bi: usize = 0;++ while (bi < body.len) : (bi += 1) {++ if (body[bi] == '\\' and bi + 1 < body.len and body[bi + 1] == '|') {++ try cell.append('|'); // escaped \| is a literal pipe, not a column delimiter++ bi += 1;++ } else if (body[bi] == '|') {++ try cells.append(try plainInline(a, std.mem.trim(u8, cell.items, " \t")));++ cell = std.array_list.Managed(u8).init(a);++ } else {++ try cell.append(body[bi]);++ }++ }++ try cells.append(try plainInline(a, std.mem.trim(u8, cell.items, " \t")));+ try rows.append(cells.items);+ }+ if (rows.items.len == 0 or rows.items[0].len == 0) return;+ const ncols = rows.items[0].len;++ const widths = try a.alloc(usize, ncols);+ @memset(widths, 1);+ for (rows.items) |cells| {+ for (cells, 0..) |c, i| {+ if (i < ncols) widths[i] = @max(widths[i], dispWidth(c));+ }+ }+ const budget = (if (width_hint == 0) @as(usize, 100) else @max(width_hint, 40)) -| 8;+ const overhead = ncols * 3 + 1;+ while (true) {+ var total: usize = overhead;+ for (widths) |w| total += w;+ if (total <= budget) break;+ var wi: usize = 0;+ var wmax: usize = 0;+ for (widths, 0..) |w, i| {+ if (w > wmax) {+ wmax = w;+ wi = i;+ }+ }+ if (wmax <= 8) break; // column floor reached — record fallback below+ widths[wi] = wmax - 1;+ }++ var total: usize = overhead;+ for (widths) |w| total += w;+ if (total > budget and rows.items.len >= 2) {+ // Even at the column floor the box form overflows the pane — fall back+ // to one record per row, mirroring the harness's narrow rendering.+ try renderRecords(out, a, rows.items, budget);+ return;+ }++ try tableRule(out, a, widths, "┌", "┬", "┐");+ for (rows.items, 0..) |cells, ri| {+ const wrapped = try a.alloc([]const []const u8, ncols);+ var height: usize = 1;+ for (0..ncols) |i| {+ wrapped[i] = try wrapCell(a, if (i < cells.len) cells[i] else "", widths[i]);+ height = @max(height, wrapped[i].len);+ }+ for (0..height) |li| {+ try out.append('\n');+ for (0..ncols) |i| {+ try out.appendSlice(try (zz.Style{}).fg(.brightBlack).render(a, "│"));+ try out.append(' ');+ const seg = if (li < wrapped[i].len) wrapped[i][li] else "";+ if (seg.len > 0) {+ if (ri == 0) {+ try out.appendSlice(try (zz.Style{}).bold(true).render(a, seg));+ } else {+ try out.appendSlice(seg);+ }+ }+ var p = dispWidth(seg);+ while (p < widths[i]) : (p += 1) try out.append(' ');+ try out.append(' ');+ }+ try out.appendSlice(try (zz.Style{}).fg(.brightBlack).render(a, "│"));+ }+ try out.append('\n');+ if (ri + 1 == rows.items.len) {+ try tableRule(out, a, widths, "└", "┴", "┘");+ } else {+ try tableRule(out, a, widths, "├", "┼", "┤");+ }+ }+ }+-fn renderInline(out: *std.array_list.Managed(u8), a: std.mem.Allocator, line: []const u8) !void {- var i: usize = 0;- while (i < line.len) {- const c = line[i];- if (c == '`') {- if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {- try out.appendSlice(try (zz.Style{}).fg(.cyan).render(a, line[i + 1 .. end]));- i = end + 1;- continue;- }- } else if (c == '*' and i + 1 < line.len and line[i + 1] == '*') {- if (std.mem.indexOfPos(u8, line, i + 2, "**")) |end| {- try out.appendSlice(try (zz.Style{}).bold(true).render(a, line[i + 2 .. end]));- i = end + 2;- continue;- }- }- try out.append(c);- i += 1;- }-}-fn eqlAny(s: []const u8, options: []const []const u8) bool {- for (options) |o| if (std.mem.eql(u8, s, o)) return true;- return false;-}--/// Strip ANSI/control sequences (and CR) so the agent's live streamed output-/// can be shown as plain text — cursor moves/redraws can't corrupt the pane.-/// Result owned by `a`.-fn stripControl(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) {- const c = s[i];- if (c == 0x1b) {- i += 1;- if (i < s.len and s[i] == '[') {- i += 1;- while (i < s.len and !std.ascii.isAlphabetic(s[i])) i += 1;- if (i < s.len) i += 1;- } else if (i < s.len and s[i] == ']') {- i += 1;- while (i < s.len and s[i] != 0x07 and s[i] != 0x1b) i += 1;- if (i < s.len) i += 1;- } else if (i < s.len) {- i += 1;- }- } else if (c == '\r') {- i += 1;- } else {- out.append(c) catch {};- i += 1;- }- }- return out.items;-}--/// Compact live-activity preview: the last `n` non-empty lines of `plain`, each-/// width-truncated (UTF-8 safe) and dimmed, indented. Keeps the agent's tool-/// chatter from flooding the pane while still showing live progress.-fn tailPreview(a: std.mem.Allocator, plain: []const u8, width: usize, n: usize) ![]const u8 {- var lines = std.array_list.Managed([]const u8).init(a);- var it = std.mem.splitScalar(u8, plain, '\n');- while (it.next()) |ln| {- const t = std.mem.trim(u8, ln, " \t");- if (t.len > 0) try lines.append(t);- }- const start = if (lines.items.len > n) lines.items.len - n else 0;- const cap = if (width > 6) width - 4 else 12;- var out = std.array_list.Managed(u8).init(a);- for (lines.items[start..]) |ln| {- var tw = @min(ln.len, cap);- while (tw > 0 and tw < ln.len and (ln[tw] & 0xC0) == 0x80) tw -= 1; // don't cut mid-UTF-8- try out.appendSlice(" ");- try out.appendSlice(try (zz.Style{}).dim(true).render(a, ln[0..tw]));- try out.append('\n');- }- return out.items;-}--fn parseToggle(arg: []const u8, current: bool) bool {- if (std.mem.eql(u8, arg, "on")) return true;- if (std.mem.eql(u8, arg, "off")) return false;- return !current; // bare toggle-}--fn onOff(v: bool) []const u8 {- return if (v) "on" else "off";-}--/// Run the REPL. Pass a `turn_fn` (+ opaque ctx + model name) to chat with a-/// model; pass null/null/"" for the offline arithmetic engine.-pub fn run(- gpa: std.mem.Allocator,- io: std.Io,- environ_map: *const std.process.Environ.Map,- turn_ctx: ?*anyopaque,- turn_fn: ?TurnFn,- model_fn: ?ModelFn,- cancel_fn: ?CancelFn,- model_name: []const u8,- models: []const u8,-) !void {- g_turn_ctx = turn_ctx;- g_turn_fn = turn_fn;- g_model_fn = model_fn;- g_cancel_fn = cancel_fn;- g_model_name = model_name;- g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;- g_models = models;- var program = zz.Program(Model).initWithOptions(gpa, io, environ_map, .{ .mouse = true });- defer program.deinit();- try program.run();-}--/// Headless, scriptable twin of run(): drives the SAME Model + turn_fn as the-/// live TUI, but reads input lines from `in` and prints each turn's new output to-/// `out` instead of taking over the terminal. Lets-/// printf '/goal X\n<prompt>\n' | graff repl-/// exercise the exact repl path (goal steering, todo_write, cross-turn continuity)-/// from a script / CI / test — a 1:1 map of the interactive behavior. main() routes-/// here automatically when stdin is not a TTY. GRAFF_REPL_DEBUG=1 additionally dumps-/// each turn's raw agent stream to stderr (where mid-turn renders like the-/// todo_write checklist appear).-pub fn runScripted(- gpa: std.mem.Allocator,- io: std.Io,- environ_map: *const std.process.Environ.Map,- in: *std.Io.Reader,- out: *std.Io.Writer,- turn_ctx: ?*anyopaque,- turn_fn: ?TurnFn,- model_fn: ?ModelFn,- cancel_fn: ?CancelFn,- model_name: []const u8,- models: []const u8,-) !void {- g_turn_ctx = turn_ctx;- g_turn_fn = turn_fn;- g_model_fn = model_fn;- g_cancel_fn = cancel_fn;- g_model_name = model_name;- g_debug = environ_map.get("GRAFF_REPL_DEBUG") != null;- g_models = models;-- var m: Model = undefined;- m.setup(gpa);- defer m.deinit();-- while (true) {- const raw = (in.takeDelimiter('\n') catch null) orelse break; // EOF ends the script- const line = std.mem.trim(u8, raw, " \t\r\n");- if (line.len == 0) continue;-- try out.print("\n> {s}\n", .{line});- try out.flush();-- const before = m.history.items.len;- const eff = m.applyLine(line);-- // A chat line spawns a background turn; a slash command runs inline.- if (m.pending != null) {- while (m.pending) |job| {- if (job.done.load(.acquire)) {- m.finishJob();- break;- }- io.sleep(.fromMilliseconds(20), .awake) catch {};- }- }-- // Print what the line produced — slash-command info, the assistant reply,- // or an error. The user line is already echoed above; the pending- // placeholder is gone once finishJob ran.- var i = before;- while (i < m.history.items.len) : (i += 1) {- switch (m.history.items[i].kind) {- .pending, .input, .welcome => {},- else => try out.print("{s}\n", .{m.history.items[i].text}),- }- }- try out.flush();-- if (eff == .quit) break;- }-- const pane = try m.render(gpa, 100, 60, 0);- defer gpa.free(pane);- try out.print("\n===== final repl pane =====\n{s}\n===========================\n", .{pane});- try out.flush();-}--pub fn main(init: std.process.Init) !void {- return run(init.gpa, init.io, init.environ_map, null, null, null, null, "", "");-}+// run/runScripted (the live TUI loop + the headless/scriptable twin) and+// main() (the standalone `graff-repl` exe's entry point) live in+// repl_run.zig.+pub const run = repl_run.run;+pub const runScripted = repl_run.runScripted;+pub const main = repl_run.main;// ---------------------------------------------------------------------------// Tests — headless. Chat path uses a stubbed turn_fn (no network); it still@@@ -594,3 -1515,55 +847,68 @@@ test "model: empty Enter force-interrupwhile (m.pending != null and !m.pending.?.done.load(.acquire)) {}if (m.pending != null) m.finishJob();}++ test "renderMarkdown: pipe table renders as box-drawing" {+ const gpa = std.testing.allocator;+ const md = "before\n| Impact | Site |\n|---|---|\n| high | `repl.zig:700` |\n| medium | **main.zig** |\nafter";+ const out = try renderMarkdown(gpa, md, 80);+ defer gpa.free(out);+ try std.testing.expect(std.mem.indexOf(u8, out, "┌") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "┼") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "└") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "repl.zig:700") != null); // backticks stripped in cells+ try std.testing.expect(std.mem.indexOf(u8, out, "|---") == null); // separator row consumed+ try std.testing.expect(std.mem.indexOf(u8, out, "before") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "after") != null);+ }++ test "renderMarkdown: table cells wrap to the width budget" {+ const gpa = std.testing.allocator;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const md = "| K | V |\n|---|---|\n| x | this is a very long cell that must wrap across multiple lines to stay inside a narrow table |";+ const out = try renderMarkdown(gpa, md, 48);+ defer gpa.free(out);- const plain = stripControl(a, out);++ const plain = util.stripControl(a, out);+ var it = std.mem.splitScalar(u8, plain, '\n');+ var cell_rows: usize = 0;+ while (it.next()) |line| {+ try std.testing.expect(dispWidth(line) <= 48);+ if (std.mem.indexOf(u8, line, "│") != null) cell_rows += 1;+ }+ try std.testing.expect(cell_rows >= 3); // long cell spans several visual lines+ }++ test "renderMarkdown: lone pipe line is not a table" {+ const gpa = std.testing.allocator;+ const out = try renderMarkdown(gpa, "| just text with pipes |\nno separator", 80);+ defer gpa.free(out);+ try std.testing.expect(std.mem.indexOf(u8, out, "┌") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "| just text with pipes |") != null);+ }++ test "renderMarkdown: too-wide table falls back to record layout" {+ const gpa = std.testing.allocator;+ const md = "| Impact | Site | Finding | Fix safe? |\n|---|---|---|---|\n| high | repl.zig:700 | full scrollback re-styled and re-allocated every single frame | needs care |\n| medium | main.zig:14048 | never-reset session arena grows RSS forever | no |";+ const out = try renderMarkdown(gpa, md, 44);+ defer gpa.free(out);+ try std.testing.expect(std.mem.indexOf(u8, out, "┌") == null); // box form abandoned+ try std.testing.expect(std.mem.indexOf(u8, out, "Impact") != null); // labels repeated per record+ try std.testing.expect(std.mem.indexOf(u8, out, "────") != null); // rule between records+ try std.testing.expect(std.mem.indexOf(u8, out, "repl.zig:700") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "main.zig:14048") != null);+ }++++test "renderMarkdown: escaped pipe stays inside a table cell" {++ const gpa = std.testing.allocator;++ var arena_state = std.heap.ArenaAllocator.init(gpa);++ defer arena_state.deinit();++ const a = arena_state.allocator();++ const md = "| head |\n|---|\n| a \\| b |";++ const out = try renderMarkdown(gpa, md, 100);++ defer gpa.free(out);++ const plain = util.stripControl(a, out); // arena-owned; freed with arena_state++ // the escaped \\| renders as a literal pipe inside the single cell.++ try std.testing.expect(std.mem.indexOf(u8, plain, "a | b") != null);++}diff --cc src/repl_model_render.zigindex 4bfc83ed,00000000..da97e173mode 100644,000000..100644--- a/src/repl_model_render.zig+++ b/src/repl_model_render.zig@@@ -1,183 -1,0 +1,184 @@@+//! `graff repl` Model — pane rendering: spinner frame selection, the status+//! line, the full frame draw (conversation history + input box, clamped to+//! the terminal size), and mouse drag-selection copy. Split out of the+//! Model struct in repl.zig (#123, 600-line goal); reached through+//! repl.zig's member aliases, so both `self.render(...)` and+//! `Model.render(...)` resolve here unchanged.++const std = @import("std");+const zz = @import("zigzag");++const repl = @import("repl.zig");+const Model = repl.Model;++const util = @import("repl_util.zig");+const stripControl = util.stripControl;+const tailPreview = util.tailPreview;++pub fn spinnerFrame(self: *const Model, now_ms: u64) []const u8 {+ return switch (self.anim) {+ .braille => repl.braille_frames[(now_ms / 80) % repl.braille_frames.len],+ .dragon => repl.dragon_frames[(now_ms / 220) % repl.dragon_frames.len],+ };+}++pub fn statusLine(self: *const Model, a: std.mem.Allocator) ![]const u8 {+ var b = std.array_list.Managed(u8).init(a);+ if (self.scroll > 0) try b.appendSlice("↑ scrolled · PgDn to bottom · ");+ if (self.chat and repl.g_model_name.len > 0) try b.appendSlice(repl.g_model_name) else try b.appendSlice("offline · arithmetic");+ try b.appendSlice(try std.fmt.allocPrint(a, " · effort:{s}", .{@tagName(self.effort)}));+ if (self.fast) try b.appendSlice(" · ⚡fast");+ if (self.ultracode) try b.appendSlice(" · ✦ultracode");+ if (self.plan) try b.appendSlice(" · plan");+ if (self.yolo) try b.appendSlice(" · yolo");+ if (self.strict) try b.appendSlice(" · strict");+ if (self.thinking_show) try b.appendSlice(" · thinking");+ if (!self.keepcontext) try b.appendSlice(" · no-ctx");+ if (self.goal != null) try b.appendSlice(" · 🎯goal");+ if (self.turns > 0) try b.appendSlice(try std.fmt.allocPrint(a, " · {d}t", .{self.turns}));+ try b.appendSlice(" · /help");+ return b.items;+}++/// Render at `term_width` x `term_height`; `now_ms` drives animations. Input+/// box is pinned to the bottom; conversation fills from the top.+pub fn render(self: *Model, gpa: std.mem.Allocator, term_width: usize, term_height: usize, now_ms: u64) ![]const u8 {++ self.last_term_width = term_width;+ var arena_state = std.heap.ArenaAllocator.init(gpa);+ defer arena_state.deinit();+ const a = arena_state.allocator();++ const inner: u16 = @intCast(@max(@as(usize, 8), term_width) - 4);+ const border_color = if (self.ultracode) repl.rainbow[(now_ms / 90) % repl.rainbow.len] else zz.Color.brightBlack;+ const box = (zz.Style{}).borderAll(zz.Border.rounded)+ .borderForeground(border_color).paddingLeft(1).paddingRight(1).width(inner);++ var top = std.array_list.Managed(u8).init(a);+ for (self.history.items) |e| {+ switch (e.kind) {+ .welcome => {+ const star = try (zz.Style{}).fg(repl.accent).bold(true).render(a, "✻");+ const sub = if (self.chat) "Chat with the model — ask anything." else "i64 arithmetic — + - * / %, parens, unary minus.";+ const body = try std.fmt.allocPrint(a, "{s} Welcome to graff repl\n\n {s}\n /help for commands · ctrl-c to quit", .{ star, sub });+ try top.appendSlice(try box.render(a, body));+ try top.append('\n');+ },+ .input => {+ const g = try (zz.Style{}).fg(.brightBlack).render(a, ">");+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));+ },+ .result => {+ const g = try (zz.Style{}).fg(.green).bold(true).render(a, "⏺");+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));+ },+ .assistant => {+ const g = try (zz.Style{}).fg(repl.accent).bold(true).render(a, "⏺");+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, e.text }));+ },+ .pending => {+ const g = try (zz.Style{}).fg(repl.accent).bold(true).render(a, self.spinnerFrame(now_ms));+ const live = if (self.pending) |job| job.stream.snapshot(a) else null;+ if (live) |s| {+ // Compact live activity: the last few lines of the+ // agent's output, control-stripped + width-truncated,+ // so tool chatter can't flood the pane.+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} working…\n", .{g}));+ try top.appendSlice(try tailPreview(a, stripControl(a, s), term_width, 3));+ } else {+ const t = try (zz.Style{}).dim(true).render(a, "thinking…");+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, t }));+ }+ if (self.steer_queue.items.len > 0) {+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, try std.fmt.allocPrint(a, " ↳ {d} steer queued · empty Enter runs now\n", .{self.steer_queue.items.len})));+ } else {+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, " ↳ type to steer · Enter queues\n"));+ }+ },+ .err => {+ const g = try (zz.Style{}).fg(.red).bold(true).render(a, "⏺");+ const m = try (zz.Style{}).fg(.red).render(a, e.text);+ try top.appendSlice(try std.fmt.allocPrint(a, "{s} {s}\n", .{ g, m }));+ },+ .info => {+ try top.appendSlice(try (zz.Style{}).dim(true).render(a, e.text));+ try top.append('\n');+ },+ }+ }++ var bottom = std.array_list.Managed(u8).init(a);+ try bottom.appendSlice(try box.render(a, try self.input.view(a)));+ try bottom.append('\n');+ try bottom.appendSlice(try (zz.Style{}).dim(true).render(a, try self.statusLine(a)));++ // The conversation is a scrollable viewport above the pinned input box.+ // scroll = lines scrolled up from the bottom (0 = latest). Clamped here.+ const bottom_lines = std.mem.count(u8, bottom.items, "\n") + 1;+ const view_h = if (term_height > bottom_lines) term_height - bottom_lines else 1;++ var lines = std.array_list.Managed([]const u8).init(a);+ var it = std.mem.splitScalar(u8, top.items, '\n');+ while (it.next()) |ln| try lines.append(ln);+ if (lines.items.len > 0 and lines.items[lines.items.len - 1].len == 0) _ = lines.pop();+ const n = lines.items.len;++ var out = std.array_list.Managed(u8).init(a);+ // Reset the per-frame visible-row snapshot (Model-owned plaintext, so a+ // mouse row can be mapped back to conversation text for copy — #91).+ for (self.visible_text.items) |l| self.alloc.free(l);+ self.visible_text.clearRetainingCapacity();+ self.view_start = 0;+ self.view_rows = 0;+ if (n <= view_h) {+ self.scroll = 0;+ try out.appendSlice(top.items);+ for (0..(view_h - n)) |_| try out.append('\n');+ self.view_rows = n;+ for (lines.items[0..n]) |ln| {+ self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};+ }+ } else {+ const max_scroll = n - view_h;+ if (self.scroll > max_scroll) self.scroll = max_scroll;+ const start = max_scroll - self.scroll;+ self.view_start = start;+ self.view_rows = view_h;+ for (lines.items[start .. start + view_h]) |ln| {+ try out.appendSlice(ln);+ try out.append('\n');+ self.visible_text.append(self.alloc.dupe(u8, stripControl(a, ln)) catch continue) catch {};+ }+ }+ try out.appendSlice(bottom.items);+ if (self.dump_next) {+ std.debug.print("\n[repl-debug] ===== rendered frame ({d}x{d}) =====\n{s}\n[repl-debug] ===== end frame =====\n", .{ term_width, term_height, out.items });+ self.dump_next = false;+ }+ return gpa.dupe(u8, out.items);+}++/// Copy the conversation lines spanned by a drag-selection (screen rows+/// r0..r1 inclusive, 0-based) to the clipboard via OSC52. Line-granular —+/// restores copy after mouse mode disabled native terminal selection (#91).+pub fn copySelection(self: *Model, ctx: *zz.Context, r0: usize, r1: usize) void {+ if (self.view_rows == 0 or self.visible_text.items.len == 0) return;+ const lo = @min(r0, r1);+ var hi = @max(r0, r1);+ if (lo >= self.view_rows) return; // selection started below the conversation+ if (hi >= self.view_rows) hi = self.view_rows - 1;+ if (hi >= self.visible_text.items.len) hi = self.visible_text.items.len - 1;++ var buf = std.array_list.Managed(u8).init(self.alloc);+ defer buf.deinit();+ var r = lo;+ while (r <= hi) : (r += 1) {+ const ln = std.mem.trimEnd(u8, self.visible_text.items[r], " \t");+ buf.appendSlice(ln) catch return;+ if (r != hi) buf.append('\n') catch return;+ }+ const text = std.mem.trim(u8, buf.items, " \t\r\n");+ if (text.len == 0) return;+ _ = ctx.setClipboard(text) catch false;+ // render() is hash-gated and may skip its flush; push the OSC52 out now.+ if (ctx._terminal) |term| term.flush() catch {};+}diff --cc src/repl_model_turn.zigindex 4e19fa3a,00000000..d534cc57mode 100644,000000..100644--- a/src/repl_model_turn.zig+++ b/src/repl_model_turn.zig@@@ -1,133 -1,0 +1,133 @@@+//! `graff repl` Model — background chat-turn lifecycle: spawn the model call+//! on a worker thread, collect its result, and steering-queue plumbing+//! (queue a line while a turn streams, drain it as the next turn, or+//! force-interrupt with an empty Enter). Split out of the Model struct in+//! repl.zig (#123, 600-line goal); reached through repl.zig's member+//! aliases, so both `self.startJob()` and `Model.startJob(...)` resolve+//! here unchanged.++const std = @import("std");++const repl = @import("repl.zig");+const Model = repl.Model;+const Job = repl.Job;+const jobRun = repl.jobRun;+const Turn = repl.Turn;+const Effect = repl.Effect;+const renderMarkdown = repl.renderMarkdown;++/// Snapshot the conversation, push the `thinking…` placeholder, and spawn+/// the model call on a background thread (so the spinner can animate).+pub fn startJob(self: *Model) void {+ var turns = std.array_list.Managed(Turn).init(self.alloc);+ for (self.history.items) |e| {+ const role: ?Turn.Role = switch (e.kind) {+ .input => .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(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(.{}, jobRun, .{job})) |th| {+ job.thread = th;+ } else |_| {+ job.threaded = false;+ jobRun(job); // no threads → run synchronously (spinner just won't animate)+ }+}++/// Collect a finished job: drop the placeholder, append the reply, free.+pub fn finishJob(self: *Model) void {+ const job = self.pending orelse return;+ if (!job.done.load(.acquire)) return;+ if (job.threaded) job.thread.join();+ if (repl.g_debug) {+ if (job.stream.snapshot(self.alloc)) |raw| {+ std.debug.print("\n[repl-debug] raw agent stream ({d} bytes):\n{s}\n", .{ raw.len, raw });+ self.alloc.free(raw);+ }+ std.debug.print("[repl-debug] final reply:\n{s}\n[repl-debug] ----- end turn -----\n", .{job.result orelse "(model call failed)"});+ }++ 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);+ }+ if (job.result) |r| {+ self.chars_out += r.len;- if (renderMarkdown(self.alloc, r)) |rendered| {++ if (renderMarkdown(self.alloc, r, self.last_term_width)) |rendered| {+ self.alloc.free(r);+ self.pushOwned(.assistant, rendered) catch self.alloc.free(rendered);+ } else |_| {+ self.pushOwned(.assistant, r) catch self.alloc.free(r);+ }+ } else if (self.cancel_requested) {+ // Force-steer interrupted this turn (runTurn → error.Interrupted →+ // replTurnCb returns null); not an error.+ self.push(.info, "⏹ 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; // reply landed → jump to the latest+}++/// Pop the next queued steer line (FIFO) and run it as the next turn.+/// Returns the applyLine Effect so a steered "/quit" still propagates.+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 self.applyLine(text);+}++/// Handle Enter while a turn streams. A typed line is queued as a steer+/// (runs as a follow-up turn after the current one finishes); an empty line+/// with a non-empty queue FORCES — flags the turn for interrupt and signals+/// the harness via the cancel callback so the queue drains immediately.+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(.info, "↳ steer › queued ({d} waiting)", .{self.steer_queue.items.len}) catch {};+ } else |_| {}+ } else if (self.steer_queue.items.len > 0) {+ self.cancel_requested = true;+ if (repl.g_cancel_fn) |f| f(repl.g_turn_ctx);+ self.push(.info, "↳ force › interrupting…") catch {};+ }+}