graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: filter citations at live terminal boundaries
yxlyxc666c37211bc
diff --git a/docs/adr/0111-live-citations-are-terminal-presentation.md b/docs/adr/0111-live-citations-are-terminal-presentation.mdnew file mode 100644index 00000000..410c7d95--- /dev/null+++ b/docs/adr/0111-live-citations-are-terminal-presentation.md@@ -0,0 +1,15 @@+# 0111. Live citation filtering belongs to terminal presentation++Status: accepted 2026-09-14++## Context++Completed-text sanitization did not protect incremental reasoning, answers, or completion arguments (#874). A citation delimiter or its payload can cross any chunk boundary. Filtering individual chunks loses that context; filtering engine events would also change structured clients' input.++## Decision++Apply the existing incremental citation recognizer at terminal display boundaries, before markdown rendering, reasoning replay buffers, or fullscreen live prose buffers. Keep reasoning state independent from answer state and reset it at stream start and completion, interruption, or transport failure. One-shot and hosted terminal output use the same recognition contract. Keep structured JSON and ACP serialization and raw tool output unchanged.++## Consequences++The filter holds only delimiter-prefix bytes and suppression state, not citation payloads. Unclosed annotations are suppressed until the stream boundary; a fresh stream cannot inherit them. Each terminal adapter must retain lifecycle coverage. Real sink-dispatch regressions cover split delimiters, independent channels, reset recovery, and unchanged structured output; completed-text tests alone are insufficient.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 8cb1e80b..2bd32551 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -121,6 +121,7 @@ record only when you need the evidence or the edge cases.| [0108](0108-browser-events-outrank-pending-snapshots.md) | Browser page-info events invalidate older pending IPC snapshots; a loaded page must not revert to loading. || [0109](0109-resume-retains-catalog-and-layout-snapshots.md) | Resume restores loaded tool selections and the same-workspace layout snapshot, without freezing current instructions or granting permissions. || [0110](0110-project-mcp-listing-opts-in-optional-servers.md) | Project MCP entries opt in optional servers; inherited extras still require opt-in, and startup consent applies to both. |+| [0111](0111-live-citations-are-terminal-presentation.md) | Live terminal citations use per-stream display filters with independent reasoning state; structured JSON/ACP output stays unchanged. |## When to write onediff --git a/src/agent.zig b/src/agent.zigindex 89afa76d..4d1cf6dc 100644--- a/src/agent.zig+++ b/src/agent.zig@@ -131,6 +131,7 @@ pub const Agent = struct {model_calls_this_turn: u64 = 0,handle_note_shown: bool = false, // #541: the handle-protocol lesson rides this agent's FIRST handle, onceseen_tool_keys: std.ArrayList([]const u8) = .empty, // root-only per-turn dedupe keys+ cite_stream: @import("terminal_citations.zig").State = .{}, // display-only, independent prose channelsmd_buf: std.ArrayList(u8) = .empty, // current incomplete streamed line (markdown rendering)md_fence: bool = false, // inside a ``` code fence while streamingmd_kind: MdKind = .classify, // incremental renderer: current line's classificationdiff --git a/src/agent_stream.zig b/src/agent_stream.zigindex 5775be57..ec0ebe97 100644--- a/src/agent_stream.zig+++ b/src/agent_stream.zig@@ -488,8 +488,7 @@ pub fn printDelta(self: *Agent, raw_line: []const u8) void {if (no_ui) {if (oneshotShouldPaint(main_mod.unattended, main_mod.json_mode, text.len)) {if (main_mod.g_out) |w| {- w.writeAll(text) catch {};- w.flush() catch {};+ @import("terminal_citations.zig").plain(&self.cite_stream.answer, w, text);}self.streamed_text = true;self.traceFirstToken();diff --git a/src/cite_markup_stream_tests.zig b/src/cite_markup_stream_tests.zignew file mode 100644index 00000000..97b2a4c7--- /dev/null+++ b/src/cite_markup_stream_tests.zig@@ -0,0 +1,122 @@+//! Differential coverage for the byte-stream citation filter (#874).+const std = @import("std");+const markup = @import("cite_markup.zig");+const a = std.testing.allocator;+const start = "\u{E200}";+const end = "\u{E201}";+const sep = "\u{E202}";++fn feed(stream: *markup.Stream, output: *std.Io.Writer.Allocating, chunk: []const u8) !void {+ for (chunk) |byte| {+ var buf: [3]u8 = undefined;+ try output.writer.writeAll(stream.byte(byte, &buf));+ }+}++// Chunk boundaries intentionally include UTF-8 continuation bytes. Empty chunks+// must neither flush a pending marker prefix nor reset annotation suppression.+fn checkChunks(raw: []const u8, expected: []const u8, width: usize, seed: ?u64) !void {+ var output: std.Io.Writer.Allocating = .init(a);+ defer output.deinit();+ var stream: markup.Stream = .{};+ var random = std.Random.DefaultPrng.init(seed orelse 0);+ var offset: usize = 0;+ try feed(&stream, &output, "");+ while (offset < raw.len) {+ const n = @min(raw.len - offset, if (seed != null) random.random().intRangeAtMost(usize, 1, width) else width);+ try feed(&stream, &output, raw[offset .. offset + n]);+ try feed(&stream, &output, "");+ offset += n;+ }+ try feed(&stream, &output, "");+ try std.testing.expectEqualStrings(expected, output.written());+}++fn check(raw: []const u8, known: ?[]const u8, every_split: bool) !void {+ try std.testing.expect(std.unicode.utf8ValidateSlice(raw));+ const expected = try markup.dupe(a, raw);+ defer a.free(expected);+ if (known) |text| try std.testing.expectEqualStrings(text, expected);+ try checkChunks(raw, expected, 1, null);+ try checkChunks(raw, expected, @max(raw.len, 1), null);+ for ([_]usize{ 2, 3, 7, 31 }) |width| try checkChunks(raw, expected, width, null);+ for ([_]u64{ 0, 1, 874, 0xdeadbeef }) |seed| try checkChunks(raw, expected, 47, seed);+ if (every_split) {+ for (0..raw.len + 1) |split| {+ var output: std.Io.Writer.Allocating = .init(a);+ defer output.deinit();+ var stream: markup.Stream = .{};+ try feed(&stream, &output, raw[0..split]);+ try feed(&stream, &output, "");+ try feed(&stream, &output, raw[split..]);+ try std.testing.expectEqualStrings(expected, output.written());+ }+ }+}++test "stream preserves ordinary UTF-8 and unrelated private-use glyphs" {+ try check("", "", true);+ try check("plain\x00text\n\t\r", "plain\x00text\n\t\r", true);+ const text = "é e\u{301} 日本語 😀 \u{E000}\u{E1FF}\u{E203}\u{E23F}\u{E240}\u{F8FF}\u{F0000}\u{10FFFD}";+ try check(text, text, true);+ // Exhaust the BMP private-use range, including every non-marker sharing+ // either one or two marker-prefix bytes, both visible and hidden.+ var raw: std.Io.Writer.Allocating = .init(a);+ defer raw.deinit();+ for (0xE000..0xF900) |cp| {+ if (cp >= 0xE200 and cp <= 0xE202) continue;+ var encoded: [4]u8 = undefined;+ const n = try std.unicode.utf8Encode(@intCast(cp), &encoded);+ try raw.writer.writeAll(encoded[0..n]);+ }+ try check(raw.written(), raw.written(), false);+ try raw.writer.writeAll(start);+ // A second copy inside an unclosed annotation must not escape.+ const visible_len = raw.written().len - start.len;+ const visible = try a.dupe(u8, raw.written()[0..visible_len]);+ defer a.free(visible);+ try raw.writer.writeAll(visible);+ try check(raw.written(), visible, false);+}++test "stream adjacent nested unclosed and standalone annotations match batch semantics" {+ const Case = struct { raw: []const u8, want: []const u8 };+ const cases = [_]Case{+ .{ .raw = start ++ end, .want = "" },+ .{ .raw = start, .want = "" },+ .{ .raw = end ++ sep ++ end, .want = "" },+ .{ .raw = "a" ++ sep ++ "b" ++ end ++ "c", .want = "abc" },+ .{ .raw = "a" ++ start ++ "cite" ++ sep ++ "turn0search0" ++ end ++ "b", .want = "ab" },+ .{ .raw = "a" ++ start ++ "one" ++ end ++ start ++ "two" ++ end ++ "b", .want = "ab" },+ // Batch stripping ends at the first end mark, not at balanced depth.+ .{ .raw = "a" ++ start ++ "outer" ++ start ++ "inner" ++ end ++ "visible" ++ end ++ "b", .want = "avisibleb" },+ .{ .raw = "a" ++ start ++ "unclosed 😀\u{E203}", .want = "a" },+ .{ .raw = "a" ++ start ++ start ++ sep, .want = "a" },+ .{ .raw = "\u{E203}" ++ start ++ "\u{E203}\u{E240}日本語" ++ end ++ "\u{E240}", .want = "\u{E203}\u{E240}" },+ .{ .raw = start ++ "x" ++ sep ++ sep ++ "y" ++ end ++ "😀" ++ start ++ "tail", .want = "😀" },+ };+ for (cases) |case| try check(case.raw, case.want, true);+}++test "stream exhausts short delimiter and unicode combinations" {+ const atoms = [_][]const u8{ "x", start, end, sep, "\u{E203}", "\u{E240}", "😀" };+ var raw: std.Io.Writer.Allocating = .init(a);+ defer raw.deinit();+ for (atoms) |first| for (atoms) |second| for (atoms) |third| {+ raw.clearRetainingCapacity();+ try raw.writer.writeAll(first);+ try raw.writer.writeAll(second);+ try raw.writer.writeAll(third);+ try check(raw.written(), null, true);+ };+}++test "stream suppresses long payload without truncating resumed prose" {+ var raw: std.Io.Writer.Allocating = .init(a);+ defer raw.deinit();+ try raw.writer.writeAll("before 😀" ++ start);+ for (0..8192) |_| try raw.writer.writeAll("payload\u{E203}\u{E240}日本語" ++ sep);+ try check(raw.written(), "before 😀", false);+ try raw.writer.writeAll(end ++ "after é" ++ start ++ "next" ++ end ++ "!");+ try check(raw.written(), "before 😀after é!", false);+}diff --git a/src/engine_sink.zig b/src/engine_sink.zigindex 458d5c09..cb69e9ec 100644--- a/src/engine_sink.zig+++ b/src/engine_sink.zig@@ -208,6 +208,11 @@ fn lifecycleEmit(ctx: *anyopaque, ev: Stamped) void {/// text now shares the Markdown renderer so link targets exclude delimiters (#729).fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {const a: *Agent = @ptrCast(@alignCast(ctx));+ const citations = @import("terminal_citations.zig");+ switch (ev.event) {+ .stream_begin, .stream_complete, .stream_aborted, .stream_finished, .transport_aborted => a.cite_stream = .{},+ else => {},+ }if (hosted_frontend) return hostedEmit(a, ev.event);switch (ev.event) {.stream_begin => render.spinnerStart(a),@@ -218,28 +223,14 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {// wire-split sink cannot, so it must move into the event payload or// become a sink-owned preference before Phase 2..reasoning_delta => |d| if (a.show_thinking and !a.sub and !a.stream_quiet and main_mod.use_color)- render.streamThinking(a, d.text),- .text_delta => |d| {- if (a.thinking_open) render.closeThinkingBlock(a); // reasoning -> answer transition- render.spinnerStop(a); // first visible byte: clear the thinking line- // Empty style strings make this plain text when color is off, but- // Markdown delimiters still stay out of terminal link targets (#729).- a.streamMarkdown(d.text);- },+ citations.emit(a, .reasoning, d.text),+ .text_delta => |d| citations.emit(a, .answer, d.text),// Meta-tool argument prose renders like answer text — spinner handoff// included — with two deliberate differences from .text_delta, both// the old inline emitArgText behavior verbatim: the reasoning block// stays as-is (the model is still mid-call), and the no-color branch// never marks a tick-gate line start.- .tool_arg_delta => |d| {- render.spinnerStop(a); // first visible byte: clear the thinking line- if (main_mod.use_color) {- a.streamMarkdown(d.text);- } else if (a.out) |w| {- w.writeAll(d.text) catch return;- w.flush() catch return;- }- },+ .tool_arg_delta => |d| citations.emit(a, .arguments, d.text),// grok-build RawTerminal/Append: live bash bytes, not markdown.// Line REPL keeps them off the transcript unless /debug (ADR 0020)..tool_output_delta => |d| tool_render.liveOutput(a, d.text),@@ -340,10 +331,8 @@ fn notice(a: *Agent, text: []const u8) void {fn hostedEmit(a: *Agent, ev: EngineEvent) void {const w = a.out orelse return;switch (ev) {- .text_delta, .tool_arg_delta => |d| {- w.writeAll(d.text) catch {};- w.flush() catch {};- },+ .text_delta => |d| @import("terminal_citations.zig").plain(&a.cite_stream.answer, w, d.text),+ .tool_arg_delta => |d| @import("terminal_citations.zig").plain(&a.cite_stream.arguments, w, d.text),.tool_output_delta => |d| {w.writeAll(d.text) catch {};w.flush() catch {};diff --git a/src/engine_sink_citation_tests.zig b/src/engine_sink_citation_tests.zignew file mode 100644index 00000000..1adbb505--- /dev/null+++ b/src/engine_sink_citation_tests.zig@@ -0,0 +1,223 @@+//! Citation regressions through the actual Agent-backed sink dispatch (#874).+const std = @import("std");+const Io = std.Io;+const main_mod = @import("main.zig");+const Agent = @import("agent.zig").Agent;+const engine_sink = @import("engine_sink.zig");+const EngineEvent = @import("engine_events.zig").EngineEvent;+const EngineSink = engine_sink.EngineSink;+const deinitMarkdown = @import("agent_render.zig").deinitMarkdown;+const protocol_seq = @import("protocol_seq.zig");++const citation = "citeturn0search0turn1search2";+const raw = "left" ++ citation ++ "right\n";+const clean = "leftright\n";+const Channel = enum { answer, reasoning, arg };++fn testAgent(w: *Io.Writer) Agent {+ @import("line_repl_disclosure.zig").reset(std.testing.io);+ return .{+ .gpa = std.testing.allocator,+ .arena = std.testing.allocator,+ .io = std.testing.io,+ .client = undefined,+ .provider = undefined,+ .messages = undefined,+ .sub = false,+ .label = "test",+ .out = w,+ .show_thinking = true,+ };+}++fn cleanup(a: *Agent) void {+ engine_sink.tuiSink(a).emit(undefined, .stream_finished);+ deinitMarkdown(a);+ a.thinking_text.deinit(std.testing.allocator);+}++fn delta(s: EngineSink, channel: Channel, text: []const u8) void {+ switch (channel) {+ .answer => s.emit(undefined, .{ .text_delta = .{ .text = text } }),+ .reasoning => s.emit(undefined, .{ .reasoning_delta = .{ .text = text } }),+ .arg => s.emit(undefined, .{ .tool_arg_delta = .{ .text = text } }),+ }+}++fn expectNoCitation(bytes: []const u8) !void {+ try std.testing.expect(std.mem.indexOf(u8, bytes, "") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "turn0search0") == null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "turn1search2") == null);+}++// Comparing to the same dispatch fed clean prose checks visible bytes without+// depending on the palette or Markdown's terminal styling choices.+fn rendered(channel: Channel, text: []const u8, split: ?usize) ![]u8 {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ defer cleanup(&a);+ const s = engine_sink.tuiSink(&a);+ if (split) |at| {+ delta(s, channel, text[0..at]);+ delta(s, channel, text[at..]);+ } else {+ delta(s, channel, text);+ }+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = channel == .answer } });+ s.emit(undefined, .stream_finished);+ return std.testing.allocator.dupe(u8, aw.written());+}++test "TuiSink citation answer and completion argument filtering survives every byte split" {+ const saved_color = main_mod.use_color;+ defer main_mod.use_color = saved_color;+ for ([_]bool{ false, true }) |color| {+ main_mod.use_color = color;+ for ([_]Channel{ .answer, .arg }) |channel| {+ const expected = try rendered(channel, clean, null);+ defer std.testing.allocator.free(expected);+ for (0..raw.len + 1) |at| {+ const actual = try rendered(channel, raw, at);+ defer std.testing.allocator.free(actual);+ try std.testing.expectEqualStrings(expected, actual);+ }+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ defer cleanup(&a);+ const s = engine_sink.tuiSink(&a);+ for (0..raw.len) |at| delta(s, channel, raw[at .. at + 1]);+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = channel == .answer } });+ s.emit(undefined, .stream_finished);+ try std.testing.expectEqualStrings(expected, aw.written());+ }+ }+}++test "TuiSink reasoning buffer and fold replay exclude citation bytes at every split" {+ const saved_color = main_mod.use_color;+ main_mod.use_color = true;+ defer main_mod.use_color = saved_color;+ for (0..raw.len + 1) |at| {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ defer cleanup(&a);+ const s = engine_sink.tuiSink(&a);+ delta(s, .reasoning, raw[0..at]);+ // Even a partial UTF-8 marker or a partial hidden payload must not+ // reach the buffer that Ctrl-T later replays.+ try std.testing.expect(std.mem.startsWith(u8, clean, a.thinking_text.items));+ if (a.thinking_open) s.emit(undefined, .thinking_fold_toggle);+ delta(s, .reasoning, raw[at..]);+ try std.testing.expectEqualStrings(clean, a.thinking_text.items);+ if (a.thinking_folded) s.emit(undefined, .thinking_fold_toggle);+ try expectNoCitation(aw.written());+ s.emit(undefined, .stream_finished);+ try expectNoCitation(aw.written());+ }+}++test "TuiSink interleaved reasoning answer and argument citations have independent state" {+ const saved_color = main_mod.use_color;+ main_mod.use_color = true;+ defer main_mod.use_color = saved_color;+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ defer cleanup(&a);+ const s = engine_sink.tuiSink(&a);+ delta(s, .reasoning, "reason citeturn0");+ delta(s, .answer, "answer ");+ delta(s, .arg, "argument ");+ delta(s, .answer, "citeturn1");+ delta(s, .arg, "citeturn0");+ delta(s, .reasoning, "search0continued\n");+ delta(s, .answer, "search2visible\n");+ delta(s, .arg, "search0result\n");+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = true } });+ s.emit(undefined, .stream_finished);+ try std.testing.expectEqualStrings("reason continued\n", a.thinking_text.items);+ try expectNoCitation(aw.written());+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "answer") != null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "argument") != null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "visible") != null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "result") != null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "search0") == null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "search2") == null);+}++test "TuiSink lifecycle dispatch resets incomplete citations in each channel" {+ const saved_color = main_mod.use_color;+ defer main_mod.use_color = saved_color;+ const saved_anim = @import("anim.zig").g_anim_off;+ @import("anim.zig").g_anim_off = true;+ defer @import("anim.zig").g_anim_off = saved_anim;+ const resets = [_]EngineEvent{+ .stream_begin,+ .{ .stream_complete = .{ .streamed_text = false } },+ .{ .stream_aborted = .interrupted },+ .stream_finished,+ .{ .transport_aborted = .{ .reason = .dropped, .turn_ending = false } },+ .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = true } },+ };+ for ([_]bool{ false, true }) |color| {+ main_mod.use_color = color;+ for ([_]Channel{ .answer, .reasoning, .arg }) |channel| {+ if (!color and channel == .reasoning) continue;+ for (resets) |reset| {+ for ([_][]const u8{ "\xee", "\xee\x88", "citeturn0search0" }) |pending| {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ defer cleanup(&a);+ const s = engine_sink.tuiSink(&a);+ delta(s, channel, pending);+ s.emit(undefined, reset);+ // Reset alone is the boundary: do not insert stream_begin+ // here, which could mask a missing end/abort reset.+ delta(s, channel, "fresh\n");+ s.emit(undefined, .{ .stream_complete = .{ .streamed_text = false } });+ s.emit(undefined, .stream_finished);+ try expectNoCitation(aw.written());+ try std.testing.expect(std.mem.indexOfScalar(u8, aw.written(), 0xee) == null);+ try std.testing.expect(std.mem.indexOf(u8, aw.written(), "fresh") != null);+ if (channel == .reasoning)+ try std.testing.expectEqualStrings("fresh\n", a.thinking_text.items);+ }+ }+ }+ }+}++test "JsonSink preserves raw citation text and reasoning across every byte split" {+ const saved_json = main_mod.json_mode;+ main_mod.json_mode = false;+ defer main_mod.json_mode = saved_json;+ protocol_seq.resetForTest();+ defer protocol_seq.resetForTest();+ for ([_]Channel{ .answer, .reasoning }) |channel| {+ for (0..raw.len + 1) |at| {+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ var a = testAgent(&aw.writer);+ const s = engine_sink.jsonSink(&a);+ delta(s, channel, raw[0..at]);+ delta(s, channel, raw[at..]);+ // Build the expected wire through its serializer, not by parsing+ // invalid UTF-8 fragments split inside a marker code point.+ var expected: Io.Writer.Allocating = .init(std.testing.allocator);+ defer expected.deinit();+ const last = protocol_seq.current();+ const kind: []const u8 = if (channel == .answer) "text" else "reasoning";+ try protocol_seq.writeEventStamped(&expected.writer, last - 1, .{ .type = kind, .text = raw[0..at] });+ try expected.writer.writeByte('\n');+ try protocol_seq.writeEventStamped(&expected.writer, last, .{ .type = kind, .text = raw[at..] });+ try expected.writer.writeByte('\n');+ try std.testing.expectEqualStrings(expected.written(), aw.written());+ }+ }+}diff --git a/src/main.zig b/src/main.zigindex a95fede8..507ba998 100644--- a/src/main.zig+++ b/src/main.zig@@ -563,7 +563,7 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagentsconst workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)- _ = .{ @import("mcp_apps.zig"), @import("html_view.zig") };+ _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };_ = @import("main_test.zig");_ = @import("session_catalog.zig");_ = @import("session_prompt.zig");diff --git a/src/oneshot_citation_tests.zig b/src/oneshot_citation_tests.zignew file mode 100644index 00000000..4ee4e187--- /dev/null+++ b/src/oneshot_citation_tests.zig@@ -0,0 +1,188 @@+//! #874: real hosted fallback and unattended printDelta dispatch boundaries.+const std = @import("std");+const Agent = @import("agent.zig").Agent;+const main = @import("main.zig");+const sinks = @import("engine_sink.zig");+const Event = @import("engine_events.zig").EngineEvent;+const Kind = @import("provider.zig").Provider.Kind;+const a = std.testing.allocator;++// Restore every process-global touched here, including the stdout writer.+const Globals = struct {+ hosted: bool,+ unattended: bool,+ json: bool,+ out: ?*std.Io.Writer,++ fn capture() Globals {+ return .{ .hosted = sinks.hosted_frontend, .unattended = main.unattended, .json = main.json_mode, .out = main.g_out };+ }++ fn restore(self: Globals) void {+ sinks.hosted_frontend = self.hosted;+ main.unattended = self.unattended;+ main.json_mode = self.json;+ main.g_out = self.out;+ }+};++fn agent(arena: std.mem.Allocator, client: *std.http.Client) Agent {+ return .{+ .gpa = a,+ .arena = arena,+ .io = std.testing.io,+ .client = client,+ .provider = .{ .id = "test", .kind = .responses, .auth = .bearer, .url = "", .api_key = "", .model = "test", .context = 0 },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "test",+ .out = null,+ };+}++const boundaries = [_]Event{+ .stream_begin,+ .{ .stream_complete = .{ .streamed_text = true } },+ .{ .stream_aborted = .interrupted },+ .{ .stream_aborted = .stalled },+ .{ .stream_aborted = .dropped },+ .stream_finished,+ .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } },+};++test "hosted fallback citation dispatch isolates text and arguments and preserves source bytes" {+ const saved = Globals.capture();+ defer saved.restore();+ sinks.hosted_frontend = true;+ main.json_mode = false;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ var client: std.http.Client = .{ .allocator = a, .io = std.testing.io };+ defer client.deinit();+ var output: std.Io.Writer.Allocating = .init(a);+ defer output.deinit();+ var root = agent(arena.allocator(), &client);+ root.out = &output.writer;+ const sink = sinks.forAgent(&root); // No injected sink: hosted fallback itself.+ const raw = try a.dupe(u8, "A\u{e200}cite\u{e202}hidden\u{e201}B");+ defer a.free(raw);+ const expected_raw = "A\u{e200}cite\u{e202}hidden\u{e201}B";+ // Exercise every UTF-8 byte boundary and interleave a second channel while+ // the answer channel holds a partial opener or hidden payload.+ for (0..raw.len + 1) |split| {+ sink.emit(root.io, .stream_begin);+ const start = output.written().len;+ const first: Event = .{ .text_delta = .{ .text = raw[0..split] } };+ sink.emit(root.io, first);+ sink.emit(root.io, .{ .tool_arg_delta = .{ .text = "X\u{e200}cite\u{e202}arg-hidden" } });+ sink.emit(root.io, .{ .text_delta = .{ .text = raw[split..] } });+ sink.emit(root.io, .{ .tool_arg_delta = .{ .text = "\u{e201}Y" } });+ const expected = if (split == 0) "XABY" else if (split == raw.len) "ABXY" else "AXBY";+ try std.testing.expectEqualStrings(expected, output.written()[start..]);+ try std.testing.expectEqualStrings(expected_raw, raw);+ try std.testing.expectEqualStrings(raw[0..split], first.text_delta.text);+ }+ // Arbitrary tool stdout is not model prose and must remain byte-exact.+ const start = output.written().len;+ sink.emit(root.io, .{ .tool_output_delta = .{ .name = "bash", .text = raw } });+ try std.testing.expectEqualStrings(raw, output.written()[start..]);+ // The argument producer captures the original bytes before sink dispatch.+ sink.emit(root.io, .stream_begin);+ const arg_start = output.written().len;+ @import("agent_argstream.zig").emitArgText(&root, .attempt_completion, raw);+ try std.testing.expectEqualStrings("AB", output.written()[arg_start..]);+ try std.testing.expectEqualStrings(raw, root.partial_text.items);+}++test "hosted fallback lifecycle drops unfinished markers and resets both prose channels" {+ const saved = Globals.capture();+ defer saved.restore();+ sinks.hosted_frontend = true;+ main.json_mode = false;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ var client: std.http.Client = .{ .allocator = a, .io = std.testing.io };+ defer client.deinit();+ var output: std.Io.Writer.Allocating = .init(a);+ defer output.deinit();+ var root = agent(arena.allocator(), &client);+ root.out = &output.writer;+ const sink = sinks.forAgent(&root);+ for (boundaries) |boundary| {+ for ([_][]const u8{ "\xee", "\xee\x88", "\u{e200}cite\u{e202}unfinished" }) |held| {+ sink.emit(root.io, .stream_begin);+ const start = output.written().len;+ sink.emit(root.io, .{ .text_delta = .{ .text = held } });+ sink.emit(root.io, .{ .tool_arg_delta = .{ .text = held } });+ sink.emit(root.io, boundary);+ sink.emit(root.io, .{ .text_delta = .{ .text = "answer" } });+ sink.emit(root.io, .{ .tool_arg_delta = .{ .text = "args" } });+ try std.testing.expectEqualStrings("answerargs", output.written()[start..]);+ }+ }+}++fn delta(root: *Agent, text: []const u8) !void {+ // Stringify the chunk: split UTF-8 bytes must travel through JSON escapes,+ // so this helper is used only with complete UTF-8 strings.+ const encoded = try std.json.Stringify.valueAlloc(a, text, .{});+ defer a.free(encoded);+ const line = switch (root.provider.kind) {+ .responses => try std.fmt.allocPrint(a, "data: {{\"type\":\"response.output_text.delta\",\"delta\":{s}}}", .{encoded}),+ .openai => try std.fmt.allocPrint(a, "data: {{\"choices\":[{{\"delta\":{{\"content\":{s}}}}}]}}", .{encoded}),+ .anthropic => try std.fmt.allocPrint(a, "data: {{\"type\":\"content_block_delta\",\"delta\":{{\"type\":\"text_delta\",\"text\":{s}}}}}", .{encoded}),+ .interactions => try std.fmt.allocPrint(a, "data: {{\"delta\":{{\"type\":\"text\",\"text\":{s}}}}}", .{encoded}),+ };+ defer a.free(line);+ const original = try a.dupe(u8, line);+ defer a.free(original);+ root.printDelta(line);+ try std.testing.expectEqualStrings(original, line);+}++test "unattended no_ui printDelta filters live prose across provider envelopes without touching raw capture" {+ const saved = Globals.capture();+ defer saved.restore();+ main.unattended = true;+ main.json_mode = false;+ // Both settings must work: tuiEmit resets before its hosted early return,+ // even though Agent.out is null and printDelta writes main.g_out directly.+ for ([_]bool{ false, true }) |hosted| {+ sinks.hosted_frontend = hosted;+ var arena = std.heap.ArenaAllocator.init(a);+ defer arena.deinit();+ var client: std.http.Client = .{ .allocator = a, .io = std.testing.io };+ defer client.deinit();+ var output: std.Io.Writer.Allocating = .init(a);+ defer output.deinit();+ main.g_out = &output.writer;+ var root = agent(arena.allocator(), &client);+ const raw_capture = "captured\u{e200}cite\u{e202}raw-source\u{e201}";+ try root.partial_text.appendSlice(arena.allocator(), raw_capture);+ for ([_]Kind{ .responses, .openai, .anthropic, .interactions }) |kind| {+ root.provider.kind = kind;+ sinks.forAgent(&root).emit(root.io, .stream_begin);+ const start = output.written().len;+ for ([_][]const u8{ "before", "\u{e200}", "cite", "\u{e202}source", "\u{e201}", "after" }) |chunk| try delta(&root, chunk);+ try std.testing.expectEqualStrings("beforeafter", output.written()[start..]);+ try std.testing.expect(root.streamed_text);+ // printDelta's direct-output branch does not populate partial_text;+ // any existing capture must stay raw, not be rewritten by painting.+ try std.testing.expectEqualStrings(raw_capture, root.partial_text.items);+ }+ for (boundaries) |boundary| {+ const start = output.written().len;+ try delta(&root, "\u{e200}cite\u{e202}unfinished");+ sinks.forAgent(&root).emit(root.io, boundary);+ try delta(&root, "fresh");+ try std.testing.expectEqualStrings("fresh", output.written()[start..]);+ }+ // Unattended JSON must not accidentally send terminal text to stdout.+ main.json_mode = true;+ const start = output.written().len;+ try delta(&root, "not terminal output");+ try std.testing.expectEqual(start, output.written().len);+ main.json_mode = false;+ main.g_out = saved.out;+ }+}diff --git a/src/terminal_citations.zig b/src/terminal_citations.zignew file mode 100644index 00000000..f477c072--- /dev/null+++ b/src/terminal_citations.zig@@ -0,0 +1,63 @@+//! Citation filtering belongs to terminal presentation, never the event wire.+const std = @import("std");+const Stream = @import("cite_markup.zig").Stream;+const Agent = @import("agent.zig").Agent;+const main = @import("main.zig");+const render = @import("agent_stream_render.zig");++pub const Channel = enum { reasoning, answer, arguments };+pub const State = struct {+ reasoning: Stream = .{},+ answer: Stream = .{},+ arguments: Stream = .{},+};++/// Bounded scratch space: hidden payloads never allocate or reach render state.+fn feed(stream: *Stream, text: []const u8, ctx: anytype, comptime paint: anytype) void {+ var buf: [1024]u8 = undefined;+ var n: usize = 0;+ for (text) |c| {+ var unit: [3]u8 = undefined;+ const clean = stream.byte(c, &unit);+ if (n + clean.len > buf.len) {+ paint(ctx, buf[0..n]);+ n = 0;+ }+ @memcpy(buf[n..][0..clean.len], clean);+ n += clean.len;+ }+ if (n != 0) paint(ctx, buf[0..n]);+}++pub fn plain(stream: *Stream, w: *std.Io.Writer, text: []const u8) void {+ feed(stream, text, w, struct {+ fn write(out: *std.Io.Writer, clean: []const u8) void {+ out.writeAll(clean) catch {};+ }+ }.write);+ w.flush() catch {};+}++pub fn emit(a: *Agent, comptime channel: Channel, text: []const u8) void {+ feed(&@field(a.cite_stream, @tagName(channel)), text, a, struct {+ fn paint(agent: *Agent, clean: []const u8) void {+ switch (channel) {+ .reasoning => render.streamThinking(agent, clean),+ .answer => {+ if (agent.thinking_open) render.closeThinkingBlock(agent);+ render.spinnerStop(agent);+ agent.streamMarkdown(clean);+ },+ .arguments => {+ render.spinnerStop(agent);+ if (main.use_color) {+ agent.streamMarkdown(clean);+ } else if (agent.out) |w| {+ w.writeAll(clean) catch return;+ w.flush() catch {};+ }+ },+ }+ }+ }.paint);+}diff --git a/src/tui_acp.zig b/src/tui_acp.zigindex 2ec388d4..eab226fe 100644--- a/src/tui_acp.zig+++ b/src/tui_acp.zig@@ -77,6 +77,10 @@ fn transcriptEmit(ctx: *anyopaque, ev: engine_sink.Stamped) void {// Text carries no JSON-only fields. Use the decoder's normalized path,// avoiding a writer allocation + JSON parse for each in-process chunk.switch (ev.event) {+ .stream_begin, .stream_complete, .stream_finished, .stream_aborted, .transport_aborted => {+ t.apply.reset();+ return;+ },.reasoning_delta => |d| return updates.applyChunk(t.apply, true, d.text),.text_delta, .tool_arg_delta => |d| return updates.applyChunk(t.apply, false, d.text),else => {},@@ -394,3 +398,30 @@ test "session/cancel latches the engine cancel flag" {agent_mod.Agent.esc_cancel.store(false, .release);acp_engine.cancel_flag.store(false, .release);}++test "transcript sink: citations in reasoning answer and completion args reset on boundaries (#874)" {+ var q: tui.EventQueue = .{};+ var buf: [256]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };+ var t: Transcript = .{ .gpa = std.testing.allocator, .session_id = "s1", .apply = &a };+ const sink: engine_sink.EngineSink = .{ .ctx = @ptrCast(&t), .vt = &transcript_vt };+ sink.emit(undefined, .stream_begin);+ const thought = "why\u{E200}cite\u{E202}turn0view0\u{E201}";+ for (thought) |c| sink.emit(undefined, .{ .reasoning_delta = .{ .text = &.{c} } });+ const answer = "answer\u{E200}cite\u{E202}turn0view0\u{E201}";+ for (answer) |c| sink.emit(undefined, .{ .text_delta = .{ .text = &.{c} } });+ const args = " args\u{E200}cite\u{E202}turn1view0\u{E201}!";+ for (args) |c| sink.emit(undefined, .{ .tool_arg_delta = .{ .text = &.{c} } });+ sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}unfinished" } });+ sink.emit(undefined, .{ .stream_aborted = .interrupted });+ sink.emit(undefined, .stream_begin);+ sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}transport tail" } });+ sink.emit(undefined, .{ .transport_aborted = .{ .reason = .stalled, .turn_ending = true } });+ sink.emit(undefined, .{ .text_delta = .{ .text = "fresh" } });+ try std.testing.expectEqualStrings("why\nanswer args!fresh", buf[0..stream.len.load(.acquire)]);+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);+ defer aw.deinit();+ try writeUpdate(&aw.writer, "s1", .{ .text_delta = .{ .text = answer } });+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "\u{E200}") != null);+}diff --git a/src/tui_acp_updates.zig b/src/tui_acp_updates.zigindex 5946c481..69bd4d94 100644--- a/src/tui_acp_updates.zig+++ b/src/tui_acp_updates.zig@@ -6,6 +6,7 @@ const tui = @import("tui");const repl = @import("repl.zig");const util = @import("util.zig");const label = @import("agent_tool_label.zig");+const citations = @import("cite_markup.zig");/// Maps one ACP `session/update` line onto the TUI stream / event queue.pub const Apply = struct {@@ -13,8 +14,16 @@ pub const Apply = struct {stream: *repl.StreamBuf,show_thinking: bool = false,reasoning_open: bool = false,+ reasoning_citations: citations.Stream = .{},+ answer_citations: citations.Stream = .{},last_title: [160]u8 = undefined,last_title_len: usize = 0,++ pub fn reset(self: *Apply) void {+ self.reasoning_citations = .{};+ self.answer_citations = .{};+ self.reasoning_open = false;+ }};pub fn applyBuffered(a: *Apply, gpa: Allocator, bytes: []const u8) void {@@ -92,13 +101,28 @@ fn cap(s: []const u8, n: usize) []const u8 {/// The in-process transport can pass text directly; wire clients decode into this same path.pub fn applyChunk(a: *Apply, thinking: bool, text: []const u8) void {if (text.len == 0 or (thinking and !a.show_thinking)) return;- if (thinking) {- a.reasoning_open = true;- } else if (a.reasoning_open) {- a.reasoning_open = false;- a.stream.appendBytes("\n");+ const filter = if (thinking) &a.reasoning_citations else &a.answer_citations;+ // Batch visible bytes: the live tail publishes atomically on each append.+ var visible: [1024]u8 = undefined;+ var len: usize = 0;+ for (text) |c| {+ var scratch: [3]u8 = undefined;+ const clean = filter.byte(c, &scratch);+ if (clean.len == 0) continue;+ if (thinking) {+ a.reasoning_open = true;+ } else if (a.reasoning_open) {+ a.reasoning_open = false;+ a.stream.appendBytes("\n");+ }+ if (len + clean.len > visible.len) {+ a.stream.appendBytes(visible[0..len]);+ len = 0;+ }+ @memcpy(visible[len..][0..clean.len], clean);+ len += clean.len;}- a.stream.appendBytes(text);+ if (len != 0) a.stream.appendBytes(visible[0..len]);}test "applyLine: thought then text land on the live tail" {@@ -160,3 +184,33 @@ test "hidden reasoning and empty chunks do not alter transcript" {try std.testing.expectEqualStrings("visible", stream.buf[0..stream.len.load(.acquire)]);try std.testing.expect(!a.reasoning_open);}++test "ACP citation display filters every byte split and independent channels (#874)" {+ const raw = "before日\u{E200}cite\u{E202}turn0view0\u{E201}after\u{E202}🚀\u{E201}";+ for (0..raw.len + 1) |split| {+ var q: tui.EventQueue = .{};+ var buf: [256]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };+ applyChunk(&a, true, "why\u{E200}cite");+ applyChunk(&a, false, raw[0..split]);+ applyChunk(&a, false, raw[split..]);+ applyChunk(&a, true, "hidden\u{E201}done");+ try std.testing.expectEqualStrings("why\nbefore日after🚀done", buf[0..stream.len.load(.acquire)]);+ }+}++test "ACP citation-only chunks do not add reasoning separators and reset drops partial spans (#874)" {+ var q: tui.EventQueue = .{};+ var buf: [128]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var a: Apply = .{ .queue = &q, .stream = &stream, .show_thinking = true };+ applyLine(&a, std.testing.allocator, "{\"method\":\"session/update\",\"params\":{\"update\":{\"sessionUpdate\":\"agent_thought_chunk\",\"content\":{\"text\":\"\\ue200cite\\ue202turn0view0\\ue201\"}}}}");+ applyChunk(&a, false, "ok");+ applyChunk(&a, true, "\xee\x88");+ applyChunk(&a, false, "\u{E200}unterminated");+ a.reset();+ applyChunk(&a, true, "fresh");+ applyChunk(&a, false, "answer");+ try std.testing.expectEqualStrings("okfresh\nanswer", buf[0..stream.len.load(.acquire)]);+}diff --git a/src/tui_sink.zig b/src/tui_sink.zigindex e6726a78..d811c547 100644--- a/src/tui_sink.zig+++ b/src/tui_sink.zig@@ -28,6 +28,7 @@ const repl = @import("repl.zig");const tui = @import("tui");const label = @import("agent_tool_label.zig");const working = @import("agent_working.zig");+const citations = @import("cite_markup.zig");/// 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.@@ -78,6 +79,30 @@ pub const Bridge = struct {/// ADR 0041: thought / tool / text rows come from ACP `session/update`./// This sink still handles meters, notices, raw bash, and failover.acp_owns_transcript: bool = false,+ reasoning_citations: citations.Stream = .{},+ answer_citations: citations.Stream = .{},++ fn resetProse(self: *Bridge) void {+ self.reasoning_citations = .{};+ self.answer_citations = .{};+ self.reasoning_open = false;+ }++ fn appendProse(self: *Bridge, text: []const u8, reasoning: bool) void {+ const filter = if (reasoning) &self.reasoning_citations else &self.answer_citations;+ for (text) |byte| {+ var buf: [3]u8 = undefined;+ const visible = filter.byte(byte, &buf);+ if (visible.len == 0) continue;+ if (reasoning) {+ self.reasoning_open = true;+ } else if (self.reasoning_open) {+ self.reasoning_open = false;+ self.stream.appendBytes("\n");+ }+ self.stream.appendBytes(visible);+ }+ }};const vtable: engine_sink.VTable = .{ .emit = emit, .durable = false };@@ -91,15 +116,10 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {switch (ev.event) {// ── prose: into the live tail ────────────────────────────────────.reasoning_delta => |d| if (!b.acp_owns_transcript and b.show_thinking) {- b.reasoning_open = true;- b.stream.appendBytes(d.text);+ b.appendProse(d.text, true);},.text_delta, .tool_arg_delta => |d| if (!b.acp_owns_transcript) {- if (b.reasoning_open) {- b.reasoning_open = false;- b.stream.appendBytes("\n");- }- b.stream.appendBytes(d.text);+ b.appendProse(d.text, false);},// grok-build RawTerminal: bash bytes go to the dedicated raw buf,// never the prose stream (that mixing is what #551 took apart).@@ -168,6 +188,7 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {b.queue.push(.{ .notice = line });},.transport_aborted => |t| {+ b.resetProse();// Mid-turn cuts are the reconnect ladder (ADR 0021). The pager// already shows Thinking / tool rows; a ⚠ here is what made// people hit Esc on a turn that was still recovering.@@ -178,10 +199,13 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {.dropped => b.queue.push(.{ .notice = "⚠ connection dropped — response ended early" }),}},- .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" }),+ .stream_aborted => |reason| {+ b.resetProse();+ 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@@ -191,7 +215,8 @@ fn emit(ctx: *anyopaque, ev: engine_sink.Stamped) void {// ── 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 => {},+ .stream_begin, .stream_complete, .stream_finished => b.resetProse(),+ .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.@@ -477,3 +502,88 @@ test "acp_owns_transcript leaves thought/tool/text to session/update" {defer qbuf.free(evs);try std.testing.expectEqual(@as(usize, 0), evs.len);}++test "legacy bridge citations survive every pair of chunk boundaries" {+ const raw = "a\u{E200}cite\u{E202}ref\u{E201}b\u{E202}c\u{E201}\u{E203}!";+ for (0..raw.len + 1) |i| {+ for (i..raw.len + 1) |j| {+ var queue: tui.EventQueue = .{};+ var buf: [128]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var bridge: Bridge = .{ .queue = &queue, .stream = &stream };+ const sink = forBridge(&bridge);+ sink.emit(undefined, .{ .text_delta = .{ .text = raw[0..i] } });+ sink.emit(undefined, .{ .tool_arg_delta = .{ .text = raw[i..j] } });+ sink.emit(undefined, .{ .text_delta = .{ .text = raw[j..] } });+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;+ defer std.testing.allocator.free(snap);+ try std.testing.expectEqualStrings("abc\u{E203}!", snap);+ }+ }+}++test "legacy bridge citation filtering leaves structured and whole tool output unchanged" {+ var queue: tui.EventQueue = .{};+ queue.attach(std.testing.allocator);+ defer queue.deinit();+ var buf: [128]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var bridge: Bridge = .{ .queue = &queue, .stream = &stream };+ const sink = forBridge(&bridge);+ const raw = "raw\u{E200}cite\u{E202}ref\u{E201}";+ sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}unclosed" } });+ sink.emit(undefined, .{ .tool_result = .{ .name = "bash", .text = raw, .is_error = false } });+ sink.emit(undefined, .{ .completion_text = .{ .text = raw } });+ const evs = queue.drain();+ defer queue.free(evs);+ try std.testing.expectEqualStrings(raw, evs[0].tool_finished.detail);+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;+ defer std.testing.allocator.free(snap);+ try std.testing.expectEqualStrings(raw ++ "\n", snap);+}++test "legacy bridge citation channels stay independent" {+ var queue: tui.EventQueue = .{};+ var buf: [128]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var bridge: Bridge = .{ .queue = &queue, .stream = &stream, .show_thinking = true };+ const sink = forBridge(&bridge);+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "\u{E200}unclosed" } });+ sink.emit(undefined, .{ .text_delta = .{ .text = "answer" } });+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "\u{E201}thought" } });+ sink.emit(undefined, .{ .text_delta = .{ .text = "\u{E200}hidden" } });+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "!" } });+ sink.emit(undefined, .{ .tool_arg_delta = .{ .text = "\u{E201}tail" } });+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;+ defer std.testing.allocator.free(snap);+ try std.testing.expectEqualStrings("answerthought!\ntail", snap);+}++test "legacy bridge citation lifecycle drops unclosed spans and split prefixes" {+ const boundaries = [_]EngineEvent{+ .stream_begin,+ .{ .stream_complete = .{ .streamed_text = true } },+ .stream_finished,+ .{ .stream_aborted = .interrupted },+ .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = false } },+ .{ .transport_aborted = .{ .reason = .interrupted, .turn_ending = true } },+ };+ for (boundaries) |boundary| {+ for ([_][]const u8{ "\u{E200}unclosed", "\xee", "\xee\x88" }) |unfinished| {+ var queue: tui.EventQueue = .{};+ var buf: [128]u8 = undefined;+ var stream: repl.StreamBuf = .{ .buf = &buf };+ var bridge: Bridge = .{ .queue = &queue, .stream = &stream, .show_thinking = true };+ const sink = forBridge(&bridge);+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "why" } });+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = unfinished } });+ sink.emit(undefined, .{ .text_delta = .{ .text = unfinished } });+ sink.emit(undefined, boundary);+ sink.emit(undefined, .{ .text_delta = .{ .text = "next" } });+ sink.emit(undefined, .{ .reasoning_delta = .{ .text = "thought" } });+ const snap = stream.snapshot(std.testing.allocator) orelse return error.NoStream;+ defer std.testing.allocator.free(snap);+ try std.testing.expectEqualStrings("whynextthought", snap);+ }+ }+}