Skip to content

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

Python

fix(cancel): record who cancelled; an unsourced cancel is the harness's (#728)

justrach8ffd5784f2bd
diff --git a/docs/adr/0063-unsourced-cancel-is-the-harness.md b/docs/adr/0063-unsourced-cancel-is-the-harness.md
new file mode 100644
index 00000000..584ee887
--- /dev/null
+++ b/docs/adr/0063-unsourced-cancel-is-the-harness.md
@@ -0,0 +1,37 @@
+# 0063. A cancel with no recorded source is the harness's, not the user's
+
+Status: accepted 2026-09-03
+
+## Context
+
+`Agent.esc_cancel` is one process-wide flag with six setters — a lone Esc
+on the line REPL's raw stdin, a double-Enter force steer, a `--json`
+`cancel` line, an ACP `session/cancel`, the fullscreen TUI's cancel — and
+the turn-ending marker always read `[response interrupted by user]`. #728
+reports that marker twice on responses the user never interrupted, with no
+Esc, cancel, or stall event anywhere in the trace. Whatever flipped the flag
+(the report correlates it with a background-job exit notice), the label was
+wrong in two ways: it blamed the user, and it left no trace of the real
+source, so the next occurrence could not be attributed either.
+
+## Decision
+
+* Every setter goes through `cancel_source.cancel(source)`, which records
+ who raised the flag. A fresh turn clears both together.
+* Mainloop's `error.Interrupted` branch consumes the source. With a user
+ source the transcript keeps `[response interrupted by user]`; with none it
+ writes `[response ended early: cancelled by the harness, not the user]`,
+ the chrome line and the `--json` error say the same, and the trace carries
+ `interrupted source=<name>` either way.
+* The raw stdin scanner swallows an OSC sequence (a terminal's colour or
+ title *reply*) through its terminator instead of reading its leading ESC
+ as a keypress — one of the few ways the flag can rise without a hand on
+ the keyboard.
+* A job exit the model already read no longer queues a wake (ADR 0061),
+ which removes the injected notice the report describes.
+
+## Consequences
+
+* A false interrupt is now labelled honestly and named in the trace; the
+ root cause of #728, if it recurs, is one trace line away instead of a
+ guess. The user-facing behaviour of a real Esc is unchanged.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 2f95c5a5..14425c87 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -72,6 +72,7 @@ record only when you need the evidence or the edge cases.
| [0059](0059-saved-session-discovery-is-device-scoped.md) | `/resume` and `/sessions` list cwd then `~/.graff/sessions`; resume keeps tools in the current cwd. |
| [0060](0060-named-source-gate-is-per-unanswered-mention.md) | The named-source nudge is per unanswered mention; identical user turns do not replay (#714). |
| [0061](0061-tool-only-turns-narrate-and-ask-in-band.md) | Heads-up text rides in the same response as the tool calls; a choice for the user is an `ask_user` call; a job exit the model already read never wakes it. |
+| [0063](0063-unsourced-cancel-is-the-harness.md) | Every cancel records its source; a turn cancelled with no recorded source is labelled a harness cancel, never a user interrupt, and the source lands in the trace (#728). |
## When to write one
diff --git a/src/acp.zig b/src/acp.zig
index 45423af6..7df0d06e 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -57,7 +57,7 @@ pub fn isAcpSubcommand(positional: []const u8) bool {
}
fn syncEscCancel() void {
- agent_mod.Agent.esc_cancel.store(true, .release);
+ @import("cancel_source.zig").cancel(.acp_cancel); // #728
}
fn liveCancelled() bool {
diff --git a/src/agent.zig b/src/agent.zig
index 9994ce05..0bc891b5 100644
--- a/src/agent.zig
+++ b/src/agent.zig
@@ -334,7 +334,7 @@ pub const Agent = struct {
// No per-turn teardown: the socket and the chain span user turns, guarded by codex_chain.usable instead.
self.completed = null;
@import("named_work.zig").beginTurn(self);
- if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) esc_cancel.store(false, .release);
+ if (!self.sub and !root_turn_prepared.swap(false, .acq_rel)) @import("cancel_source.zig").clear();
while (true) {
if (try @import("turn_chrome.zig").beforeRequest(self)) |paused| return paused;
// Esc during a tool join lands here; root consumes, subagents bail.
@@ -515,7 +515,7 @@ pub const Agent = struct {
/// Clear stale cancellation before the root becomes externally cancellable;
/// runTurn consumes the marker without erasing a cancellation arriving later.
pub fn prepareRootTurn() void {
- esc_cancel.store(false, .release);
+ @import("cancel_source.zig").clear(); // flag + source (#728)
root_turn_prepared.store(true, .release);
}
diff --git a/src/agent_interrupt.zig b/src/agent_interrupt.zig
index 9d406bdf..0accccf1 100644
--- a/src/agent_interrupt.zig
+++ b/src/agent_interrupt.zig
@@ -20,6 +20,7 @@ const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const repl_glue = @import("repl_glue.zig");
const Agent = agent_mod.Agent;
+const cancel_source = @import("cancel_source.zig"); // #728
const ansi = @import("ansi.zig");
const style = &ansi.style;
@@ -29,7 +30,7 @@ const tty = terminal.tty;
pub fn escWatchTask() void {
while (!Agent.esc_watch_done.load(.acquire)) {
if (tty.poll(100) and escPressed(false)) {
- Agent.esc_cancel.store(true, .release);
+ cancel_source.cancelFromStdin();
return;
}
}
@@ -93,6 +94,20 @@ pub fn escPressed(echo: bool) bool {
// ESC O <final>. Swallow the whole sequence.
i = @min(i + 2, n - 1);
continue;
+ } else if (i + 1 < n and buf[i + 1] == ']') {
+ // OSC — a terminal's colour/title REPLY (ESC ] … BEL, or ESC \\):
+ // never a keypress, so it must not read as Esc (#728). Swallow
+ // through the terminator, pulling a split tail in like CSI.
+ var j = i + 2;
+ while (true) {
+ while (j < n and buf[j] != 0x07 and !(buf[j] == 0x1b and j + 1 < n and buf[j + 1] == '\\')) : (j += 1) {}
+ if (j < n or n >= buf.len or !tty.poll(50)) break;
+ const more = tty.readStdin(buf[n..]);
+ if (more == 0) break;
+ n += more;
+ }
+ i = if (j < n) (if (buf[j] == 0x1b) j + 1 else j) else n - 1;
+ continue;
} else if (i + 1 >= n) {
// ESC is the LAST byte of this chunk — it may be the truncated
// head of a split CSI/SS3/DSR sequence (e.g. a delayed
@@ -242,3 +257,7 @@ pub fn sseIndex(obj: std.json.ObjectMap) ?usize {
if (ix != .integer or ix.integer < 0) return null;
return @intCast(ix.integer);
}
+
+test { // #728: cancel_source has no other path into the test root
+ _ = cancel_source;
+}
diff --git a/src/cancel_source.zig b/src/cancel_source.zig
new file mode 100644
index 00000000..37e4ccd8
--- /dev/null
+++ b/src/cancel_source.zig
@@ -0,0 +1,127 @@
+//! Who cancelled the turn (#728). `Agent.esc_cancel` is one process-wide
+//! bool with six setters — a lone Esc on raw stdin, a double-Enter force
+//! steer, a `--json` cancel line, an ACP session/cancel, the TUI's cancel —
+//! and the turn-ending marker always read "[response interrupted by user]".
+//! When the flag flips for any other reason, that label is wrong twice: it
+//! blames the user, and it leaves no trace of the real source. Every setter
+//! now goes through `cancel(source)`, and mainloop reads the source back: a
+//! turn that ends cancelled with no recorded source is labelled a harness
+//! cancel, not a user interrupt, and the source lands in the trace.
+
+const std = @import("std");
+const Agent = @import("agent.zig").Agent;
+const main_mod = @import("main.zig");
+const Tracer = @import("trace.zig").Tracer;
+
+pub const Source = enum(u8) {
+ /// Nobody recorded one: the harness ended the turn, not the user.
+ none,
+ /// A lone Esc on the line REPL's raw stdin.
+ esc_key,
+ /// Double Enter with a queued steer line (escPressed marks it force).
+ force_steer,
+ /// --json `{"type":"cancel"}`.
+ json_cancel,
+ /// ACP `session/cancel`.
+ acp_cancel,
+ /// The fullscreen TUI's Esc / Ctrl+C / force / quit.
+ ui_cancel,
+};
+
+var source: std.atomic.Value(u8) = .init(0);
+
+/// Raise the flag and remember who did.
+pub fn cancel(s: Source) void {
+ source.store(@intFromEnum(s), .release);
+ Agent.esc_cancel.store(true, .release);
+}
+
+/// A cancel that came off raw stdin: a double Enter with a queued steer
+/// line is the force path, anything else is a real Esc.
+pub fn cancelFromStdin() void {
+ cancel(if (main_mod.g_force_interrupt) .force_steer else .esc_key);
+}
+
+/// Fresh turn: the flag and the source clear together.
+pub fn clear() void {
+ Agent.esc_cancel.store(false, .release);
+ source.store(0, .release);
+}
+
+/// The source of the cancel that just ended a turn; consumed, and traced
+/// (`interrupted source=…`) so the next false interrupt can be attributed.
+pub fn take(tracer: ?*Tracer) Source {
+ const s: Source = @enumFromInt(source.swap(0, .acq_rel));
+ if (tracer) |tr| {
+ var buf: [48]u8 = undefined;
+ tr.note("turn", note(&buf, s));
+ }
+ return s;
+}
+
+pub fn byUser(s: Source) bool {
+ return s != .none;
+}
+
+/// The transcript marker appended as the (incomplete) assistant turn.
+pub fn marker(s: Source) []const u8 {
+ return if (byUser(s)) "[response interrupted by user]" else "[response ended early: cancelled by the harness, not the user]";
+}
+
+/// The yellow chrome line the line REPL prints.
+pub fn chrome(s: Source) []const u8 {
+ return switch (s) {
+ .esc_key => "✗ interrupted (esc)",
+ .force_steer => "✗ interrupted (force)",
+ .json_cancel, .acp_cancel, .ui_cancel => "✗ interrupted (cancel)",
+ .none => "✗ ended early (harness cancel — no user action recorded)",
+ };
+}
+
+/// The --json error message.
+pub fn jsonMessage(s: Source) []const u8 {
+ return if (byUser(s)) "turn cancelled" else "turn cancelled by the harness (no user cancel recorded)";
+}
+
+/// The trace note: `interrupted source=esc_key`.
+pub fn note(buf: []u8, s: Source) []const u8 {
+ return std.fmt.bufPrint(buf, "interrupted source={t}", .{s}) catch "interrupted";
+}
+
+test "cancel raises the flag with its source; take consumes; clear drops both" {
+ clear();
+ try std.testing.expectEqual(Source.none, take(null));
+ cancel(.json_cancel);
+ try std.testing.expect(Agent.esc_cancel.load(.acquire));
+ try std.testing.expectEqual(Source.json_cancel, take(null));
+ try std.testing.expectEqual(Source.none, take(null)); // consumed
+ cancel(.acp_cancel);
+ clear();
+ try std.testing.expect(!Agent.esc_cancel.load(.acquire));
+ try std.testing.expectEqual(Source.none, take(null));
+}
+
+test "cancelFromStdin is force after a double Enter, else Esc" {
+ const saved = main_mod.g_force_interrupt;
+ defer main_mod.g_force_interrupt = saved;
+ main_mod.g_force_interrupt = true;
+ cancelFromStdin();
+ try std.testing.expectEqual(Source.force_steer, take(null));
+ main_mod.g_force_interrupt = false;
+ cancelFromStdin();
+ try std.testing.expectEqual(Source.esc_key, take(null));
+ clear();
+}
+
+test "#728: an unsourced cancel is labelled a harness cancel, never a user one" {
+ try std.testing.expectEqualStrings("[response interrupted by user]", marker(.esc_key));
+ try std.testing.expectEqualStrings("[response interrupted by user]", marker(.ui_cancel));
+ try std.testing.expectEqualStrings("[response ended early: cancelled by the harness, not the user]", marker(.none));
+ try std.testing.expect(std.mem.indexOf(u8, chrome(.none), "harness") != null);
+ try std.testing.expect(std.mem.indexOf(u8, chrome(.force_steer), "force") != null);
+ try std.testing.expect(std.mem.indexOf(u8, jsonMessage(.none), "harness") != null);
+ try std.testing.expectEqualStrings("turn cancelled", jsonMessage(.json_cancel));
+ var buf: [48]u8 = undefined;
+ try std.testing.expectEqualStrings("interrupted source=none", note(&buf, .none));
+ try std.testing.expectEqualStrings("interrupted source=acp_cancel", note(&buf, .acp_cancel));
+}
diff --git a/src/http.zig b/src/http.zig
index 2817e66c..86020f44 100644
--- a/src/http.zig
+++ b/src/http.zig
@@ -14,6 +14,7 @@ const provider_mod = @import("provider.zig");
const agent_mod = @import("agent.zig");
const Provider = provider_mod.Provider;
const Agent = agent_mod.Agent;
+const cancel_source = @import("cancel_source.zig"); // #728
const headers = @import("http_headers.zig");
const stall = @import("http_stall.zig"); // #56: the watchdogs' pure budget arithmetic
const http_client = @import("http_client.zig");
@@ -306,7 +307,7 @@ pub fn streamStallWatch(io: Io, poll_stdin: bool, tokens_flowing: bool) Watchdog
io.sleep(.fromMilliseconds(50), .awake) catch return .deadline; // canceled: a line arrived
waited += 50;
if (poll_stdin and Agent.drainSteerStdin(true)) {
- Agent.esc_cancel.store(true, .release);
+ cancel_source.cancelFromStdin();
return .esc;
}
if (Agent.esc_cancel.load(.acquire)) return .esc;
@@ -322,7 +323,7 @@ pub fn deadlineStallTask(io: Io, poll_stdin: bool, budget_ms: u64) WatchdogFired
io.sleep(.fromMilliseconds(50), .awake) catch return .deadline;
waited += 50;
if (poll_stdin and Agent.drainSteerStdin(true)) {
- Agent.esc_cancel.store(true, .release);
+ cancel_source.cancelFromStdin();
return .esc;
}
if (Agent.esc_cancel.load(.acquire)) return .esc;
diff --git a/src/json_inbox.zig b/src/json_inbox.zig
index f175b455..90f40a3f 100644
--- a/src/json_inbox.zig
+++ b/src/json_inbox.zig
@@ -6,6 +6,7 @@ const Io = std.Io;
const Allocator = std.mem.Allocator;
const Value = std.json.Value;
const Agent = @import("agent.zig").Agent;
+const cancel_source = @import("cancel_source.zig"); // #728
const cancelled_answer = "{\"type\":\"answer\",\"cancelled\":true}";
@@ -127,7 +128,7 @@ fn readerTask() void {
var queued_turn = false;
for (lines.items) |queued| queued_turn = queued_turn or isTurn(gpa, queued);
if (active) {
- Agent.esc_cancel.store(true, .release);
+ cancel_source.cancel(.json_cancel);
cancel_epoch +%= 1;
} else if (pending) {
pending_cancelled = true;
diff --git a/src/mainloop.zig b/src/mainloop.zig
index 01d54d80..b30089b4 100644
--- a/src/mainloop.zig
+++ b/src/mainloop.zig
@@ -7,6 +7,7 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const util = @import("util.zig");
+const cancel_source = @import("cancel_source.zig"); // #728: who cancelled, for the marker
const agent_mod = @import("agent.zig");
const provider_mod = @import("provider.zig");
const ansi = @import("ansi.zig");
@@ -427,19 +428,19 @@ pub fn run(ctx: *Ctx) !void {
}
const final_text = turn_result catch |err| switch (err) {
error.Interrupted => {
- // Preserve streamed text and mark the saved assistant turn incomplete.
+ // Preserve streamed text and mark the saved assistant turn incomplete. #728: an unsourced cancel is the harness's, not the user's.
+ const src = cancel_source.take(ctx.root.tracer);
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 interrupted by user]", .{partial})
+ try std.fmt.allocPrint(ctx.arena, "{s}\n\n{s}", .{ partial, cancel_source.marker(src) })
else
- "[response interrupted by user]";
+ cancel_source.marker(src);
try ctx.root.messages.append(try messages.textMessage(ctx.arena, "assistant", marker));
- const int_msg: []const u8 = if (main_mod.g_force_interrupt) "✗ interrupted (force)" else "✗ interrupted (esc)";
main_mod.g_force_interrupt = false;
if (main_mod.json_mode) {
- ctx.root.emit(.{ .type = "error", .message = "turn cancelled" });
+ ctx.root.emit(.{ .type = "error", .message = cancel_source.jsonMessage(src) });
} else {
- try ctx.out.print("{s}{s}{s}\n", .{ style.yellow, int_msg, style.reset });
+ try ctx.out.print("{s}{s}{s}\n", .{ style.yellow, cancel_source.chrome(src), style.reset });
try ctx.out.flush();
}
session.saveSession(ctx.root, ctx.arena, ctx.root.session_name) catch {};
diff --git a/src/repl_glue.zig b/src/repl_glue.zig
index 4b6473ad..fd22b9e8 100644
--- a/src/repl_glue.zig
+++ b/src/repl_glue.zig
@@ -364,7 +364,7 @@ pub fn replModelPick(ctx_ptr: ?*anyopaque, gpa: Allocator, provider_id: []const
/// queue. Cross-thread safe (atomic) — the same signal the TTY esc-watch uses.
pub fn replCancelCb(ctx_ptr: ?*anyopaque) void {
_ = ctx_ptr;
- Agent.esc_cancel.store(true, .release);
+ @import("cancel_source.zig").cancel(.ui_cancel); // #728
}
pub const SteerEntry = struct { text: []const u8, force: bool };
diff --git a/src/tui_acp.zig b/src/tui_acp.zig
index ed3d74b4..ca925132 100644
--- a/src/tui_acp.zig
+++ b/src/tui_acp.zig
@@ -269,7 +269,7 @@ fn bindSession(ctx: *anyopaque, sid: []const u8) void {
}
fn syncEsc() void {
- agent_mod.Agent.esc_cancel.store(true, .release);
+ @import("cancel_source.zig").cancel(.ui_cancel); // #728
}
fn liveCancelled() bool {