graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(tui): worker activity lines wait for the foreground's line boundary
justrach7940bbd60abf
diff --git a/src/agent.zig b/src/agent.zigindex 3fe221e7..9b9f96ec 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -24,6 +24,7 @@ const models_cache = @import("models_cache.zig");const keys_cli = @import("keys_cli.zig");const run_budget_mod = @import("run_budget.zig");const protocol_seq = @import("protocol_seq.zig"); // #330: monotonic `seq` on every --json event+const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundary// prompt_ui (agent_prompt.zig) owns the width-budgeted status line (#209,// 600-line goal); prompt() is member-aliased back onto Agent below.@@ -212,11 +213,37 @@ pub const Agent = struct {if (self.out) |w| {try w.print(fmt, args);try w.flush();+ // The root just ended a row: anything a child offered mid-stream+ // may land now (#tui-tick).+ if (!self.sub and !main_mod.json_mode and comptime endsLine(fmt)) _ = tick_gate.setLineStart(true);} else {- std.debug.print(" [{s}] " ++ fmt, .{self.label} ++ args);+ // A pool-thread child has no writer: its activity line goes to+ // stderr THROUGH the gate, so it lands at a line boundary the root+ // has published rather than mid-row (#tui-tick).+ var buf: [tick_gate.slot_bytes]u8 = undefined;+ var sink = Io.Writer.fixed(&buf);+ const fit = if (sink.print(" [{s}] " ++ fmt, .{self.label} ++ args)) |_| true else |_| false;+ var line = sink.buffered();+ // Over-long (an uncapped provider error) means the fixed sink cut+ // the text and ate the trailing newline. The gate cannot repair+ // that — the cut exactly fills a slot, so its own guard never fires+ // — and a line that does not end its row splices the next worker+ // line onto it mid-column, which is the reported artifact. End it.+ if (!fit or line.len == 0 or line[line.len - 1] != '\n') {+ // usize, not @min's narrowed comptime-derived type: at + 1 == buf.len.+ const at: usize = @min(line.len, buf.len - 1); // append, or overwrite the last byte+ buf[at] = '\n';+ line = buf[0 .. at + 1];+ }+ tick_gate.workerLine(line);}}+ /// Comptime: does this say() format end a terminal row?+ fn endsLine(comptime fmt: []const u8) bool {+ return fmt.len > 0 and fmt[fmt.len - 1] == '\n';+ }+/// Report an API error: remember the formatted message so the --json/// `error` event can carry the detail, then print it like say().pub fn sayApiError(self: *Agent, comptime fmt: []const u8, args: anytype) !void {@@ -565,3 +592,7 @@ test {_ = @import("agent_prompt.zig");try agent_tests.lazyRootTools(Agent);}++test "say: an over-long worker line still ends its row (#tui-tick)" {+ try agent_tests.workerLineAlwaysEndsRow(Agent);+}diff --git a/src/agent_render.zig b/src/agent_render.zigindex 5cc872a8..9667b120 100644--- a/src/agent_render.zig+++ b/src/agent_render.zig@@ -19,6 +19,8 @@ const style = &ansi.style;const terminal = @import("term.zig");const termCols = terminal.termCols;+const tick_gate = @import("tick_gate.zig"); // #tui-tick: subagent ticks land at line boundaries+// isTableSeparator lives in agent_table.zig; reached through the Agent// struct's member alias.const isTableSeparator = Agent.isTableSeparator;@@ -39,6 +41,18 @@ pub fn streamMarkdown(self: *Agent, text: []const u8) void {const w = self.out orelse return;for (text) |b| self.mdByte(w, b);w.flush() catch {};+ // Only now, with the delta actually on the terminal, may a parallel+ // child's activity line through — and only if this delta ended a row+ // (#tui-tick). Subagents render no markdown, so this is the root's stream.+ if (!self.sub and !main_mod.json_mode) _ = tick_gate.setLineStart(atLineStart(self));+}++/// True when the renderer has nothing painted on the current row: it committed+/// its last line with a newline and holds no prefix. A still-held/classifying+/// line has printed nothing yet but counts as mid-line anyway — a tick delayed+/// by one line is harmless, a tick inside a word is the bug.+pub fn atLineStart(self: *const Agent) bool {+ return self.md_kind == .classify and self.md_buf.items.len == 0 and self.md_word.items.len == 0;}pub const MdKind = enum { classify, hold, prose, header, fenced };diff --git a/src/agent_stream.zig b/src/agent_stream.zigindex 856254d2..7bc5eebb 100644--- a/src/agent_stream.zig+++ b/src/agent_stream.zig@@ -23,6 +23,7 @@ const Agent = agent_mod.Agent;const style = &@import("ansi.zig").style;const anim = @import("anim.zig");+const tick_gate = @import("tick_gate.zig"); // #tui-tick: child ticks wait for a foreground line boundaryconst terminal = @import("term.zig");const tty = terminal.tty;@@ -116,6 +117,10 @@ pub fn streamThinking(self: *Agent, chunk: []const u8) void {self.thinking_rows = 1; // the header newline already moved us down one lineself.thinking_col = 0;self.thinking_overflow = false;+ // The block owns every row below this one and collapses them by cursor+ // math — a child's tick printed inside it would be erased with the+ // block (or shift the erase onto real output). Hold until it closes.+ tick_gate.hold();}self.thinking_text.appendSlice(self.gpa, chunk) catch {};if (self.thinking_folded) return; // folded: buffer only, don't draw the live block@@ -142,6 +147,7 @@ pub fn closeThinkingBlock(self: *Agent) void {w.print("{s}\n{s}✓ Thought{s}\n\n", .{ style.reset, style.dim, style.reset }) catch return;}w.flush() catch return;+ _ = tick_gate.setLineStart(true); // both branches end at column 0 — held ticks land here (#tui-tick)}/// Ctrl-T: fold/unfold the live "Thinking" block in place (#92/#85). Only@@ -210,23 +216,18 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []consself.md_table.clearRetainingCapacity();self.partial_text.clearRetainingCapacity(); // fresh Esc-interrupt capture- // Esc-interrupt: while the root's request is on a TTY, stdin sits in- // raw non-blocking no-echo mode — from *before* the connect, so Esc- // pressed during a slow time-to-first-token wait neither echoes ^[- // nor leaks into the next prompt. Polled between SSE lines; leftover- // bytes are drained before canonical mode returns, so gate prompts- // and the line editor see a clean tty.+ // Esc-interrupt: while the root's request is on a TTY, stdin sits in raw+ // non-blocking no-echo mode — from *before* the connect, so Esc pressed+ // during a slow time-to-first-token wait neither echoes ^[ nor leaks into+ // the next prompt. Polled between SSE lines; leftover bytes are drained+ // before canonical mode returns, so gate prompts and the line editor see a+ // clean tty. SGR mouse reporting is deliberately NOT enabled: grabbing the+ // mouse (\x1b[?1000;1006h) forwards wheel events to us instead of letting+ // the terminal scroll its own scrollback — native scroll wins, and Ctrl-T+ // still folds the live Thinking block (escPressed).const watch_esc = !self.sub and self.in != null and main_mod.use_color and !main_mod.json_mode;var orig_tio: ?tty.RawState = null;- if (watch_esc) {- orig_tio = rawNonblockStdin();- // SGR mouse reporting is intentionally NOT enabled. Grabbing the mouse- // (\x1b[?1000;1006h) makes the terminal forward wheel events to us instead- // of scrolling its own scrollback, so scrolling up mid-stream got captured- // as input. Leaving the mouse to the terminal keeps native scroll — parity- // with Claude Code. The live Thinking block still folds via Ctrl-T (see- // escPressed); its SGR click-to-fold path stays wired but dormant.- }+ if (watch_esc) orig_tio = rawNonblockStdin();defer if (orig_tio) |o| {_ = drainSteerStdin(true);tty.restore(o);@@ -302,9 +303,8 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []consconst status_code = @intFromEnum(response.head.status);if (status_code == 429 or status_code >= 500) {http.captureRetryAfter(&response); // #retry-after: honor the provider's requested backoff- // Drain a snippet of the error body so the retry message can- // surface the gateway's diagnostic (e.g. "upstream timeout")- // instead of a bare "server error (5xx)".+ // Drain a snippet of the error body so the retry message surfaces the+ // gateway's diagnostic instead of a bare "server error (5xx)".capture5xxBodyStream(self.gpa, &response);if (req.connection) |conn| conn.closing = true;return if (status_code == 429) error.RateLimited else error.ServerError;@@ -423,15 +423,13 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []consmain_mod.g_thinking_fold_request = false;self.toggleThinkingFold();}- // Logical stream terminator: once the provider's final event- // ([DONE] / response.completed / message_stop) has landed in `full`,- // the response is complete — stop instead of waiting for the socket to- // close. Some gateways hold the connection open (or reset it) after the- // last event, which otherwise trips the 120s idle-stall watchdog or a- // spurious retry on an already-complete response (#134/#135).- // #133: a finish_reason chunk means the response is complete even if the- // provider never sends [DONE] — record it so a subsequent close counts- // as a clean end, but keep reading so a trailing usage chunk still lands.+ // Logical stream terminator: once the provider's final event ([DONE] /+ // response.completed / message_stop) lands in `full` the response is+ // complete — stop instead of waiting for a socket some gateways hold+ // open (or reset), which otherwise trips the 120s idle-stall watchdog or+ // a spurious retry on an already-complete response (#134/#135). #133: a+ // finish_reason chunk completes the response even without [DONE] — note+ // it so a later close is clean, but keep reading for a usage chunk.if (self.provider.kind == .openai and openaiComplete(line.writer.buffered())) saw_done = true;if (isStreamEnd(self.scratchAlloc(), self.provider.kind, line.writer.buffered())) { // #124: parse tree is a transient bool checksaw_done = true; // #133: the provider's terminal event landed — a later close is clean@@ -455,6 +453,7 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []consif (!main_mod.json_mode and self.streamed_text) if (self.out) |w| {w.writeAll("\n") catch {};w.flush() catch {};+ _ = tick_gate.setLineStart(true); // answer is off the wire: release held child ticks (#tui-tick)};return full.toOwnedSlice();}@@ -596,5 +595,6 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {} else {w.writeAll(text) catch return;w.flush() catch return;+ if (!self.sub) _ = tick_gate.setLineStart(text[text.len - 1] == '\n'); // #tui-tick}}diff --git a/src/agent_tests.zig b/src/agent_tests.zigindex 687669bd..3dd57eb7 100644--- a/src/agent_tests.zig+++ b/src/agent_tests.zig@@ -2,6 +2,47 @@const std = @import("std");const mcp = @import("mcp.zig");+const tick_gate = @import("tick_gate.zig");++/// #tui-tick: Agent.say's worker branch formats into one slot-sized fixed+/// buffer, so an argument longer than the slot (an uncapped provider error)+/// overflows it — the sink cuts the text and eats the trailing newline. The+/// bytes handed to the gate must still end their row, or the next worker line+/// released after this one starts mid-column: the reported interleave.+pub fn workerLineAlwaysEndsRow(comptime Agent: type) !void {+ const gpa = std.testing.allocator;+ var huge_buf: [tick_gate.slot_bytes + 64]u8 = @splat('x');+ const huge: []const u8 = &huge_buf;++ var agent: Agent = undefined;+ agent.out = null; // a pool-thread child has no writer: the worker branch+ agent.sub = true;+ agent.label = "Review Python hot path";++ tick_gate.hold(); // foreground mid-row, so the gate keeps what say() offers+ defer _ = tick_gate.setLineStart(true); // leave the global gate as we found it+ try agent.say("{s}\n", .{huge});++ var buf: [tick_gate.slot_bytes]u8 = undefined;+ const n = tick_gate.g_gate.take(&buf) orelse return error.WorkerLineNotOffered;+ try std.testing.expect(n > 0 and n <= tick_gate.slot_bytes);+ try std.testing.expect(n < huge.len); // it really was cut+ try std.testing.expectEqual(@as(u8, '\n'), buf[n - 1]);++ // …so a second tick released after it starts its own row.+ const tick2 = " [w] ⚙ bash {}\n";+ var gate: tick_gate.Gate = .{};+ gate.noteForeground("guard `if (buf.len - ");+ try std.testing.expect(gate.offer(buf[0..n]));+ try std.testing.expect(gate.offer(tick2));+ gate.noteForeground("\n");+ var screen: std.ArrayList(u8) = .empty;+ defer screen.deinit(gpa);+ var slot: [tick_gate.slot_bytes]u8 = undefined;+ while (gate.take(&slot)) |m| try screen.appendSlice(gpa, slot[0..m]);+ const at = std.mem.indexOf(u8, screen.items, tick2).?;+ try std.testing.expect(at > 0 and screen.items[at - 1] == '\n');+}pub fn lazyRootTools(comptime Agent: type) !void {var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);diff --git a/src/cards.zig b/src/cards.zigindex 38d34695..0803a4d6 100644--- a/src/cards.zig+++ b/src/cards.zig@@ -20,6 +20,9 @@ const root = @import("main.zig");const util = @import("util.zig");const utf8Prefix = util.utf8Prefix;+// #tui-tick: cards go through the line-boundary gate, not straight to stderr.+const tick_gate = @import("tick_gate.zig");+// ── Subagent cards (#51) ───────────────────────────────────────────────────//// When the model fans out parallel subagents (several `subagent` calls in one@@ -31,9 +34,12 @@ const utf8Prefix = util.utf8Prefix;// run can be inspected from the terminal (the card prints the inspect: path).//// The cards are append-only and each card is built as one string then handed-// to a single std.debug.print (std serializes the stderr mutex), so parallel-// children never interleave mid-card. Box width is clamped to the terminal so-// narrow terminals degrade to a readable column. Execution is unchanged.+// to tick_gate.workerLine — one std.debug.print (std serializes the stderr+// mutex) so parallel children never interleave mid-card, deferred until the+// foreground stream's last published position is a line boundary (flush+// granularity — see tick_gate.zig's module doc for what that does and does not+// guarantee, #tui-tick). Box width is clamped to the terminal so narrow+// terminals degrade to a readable column. Execution is unchanged./// Monotonic counter feeding the per-subagent ordinal in its stable id.pub var g_subagent_seq: std.atomic.Value(u32) = .init(0);@@ -83,7 +89,7 @@ pub fn subagentLaunchCard(arena: Allocator, id: []const u8, sprite: []const u8,boxRule(w, inner, .top);boxLine(w, inner, if (root.use_color) "▸ " else "> ", activity);boxRule(w, inner, .bottom);- std.debug.print("{s}", .{aw.writer.buffered()});+ tick_gate.workerLine(aw.writer.buffered());}/// Render the completion card: status, elapsed, tools, and the inspect: path.@@ -111,7 +117,7 @@ pub fn subagentDoneCard(arena: Allocator, id: []const u8, sprite: []const u8, laif (detail_path) |p|boxLine(w, inner, bullet, std.fmt.allocPrint(arena, "inspect: {s}", .{p}) catch p);boxRule(w, inner, .bottom);- std.debug.print("{s}", .{aw.writer.buffered()});+ tick_gate.workerLine(aw.writer.buffered());}const BoxEdge = enum { top, bottom };@@ -216,6 +222,9 @@ pub fn writeSubagentDetail(Io.Dir.cwd().writeFile(io, .{ .sub_path = path, .data = aw.writer.buffered() }) catch return null;return path;}+test { // the gate's own tests only run when something references the module+ _ = tick_gate;+}test "subagentId: stable shape, ordinal-prefixed, hash-suffixed (#51)" {var a: [40]u8 = undefined;var b: [40]u8 = undefined;diff --git a/src/tick_gate.zig b/src/tick_gate.zignew file mode 100644index 00000000..b5d97b30--- /dev/null+++ b/src/tick_gate.zig@@ -0,0 +1,261 @@+//! Line-boundary gate for parallel-subagent activity output (#tui-tick).+//!+//! Parallel children run on pool threads with no stdout of their own and log+//! through std.debug.print, which locks stderr — so every worker line is atomic+//! on its own. The ROOT agent streams its answer to stdout a token at a time,+//! and nothing tied the two together: a tick arriving between two deltas landed+//! wherever the cursor happened to be, which in a real fleet run was inside a+//! half-written word —+//!+//! guard `if (buf.len - [Review Python hot path] ⚙ bash {…} pos < 2…`+//!+//! This module is the missing rendezvous. The foreground stream publishes+//! whether it is mid-line after every flushed delta (setLineStart / hold); a+//! worker line offered while it is mid-line is HELD and printed the moment that+//! line completes. Bounded by construction: `max_pending` slots of `slot_bytes`+//! each, drop-oldest plus a count marker when a flood outruns the stream, and+//! no allocation anywhere on the path.+//!+//! The guarantee, precisely: no worker line is emitted while the foreground's+//! last PUBLISHED position is mid-row, and every held line and every cut line+//! ends in a newline, so released ticks each own whole rows. That is flush+//! granularity, not word granularity — the position is published only after a+//! flush, so a tick offered in the window between the foreground writing bytes+//! and publishing the new position still lands wherever the cursor is. Deltas+//! publish per flushed chunk, so that window is one delta wide; the reported+//! artifact was a tick landing between deltas, and that is what this closes.+//!+//! TUI only. In --json mode stdout is a strict JSONL transport that children+//! never share (they emit structured events), so workerLine keeps the old+//! direct stderr write and the gate stays out of the way.++const std = @import("std");+const root = @import("main.zig"); // live json_mode toggle++/// Held lines. Small on purpose: a fleet that outruns the stream should show+/// its newest activity, not replay a backlog once the line finally ends.+pub const max_pending = 6;+/// Per-slot capacity. A launch/done card (box rules + rows + SGR) is the widest+/// realistic tick at well under 1 KiB; longer text is cut, never spilled.+pub const slot_bytes = 2048;++/// The pure line-boundary rule — no I/O, no globals, so the interleave the bug+/// report describes can be unit-tested directly.+pub const Gate = struct {+ /// True when the foreground stream has painted part of a row that has not+ /// ended yet. Nothing may be injected in that state.+ mid_line: bool = false,+ slots: [max_pending][slot_bytes]u8 = undefined,+ lens: [max_pending]u16 = @splat(0),+ head: usize = 0, // oldest held slot+ count: usize = 0,+ dropped: u32 = 0,++ /// The foreground just wrote `bytes` (already flushed): it is mid-line+ /// unless that write ended one. An empty write says nothing.+ pub fn noteForeground(self: *Gate, bytes: []const u8) void {+ if (bytes.len == 0) return;+ self.mid_line = bytes[bytes.len - 1] != '\n';+ }++ /// Offer one worker line (newline-terminated). Returns true when the gate+ /// took it — the caller must NOT print. False means the foreground is at a+ /// line boundary and the caller prints immediately, exactly as before.+ pub fn offer(self: *Gate, text: []const u8) bool {+ if (!self.mid_line or text.len == 0) return false;+ if (self.count == max_pending) { // flooded: drop the oldest, count it+ self.head = (self.head + 1) % max_pending;+ self.count -= 1;+ self.dropped +|= 1;+ }+ const i = (self.head + self.count) % max_pending;+ const n = @min(text.len, slot_bytes);+ @memcpy(self.slots[i][0..n], text[0..n]);+ // A cut line still has to end its row, or the release after it starts+ // mid-column and reintroduces the very bug this gate exists to stop.+ if (n < text.len and self.slots[i][n - 1] != '\n') self.slots[i][n - 1] = '\n';+ self.lens[i] = @intCast(n);+ self.count += 1;+ return true;+ }++ /// Copy the oldest held line into `buf` (must be >= slot_bytes) and drop+ /// it, so the caller can print without holding the lock. Null when empty.+ pub fn take(self: *Gate, buf: []u8) ?usize {+ if (self.count == 0) return null;+ const n = self.lens[self.head];+ @memcpy(buf[0..n], self.slots[self.head][0..n]);+ self.head = (self.head + 1) % max_pending;+ self.count -= 1;+ return n;+ }++ /// Lines discarded since the last report; reading clears the counter.+ pub fn takeDropped(self: *Gate) u32 {+ defer self.dropped = 0;+ return self.dropped;+ }+};++/// The process-wide gate. pub only so agent_tests.zig can drive the real+/// workerLine path and inspect what a worker actually handed over.+pub var g_gate: Gate = .{};+var g_lock: std.atomic.Value(bool) = .init(false);++/// Spin-lock, same shape (and reasoning) as repl_glue.steerLock: pool threads+/// offering and the foreground releasing hold it only for a memcpy-sized+/// critical section, never across a print, so it stays uncontended and needs no+/// Io handle — cards.zig and the io-less render path could not reach one.+fn lock() void {+ while (g_lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();+}+fn unlock() void {+ g_lock.store(false, .release);+}++/// A pool-thread worker wants `text` (whole, newline-terminated lines) on the+/// terminal: printed now at a foreground line boundary, held otherwise.+pub fn workerLine(text: []const u8) void {+ if (root.json_mode) return std.debug.print("{s}", .{text});+ lock();+ const held = g_gate.offer(text);+ unlock();+ if (!held) std.debug.print("{s}", .{text});+}++/// Publish the foreground stream's position and release everything held once it+/// is back at column 0. Returns the number of physical lines released, so a+/// caller doing cursor math over its own rows can account for them.+pub fn setLineStart(at_bol: bool) usize {+ lock();+ g_gate.mid_line = !at_bol;+ unlock();+ return release();+}++/// Hold worker lines until the next setLineStart(true). For foreground output+/// that owns the rows below the cursor — the live "Thinking" block collapses by+/// cursor math, so a tick printed inside it would be erased with the block.+pub fn hold() void {+ lock();+ g_gate.mid_line = true;+ unlock();+}++fn release() usize {+ var lines: usize = 0;+ var buf: [slot_bytes]u8 = undefined;+ while (true) {+ lock();+ if (g_gate.mid_line) {+ unlock();+ return lines;+ }+ const took = g_gate.take(&buf);+ const dropped = if (took == null) g_gate.takeDropped() else 0;+ unlock();+ if (took) |n| {+ std.debug.print("{s}", .{buf[0..n]});+ for (buf[0..n]) |c| {+ if (c == '\n') lines += 1;+ }+ continue;+ }+ if (dropped > 0) {+ std.debug.print(" [·] {d} subagent line(s) dropped while the answer streamed\n", .{dropped});+ lines += 1;+ }+ return lines;+ }+}++test "tick gate: a tick offered mid-line waits for the newline (#tui-tick)" {+ var gate: Gate = .{};+ var buf: [slot_bytes]u8 = undefined;+ // Foreground painted part of a row.+ gate.noteForeground("guard `if (buf.len - ");+ try std.testing.expect(gate.mid_line);+ // A worker tick arrives right there: held, not printed.+ try std.testing.expect(gate.offer(" [Review Python hot path] ⚙ bash {}\n"));+ try std.testing.expect(gate.mid_line);+ // Still mid-line: the foreground continues its row, the tick keeps waiting.+ gate.noteForeground("pos < 2)`");+ try std.testing.expect(gate.mid_line);+ // The row ends — now it may land.+ gate.noteForeground("\n");+ try std.testing.expect(!gate.mid_line);+ const n = gate.take(&buf).?;+ try std.testing.expectEqualStrings(" [Review Python hot path] ⚙ bash {}\n", buf[0..n]);+ try std.testing.expect(gate.take(&buf) == null);+}++test "tick gate: at a line boundary the worker prints immediately" {+ var gate: Gate = .{};+ try std.testing.expect(!gate.mid_line); // fresh gate starts at column 0+ try std.testing.expect(!gate.offer(" [w] ⚙ read_file {}\n")); // caller prints+ gate.noteForeground("a full line\n");+ try std.testing.expect(!gate.offer(" [w] ⚙ read_file {}\n"));+ var buf: [slot_bytes]u8 = undefined;+ try std.testing.expect(gate.take(&buf) == null); // nothing was buffered+}++test "tick gate: a flood drops the oldest and counts it, order is FIFO" {+ var gate: Gate = .{};+ var buf: [slot_bytes]u8 = undefined;+ gate.noteForeground("mid");+ var i: usize = 0;+ while (i < max_pending + 2) : (i += 1) {+ var line: [16]u8 = undefined;+ try std.testing.expect(gate.offer(std.fmt.bufPrint(&line, "tick {d}\n", .{i}) catch unreachable));+ }+ try std.testing.expectEqual(@as(u32, 2), gate.dropped); // two oldest evicted+ gate.noteForeground("\n");+ // Survivors drain oldest-first, starting after the two that were dropped.+ i = 2;+ while (gate.take(&buf)) |n| : (i += 1) {+ var want: [16]u8 = undefined;+ try std.testing.expectEqualStrings(std.fmt.bufPrint(&want, "tick {d}\n", .{i}) catch unreachable, buf[0..n]);+ }+ try std.testing.expectEqual(@as(usize, max_pending + 2), i);+ try std.testing.expectEqual(@as(u32, 2), gate.takeDropped());+ try std.testing.expectEqual(@as(u32, 0), gate.takeDropped()); // reading clears it+}++test "tick gate: an oversized tick is cut but still ends its row" {+ var gate: Gate = .{};+ var buf: [slot_bytes]u8 = undefined;+ var big: [slot_bytes + 64]u8 = @splat('x');+ big[big.len - 1] = '\n';+ gate.noteForeground("mid");+ try std.testing.expect(gate.offer(&big));+ gate.noteForeground("\n");+ const n = gate.take(&buf).?;+ try std.testing.expectEqual(@as(usize, slot_bytes), n);+ try std.testing.expectEqual(@as(u8, '\n'), buf[n - 1]); // never leaves the cursor mid-row+}++test "tick gate: the reported mid-word injection cannot happen (#tui-tick)" {+ const gpa = std.testing.allocator;+ var screen: std.ArrayList(u8) = .empty;+ defer screen.deinit(gpa);+ var gate: Gate = .{};+ var buf: [slot_bytes]u8 = undefined;+ const tick = " [Review Python hot path] ⚙ bash {\"cmd\":\"pytest\"}\n";+ // The transcript's own deltas: the tick arrives after the first one, i.e.+ // exactly where the user saw it land inside the word.+ const deltas = [_][]const u8{ "guard `if (buf.len - ", "pos < 2)` fails\n", "next paragraph\n" };+ for (deltas, 0..) |d, i| {+ try screen.appendSlice(gpa, d);+ gate.noteForeground(d);+ if (i == 0 and !gate.offer(tick)) try screen.appendSlice(gpa, tick);+ while (!gate.mid_line) {+ const n = gate.take(&buf) orelse break;+ try screen.appendSlice(gpa, buf[0..n]);+ }+ }+ // The answer text is intact…+ try std.testing.expect(std.mem.indexOf(u8, screen.items, "guard `if (buf.len - pos < 2)` fails") != null);+ // …and the tick starts its own row instead of splitting a word.+ const at = std.mem.indexOf(u8, screen.items, tick).?;+ try std.testing.expect(at > 0 and screen.items[at - 1] == '\n');+}