graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Merge wip/v0.0.262-batch: Lean conformance corpus + TUI hardening
Rach Pradhan69cdd9f7cd3f
diff --cc TUI/key.zigindex a36023fb,fdeb381b..b8e32277--- a/TUI/key.zig+++ b/TUI/key.zig@@@ -190,8 -119,12 +190,13 @@@ fn escapeSeq(bytes: []const u8, i: *usi/// OSC/DCS/APC/PM/SOS reply on stdin (e.g. a color query answer) — consume/// through BEL or ST so the payload is never typed into the prompt.+ /// Longest stdin reply we ever solicit (OSC 10/11 color answers are ~25+ /// bytes; kitty acks are shorter). Anything bigger behind an unterminated+ /// introducer is typed text, not a reply (#516).+ const max_reply_pending = 128;+fn stringSeq(bytes: []const u8, i: *usize) ?Key {+ const start = i.*; // bytes[start] is ']' for OSCvar j = i.* + 1;while (j < bytes.len) : (j += 1) {if (bytes[j] == 0x07) {diff --cc TUI/key_tests.zigindex 82aacc7f,00000000..27b486b1mode 100644,000000..100644--- a/TUI/key_tests.zig+++ b/TUI/key_tests.zig@@@ -1,382 -1,0 +1,402 @@@+//! key.zig's test battery, parked here under the 600-line ceiling.++const std = @import("std");+const key = @import("key.zig");+const Key = key.Key;+const next = key.next;++test "next: letters, enter, ctrl-c, arrows, kitty ctrl-p" {+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .char = 'a' }, next("a", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.enter, next("\r", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .ctrl = 'c' }, next("\x03", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.up, next("\x1b[A", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.shift_tab, next("\x1b[Z", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .ctrl = 'p' }, next("\x1b[112;5u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '/' }, next("/", &i).?);+ i = 0;+ const click = next("\x1b[<0;12;8M", &i).?;+ try std.testing.expect(click == .mouse);+ try std.testing.expectEqual(@as(u8, 0), click.mouse.btn);+ try std.testing.expectEqual(@as(u16, 12), click.mouse.x);+ try std.testing.expectEqual(@as(u16, 8), click.mouse.y);+ try std.testing.expect(click.mouse.down);+ i = 0;+ try std.testing.expectEqual(Key.paste_start, next("\x1b[200~", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.paste_end, next("\x1b[201~", &i).?);+ i = 0;+ try std.testing.expect(next("\x1b[20", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 0xc3 }, next("\xc3\xa9", &i).?);+ try std.testing.expectEqual(Key{ .char = 0xa9 }, next("\xc3\xa9", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.delete_to_start, next("\x1b[127;9u", &i).?);+ key.held = 0;+ i = 0;+ try std.testing.expectEqual(Key.delete_word, next("\x1b\x7f", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.prev_turn, next("\x1b[1;2D", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.next_turn, next("\x1b[1;2C", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.word_left, next("\x1b[1;3D", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.home, next("\x1b[1;9D", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.shift_enter, next("\x1b[13;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.shift_enter, next("\x1b\r", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.delete_to_start, next("\x1b[27;9;127~", &i).?);+ i = 0;+ key.held = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57444;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.delete_to_start, next("\x7f", &i).?);+ key.held = 0;+}++test "lone trailing ESC stays pending, not an instant Escape" {+ var i: usize = 0;+ try std.testing.expect(next("\x1b", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+}++test "ESC ESC delivers an Escape and leaves the second pending" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.escape, next("\x1b\x1b", &i).?);+ try std.testing.expectEqual(@as(usize, 1), i);+ try std.testing.expect(next("\x1b\x1b", &i) == null);+ try std.testing.expectEqual(@as(usize, 1), i);+}++test "kitty release events never fire keys" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[1;1:3A", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[3;1:3~", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[5;1:3~", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[97;1:3u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.up, next("\x1b[1;1:2A", &i).?); // repeat acts+}++test "right-side modifiers follow the real kitty table, never Escape" {+ key.held = 0;+ var i: usize = 0;+ // Right-Shift (57447) and Right-Ctrl (57448) must not latch key.held bits.+ try std.testing.expectEqual(Key.ignore, next("\x1b[57447;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57448;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ // Right-Alt (57449) latches alt; its release clears it.+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:1u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.delete_word, next("\x7f", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57449;1:3u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ key.held = 0;+}++test "unknown keys and replies are inert, never Escape" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[57376u", &i).?); // F13+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[17~", &i).?); // F6+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[2~", &i).?); // Insert+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b[?1;2c", &i).?); // DA reply+}++test "kitty functional arrows and keypad map; a stale super latch resyncs" {+ key.held = 8; // pretend we missed the Super release+ var i: usize = 0;+ try std.testing.expectEqual(Key.up, next("\x1b[57352u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97;1u", &i).?);+ try std.testing.expectEqual(@as(u32, 0), key.held);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.enter, next("\x1b[57414u", &i).?); // KP_ENTER+ key.held = 0;+}++test "SS3 application keys and unbound alt-chords" {+ var i: usize = 0;+ try std.testing.expectEqual(Key.up, next("\x1bOA", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.f1, next("\x1bOP", &i).?);+ i = 0;+ // Split SS3 stays pending.+ try std.testing.expect(next("\x1bO", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+ i = 0;+ // Unbound Alt+p swallows both bytes — no phantom Escape, no stray 'p'.+ try std.testing.expectEqual(Key.ignore, next("\x1bp", &i).?);+ try std.testing.expectEqual(@as(usize, 2), i);+ try std.testing.expect(next("\x1bp", &i) == null);+}++test "X10 mouse fallback consumes its payload instead of typing it" {+ var i: usize = 0;+ const ev = next("\x1b[M\x20\x2c\x28", &i).?;+ try std.testing.expect(ev == .mouse);+ try std.testing.expectEqual(@as(u8, 0), ev.mouse.btn);+ try std.testing.expectEqual(@as(u16, 12), ev.mouse.x);+ try std.testing.expectEqual(@as(u16, 8), ev.mouse.y);+ try std.testing.expect(ev.mouse.down);+ try std.testing.expectEqual(@as(usize, 6), i);+ i = 0;+ // Split short — wait for the rest.+ try std.testing.expect(next("\x1b[M\x20", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+}++test "non-ASCII CSI-u codepoints type text instead of Escape" {+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .codepoint = 0xe9 }, next("\x1b[233;1u", &i).?);+ key.held = 0;+}++test "OSC and APC replies on stdin are consumed, never typed" {+ var i: usize = 0;+ // OSC 11 replies now carry the terminal background (auto light/dark).+ try std.testing.expectEqual(Key{ .bg_report = .{ 0x14, 0x14, 0x14 } }, next("\x1b]11;rgb:14/14/14\x07", &i).?);+ try std.testing.expectEqual(@as(usize, 18), i);+ i = 0;+ // 4-digit form takes the high byte; other OSC bodies stay inert.+ try std.testing.expectEqual(Key{ .bg_report = .{ 0xf6, 0xf6, 0xf6 } }, next("\x1b]11;rgb:f6f6/f6f6/f6f6\x1b\\", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b]10;rgb:14/14/14\x07", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.ignore, next("\x1b_Gi=1;OK\x1b\\", &i).?);+ try std.testing.expectEqual(@as(usize, 11), i);+ i = 0;+ // Unterminated reply stays pending until the rest arrives.+ try std.testing.expect(next("\x1b]11;rgb:14", &i) == null);+ try std.testing.expectEqual(@as(usize, 0), i);+}++test "orphan SGR mouse is never inserted as letters" {+ var i: usize = 0;+ const k = next("39;33;23M", &i).?;+ try std.testing.expect(k == .mouse);+ try std.testing.expectEqual(@as(u8, 39), k.mouse.btn);+ try std.testing.expectEqual(@as(u16, 33), k.mouse.x);+ try std.testing.expectEqual(@as(usize, 9), i);+ i = 0;+ const k2 = next("<64;4;8Mhi", &i).?;+ try std.testing.expect(k2 == .mouse);+ try std.testing.expectEqual(@as(u8, 64), k2.mouse.btn);+ try std.testing.expectEqual(Key{ .char = 'h' }, next("<64;4;8Mhi", &i).?);+}++test "SGR mouse flood does not leak digits" {+ const seq = "\x1b[<39;33;23M\x1b[<39;26;20M\x1b[<39;25;19M";+ var i: usize = 0;+ var n: usize = 0;+ while (next(seq, &i)) |k| {+ try std.testing.expect(k == .mouse);+ n += 1;+ }+ try std.testing.expectEqual(@as(usize, 3), n);+ try std.testing.expectEqual(seq.len, i);+}++test "orphan kitty CSI-u is ignore, never letters or Escape" {+ var i: usize = 0;+ const seq = "3u7444;9u7441;10u";+ // `3u` carries neither a `<` nor a `;`, so on its own it reads as somebody+ // typing. The loop arms us when it drops a truncated sequence — which is+ // the only way this tail can exist.+ key.orphan_armed = true;+ defer key.orphan_armed = false;+ var n: usize = 0;+ while (next(seq, &i)) |k| {+ try std.testing.expect(k == .ignore);+ n += 1;+ }+ try std.testing.expectEqual(@as(usize, 3), n);+ try std.testing.expectEqual(seq.len, i);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'h' }, next("hi", &i).?);+}++/// run.zig's read loop, minus the terminal: fixed input buffer, parse to+/// exhaustion, carry the unparsed tail into the next read. Regressions in the+/// carry/rewind contract only show up across a read boundary, so the debris+/// tests have to drive the real thing.+const Loop = struct {+ inbuf: [4096]u8 = undefined,+ pending: usize = 0,+ typed: std.array_list.Managed(u8),+ mice: usize = 0,++ fn init(a: std.mem.Allocator) Loop {+ key.resetInputState();+ return .{ .typed = std.array_list.Managed(u8).init(a) };+ }+ fn deinit(self: *Loop) void {+ self.typed.deinit();+ }++ fn read(self: *Loop, bytes: []const u8) !void {+ @memcpy(self.inbuf[self.pending .. self.pending + bytes.len], bytes);+ const n = self.pending + bytes.len;+ var i: usize = 0;+ while (next(self.inbuf[0..n], &i)) |k| switch (k) {+ .char => |c| try self.typed.append(c),+ .codepoint => try self.typed.append('?'),+ .mouse => self.mice += 1,+ .escape => try self.typed.append('E'), // a phantom Escape cancels the turn+ else => {},+ };+ self.pending = if (i < n) blk: {+ const rest = n - i;+ std.mem.copyForwards(u8, self.inbuf[0..rest], self.inbuf[i..n]);+ break :blk rest;+ } else 0;+ }+};++test "SGR motion flood chopped at every byte offset never types a character" {+ key.orphan_armed = false;+ // The exact bytes the user saw on the bottom row, plus one hover report.+ const flood = "\x1b[<39;7;32M\x1b[<39;4;32M\x1b[<39;3;33M\x1b[<39;1;33M\x1b[<35;80;24M";+ var cut: usize = 0;+ while (cut <= flood.len) : (cut += 1) {+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ try loop.read(flood[0..cut]);+ try loop.read(flood[cut..]);+ try std.testing.expectEqualStrings("", loop.typed.items);+ try std.testing.expectEqual(@as(usize, 5), loop.mice);+ try std.testing.expectEqual(@as(usize, 0), loop.pending);+ }+}++test "debris after a dropped ESC head is consumed, not typed — even split again" {+ // run.zig drops a pending head that never completed and arms us; the tail+ // arrives alone, and may itself straddle the next read boundary.+ const tail = "39;7;32M\x1b[<39;4;32M";+ var cut: usize = 0;+ while (cut <= tail.len) : (cut += 1) {+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ key.orphan_armed = true;+ defer key.orphan_armed = false;+ try loop.read(tail[0..cut]);+ try loop.read(tail[cut..]);+ try std.testing.expectEqualStrings("", loop.typed.items);+ try std.testing.expectEqual(@as(usize, 2), loop.mice);+ }+}++test "typed and pasted text survives the debris guard (0x1f, [12], 1e5)" {+ key.orphan_armed = false;+ const cases = [_][]const u8{+ "const x = 0x1f;",+ "v1e5 [12] 2xM",+ "1.5]",+ "0x1f",+ "[12]",+ "1e5",+ "grep -n '39;7;32M' log", // debris-shaped text, but not at a read head+ "step 3 of 10 (2m30s)",+ };+ for (cases) |text| {+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ try loop.read(text);+ try std.testing.expectEqualStrings(text, loop.typed.items);+ try std.testing.expectEqual(@as(usize, 0), loop.mice);+ }+ // Byte-at-a-time typing is the same string.+ var slow = Loop.init(std.testing.allocator);+ defer slow.deinit();+ for ("0x1f + [12] = 1e5") |c| try slow.read(&[_]u8{c});+ try std.testing.expectEqualStrings("0x1f + [12] = 1e5", slow.typed.items);+}++test "bracketed paste of debris-shaped code reaches the composer intact" {+ key.orphan_armed = false;+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ try loop.read("\x1b[200~");+ try loop.read("39;7;32M and 0x1f");+ try loop.read("\x1b[201~");+ try std.testing.expectEqualStrings("39;7;32M and 0x1f", loop.typed.items);+}++test "Shift+9 is open-paren, Shift+0 is close-paren" {+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = ')' }, next("\x1b[48;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57:40;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[57;2;40u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '!' }, next("\x1b[49;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'A' }, next("\x1b[97;2u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key{ .char = '(' }, next("\x1b[27;2;57~", &i).?);+}++test "a plain CSI-u keypress clears a stale super latch — Backspace stays Backspace" {+ // Cmd+Tab mid-composition: the super PRESS arrives, focus leaves, the+ // RELEASE goes to the other app. Typing resumes with plain CSI-u keys+ // (no mods field). Those must resync held to 0, or the next Backspace+ // reads as Cmd+Backspace = delete_to_start and wipes the composer.+ key.held = 8; // stale Super+ var i: usize = 0;+ try std.testing.expectEqual(Key{ .char = 'h' }, next("\x1b[104u", &i).?);+ try std.testing.expectEqual(@as(u32, 0), key.held);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ // Stale alt is the same class of bug (backspace -> delete_word).+ key.held = 2;+ i = 0;+ try std.testing.expectEqual(Key{ .char = 'a' }, next("\x1b[97u", &i).?);+ i = 0;+ try std.testing.expectEqual(Key.backspace, next("\x7f", &i).?);+ key.held = 0;+}++++test "typed text behind an Alt+] chord recovers instead of wedging (#516)" {++ // CR proves it is not a reply: the introducer is swallowed as a chord++ // and the sentence reparses as ordinary keys, Enter included.++ var i: usize = 0;++ const bytes = "\x1b]fix it\r";++ try std.testing.expectEqual(Key.ignore, next(bytes, &i).?);++ try std.testing.expectEqual(Key{ .char = 'f' }, next(bytes, &i).?);++ var last: Key = .ignore;++ while (next(bytes, &i)) |k| last = k;++ try std.testing.expectEqual(Key.enter, last);++ // Longer than any real reply — recover even without CR/LF.++ var big: [140]u8 = undefined;++ big[0] = 0x1b;++ big[1] = 'P';++ @memset(big[2..], 'a');++ i = 0;++ try std.testing.expectEqual(Key.ignore, next(&big, &i).?);++ try std.testing.expectEqual(Key{ .char = 'a' }, next(&big, &i).?);++}diff --cc TUI/keys.zigindex ac19cc62,3b6e57e0..f8fc2e03--- a/TUI/keys.zig+++ b/TUI/keys.zig@@@ -230,18 -212,13 +221,16 @@@ fn mouseKey(self: *Model, ev: key_mod.Mreturn .stay;}if (y < self.mid_origin) return .stay;+ // Sticky-header chrome occludes the top content rows — a click there must+ // not toggle whatever is hidden underneath it.+ if (y < self.mid_origin + self.sticky_rows) return .stay;const vis = y - self.mid_origin + self.mid_skip;- // No fallback on a miss: clicking blank space below the transcript used to- // silently expand the LAST tool run (audit: easiest bug to hit).- const idx = scrollback.indexAtVisual(self, vis, self.last_term_width);self.focus = .scrollback;- if (idx) |i| {- self.selected = i;- if (self.history.items[i].kind == .tool) self.toggleToolGroup(i);- }+ // A click on blank padding maps to no entry — it must not select or+ // toggle anything (#519).+ const i = scrollback.indexAtVisual(self, vis, self.last_term_width) orelse return .stay;+ self.selected = i;+ if (self.history.items[i].kind == .tool) self.toggleToolGroup(i);return .stay;}diff --cc TUI/run.zigindex 46a2736b,83e2741f..352b7da0--- a/TUI/run.zig+++ b/TUI/run.zig@@@ -138,28 -121,30 +140,35 @@@ pub fn runif (!tty.poll(wait)) {if (pending_len > 0) {esc_stall += 1;- if (esc_stall >= 2) {- switch (stalledPending(inbuf[0..pending_len])) {- .escape_key => if (keys.handle(&m, .escape) == .quit) {- m.running = false;- },- // A sequence the terminal never finished. Delivering- // Escape here cancelled the running turn on a- // half-arrived mouse report; dropping it silently- // leaves its tail to arrive alone on the next read, so+ switch (stallVerdict(inbuf[0..pending_len], esc_stall)) {+ .wait => {},+ .escape_key => {+ if (keys.handle(&m, .escape) == .quit) m.running = false;+ pending_len = 0;+ esc_stall = 0;+ },+ .drop => {++ // A sequence the terminal never finished, waited out.++ // Its tail may still arrive alone on a later read —+ // tell key.zig to expect orphan debris there.- .truncated_sequence => key_mod.orphan_armed = true,- .discard => {},- }- pending_len = 0;- esc_stall = 0;++ key_mod.orphan_armed = true;+ pending_len = 0;+ esc_stall = 0;+ },}}continue;}esc_stall = 0;+ if (pending_len == inbuf.len) {+ // A stuck head has filled the whole buffer: that is a parser+ // wedge, not a dead tty. Drop it rather than letting the+ // zero-length read below masquerade as a hangup and kill the+ // TUI mid-session (#517).+ pending_len = 0;+ }const got = tty.readStdin(inbuf[pending_len..]);+ if (got > 0) traj.note(io, m.now_ms, inbuf[pending_len .. pending_len + got]);if (got == 0) {// poll says readable but read gives nothing: hangup or transient// error. Three in a row means the TTY is gone.@@@ -192,25 -177,20 +201,25 @@@pending_len = rest;} else pending_len = 0;}+ if (prev.len != 0) {+ const vis = @import("dump.zig").visible(gpa, prev) catch prev;+ defer if (vis.ptr != prev.ptr) gpa.free(vis);+ traj.snap(io, m.now_ms, vis);+ }}- /// What to do with bytes still pending after the input stalled (#94). A LONE- /// ESC that nothing followed is the Escape KEY. Anything longer is a real- /// escape sequence the terminal never finished — a half-arrived SGR mouse- /// report under 1003 hover tracking is the common one, and reading it as- /// Escape cancelled the user's running turn while its tail leaked into the- /// composer as `39;7;32M`-shaped text on the next read.- pub const StallAction = enum { escape_key, truncated_sequence, discard };+ /// What to do with input bytes stuck mid-sequence after quiet polls (~25ms+ /// each). Exactly one pending ESC byte is the Escape key after the #94 grace.+ /// A longer prefix is a truncated CSI/OSC split by link latency (ssh/tmux):+ /// delivering Escape cancelled live turns and typing the late tail sprayed+ /// "2;39M"-style debris into the transcript — wait for the tail instead, and+ /// only silently drop once it is clearly never coming.+ pub const StallVerdict = enum { wait, escape_key, drop };- pub fn stalledPending(pending: []const u8) StallAction {- if (pending.len == 0) return .discard;- if (pending[0] != 0x1b) return .truncated_sequence;- return if (pending.len == 1) .escape_key else .truncated_sequence;+ pub fn stallVerdict(pending: []const u8, stalls: u8) StallVerdict {+ if (pending.len == 0) return .wait;+ if (pending.len == 1 and pending[0] == 0x1b) return if (stalls >= 2) .escape_key else .wait;+ return if (stalls >= 20) .drop else .wait;}fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {@@@ -317,55 -283,22 +326,59 @@@ test "run loop enables click+hover tractry 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);+ // #517: a buffer-filling parser wedge must be cleared before the read,+ // or the zero-length read reads as a hangup and kills the TUI.+ try std.testing.expect(std.mem.indexOf(u8, src, "pending_len == inbuf.len") != null);+ }++ test "a truncated CSI never becomes Escape or typed debris; a lone ESC still does (#94)" {+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 1));+ try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 2));+ // Split SGR mouse / kitty CSI-u: never Escape, wait for the tail...+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<65;2;3", 2));+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[5744", 19));+ // ...and silently drop once it is clearly lost, so it is never typed.+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20));++ // Half-arrived shapes from 1003 hover tracking — never the Escape key.++ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[", 20));++ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1bO", 20));++ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("39;7", 20));+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("", 5));}+fn paintToBuf(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8) ![]u8 {+ var aw = Io.Writer.Allocating.init(a);+ errdefer aw.deinit();+ try paint(&aw.writer, frame, rows, cols, prev, "\x1b[48;2;20;20;20m");+ return aw.toOwnedSlice();+}++test "paint keeps a full row's last glyph but still erases every shorter row" {+ const a = std.testing.allocator;+ // Row 0 is exactly 10 columns: ESC[K sits ON the last cell and would eat+ // the composer's right border, so a full row gets neither pad nor erase.+ // Row 1 is short and must get both.+ const out = try paintToBuf(a, "╭────────╮\nshort", 2, 10, "XXXXXXXXXX\nold row!!");+ defer a.free(out);+ const border = std.mem.indexOf(u8, out, "╭────────╮").?;+ const short = std.mem.indexOf(u8, out, "short").?;+ const erase = std.mem.indexOfPos(u8, out, border, "\x1b[K");+ try std.testing.expect(erase != null and erase.? > short);+ try std.testing.expect(std.mem.indexOfPos(u8, out, short, " ") != null);+}++test "paint erases a row whose glyphs are ambiguous width" {+ const a = std.testing.allocator;+ // " ✓ bash finished ok" draws 20 cells. When visibleLen claimed 21 it+ // measured full at cols=21, so paint skipped the pad AND the erase and the+ // 21st cell kept the previous frame. Both must still happen.+ const frame = " \u{2713} bash finished ok";+ try std.testing.expectEqual(@as(usize, 20), theme_mod.visibleLen(frame));+ const out = try paintToBuf(a, frame, 1, 21, "RESIDUE RESIDUE RESIDU");+ defer a.free(out);+ try std.testing.expect(std.mem.indexOf(u8, out, "\x1b[K") != null);+}+- test "stalled pending: only a LONE ESC is the Escape key" {- // #94: a bare ESC nothing followed is the Escape keypress.- try std.testing.expectEqual(StallAction.escape_key, stalledPending("\x1b"));- // A half-arrived SGR mouse report under 1003 hover tracking. Reading these- // as Escape cancelled the running turn, and dropping them silently left- // `39;7;32M`-shaped debris to land alone on the next read.- try std.testing.expectEqual(StallAction.truncated_sequence, stalledPending("\x1b["));- try std.testing.expectEqual(StallAction.truncated_sequence, stalledPending("\x1b[<"));- try std.testing.expectEqual(StallAction.truncated_sequence, stalledPending("\x1b[<39;7"));- try std.testing.expectEqual(StallAction.truncated_sequence, stalledPending("\x1bO"));- try std.testing.expectEqual(StallAction.truncated_sequence, stalledPending("39;7"));- try std.testing.expectEqual(StallAction.discard, stalledPending(""));- }-test "rowChanged only flags the line that actually moved" {const prev = "top\nmiddle\nbottom";const next = "top\nmiddle\nBOTTOM";diff --cc TUI/scrollback.zigindex a7f4c8c2,4c580b06..3d14ab8c--- a/TUI/scrollback.zig+++ b/TUI/scrollback.zig@@@ -258,12 -219,11 +256,12 @@@ fn row(self: *const Model, a: std.mem.Areturn 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}{s}", .{ sel, fg, theme_mod.reset, th.muted, body, theme_mod.reset });- // Steady bar; the animated dots in the label carry the motion.- const line = try std.fmt.allocPrint(a, "{s}{s}❙{s} {s}{s}", .{ sel, th.accent, theme_mod.reset, body, theme_mod.reset });++ // Steady accent bar (no flicker); the animated dots carry the motion.++ const line = try std.fmt.allocPrint(a, "{s}{s}❙{s}{s} {s}{s}", .{ sel, th.accent, theme_mod.reset, th.muted, 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 });+ const body_fg = if (e.kind == .err) th.error_fg else th.text;+ const line = try std.fmt.allocPrint(a, "{s}{s}{s}{s}{s} {s}{s}", .{ sel, color, mark, theme_mod.reset, body_fg, body, theme_mod.reset });return theme_mod.wrapToWidth(a, line, width);}@@@ -410,11 -365,46 +404,46 @@@ 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)));+test "thinking animation is Grok ❙ flicker plus static Thinking" {+ try std.testing.expectEqualStrings("Thinking", thinkingLabel(0));+ try std.testing.expectEqualStrings(thinkingLabel(0), thinkingLabel(320));try std.testing.expectEqualStrings("❙", thinkingGlyph(0));- try std.testing.expect(flickerOn(0) != flickerOn(140));+ }++ test "a live turn never pulses or shifts historical rows" {+ const engine = @import("engine.zig");+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "hi");+ try m.push(.tool, "⚙ bash");+ try m.push(.tool, "✓ bash");+ try m.push(.assistant, "done");+ try m.push(.pending, "");+ var sbuf: [16]u8 = undefined;+ var none: [0]engine.Turn = .{};+ var job: engine.Job = .{+ .gpa = std.testing.allocator,+ .history = &none,+ .params = .{},+ .stream = .{ .buf = &sbuf },+ };+ m.pending = &job;+ defer m.pending = null;+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const t0 = try render(&m, arena.allocator(), 80, 0);+ const t140 = try render(&m, arena.allocator(), 80, 140);+ var it = std.mem.splitScalar(u8, t0, '\n');+ var saw_summary = false;+ while (it.next()) |ln| {+ if (std.mem.indexOf(u8, ln, "Called") != null) {+ saw_summary = true;+ try std.testing.expect(std.mem.indexOf(u8, ln, "❙") == null);+ }+ }+ try std.testing.expect(saw_summary);+ try std.testing.expectEqualStrings(t0, t140);}test "prettyTool strips mcp prefix" {diff --cc TUI/turn.zigindex 49a1a74d,55a6bc3b..a2a18a85--- a/TUI/turn.zig+++ b/TUI/turn.zig@@@ -293,32 -283,24 +301,54 @@@ test "Ctrl+C during a turn cancels onctry std.testing.expectEqual(@import("app.zig").Effect.quit, keys.handle(&m, .{ .ctrl = 'c' }));}+test "cancelTurn collapses thinking immediately" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ const job = try std.testing.allocator.create(engine.Job);+ job.* = .{+ .gpa = std.testing.allocator,+ .history = &.{},+ .params = .{},+ .stream = .{ .buf = &.{} },+ .threaded = false,+ .done = std.atomic.Value(bool).init(false),+ };+ try m.push(.pending, "");+ m.pending = job;+ cancelTurn(&m);+ try std.testing.expect(m.cancel_requested);+ try std.testing.expect(m.history.items.len == 1);+ try std.testing.expect(m.history.items[0].kind == .system);+ try std.testing.expectEqualStrings("■ interrupted", m.history.items[0].text);+ job.done.store(true, .release);+ finishJob(&m);+ try std.testing.expect(m.pending == null);+ var n: usize = 0;+ for (m.history.items) |e| {+ if (std.mem.eql(u8, e.text, "■ interrupted")) n += 1;+ }+ try std.testing.expectEqual(@as(usize, 1), n);+}+++ test "finishJob strips a pending row buried under steer echoes (#520)" {+ var m: Model = undefined;+ m.setup(std.testing.allocator);+ defer m.deinit();+ try m.push(.user, "hi");+ try m.push(.pending, "");+ try m.push(.system, "↳ queued (1 waiting)");+ const job = try std.testing.allocator.create(engine.Job);+ job.* = .{+ .threaded = false,+ .gpa = std.testing.allocator,+ .history = try std.testing.allocator.alloc(engine.Turn, 0),+ .params = .{},+ .stream = .{},+ };+ job.done.store(true, .release);+ m.pending = job;+ finishJob(&m);+ try std.testing.expect(m.pending == null);+ for (m.history.items) |e| try std.testing.expect(e.kind != .pending);+ }diff --cc src/agent_ws.zigindex 1df7db47,52015a15..f6f05716--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@@ -51,17 -54,19 +52,18 @@@ const escPressed = Agent.escPressedconst rawNonblockStdin = Agent.rawNonblockStdin;const drainSteerStdin = Agent.drainSteerStdin;-/// Codex ws applies to root Responses turns when enabled and not already fallen-/// back this session. Subagents/quiet turns keep the non-streaming SSE path.+/// WS: root Responses turns when enabled and not fallen back this session+/// (codex + xai only — Platform OpenAI has no WS endpoint).pub fn wsEligible(self: *Agent) bool {- return transport_gate.eligible(.{ .kind = self.provider.kind, .is_sub = self.sub, .codex_ws = main_mod.g_codex_ws, .ws_off = self.ws_off, .has_out = self.out != null, .quiet = self.stream_quiet });++ // Provider id is a production filter on top of the spec'd kind/flag++ // algebra: only codex and xai actually serve a WS endpoint.+ const has_ws = std.mem.eql(u8, self.provider.id, "codex") or std.mem.eql(u8, self.provider.id, "xai");- return main_mod.g_codex_ws and !self.ws_off and !self.sub and has_ws and- self.provider.kind == .responses and self.out != null and !self.stream_quiet;++ return has_ws and transport_gate.eligible(.{ .kind = self.provider.kind, .is_sub = self.sub, .codex_ws = main_mod.g_codex_ws, .ws_off = self.ws_off, .has_out = self.out != null, .quiet = self.stream_quiet });}-/// (#codex-ws) Client-side idle limit on the held codex WS, opencode's-/// OpenAIWebSocketPool design: never reuse a socket the server may already-/// have killed. A real trace showed the backend closing ours somewhere-/// within 8.5 min idle (user parked on an ask_user prompt) — 4 min stays-/// comfortably under (opencode uses 5). Overridable via-/// GRAFF_CODEX_WS_IDLE_SECS (parsed in session_run.zig beside the other-/// codex transport knobs).+/// (#codex-ws) Idle limit on the held WS (never reuse a socket the server+/// may have killed; 4 min stays under the observed ~8.5-min server close).+/// GRAFF_CODEX_WS_IDLE_SECS overrides (session_run.zig).pub var codex_ws_idle_ms: i64 = 4 * std.time.ms_per_min;/// (#codex-ws) The idle-reanchor decision, pure so the regression test can