Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix(tui): stop SGR mouse debris typing itself into the frame, and stop the debris guard eating real text

Rach Pradhan258e2445ffcf
diff --git a/TUI/key.zig b/TUI/key.zig
index 95fb544c..d6d3e907 100644
--- a/TUI/key.zig
+++ b/TUI/key.zig
@@ -6,6 +6,32 @@ const std = @import("std");
/// often arrives as a bare DEL after Super-down).
pub var held: u32 = 0;
+/// Armed by the read loop when it throws away a partial escape sequence that
+/// never finished (run.zig's stall path) — the NEXT read can then legitimately
+/// open with that sequence's orphaned tail. Cleared by the first token that is
+/// not orphan debris.
+pub var orphan_armed: bool = false;
+
+/// End offset of the last orphan fragment consumed from the buffer currently
+/// being parsed, so back-to-back debris keeps being eaten while a digit run
+/// that follows real input never is. `maxInt` = no run in progress.
+var orphan_end: usize = std.math.maxInt(usize);
+
+/// Inside `CSI 200~ … CSI 201~`. Every byte between them is literal text by
+/// definition, and a long paste spans several reads — so the debris guard must
+/// stay out of it or a chunk that happens to start `39;7;32M` gets eaten.
+var in_paste: bool = false;
+
+/// Drop every latched parser bit. The globals live for one input loop, so a
+/// fresh session (or a headless sim.Term) must not inherit a held modifier, an
+/// unclosed bracketed paste, or an arm from whatever ran before it.
+pub fn resetInputState() void {
+ held = 0;
+ orphan_armed = false;
+ orphan_end = std.math.maxInt(usize);
+ in_paste = false;
+}
+
pub const Key = union(enum) {
char: u8,
/// Non-ASCII codepoint delivered via kitty CSI-u (é and friends).
@@ -53,7 +79,29 @@ pub const Mouse = struct {
pub fn next(bytes: []const u8, i: *usize) ?Key {
if (i.* >= bytes.len) return null;
- if (takeOrphanCsi(bytes, i)) |k| return k;
+ // Orphan CSI debris can only ever be the HEAD of a read: the ESC that
+ // opened the sequence was lost BETWEEN reads (the loop dropped a truncated
+ // pending head, or the tty input queue overflowed while a slow frame
+ // painted). A digit run anywhere else is typed or pasted TEXT — swallowing
+ // it ate `0x1f`, `[12]`, `1e5` and every version string.
+ if (!in_paste and (i.* == 0 or i.* == orphan_end)) {
+ switch (takeOrphanCsi(bytes, i)) {
+ .took => |k| {
+ orphan_end = i.*;
+ return k;
+ },
+ // Debris cut short at the read boundary: hold the bytes so the loop
+ // carries them into the next read instead of typing the digits. The
+ // held bytes ARE the carry-over, so the arm has done its job.
+ .partial => {
+ orphan_armed = false;
+ return null;
+ },
+ .none => {},
+ }
+ }
+ orphan_end = std.math.maxInt(usize);
+ orphan_armed = false;
const b = bytes[i.*];
i.* += 1;
if (b == 0x1b) return escapeSeq(bytes, i);
@@ -255,8 +303,14 @@ fn decodeCsi(params: []const u8, final: u8) Key {
6 => .page_down,
11 => .f1,
12 => .f2,
- 200 => .paste_start,
- 201 => .paste_end,
+ 200 => blk: {
+ in_paste = true;
+ break :blk .paste_start;
+ },
+ 201 => blk: {
+ in_paste = false;
+ break :blk .paste_end;
+ },
27 => fixterms(params),
// 2 (Insert), 13-24 (F3-F12) and friends: inert, never Escape.
else => .ignore,
@@ -420,20 +474,41 @@ fn sgrMouse(params: []const u8, down: bool) Key {
} };
}
-/// CSI debris after a split ESC (`7444;9u`, `39;33;23M`, `3u`). Never a
+const Orphan = union(enum) {
+ /// Not debris — hand the bytes to the normal parser (typed text).
+ none,
+ /// Debris shape, cut short by the read boundary: hold, do not type it.
+ partial,
+ took: Key,
+};
+
+/// CSI debris after a lost ESC (`7444;9u`, `39;33;23M`, `<35;80;24M`). Never a
/// letter and never Escape/Ctrl-C — those cancel or kill the turn.
-fn takeOrphanCsi(bytes: []const u8, i: *usize) ?Key {
+///
+/// Strictly shaped, because this runs against text a human may have typed: an
+/// optional `<`, then digits with `;`/`:` separators, then a MOUSE or CSI-u
+/// final (`M`/`m`/`u`/`~`). Any other terminator is text — accepting the whole
+/// 0x40..0x7e range ate `0x1f` (final `x`), `[12]` (final `]`) and `1e5`
+/// (final `e`). A run with neither `<` nor a separator (`3u`) is debris only
+/// while `orphan_armed` says the loop really did drop a truncated sequence.
+fn takeOrphanCsi(bytes: []const u8, i: *usize) Orphan {
const start = i.*;
- if (start >= bytes.len) return null;
+ if (start >= bytes.len) return .none;
var j = start;
- if (bytes[j] == '<') j += 1;
- if (j >= bytes.len or bytes[j] < '0' or bytes[j] > '9') return null;
+ const lt = bytes[j] == '<';
+ if (lt) j += 1;
+ if (j >= bytes.len or bytes[j] < '0' or bytes[j] > '9') return .none;
+ var sep = false;
var k = j;
while (k < bytes.len) : (k += 1) {
const c = bytes[k];
if (c >= '0' and c <= '9') continue;
- if (c == ';' or c == ':') continue;
- if (c >= 0x40 and c <= 0x7e) {
+ if (c == ';' or c == ':') {
+ sep = true;
+ continue;
+ }
+ if (c == 'M' or c == 'm' or c == 'u' or c == '~') {
+ if (!lt and !sep and !orphan_armed) return .none;
i.* = k + 1;
if (c == 'M' or c == 'm') {
const body = bytes[j..k];
@@ -441,18 +516,21 @@ fn takeOrphanCsi(bytes: []const u8, i: *usize) ?Key {
const btn = leadingInt(it.next() orelse "0");
const x = leadingInt(it.next() orelse "1");
const y = leadingInt(it.next() orelse "1");
- return .{ .mouse = .{
+ return .{ .took = .{ .mouse = .{
.btn = @intCast(@min(btn, 255)),
.x = @intCast(@min(x, 999)),
.y = @intCast(@min(y, 999)),
.down = c == 'M',
- } };
+ } } };
}
- return .ignore;
+ return .{ .took = .ignore };
}
- return null;
+ return .none;
}
- return null;
+ // Ran off the end mid-fragment. Hold it when it already reads as a CSI
+ // parameter list, or when the loop armed us; a bare unarmed digit run is
+ // somebody typing, and holding it would strand the keystrokes.
+ return if (lt or sep or orphan_armed) .partial else .none;
}
fn leadingInt(s: []const u8) u32 {
diff --git a/TUI/key_tests.zig b/TUI/key_tests.zig
index 4d0eea93..6d2db0e1 100644
--- a/TUI/key_tests.zig
+++ b/TUI/key_tests.zig
@@ -222,6 +222,11 @@ test "SGR mouse flood does not leak digits" {
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);
@@ -233,6 +238,112 @@ test "orphan kitty CSI-u is ignore, never letters or Escape" {
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).?);
diff --git a/TUI/run.zig b/TUI/run.zig
index ce84b2b2..8f601571 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -139,7 +139,18 @@ pub fn run(
if (pending_len > 0) {
esc_stall += 1;
if (esc_stall >= 2) {
- if (inbuf[0] == 0x1b and keys.handle(&m, .escape) == .quit) m.running = false;
+ 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
+ // tell key.zig to expect orphan debris there.
+ .truncated_sequence => key_mod.orphan_armed = true,
+ .discard => {},
+ }
pending_len = 0;
esc_stall = 0;
}
@@ -188,6 +199,20 @@ pub fn run(
}
}
+/// 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 };
+
+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;
+}
+
fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {
w.writeAll(restore_mod.seq) catch {};
w.flush() catch {};
@@ -294,6 +319,20 @@ test "run loop enables click+hover tracking and bracketed paste" {
try std.testing.expect(std.mem.indexOf(u8, src, "a=d,d=A") != 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 --git a/TUI/sim.zig b/TUI/sim.zig
index f507448b..8e3cfe76 100644
--- a/TUI/sim.zig
+++ b/TUI/sim.zig
@@ -38,6 +38,8 @@ pub const Term = struct {
rows: usize = 24,
now_ms: u64 = 0,
last_effect: Effect = .stay,
+ inbuf: [4096]u8 = undefined,
+ pending: usize = 0,
pub fn init(self: *Term, alloc: std.mem.Allocator, cols: usize, rows: usize) void {
self.alloc = alloc;
@@ -45,6 +47,8 @@ pub const Term = struct {
self.rows = if (rows < 12) 24 else rows;
self.now_ms = 0;
self.last_effect = .stay;
+ self.pending = 0;
+ key_mod.resetInputState();
self.model.setup(alloc);
}
@@ -52,18 +56,38 @@ pub const Term = struct {
self.model.deinit();
}
- /// Raw Ghostty/xterm bytes. Incomplete CSI is left unconsumed (same as the live loop).
+ /// Raw Ghostty/xterm bytes. An incomplete sequence is CARRIED into the next
+ /// feed, exactly like run.zig's pending buffer — dropping it here let a
+ /// split CSI vanish, which is the one thing these harness tests exist to
+ /// catch.
pub fn feed(self: *Term, bytes: []const u8) Effect {
+ const room = self.inbuf.len - self.pending;
+ const take = @min(bytes.len, room);
+ @memcpy(self.inbuf[self.pending .. self.pending + take], bytes[0..take]);
+ const n = self.pending + take;
var i: usize = 0;
var last: Effect = .stay;
- while (key_mod.next(bytes, &i)) |k| {
+ while (key_mod.next(self.inbuf[0..n], &i)) |k| {
last = keys.handle(&self.model, k);
if (last != .stay) break;
}
+ 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;
self.last_effect = last;
return last;
}
+ /// The live loop gives up on a pending sequence that never finished and
+ /// tells key.zig to expect its orphaned tail (run.zig's stall path).
+ pub fn stallDropPending(self: *Term) void {
+ if (self.pending == 0) return;
+ self.pending = 0;
+ key_mod.orphan_armed = true;
+ }
+
pub fn press(self: *Term, k: Key) Effect {
const last = keys.handle(&self.model, k);
self.last_effect = last;
@@ -228,6 +252,50 @@ test "hoverText on an image chip opens the preview" {
try std.testing.expectEqualStrings("/tmp/shot.png", term.model.preview_path);
}
+test "a 1003 hover flood during a live turn never types itself into the frame" {
+ const engine = @import("engine.zig");
+ key_mod.orphan_armed = false;
+ defer key_mod.orphan_armed = false;
+ var term: Term = undefined;
+ term.init(std.testing.allocator, 80, 24);
+ defer term.deinit();
+ try term.model.push(.user, "explain this");
+ const job = try std.testing.allocator.create(engine.Job);
+ defer std.testing.allocator.destroy(job);
+ job.* = .{
+ .gpa = std.testing.allocator,
+ .history = &.{},
+ .params = .{},
+ .stream = .{},
+ .threaded = false,
+ };
+ try term.model.push(.pending, "");
+ term.model.pending = job;
+ defer term.model.pending = null;
+
+ // The exact bytes off the user's terminal: SGR motion reports under
+ // ?1003h, arriving in ragged chunks while a slow frame paints, with the
+ // loop giving up on the head that never finished.
+ const flood = "\x1b[<39;7;32M\x1b[<39;4;32M\x1b[<39;3;33M\x1b[<39;1;33M";
+ var cut: usize = 1;
+ while (cut < flood.len) : (cut += 1) {
+ _ = term.feed(flood[0..cut]);
+ _ = term.feed(flood[cut..]);
+ term.stallDropPending();
+ _ = term.feed(flood);
+ }
+ try std.testing.expectEqualStrings("", term.model.input.getValue());
+ try std.testing.expectEqual(@as(usize, 0), term.model.steer_queue.items.len);
+ // A half-arrived report must not read as Escape either — that cancelled
+ // the turn under the user.
+ try std.testing.expect(!term.model.cancel_requested);
+ const vis = try term.screen();
+ defer std.testing.allocator.free(vis);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "39;7;32M") == null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, ";32M") == null);
+ try std.testing.expect(std.mem.indexOf(u8, vis, "Enter:queue") != null);
+}
+
test "annotated dump prefixes 1-based rows" {
var term: Term = undefined;
term.init(std.testing.allocator, 80, 24);