Skip to content

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

Python

fix(tui): rejoin a given-up escape head with its late tail

Rach Pradhanff7987f66893
diff --git a/TUI/key.zig b/TUI/key.zig
index b8e32277..56df778e 100644
--- a/TUI/key.zig
+++ b/TUI/key.zig
@@ -1,35 +1,43 @@
//! Keyboard tokens. Understands classic CSI, SS3, and kitty CSI-u (Ghostty).
const std = @import("std");
+const orphan = @import("key_orphan.zig");
/// Super/alt currently held, from kitty modifier-key events (Ghostty Cmd+Delete
/// often arrives as a bare DEL after Super-down).
pub var held: u32 = 0;
-/// 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;
+/// Arm/disarm the orphan-debris sweeper. The read loop arms it when it throws
+/// away a partial escape sequence that never finished, because the NEXT read
+/// can then legitimately open with that sequence's orphaned tail.
+pub fn armOrphan(on: bool) void {
+ orphan.armed = on;
+}
+
+/// Keep the truncated escape head the read loop just abandoned, so the next
+/// read can rejoin it (see key_orphan.zig).
+pub fn stashOrphanHead(bytes: []const u8) void {
+ orphan.stashHead(bytes);
+}
+
+/// Prepend a stashed head to a freshly read buffer when it completes it.
+/// Every read must call this — the head is one-shot and expires here.
+pub fn joinOrphanHead(buf: []u8, n: usize) usize {
+ return orphan.joinHead(buf, n);
+}
+
/// 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;
+ orphan.reset();
}
pub const Key = union(enum) {
@@ -84,24 +92,28 @@ pub fn next(bytes: []const u8, i: *usize) ?Key {
// 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)) {
+ if (!in_paste and (i.* == 0 or i.* == orphan.end)) {
+ switch (orphan.take(bytes, i)) {
.took => |k| {
- orphan_end = i.*;
+ orphan.end = i.*;
+ // The arm covers exactly ONE lost head. Leaving it latched let
+ // the sweeper keep eating whatever the user typed next — `3u
+ // apples` reached the composer as ` apples`, and a lone `3`
+ // was held pending until the stall path dropped it (#531).
+ orphan.armed = false;
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;
- },
+ // arm must SURVIVE that carry — the rejoined fragment is the same
+ // one lost head, and disarming here made `3` + `u` read as typed
+ // text and type itself (#546).
+ .partial => return null,
.none => {},
}
}
- orphan_end = std.math.maxInt(usize);
- orphan_armed = false;
+ orphan.end = std.math.maxInt(usize);
+ orphan.armed = false;
const b = bytes[i.*];
i.* += 1;
if (b == 0x1b) return escapeSeq(bytes, i);
@@ -496,66 +508,7 @@ fn sgrMouse(params: []const u8, down: bool) Key {
} };
}
-const Orphan = union(enum) {
- /// Not debris — hand the bytes to the normal parser (typed text).
- none,
- /// Debris shape, cut short by the read boundary: hold, do not type it.
- partial,
- took: Key,
-};
-
-/// CSI debris after a lost ESC (`7444;9u`, `39;33;23M`, `<35;80;24M`). Never a
-/// letter and never Escape/Ctrl-C — those cancel or kill the turn.
-///
-/// Strictly shaped, because this runs against text a human may have typed: an
-/// optional `<`, then digits with `;`/`:` separators, then a MOUSE or CSI-u
-/// final (`M`/`m`/`u`/`~`). Any other terminator is text — accepting the whole
-/// 0x40..0x7e range ate `0x1f` (final `x`), `[12]` (final `]`) and `1e5`
-/// (final `e`). A run with neither `<` nor a separator (`3u`) is debris only
-/// while `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 .none;
- var j = start;
- 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 == ':') {
- 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];
- var it = std.mem.splitScalar(u8, body, ';');
- const btn = leadingInt(it.next() orelse "0");
- const x = leadingInt(it.next() orelse "1");
- const y = leadingInt(it.next() orelse "1");
- return .{ .took = .{ .mouse = .{
- .btn = @intCast(@min(btn, 255)),
- .x = @intCast(@min(x, 999)),
- .y = @intCast(@min(y, 999)),
- .down = c == 'M',
- } } };
- }
- return .{ .took = .ignore };
- }
- return .none;
- }
- // 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 {
+pub fn leadingInt(s: []const u8) u32 {
var n: u32 = 0;
for (s) |c| {
if (c < '0' or c > '9') break;
diff --git a/TUI/key_loop_tests.zig b/TUI/key_loop_tests.zig
new file mode 100644
index 00000000..2c7dea9b
--- /dev/null
+++ b/TUI/key_loop_tests.zig
@@ -0,0 +1,243 @@
+//! The read-loop half of key.zig's battery: everything that only shows up
+//! ACROSS a read boundary. Parked out of key_tests.zig under the 600-line
+//! ceiling.
+
+const std = @import("std");
+const key = @import("key.zig");
+const Key = key.Key;
+const next = key.next;
+
+/// run.zig's read loop, minus the terminal: fixed input buffer, parse to
+/// exhaustion, carry the unparsed tail into the next read. Regressions in the
+/// carry/rewind contract only show up across a read boundary, so the debris
+/// tests have to drive the real thing.
+const Loop = struct {
+ inbuf: [4096]u8 = undefined,
+ pending: usize = 0,
+ typed: std.array_list.Managed(u8),
+ mice: usize = 0,
+ bg_reports: usize = 0,
+
+ fn init(a: std.mem.Allocator) Loop {
+ key.resetInputState();
+ return .{ .typed = std.array_list.Managed(u8).init(a) };
+ }
+ fn deinit(self: *Loop) void {
+ self.typed.deinit();
+ }
+
+ fn read(self: *Loop, bytes: []const u8) !void {
+ @memcpy(self.inbuf[self.pending .. self.pending + bytes.len], bytes);
+ const n = key.joinOrphanHead(&self.inbuf, self.pending + bytes.len);
+ var i: usize = 0;
+ while (next(self.inbuf[0..n], &i)) |k| switch (k) {
+ .char => |c| try self.typed.append(c),
+ .codepoint => try self.typed.append('?'),
+ .mouse => self.mice += 1,
+ .escape => try self.typed.append('E'), // a phantom Escape cancels the turn
+ .bg_report => self.bg_reports += 1,
+ else => {},
+ };
+ self.pending = if (i < n) blk: {
+ const rest = n - i;
+ std.mem.copyForwards(u8, self.inbuf[0..rest], self.inbuf[i..n]);
+ break :blk rest;
+ } else 0;
+ }
+
+ /// run.zig's `.escape_key` verdict: a lone pending ESC outlived the #94
+ /// grace, so a real Escape is delivered — but the byte is carried, not
+ /// thrown away.
+ fn stallEscape(self: *Loop) !void {
+ key.stashOrphanHead(self.inbuf[0..self.pending]);
+ self.pending = 0;
+ try self.typed.append('E');
+ }
+
+ /// run.zig's `.drop` verdict: carry the head so a late tail can rejoin
+ /// it, and arm the sweeper for the tails that arrive headless.
+ fn stallDrop(self: *Loop) void {
+ key.stashOrphanHead(self.inbuf[0..self.pending]);
+ self.pending = 0;
+ key.armOrphan(true);
+ }
+};
+
+test "SGR motion flood chopped at every byte offset never types a character" {
+ key.armOrphan(false);
+ // The exact bytes the user saw on the bottom row, plus one hover report.
+ const flood = "\x1b[<39;7;32M\x1b[<39;4;32M\x1b[<39;3;33M\x1b[<39;1;33M\x1b[<35;80;24M";
+ var cut: usize = 0;
+ while (cut <= flood.len) : (cut += 1) {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read(flood[0..cut]);
+ try loop.read(flood[cut..]);
+ try std.testing.expectEqualStrings("", loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 5), loop.mice);
+ try std.testing.expectEqual(@as(usize, 0), loop.pending);
+ }
+}
+
+test "debris after a dropped ESC head is consumed, not typed — even split again" {
+ // run.zig drops a pending head that never completed and arms us; the tail
+ // arrives alone, and may itself straddle the next read boundary.
+ const tail = "39;7;32M\x1b[<39;4;32M";
+ var cut: usize = 0;
+ while (cut <= tail.len) : (cut += 1) {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ key.armOrphan(true);
+ defer key.armOrphan(false);
+ try loop.read(tail[0..cut]);
+ try loop.read(tail[cut..]);
+ try std.testing.expectEqualStrings("", loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 2), loop.mice);
+ }
+}
+
+test "typed and pasted text survives the debris guard (0x1f, [12], 1e5)" {
+ key.armOrphan(false);
+ const cases = [_][]const u8{
+ "const x = 0x1f;",
+ "v1e5 [12] 2xM",
+ "1.5]",
+ "0x1f",
+ "[12]",
+ "1e5",
+ "grep -n '39;7;32M' log", // debris-shaped text, but not at a read head
+ "step 3 of 10 (2m30s)",
+ };
+ for (cases) |text| {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read(text);
+ try std.testing.expectEqualStrings(text, loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 0), loop.mice);
+ }
+ // Byte-at-a-time typing is the same string.
+ var slow = Loop.init(std.testing.allocator);
+ defer slow.deinit();
+ for ("0x1f + [12] = 1e5") |c| try slow.read(&[_]u8{c});
+ try std.testing.expectEqualStrings("0x1f + [12] = 1e5", slow.typed.items);
+}
+
+test "bracketed paste of debris-shaped code reaches the composer intact" {
+ key.armOrphan(false);
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read("\x1b[200~");
+ try loop.read("39;7;32M and 0x1f");
+ try loop.read("\x1b[201~");
+ try std.testing.expectEqualStrings("39;7;32M and 0x1f", loop.typed.items);
+}
+
+test "a body that arrives after the escape_key verdict rejoins its ESC (#530)" {
+ // ssh/tmux cuts right after the 0x1b of a sequence and the next segment is
+ // >50ms late. run.zig delivers Escape (the E below) — but throwing the ESC
+ // away typed the whole body into the composer on top of that.
+ const bodies = [_][]const u8{ "[<35;80;24M", "[A", "[3~", "OA", "]11;rgb:14/14/14\x07" };
+ for (bodies) |body| {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read("\x1b");
+ try loop.stallEscape();
+ try loop.read(body);
+ try std.testing.expectEqualStrings("E", loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 0), loop.pending);
+ }
+ // ...and the rejoined sequences are the real events, not merely swallowed.
+ var mouse = Loop.init(std.testing.allocator);
+ defer mouse.deinit();
+ try mouse.read("\x1b");
+ try mouse.stallEscape();
+ try mouse.read("[<35;80;24M");
+ try std.testing.expectEqual(@as(usize, 1), mouse.mice);
+ var osc = Loop.init(std.testing.allocator);
+ defer osc.deinit();
+ try osc.read("\x1b");
+ try osc.stallEscape();
+ try osc.read("]11;rgb:14/14/14\x07");
+ try std.testing.expectEqual(@as(usize, 1), osc.bg_reports);
+}
+
+test "a dropped head rejoins its tail whatever the split (#531/#546)" {
+ // Every shape takeOrphanCsi structurally cannot sweep: a split ON the
+ // separator, a non-mouse final, an OSC body.
+ const cases = [_]struct { head: []const u8, tail: []const u8, mice: usize }{
+ .{ .head = "\x1b[<35;80", .tail = ";24M", .mice = 1 },
+ .{ .head = "\x1b[", .tail = "A", .mice = 0 },
+ .{ .head = "\x1b[3", .tail = "~", .mice = 0 },
+ .{ .head = "\x1b]11;rgb:1c", .tail = "1c/1c1c/1c1c\x07", .mice = 0 },
+ .{ .head = "\x1b[<39;7;32", .tail = "M", .mice = 1 },
+ };
+ for (cases) |c| {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read(c.head);
+ loop.stallDrop();
+ try loop.read(c.tail);
+ try std.testing.expectEqualStrings("", loop.typed.items);
+ try std.testing.expectEqual(c.mice, loop.mice);
+ try std.testing.expectEqual(@as(usize, 0), loop.pending);
+ }
+}
+
+test "a head whose tail never comes never eats the keystrokes that follow" {
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ try loop.read("\x1b[<35;80");
+ loop.stallDrop();
+ // The user gave up waiting and resumed typing: nothing is glued on, and
+ // the armed sweeper must not swallow the words either.
+ try loop.read("hello world");
+ try std.testing.expectEqualStrings("hello world", loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 0), loop.pending);
+}
+
+test "the orphan arm covers exactly one lost head (#531)" {
+ // Latched, the sweeper kept eating: `3u apples` reached the composer as
+ // ` apples`, and a lone `3` was held pending until the loop dropped it.
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ key.armOrphan(true);
+ try loop.read("39;7;32M");
+ try std.testing.expectEqual(@as(usize, 1), loop.mice);
+ try loop.read("3u apples");
+ try std.testing.expectEqualStrings("3u apples", loop.typed.items);
+ try std.testing.expectEqual(@as(usize, 0), loop.pending);
+
+ var slow = Loop.init(std.testing.allocator);
+ defer slow.deinit();
+ key.armOrphan(true);
+ try slow.read("39;7;32M");
+ try slow.read("3");
+ try std.testing.expectEqual(@as(usize, 0), slow.pending);
+ try std.testing.expectEqualStrings("3", slow.typed.items);
+ key.armOrphan(false);
+}
+
+test "a headless debris tail that opens on a separator is eaten, not typed (#546)" {
+ // The head is gone for good (no carry): the sweeper is the only guard
+ // left, and it must accept the `;`-led continuation while armed.
+ var loop = Loop.init(std.testing.allocator);
+ defer loop.deinit();
+ key.armOrphan(true);
+ try loop.read(";24M");
+ try std.testing.expectEqualStrings("", loop.typed.items);
+ // Never a phantom click at (1,1): the coordinates cannot be reconstructed.
+ try std.testing.expectEqual(@as(usize, 0), loop.mice);
+ // Split again, on the final byte this time.
+ var split = Loop.init(std.testing.allocator);
+ defer split.deinit();
+ key.armOrphan(true);
+ try split.read("3");
+ try split.read("u");
+ try std.testing.expectEqualStrings("", split.typed.items);
+ key.armOrphan(false);
+ // Unarmed, the very same bytes are the user typing.
+ var typed = Loop.init(std.testing.allocator);
+ defer typed.deinit();
+ try typed.read(";24M");
+ try std.testing.expectEqualStrings(";24M", typed.typed.items);
+}
diff --git a/TUI/key_orphan.zig b/TUI/key_orphan.zig
new file mode 100644
index 00000000..64960e4a
--- /dev/null
+++ b/TUI/key_orphan.zig
@@ -0,0 +1,221 @@
+//! Escape-sequence debris recovery, parked out of key.zig under the 600-line
+//! ceiling.
+//!
+//! Two halves of one problem: the read loop gives up on a truncated escape
+//! head once the terminal goes quiet (an ssh/tmux hiccup mid-sequence), and
+//! that sequence's tail can still land on a LATER read with its introducer
+//! gone.
+//!
+//! * `stashHead`/`joinHead` keep the abandoned head for exactly one more
+//! read and re-attach it when the new bytes really do complete it. The
+//! tail then parses as the thing it always was — mouse report, arrow,
+//! OSC-11 reply — with no shape guessing at all (#530/#531).
+//! * `take` is the fallback sweeper for tails whose head is gone for good,
+//! so `;24M` is eaten instead of typed into the composer (#546).
+
+const std = @import("std");
+const key = @import("key.zig");
+const Key = key.Key;
+
+/// Set by the read loop when it abandons a truncated escape head: the NEXT
+/// read may legitimately open with that sequence's orphaned tail.
+pub var armed: bool = false;
+
+/// End offset of the last fragment consumed from the buffer currently being
+/// parsed, so back-to-back debris keeps being eaten while a digit run that
+/// follows real input never is. `maxInt` = no run in progress.
+pub var end: usize = std.math.maxInt(usize);
+
+/// Longest head worth carrying. Real CSI/OSC heads are far shorter; anything
+/// bigger is a parser wedge, not a sequence.
+const max_head = 64;
+var head: [max_head]u8 = undefined;
+var head_len: usize = 0;
+
+pub fn reset() void {
+ armed = false;
+ end = std.math.maxInt(usize);
+ head_len = 0;
+}
+
+/// Keep the head the loop just gave up on. One shot: `joinHead` spends it on
+/// the very next read whether or not it is used.
+pub fn stashHead(bytes: []const u8) void {
+ head_len = 0;
+ if (bytes.len == 0 or bytes.len > max_head) return;
+ @memcpy(head[0..bytes.len], bytes);
+ head_len = bytes.len;
+}
+
+/// Re-attach a stashed head to the front of `buf[0..n]` when the new bytes
+/// complete it, returning the new length. Spending the head unconditionally is
+/// the point: a head whose tail never came can never glue itself onto a later
+/// keystroke.
+pub fn joinHead(buf: []u8, n: usize) usize {
+ const h = head_len;
+ head_len = 0;
+ if (h == 0 or n == 0 or h + n > buf.len) return n;
+ if (!completes(head[0..h], buf[0..n])) return n;
+ std.mem.copyBackwards(u8, buf[h .. h + n], buf[0..n]);
+ @memcpy(buf[0..h], head[0..h]);
+ return n + h;
+}
+
+fn at(h: []const u8, t: []const u8, k: usize) u8 {
+ return if (k < h.len) h[k] else t[k - h.len];
+}
+
+/// Does `t` finish the truncated escape `h`? Only a join that yields a
+/// COMPLETE sequence is worth making: after a give-up stall the next bytes are
+/// just as likely to be a human resuming typing, and gluing a stale head onto
+/// those would eat a keystroke.
+pub fn completes(h: []const u8, t: []const u8) bool {
+ const n = h.len + t.len;
+ if (h.len == 0 or t.len == 0 or h[0] != 0x1b or n < 2) return false;
+ switch (at(h, t, 1)) {
+ 0x1b => return true, // ESC ESC — a real Escape either way
+ 'O' => return n >= 3, // SS3 is exactly one more byte
+ '[' => {
+ var k: usize = 2;
+ while (k < n) : (k += 1) {
+ const c = at(h, t, k);
+ if (c >= 0x20 and c <= 0x3f) continue; // params + intermediates
+ return isInputFinal(c);
+ }
+ return false;
+ },
+ ']', 'P', '_', '^', 'X' => {
+ var k: usize = 2;
+ while (k < n) : (k += 1) {
+ const c = at(h, t, k);
+ if (c == 0x07) return true; // BEL
+ if (c == 0x1b) return k + 1 < n and at(h, t, k + 1) == '\\'; // ST
+ if (c == 0x0d or c == 0x0a) return false; // typed text, not a reply
+ }
+ return false;
+ },
+ // A lone ESC in front of ordinary text is an Alt chord, and joining it
+ // would SWALLOW that character. Typing it is the lesser harm.
+ else => return false,
+ }
+}
+
+/// CSI finals a terminal actually sends on stdin. Deliberately narrow: the
+/// whole 0x40..0x7e range would let a stale head glue itself onto the first
+/// letter a human types after the stall.
+fn isInputFinal(c: u8) bool {
+ return switch (c) {
+ 'A'...'F', 'H', 'M', 'P'...'S', 'Z', 'm', 'u', '~' => true,
+ else => false,
+ };
+}
+
+pub const Orphan = union(enum) {
+ /// Not debris — hand the bytes to the normal parser (typed text).
+ none,
+ /// Debris shape, cut short by the read boundary: hold, do not type it.
+ partial,
+ took: Key,
+};
+
+/// CSI debris after a lost ESC (`7444;9u`, `39;33;23M`, `<35;80;24M`). Never a
+/// letter and never Escape/Ctrl-C — those cancel or kill the turn.
+///
+/// Strictly shaped, because this runs against text a human may have typed: an
+/// optional `<`, then digits with `;`/`:` separators, then a MOUSE or CSI-u
+/// final (`M`/`m`/`u`/`~`). Any other terminator is text — accepting the whole
+/// 0x40..0x7e range ate `0x1f` (final `x`), `[12]` (final `]`) and `1e5`
+/// (final `e`). A run with neither `<` nor a separator (`3u`) is debris only
+/// while `armed` says the loop really did drop a truncated sequence.
+pub fn take(bytes: []const u8, i: *usize) Orphan {
+ const start = i.*;
+ if (start >= bytes.len) return .none;
+ var j = start;
+ const lt = bytes[j] == '<';
+ if (lt) j += 1;
+ var sep = false;
+ // A dropped head can split ON a separator (`\x1b[<35;80` + `;24M`), so the
+ // tail opens with `;`/`:`. That is never typed text at the head of a read,
+ // but it is only debris once the loop has told us a head was lost (#546).
+ var headless = false;
+ if (j < bytes.len and (bytes[j] == ';' or bytes[j] == ':') and armed) {
+ sep = true;
+ headless = true;
+ j += 1;
+ }
+ if (j >= bytes.len) return if (headless) .partial else .none;
+ if (bytes[j] < '0' or bytes[j] > '9') return .none;
+ var k = j;
+ while (k < bytes.len) : (k += 1) {
+ const c = bytes[k];
+ if (c >= '0' and c <= '9') continue;
+ if (c == ';' or c == ':') {
+ sep = true;
+ continue;
+ }
+ if (c == 'M' or c == 'm' or c == 'u' or c == '~') {
+ if (!lt and !sep and !armed) return .none;
+ i.* = k + 1;
+ // A fragment that opened on a separator lost its leading fields:
+ // the coordinates cannot be reconstructed, and inventing a click
+ // at (1,1) is worse than dropping the report.
+ if (!headless and (c == 'M' or c == 'm')) {
+ const body = bytes[j..k];
+ var it = std.mem.splitScalar(u8, body, ';');
+ const btn = key.leadingInt(it.next() orelse "0");
+ const x = key.leadingInt(it.next() orelse "1");
+ const y = key.leadingInt(it.next() orelse "1");
+ return .{ .took = .{ .mouse = .{
+ .btn = @intCast(@min(btn, 255)),
+ .x = @intCast(@min(x, 999)),
+ .y = @intCast(@min(y, 999)),
+ .down = c == 'M',
+ } } };
+ }
+ return .{ .took = .ignore };
+ }
+ return .none;
+ }
+ // 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 armed) .partial else .none;
+}
+
+test "a join only happens when the tail really completes the head" {
+ // The shapes run.zig drops mid-flight, rejoined.
+ try std.testing.expect(completes("\x1b", "[<35;80;24M"));
+ try std.testing.expect(completes("\x1b", "[A"));
+ try std.testing.expect(completes("\x1b", "[3~"));
+ try std.testing.expect(completes("\x1b", "OA"));
+ try std.testing.expect(completes("\x1b", "]11;rgb:14/14/14\x07"));
+ try std.testing.expect(completes("\x1b[<35;80", ";24M"));
+ try std.testing.expect(completes("\x1b[201", "~"));
+ try std.testing.expect(completes("\x1b]11;rgb:1c", "1c/1c1c/1c1c\x07"));
+ // ...and never onto a human who simply resumed typing.
+ try std.testing.expect(!completes("\x1b", "hello"));
+ try std.testing.expect(!completes("\x1b", ""));
+ try std.testing.expect(!completes("\x1b[<35;80", "hello"));
+ try std.testing.expect(!completes("\x1b[", "3")); // still incomplete
+ try std.testing.expect(!completes("\x1b]11;rgb:1c", "fix it\r"));
+ try std.testing.expect(!completes("", "[A"));
+ try std.testing.expect(!completes("39;7", ";32M")); // headless debris is take()'s job
+}
+
+test "joinHead spends the head on the next read either way" {
+ reset();
+ var buf: [32]u8 = undefined;
+ stashHead("\x1b[<35;80");
+ @memcpy(buf[0..4], ";24M");
+ try std.testing.expectEqual(@as(usize, 12), joinHead(&buf, 4));
+ try std.testing.expectEqualStrings("\x1b[<35;80;24M", buf[0..12]);
+ // Second read: the head is spent, nothing is glued on.
+ @memcpy(buf[0..4], ";24M");
+ try std.testing.expectEqual(@as(usize, 4), joinHead(&buf, 4));
+ // A head whose tail never came never corrupts the keystroke that follows.
+ stashHead("\x1b[<35;80");
+ @memcpy(buf[0..5], "hello");
+ try std.testing.expectEqual(@as(usize, 5), joinHead(&buf, 5));
+ try std.testing.expectEqualStrings("hello", buf[0..5]);
+ reset();
+}
diff --git a/TUI/key_tests.zig b/TUI/key_tests.zig
index 27b486b1..32e946ce 100644
--- a/TUI/key_tests.zig
+++ b/TUI/key_tests.zig
@@ -225,8 +225,8 @@ test "orphan kitty CSI-u is ignore, never letters or Escape" {
// `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;
+ key.armOrphan(true);
+ defer key.armOrphan(false);
var n: usize = 0;
while (next(seq, &i)) |k| {
try std.testing.expect(k == .ignore);
@@ -238,112 +238,6 @@ 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/root.zig b/TUI/root.zig
index 43f0771e..7c3bdfc8 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -36,7 +36,9 @@ test {
_ = app;
_ = @import("dispatch.zig");
_ = @import("key.zig");
+ _ = @import("key_orphan.zig");
_ = @import("key_tests.zig");
+ _ = @import("key_loop_tests.zig");
_ = @import("input.zig");
_ = @import("keys.zig");
_ = @import("nav.zig");
diff --git a/TUI/run.zig b/TUI/run.zig
index 352b7da0..ed947c68 100644
--- a/TUI/run.zig
+++ b/TUI/run.zig
@@ -86,6 +86,7 @@ pub fn run(
var pending_len: usize = 0;
var esc_stall: u8 = 0;
var zero_reads: u8 = 0;
+ var stash_ms: u64 = 0;
var last_hash: u64 = 0;
var saw_gfx: bool = false;
var prev: []u8 = &.{};
@@ -139,19 +140,30 @@ pub fn run(
const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null) 50 else 200;
if (!tty.poll(wait)) {
if (pending_len > 0) {
- esc_stall += 1;
- switch (stallVerdict(inbuf[0..pending_len], esc_stall)) {
+ esc_stall +|= 1;
+ switch (stallVerdict(inbuf[0..pending_len], esc_stall, .{
+ .turn_live = m.pending != null,
+ })) {
.wait => {},
.escape_key => {
- if (keys.handle(&m, .escape) == .quit) m.running = false;
+ // Keep the ESC. If the next read is this sequence's
+ // body after all, the two rejoin and it parses as the
+ // arrow / mouse report / OSC reply it always was
+ // instead of spraying `[<35;80;24M` into the composer
+ // (#530).
+ key_mod.stashOrphanHead(inbuf[0..pending_len]);
+ stash_ms = m.now_ms;
pending_len = 0;
esc_stall = 0;
+ if (keys.handle(&m, .escape) == .quit) m.running = false;
},
.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.
- key_mod.orphan_armed = true;
+ // Carry the head so a late tail can still rejoin it,
+ // and tell key.zig to expect orphan debris otherwise.
+ key_mod.stashOrphanHead(inbuf[0..pending_len]);
+ stash_ms = m.now_ms;
+ key_mod.armOrphan(true);
pending_len = 0;
esc_stall = 0;
},
@@ -177,7 +189,12 @@ pub fn run(
continue;
}
zero_reads = 0;
- const n = pending_len + got;
+ // Spends any head the stall path carried: it is glued back on only
+ // when these bytes really complete it (key_orphan.zig), and only while
+ // the join can still plausibly be link jitter rather than a human
+ // resuming typing.
+ if (carryExpired(m.now_ms, stash_ms)) key_mod.stashOrphanHead("");
+ const n = key_mod.joinOrphanHead(&inbuf, pending_len + got);
var i: usize = 0;
while (key_mod.next(inbuf[0..n], &i)) |k| {
switch (keys.handle(&m, k)) {
@@ -216,9 +233,32 @@ pub fn run(
/// only silently drop once it is clearly never coming.
pub const StallVerdict = enum { wait, escape_key, drop };
-pub fn stallVerdict(pending: []const u8, stalls: u8) StallVerdict {
+pub const StallCtx = struct {
+ /// A turn is streaming. A phantom Escape here CANCELS it, and this is
+ /// precisely when the 1003 motion flood makes a split sequence likely, so
+ /// the lone-ESC grace stretches. Idle, #94's snappy Escape is untouched.
+ turn_live: bool = false,
+};
+
+/// ~25ms a stall: 2 polls idle, 8 (~200ms) while a turn streams.
+const esc_grace_idle: u8 = 2;
+const esc_grace_live: u8 = 8;
+/// How long a given-up head stays eligible to rejoin its tail. A sequence cut
+/// by ssh/tmux jitter finishes within a few hundred ms of the give-up; past
+/// that the next bytes are a human typing, and `\x1b[` + `Hello` would eat the
+/// H (`CSI H` is a legal Home).
+const carry_window_ms: u64 = 400;
+
+fn carryExpired(now_ms: u64, stash_ms: u64) bool {
+ return now_ms -| stash_ms > carry_window_ms;
+}
+
+pub fn stallVerdict(pending: []const u8, stalls: u8, ctx: StallCtx) StallVerdict {
if (pending.len == 0) return .wait;
- if (pending.len == 1 and pending[0] == 0x1b) return if (stalls >= 2) .escape_key else .wait;
+ if (pending.len == 1 and pending[0] == 0x1b) {
+ const grace = if (ctx.turn_live) esc_grace_live else esc_grace_idle;
+ return if (stalls >= grace) .escape_key else .wait;
+ }
return if (stalls >= 20) .drop else .wait;
}
@@ -332,18 +372,41 @@ test "run loop enables click+hover tracking and bracketed paste" {
}
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));
+ const idle: StallCtx = .{};
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 1, idle));
+ try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 2, idle));
// Split SGR mouse / kitty CSI-u: never Escape, wait for the tail...
- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<65;2;3", 2));
- try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[5744", 19));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[<65;2;3", 2, idle));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[5744", 19, idle));
// ...and silently drop once it is clearly lost, so it is never typed.
- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20));
+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20, idle));
// Half-arrived shapes from 1003 hover tracking — never the Escape key.
- try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[", 20));
- 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));
+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[", 20, idle));
+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1bO", 20, idle));
+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("39;7", 20, idle));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("", 5, idle));
+}
+
+test "the lone-ESC grace stretches while a turn streams (#530)" {
+ // ssh/tmux jitter during a 1003 motion flood cuts right after an ESC. At
+ // 2 polls that became a phantom Escape and cancelled the live turn; the
+ // body then typed itself. Idle, #94's latency is unchanged.
+ const live: StallCtx = .{ .turn_live = true };
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 2, live));
+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 7, live));
+ try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 8, live));
+ try std.testing.expectEqual(StallVerdict.escape_key, stallVerdict("\x1b", 2, .{}));
+}
+
+test "the carried head expires before it can reach a human keystroke (#530)" {
+ // A tail split off by link jitter lands within a few hundred ms of the
+ // give-up; anything later is somebody typing and must arrive untouched.
+ try std.testing.expect(!carryExpired(1000, 1000));
+ try std.testing.expect(!carryExpired(1400, 1000));
+ try std.testing.expect(carryExpired(1401, 1000));
+ try std.testing.expect(carryExpired(9000, 1000));
+ // A clock that never ran (no stash yet) is expired, not live.
+ try std.testing.expect(carryExpired(100_000, 0));
}
fn paintToBuf(a: std.mem.Allocator, frame: []const u8, rows: usize, cols: usize, prev: []const u8) ![]u8 {
diff --git a/TUI/sim.zig b/TUI/sim.zig
index 8e3cfe76..fc654477 100644
--- a/TUI/sim.zig
+++ b/TUI/sim.zig
@@ -64,7 +64,7 @@ pub const Term = struct {
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;
+ const n = key_mod.joinOrphanHead(&self.inbuf, self.pending + take);
var i: usize = 0;
var last: Effect = .stay;
while (key_mod.next(self.inbuf[0..n], &i)) |k| {
@@ -80,12 +80,14 @@ pub const Term = struct {
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).
+ /// The live loop gives up on a pending sequence that never finished: it
+ /// carries the head for one more read and arms the debris
+ /// sweeper (run.zig's stall path).
pub fn stallDropPending(self: *Term) void {
if (self.pending == 0) return;
+ key_mod.stashOrphanHead(self.inbuf[0..self.pending]);
self.pending = 0;
- key_mod.orphan_armed = true;
+ key_mod.armOrphan(true);
}
pub fn press(self: *Term, k: Key) Effect {
@@ -254,8 +256,8 @@ test "hoverText on an image chip opens the preview" {
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;
+ key_mod.armOrphan(false);
+ defer key_mod.armOrphan(false);
var term: Term = undefined;
term.init(std.testing.allocator, 80, 24);
defer term.deinit();