graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): recover from a bracketed paste that never closes
Rach Pradhanf92c004a7083
diff --git a/TUI/key.zig b/TUI/key.zigindex 56df778e..a14cb535 100644--- a/TUI/key.zig+++ b/TUI/key.zig@@ -12,6 +12,19 @@ pub var held: u32 = 0;/// stay out of it or a chunk that happens to start `39;7;32M` gets eaten.var in_paste: bool = false;+pub fn inPaste() bool {+ return in_paste;+}++/// Close a bracketed paste the terminal never closed for us. The read loop+/// calls this when it gives up on a `CSI 201~` that split across reads and+/// never arrived — without it the latch is permanent and every Enter, Escape+/// and slash command becomes literal text for the rest of the session+/// (#532/#536/#548).+pub fn endPaste() void {+ in_paste = 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.diff --git a/TUI/key_loop_tests.zig b/TUI/key_loop_tests.zigindex 2c7dea9b..7a1a2431 100644--- a/TUI/key_loop_tests.zig+++ b/TUI/key_loop_tests.zig@@ -16,6 +16,7 @@ const Loop = struct {pending: usize = 0,typed: std.array_list.Managed(u8),mice: usize = 0,+ paste_ends: usize = 0,bg_reports: usize = 0,fn init(a: std.mem.Allocator) Loop {@@ -35,6 +36,7 @@ const Loop = struct {.codepoint => try self.typed.append('?'),.mouse => self.mice += 1,.escape => try self.typed.append('E'), // a phantom Escape cancels the turn+ .paste_end => self.paste_ends += 1,.bg_report => self.bg_reports += 1,else => {},};@@ -54,12 +56,16 @@ const Loop = struct {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.+ /// run.zig's `.drop` verdict: carry the head, arm the sweeper, and close+ /// out a paste that can no longer be closed by its own marker.fn stallDrop(self: *Loop) void {key.stashOrphanHead(self.inbuf[0..self.pending]);self.pending = 0;key.armOrphan(true);+ if (key.inPaste()) {+ key.endPaste();+ self.paste_ends += 1;+ }}};@@ -241,3 +247,48 @@ test "a headless debris tail that opens on a separator is eaten, not typed (#546try typed.read(";24M");try std.testing.expectEqualStrings(";24M", typed.typed.items);}++test "a paste whose end marker is lost still closes (#532/#536/#548)" {+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ try loop.read("\x1b[200~");+ try loop.read("hello");+ try loop.read("\x1b[201");+ try std.testing.expect(key.inPaste());+ loop.stallDrop(); // ~2s of silence: give up on the marker+ try std.testing.expect(!key.inPaste());+ try std.testing.expectEqual(@as(usize, 1), loop.paste_ends);+ // The late `~` rejoins its head, so it is never typed either.+ try loop.read("~");+ try std.testing.expectEqualStrings("hello", loop.typed.items);+ // And the debris guard is live again, because the paste really did close.+ try loop.read("\x1b[<39;7;32M");+ try std.testing.expectEqualStrings("hello", loop.typed.items);+ try std.testing.expectEqual(@as(usize, 1), loop.mice);+}++test "an unterminated paste releases on the idle timeout (#548)" {+ var loop = Loop.init(std.testing.allocator);+ defer loop.deinit();+ try loop.read("\x1b[200~body");+ try std.testing.expect(key.inPaste());+ key.endPaste(); // run.zig's paste_idle_ms sweep+ try std.testing.expect(!key.inPaste());+ // Back to a normal composer: debris is eaten again instead of typed.+ try loop.read("\x1b[<39;7;32M");+ try std.testing.expectEqualStrings("body", loop.typed.items);+ try std.testing.expectEqual(@as(usize, 1), loop.mice);+}++test "a real multi-read paste is untouched by any of the recovery paths" {+ 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("second chunk ;24M");+ try loop.read("\x1b[201~");+ try std.testing.expectEqualStrings("39;7;32M and 0x1f second chunk ;24M", loop.typed.items);+ try std.testing.expectEqual(@as(usize, 1), loop.paste_ends);+ try std.testing.expectEqual(@as(usize, 0), loop.mice);+ try std.testing.expect(!key.inPaste());+}diff --git a/TUI/keys.zig b/TUI/keys.zigindex f8fc2e03..28931cb7 100644--- a/TUI/keys.zig+++ b/TUI/keys.zig@@ -40,6 +40,7 @@ pub fn handle(self: *Model, k: Key) Effect {}if (k == .paste_end) {self.pasting = false;+ key_mod.endPaste(); // the two latches must never drift apartconst v = std.mem.trim(u8, self.input.getValue(), " \t\r\n");if (@import("image.zig").attachDropped(self, v)) {self.input.setValue("") catch {};@@ -51,6 +52,15 @@ pub fn handle(self: *Model, k: Key) Effect {.enter => self.input.handle(.{ .char = '\n' }),.char => |c| self.input.handle(.{ .char = c }),.codepoint => self.input.handle(k),+ // In-band escape hatch. A paste whose `CSI 201~` never arrived+ // latches this branch forever, and it swallows Enter, Tab, the+ // slash menu and every overlay — indistinguishable from a hung+ // TUI. Escape breaks the latch instead of vanishing (#536/#548).+ .escape => {+ self.pasting = false;+ key_mod.endPaste();+ self.setToast("paste ended");+ },else => {},}return .stay;diff --git a/TUI/run.zig b/TUI/run.zigindex ed947c68..9cb37d62 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 last_input_ms: u64 = 0;var stash_ms: u64 = 0;var last_hash: u64 = 0;var saw_gfx: bool = false;@@ -139,10 +140,21 @@ pub fn run(// nothing follows, the lone ESC was a real Escape keypress (#94).const wait: i32 = if (pending_len > 0) 25 else if (m.pending != null) 50 else 200;if (!tty.poll(wait)) {+ if (key_mod.inPaste() and m.now_ms -| last_input_ms >= paste_idle_ms) {+ // A `CSI 200~` whose `CSI 201~` never arrives latches the+ // composer into literal mode for the rest of the session:+ // Enter only inserts a newline, and Escape, Tab and every+ // slash command are swallowed. Close it out once the terminal+ // has been quiet far longer than any paste keeps streaming+ // (#532/#536/#548).+ closePaste(&m);+ last_input_ms = m.now_ms;+ }if (pending_len > 0) {esc_stall +|= 1;switch (stallVerdict(inbuf[0..pending_len], esc_stall, .{.turn_live = m.pending != null,+ .in_paste = key_mod.inPaste(),})) {.wait => {},.escape_key => {@@ -166,6 +178,7 @@ pub fn run(key_mod.armOrphan(true);pending_len = 0;esc_stall = 0;+ closePaste(&m);},}}@@ -189,6 +202,7 @@ pub fn run(continue;}zero_reads = 0;+ last_input_ms = m.now_ms;// 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@@ -238,11 +252,19 @@ pub const StallCtx = struct {/// 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,+ /// Inside a bracketed paste: a lone ESC is far more likely to be the head+ /// of the closing `CSI 201~` than the Escape key, and giving up on that+ /// marker wedges the composer.+ in_paste: 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;+/// A paste marker is worth ~2s before we conclude it is never coming.+const paste_marker_stalls: u8 = 80;+/// Input silence that ends a bracketed paste nothing else can close.+const paste_idle_ms: u64 = 2000;/// 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@@ -255,6 +277,9 @@ fn carryExpired(now_ms: u64, stash_ms: u64) bool {pub fn stallVerdict(pending: []const u8, stalls: u8, ctx: StallCtx) StallVerdict {if (pending.len == 0) return .wait;+ if (ctx.in_paste and isPasteMarkerPrefix(pending)) {+ return if (stalls >= paste_marker_stalls) .drop 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;@@ -262,6 +287,21 @@ pub fn stallVerdict(pending: []const u8, stalls: u8, ctx: StallCtx) StallVerdictreturn if (stalls >= 20) .drop else .wait;}+/// A proper prefix of either bracketed-paste marker.+fn isPasteMarkerPrefix(pending: []const u8) bool {+ return std.mem.startsWith(u8, "\x1b[201~", pending) or+ std.mem.startsWith(u8, "\x1b[200~", pending);+}++/// Close a bracketed paste we can no longer finish. The parser latch and the+/// model flag are both cleared through the SAME event the terminal would have+/// sent, so there is exactly one teardown path (image attach, focus restore).+fn closePaste(m: *Model) void {+ if (!key_mod.inPaste()) return;+ key_mod.endPaste();+ _ = keys.handle(m, .paste_end);+}+fn parkToShell(io: Io, w: *Io.Writer, raw: *tty.RawState) void {w.writeAll(restore_mod.seq) catch {};w.flush() catch {};@@ -409,6 +449,22 @@ test "the carried head expires before it can reach a human keystroke (#530)" {try std.testing.expect(carryExpired(100_000, 0));}+test "a paste marker is never abandoned on the #94 timescale (#532)" {+ // Both give-up routes strand `in_paste` forever, so every prefix of either+ // marker gets ~2s — including the lone ESC, which must NOT become Escape.+ const p: StallCtx = .{ .in_paste = true };+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b", 2, p));+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[201", 20, p));+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[20", 79, p));+ try std.testing.expectEqual(StallVerdict.wait, stallVerdict("\x1b[200", 79, p));+ // Then give up for real — run.zig synthesizes the paste_end on that drop.+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[201", 80, p));+ // Anything that is not a marker prefix keeps the ordinary budget.+ try std.testing.expectEqual(StallVerdict.drop, stallVerdict("\x1b[<65;2;3", 20, p));+ try std.testing.expect(isPasteMarkerPrefix("\x1b[201~"));+ try std.testing.expect(!isPasteMarkerPrefix("\x1b[202"));+}+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();diff --git a/TUI/sim.zig b/TUI/sim.zigindex fc654477..b961dd57 100644--- a/TUI/sim.zig+++ b/TUI/sim.zig@@ -81,13 +81,18 @@ pub const Term = struct {}/// 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).+ /// carries the head for one more read, arms the debris sweeper, and — if+ /// the casualty was a bracketed-paste marker — synthesizes the paste_end+ /// the terminal never sent (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.armOrphan(true);+ if (key_mod.inPaste()) {+ key_mod.endPaste();+ _ = keys.handle(&self.model, .paste_end);+ }}pub fn press(self: *Term, k: Key) Effect {@@ -308,3 +313,37 @@ test "annotated dump prefixes 1-based rows" {try std.testing.expect(std.mem.indexOf(u8, ann, " 1|") != null);try std.testing.expect(std.mem.indexOf(u8, ann, "abc") != null);}++test "a paste that never terminates does not wedge the composer (#536/#548)" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ // The terminator is lost in flight: `pasting` latches and swallows Enter,+ // Tab, the slash menu and every overlay — the 'TUI froze' report.+ _ = term.feed("\x1b[200~/help");+ try std.testing.expect(term.model.pasting);+ _ = term.press(.enter);+ try std.testing.expect(term.model.pasting);+ // Escape is the in-band hatch: it breaks the latch instead of vanishing.+ _ = term.press(.escape);+ try std.testing.expect(!term.model.pasting);+ try std.testing.expect(!key_mod.inPaste());+ // ...and the composer works again: Tab moves focus, Escape reaches esc().+ _ = term.press(.tab);+ try std.testing.expectEqual(app.Focus.scrollback, term.model.focus);+}++test "giving up on a split paste terminator closes the paste, tail and all (#532)" {+ var term: Term = undefined;+ term.init(std.testing.allocator, 80, 24);+ defer term.deinit();+ _ = term.feed("\x1b[200~hello");+ _ = term.feed("\x1b[201");+ try std.testing.expect(key_mod.inPaste());+ term.stallDropPending(); // the loop waited the marker out+ try std.testing.expect(!key_mod.inPaste());+ try std.testing.expect(!term.model.pasting);+ // The late `~` rejoins its carried head instead of typing itself.+ _ = term.feed("~");+ try std.testing.expectEqualStrings("hello", term.model.input.getValue());+}