graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix(codex): bound a dead reused WS, and count arg prose as tokens (#401)
Rach Pradhan803a80cf09c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 64a6dafd..4a4d7f5d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,25 +16,37 @@ current is part of cutting a release.quiet mid-response. The WS reader armed its stall watchdog with a hardcoded"no tokens yet", so it re-armed the full 120s pre-first-token budget on everyframe and never tightened once the model was actually emitting — the SSE- reader has always tightened to a quarter. Silence after visible output text- now trips in ~30s, while a silent reasoning phase keeps the full budget,- exactly as on SSE: the signal is the same `response.output_text.delta` the SSE- reader keys on, not mere frame arrival, because the protocol events land- milliseconds after the send and would otherwise stall out a long thinking- turn. The trace gains `sent <n>b`, `first frame` and `first output text`- notes, so a hang says which half of the turn went quiet instead of stopping- dead at `reuse (delta)` (#401).+ reader has always tightened to a quarter. Silence after visible prose now+ trips in ~30s, while a silent reasoning phase keeps the full budget, exactly+ as on SSE. "Visible prose" means both things that print on SSE: a+ `response.output_text.delta`, and the streamed arguments of `attempt_completion`+ / `ask_user` — which is all a final-answer turn emits, so keying on output+ text alone would have left the commonest turn shape on the old budget. Mere+ frame arrival is still not the signal: the protocol events land milliseconds+ after the send and would stall out a long thinking turn. The trace gains+ `sent <n>b`, `first frame` and `first output text` notes, so a hang says which+ half of the turn went quiet instead of stopping dead at `reuse (delta)` (#401).+- A REUSED codex WS that answers nothing is now caught in ~30s instead of ~120s,+ and as a transport failure rather than a stalled turn. Nothing proves a held+ socket is still alive, and the backend acks a send within milliseconds, so+ zero frames back is a dead socket: it gets the head budget and re-anchors on a+ fresh connection (SSE only after a second failure), instead of spending a slot+ of the turn's stall budget waiting out the full pre-first-token window. A+ freshly dialed socket is unaffected — its handshake just proved the peer is+ there, so it keeps the full budget for a model that thinks before it speaks.- The WS send and dial are under a deadline too (an unbounded blocking write /an unbounded dial through DNS + TLS + the 101 status line), with Esc liveduring both. They report the transport-flake error the SSE guard uses, so awedged socket is retried on a fresh one rather than spending the turn's stallbudget; the send deadline scales with the frame so a full-conversation- re-anchor is not a false positive. When the Io pool is exhausted both fail- retryable instead of degrading to an unwatched blocking call, and both name- themselves in the trace (`send stall` / `connect stall`), so a stalled dial is- no longer reported as a bare error name. A socket the idle window condemns is- torn down with a plain FIN rather than a courtesy close frame that could block- again, and a failed WS handshake no longer leaks its fd and CA bundle.+ re-anchor is not a false positive. Both name themselves in the trace+ (`send stall` / `connect stall`), so a stalled dial is no longer reported as a+ bare error name. Under Io-pool exhaustion they follow the SSE guard exactly: a+ failed payload spawn fails retryable, a failed watchdog spawn degrades to the+ unwatched call already in flight, so a momentary pool shortage cannot latch a+ session onto SSE. A socket the idle window condemns is torn down with a plain+ FIN rather than a courtesy close frame that could block again, and a failed WS+ handshake no longer leaks its fd and CA bundle.## v0.0.237 (2026-08-04)diff --git a/src/agent_ws.zig b/src/agent_ws.zigindex 864a46e3..4bcd76c9 100644--- a/src/agent_ws.zig+++ b/src/agent_ws.zig@@ -31,11 +31,17 @@ const term = @import("term.zig");const tty = term.tty;const http = @import("http.zig");+const http_stall = @import("http_stall.zig");const WatchdogFired = http.WatchdogFired;-const streamStallWatch = http.streamStallWatch;const deadlineStallTask = http.deadlineStallTask;const watchdogError = http.watchdogError;+/// (#401) The tokens-flowing classifier: its own module (this file is at the+/// 600-line cap), aliased back so call sites and tests keep naming agent_ws.+const signal = @import("agent_ws_signal.zig");+pub const frameHasOutputText = signal.frameHasOutputText;+pub const TokenSignal = signal.TokenSignal;+const isStreamEnd = @import("agent_stream.zig").isStreamEnd;const escPressed = Agent.escPressed;@@ -212,17 +218,24 @@ pub fn sendFrameWatched(io: Io, client: *ws.WsClient, frame: []const u8, poll_stconst SendDone = union(enum) { sent: ws.Error!void, stall: WatchdogFired };var sd_buf: [2]SendDone = undefined;var ssel: Io.Select(SendDone) = .init(io, &sd_buf);- // #56 Fix-B: pool exhausted — never degrade to a bare blocking sendText,- // which IS the hang this guard exists for; fail retryable (HungRequest) the- // way the SSE head guard does. The WATCHDOG is spawned FIRST so that stays- // possible on the SECOND spawn too: once an unbounded blocking write is in- // flight, the only way out of this function is to join it — #401's hang- // through a different door. Watchdog-first leaves every failure with- // nothing running, or only a cancellable sleeper to unwind.- ssel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget }) catch return error.HungRequest;- ssel.concurrent(.sent, wsSendTask, .{ client, frame }) catch {- ssel.cancelDiscard(); // only the sleeper is running; it unwinds at once- return error.HungRequest;+ // #56 Fix-B, mirroring the SSE head guard's ASYMMETRY exactly+ // (agent_stream.zig:263-283) rather than hard-failing both arms:+ // * PAYLOAD spawn failed → fail retryable (HungRequest). Nothing is in+ // flight, and a bare blocking sendText IS the hang this guard exists+ // for, so there is nothing to degrade to.+ // * WATCHDOG spawn failed → DEGRADE: the write is already in flight and+ // the only exit is to join it. Failing here instead would turn a+ // momentary Io-pool shortage (a deep subagent fan-out) into two+ // transport failures and a session-wide SSE latch — where SSE, in the+ // same situation, simply proceeds.+ ssel.concurrent(.sent, wsSendTask, .{ client, frame }) catch return error.HungRequest;+ ssel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, budget }) catch {+ const r = ssel.await() catch |e| { // the send is the only arm running+ ssel.cancelDiscard();+ return e;+ };+ ssel.cancelDiscard();+ return r.sent;};const first = ssel.await() catch |e| {ssel.cancelDiscard();@@ -262,13 +275,18 @@ pub fn connectWatched(gpa: std.mem.Allocator, io: Io, url: []const u8, headers:const Dialed = union(enum) { dialed: ws.Error!*ws.WsClient, stall: WatchdogFired };var dl_buf: [2]Dialed = undefined;var dsel: Io.Select(Dialed) = .init(io, &dl_buf);- // Watchdog first, then the dial — same #56 Fix-B reasoning as- // sendFrameWatched: neither spawn failure may leave an unwatched blocking- // call, and an in-flight dial can only be unwound by joining it.- dsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, http.head_stall_ms }) catch return error.HungRequest;- dsel.concurrent(.dialed, wsConnectTask, .{ gpa, io, url, headers }) catch {+ // Same #56 Fix-B asymmetry as sendFrameWatched (and the SSE head guard it+ // copies): a failed DIAL spawn is retryable HungRequest with nothing in+ // flight; a failed WATCHDOG spawn degrades to the unwatched dial, because+ // that dial is already running and a pool shortage must not cost a turn.+ dsel.concurrent(.dialed, wsConnectTask, .{ gpa, io, url, headers }) catch return error.HungRequest;+ dsel.concurrent(.stall, deadlineStallTask, .{ io, poll_stdin, http.head_stall_ms }) catch {+ const r = dsel.await() catch |e| { // the dial is the only arm running+ drainDialSelect(gpa, &dsel);+ return e;+ };drainDialSelect(gpa, &dsel);- return error.HungRequest;+ return r.dialed;};const first = dsel.await() catch |e| {drainDialSelect(gpa, &dsel);@@ -308,48 +326,25 @@ pub fn connectWatched(gpa: std.mem.Allocator, io: Io, url: []const u8, headers:// full-history re-anchor. A false positive here is expensive.// * A blocking peek is #401's hang, moved earlier in the turn.//-// So the held socket is written into on faith and DETECTION is the pair of-// deadlines this file adds: sendFrameWatched bounds the write into a wedged-// socket, and the read watchdog bounds the silence after it. A dead reused-// socket costs one bounded round trip plus a re-anchor instead of an unbounded-// hang — what `is_closed()` buys, one turn later.--/// (#401) Does this ws frame carry VISIBLE OUTPUT TEXT — the WS side of the-/// SSE reader's tokens-flowing signal?-///-/// It must mean EXACTLY what the SSE signal means, because both feed the same-/// http_stall.budgetMs. SSE passes `self.partial_text.items.len != 0`, and-/// partial_text grows in exactly one place for `.responses` (agent_stream.zig,-/// streamSseLine): a `response.output_text.delta` whose `delta` is a non-empty-/// string. Reasoning deltas are handled ABOVE that arm's `if (text.len == 0)-/// return;` and never reach the append, so a silent reasoning phase keeps the-/// FULL pre-first-token budget on SSE — deliberately, since it legitimately-/// runs minutes. `response.output_item.done` carries the finished text and also-/// never touches partial_text. Both are excluded here for the same reason.-///-/// Frame ARRIVAL is not that signal: response.created / response.in_progress /-/// response.output_item.added land within milliseconds of the send, long before-/// the model has thought (and ping/pong never surfaces from readMessage at-/// all). Keying the budget on "a frame landed" tightens every WS turn to a-/// quarter budget from ~100ms in, so a high-effort turn reasoning silently past-/// that is killed as a stall, re-sent as a full re-anchor, stalled again, and-/// latched off WS for the session — while the identical turn survives on SSE.-///-/// Shape mirrors isStreamEnd: a cheap substring candidate, then an-/// authoritative parse, so a reasoning delta that merely QUOTES the event name-/// is not mistaken for one. Called only until it first returns true.-pub fn frameHasOutputText(gpa: std.mem.Allocator, frame: []const u8) bool {- const ev = "response.output_text.delta";- if (std.mem.indexOf(u8, frame, ev) == null) return false;- var scratch = std.heap.ArenaAllocator.init(gpa);- defer scratch.deinit();- const v = std.json.parseFromSliceLeaky(std.json.Value, scratch.allocator(), frame, .{ .allocate = .alloc_always }) catch return false;- if (v != .object) return false;- const ty = v.object.get("type") orelse return false;- if (ty != .string or !std.mem.eql(u8, ty.string, ev)) return false;- const d = v.object.get("delta") orelse return false;- return d == .string and d.string.len != 0;-}+// So the held socket is written into on faith and DETECTION is the three+// deadlines this file adds. Stated as the bound it actually is, since an+// earlier round of this note claimed more than it bought:+//+// * sendFrameWatched bounds the WRITE into a wedged socket (sendDeadlineMs).+// * On a REUSED socket the read loop's FIRST frame is bounded by+// head_stall_ms (30s), not the 120s pre-first-token budget, and surfaces as+// error.HungRequest — the transport ladder (one fresh re-dial with full+// history, SSE on the second), never a spend against request()'s 2-slot+// stall budget. The WS analog of the SSE head guard, safe for the same+// reason frame arrival is a BAD tokens-flowing signal: created/in_progress+// land within milliseconds of a send, so ZERO frames from a socket we have+// no handshake for is a dead socket, not a thinking model.+// * After that first frame the inter-frame budget takes over (full while the+// model reasons in silence, a quarter once prose has flowed).+//+// So a dead reused socket costs up to 30s of dead air plus a re-anchor, where+// `is_closed()` costs a syscall. Bounded and off the stall budget, not free:+// reference parity on the pre-reuse check itself stays NOT MET./// One Responses turn over ws. Returns the reassembled body as SSE-format/// `data:` lines (parseResponses consumes it unchanged). Connect/transport@@ -419,6 +414,12 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {// Hold ONE WS across the turn's tool loop (codex-style): the first request// dials; subsequent requests reuse it and send previous_response_id + delta.// The open connection IS the sticky context (no x-codex-turn-state to echo).+ //+ // (#401) …and which of the two it is decides the FIRST-frame budget below: a+ // socket dialed just now finished a TLS + upgrade handshake milliseconds+ // ago, so the peer is known live and a long silence is the model thinking. A+ // socket held since the last request has proved nothing since.+ const reused = self.codex_ws != null;if (self.codex_ws == null) {self.codex_ws = connectWatched(gpa, self.io, url, &headers, orig_tio != null) catch |e| {// HungRequest, matching connectWatched's deadline error — NOT@@ -470,29 +471,45 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {errdefer full.deinit();var fbuf: std.ArrayList(u8) = .empty;defer fbuf.deinit(gpa);- // (#401) Frames received for THIS response — the OBSERVABILITY counter,- // used only for the "first frame" trace note that splits a hung turn into- // its two halves.+ // (#401) Frames received for THIS response: the "first frame" trace note+ // that splits a hung turn into its two halves, and the head-budget gate+ // below. It is NOT the tokens-flowing signal — see TokenSignal.var frames_seen: usize = 0;- // (#401) …and, separately, whether VISIBLE OUTPUT TEXT has arrived — THIS is- // what the read watchdog's budget keys on. Before the first token the model- // may legitimately reason in silence for minutes (the full stream_stall_ms);- // once text has flowed and stopped, that is a dead socket and- // http_stall.budgetMs tightens to a quarter (#56). The WS reader used to- // hardcode "no tokens yet", so it re-armed the FULL 120s budget on every- // frame and never tightened — why #401's mid-stream silence sat for 120s per- // attempt, ~4 minutes before the SSE latch, against successful turns of- // 3.6-11.6s. frameHasOutputText mirrors the SSE reader's signal exactly.+ // (#401) …and, separately, whether VISIBLE PROSE has arrived — THIS is what+ // the read watchdog's budget keys on. Before the first token the model may+ // reason in silence for minutes (the full stream_stall_ms); once prose has+ // flowed and stopped, that is a dead socket and http_stall.budgetMs tightens+ // to a quarter (#56). The WS reader used to hardcode "no tokens yet", re-arming+ // the FULL 120s budget on every frame — why #401's mid-stream silence sat for+ // 120s per attempt, ~4 minutes before the SSE latch, against successful turns+ // of 3.6-11.6s. TokenSignal mirrors BOTH of the SSE reader's producers.+ var sig: TokenSignal = .{};var text_seen = false;stream: while (true) {- // Race the frame read against the shared idle-stall watchdog so a dead- // ws can't hang the turn — a deadline surfaces as error.StreamStalled- // (never a user Esc), handled identically to the SSE path (#134). The- // budget is re-decided every iteration from text_seen, so silence AFTER- // OUTPUT TEXT tightens to a quarter the way SSE's always has, and a- // silent reasoning phase keeps the full budget the way SSE's does (#401).+ // Race the frame read against a stall watchdog so a dead ws can't hang+ // the turn (#134), on a budget re-decided every iteration:+ //+ // * REUSED socket, no frame yet → the head budget, as HungRequest.+ // Nothing has proved this peer alive since the last turn, and the+ // backend answers a send with response.created / in_progress within+ // milliseconds, so zero frames is a dead socket, not a thinking+ // model. HungRequest keeps it on postLive's transport ladder (one+ // fresh re-dial, then SSE) instead of spending a slot of request()'s+ // 2-slot stall budget — the SSE head guard's contract for "sent,+ // 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 while only protocol /+ // reasoning frames have landed, a quarter once prose has flowed.+ // 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.budgetMs(http.stream_stall_ms, text_seen);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);@@ -508,7 +525,7 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {if (self.tracer) |tr| tr.note("ws", "stall");return error.StreamStalled;};- rsel.concurrent(.stall, streamStallWatch, .{ self.io, orig_tio != null, text_seen }) catch {+ rsel.concurrent(.stall, deadlineStallTask, .{ self.io, orig_tio != null, budget }) catch {const r = rsel.await() catch |e| {rsel.cancelDiscard();return e;@@ -524,7 +541,14 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {rsel.cancelDiscard();switch (first) {.msg => |m| _ = m catch |e| return e,- .stall => |w| {+ .stall => |w| if (head_wait) {+ // A reused socket that answered NOTHING is a transport+ // failure, not the end of the turn: no user-facing "ending+ // turn" line (postLive retries a fresh socket, as for a send+ // stall), and HungRequest so the ladder pays, not the budget.+ if (self.tracer) |tr| tr.note("ws", if (w == .esc) "esc" else "reuse dead — no first frame");+ return watchdogError(w, error.HungRequest);+ } else {if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};o.flush() catch {};@@ -534,16 +558,19 @@ pub fn postResponsesWs(self: *Agent, body: []const u8) ![]u8 {},}}- // A frame landed. This only feeds the trace note — it is NOT the budget- // signal (the first frames of a turn are protocol events that arrive- // before the model has thought). Counted before the empty-frame skip- // below: an empty frame is still evidence the peer is alive.+ // A frame landed: the peer is alive, which retires the head budget — but+ // it is NOT the tokens-flowing signal (the first frames of a turn are+ // protocol events that arrive before the model has thought). Counted+ // before the empty-frame skip: an empty frame is still evidence too.frames_seen += 1;if (frames_seen == 1) if (self.tracer) |tr| tr.note("ws", "first frame");if (fbuf.items.len == 0) continue :stream;- // …and THIS is the budget signal: visible output text, the same event- // that grows partial_text on SSE. Checked only until it first fires.- if (!text_seen and frameHasOutputText(gpa, fbuf.items)) {+ // …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)) {text_seen = true;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.zignew file mode 100644index 00000000..04f50366--- /dev/null+++ b/src/agent_ws_mock.zig@@ -0,0 +1,208 @@+//! (#401) The loopback WebSocket peer the codex-WS transport tests drive, and+//! the root-shaped Agent pointed at it. Harness only — no tests live here; they+//! live in agent_ws_stall_test.zig (the budgets and the guards) and+//! agent_ws_reuse_test.zig (reuse vs fresh connect). Split out because both+//! files would otherwise carry a copy, and a second copy of a mock server is+//! exactly how two suites start testing different things.+//!+//! Same spirit as the GRAFF_CODEX_URL/lmstudio HTTP mocks: `provider.url` points+//! at 127.0.0.1, and no network, key or provider is used.++const std = @import("std");+const Io = std.Io;++const Agent = @import("agent.zig").Agent;++pub fn nowMs(io: Io) i64 {+ return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));+}++pub const delta_event = "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}";+pub const completed_event = "{\"type\":\"response.completed\"}";++/// What the backend actually puts on the socket in the first milliseconds after+/// a send, before the model has produced anything: the two protocol events, then+/// a reasoning delta. None of these grows partial_text on the SSE path, so none+/// may tighten the WS read budget either.+pub const protocol_events = [_][]const u8{+ "{\"type\":\"response.created\",\"response\":{\"id\":\"r1\"}}",+ "{\"type\":\"response.in_progress\",\"response\":{\"id\":\"r1\"}}",+ "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"thinking\"}",+};++/// A codex turn whose whole visible answer is attempt_completion's `result`+/// prose: the model opens the meta call and streams its ARGUMENTS. Not one+/// output_text delta in the turn — on SSE this prints (argLiveDelta →+/// emitArgText → partial_text), so it is tokens-flowing there and must be here.+pub const arg_prose_events = [_][]const u8{+ "{\"type\":\"response.created\",\"response\":{\"id\":\"r1\"}}",+ "{\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"attempt_completion\",\"id\":\"fc1\"}}",+ "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"delta\":\"{\\\"result\\\":\\\"the ans\"}",+ "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"delta\":\"wer is 42\"}",+};++/// How long `slow_first_frame` thinks before its first frame: past a shrunken+/// head budget, inside the pre-first-token budget.+pub var slow_first_frame_ms: i64 = 700;++/// A loopback WebSocket peer with a scripted failure mode.+pub const Mock = struct {+ pub const Mode = enum {+ /// Accept the TCP connection and never answer the upgrade — the dial+ /// that hangs before the 101 status line.+ no_upgrade,+ /// Upgrade, then never read again: the client's frame fills the socket+ /// buffers and its write parks in the kernel.+ never_drain,+ /// Upgrade, take the client's frame, answer with ONE delta frame and+ /// then go permanently silent. This is #401's reported signature: the+ /// turn is under way, data flowed, and the server stopped.+ frame_then_silence,+ /// The healthy control: delta, then response.completed.+ frame_then_complete,+ /// Upgrade, take the client's frame, answer with `protocol_events` and+ /// then go quiet while the model "thinks". Frames flow, none of them is+ /// output text — so the budget must stay at the pre-first-token value.+ protocol_then_silence,+ /// Upgrade, take the client's frame, answer NOTHING — ever. On a REUSED+ /// socket that is the dead-socket signature: the backend acks a send+ /// with response.created within milliseconds, so zero frames means the+ /// peer is gone, not thinking.+ read_then_silence,+ /// Upgrade, take the client's frame, think past the head budget, then+ /// answer normally. A FRESH connect must survive this.+ slow_first_frame,+ /// Upgrade, take the client's frame, stream a whitelisted meta call's+ /// arguments (`arg_prose_events`) and then go silent.+ arg_prose_then_silence,+ };++ pub fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {+ const c = server.accept(io) catch return;+ defer c.close(io);+ var rbuf: [8192]u8 = undefined;+ var wbuf: [4096]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);+ if (mode == .no_upgrade) return idle(io, done);++ while (true) {+ const line = sr.interface.takeDelimiterInclusive('\n') catch return idle(io, done);+ if (line.len <= 2) break; // the blank line ends the upgrade request+ }+ sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch return idle(io, done);+ sw.interface.flush() catch return idle(io, done);++ switch (mode) {+ .no_upgrade, .never_drain => {},+ .frame_then_silence, .frame_then_complete => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);+ if (mode == .frame_then_complete)+ writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);+ },+ .protocol_then_silence => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ for (protocol_events) |ev|+ writeTextFrame(&sw.interface, ev) catch return idle(io, done);+ },+ .read_then_silence => readClientFrame(&sr.interface) catch return idle(io, done),+ .slow_first_frame => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ io.sleep(.fromMilliseconds(slow_first_frame_ms), .awake) catch return idle(io, done);+ writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);+ writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);+ },+ .arg_prose_then_silence => {+ readClientFrame(&sr.interface) catch return idle(io, done);+ for (arg_prose_events) |ev|+ writeTextFrame(&sw.interface, ev) catch return idle(io, done);+ },+ }+ idle(io, done);+ }++ /// Hold the connection open (and, for never_drain, undrained) until the test+ /// releases it. Closing early hands the client a clean EOF, a different+ /// failure than the silence being reproduced.+ pub fn idle(io: Io, done: *std.atomic.Value(bool)) void {+ while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch break;+ }++ /// Consume one masked client frame (RFC 6455 §5.2); the payload is ignored.+ pub fn readClientFrame(r: *Io.Reader) !void {+ const h = try r.takeArray(2);+ var len: u64 = h[1] & 0x7f;+ if (len == 126) {+ len = std.mem.readInt(u16, try r.takeArray(2), .big);+ } else if (len == 127) {+ len = std.mem.readInt(u64, try r.takeArray(8), .big);+ }+ if ((h[1] & 0x80) != 0) _ = try r.takeArray(4); // mask key+ try r.discardAll(@intCast(len));+ }++ /// One unmasked server->client text frame (payloads here are all < 126 B).+ pub fn writeTextFrame(w: *Io.Writer, payload: []const u8) !void {+ try w.writeAll(&[_]u8{ 0x81, @intCast(payload.len) });+ try w.writeAll(payload);+ try w.flush();+ }+};++/// A root-shaped Agent pointed at the mock. `out`/`in` stay null: no TTY means no+/// spinner, no Esc poll and no user-facing stall line — the transport alone.+pub fn mockAgent(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: Io, url: []const u8) Agent {+ return .{+ .gpa = gpa,+ .arena = arena,+ .io = io,+ .client = undefined, // the WS path never touches the HTTP client+ .provider = .{+ .id = "codex",+ .kind = .responses,+ .auth = .bearer,+ .url = url,+ .api_key = "k",+ .model = "gpt-5",+ .context = 100_000,+ },+ .messages = std.json.Array.init(arena),+ .sub = false,+ .label = "",+ .out = null,+ };+}++pub fn traced(tw: *Io.Writer.Allocating, needle: []const u8) bool {+ return std.mem.indexOf(u8, tw.written(), needle) != null;+}++/// How the client ended the connection, as seen from the other side.+pub const saw_nothing: u8 = 0;+pub const saw_close_frame: u8 = 1;+pub const saw_fin: u8 = 2;++/// Complete the upgrade, then classify the next thing the client does: a ws close+/// frame (opcode 0x8) or EOF. `deinit` normally writes a courtesy close frame —+/// one more BLOCKING write on a socket that may be what wedged us.+pub fn closeObserver(io: Io, server: *std.Io.net.Server, seen: *std.atomic.Value(u8), done: *std.atomic.Value(bool)) void {+ const c = server.accept(io) catch return;+ defer c.close(io);+ var rbuf: [8192]u8 = undefined;+ var wbuf: [4096]u8 = undefined;+ var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);+ var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);+ while (true) {+ const line = sr.interface.takeDelimiterInclusive('\n') catch return Mock.idle(io, done);+ if (line.len <= 2) break;+ }+ sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch return Mock.idle(io, done);+ sw.interface.flush() catch return Mock.idle(io, done);+ const h = sr.interface.takeArray(2) catch {+ seen.store(saw_fin, .release); // stream ended: a plain TCP FIN+ return Mock.idle(io, done);+ };+ seen.store(if ((h[0] & 0x0f) == 0x8) saw_close_frame else saw_nothing, .release);+ Mock.idle(io, done);+}diff --git a/src/agent_ws_reuse_test.zig b/src/agent_ws_reuse_test.zignew file mode 100644index 00000000..cb6dbc64--- /dev/null+++ b/src/agent_ws_reuse_test.zig@@ -0,0 +1,235 @@+//! (#401 round 4) What a codex WS turn is allowed to WAIT for, end-to-end+//! through agent_ws.postResponsesWs on the agent_ws_mock loopback peer.+//!+//! Two invariants the round-3 fix did not have:+//! * a REUSED socket that answers nothing is a dead socket, bounded by the+//! head budget and reported to the transport ladder — not 120s of dead air+//! charged to the turn's 2-slot stall budget;+//! * a FRESH connect keeps the full pre-first-token budget, because its+//! handshake just proved the peer is there;+//! * and the tokens-flowing signal covers tool-argument prose, which is the+//! ONLY visible output an attempt_completion turn produces.++const std = @import("std");+const builtin = @import("builtin");+const Io = std.Io;++const http = @import("http.zig");+const http_stall = @import("http_stall.zig");+const trace = @import("trace.zig");+const ws = @import("ws.zig");+const agent_ws = @import("agent_ws.zig");++const mock = @import("agent_ws_mock.zig");+const Mock = mock.Mock;+const nowMs = mock.nowMs;+const mockAgent = mock.mockAgent;+const traced = mock.traced;++// The arg-prose half of the tokens-flowing signal, at the call site.+//+// A codex turn whose whole visible answer is attempt_completion's `result`+// streams `response.function_call_arguments.delta` and never one+// `response.output_text.delta`. On SSE that prose grows partial_text+// (argLiveDelta → emitArgText), so the SSE reader tightens to a quarter from the+// first byte; the round-3 WS signal saw none of it and held the FULL+// pre-first-token budget for exactly the turn shape #401 was reported from.+// Keying only on output_text fails this at `ms < 1500`.+test "#401: silence after streamed tool-argument prose trips the tightened budget" {+ 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.arg_prose_then_silence, &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.expectEqual(@as(u64, 500), 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;+ };++ // A FRESH dial, so the head budget below is not what bounds this: the only+ // thing that can end the turn early is the tightened inter-frame budget.+ const body = "{\"model\":\"gpt-5\",\"input\":[]}";+ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ try std.testing.expectError(error.StreamStalled, r);+ try std.testing.expect(ms >= 400);+ try std.testing.expect(ms < 1500); // NOT the 2000ms pre-first-token budget+ // …and it was the ARGUMENT prose that did it: not one output_text delta+ // was sent, yet the reader reports prose flowing.+ try std.testing.expect(traced(&tw, "\"detail\":\"first output text"));+ try std.testing.expect(traced(&tw, "\"detail\":\"stall\""));+}++// The reused-socket first-frame budget.+//+// The branch's own reasoning says response.created / in_progress land within+// milliseconds of a send — which is why frame ARRIVAL is a bad tokens-flowing+// signal, and equally why ZERO frames on a socket held since the last request is+// a dead-socket signature rather than a thinking model. Before this, that case+// armed the full 120s pre-first-token budget and surfaced as StreamStalled,+// spending a slot of request()'s 2-slot stall budget; SSE bounds the same+// condition at head_stall_ms and returns HungRequest. Forcing `head_wait = false`+// fails this on the error type and on `ms < 2000`.+test "#401: a reused socket that answers nothing fails on the head budget as a transport error" {+ 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.read_then_silence, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ // A head budget an order of magnitude under the pre-first-token budget, so+ // which one fired is unambiguous from the elapsed time alone.+ const saved_head = http.head_stall_ms;+ const saved_stream = http.stream_stall_ms;+ http.head_stall_ms = 400;+ http.stream_stall_ms = 4000;+ defer http.head_stall_ms = saved_head;+ defer http.stream_stall_ms = saved_stream;++ 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;++ // #401's reported state: a socket held across the tool call, reused for the+ // delta. The peer takes the frame and never speaks again.+ var ws_url_buf: [64]u8 = undefined;+ const ws_url = try std.fmt.bufPrint(&ws_url_buf, "ws://127.0.0.1:{d}/x", .{server.socket.address.getPort()});+ agent.codex_ws = try ws.WsClient.connect(gpa, io, ws_url, false, &.{});+ agent.codex_ws_used_ms = nowMs(io); // fresh: the idle re-anchor must not fire+ defer if (agent.codex_ws) |c| {+ c.dead = true;+ c.deinit(gpa);+ agent.codex_ws = null;+ };++ const body = "{\"model\":\"gpt-5\",\"previous_response_id\":\"resp_1\",\"input\":[]}";+ const t0 = nowMs(io);+ const r = agent_ws.postResponsesWs(&agent, body);+ const ms = nowMs(io) - t0;+ if (r) |ok| gpa.free(ok) else |_| {}++ // HungRequest, not StreamStalled: postLive re-anchors on a fresh socket and+ // only latches SSE on a second failure, instead of spending the turn's+ // stall budget on a socket that was already dead when we wrote to it.+ try std.testing.expectError(error.HungRequest, r);+ try std.testing.expect(ms >= 300); // the watchdog ran+ try std.testing.expect(ms < 2000); // …on the head budget, not the 4000ms one+ try std.testing.expect(traced(&tw, "\"detail\":\"reuse (delta)\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"sent "));+ try std.testing.expect(traced(&tw, "\"detail\":\"reuse dead — no first frame\""));+ try std.testing.expect(!traced(&tw, "\"detail\":\"first frame\""));+ // Torn down, so request()'s rebuild loop re-anchors with FULL input.+ try std.testing.expect(agent.codex_ws == null);+ try std.testing.expect(agent.codex_prev_id == null);+ try std.testing.expectEqual(@as(usize, 0), agent.codex_sent_upto);+}++// …and the other side of that boundary, which is what makes the head budget+// safe to apply at all: a FRESH connect just completed a TCP + upgrade+// handshake, so its silence is a model thinking, not a dead peer. It keeps the+// full pre-first-token budget. Dropping the `reused` term (`head_wait =+// frames_seen == 0`) fails this: the first token arrives after the head budget,+// so a legitimate high-effort turn would die as a transport error.+test "#401: a fresh connect keeps the full pre-first-token budget for a slow first token" {+ 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.slow_first_frame, &done });+ defer fut.await(io);+ defer done.store(true, .release);++ const saved_head = http.head_stall_ms;+ const saved_stream = http.stream_stall_ms;+ const saved_think = mock.slow_first_frame_ms;+ http.head_stall_ms = 300; // …which the dial still fits inside+ http.stream_stall_ms = 4000;+ mock.slow_first_frame_ms = 700; // > the head budget, << the full one+ defer http.head_stall_ms = saved_head;+ defer http.stream_stall_ms = saved_stream;+ defer mock.slow_first_frame_ms = saved_think;++ 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;+ };++ // No held socket: this turn dials, so `reused` is false.+ const body = "{\"model\":\"gpt-5\",\"input\":[]}";+ const t0 = nowMs(io);+ const out = try agent_ws.postResponsesWs(&agent, body);+ defer gpa.free(out);+ const ms = nowMs(io) - t0;++ try std.testing.expect(std.mem.indexOf(u8, out, mock.delta_event) != null);+ try std.testing.expect(std.mem.indexOf(u8, out, mock.completed_event) != null);+ try std.testing.expect(ms >= 600); // the first token really did outlast the head budget+ try std.testing.expect(traced(&tw, "\"detail\":\"connected\""));+ try std.testing.expect(traced(&tw, "\"detail\":\"completed\""));+ try std.testing.expect(!traced(&tw, "\"detail\":\"reuse dead"));+ try std.testing.expect(!traced(&tw, "\"detail\":\"stall\""));+ try std.testing.expect(agent.codex_ws != null); // held for the next delta+}diff --git a/src/agent_ws_signal.zig b/src/agent_ws_signal.zignew file mode 100644index 00000000..434ca38b--- /dev/null+++ b/src/agent_ws_signal.zig@@ -0,0 +1,124 @@+//! (#401) "Is VISIBLE PROSE flowing?" for the codex WebSocket reader — the WS+//! side of the signal the SSE reader takes straight from `partial_text`.+//!+//! Both feed the same http_stall.budgetMs, so this must mean EXACTLY what the+//! SSE signal means: too loose and a silently-reasoning turn is killed as a+//! 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+//! partial_text has TWO producers, both reached from agent_stream.streamSseLine:+//!+//! 1. the `response.output_text.delta` arm, whose `if (text.len == 0) return;`+//! gate is why an EMPTY delta does not count. Reasoning deltas are handled+//! above the append and `response.output_item.done` never reaches it, so a+//! silent reasoning phase keeps the FULL pre-first-token budget on SSE —+//! deliberately, since it legitimately runs minutes. → frameHasOutputText.+//! 2. `argLiveDelta` (called on EVERY line, before the text extraction) →+//! ArgLive.feed → agent_argstream.emitArgText, which appends the streamed+//! tool-ARGUMENT prose of a whitelisted call. Not an exotic path:+//! attempt_completion is graff's ordinary final-answer tool, so a codex+//! turn whose entire visible output is that prose streams only+//! `response.function_call_arguments.delta` and never one output_text+//! delta. → TokenSignal.+//!+//! The whitelist is NOT duplicated here: `argToolFor` is the same function+//! ArgLive.open classifies with, so the SSE and WS signals cannot drift.+//!+//! Lives beside agent_ws.zig (which is near the 600-line cap) the way+//! http_stall.zig lives beside http.zig, and is aliased back into agent_ws.++const std = @import("std");++const argstream = @import("agent_argstream.zig");+const argToolFor = argstream.argToolFor;+const outputIndex = argstream.outputIndex;++/// Producer 1: does this ws frame carry VISIBLE OUTPUT TEXT?+///+/// Frame ARRIVAL is not the signal: response.created / response.in_progress /+/// response.output_item.added land within milliseconds of the send, long before+/// the model has thought (and ping/pong never surfaces from readMessage at+/// all). Keying the budget on "a frame landed" tightens every WS turn to a+/// quarter budget from ~100ms in, so a high-effort turn reasoning silently past+/// that is killed as a stall, re-sent as a full re-anchor, stalled again, and+/// latched off WS for the session — while the identical turn survives on SSE.+///+/// Shape mirrors isStreamEnd: a cheap substring candidate, then an+/// authoritative parse, so a reasoning delta that merely QUOTES the event name+/// is not mistaken for one.+pub fn frameHasOutputText(gpa: std.mem.Allocator, frame: []const u8) bool {+ const ev = "response.output_text.delta";+ if (std.mem.indexOf(u8, frame, ev) == null) return false;+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const v = std.json.parseFromSliceLeaky(std.json.Value, scratch.allocator(), frame, .{ .allocate = .alloc_always }) catch return false;+ if (v != .object) return false;+ const ty = v.object.get("type") orelse return false;+ if (ty != .string or !std.mem.eql(u8, ty.string, ev)) return false;+ const d = v.object.get("delta") orelse return false;+ return d == .string and d.string.len != 0;+}++/// 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).+///+/// Producer 2 is keyed on the item, not the tool-argument bytes: SSE's ArgLive+/// starts appending a fraction of a frame later (once its scanner reaches the+/// `result`/`question` VALUE), so keying on the first non-empty argument delta+/// of a whitelisted call tightens at most one frame early on the same stream.+/// That direction is the safe one — the alternative is running a second copy of+/// the ArgLive scanner here, i.e. the drift this module exists to prevent.+pub const TokenSignal = struct {+ /// `output_index` of the open whitelisted (attempt_completion / ask_user)+ /// function call; -1 for none. The mirror of ArgLive.index, opened and+ /// closed by the same events argLiveDelta uses.+ arg_ix: i64 = -1,++ /// True the first time a frame proves visible prose is flowing. Called only+ /// until it returns true — the budget never un-tightens.+ pub fn flowing(self: *TokenSignal, gpa: std.mem.Allocator, frame: []const u8) bool {+ if (frameHasOutputText(gpa, frame)) return true;+ return self.argProse(gpa, frame);+ }++ /// 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+ /// nothing on SSE and so must leave the pre-first-token budget standing.+ fn argProse(self: *TokenSignal, gpa: std.mem.Allocator, frame: []const u8) bool {+ const arg_delta = "response.function_call_arguments.delta";+ // Cheap candidate filter, same shape as frameHasOutputText's: the two+ // item lifecycle events share the `response.output_item.` prefix.+ if (std.mem.indexOf(u8, frame, "response.output_item.") == null and+ std.mem.indexOf(u8, frame, arg_delta) == null) return false;+ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const v = std.json.parseFromSliceLeaky(std.json.Value, scratch.allocator(), frame, .{ .allocate = .alloc_always }) catch return false;+ if (v != .object) return false;+ const ty = v.object.get("type") orelse return false;+ if (ty != .string) return false;+ if (std.mem.eql(u8, ty.string, "response.output_item.added")) {+ const ix = outputIndex(v.object) orelse return false;+ const item = v.object.get("item") orelse return false;+ if (item != .object) return false;+ const it = item.object.get("type") orelse return false;+ if (it != .string or !std.mem.eql(u8, it.string, "function_call")) return false;+ const name = item.object.get("name") orelse return false;+ // Exactly ArgLive.open's gate: a non-whitelisted name opens nothing+ // (and cannot clobber an open index — output indices are unique).+ if (name == .string and argToolFor(name.string) != .none) self.arg_ix = ix;+ return false;+ }+ if (std.mem.eql(u8, ty.string, "response.output_item.done")) {+ const ix = outputIndex(v.object) orelse return false;+ if (ix == self.arg_ix) self.arg_ix = -1; // ArgLive.close+ return false;+ }+ if (!std.mem.eql(u8, ty.string, arg_delta)) return false;+ const ix = outputIndex(v.object) orelse return false;+ if (ix != self.arg_ix) return false;+ const d = v.object.get("delta") orelse return false;+ return d == .string and d.string.len != 0;+ }+};diff --git a/src/agent_ws_stall_test.zig b/src/agent_ws_stall_test.zigindex d6589fbe..01c244f6 100644--- a/src/agent_ws_stall_test.zig+++ b/src/agent_ws_stall_test.zig@@ -1,10 +1,11 @@-//! (#401) End-to-end transport tests for the codex WebSocket turn, driven by a-//! loopback WebSocket server that can misbehave on demand. These exercise the-//! REAL production entry point (agent_ws.postResponsesWs) rather than the guard+//! (#401) End-to-end transport tests for the codex WebSocket turn, driven by the+//! loopback WebSocket server in agent_ws_mock.zig. These exercise the REAL+//! production entry point (agent_ws.postResponsesWs) rather than the guard//! helpers in isolation, because #401's whole lesson was that the call sites and-//! the budgets — not the helpers — were where the turn went silent. The mock is-//! in the same spirit as the GRAFF_CODEX_URL/lmstudio HTTP mocks: `provider.url`-//! points at 127.0.0.1, and no network, key or provider is used.+//! the budgets — not the helpers — were where the turn went silent.+//!+//! Here: the read/send/dial BUDGETS and the teardown. The reuse-vs-fresh-connect+//! first-frame budget is agent_ws_reuse_test.zig, on the same harness.const std = @import("std");const builtin = @import("builtin");@@ -15,134 +16,14 @@ const http_stall = @import("http_stall.zig");const trace = @import("trace.zig");const ws = @import("ws.zig");const agent_ws = @import("agent_ws.zig");-const Agent = @import("agent.zig").Agent;-fn nowMs(io: Io) i64 {- return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_ms));-}--const delta_event = "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}";-const completed_event = "{\"type\":\"response.completed\"}";--/// What the backend actually puts on the socket in the first milliseconds after-/// a send, before the model has produced anything: the two protocol events, then-/// a reasoning delta. None of these grows partial_text on the SSE path, so none-/// may tighten the WS read budget either.-const protocol_events = [_][]const u8{- "{\"type\":\"response.created\",\"response\":{\"id\":\"r1\"}}",- "{\"type\":\"response.in_progress\",\"response\":{\"id\":\"r1\"}}",- "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"thinking\"}",-};--/// A loopback WebSocket peer with a scripted failure mode.-const Mock = struct {- const Mode = enum {- /// Accept the TCP connection and never answer the upgrade — the dial- /// that hangs before the 101 status line.- no_upgrade,- /// Upgrade, then never read again: the client's frame fills the socket- /// buffers and its write parks in the kernel.- never_drain,- /// Upgrade, take the client's frame, answer with ONE delta frame and- /// then go permanently silent. This is #401's reported signature: the- /// turn is under way, data flowed, and the server stopped.- frame_then_silence,- /// The healthy control: delta, then response.completed.- frame_then_complete,- /// Upgrade, take the client's frame, answer with `protocol_events` and- /// then go quiet while the model "thinks". Frames flow, none of them is- /// output text — so the budget must stay at the pre-first-token value.- protocol_then_silence,- };-- fn run(io: Io, server: *std.Io.net.Server, mode: Mode, done: *std.atomic.Value(bool)) void {- const c = server.accept(io) catch return;- defer c.close(io);- var rbuf: [8192]u8 = undefined;- var wbuf: [4096]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);- var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);- if (mode == .no_upgrade) return idle(io, done);-- while (true) {- const line = sr.interface.takeDelimiterInclusive('\n') catch return idle(io, done);- if (line.len <= 2) break; // the blank line ends the upgrade request- }- sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch return idle(io, done);- sw.interface.flush() catch return idle(io, done);-- switch (mode) {- .no_upgrade, .never_drain => {},- .frame_then_silence, .frame_then_complete => {- readClientFrame(&sr.interface) catch return idle(io, done);- writeTextFrame(&sw.interface, delta_event) catch return idle(io, done);- if (mode == .frame_then_complete)- writeTextFrame(&sw.interface, completed_event) catch return idle(io, done);- },- .protocol_then_silence => {- readClientFrame(&sr.interface) catch return idle(io, done);- for (protocol_events) |ev|- writeTextFrame(&sw.interface, ev) catch return idle(io, done);- },- }- idle(io, done);- }-- /// Hold the connection open (and, for never_drain, undrained) until the test- /// releases it. Closing early hands the client a clean EOF, a different- /// failure than the silence being reproduced.- fn idle(io: Io, done: *std.atomic.Value(bool)) void {- while (!done.load(.acquire)) io.sleep(.fromMilliseconds(20), .awake) catch break;- }-- /// Consume one masked client frame (RFC 6455 §5.2); the payload is ignored.- fn readClientFrame(r: *Io.Reader) !void {- const h = try r.takeArray(2);- var len: u64 = h[1] & 0x7f;- if (len == 126) {- len = std.mem.readInt(u16, try r.takeArray(2), .big);- } else if (len == 127) {- len = std.mem.readInt(u64, try r.takeArray(8), .big);- }- if ((h[1] & 0x80) != 0) _ = try r.takeArray(4); // mask key- try r.discardAll(@intCast(len));- }-- /// One unmasked server->client text frame (payloads here are all < 126 B).- fn writeTextFrame(w: *Io.Writer, payload: []const u8) !void {- try w.writeAll(&[_]u8{ 0x81, @intCast(payload.len) });- try w.writeAll(payload);- try w.flush();- }-};--/// A root-shaped Agent pointed at the mock. `out`/`in` stay null: no TTY means no-/// spinner, no Esc poll and no user-facing stall line — the transport alone.-fn mockAgent(gpa: std.mem.Allocator, arena: std.mem.Allocator, io: Io, url: []const u8) Agent {- return .{- .gpa = gpa,- .arena = arena,- .io = io,- .client = undefined, // the WS path never touches the HTTP client- .provider = .{- .id = "codex",- .kind = .responses,- .auth = .bearer,- .url = url,- .api_key = "k",- .model = "gpt-5",- .context = 100_000,- },- .messages = std.json.Array.init(arena),- .sub = false,- .label = "",- .out = null,- };-}--fn traced(tw: *Io.Writer.Allocating, needle: []const u8) bool {- return std.mem.indexOf(u8, tw.written(), needle) != null;-}+const mock = @import("agent_ws_mock.zig");+const Mock = mock.Mock;+const nowMs = mock.nowMs;+const mockAgent = mock.mockAgent;+const traced = mock.traced;+const delta_event = mock.delta_event;+const completed_event = mock.completed_event;// ── the #401 read-side stall ─────────────────────────────────────────────────@@ -493,35 +374,6 @@ test "#401: a stalled dial fails the turn fast and traces `connect stall` (produ// ── teardown: a suspect socket gets a FIN, not a courtesy close frame ────────-// How the client ended the connection, as seen from the other side.-const saw_nothing: u8 = 0;-const saw_close_frame: u8 = 1;-const saw_fin: u8 = 2;--/// Complete the upgrade, then classify the next thing the client does: a ws close-/// frame (opcode 0x8) or EOF. `deinit` normally writes a courtesy close frame —-/// one more BLOCKING write on a socket that may be what wedged us.-fn closeObserver(io: Io, server: *std.Io.net.Server, seen: *std.atomic.Value(u8), done: *std.atomic.Value(bool)) void {- const c = server.accept(io) catch return;- defer c.close(io);- var rbuf: [8192]u8 = undefined;- var wbuf: [4096]u8 = undefined;- var sr = std.Io.net.Stream.Reader.init(c, io, &rbuf);- var sw = std.Io.net.Stream.Writer.init(c, io, &wbuf);- while (true) {- const line = sr.interface.takeDelimiterInclusive('\n') catch return Mock.idle(io, done);- if (line.len <= 2) break;- }- sw.interface.writeAll("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n\r\n") catch return Mock.idle(io, done);- sw.interface.flush() catch return Mock.idle(io, done);- const h = sr.interface.takeArray(2) catch {- seen.store(saw_fin, .release); // stream ended: a plain TCP FIN- return Mock.idle(io, done);- };- seen.store(if ((h[0] & 0x0f) == 0x8) saw_close_frame else saw_nothing, .release);- Mock.idle(io, done);-}-// The idle-expiry branch's own comment says the server has "likely already// killed" that socket, so it must not spend deinit's blocking courtesy close// frame on it. Watching the wire is the only way to test this: closeCodexWs@@ -536,8 +388,8 @@ test "#401: the idle-expiry teardown FINs a suspect socket instead of writing avar server = try std.Io.net.IpAddress.listen(&addr, io, .{});defer server.deinit(io);var done: std.atomic.Value(bool) = .init(false);- var seen: std.atomic.Value(u8) = .init(saw_nothing);- var fut = io.async(closeObserver, .{ io, &server, &seen, &done });+ var seen: std.atomic.Value(u8) = .init(mock.saw_nothing);+ var fut = io.async(mock.closeObserver, .{ io, &server, &seen, &done });defer fut.await(io);defer done.store(true, .release);@@ -572,7 +424,7 @@ test "#401: the idle-expiry teardown FINs a suspect socket instead of writing atry std.testing.expect(agent.codex_ws == null);var waited: usize = 0;- while (seen.load(.acquire) == saw_nothing and waited < 3000) : (waited += 20)+ while (seen.load(.acquire) == mock.saw_nothing and waited < 3000) : (waited += 20)try io.sleep(.fromMilliseconds(20), .awake);- try std.testing.expectEqual(saw_fin, seen.load(.acquire));+ try std.testing.expectEqual(mock.saw_fin, seen.load(.acquire));}diff --git a/src/agent_ws_test.zig b/src/agent_ws_test.zigindex c58ba118..fc385e9d 100644--- a/src/agent_ws_test.zig+++ b/src/agent_ws_test.zig@@ -367,6 +367,59 @@ test "#401: only a visible output-text delta is the tokens-flowing signal (SSE ptry std.testing.expect(agent_ws.frameHasOutputText(gpa, "{\"seq\":3,\"delta\":\"h\",\"type\":\"response.output_text.delta\"}"));}+// (#401 round 4) …and the SECOND producer, which the round-3 signal missed.+//+// partial_text does NOT grow in only one place on SSE: streamSseLine calls+// argLiveDelta on every line, and emitArgText appends the streamed ARGUMENTS of+// a whitelisted meta call (agent_argstream.ArgTool). attempt_completion is+// graff's ordinary final-answer tool, so a codex turn whose whole visible output+// is that prose emits `response.function_call_arguments.delta` and never one+// output_text delta — SSE tightened from the first prose byte while WS held the+// full 120s. The whitelist is `argToolFor`, shared with ArgLive so the two+// cannot drift: an ordinary tool's argument stream prints nothing and must not+// tighten anything.+test "#401: whitelisted tool-argument prose is a tokens-flowing signal too (SSE parity)" {+ const gpa = std.testing.allocator;+ const open_meta = "{\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"attempt_completion\"}}";+ const open_edit = "{\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"function_call\",\"name\":\"edit_file\"}}";+ const arg_delta = "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"delta\":\"{\\\"result\\\":\\\"hi\"}";+ const done_0 = "{\"type\":\"response.output_item.done\",\"output_index\":0}";++ // attempt_completion: the open event is not prose, the first argument byte is.+ var meta: agent_ws.TokenSignal = .{};+ try std.testing.expect(!meta.flowing(gpa, open_meta));+ try std.testing.expect(meta.flowing(gpa, arg_delta));++ // ask_user's `question` is the other whitelisted field.+ var ask: agent_ws.TokenSignal = .{};+ try std.testing.expect(!ask.flowing(gpa, "{\"type\":\"response.output_item.added\",\"output_index\":7,\"item\":{\"type\":\"function_call\",\"name\":\"ask_user\"}}"));+ try std.testing.expect(ask.flowing(gpa, "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":7,\"delta\":\"{\\\"question\\\":\\\"?\"}"));++ // An ORDINARY tool's arguments stream invisibly on SSE, so the identical+ // delta must leave the pre-first-token budget standing.+ var edit: agent_ws.TokenSignal = .{};+ try std.testing.expect(!edit.flowing(gpa, open_edit));+ try std.testing.expect(!edit.flowing(gpa, arg_delta));++ // …as must an arg delta for an item nobody opened, a different item, an+ // empty delta, a non-function_call item, and one whose call already closed.+ var stray: agent_ws.TokenSignal = .{};+ try std.testing.expect(!stray.flowing(gpa, arg_delta));+ try std.testing.expect(!stray.flowing(gpa, open_meta));+ try std.testing.expect(!stray.flowing(gpa, "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":1,\"delta\":\"x\"}"));+ try std.testing.expect(!stray.flowing(gpa, "{\"type\":\"response.function_call_arguments.delta\",\"output_index\":0,\"delta\":\"\"}"));+ try std.testing.expect(!stray.flowing(gpa, done_0));+ try std.testing.expect(!stray.flowing(gpa, arg_delta)); // closed by done_0+ var msg: agent_ws.TokenSignal = .{};+ try std.testing.expect(!msg.flowing(gpa, "{\"type\":\"response.output_item.added\",\"output_index\":0,\"item\":{\"type\":\"message\",\"name\":\"attempt_completion\"}}"));+ try std.testing.expect(!msg.flowing(gpa, arg_delta));++ // …and the other producer still reaches the same entry point unchanged.+ var text: agent_ws.TokenSignal = .{};+ try std.testing.expect(!text.flowing(gpa, "{\"type\":\"response.reasoning_summary_text.delta\",\"delta\":\"hmm\"}"));+ try std.testing.expect(text.flowing(gpa, "{\"type\":\"response.output_text.delta\",\"delta\":\"hi\"}"));+}+// A flat head-sized send deadline is a false-positive generator on exactly the// frame most likely to sit under it: every recovery re-anchors with the FULL// conversation, so the retried frame is hundreds of KB where the delta was a few.@@ -395,12 +448,15 @@ test "sendDeadlineMs (#401): head budget for a delta, transmit room for a full rtry std.testing.expectEqual(head, agent_ws.sendDeadlineMs(1024 * 1024, head, 500));}-// #401's transport tests (mock-WS end-to-end) live in agent_ws_stall_test.zig:-// they need a loopback WebSocket server and a real Agent, which is more harness-// than this file's pure-decision tests carry. main.zig's test root is AT the-// 600-line cap, so that module is hooked transitively through this one, which is-// already on the root chain (reference_zig_test_wiring: a module with no path to-// the root compiles but never runs a single test).+// #401's transport tests (mock-WS end-to-end) live in agent_ws_stall_test.zig+// (budgets, guards, teardown) and agent_ws_reuse_test.zig (reuse vs fresh+// connect), on the shared agent_ws_mock.zig harness: they need a loopback+// WebSocket server and a real Agent, which is more harness than this file's+// pure-decision tests carry. main.zig's test root is AT the 600-line cap, so+// those modules are hooked transitively through this one, which is already on+// the root chain (reference_zig_test_wiring: a module with no path to the root+// compiles but never runs a single test).comptime {_ = @import("agent_ws_stall_test.zig");+ _ = @import("agent_ws_reuse_test.zig");}