Skip to content

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

Python

fix(#134): distinguish a stream stall from a user Esc interrupt

justrach370013bf4566
diff --git a/src/agent_request.zig b/src/agent_request.zig
index 88a9f95a..b780db42 100644
--- a/src/agent_request.zig
+++ b/src/agent_request.zig
@@ -81,6 +81,18 @@ pub fn request(self: *Agent, tools: ?[]const u8) !std.json.ObjectMap {
self.streamed_args = .none;
// Esc is a deliberate stop, not a flaky network — no retry.
if (err == error.Interrupted) return error.Interrupted;
+ // A mid-stream idle stall already streamed its partial text
+ // and printed the "stream stalled" notice; retrying would
+ // re-stream the whole answer from scratch. End the turn — but
+ // as error.StreamStalled, recorded with the timeout + reason,
+ // so it is classified as a harness stall and never as a user
+ // Esc interruption (#134).
+ if (err == error.StreamStalled) {
+ self.last_api_error = std.fmt.allocPrint(self.arena, "stream stalled: no data from the model for {d}s — ended the turn (raise GRAFF_STREAM_STALL_SECS if your model needs longer)", .{http.stream_stall_ms / 1000}) catch null;
+ if (telemetry.g_telem) |t| t.errorEvent("stream_stall", self.last_api_error orelse "stream stalled");
+ if (self.tracer) |tr| tr.note("stream_stall", self.last_api_error orelse "stream stalled");
+ return error.StreamStalled;
+ }
// 429/5xx: the server asked us to back off — wait
// (1s·2ⁿ, capped at 8s; Esc cancels) and allow a few
// more attempts than a plain transport flake gets.
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index 82cc5ce7..0b378349 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -43,6 +43,7 @@ const sendHeadTask = http.sendHeadTask;
const headStallTask = http.headStallTask;
const streamLineTask = http.streamLineTask;
const streamStallTask = http.streamStallTask;
+const watchdogError = http.watchdogError;
// escPressed/drainSteerStdin/rawNonblockStdin/ssePayload live in
// agent_interrupt.zig; reached through the Agent struct's member aliases.
@@ -283,7 +284,7 @@ pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
},
.stall => |w| {
if (req.connection) |conn| conn.closing = true;
- return if (w == .esc) error.Interrupted else error.HungRequest;
+ return watchdogError(w, error.HungRequest);
},
}
}
@@ -353,11 +354,16 @@ pub fn postStream(self: *Agent, body: []const u8) ![]u8 {
.stall => |w| {
self.flushStreamTail();
if (req.connection) |conn| conn.closing = true;
+ // A user Esc is a deliberate cancel; a `.deadline` is a dead
+ // or idle stream (no SSE bytes for stream_stall_ms) — end the
+ // turn, but as error.StreamStalled so it is never recorded as
+ // "[response interrupted by user]" (#134). The notice below is
+ // for the deadline case only (Esc has its own message path).
if (w == .deadline and !main_mod.json_mode) if (self.out) |o| {
o.writeAll("\n⚠ stream stalled — ending turn\n") catch {};
o.flush() catch {};
};
- return error.Interrupted;
+ return watchdogError(w, error.StreamStalled);
},
}
}
diff --git a/src/http.zig b/src/http.zig
index 2b17bbf4..1493d0bd 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -136,6 +136,29 @@ const post_deadline_ms: u64 = 5 * 60 * 1000;
pub const WatchdogFired = enum { esc, deadline };
+/// Classify a fired stream/head watchdog into an error. A user Esc is a
+/// deliberate cancel — error.Interrupted, which request()'s retry loop never
+/// retries and mainloop records as a user interruption. A `.deadline` is a
+/// dead/idle connection, NOT the user: the caller passes the error it wants
+/// for that case (HungRequest to retry the head, StreamStalled to end the
+/// turn). This is the seam that keeps a stall from being mislabeled as an
+/// Esc — the root cause of #134.
+pub fn watchdogError(w: WatchdogFired, on_deadline: anyerror) anyerror {
+ return if (w == .esc) error.Interrupted else on_deadline;
+}
+
+test "watchdogError (#134): Esc -> Interrupted; a deadline is the caller's error, never Interrupted" {
+ // A real user Esc is always a deliberate interrupt, whatever the caller's deadline error.
+ try std.testing.expect(watchdogError(.esc, error.HungRequest) == error.Interrupted);
+ try std.testing.expect(watchdogError(.esc, error.StreamStalled) == error.Interrupted);
+ // A deadline (idle/dead connection) surfaces as whatever the caller chose:
+ // HungRequest for the head (retry), StreamStalled for a mid-stream stall (end turn).
+ try std.testing.expect(watchdogError(.deadline, error.HungRequest) == error.HungRequest);
+ try std.testing.expect(watchdogError(.deadline, error.StreamStalled) == error.StreamStalled);
+ // The #134 regression guard: a stall must NEVER be reported as a user Esc.
+ try std.testing.expect(watchdogError(.deadline, error.StreamStalled) != error.Interrupted);
+}
+
/// Watchdog arm for postWatched: ticks every 200ms so a user Esc aborts a
/// stuck subagent request promptly; otherwise fires at the hard deadline.
fn postWatchdog(io: Io) WatchdogFired {
@@ -148,12 +171,17 @@ fn postWatchdog(io: Io) WatchdogFired {
return .deadline;
}
-// A streaming response idle this long (no SSE bytes — a dead/stalled
-// connection, or a model that hung before its first token or mid-answer) is
-// given up on, so a turn can't hang forever. Generous, so a legit reasoning
-// pause doesn't trip it. The TTY Esc-interrupt is the only other escape and
-// doesn't apply to --json/GUI sessions, where this matters most.
-const stream_stall_ms: u64 = 120 * 1000;
+// A streaming response idle THIS LONG between SSE events (not total response
+// time — streamStallTask resets its clock on every line, so it measures the
+// gap between tokens/keep-alives/reasoning deltas) is treated as a dead or
+// hung connection and given up on, so a turn can't wait forever. Generous, so
+// a legit reasoning pause between tokens doesn't trip it; a model that streams
+// — even slowly — never does, since each event resets the clock. Only TOTAL
+// silence trips it. Tunable via GRAFF_STREAM_STALL_SECS (wired in
+// session_run.setupSkillsAndTheme) for providers that buffer a long reasoning
+// phase in complete silence. Giving up here is error.StreamStalled — a
+// harness stall, NEVER a user Esc interruption (#134).
+pub var stream_stall_ms: u64 = 120 * 1000;
/// A response head (HTTP status line + headers) idle this long means the
/// server accepted the connection but isn't responding — common right
@@ -289,6 +317,6 @@ pub fn postWatched(gpa: Allocator, io: Io, client: *std.http.Client, provider: P
drainPostSelect(gpa, &sel);
return switch (first) {
.posted => |p| p,
- .watchdog => |w| if (w == .esc) error.Interrupted else error.HungRequest,
+ .watchdog => |w| watchdogError(w, error.HungRequest),
};
}
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 3b4eb736..b78f3291 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -470,6 +470,7 @@ pub fn run(ctx: *Ctx) !void {
if (!turn_ok) {
const fail_detail: []const u8 = if (turn_result) |_| "" else |e| switch (e) {
error.ApiError => ctx.root.last_api_error orelse "api error",
+ error.StreamStalled => ctx.root.last_api_error orelse "stream stalled — ended turn",
else => @errorName(e),
};
tj.node(.{ .kind = "turn_error", .parent = turn_id, .t = tj.elapsedMs(), .detail = fail_detail });
@@ -496,6 +497,26 @@ pub fn run(ctx: *Ctx) !void {
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
continue;
},
+ error.StreamStalled => {
+ // A dead/idle stream (no SSE bytes for stream_stall_ms): the
+ // harness gave up, NOT the user (#134) — keep the partial but
+ // tag it a stall, and emit the structured error for --json.
+ const partial = std.mem.trim(u8, ctx.root.partial_text.items, " \t\r\n");
+ const marker: []const u8 = if (partial.len > 0)
+ try std.fmt.allocPrint(ctx.arena, "{s}\n\n[response ended early: stream stalled]", .{partial})
+ else
+ "[response ended early: stream stalled]";
+ try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", marker));
+ if (main_mod.json_mode) {
+ ctx.root.emit(.{ .type = "error", .message = ctx.root.last_api_error orelse "stream stalled — ending turn" });
+ if (partial.len > 0) {
+ ctx.root.emit(.{ .type = "finalizing" });
+ ctx.root.emit(.{ .type = "turn", .text = partial, .context_tokens = ctx.root.last_context_tokens, .cost_usd = pricing.g_cost.snap(ctx.io).usd, .complete = false, .metadata_complete = ctx.root.last_context_tokens > 0 });
+ }
+ }
+ session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
+ continue;
+ },
error.ApiError => {
if (telemetry.g_telem) |t| t.errorEvent("api", ctx.root.last_api_error orelse "api error");
if (main_mod.json_mode) {
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index fbfb42c9..1a51c040 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -210,7 +210,21 @@ pub fn replTurnCb(ctx_ptr: ?*anyopaque, gpa: Allocator, history: []const repl.Tu
};
agent.messages.append(textMessage(arena, role, t.text) catch return null) catch return null;
}
- const final = agent.runTurn() catch return null;
+ const final = agent.runTurn() catch |err| switch (err) {
+ // A mid-stream stall (#134): the repl turn IS live (stream_quiet=false),
+ // so postStream can return error.StreamStalled. Don't collapse it to
+ // null — the pane renders that as "model call failed — check /model and
+ // your API key", mislabeling a harness stall as an auth/config problem.
+ // Keep the streamed partial + an honest marker, mirroring mainloop.
+ error.StreamStalled => {
+ const partial = std.mem.trim(u8, agent.partial_text.items, " \t\r\n");
+ return if (partial.len > 0)
+ std.fmt.allocPrint(gpa, "{s}\n\n[response ended early: stream stalled]", .{partial}) catch null
+ else
+ gpa.dupe(u8, "[response ended early: stream stalled]") catch null;
+ },
+ else => return null,
+ };
const trimmed = std.mem.trim(u8, final, " \t\r\n");
if (trimmed.len == 0) return null;
return gpa.dupe(u8, trimmed) catch null;
diff --git a/src/session_run.zig b/src/session_run.zig
index df31af2a..9b7a6281 100644
--- a/src/session_run.zig
+++ b/src/session_run.zig
@@ -28,6 +28,7 @@ const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const approvals_mod = @import("approvals.zig");
const tools_mod = @import("tools.zig");
+const http = @import("http.zig");
const provider_mod = @import("provider.zig");
const keys_cli = @import("keys_cli.zig");
const pricing = @import("pricing.zig");
@@ -331,6 +332,14 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
// auto-detection above it, NOT arbitrary workspace config.
main_mod.g_path_env = try arena.dupe(u8, environ_map.get("PATH") orelse "");
main_mod.g_codedb_guard = environ_map.get("GRAFF_NO_CODEDB_GUARD") == null; // issue #626 guard, opt-out via env
+ // #134: let a provider that buffers a long reasoning phase in total silence
+ // raise the mid-stream idle-stall cutoff (default 120s). Seconds; ignored if
+ // unparseable or 0. A stall is never a user interrupt regardless of the value.
+ if (environ_map.get("GRAFF_STREAM_STALL_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
+ } else |_| {}
+ }
skills.loadSkillSettings(io, arena); // per-skill opt-outs, also gates the auto-connect
anim.loadAnimationSetting(io, arena); // {"animation": "..."} → thinking spinner choice
anim.loadThemeSetting(io, arena); // {"theme": "<name>"} → opt-in terminal color theme