Skip to content

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

Python

stream: prose tightens the stall budget only until its item closes

justrach31598b806d6c
diff --git a/docs/adr/0241-prose-tightens-the-stall-budget-only-until-its-item-closes.md b/docs/adr/0241-prose-tightens-the-stall-budget-only-until-its-item-closes.md
new file mode 100644
index 00000000..98a1d2eb
--- /dev/null
+++ b/docs/adr/0241-prose-tightens-the-stall-budget-only-until-its-item-closes.md
@@ -0,0 +1,36 @@
+# 0241. Prose tightens the stall budget only until its item closes
+
+Status: accepted 2026-10-03
+
+## Context
+
+#56 gave a stream a quarter of the stall budget once visible prose had
+flowed, on the reasoning that bytes arriving and then stopping means a dead
+socket. #401 made the WebSocket reader match the SSE reader. Both kept the
+tightened budget for the rest of the response.
+
+A response is a sequence of output items. A model that writes a one-line
+heads-up and then composes several tool calls closes the message item and can
+think in silence before the next item starts, and a large edit batch takes
+longer than a quarter budget. Eval traces showed exactly that: a heads-up,
+then a stall well inside the full budget, a reconnect, and the whole
+generation paid again. The silence was the model thinking, which is what the
+full budget exists for.
+
+## Decision
+
+On the Responses wire, prose tightens the between-lines budget only while the
+item that holds it is open. An event that closes an output item
+(`response.output_item.done`) restores the full budget; the next prose delta
+tightens it again. The WebSocket reader tracks this in `TokenSignal.step` and
+the SSE reader from its `partial_text` growth plus the same `closesItem`
+check, so the two transports still mean the same thing. Other wires keep the
+old rule: they have no item-close event the reader can rely on.
+
+## Consequences
+
+A stream that dies right after an item closes is caught by the full budget,
+not the quarter, so that one case waits longer before the reconnect. A death
+mid-sentence is still caught at the quarter. The #680 widening ladder is
+unchanged. Revisit if traces show dead sockets lingering between items, or
+another wire gains an item-close event worth reading.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 98265dc7..77b111f8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -265,6 +265,7 @@ record only when you need the evidence or the edge cases.
| [0236](0236-rlm-takes-json-literals-and-each-maps-plain-values.md) | `rlm` takes JSON array/object literals as arguments and binds (`name = [...]`, bound names allowed inside); its splitters nest `[]`/`{}`; `each(arr, tool[, field])` passes plain items as is, picks `field` from objects (default: an MCP tool's first parameter) and names the fields it found; an unsupported statement lists the forms that work. |
| [0237](0237-deepseek-thinks-at-its-low-level-by-default.md) | DeepSeek's default effort (`medium`) sends `reasoning_effort: low` with thinking enabled; `/effort low` still turns thinking off (ADR 0054), and `high` and above are unchanged. |
| [0238](0238-rlm-binds-keep-the-whole-mcp-result.md) | An MCP call inside an rlm script binds the whole result; `print()` shows the slim view (each item of an `each()` bind cut on its own), `project(x, field)` reads any field (`n`/`latest_author` through a comment list's fold), and `write_file` saves the whole result; inside rlm, `read_tool_result("tr_N")` with no range binds a stored result whole. |
+| [0241](0241-prose-tightens-the-stall-budget-only-until-its-item-closes.md) | On the Responses wire, prose tightens the stall budget only while its output item is open; `response.output_item.done` restores the full budget for the next item (WS and SSE alike). |
## When to write one
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index e912c0e5..42c16555 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -232,19 +232,20 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
var loop_guard: @import("agent_model_loop.zig").Stream = .{};
var got_body = false; // #134: true once response bytes have been received (gates the post-completion read-error handling)
var saw_done = false; // #133: true only once the provider's terminal event landed — a close before this is a drop, not a clean end
+ var prose_open = false; // #56/ADR 0241: prose is streaming in an item that has not closed
defer line.deinit();
stream: while (true) {
// Race the line read against an idle-stall watchdog so a dead stream can't
// hang the turn (the Esc escape below is TTY-only, so --json/GUI sessions
- // would otherwise wait forever). #56: a non-empty partial_text (cleared per
- // stream above) means tokens already flowed, so the silence trips sooner.
+ // would otherwise wait forever). #56: prose still streaming means tokens
+ // were flowing, so the silence trips sooner — until its item closes (ADR 0241).
read: {
const ReadDone = union(enum) { line: anyerror!usize, stall: WatchdogFired };
var rd_buf: [2]ReadDone = undefined;
var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
// #680: widened by each stall reconnect this request has already made.
- const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, self.partial_text.items.len != 0, self.stall.widen);
+ const stall_budget = http_stall.interFrameBudgetMs(http.stream_stall_ms, got_body, prose_open, self.stall.widen);
rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer }) catch {
// #56 Fix-B: pool exhausted — no idle-stall watchdog for this read.
// A bare blocking streamDelimiterEnding here is the last forever-hang:
@@ -308,12 +309,14 @@ pub fn postStreamWithClient(self: *Agent, client: *std.http.Client, body: []cons
// End of stream leaves the reader empty; otherwise the '\n' is
// still buffered (and consumed below, after the line is handled).
const more = if (reader.peekByte()) |_| true else |_| false;
+ const prose_len = self.partial_text.items.len; // the loop guard and printDelta both grow it
if (ssePayload(line.writer.buffered())) |payload|
try loop_guard.event(self, payload, true);
try full.writer.writeAll(line.writer.buffered());
try full.writer.writeByte('\n');
got_body = true; // #134: response bytes are in `full`; a later read error is a clean close
self.printDelta(line.writer.buffered());
+ if (self.partial_text.items.len > prose_len) prose_open = true else if (@import("agent_ws_signal.zig").closesItem(gpa, line.writer.buffered())) prose_open = false;
if (main_mod.g_thinking_fold_request) {
main_mod.g_thinking_fold_request = false;
sink.emit(self.io, .thinking_fold_toggle);
diff --git a/src/agent_stream_stall_test.zig b/src/agent_stream_stall_test.zig
index 5f74b7d8..45d6490b 100644
--- a/src/agent_stream_stall_test.zig
+++ b/src/agent_stream_stall_test.zig
@@ -304,3 +304,81 @@ test "Chat terminal marker keeps delayed usage and completes silent trailer; non
try std.testing.expectEqual(@as(u64, 0), child.stall.tripped_ms);
}
}
+
+/// ADR 0241 on SSE: a Responses stream whose prose item closes, then thinks in
+/// silence past the tightened budget before it completes.
+const ResponsesSrv = struct {
+ const delta = "data: {\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}\n\n";
+ const item_done = "data: {\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"type\":\"message\"}}\n\n";
+ const completed = "data: {\"type\":\"response.completed\",\"response\":{\"id\":\"r1\",\"output\":[]}}\n\n";
+ const think_ms = 1000;
+ fn run(io: Io, server: *std.Io.net.Server, done: *std.atomic.Value(bool)) void {
+ const c = while (true) {
+ const conn = server.accept(io) catch return;
+ if (takePostHead(io, conn)) break conn;
+ conn.close(io);
+ };
+ defer c.close(io);
+ var wbuf: [1024]u8 = undefined;
+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);
+ sw.interface.writeAll("HTTP/1.1 200 OK\r\ncontent-type: text/event-stream\r\nconnection: close\r\n\r\n" ++ delta ++ item_done) catch return;
+ sw.interface.flush() catch return;
+ io.sleep(.fromMilliseconds(think_ms), .awake) catch return;
+ sw.interface.writeAll(completed) catch return;
+ sw.interface.flush() catch return;
+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(10), .awake) catch return;
+ }
+};
+
+test "ADR 0241: on the Responses SSE wire a closed prose item gets the full budget back" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+
+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});
+ defer server.deinit(io);
+ var done: std.atomic.Value(bool) = .init(false);
+ var fut = io.async(ResponsesSrv.run, .{ io, &server, &done });
+ defer fut.await(io);
+ defer done.store(true, .release);
+
+ // 2000ms full, 500ms tightened: the think sits between the two.
+ const saved_stream = http.stream_stall_ms;
+ const saved_floor = http_stall.idle_floor_ms;
+ http.stream_stall_ms = 2000;
+ http_stall.idle_floor_ms = 100;
+ defer http.stream_stall_ms = saved_stream;
+ defer http_stall.idle_floor_ms = saved_floor;
+ try std.testing.expect(ResponsesSrv.think_ms > http_stall.budgetMs(http.stream_stall_ms, true));
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var out: Io.Writer.Allocating = .init(gpa); // printDelta grows partial_text only with a frontend
+ defer out.deinit();
+ var client: std.http.Client = .{ .allocator = gpa, .io = io };
+ defer client.deinit();
+
+ var url_buf: [64]u8 = undefined;
+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/v1/responses", .{server.socket.address.getPort()});
+ var agent: Agent = .{
+ .gpa = gpa,
+ .arena = arena,
+ .io = io,
+ .client = &client,
+ .provider = .{ .id = "test", .kind = .responses, .auth = .bearer, .url = url, .api_key = "k", .model = "m", .context = 0 },
+ .messages = std.json.Array.init(arena),
+ .sub = false,
+ .label = "",
+ .out = &out.writer,
+ };
+ defer deinitMarkdown(&agent);
+
+ const t0 = nowMs(io);
+ const body = try agent_stream.postStreamWithClient(&agent, &client, "{}");
+ defer gpa.free(body);
+ try std.testing.expect(nowMs(io) - t0 >= ResponsesSrv.think_ms - 100); // the think really happened
+ try std.testing.expect(std.mem.indexOf(u8, body, "response.completed") != null);
+ try std.testing.expect(agent.partial_text.items.len != 0); // prose did flow, so the budget had tightened
+}
diff --git a/src/agent_ws.zig b/src/agent_ws.zig
index 39b27bc8..d7972c85 100644
--- a/src/agent_ws.zig
+++ b/src/agent_ws.zig
@@ -470,7 +470,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
var fbuf: std.ArrayList(u8) = .empty;
defer fbuf.deinit(gpa);
var frames_seen: usize = 0;
- // Prose (not protocol frames) tightens the inter-frame stall budget.
+ // Prose tightens the inter-frame stall budget until its item closes (ADR 0241).
var loop_guard: @import("agent_model_loop.zig").Stream = .{};
var sig: TokenSignal = .{};
var text_seen = false;
@@ -491,13 +491,13 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
// nothing came back". A FRESH connect skips this: its handshake just
// proved liveness, so it keeps the full pre-first-token budget.
// * otherwise → the inter-frame budget: full stream_stall_ms after
- // protocol frames (encrypted thinking), a quarter once prose flowed.
+ // protocol frames (encrypted thinking), a quarter while prose streams.
// http_stall.budgetMs is what streamStallWatch asks the SSE reader's
// budget of on every tick; it cannot change mid-wait, so deciding it
// here is equivalent and lets both regimes share one watchdog arm.
read: {
const head_wait = reused and frames_seen == 0;
- const budget = if (head_wait) http.head_stall_ms else http_stall.interFrameBudgetMs(http.stream_stall_ms, frames_seen > 0, text_seen, self.stall.widen);
+ const budget = if (head_wait) http.head_stall_ms else http_stall.interFrameBudgetMs(http.stream_stall_ms, frames_seen > 0, text_seen and sig.open, self.stall.widen);
const ReadDone = union(enum) { msg: ws.Error!ws.Opcode, stall: WatchdogFired };
var rd_buf: [2]ReadDone = undefined;
var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
@@ -558,9 +558,9 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {
// …and THIS is the budget signal: visible prose, from EITHER event that
// grows partial_text on SSE — an output-text delta, or the streamed
// arguments of a whitelisted meta call (attempt_completion / ask_user),
- // which is all a final-answer turn emits. Fed every frame until it
- // fires (output_item.added/done open and close the tracked call).
- if (!text_seen and sig.flowing(gpa, fbuf.items)) {
+ // which is all a final-answer turn emits. Fed every frame: an item that
+ // closes restores the full budget for the next one (ADR 0241).
+ if (sig.step(gpa, fbuf.items) and !text_seen) {
text_seen = true;
self.traceFirstToken();
if (self.tracer) |tr| tr.note("ws", "first output text — tightening stall budget");
diff --git a/src/agent_ws_mock.zig b/src/agent_ws_mock.zig
index 183229f4..1cbbcfc3 100644
--- a/src/agent_ws_mock.zig
+++ b/src/agent_ws_mock.zig
@@ -49,6 +49,11 @@ pub const arg_prose_events = [_][]const u8{
/// head budget, inside the pre-first-token budget.
pub var slow_first_frame_ms: i64 = 700;
+/// ADR 0241: the item holding the prose closes, then `prose_close_then_think`
+/// thinks this long: past the tests' tightened 500ms, inside their full 2000ms.
+pub const item_done_event = "{\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"type\":\"message\"}}";
+pub const think_after_prose_ms = 1000;
+
/// A loopback WebSocket peer with a scripted failure mode.
pub const Mock = struct {
pub const Mode = enum {
@@ -82,6 +87,9 @@ pub const Mock = struct {
/// Send a generic terminal API error and close immediately, matching
/// Codex's failure sequence from issue #692.
generic_error_then_close,
+ /// ADR 0241: a heads-up delta, its item closes, a silent think past the
+ /// tightened budget (a tool call being composed), then completion.
+ prose_close_then_think,
};
pub fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {
@@ -125,6 +133,13 @@ pub const Mock = struct {
for (arg_prose_events) |ev|
writeTextFrame(&sw.interface, ev) catch return idle(io, done);
},
+ .prose_close_then_think => {
+ readRealFrame(io, &sr.interface, &sw.interface) catch return idle(io, done);
+ writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);
+ writeTextFrame(&sw.interface, item_done_event) catch return idle(io, done);
+ io.sleep(.fromMilliseconds(think_after_prose_ms), .awake) catch return idle(io, done);
+ writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);
+ },
.generic_error_then_close => {
readRealFrame(io, &sr.interface, &sw.interface) catch return;
writeTextFrame(&sw.interface, generic_error_event) catch return;
diff --git a/src/agent_ws_signal.zig b/src/agent_ws_signal.zig
index bc4f4313..97a29eb8 100644
--- a/src/agent_ws_signal.zig
+++ b/src/agent_ws_signal.zig
@@ -6,7 +6,7 @@
//! stall (the round-2 regression), too tight and a mid-answer server death
//! waits four times as long as it does on SSE (the round-4 finding).
//!
-//! SSE passes `self.partial_text.items.len != 0`, and on the `.responses` path
+//! SSE reads partial_text growth (until an item closes, ADR 0241), and on the `.responses` path
//! partial_text has TWO producers, both reached from agent_stream.streamSseLine:
//!
//! 1. the `response.output_text.delta` arm, whose `if (text.len == 0) return;`
@@ -60,6 +60,27 @@ pub fn frameHasOutputText(gpa: std.mem.Allocator, frame: []const u8) bool {
return d == .string and d.string.len != 0;
}
+/// ADR 0241: true for a Responses event that closes an output item, read off a
+/// WS frame or an SSE `data:`/`event:` line. Prose tightens the between-lines
+/// budget only until its item closes: the next item (a tool call composed
+/// after a heads-up, say) can follow a silent think, and a quarter budget
+/// there killed healthy turns as stalls and re-paid the whole generation.
+/// Same shape as frameHasOutputText: a substring candidate, then a parse, so
+/// prose that merely quotes the event name does not count.
+pub fn closesItem(gpa: std.mem.Allocator, frame: []const u8) bool {
+ const ev = "response.output_item.done";
+ if (std.mem.indexOf(u8, frame, ev) == null) return false;
+ var payload = std.mem.trim(u8, frame, " \t\r\n");
+ if (std.mem.startsWith(u8, payload, "event:")) return std.mem.eql(u8, std.mem.trim(u8, payload["event:".len..], " \t"), ev);
+ if (std.mem.startsWith(u8, payload, "data:")) payload = std.mem.trim(u8, payload["data:".len..], " \t");
+ var scratch = std.heap.ArenaAllocator.init(gpa);
+ defer scratch.deinit();
+ const v = std.json.parseFromSliceLeaky(std.json.Value, scratch.allocator(), payload, .{ .allocate = .alloc_always }) catch return false;
+ if (v != .object) return false;
+ const ty = v.object.get("type") orelse return false;
+ return ty == .string and std.mem.eql(u8, ty.string, ev);
+}
+
/// The turn's tokens-flowing signal: both producers, and the little bit of
/// state producer 2 needs (which output item is the open whitelisted call).
///
@@ -74,14 +95,27 @@ pub const TokenSignal = struct {
/// function call; -1 for none. The mirror of ArgLive.index, opened and
/// closed by the same events argLiveDelta uses.
arg_ix: i64 = -1,
+ /// ADR 0241: prose is streaming in an item that has not closed yet. The WS
+ /// read budget is tightened only while this holds.
+ open: bool = false,
- /// True the first time a frame proves visible prose is flowing. Called only
- /// until it returns true — the budget never un-tightens.
+ /// True when a frame proves visible prose is flowing.
pub fn flowing(self: *TokenSignal, gpa: std.mem.Allocator, frame: []const u8) bool {
if (frameHasOutputText(gpa, frame)) return true;
return self.argProse(gpa, frame);
}
+ /// Fed every frame. True when this frame is prose, which opens the gate;
+ /// a frame that closes an output item shuts it again (ADR 0241).
+ pub fn step(self: *TokenSignal, gpa: std.mem.Allocator, frame: []const u8) bool {
+ if (self.flowing(gpa, frame)) {
+ self.open = true;
+ return true;
+ }
+ if (closesItem(gpa, frame)) self.open = false;
+ return false;
+ }
+
/// Producer 2. Tracks response.output_item.added/done to know WHICH item is
/// a whitelisted call, then fires on that item's first non-empty argument
/// delta. An ordinary tool's argument stream (edit_file, bash) prints
@@ -193,3 +227,29 @@ test "shouldLatchSse: 426 and connect stall latch now; 500 handshake still retri
try std.testing.expect(!shouldLatchSse(false, error.HandshakeFailed, 1));
try std.testing.expect(shouldLatchSse(false, error.HandshakeFailed, 2));
}
+
+test "ADR 0241: prose tightens until its item closes; an ordinary tool's arguments do not reopen it" {
+ const gpa = std.testing.allocator;
+ var sig: TokenSignal = .{};
+ try std.testing.expect(!sig.step(gpa, "{\"type\":\"response.created\"}"));
+ try std.testing.expect(!sig.open);
+ try std.testing.expect(sig.step(gpa, "{\"type\":\"response.output_text.delta\",\"delta\":\"Checking the logs.\"}"));
+ try std.testing.expect(sig.open);
+ try std.testing.expect(!sig.step(gpa, "{\"type\":\"response.output_item.done\",\"output_index\":0,\"item\":{\"type\":\"message\"}}"));
+ try std.testing.expect(!sig.open);
+ try std.testing.expect(!sig.step(gpa, "{\"type\":\"response.output_item.added\",\"output_index\":1,\"item\":{\"type\":\"function_call\",\"name\":\"edit_file\"}}"));
+ try std.testing.expect(!sig.step(gpa, "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":1,\"delta\":\"{\\\"path\\\":\"}"));
+ try std.testing.expect(!sig.open);
+ try std.testing.expect(sig.step(gpa, "{\"type\":\"response.output_text.delta\",\"delta\":\"Done.\"}"));
+ try std.testing.expect(sig.open);
+}
+
+test "ADR 0241: closesItem reads WS frames and SSE lines, not prose that quotes the event name" {
+ const gpa = std.testing.allocator;
+ try std.testing.expect(closesItem(gpa, "{\"type\":\"response.output_item.done\",\"output_index\":0}"));
+ try std.testing.expect(closesItem(gpa, "data: {\"type\":\"response.output_item.done\",\"output_index\":0}"));
+ try std.testing.expect(closesItem(gpa, "event: response.output_item.done"));
+ try std.testing.expect(!closesItem(gpa, "{\"type\":\"response.output_text.delta\",\"delta\":\"response.output_item.done\"}"));
+ try std.testing.expect(!closesItem(gpa, "event: response.output_text.delta"));
+ try std.testing.expect(!closesItem(gpa, "event: content_block_stop"));
+}
diff --git a/src/agent_ws_stall_test.zig b/src/agent_ws_stall_test.zig
index ece186cc..e23f94cc 100644
--- a/src/agent_ws_stall_test.zig
+++ b/src/agent_ws_stall_test.zig
@@ -116,6 +116,61 @@ test "#401: silence after frames trips the tightened read budget, not the full p
try std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto);
}
+// ADR 0241: the tightened budget belongs to prose that is still streaming. A
+// heads-up whose item has closed is followed by a silent think while the model
+// composes its tool calls; tripping a quarter budget there killed healthy
+// turns and re-paid the whole generation. Same tightened budgets as #401, a
+// server that thinks past them after the item closes: the turn must finish.
+test "ADR 0241: a closed prose item gets the full budget back for a silent think" {
+ if (builtin.os.tag == .windows) return error.SkipZigTest;
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+
+ var addr = try std.Io.net.IpAddress.parseLiteral("127.0.0.1:0");
+ var server = try std.Io.net.IpAddress.listen(&addr, io, .{});
+ defer server.deinit(io);
+ var done: std.atomic.Value(bool) = .init(false);
+ var fut = io.async(Mock.run, .{ io, &server, Mock.Mode.prose_close_then_think, &done });
+ defer fut.await(io);
+ defer done.store(true, .release);
+
+ const saved_stream = http.stream_stall_ms;
+ const saved_floor = http_stall.idle_floor_ms;
+ http.stream_stall_ms = 2000;
+ http_stall.idle_floor_ms = 100;
+ defer http.stream_stall_ms = saved_stream;
+ defer http_stall.idle_floor_ms = saved_floor;
+ try std.testing.expect(mock.think_after_prose_ms > http_stall.budgetMs(http.stream_stall_ms, true));
+
+ var arena_state = std.heap.ArenaAllocator.init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var tw: Io.Writer.Allocating = .init(gpa);
+ defer tw.deinit();
+ var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &tw.writer, .start = Io.Timestamp.now(io, .awake) };
+
+ var url_buf: [64]u8 = undefined;
+ const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/x", .{server.socket.address.getPort()});
+ var agent = mockAgent(gpa, arena, io, url);
+ agent.tracer = &tracer;
+ defer if (agent.codex_ws) |c| {
+ c.dead = true;
+ c.deinit(gpa);
+ agent.codex_ws = null;
+ };
+
+ const body = "{\"model\":\"gpt-5\",\"input\":[]}";
+ const t0 = nowMs(io);
+ const out = try agent_ws.postResponsesWs(&agent, body);
+ defer gpa.free(out);
+ try std.testing.expect(nowMs(io) - t0 >= mock.think_after_prose_ms - 100); // the think really happened
+ try std.testing.expect(std.mem.indexOf(u8, out, mock.item_done_event) != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, completed_event) != null);
+ try std.testing.expect(traced(&tw, "\"detail\":\"completed\""));
+ try std.testing.expect(!traced(&tw, "\"detail\":\"stall\""));
+}
+
// The control: same harness, same tightened budgets, a server that finishes.
// Proves the stall is the SERVER's silence, not the mock — and pins the notes.
test "#401 control: a mock that completes the response still finishes the turn cleanly" {