Skip to content

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

Python

feat(tui): consume the engine's typed events instead of scraping rendered text

Rach Pradhanc64bea1dec86
diff --git a/TUI/app.zig b/TUI/app.zig
index 4f785bec..64426805 100644
--- a/TUI/app.zig
+++ b/TUI/app.zig
@@ -14,10 +14,31 @@ pub const AgentMode = enum { normal, plan, always_approve };
pub const EscArm = enum { none, clear, rewind };
pub const EntryKind = enum { user, assistant, tool, system, err, pending };
+/// A tool row's payload, straight off the engine's ToolInvocation /
+/// ToolOutcome / ToolRejection (#551). Rendering reads these FIELDS; nothing
+/// re-derives them by splitting a rendered line on a glyph or on " | ".
+pub const ToolInfo = struct {
+ /// The engine's tool name, verbatim. Classification (mcp / search) tests
+ /// this, never the whole row.
+ name: []const u8,
+ /// Argument preview on a call, result preview on an outcome.
+ detail: []const u8 = "",
+ /// false = the call was announced, true = it returned (or was refused).
+ done: bool = false,
+ is_error: bool = false,
+ /// Refused by the harness before it ran.
+ denied: bool = false,
+};
+
pub const Entry = struct {
kind: EntryKind,
text: []const u8,
folded: bool = false,
+ /// Non-null on every `.tool` row a live turn produces. Null on a legacy
+ /// `.tool` row restored from a session written before the typed contract —
+ /// those still render from `text` alone (see scrollback.zig), which is the
+ /// whole reason this is optional rather than required.
+ tool: ?ToolInfo = null,
};
pub const Effect = enum { stay, quit, background };
@@ -64,6 +85,10 @@ pub const Model = struct {
goal: ?[]const u8 = null,
session_name: ?[]const u8 = null,
+ /// Owns the string `engine.g_model_name` points at after a mid-turn
+ /// provider failover (#551): the event that carried it is freed as soon as
+ /// the drain that delivered it returns.
+ model_override: ?[]const u8 = null,
scroll: usize = 0,
selected: usize = 0,
turns: usize = 0,
@@ -126,7 +151,7 @@ pub const Model = struct {
if (self.bg) |op| {
if (!op.threaded or op.done.load(.acquire)) @import("bgop.zig").reap(self) else self.bg = null;
}
- for (self.history.items) |e| self.alloc.free(e.text);
+ for (self.history.items) |e| self.freeEntry(e);
self.history.deinit();
for (self.prompt_hist.items) |s| self.alloc.free(s);
self.prompt_hist.deinit();
@@ -136,6 +161,12 @@ pub const Model = struct {
self.images.deinit();
if (self.goal) |g| self.alloc.free(g);
if (self.session_name) |s| self.alloc.free(s);
+ if (self.model_override) |m| {
+ // The global points into this buffer; drop it before the free so a
+ // late reader cannot follow a dangling slice.
+ if (engine.g_model_name.ptr == m.ptr) engine.g_model_name = "";
+ self.alloc.free(m);
+ }
if (self.overlay_filter.len > 0) self.alloc.free(self.overlay_filter);
if (self.files_cache) |f| self.alloc.free(f);
if (self.sel_text.len > 0) self.alloc.free(self.sel_text);
@@ -148,6 +179,7 @@ pub const Model = struct {
for (job.history) |t| self.alloc.free(t.text);
self.alloc.free(job.history);
if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);
+ job.events.deinit();
self.alloc.destroy(job);
self.pending = null;
}
@@ -167,6 +199,44 @@ pub const Model = struct {
}
}
+ /// Append a FIELD-BACKED tool row (#551). `name`/`detail` come from the
+ /// engine's typed event and are copied here; `text` is kept only as the
+ /// plain fallback the non-rendering readers use (sticky header, selection
+ /// copy, session persistence), never as the thing rendering parses.
+ pub fn pushTool(self: *Model, info: ToolInfo) !void {
+ const name = try self.alloc.dupe(u8, info.name);
+ errdefer self.alloc.free(name);
+ const detail = try sanitized(self.alloc, info.detail);
+ errdefer self.alloc.free(detail);
+ const text = if (detail.len > 0)
+ try std.fmt.allocPrint(self.alloc, "{s} {s}", .{ name, detail })
+ else
+ try self.alloc.dupe(u8, name);
+ errdefer self.alloc.free(text);
+ try self.history.append(.{
+ .kind = .tool,
+ .text = text,
+ .folded = true,
+ .tool = .{
+ .name = name,
+ .detail = detail,
+ .done = info.done,
+ .is_error = info.is_error,
+ .denied = info.denied,
+ },
+ });
+ }
+
+ /// Release everything an entry owns. Tool rows own two extra strings, so
+ /// freeing `text` alone leaks them.
+ pub fn freeEntry(self: *Model, e: Entry) void {
+ self.alloc.free(e.text);
+ if (e.tool) |t| {
+ self.alloc.free(t.name);
+ self.alloc.free(t.detail);
+ }
+ }
+
pub fn pushFmt(self: *Model, kind: EntryKind, comptime fmt: []const u8, args: anytype) !void {
const raw = try std.fmt.allocPrint(self.alloc, fmt, args);
defer self.alloc.free(raw);
@@ -181,7 +251,7 @@ pub const Model = struct {
}
pub fn clearHistory(self: *Model) void {
- for (self.history.items) |e| self.alloc.free(e.text);
+ for (self.history.items) |e| self.freeEntry(e);
self.history.clearRetainingCapacity();
self.turns = 0;
self.chars_in = 0;
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 937b58ec..2ca7b6d5 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -262,7 +262,7 @@ pub fn rewind(self: *Model) void {
return;
}
var j = self.history.items.len;
- while (j > i - 1) : (j -= 1) self.alloc.free(self.history.items[j - 1].text);
+ while (j > i - 1) : (j -= 1) self.freeEntry(self.history.items[j - 1]);
self.history.shrinkRetainingCapacity(i - 1);
self.push(.system, "rewound the last turn") catch {};
}
diff --git a/TUI/engine.zig b/TUI/engine.zig
index 847cb3d5..e332b7d4 100644
--- a/TUI/engine.zig
+++ b/TUI/engine.zig
@@ -3,6 +3,12 @@
const std = @import("std");
+const events_mod = @import("events.zig");
+
+pub const Event = events_mod.Event;
+pub const EventQueue = events_mod.Queue;
+pub const ToolEvent = events_mod.Tool;
+
pub const Effort = enum { low, medium, high, xhigh, max, ultra };
pub const Turn = struct {
@@ -40,7 +46,12 @@ pub const StreamBuf = struct {
}
};
-pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf) ?[]const u8;
+/// A turn backend gets the live text buffer AND the typed event queue (#551):
+/// prose streams into `stream` for the pending row's tail view, while every
+/// structured moment (tool call, outcome, refusal, notice, failover) is PUSHED
+/// as an event. The TUI used to recover the second kind by parsing the first,
+/// which is the defect this seam removes.
+pub const TurnFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, history: []const Turn, params: Params, stream: *StreamBuf, events: *events_mod.Queue) ?[]const u8;
pub const ModelFn = *const fn (turn_ctx: ?*anyopaque, gpa: std.mem.Allocator, name: []const u8) ?[]const u8;
pub const CancelFn = *const fn (turn_ctx: ?*anyopaque) void;
/// Fill dest with a staged image path (return >0) or an error line (return <0).
@@ -69,6 +80,10 @@ pub const Job = struct {
history: []Turn,
params: Params,
stream: StreamBuf,
+ /// Typed engine events for this turn (#551). Attached to the model's
+ /// allocator by startJob; a Job literal that leaves it unattached simply
+ /// carries no events.
+ events: events_mod.Queue = .{},
};
/// A background engine op: `/compact`, `!cmd`, or the @-file list. Same
@@ -130,7 +145,7 @@ pub var g_models: []const u8 = "";
pub var g_cwd: []const u8 = ".";
pub fn jobRun(job: *Job) void {
- const reply = if (g_turn_fn) |f| f(g_turn_ctx, job.gpa, job.history, job.params, &job.stream) else null;
+ const reply = if (g_turn_fn) |f| f(g_turn_ctx, job.gpa, job.history, job.params, &job.stream, &job.events) else null;
job.result = reply;
job.done.store(true, .release);
}
diff --git a/TUI/events.zig b/TUI/events.zig
new file mode 100644
index 00000000..86d58cdb
--- /dev/null
+++ b/TUI/events.zig
@@ -0,0 +1,234 @@
+//! The typed engine-event channel the TUI consumes (#551, the #422 epic).
+//!
+//! Before this file the TUI learned what the engine did by SCANNING the sink's
+//! own rendered bytes: turn.zig matched "⚙ /✓ /✗ /⊘ " line prefixes out of the
+//! live stream and scrollback.zig re-derived the tool's name, status, argument
+//! and preview by splitting that line on the glyph, ' ' and ' | '. Both were
+//! guesses about formatting rather than knowledge about the run, and both were
+//! wrong in the obvious ways: an assistant answer whose line began "✓ " became
+//! a phantom tool row, and a command containing " | " was mis-titled.
+//!
+//! Now the engine hands over typed events and this queue carries them across
+//! the turn thread. Growth rule: a new engine moment becomes a new variant with
+//! the FIELDS a frontend needs, never a pre-rendered string that a reader has
+//! to take apart again.
+//!
+//! The package stays frontend-agnostic (it never imports the harness), so this
+//! is a projection of src/engine_events.zig, not that union itself; the
+//! translation lives in src/tui_sink.zig, which is the only place that knows
+//! both vocabularies.
+
+const std = @import("std");
+
+/// One tool moment, as a row can render it without parsing anything.
+pub const Tool = struct {
+ /// The engine's tool name, verbatim ("bash", "read_file",
+ /// "mcp__codedbpro__read"). Classification reads THIS, never a rendered
+ /// line: `isMcp` is a prefix test on the name, and a bash command that
+ /// happens to mention "search" is not a search.
+ name: []const u8,
+ /// A one-line argument preview (on a call) or result preview (on an
+ /// outcome). Already first-lined and capped by the emitter.
+ detail: []const u8 = "",
+ is_error: bool = false,
+ /// The harness refused the call before it ran (tool_rejected).
+ denied: bool = false,
+};
+
+pub const Event = union(enum) {
+ /// A tool call cleared the gates and is running (ToolInvocation).
+ tool_started: Tool,
+ /// It returned (ToolOutcome). `is_error` is the engine's verdict.
+ tool_finished: Tool,
+ /// The harness refused it before it ran (ToolRejection) — a moment the
+ /// TUI had no way to see at all before this file existed.
+ tool_rejected: Tool,
+ /// One operational line about the session (session_notice) -> system row.
+ notice: []const u8,
+ /// The active provider failed over mid-turn (provider_fallback).
+ model_changed: []const u8,
+};
+
+/// Lock-guarded SPSC-shaped hand-off: the turn thread (and the parallel tool
+/// pool behind it) pushes, the render loop drains at its existing poll points.
+///
+/// Allocation discipline: engine payloads point into the per-turn arena that
+/// dies with the turn, so `push` COPIES every string into this queue's own
+/// gpa and `drain` hands that ownership to the caller. The queue is bounded —
+/// a turn that outruns the render loop drops events and counts them rather
+/// than growing without limit.
+pub const Queue = struct {
+ /// Bounded so a runaway turn cannot grow the queue without limit. ~4k
+ /// events is far more tool activity than one turn produces.
+ pub const cap: usize = 4096;
+
+ /// Spin lock rather than a mutex: this zig's std has no io-less Thread
+ /// mutex, and the TUI package deliberately never takes an Io handle. The
+ /// critical sections are a dupe and an append — microseconds, never a
+ /// syscall — so it stays uncontended (the same choice repl_glue's
+ /// steerLock made for its queue).
+ lock: std.atomic.Value(bool) = std.atomic.Value(bool).init(false),
+ /// Set by the owner (turn.zig) before the turn thread starts. A queue that
+ /// was never attached drops silently — which is exactly what a Job literal
+ /// in a test that does not care about events wants.
+ gpa: ?std.mem.Allocator = null,
+ items: std.ArrayList(Event) = .empty,
+ /// Events refused because the queue was full or a copy failed. Surfaced
+ /// rather than swallowed: silent loss here is how a tool row goes missing.
+ dropped: usize = 0,
+
+ fn acquire(self: *Queue) void {
+ while (self.lock.cmpxchgWeak(false, true, .acquire, .monotonic) != null) std.atomic.spinLoopHint();
+ }
+
+ fn release(self: *Queue) void {
+ self.lock.store(false, .release);
+ }
+
+ pub fn attach(self: *Queue, gpa: std.mem.Allocator) void {
+ self.acquire();
+ defer self.release();
+ self.gpa = gpa;
+ }
+
+ pub fn push(self: *Queue, ev: Event) void {
+ self.acquire();
+ defer self.release();
+ const gpa = self.gpa orelse return;
+ if (self.items.items.len >= cap) {
+ self.dropped += 1;
+ return;
+ }
+ const owned = dupeEvent(gpa, ev) orelse {
+ self.dropped += 1;
+ return;
+ };
+ self.items.append(gpa, owned) catch {
+ freeEvent(gpa, owned);
+ self.dropped += 1;
+ };
+ }
+
+ /// Everything queued so far. The caller owns the slice AND every string in
+ /// it until it calls `free`.
+ pub fn drain(self: *Queue) []Event {
+ self.acquire();
+ defer self.release();
+ const gpa = self.gpa orelse return &.{};
+ return self.items.toOwnedSlice(gpa) catch &.{};
+ }
+
+ pub fn free(self: *Queue, evs: []Event) void {
+ const gpa = self.gpa orelse return;
+ for (evs) |e| freeEvent(gpa, e);
+ gpa.free(evs);
+ }
+
+ pub fn deinit(self: *Queue) void {
+ self.acquire();
+ defer self.release();
+ const gpa = self.gpa orelse return;
+ for (self.items.items) |e| freeEvent(gpa, e);
+ self.items.deinit(gpa);
+ self.items = .empty;
+ }
+};
+
+fn dupeEvent(gpa: std.mem.Allocator, ev: Event) ?Event {
+ return switch (ev) {
+ .tool_started => |t| .{ .tool_started = dupeTool(gpa, t) orelse return null },
+ .tool_finished => |t| .{ .tool_finished = dupeTool(gpa, t) orelse return null },
+ .tool_rejected => |t| .{ .tool_rejected = dupeTool(gpa, t) orelse return null },
+ .notice => |s| .{ .notice = gpa.dupe(u8, s) catch return null },
+ .model_changed => |s| .{ .model_changed = gpa.dupe(u8, s) catch return null },
+ };
+}
+
+fn freeEvent(gpa: std.mem.Allocator, ev: Event) void {
+ switch (ev) {
+ .tool_started, .tool_finished, .tool_rejected => |t| {
+ gpa.free(t.name);
+ gpa.free(t.detail);
+ },
+ .notice, .model_changed => |s| gpa.free(s),
+ }
+}
+
+fn dupeTool(gpa: std.mem.Allocator, t: Tool) ?Tool {
+ const name = gpa.dupe(u8, t.name) catch return null;
+ const detail = gpa.dupe(u8, t.detail) catch {
+ gpa.free(name);
+ return null;
+ };
+ return .{ .name = name, .detail = detail, .is_error = t.is_error, .denied = t.denied };
+}
+
+test "queue copies payloads, so an arena that dies with the turn cannot dangle" {
+ var q: Queue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ const arena = arena_state.allocator();
+ const name = try arena.dupe(u8, "mcp__codedbpro__read");
+ const detail = try arena.dupe(u8, "src/main.zig");
+ q.push(.{ .tool_started = .{ .name = name, .detail = detail } });
+ // The engine's arena is gone; the queued copy must still be readable.
+ arena_state.deinit();
+
+ const evs = q.drain();
+ defer q.free(evs);
+ try std.testing.expectEqual(@as(usize, 1), evs.len);
+ try std.testing.expectEqualStrings("mcp__codedbpro__read", evs[0].tool_started.name);
+ try std.testing.expectEqualStrings("src/main.zig", evs[0].tool_started.detail);
+}
+
+test "drain empties the queue and hands ownership over exactly once" {
+ var q: Queue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+ q.push(.{ .tool_started = .{ .name = "bash", .detail = "ls" } });
+ q.push(.{ .tool_finished = .{ .name = "bash", .detail = "ok", .is_error = false } });
+ const first = q.drain();
+ try std.testing.expectEqual(@as(usize, 2), first.len);
+ q.free(first);
+ const second = q.drain();
+ defer q.free(second);
+ try std.testing.expectEqual(@as(usize, 0), second.len);
+}
+
+test "an unattached queue drops instead of crashing, and never hands out memory" {
+ var q: Queue = .{};
+ q.push(.{ .notice = "loaded 2 saved approval(s)" });
+ const evs = q.drain();
+ defer q.free(evs);
+ try std.testing.expectEqual(@as(usize, 0), evs.len);
+}
+
+test "the queue is bounded: past cap it drops and counts instead of growing" {
+ var q: Queue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+ var i: usize = 0;
+ while (i < Queue.cap + 8) : (i += 1) q.push(.{ .notice = "x" });
+ try std.testing.expectEqual(Queue.cap, q.items.items.len);
+ try std.testing.expectEqual(@as(usize, 8), q.dropped);
+}
+
+test "pushes from another thread arrive intact" {
+ var q: Queue = .{};
+ q.attach(std.testing.allocator);
+ defer q.deinit();
+ const Writer = struct {
+ fn f(target: *Queue) void {
+ var i: usize = 0;
+ while (i < 200) : (i += 1) target.push(.{ .tool_finished = .{ .name = "bash", .detail = "done" } });
+ }
+ };
+ const th = try std.Thread.spawn(.{}, Writer.f, .{&q});
+ th.join();
+ const evs = q.drain();
+ defer q.free(evs);
+ try std.testing.expectEqual(@as(usize, 200), evs.len);
+ for (evs) |e| try std.testing.expectEqualStrings("bash", e.tool_finished.name);
+}
diff --git a/TUI/render.zig b/TUI/render.zig
index 83de3097..8086592c 100644
--- a/TUI/render.zig
+++ b/TUI/render.zig
@@ -17,7 +17,7 @@ pub fn render(self: *Model, gpa: std.mem.Allocator, width: usize, height: usize,
self.last_term_width = width;
self.last_term_height = height;
self.now_ms = now_ms;
- @import("turn.zig").harvestLiveTools(self);
+ @import("turn.zig").drainEvents(self);
var arena_state = std.heap.ArenaAllocator.init(gpa);
defer arena_state.deinit();
@@ -172,8 +172,8 @@ test "click on a painted Called row expands the tools" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.assistant, "Hey. I am in /Users/blackfloofie/codegraff on wip/shared-checkout-2026-08-14 and holding a long worktree path so this wraps");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
const frame = try render(&m, std.testing.allocator, 80, 24, 0);
defer std.testing.allocator.free(frame);
var row: usize = 0;
@@ -212,8 +212,8 @@ test "visible dump of a fixture frame shows chips, Called, composer, no CSI" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "@[/tmp/shot.png] look");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
const frame = try render(&m, std.testing.allocator, 80, 24, 0);
defer std.testing.allocator.free(frame);
const dump_mod = @import("dump.zig");
@@ -257,7 +257,7 @@ test "debug overlay keeps the observability HUD and adds layout" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "@[/tmp/shot.png] look");
- try m.push(.tool, "⚙ bash");
+ try m.pushTool(.{ .name = "bash" });
const frame = try render(&m, std.testing.allocator, 80, 24, 0);
defer std.testing.allocator.free(frame);
m.openOverlay(.debug);
diff --git a/TUI/root.zig b/TUI/root.zig
index cd0c352d..698bef74 100644
--- a/TUI/root.zig
+++ b/TUI/root.zig
@@ -17,6 +17,9 @@ pub const HudKind = engine.HudKind;
pub const Turn = engine.Turn;
pub const Params = engine.Params;
pub const StreamBuf = engine.StreamBuf;
+pub const Event = engine.Event;
+pub const EventQueue = engine.EventQueue;
+pub const ToolEvent = engine.ToolEvent;
pub const TurnFn = engine.TurnFn;
pub const ModelFn = engine.ModelFn;
pub const CancelFn = engine.CancelFn;
@@ -35,6 +38,7 @@ pub const sim = @import("sim.zig");
test {
_ = engine;
+ _ = @import("events.zig");
_ = theme;
_ = catalog;
_ = app;
diff --git a/TUI/scrollback.zig b/TUI/scrollback.zig
index fe22f1f6..1186e025 100644
--- a/TUI/scrollback.zig
+++ b/TUI/scrollback.zig
@@ -174,12 +174,28 @@ fn lineCount(s: []const u8) usize {
return std.mem.count(u8, s, "\n") + 1;
}
-fn isSearch(text: []const u8) bool {
- return containsIgnoreCase(text, "search") or containsIgnoreCase(text, "grep") or containsIgnoreCase(text, "find");
+/// Is this a search-shaped tool? Answered from the tool NAME (#551). It used
+/// to be answered from the whole rendered line, so `bash` running a command
+/// that merely mentioned "find" counted as a search.
+fn isSearch(name: []const u8) bool {
+ return containsIgnoreCase(name, "search") or containsIgnoreCase(name, "grep") or containsIgnoreCase(name, "find");
}
-fn isMcp(text: []const u8) bool {
- return std.mem.indexOf(u8, text, "mcp__") != null or containsIgnoreCase(text, "mcp");
+fn isMcp(name: []const u8) bool {
+ return std.mem.startsWith(u8, name, "mcp__");
+}
+
+/// What a row's classification reads. A field-backed row answers with the
+/// engine's tool name; a legacy row restored from an old session has only its
+/// rendered text, and keeps the looser substring behavior it was written with.
+fn classifyOn(e: app.Entry) []const u8 {
+ if (e.tool) |t| return t.name;
+ return e.text;
+}
+
+fn rowIsMcp(e: app.Entry) bool {
+ if (e.tool) |t| return isMcp(t.name);
+ return std.mem.indexOf(u8, e.text, "mcp__") != null or containsIgnoreCase(e.text, "mcp");
}
fn containsIgnoreCase(hay: []const u8, needle: []const u8) bool {
@@ -198,9 +214,9 @@ fn summary(self: *const Model, a: std.mem.Allocator, start: usize, end: usize, s
var mcp_n: usize = 0;
var i = start;
while (i < end) : (i += 1) {
- const t = self.history.items[i].text;
- if (isMcp(t)) mcp_n += 1;
- if (isSearch(t)) searches += 1 else calls += 1;
+ const e = self.history.items[i];
+ if (rowIsMcp(e)) mcp_n += 1;
+ if (isSearch(classifyOn(e))) searches += 1 else calls += 1;
}
const sel: []const u8 = if (selected) "› " else " ";
// No live bar here: liveness belongs to the pending row alone. A bar on
@@ -242,7 +258,7 @@ fn row(self: *const Model, a: std.mem.Allocator, idx: usize, e: app.Entry, width
// pushes an empty row and gets the generic label.
(if (e.text.len > 0) e.text else thinkingLabel(now_ms))
else if (e.kind == .tool)
- try toolTitle(a, e.text)
+ try toolTitle(a, e, e)
else if (e.folded)
firstLine(e.text)
else
@@ -275,57 +291,62 @@ fn userNo(self: *const Model, idx: usize) u32 {
return if (n == 0) 1 else n;
}
-fn prettyTool(text: []const u8) []const u8 {
- var s = std.mem.trim(u8, text, " \t");
- const prefixes = [_][]const u8{ "⚙ ", "✓ ", "✗ ", "⊘ " };
- for (prefixes) |p| {
- if (std.mem.startsWith(u8, s, p)) s = s[p.len..];
- }
- if (std.mem.startsWith(u8, s, "mcp__")) {
- if (std.mem.lastIndexOf(u8, s, "__")) |u| {
- if (u + 2 < s.len) return s[u + 2 ..];
- }
- }
- return s;
-}
-
-fn isStartTool(text: []const u8) bool {
- return std.mem.startsWith(u8, std.mem.trim(u8, text, " \t"), "⚙ ");
+/// A tool row's start/done phase, straight off its typed payload. A legacy row
+/// (tool == null) is neither: it has no phase to read, so it renders alone.
+fn isStartTool(e: app.Entry) bool {
+ const t = e.tool orelse return false;
+ return !t.done;
}
-fn isDoneTool(text: []const u8) bool {
- const s = std.mem.trim(u8, text, " \t");
- return std.mem.startsWith(u8, s, "✓ ") or std.mem.startsWith(u8, s, "✗ ") or std.mem.startsWith(u8, s, "⊘ ");
+fn isDoneTool(e: app.Entry) bool {
+ const t = e.tool orelse return false;
+ return t.done;
}
fn nextTool(self: *const Model, t: usize, end: usize) usize {
- if (t + 1 < end and isStartTool(self.history.items[t].text) and isDoneTool(self.history.items[t + 1].text))
+ if (t + 1 < end and isStartTool(self.history.items[t]) and isDoneTool(self.history.items[t + 1]))
return t + 2;
return t + 1;
}
-fn shortToolName(name: []const u8) []const u8 {
+/// The display form of a tool NAME: the harness's internal names shortened,
+/// and an MCP tool shown by its leaf. Operates on the name alone — the old
+/// prettyTool did this by stripping a status glyph off a rendered line first.
+fn displayName(name: []const u8) []const u8 {
if (std.mem.eql(u8, name, "read_file")) return "read";
if (std.mem.eql(u8, name, "write_file")) return "write";
+ if (std.mem.startsWith(u8, name, "mcp__")) {
+ if (std.mem.lastIndexOf(u8, name, "__")) |u| {
+ if (u + 2 < name.len) return name[u + 2 ..];
+ }
+ }
return name;
}
-fn toolTitle(a: std.mem.Allocator, text: []const u8) ![]const u8 {
- const pretty = prettyTool(text);
- const cut = std.mem.indexOf(u8, pretty, " | ") orelse pretty.len;
- const head = pretty[0..cut];
- const sp = std.mem.indexOfScalar(u8, head, ' ') orelse return shortToolName(head);
- const name = shortToolName(head[0..sp]);
- const rest = std.mem.trim(u8, head[sp + 1 ..], " \t");
- if (rest.len == 0) return name;
- return std.fmt.allocPrint(a, "{s} {s}", .{ name, rest });
+/// The head of a tool row: `[status mark] name [argument preview]`, composed
+/// from FIELDS. On a paired card the name and its arguments come from the call
+/// (`named`) while the status mark comes from the outcome (`status`); on a lone
+/// row both are the same entry. A legacy row has only its stored line and is
+/// shown verbatim rather than taken apart — the old code split that line on
+/// " | ", which silently truncated any command containing one.
+fn toolTitle(a: std.mem.Allocator, named: app.Entry, status: app.Entry) ![]const u8 {
+ const t = named.tool orelse return named.text;
+ const mark: []const u8 = if (status.tool) |s|
+ (if (s.denied) "⊘ " else if (s.is_error) "✗ " else "")
+ else
+ "";
+ const name = displayName(t.name);
+ // A finished row's detail is its RESULT preview and belongs in the body.
+ const args = if (t.done) "" else t.detail;
+ if (args.len == 0) return if (mark.len == 0) name else std.fmt.allocPrint(a, "{s}{s}", .{ mark, name });
+ return std.fmt.allocPrint(a, "{s}{s} {s}", .{ mark, name, args });
}
-fn toolPreview(text: []const u8) ?[]const u8 {
- const pretty = prettyTool(text);
- const at = std.mem.indexOf(u8, pretty, " | ") orelse return null;
- const body = std.mem.trim(u8, pretty[at + 3 ..], " \t");
- return if (body.len == 0) null else body;
+/// The one-line body under a tool card: the outcome's result preview.
+fn toolPreview(e: app.Entry) ?[]const u8 {
+ const t = e.tool orelse return null;
+ if (!t.done or t.detail.len == 0) return null;
+ return t.detail;
}
fn toolVisual(
@@ -338,15 +359,15 @@ fn toolVisual(
selected: bool,
) ![]const u8 {
const e = self.history.items[t];
- const paired = t + 1 < end and isStartTool(e.text) and isDoneTool(self.history.items[t + 1].text);
+ const paired = t + 1 < end and isStartTool(e) and isDoneTool(self.history.items[t + 1]);
if (!paired) return row(self, a, t, e, width, now_ms, selected);
- return toolCard(a, self.theme(), e.text, self.history.items[t + 1].text, selected, width);
+ return toolCard(a, self.theme(), e, self.history.items[t + 1], selected, width);
}
-fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, start_text: []const u8, done_text: []const u8, selected: bool, width: usize) ![]const u8 {
+fn toolCard(a: std.mem.Allocator, th: theme_mod.Theme, call: app.Entry, outcome: app.Entry, selected: bool, width: usize) ![]const u8 {
const sel: []const u8 = if (selected) "› " else " ";
- const title = try toolTitle(a, start_text);
- const preview = toolPreview(done_text);
+ const title = try toolTitle(a, call, outcome);
+ const preview = toolPreview(outcome);
const head = try std.fmt.allocPrint(a, "{s}{s}◆{s}{s} {s}", .{ sel, if (selected) th.accent else th.muted, theme_mod.reset, th.text, title });
if (preview == null) return theme_mod.wrapToWidth(a, head, width);
const body = try std.fmt.allocPrint(a, "{s}{s}│ {s}{s}", .{ sel, th.muted, preview.?, theme_mod.reset });
@@ -391,11 +412,11 @@ fn strip(a: std.mem.Allocator, s: []const u8) []const u8 {
fn tail(a: std.mem.Allocator, s: []const u8, width: usize, max_lines: usize) ![]const u8 {
var lines = std.array_list.Managed([]const u8).init(a);
var it = std.mem.splitScalar(u8, s, '\n');
- while (it.next()) |ln| {
- const t = std.mem.trim(u8, ln, " \t\r");
- if (@import("turn.zig").isToolLine(t)) continue;
- try lines.append(ln);
- }
+ // No tool-line filter any more: the live buffer carries PROSE only —
+ // answer text and (with /thinking on) reasoning. Tool activity reaches the
+ // transcript as typed events, so nothing here has to guess which lines the
+ // sink drew (#551).
+ while (it.next()) |ln| try lines.append(ln);
const start = if (lines.items.len > max_lines) lines.items.len - max_lines else 0;
var out = std.array_list.Managed(u8).init(a);
for (lines.items[start..], 0..) |ln, n| {
@@ -426,8 +447,8 @@ test "a live turn never pulses or shifts historical rows" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
try m.push(.assistant, "done");
try m.push(.pending, "");
var sbuf: [16]u8 = undefined;
@@ -472,10 +493,17 @@ test "a live turn never pulses or shifts historical rows" {
try std.testing.expectEqual(@as(usize, 1), changed);
}
-test "prettyTool strips mcp prefix" {
- try std.testing.expectEqualStrings("memo", prettyTool("✓ mcp__codedbpro__memo"));
- try std.testing.expectEqualStrings("faster_search", prettyTool("⚙ mcp__codedbpro__faster_search"));
- try std.testing.expectEqualStrings("bash", prettyTool("⚙ bash"));
+test "displayName shortens an mcp tool to its leaf, reading the NAME" {
+ // The old prettyTool took a rendered LINE and stripped a status glyph off
+ // it first; this takes the engine's tool name, which is all it ever needed.
+ try std.testing.expectEqualStrings("memo", displayName("mcp__codedbpro__memo"));
+ try std.testing.expectEqualStrings("faster_search", displayName("mcp__codedbpro__faster_search"));
+ try std.testing.expectEqualStrings("bash", displayName("bash"));
+ try std.testing.expectEqualStrings("read", displayName("read_file"));
+}
+
+test {
+ _ = @import("scrollback_tests.zig");
}
test "collapsed tool run is one Called summary" {
@@ -483,8 +511,8 @@ test "collapsed tool run is one Called summary" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
try m.push(.assistant, "done");
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
@@ -517,8 +545,8 @@ test "Called summary visual row maps back to the tool group" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const text = try render(&m, arena.allocator(), 80, 0);
@@ -539,8 +567,8 @@ test "collapsed search run is one Searched summary" {
var m: Model = undefined;
m.setup(std.testing.allocator);
defer m.deinit();
- try m.push(.tool, "⚙ grep needle");
- try m.push(.tool, "✓ grep needle");
+ try m.pushTool(.{ .name = "grep", .detail = "needle" });
+ try m.pushTool(.{ .name = "grep", .detail = "3 hits", .done = true });
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const text = try render(&m, arena.allocator(), 80, 0);
@@ -555,8 +583,8 @@ test "expanded read card shows the path and preview" {
var m: Model = undefined;
m.setup(std.testing.allocator);
defer m.deinit();
- try m.push(.tool, "⚙ read src/foo.zig");
- try m.push(.tool, "✓ read | const std = @import(\"std\");");
+ try m.pushTool(.{ .name = "read_file", .detail = "src/foo.zig" });
+ try m.pushTool(.{ .name = "read_file", .detail = "const std = @import(\"std\");", .done = true });
m.toggleToolGroup(0);
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
diff --git a/TUI/scrollback_tests.zig b/TUI/scrollback_tests.zig
new file mode 100644
index 00000000..ede4694a
--- /dev/null
+++ b/TUI/scrollback_tests.zig
@@ -0,0 +1,93 @@
+//! Behavioral tests for the field-backed tool transcript (#551). They drive
+//! `scrollback.render` through the public Model, so they hold the CONTRACT —
+//! what a reader sees — rather than any one helper's shape. Split out of
+//! scrollback.zig for the 600-line ceiling.
+
+const std = @import("std");
+
+const app = @import("app.zig");
+const scrollback = @import("scrollback.zig");
+const Model = app.Model;
+
+test "classification reads the tool name, not the whole row (#551)" {
+ // `bash` running a command that merely mentions a search word is a call,
+ // not a search — the old whole-line substring test got this wrong.
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.pushTool(.{ .name = "bash", .detail = "grep -rn needle | head" });
+ try m.pushTool(.{ .name = "bash", .detail = "found 3", .done = true });
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try scrollback.render(&m, arena.allocator(), 100, 0);
+ try std.testing.expect(std.mem.indexOf(u8, text, "Called 2") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "Searched") == null);
+ // And the argument survives the " | " that used to truncate the title.
+ m.toggleToolGroup(0);
+ const open = try scrollback.render(&m, arena.allocator(), 100, 0);
+ try std.testing.expect(std.mem.indexOf(u8, open, "grep -rn needle | head") != null);
+}
+
+test "an mcp run summarises as MCP tools, off the name prefix" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "note" });
+ try m.pushTool(.{ .name = "mcp__codedbpro__memo", .detail = "saved", .done = true });
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, text, "Called 2 MCP tools") != null);
+}
+
+test "an assistant line that starts with a status glyph is NOT a tool row (#551)" {
+ // The phantom-row bug: turn.zig used to harvest any streamed line starting
+ // "✓ " into the transcript as a tool. Answer text is answer text.
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.user, "did it work?");
+ try m.push(.assistant, "✓ all three checks passed");
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, text, "all three checks passed") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "Called") == null);
+ for (m.history.items) |e| try std.testing.expect(e.kind != .tool);
+}
+
+test "a legacy text-only tool row still renders (session migration)" {
+ // Rows restored from a session written before the typed contract carry no
+ // fields. They must still show up — just without pairing or a preview.
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.push(.tool, "⚙ bash");
+ try m.push(.tool, "✓ bash | ok");
+ for (m.history.items) |e| try std.testing.expect(e.tool == null);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const folded = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, folded, "Called 2") != null);
+ m.toggleToolGroup(0);
+ const open = try scrollback.render(&m, arena.allocator(), 80, 0);
+ try std.testing.expect(std.mem.indexOf(u8, open, "⚙ bash") != null);
+ try std.testing.expect(std.mem.indexOf(u8, open, "✓ bash | ok") != null);
+}
+
+test "a failed call is marked, a refused one is marked differently" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try m.pushTool(.{ .name = "bash", .detail = "false" });
+ try m.pushTool(.{ .name = "bash", .detail = "exit 1", .done = true, .is_error = true });
+ try m.pushTool(.{ .name = "write_file", .detail = "/etc/passwd" });
+ try m.pushTool(.{ .name = "write_file", .detail = "refused by plan mode", .done = true, .is_error = true, .denied = true });
+ m.toggleToolGroup(0);
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const text = try scrollback.render(&m, arena.allocator(), 100, 0);
+ try std.testing.expect(std.mem.indexOf(u8, text, "✗ bash") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "⊘ write") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "refused by plan mode") != null);
+}
diff --git a/TUI/selection.zig b/TUI/selection.zig
index 68f56485..614eda20 100644
--- a/TUI/selection.zig
+++ b/TUI/selection.zig
@@ -361,8 +361,8 @@ test "click on a folded tool row still expands it, and paints no band" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
m.last_term_height = 24;
m.last_term_width = 80;
m.mid_origin = 1;
@@ -381,8 +381,8 @@ test "click on blank padding selects and toggles nothing (#519)" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
m.last_term_height = 24;
m.last_term_width = 80;
m.mid_origin = 0;
@@ -399,8 +399,8 @@ test "a drag that starts on a tool group leaves the group as it was" {
m.setup(std.testing.allocator);
defer m.deinit();
try m.push(.user, "hi");
- try m.push(.tool, "⚙ bash");
- try m.push(.tool, "✓ bash");
+ try m.pushTool(.{ .name = "bash" });
+ try m.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
m.last_term_height = 24;
m.last_term_width = 80;
m.mid_origin = 1;
diff --git a/TUI/sim.zig b/TUI/sim.zig
index ec3597dc..6e69a389 100644
--- a/TUI/sim.zig
+++ b/TUI/sim.zig
@@ -226,8 +226,8 @@ test "clickText on Called expands the folded tools" {
term.init(std.testing.allocator, 80, 24);
defer term.deinit();
try term.model.push(.assistant, "working");
- try term.model.push(.tool, "⚙ bash");
- try term.model.push(.tool, "✓ bash");
+ try term.model.pushTool(.{ .name = "bash" });
+ try term.model.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
const before = try term.screen();
defer std.testing.allocator.free(before);
try std.testing.expect(std.mem.indexOf(u8, before, "Called") != null);
@@ -243,8 +243,8 @@ test "feed Ghostty SGR click matches clickAt" {
term.init(std.testing.allocator, 80, 24);
defer term.deinit();
try term.model.push(.assistant, "working");
- try term.model.push(.tool, "⚙ bash");
- try term.model.push(.tool, "✓ bash");
+ try term.model.pushTool(.{ .name = "bash" });
+ try term.model.pushTool(.{ .name = "bash", .detail = "ok", .done = true });
const hit = try term.find("Called") orelse return error.NoCalled;
var buf: [40]u8 = undefined;
const seq = try std.fmt.bufPrint(&buf, "\x1b[<0;{d};{d}M", .{ hit.x, hit.y });
diff --git a/TUI/turn.zig b/TUI/turn.zig
index 5d13f936..86364874 100644
--- a/TUI/turn.zig
+++ b/TUI/turn.zig
@@ -42,6 +42,9 @@ pub fn startJob(self: *Model) void {
},
.stream = .{ .buf = self.alloc.alloc(u8, 256 * 1024) catch &.{} },
};
+ // The queue must own its copies before the turn thread can push: the
+ // engine's payloads live in a per-turn arena that dies with the turn.
+ job.events.attach(self.alloc);
self.push(.pending, "") catch {};
self.pending = job;
if (std.Thread.spawn(.{}, engine.jobRun, .{job})) |th| {
@@ -57,13 +60,11 @@ pub fn finishJob(self: *Model) void {
if (!job.done.load(.acquire)) return;
if (job.threaded) job.thread.join();
+ // Whatever the engine emitted after the last frame — the tail of the tool
+ // run, a closing notice — before the answer row goes in, so the transcript
+ // keeps its order.
+ drainEvents(self);
_ = removePendingRows(self);
- // The live stream carries ⚙/✓/✗ lines; the result is only the final
- // answer. Keep the tool rows so they don't vanish with the pending entry.
- if (job.stream.snapshot(self.alloc)) |live| {
- defer self.alloc.free(live);
- persistToolLines(self, live);
- }
if (job.result) |r| {
self.chars_out += r.len;
self.push(.assistant, r) catch {};
@@ -76,6 +77,7 @@ pub fn finishJob(self: *Model) void {
for (job.history) |t| self.alloc.free(t.text);
self.alloc.free(job.history);
if (job.stream.buf.len > 0) self.alloc.free(job.stream.buf);
+ job.events.deinit();
self.alloc.destroy(job);
self.pending = null;
self.cancel_requested = false;
@@ -140,7 +142,7 @@ pub fn cancelTurn(self: *Model) void {
fn collapseThinking(self: *Model) void {
const n = self.history.items.len;
if (n == 0 or self.history.items[n - 1].kind != .pending) return;
- self.alloc.free(self.history.items[n - 1].text);
+ self.freeEntry(self.history.items[n - 1]);
const text = self.alloc.dupe(u8, "■ interrupted") catch {
self.history.shrinkRetainingCapacity(n - 1);
return;
@@ -148,30 +150,73 @@ fn collapseThinking(self: *Model) void {
self.history.items[n - 1] = .{ .kind = .system, .text = text, .folded = false };
}
+/// Did this turn already say it was interrupted? Scans back to the prompt
+/// rather than looking only at the last row: a cancel collapses the pending
+/// row immediately, and events that were already in flight land AFTER it, so
+/// "is it the last row" would have written a second notice (#551).
fn hasInterrupted(self: *const Model) bool {
- if (self.history.items.len == 0) return false;
- return std.mem.eql(u8, self.history.items[self.history.items.len - 1].text, "■ interrupted");
-}
-
-pub fn isToolLine(line: []const u8) bool {
- return std.mem.startsWith(u8, line, "⚙ ") or
- std.mem.startsWith(u8, line, "✓ ") or
- std.mem.startsWith(u8, line, "✗ ") or
- std.mem.startsWith(u8, line, "⊘ ");
+ var i = self.history.items.len;
+ while (i > 0) {
+ i -= 1;
+ const e = self.history.items[i];
+ if (e.kind == .user) return false;
+ if (std.mem.eql(u8, e.text, "■ interrupted")) return true;
+ }
+ return false;
}
-/// Pull new ⚙/✓/✗ lines out of the live stream so they become clickable
-/// folded history *during* the turn, not only after finishJob.
-pub fn harvestLiveTools(self: *Model) void {
- if (self.cancel_requested) return;
+/// Apply everything the engine has emitted for the live turn. Called from the
+/// render loop's poll point every frame, so tool rows, notices and failovers
+/// appear *during* the turn and not only at finishJob.
+///
+/// This replaced the old harvestLiveTools, which reconstructed tool activity by
+/// matching "⚙ /✓ /✗ /⊘ " prefixes in the sink's rendered bytes — an assistant
+/// answer whose line began "✓ " became a phantom tool row, and every re-scan
+/// re-counted the rows it had already made (#551).
+pub fn drainEvents(self: *Model) void {
const job = self.pending orelse return;
- const live = job.stream.snapshot(self.alloc) orelse return;
- defer self.alloc.free(live);
+ const evs = job.events.drain();
+ defer job.events.free(evs);
+ if (evs.len == 0) return;
+ // Events land BEFORE the live "Thinking" row, which is a presentation
+ // artifact rather than transcript content.
const had_pending = removePendingRows(self);
- persistToolLines(self, live);
+ for (evs) |ev| applyEvent(self, ev);
if (had_pending) self.push(.pending, "") catch {};
}
+fn applyEvent(self: *Model, ev: engine.Event) void {
+ switch (ev) {
+ .tool_started => |t| self.pushTool(.{ .name = t.name, .detail = t.detail }) catch {},
+ .tool_finished => |t| self.pushTool(.{
+ .name = t.name,
+ .detail = t.detail,
+ .done = true,
+ .is_error = t.is_error,
+ }) catch {},
+ // A refusal is a finished tool row in the error state: the TUI has a
+ // surface for that today, and dropping it (as the old sink did) left
+ // the user watching a call that simply never came back.
+ .tool_rejected => |t| self.pushTool(.{
+ .name = t.name,
+ .detail = t.detail,
+ .done = true,
+ .is_error = true,
+ .denied = true,
+ }) catch {},
+ .notice => |s| self.push(.system, s) catch {},
+ // A mid-turn failover changes what the status bar must say. The event's
+ // copy dies with this drain, so the Model takes ownership of the name
+ // the global points at.
+ .model_changed => |s| if (self.alloc.dupe(u8, s)) |owned| {
+ if (self.model_override) |old| self.alloc.free(old);
+ self.model_override = owned;
+ engine.g_model_name = owned;
+ self.pushFmt(.system, "model → {s}", .{owned}) catch {};
+ } else |_| {},
+ }
+}
+
/// Remove every .pending row wherever it sits. Steering pushes "↳ queued"
/// rows after the pending entry, so "pending is last" is not an invariant —
/// assuming it stranded a permanent thinking row in the transcript (#520).
@@ -181,7 +226,7 @@ pub fn removePendingRows(self: *Model) bool {
while (i > 0) {
i -= 1;
if (self.history.items[i].kind == .pending) {
- self.alloc.free(self.history.items[i].text);
+ self.freeEntry(self.history.items[i]);
_ = self.history.orderedRemove(i);
had = true;
}
@@ -189,28 +234,6 @@ pub fn removePendingRows(self: *Model) bool {
return had;
}
-fn persistToolLines(self: *Model, stream: []const u8) void {
- var have: usize = 0;
- var hi = self.history.items.len;
- while (hi > 0) {
- hi -= 1;
- if (self.history.items[hi].kind == .user) break;
- if (self.history.items[hi].kind == .tool) have += 1;
- }
- var seen: usize = 0;
- var it = std.mem.splitScalar(u8, stream, '\n');
- while (it.next()) |raw| {
- const line = std.mem.trim(u8, raw, " \t\r");
- if (line.len == 0 or !isToolLine(line)) continue;
- if (seen < have) {
- seen += 1;
- continue;
- }
- self.push(.tool, line) catch {};
- seen += 1;
- }
-}
-
test "startJob without a turn_fn finishes as a failed call" {
var m: Model = undefined;
m.setup(std.testing.allocator);
@@ -225,11 +248,13 @@ test "startJob without a turn_fn finishes as a failed call" {
try std.testing.expect(m.history.items[m.history.items.len - 1].kind == .err);
}
-test "finishJob keeps tool lines from the live stream" {
+test "finishJob turns queued events into field-backed tool rows" {
var m: Model = undefined;
m.setup(std.testing.allocator);
defer m.deinit();
- const live = "hello\n⚙ bash\n✓ bash\nmore text";
+ // Prose and structure arrive on SEPARATE channels now: the answer text
+ // that happens to contain a "✓ " line is only ever an answer.
+ const live = "hello\n✓ all good\nmore text";
const buf = try std.testing.allocator.dupe(u8, live);
const job = try std.testing.allocator.create(engine.Job);
job.* = .{
@@ -241,6 +266,9 @@ test "finishJob keeps tool lines from the live stream" {
.result = try std.testing.allocator.dupe(u8, "all done"),
};
job.stream.len.store(live.len, .release);
+ job.events.attach(std.testing.allocator);
+ job.events.push(.{ .tool_started = .{ .name = "bash", .detail = "ls -la" } });
+ job.events.push(.{ .tool_finished = .{ .name = "bash", .detail = "4 files" } });
job.done.store(true, .release);
try m.push(.pending, "");
m.pending = job;
@@ -248,20 +276,104 @@ test "finishJob keeps tool lines from the live stream" {
try std.testing.expect(m.pending == null);
try std.testing.expectEqual(@as(usize, 3), m.history.items.len);
try std.testing.expectEqual(app.EntryKind.tool, m.history.items[0].kind);
- try std.testing.expectEqualStrings("⚙ bash", m.history.items[0].text);
- try std.testing.expectEqual(app.EntryKind.tool, m.history.items[1].kind);
- try std.testing.expectEqualStrings("✓ bash", m.history.items[1].text);
+ // The row carries FIELDS, not a rendered line to be taken apart again.
+ const call = m.history.items[0].tool orelse return error.NotFieldBacked;
+ try std.testing.expectEqualStrings("bash", call.name);
+ try std.testing.expectEqualStrings("ls -la", call.detail);
+ try std.testing.expect(!call.done);
+ const outcome = m.history.items[1].tool orelse return error.NotFieldBacked;
+ try std.testing.expectEqualStrings("4 files", outcome.detail);
+ try std.testing.expect(outcome.done);
+ try std.testing.expect(!outcome.is_error);
try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[2].kind);
try std.testing.expectEqualStrings("all done", m.history.items[2].text);
}
-test "hosted tool line is visible on the live tail before finishJob" {
+test "a streamed line starting with a status glyph never becomes a tool row (#551)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ // Exactly the shape that produced phantom rows: the model's own answer,
+ // formatted as a checklist, streaming through the live buffer.
+ const live = "✓ tests pass\n✗ lint fails\n⚙ retrying\n";
+ const buf = try std.testing.allocator.dupe(u8, live);
+ const job = try std.testing.allocator.create(engine.Job);
+ job.* = .{
+ .gpa = std.testing.allocator,
+ .history = &.{},
+ .params = .{},
+ .stream = .{ .buf = buf },
+ .threaded = false,
+ .result = try std.testing.allocator.dupe(u8, "✓ tests pass\n✗ lint fails\n⚙ retrying"),
+ };
+ job.stream.len.store(live.len, .release);
+ job.events.attach(std.testing.allocator);
+ job.done.store(true, .release);
+ try m.push(.pending, "");
+ m.pending = job;
+ finishJob(&m);
+ var tools: usize = 0;
+ for (m.history.items) |e| {
+ if (e.kind == .tool) tools += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 0), tools);
+ try std.testing.expectEqual(app.EntryKind.assistant, m.history.items[m.history.items.len - 1].kind);
+ // And the answer is stored ONCE — the old harvest left a copy behind as
+ // tool rows and then pushed the same text again as the answer.
+ var copies: usize = 0;
+ for (m.history.items) |e| {
+ if (std.mem.indexOf(u8, e.text, "tests pass") != null) copies += 1;
+ }
+ try std.testing.expectEqual(@as(usize, 1), copies);
+}
+
+test "a refusal and a failover reach the transcript instead of vanishing" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ const job = try std.testing.allocator.create(engine.Job);
+ job.* = .{
+ .gpa = std.testing.allocator,
+ .history = &.{},
+ .params = .{},
+ .stream = .{},
+ .threaded = false,
+ .result = try std.testing.allocator.dupe(u8, "ok"),
+ };
+ job.events.attach(std.testing.allocator);
+ job.events.push(.{ .tool_rejected = .{
+ .name = "write_file",
+ .detail = "plan mode forbids writes",
+ .is_error = true,
+ .denied = true,
+ } });
+ job.events.push(.{ .notice = "loaded 2 saved approval(s)" });
+ job.events.push(.{ .model_changed = "sonnet" });
+ job.done.store(true, .release);
+ try m.push(.pending, "");
+ m.pending = job;
+ finishJob(&m);
+ const refused = m.history.items[0].tool orelse return error.NotFieldBacked;
+ try std.testing.expect(refused.denied);
+ try std.testing.expect(refused.is_error);
+ try std.testing.expect(refused.done);
+ try std.testing.expectEqual(app.EntryKind.system, m.history.items[1].kind);
+ try std.testing.expectEqualStrings("loaded 2 saved approval(s)", m.history.items[1].text);
+ // The failover updates what the status bar reads, not just the transcript.
+ try std.testing.expectEqualStrings("sonnet", engine.g_model_name);
+ try std.testing.expect(std.mem.indexOf(u8, m.history.items[2].text, "sonnet") != null);
+}
+
+test "a live tool row is visible mid-turn, straight off the event queue" {
const scrollback = @import("scrollback.zig");
const Hold = struct {
var started: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, stream: *engine.StreamBuf) ?[]const u8 {
- stream.appendBytes("⚙ bash\n");
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, stream: *engine.StreamBuf, events: *engine.EventQueue) ?[]const u8 {
+ // The turn thread pushes structure and streams prose, exactly as
+ // the real sink does.
+ events.push(.{ .tool_started = .{ .name = "bash", .detail = "ls" } });
+ stream.appendBytes("working…\n");
started.store(true, .release);
while (!release.load(.acquire)) std.Thread.yield() catch {};
return gpa.dupe(u8, "all done") catch null;
@@ -289,10 +401,12 @@ test "hosted tool line is visible on the live tail before finishJob" {
try std.testing.expect(!job.done.load(.acquire));
const snap = job.stream.snapshot(std.testing.allocator) orelse return error.LiveTailEmpty;
defer std.testing.allocator.free(snap);
- try std.testing.expect(std.mem.indexOf(u8, snap, "⚙ bash") != null);
+ // Prose only in the live buffer — the tool row is on the other channel.
+ try std.testing.expect(std.mem.indexOf(u8, snap, "working") != null);
+ try std.testing.expect(std.mem.indexOf(u8, snap, "bash") == null);
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_state.deinit();
- harvestLiveTools(&m);
+ drainEvents(&m);
const harvested = try scrollback.render(&m, arena_state.allocator(), 80, 0);
try std.testing.expect(std.mem.indexOf(u8, harvested, "Called") != null);
@@ -347,6 +461,10 @@ test "cancelTurn collapses thinking immediately" {
try std.testing.expect(m.history.items.len == 1);
try std.testing.expect(m.history.items[0].kind == .system);
try std.testing.expectEqualStrings("■ interrupted", m.history.items[0].text);
+ // Events already in flight when the cancel landed still arrive, and they
+ // land after the notice — which must not make finishJob write a second one.
+ job.events.attach(std.testing.allocator);
+ job.events.push(.{ .tool_finished = .{ .name = "bash", .detail = "cancelled", .is_error = true } });
job.done.store(true, .release);
finishJob(&m);
try std.testing.expect(m.pending == null);
@@ -389,7 +507,7 @@ test "Model.deinit never joins a running turn thread (#534)" {
const Hold = struct {
var release: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
var started: std.atomic.Value(bool) = std.atomic.Value(bool).init(false);
- fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, _: *engine.StreamBuf) ?[]const u8 {
+ fn f(_: ?*anyopaque, gpa: std.mem.Allocator, _: []const engine.Turn, _: engine.Params, _: *engine.StreamBuf, _: *engine.EventQueue) ?[]const u8 {
started.store(true, .release);
while (!release.load(.acquire)) std.Thread.yield() catch {};
return gpa.dupe(u8, "late") catch null;
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 0b718de5..aff61763 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 1323,
+ "test_count_baseline": 1328,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index 4313a8bc..81eb6951 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -147,8 +147,37 @@ pub fn enableColor() void {
/// Set by a fullscreen frontend (TUI/) so TuiSink never draws on stdout —
/// that would fight the alt-screen. Text goes to `a.out` (the pane buffer).
+///
+/// This only ever gated hostedEmit, which renders the tool cluster back into
+/// "⚙ /✓ " TEXT for a frontend to parse out again and silently drops every
+/// other event. It survives as the fallback for a hosted agent that has NO
+/// sink of its own — a subagent, a one-shot — while a frontend that installs
+/// one (see `bindTurnSink`) never goes through it (#551).
pub var hosted_frontend: bool = false;
+/// The sink a frontend wants the next Agent built on THIS thread to use.
+///
+/// The turn constructors (repl_glue.replTurnCb) are shared by every frontend
+/// and know nothing about any of them, so the frontend leaves its sink here
+/// before handing the turn over and takes it back after. Thread-local because
+/// one turn thread runs one turn: a background subagent pool thread building
+/// its own Agent finds nothing here and keeps the process-mode default, which
+/// is exactly right — a child's output is not the frontend's transcript.
+threadlocal var g_turn_sink: ?EngineSink = null;
+
+pub fn bindTurnSink(s: EngineSink) void {
+ g_turn_sink = s;
+}
+
+pub fn unbindTurnSink() void {
+ g_turn_sink = null;
+}
+
+/// The bound sink, or null when no frontend claimed this turn.
+pub fn turnSink() ?EngineSink {
+ return g_turn_sink;
+}
+
const tui_vtable: VTable = .{ .emit = tuiEmit, .durable = false };
const json_vtable: VTable = .{ .emit = jsonEmit, .durable = true };
/// Same writer, nothing to write to: see jsonSink.
@@ -279,6 +308,11 @@ fn notice(a: *Agent, text: []const u8) void {
w.flush() catch {};
}
+/// The fallback for a HOSTED agent with no sink of its own — a subagent, a
+/// one-shot under a fullscreen frontend. It renders the tool cluster back into
+/// "⚙ /✓ " text and drops everything else, which is why a real frontend must
+/// install a sink instead of reading these bytes back (#551). Nothing new goes
+/// in here: a new event gets a surface on a real sink, not a glyph line.
fn hostedEmit(a: *Agent, ev: EngineEvent) void {
const w = a.out orelse return;
switch (ev) {
@@ -369,13 +403,16 @@ fn jsonLine(w: *Io.Writer, cursor: engine_events.Cursor, payload: anytype) void
w.flush() catch return;
}
-fn shortTool(name: []const u8) []const u8 {
+pub fn shortTool(name: []const u8) []const u8 {
if (std.mem.eql(u8, name, "read_file")) return "read";
if (std.mem.eql(u8, name, "write_file")) return "write";
return name;
}
-fn compactArg(input: std.json.Value) []const u8 {
+/// The one argument worth showing beside a tool name — the path it touches,
+/// the command it runs, the query it asks. Shared with the TUI's typed sink
+/// (tui_sink.zig) so both frontends pick the same field.
+pub fn compactArg(input: std.json.Value) []const u8 {
const obj = switch (input) {
.object => |o| o,
else => return "",
@@ -388,7 +425,7 @@ fn compactArg(input: std.json.Value) []const u8 {
return "";
}
-fn firstLineCap(text: []const u8, cap: usize) []const u8 {
+pub fn firstLineCap(text: []const u8, cap: usize) []const u8 {
var s = std.mem.trim(u8, text, " \t\r\n");
if (std.mem.indexOfScalar(u8, s, '\n')) |i| s = std.mem.trim(u8, s[0..i], " \t\r");
if (s.len > cap) return s[0..cap];
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 9fe78270..416ee4b5 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -308,6 +308,11 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
.tracer = c.tracer,
.run_budget = c.run_budget,
.approvals = &approvals,
+ // #551: a frontend that wants the engine's TYPED events installs its
+ // sink for this thread's turn (engine_sink.bindTurnSink). Null for
+ // `graff repl` and every headless caller, which keeps the process-mode
+ // default. Never re-parse rendered output to learn what the engine did.
+ .sink = @import("engine_sink.zig").turnSink(),
.tools_anthropic = c.tools_anthropic,
.tools_openai = c.tools_openai,
.tools_responses = c.tools_responses,
diff --git a/src/tui_launch.zig b/src/tui_launch.zig
index 4c7e5ed3..35ac8601 100644
--- a/src/tui_launch.zig
+++ b/src/tui_launch.zig
@@ -15,6 +15,7 @@ const repl = @import("repl.zig");
const repl_glue = @import("repl_glue.zig");
const tui = @import("tui");
const engine_sink = @import("engine_sink.zig");
+const tui_sink = @import("tui_sink.zig");
const obs = @import("obs.zig");
const telemetry = @import("telemetry.zig");
const vision = @import("vision.zig");
@@ -131,6 +132,7 @@ fn turnCb(
history: []const tui.Turn,
params: tui.Params,
stream: *tui.StreamBuf,
+ events: *tui.EventQueue,
) ?[]const u8 {
var turns = std.array_list.Managed(repl.Turn).init(gpa);
defer {
@@ -152,7 +154,19 @@ fn turnCb(
obs.prompt(last_len, model);
// Same buf AND the same atomic len — a fresh repl.StreamBuf around
// stream.buf left job.stream.len at 0 for the whole turn, so the live
- // tail never showed hosted tool lines until finishJob copied them.
+ // tail never showed streamed prose until finishJob copied it.
+ //
+ // #551: the TUI's own EngineSink for the duration of this turn. Prose goes
+ // to the live buffer, structure goes to the typed queue; nothing renders
+ // tool activity into text for the frontend to parse back out. The bridge
+ // lives on THIS frame, which outlives the turn it wraps.
+ var bridge: tui_sink.Bridge = .{
+ .queue = events,
+ .stream = liveStream(stream),
+ .show_thinking = params.thinking,
+ };
+ engine_sink.bindTurnSink(tui_sink.forBridge(&bridge));
+ defer engine_sink.unbindTurnSink();
const result = repl_glue.replTurnCb(ctx, gpa, turns.items, .{
.effort = @enumFromInt(@intFromEnum(params.effort)),
.fast = params.fast,
@@ -315,6 +329,7 @@ fn hudCb(kind: tui.HudKind, buf: []u8) usize {
test {
_ = tui;
+ _ = tui_sink;
}
test "hudCb usage/debug use the cost-tally renderer, not chars" {
diff --git a/src/tui_sink.zig b/src/tui_sink.zig
new file mode 100644
index 00000000..8349592f
--- /dev/null
+++ b/src/tui_sink.zig
@@ -0,0 +1,306 @@
+//! The fullscreen TUI's EngineSink (#551, the #422 epic).
+//!
+//! This is the one place that speaks both vocabularies: the engine's
+//! `engine_events.EngineEvent` on one side, the frontend-agnostic
+//! `tui.Event` on the other. Before it existed the TUI had no sink at all —
+//! `engine_sink.hostedEmit` rendered the tool cluster into "⚙ /✓ /✗ " lines,
+//! dropped every other event through an `else => {}`, and the TUI recovered
+//! what it could by scanning those lines back out of the stream.
+//!
+//! The split here is deliberate and is the contract the TUI renders from:
+//!
+//! - PROSE (answer text, meta-tool argument prose, and — with /thinking on —
+//! reasoning) streams into the live text buffer the pending row tails.
+//! - STRUCTURE (tool calls, outcomes, refusals, notices, failover) is pushed
+//! as a typed event with fields. Nothing is rendered here for a frontend
+//! to parse again.
+//!
+//! Every EngineEvent variant is handled explicitly. The ones with no TUI
+//! surface today are grouped and say WHY they are ignored — a bare `else` is
+//! how the reasoning stream went missing for as long as it did.
+
+const std = @import("std");
+
+const engine_events = @import("engine_events.zig");
+const EngineEvent = engine_events.EngineEvent;
+const engine_sink = @import("engine_sink.zig");
+const repl = @import("repl.zig");
+const tui = @import("tui");
+
+/// Result previews are one line, capped — the same budget hostedEmit used, so
+/// a row's body stays a body and a 20 KB tool result never reaches the queue.
+const preview_cap: usize = 80;
+/// Arguments get more room: a path or a command IS the row's identity, and
+/// truncating one at 80 columns is how a reader loses which file was touched.
+const arg_cap: usize = 160;
+
+/// One line of `text`, at most `cap` bytes, ending on a UTF-8 boundary. A byte
+/// cap alone can split a multi-byte codepoint, and half a glyph in the
+/// transcript is a rendering bug the reader gets to see.
+fn capLine(text: []const u8, cap: usize) []const u8 {
+ return dropPartialTail(engine_sink.firstLineCap(text, cap));
+}
+
+/// Drop a trailing INCOMPLETE UTF-8 sequence, and nothing else — a whole
+/// multi-byte character at the end must survive.
+fn dropPartialTail(s: []const u8) []const u8 {
+ var i = s.len;
+ var back: usize = 0;
+ while (i > 0 and back < 4) : (back += 1) {
+ i -= 1;
+ const b = s[i];
+ if (b & 0x80 == 0) return s; // ASCII tail: nothing is half-written
+ if (b & 0xC0 != 0x80) {
+ // A lead byte: keep the character only if all of it is here.
+ const need = std.unicode.utf8ByteSequenceLength(b) catch return s[0..i];
+ return if (i + need <= s.len) s else s[0..i];
+ }
+ }
+ return s;
+}
+
+/// The per-turn wiring a TUI turn hands the engine. Lives on the turn caller's
+/// frame (tui_launch.turnCb) for exactly as long as the turn runs.
+pub const Bridge = struct {
+ /// Typed events for the transcript. Lock-guarded, so the parallel tool
+ /// pool may push from its own threads.
+ queue: *tui.EventQueue,
+ /// The live prose buffer the pending row tails. Single-writer by contract:
+ /// only the streaming reader (the turn thread) writes deltas.
+ stream: *repl.StreamBuf,
+ /// /thinking — whether reasoning belongs in the live tail at all.
+ show_thinking: bool = false,
+ /// Reasoning has been written and no answer text has followed it yet, so
+ /// the first visible byte should break the line first.
+ reasoning_open: bool = false,
+};
+
+const vtable: engine_sink.VTable = .{ .emit = emit, .durable = false };
+
+pub fn forBridge(b: *Bridge) engine_sink.EngineSink {
+ return .{ .ctx = @ptrCast(b), .vt = &vtable };
+}
+
+fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {
+ const b: *Bridge = @ptrCast(@alignCast(ctx));
+ switch (ev.event) {
+ // ── prose: into the live tail ────────────────────────────────────
+ .reasoning_delta => |d| if (b.show_thinking) {
+ b.reasoning_open = true;
+ b.stream.appendBytes(d.text);
+ },
+ .text_delta, .tool_arg_delta => |d| {
+ if (b.reasoning_open) {
+ b.reasoning_open = false;
+ b.stream.appendBytes("\n");
+ }
+ b.stream.appendBytes(d.text);
+ },
+ // A meta tool owns this text's layout, so it arrives whole.
+ .completion_text, .todo_list_updated => |t| {
+ b.stream.appendBytes(t.text);
+ b.stream.appendBytes("\n");
+ },
+
+ // ── structure: typed rows ────────────────────────────────────────
+ .tool_call_announced => |t| b.queue.push(.{ .tool_started = .{
+ .name = t.name,
+ .detail = capLine(engine_sink.compactArg(t.input), arg_cap),
+ } }),
+ .tool_result => |r| b.queue.push(.{ .tool_finished = .{
+ .name = r.name,
+ .detail = capLine(r.text, preview_cap),
+ .is_error = r.is_error,
+ } }),
+ // The harness refused the call before it ran. hostedEmit dropped this
+ // outright, so the row simply never closed and the user watched a tool
+ // that looked stuck.
+ .tool_rejected => |r| b.queue.push(.{ .tool_rejected = .{
+ .name = r.name,
+ .detail = capLine(r.message, preview_cap),
+ .is_error = true,
+ .denied = true,
+ } }),
+
+ // ── notices: system rows ─────────────────────────────────────────
+ .session_notice => |n| {
+ // A notice may open with an emphasized badge ("⚠ YOLO"); the TUI's
+ // system row has one style, so the two halves are joined here
+ // rather than half of it being dropped. The queue copies, so a
+ // stack buffer is enough and nothing is allocated on this path.
+ var buf: [512]u8 = undefined;
+ const line = if (n.lead.len == 0)
+ n.text
+ else
+ std.fmt.bufPrint(&buf, "{s}{s}", .{ n.lead, n.text }) catch n.lead;
+ b.queue.push(.{ .notice = line });
+ },
+ .transport_aborted => |t| switch (t.reason) {
+ // A deliberate Esc is silent here as everywhere: finishJob already
+ // writes the one "■ interrupted" row.
+ .interrupted => {},
+ .stalled => b.queue.push(.{ .notice = "⚠ stream stalled" }),
+ .dropped => b.queue.push(.{ .notice = "⚠ connection dropped" }),
+ },
+ .stream_aborted => |reason| switch (reason) {
+ .interrupted => {},
+ .stalled => b.queue.push(.{ .notice = "⚠ stream stalled — ending turn" }),
+ .dropped => b.queue.push(.{ .notice = "⚠ connection dropped — response ended early" }),
+ },
+ // The status bar's model name is a TUI-owned global; a mid-turn
+ // failover is the one thing that can change it behind the frontend's
+ // back, so the event carries the substitute and the TUI adopts it.
+ .provider_fallback => |f| b.queue.push(.{ .model_changed = f.to_model }),
+
+ // ── consciously ignored, with the reason ─────────────────────────
+ // Live-stream bookkeeping: the TUI's pending row IS the spinner, and
+ // its fold state is frontend-owned, so none of these need a surface.
+ .stream_begin, .stream_complete, .stream_finished, .thinking_fold_toggle => {},
+ // The engine's own call brackets. tool_call_announced/tool_result are
+ // the pair a transcript row is built from; these two are the timing
+ // brackets a supervisor uses and would double every row here.
+ .tool_call_started, .tool_call_finished => {},
+ // Tool-run colour the compact transcript deliberately does not draw:
+ // batch fan-out/join tallies, the completion-gate refusal, and a
+ // retired standing goal. Each is a candidate for its own row later;
+ // none has one today.
+ .parallel_batch_started, .parallel_batch_finished, .completion_deferred, .goal_completed => {},
+ // Session lifecycle that happens OUTSIDE a turn: by the time a turn's
+ // sink exists the banner, worktree entry, checkout-owner warning and
+ // saved-model substitution have all already been decided, and the MCP
+ // consent prompt still reads stdin at its emit site (#422 phase 1b).
+ .session_banner,
+ .worktree_entered,
+ .shared_worktree_owner,
+ .saved_model_unavailable,
+ .mcp_consent_prompt,
+ .session_saved,
+ .run_finished,
+ => {},
+ // The pre-turn status line. The TUI draws its own chrome from its own
+ // Model, so adopting this needs the context/cost meters to move into
+ // that Model first — a later slice of #551, not a silent drop here.
+ .prompt_ready => {},
+ }
+}
+
+test "prose streams into the live tail; structure never does" {
+ var qbuf: tui.EventQueue = .{};
+ qbuf.attach(std.testing.allocator);
+ defer qbuf.deinit();
+ var sbuf: [256]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &sbuf };
+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };
+ const sink = forBridge(&bridge);
+
+ sink.emit(undefined, .{ .text_delta = .{ .text = "hello" } });
+ sink.emit(undefined, .{ .tool_call_announced = .{ .name = "bash", .input = .null } });
+ sink.emit(undefined, .{ .tool_result = .{ .name = "bash", .text = "ok\nmore", .is_error = false } });
+ sink.emit(undefined, .{ .text_delta = .{ .text = " world" } });
+
+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;
+ defer std.testing.allocator.free(snap);
+ // The tool cluster left no bytes in the prose buffer — that mixing is what
+ // the TUI used to have to un-mix by scanning for glyphs.
+ try std.testing.expectEqualStrings("hello world", snap);
+
+ const evs = qbuf.drain();
+ defer qbuf.free(evs);
+ try std.testing.expectEqual(@as(usize, 2), evs.len);
+ try std.testing.expectEqualStrings("bash", evs[0].tool_started.name);
+ try std.testing.expectEqualStrings("ok", evs[1].tool_finished.detail);
+ try std.testing.expect(!evs[1].tool_finished.is_error);
+}
+
+test "reasoning reaches the tail only with /thinking on" {
+ var qbuf: tui.EventQueue = .{};
+ qbuf.attach(std.testing.allocator);
+ defer qbuf.deinit();
+ var off_buf: [64]u8 = undefined;
+ var off_stream: repl.StreamBuf = .{ .buf = &off_buf };
+ var off: Bridge = .{ .queue = &qbuf, .stream = &off_stream, .show_thinking = false };
+ forBridge(&off).emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });
+ try std.testing.expect(off_stream.snapshot(std.testing.allocator) == null);
+
+ var on_buf: [64]u8 = undefined;
+ var on_stream: repl.StreamBuf = .{ .buf = &on_buf };
+ var on: Bridge = .{ .queue = &qbuf, .stream = &on_stream, .show_thinking = true };
+ const sink = forBridge(&on);
+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "because" } });
+ sink.emit(undefined, .{ .text_delta = .{ .text = "answer" } });
+ const snap = on_stream.snapshot(std.testing.allocator) orelse return error.NoStream;
+ defer std.testing.allocator.free(snap);
+ // The answer breaks the line the reasoning was on rather than running into it.
+ try std.testing.expectEqualStrings("because\nanswer", snap);
+}
+
+test "a refusal and a failover reach the frontend instead of being dropped" {
+ var qbuf: tui.EventQueue = .{};
+ qbuf.attach(std.testing.allocator);
+ defer qbuf.deinit();
+ var sbuf: [64]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &sbuf };
+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };
+ const sink = forBridge(&bridge);
+ sink.emit(undefined, .{ .tool_rejected = .{
+ .name = "bash",
+ .input = .null,
+ .reason = "budget",
+ .message = "tool-call budget spent",
+ } });
+ sink.emit(undefined, .{ .session_notice = .{ .text = "loaded 2 saved approval(s)", .tone = .dim } });
+ sink.emit(undefined, .{ .provider_fallback = .{
+ .from_provider = "codex",
+ .from_model = "gpt-5.5",
+ .to_provider = "anthropic",
+ .to_model = "sonnet",
+ .to_context = 200_000,
+ .context_note = "context kept",
+ } });
+ const evs = qbuf.drain();
+ defer qbuf.free(evs);
+ try std.testing.expectEqual(@as(usize, 3), evs.len);
+ try std.testing.expect(evs[0].tool_rejected.denied);
+ try std.testing.expectEqualStrings("tool-call budget spent", evs[0].tool_rejected.detail);
+ try std.testing.expectEqualStrings("loaded 2 saved approval(s)", evs[1].notice);
+ try std.testing.expectEqualStrings("sonnet", evs[2].model_changed);
+}
+
+test "a capped preview never ends mid-character" {
+ // 80 bytes of ASCII then a 3-byte glyph straddling the cap.
+ var buf: [128]u8 = undefined;
+ @memset(buf[0..79], 'x');
+ @memcpy(buf[79..86], "…tail");
+ const long = buf[0..86];
+ const cut = capLine(long, preview_cap);
+ try std.testing.expectEqual(@as(usize, 79), cut.len);
+ try std.testing.expect(std.unicode.utf8ValidateSlice(cut));
+ // A whole multi-byte character that FITS is kept, not shaved off.
+ try std.testing.expectEqualStrings("a…", capLine("a…\nrest", preview_cap));
+ try std.testing.expectEqualStrings("plain", capLine(" plain \nmore", preview_cap));
+}
+
+test "the turn-sink binding is thread-local and released after the turn" {
+ var qbuf: tui.EventQueue = .{};
+ var sbuf: [8]u8 = undefined;
+ var stream: repl.StreamBuf = .{ .buf = &sbuf };
+ var bridge: Bridge = .{ .queue = &qbuf, .stream = &stream };
+ try std.testing.expect(engine_sink.turnSink() == null);
+ engine_sink.bindTurnSink(forBridge(&bridge));
+ try std.testing.expect(engine_sink.turnSink() != null);
+
+ // A pool thread building its own Agent must NOT inherit the frontend's
+ // sink: a subagent's output is not the transcript.
+ const Probe = struct {
+ fn f(seen: *bool) void {
+ seen.* = engine_sink.turnSink() != null;
+ }
+ };
+ var seen = true;
+ const th = try std.Thread.spawn(.{}, Probe.f, .{&seen});
+ th.join();
+ try std.testing.expect(!seen);
+
+ engine_sink.unbindTurnSink();
+ try std.testing.expect(engine_sink.turnSink() == null);
+}