Skip to content

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

Python

fix(tools): surface user cancellation as a terminal state (#266)

Rach Pradhaneec07b1aaba2
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 14359203..52a6b727 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -112,6 +112,9 @@ jobs:
- name: PTY Markdown rendering test
run: python3 scripts/test-pty-markdown.py zig-out/bin/graff
+ - name: Parallel bash Esc cancellation test (#266)
+ run: python3 scripts/test-pty-parallel-cancel.py zig-out/bin/graff
+
- name: PTY model preference and fallback test
run: python3 scripts/test-model-preference.py zig-out/bin/graff
diff --git a/scripts/test-pty-parallel-cancel.py b/scripts/test-pty-parallel-cancel.py
new file mode 100755
index 00000000..6383d537
--- /dev/null
+++ b/scripts/test-pty-parallel-cancel.py
@@ -0,0 +1,165 @@
+#!/usr/bin/env python3
+"""Real-PTY regression for parallel bash interruption and process-group cleanup."""
+
+import http.server
+import json
+import os
+import shlex
+import socket
+import sys
+import tempfile
+import threading
+import time
+
+from pty_harness import PtySession
+
+
+_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"
+GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg
+
+
+class ToolMock:
+ def __init__(self, commands: list[str]) -> None:
+ self.commands = commands
+ self.hits = 0
+ parent = self
+
+ class Handler(http.server.BaseHTTPRequestHandler):
+ def do_POST(self) -> None: # noqa: N802
+ length = int(self.headers.get("content-length", 0))
+ if length:
+ self.rfile.read(length)
+ parent.hits += 1
+ if parent.hits == 1:
+ tool_calls = []
+ for i, command in enumerate(parent.commands):
+ tool_calls.append({
+ "index": i,
+ "id": f"cancel-{i}",
+ "type": "function",
+ "function": {
+ "name": "bash",
+ "arguments": json.dumps({"command": command}),
+ },
+ })
+ chunk = {
+ "choices": [{
+ "delta": {"role": "assistant", "tool_calls": tool_calls},
+ "finish_reason": "tool_calls",
+ }]
+ }
+ else:
+ chunk = {
+ "choices": [{
+ "delta": {"role": "assistant", "content": "done"},
+ "finish_reason": "stop",
+ }]
+ }
+ body = ("data: " + json.dumps(chunk) + "\n\ndata: [DONE]\n\n").encode()
+ self.send_response(200)
+ self.send_header("content-type", "text/event-stream")
+ self.send_header("content-length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self) -> None: # noqa: N802
+ self.send_response(404)
+ self.end_headers()
+
+ def log_message(self, *_args) -> None:
+ pass
+
+ self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 1234), Handler)
+
+ def start(self) -> None:
+ threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
+
+ def stop(self) -> None:
+ self.httpd.shutdown()
+ self.httpd.server_close()
+
+
+def wait_for_pid_files(session: PtySession, paths: list[str]) -> None:
+ deadline = time.monotonic() + 3
+ while time.monotonic() < deadline:
+ session.pump(0.05)
+ if all(os.path.exists(path) and os.path.getsize(path) > 0 for path in paths):
+ return
+ raise AssertionError(f"parallel commands did not start: {paths}")
+
+
+def assert_processes_gone(paths: list[str]) -> None:
+ pids = [int(open(path, encoding="utf-8").read().strip()) for path in paths]
+ deadline = time.monotonic() + 2
+ alive = pids
+ while alive and time.monotonic() < deadline:
+ next_alive = []
+ for pid in alive:
+ try:
+ os.kill(pid, 0)
+ next_alive.append(pid)
+ except ProcessLookupError:
+ pass
+ alive = next_alive
+ if alive:
+ time.sleep(0.05)
+ if alive:
+ for pid in alive:
+ try:
+ os.kill(pid, 9)
+ except ProcessLookupError:
+ pass
+ raise AssertionError(f"cancelled command descendants survived: {alive}")
+
+
+def main() -> None:
+ probe = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ try:
+ probe.bind(("127.0.0.1", 1234))
+ except OSError:
+ print("skip 127.0.0.1:1234 is in use — parallel-cancel PTY test skipped")
+ return
+ finally:
+ probe.close()
+
+ with tempfile.TemporaryDirectory(prefix="graff-parallel-cancel-") as tmp:
+ harness = os.path.join(tmp, ".harness")
+ os.makedirs(harness, exist_ok=True)
+ with open(os.path.join(harness, "settings.json"), "w", encoding="utf-8") as fh:
+ json.dump({"ai_title": False}, fh)
+ pid_paths = [os.path.join(tmp, f"child-{i}.pid") for i in range(2)]
+ commands = [f"sleep 30 & echo $! > {shlex.quote(path)}; wait" for path in pid_paths]
+ mock = ToolMock(commands)
+ mock.start()
+ try:
+ env = {
+ "HOME": tmp,
+ "LMSTUDIO_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ with PtySession(GRAFF, ["--model", "lmstudio", "--no-telemetry"], cwd=tmp, env=env, timeout=20) as session:
+ session.wait_for_literal("] ›")
+ session.send_line("/yolo")
+ session.wait_for_literal("yolo mode ON")
+ cursor = len(session.raw)
+ session.send_line("run both checks")
+ session.wait_for_literal("running 2 tools in parallel", start=cursor)
+ wait_for_pid_files(session, pid_paths)
+ session.send_key("esc")
+ session.wait_for_literal("[cancelled by user; local process group killed]", start=cursor)
+ session.wait_for_literal("parallel tools finished: 0 completed, 0 failed, 2 cancelled", start=cursor)
+ session.wait_for_literal("interrupted (esc)", start=cursor)
+ assert_processes_gone(pid_paths)
+ session.send_key("ctrl-d")
+ result = session.read_until_exit(5)
+ if result.timed_out or result.exit_code != 0:
+ raise AssertionError(f"REPL exit={result.exit_code} timed_out={result.timed_out}")
+ finally:
+ mock.stop()
+ print("ok parallel Esc reports terminal states and kills command descendants")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 40131ac1..82ca4197 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -182,12 +182,24 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
// Keep the model-facing history compact. The exact output remains
// inspectable on disk and the short preview carries its pointer.
const detail = persistToolResult(self, output.text);
- results[i] = .{ .text = try toolPreviewText(self.arena, output.text, detail), .is_error = output.is_error, .ms = output.ms };
+ results[i] = .{ .text = try toolPreviewText(self.arena, output.text, detail), .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
if (self.eval_cmd != null and toolInvalidatesEval(calls[i])) {
self.eval_verified = false;
self.eval_repair_pending = false;
}
}
+ // #266: a cancelled parallel batch used to just look "running" and then
+ // failed — one terminal line says what completed, failed, and cancelled.
+ if (ext_idx.items.len > 1 and !self.sub) {
+ var done: usize = 0;
+ var failed: usize = 0;
+ var cancelled: usize = 0;
+ for (ext_idx.items) |i| {
+ const r = results[i];
+ if (r.cancelled) cancelled += 1 else if (r.is_error) failed += 1 else done += 1;
+ }
+ try self.say(" {s}↯ parallel tools finished: {d} completed, {d} failed, {d} cancelled{s}\n", .{ style.dim, done, failed, cancelled, style.reset });
+ }
}
// Show a compact ✓/✗ + preview for each non-meta call (no-op for subs).
for (calls, results) |call, r| self.sayToolResult(call.name, r);
@@ -453,8 +465,8 @@ pub fn sayToolResult(self: *Agent, name: []const u8, r: ExecResult) void {
preview = std.mem.trim(u8, preview, " \t\r");
const shown = if (preview.len > 100) preview[0..100] else preview;
const truncated = shown.len < all.len; // more content (extra lines or >100 chars)
- const mark = if (r.is_error) "✗" else "✓";
- const mc = if (r.is_error) style.red else style.green;
+ const mark = if (r.cancelled) "⊘" else if (r.is_error) "✗" else "✓";
+ const mc = if (r.cancelled) style.yellow else if (r.is_error) style.red else style.green;
var tbuf: [24]u8 = undefined;
const timing = if (main_mod.show_timing and r.ms > 0)
(std.fmt.bufPrint(&tbuf, " ({d}ms)", .{r.ms}) catch "")
diff --git a/src/exec.zig b/src/exec.zig
index 17201fa4..38496014 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -75,6 +75,22 @@ const no_local_tools = @import("no_local_tools.zig"); // #330: the hard --no-loc
/// no-deadline behavior (a human is watching and may want a long build).
const subagent_bash_deadline_ms: u64 = 120 * 1000;
+/// #266: killing a local `ssh` proves nothing about the remote command it was
+/// running — a cancelled or timed-out ssh result carries a caveat saying so.
+fn isSshCommand(cmd: []const u8) bool {
+ var it = std.mem.tokenizeAny(u8, cmd, " \t\r\n");
+ const first = it.next() orelse return false;
+ return std.mem.eql(u8, std.fs.path.basename(first), "ssh");
+}
+
+test "isSshCommand: bare and pathed ssh, not scp or substrings" {
+ try std.testing.expect(isSshCommand("ssh host uptime"));
+ try std.testing.expect(isSshCommand(" /usr/bin/ssh -T host"));
+ try std.testing.expect(!isSshCommand("scp file host:"));
+ try std.testing.expect(!isSshCommand("echo ssh"));
+ try std.testing.expect(!isSshCommand(""));
+}
+
/// Wall-clock ceiling for one `codedb` query (#198). Every allowed subcommand
/// is a read that normally answers in seconds; a query that has not returned
/// in a minute is stuck, and before this it stayed stuck forever — the tool
@@ -231,7 +247,12 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
try std.fmt.allocPrint(gpa, "could not start background job ({t}) — run it in the foreground instead", .{err}),
.is_error = true,
};
- return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. Poll new output with bash_output (id {d}, optional wait_ms), stop it with bash_kill.", .{ job.id, job.cmd, job.id }) };
+ return .{ .text = try std.fmt.allocPrint(gpa, "[job {d} started: {s}]\nIt keeps running across turns. Poll new output with bash_output (id {d}, optional wait_ms), stop it with bash_kill.{s}", .{
+ job.id,
+ job.cmd,
+ job.id,
+ if (isSshCommand(cmd)) " Killing the local SSH job cannot prove a detached remote process stopped; verify the remote host." else "",
+ }) };
}
const sh = shellArgv(cmd);
const deadline: u64 = if (ctx.from_sub) subagent_bash_deadline_ms else 0;
@@ -256,13 +277,18 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
if (run.stdout_truncated) try w.print("\n[stdout truncated at {d} KB]", .{bash_stdout_cap / 1024});
if (run.stderr.len > 0) try w.print("\n[stderr]\n{s}", .{run.stderr});
if (run.stderr_truncated) try w.print("\n[stderr truncated at {d} KB]", .{bash_stderr_cap / 1024});
- if (run.timed_out) {
+ if (run.cancelled) {
+ try w.writeAll("\n[cancelled by user; local process group killed]");
+ } else if (run.timed_out) {
try w.print("\n[timed out after {d}s and was killed — too long for a subagent. Don't retry as-is: scope it to specific paths or globs instead of scanning the whole directory, or report back what you need run.]", .{subagent_bash_deadline_ms / 1000});
} else if (exit_code) |code| {
if (code != 0) try w.print("\n[exit code {d}]", .{code});
} else try w.writeAll("\n[terminated abnormally]");
+ if ((run.cancelled or run.timed_out) and isSshCommand(cmd)) {
+ try w.writeAll("\n[ssh note: the local SSH client was killed, but a detached or disconnect-resistant remote process may survive; verify it on the remote host]");
+ }
if (run.stdout.len == 0 and run.stderr.len == 0 and exit_code == 0) try w.writeAll("(no output)");
- return .{ .text = try aw.toOwnedSlice(), .is_error = exit_code == null or exit_code.? != 0 };
+ return .{ .text = try aw.toOwnedSlice(), .is_error = exit_code == null or exit_code.? != 0, .cancelled = run.cancelled };
}
if (std.mem.eql(u8, call.name, "bash_output")) {
const id = intField(input, "id") orelse return missingArg(gpa, "id");
diff --git a/src/process_runner.zig b/src/process_runner.zig
index 16509611..f170d10e 100644
--- a/src/process_runner.zig
+++ b/src/process_runner.zig
@@ -82,6 +82,7 @@ pub const CappedRun = struct {
stdout_truncated: bool,
stderr_truncated: bool,
timed_out: bool,
+ cancelled: bool = false, // user Esc ended it (the process tree was killed)
};
/// Supplying an explicit environment replaces (rather than augments) the
@@ -248,6 +249,7 @@ pub fn runCappedWithOptions(gpa: Allocator, io: Io, argv: []const []const u8, st
.stdout_truncated = saved[0] != null,
.stderr_truncated = saved[1] != null,
.timed_out = timed_out,
+ .cancelled = esc_killed,
};
}
diff --git a/src/schema.zig b/src/schema.zig
index c856bfbf..71de1a47 100644
--- a/src/schema.zig
+++ b/src/schema.zig
@@ -45,7 +45,7 @@ const empty_schema =
const base_specs = [_]ToolSpec{
.{
.name = "bash",
- .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. For long-running commands (dev servers, watchers) set run_in_background true: it returns a job id immediately; poll output with bash_output and stop it with bash_kill.",
+ .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). For long-running commands (dev servers, watchers) set run_in_background true: it returns a job id immediately; poll output with bash_output and stop it with bash_kill.",
.schema =
\\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
,
diff --git a/src/tools.zig b/src/tools.zig
index 031faf17..d09ab2f1 100644
--- a/src/tools.zig
+++ b/src/tools.zig
@@ -30,6 +30,7 @@ pub const ToolCall = struct {
pub const ExecResult = struct {
text: []const u8,
is_error: bool,
+ cancelled: bool = false, // ended by user Esc, not by failing (#266)
ms: i64 = 0, // wall-clock of the tool exec (external tools only; --timing)
};
@@ -76,6 +77,7 @@ pub const json_args = @import("json_args.zig");
pub const ToolOutput = struct {
text: []u8 = &.{}, // gpa-owned
is_error: bool = false,
+ cancelled: bool = false, // ended by user Esc, not by failing (#266)
ms: i64 = 0, // set by execTool
};