xonecas.io
64875
Mc

mini-coder / commit 5026529

fix: handle tool aborts and missing git errors

xonecas2026-04-11 5026529f9f8a5ad2d7bbd589eae224336d1d96a6 parent 5dbad98

7 files changed

TODO.md+1−3
@@ -7,9 +7,7 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
77
88 ## Open items
99
10-- [ ] **ESC doesn't interrupt during tool call** This is a spec violation, ESC should interrupt at any time during a turn.
11-- [ ] **If git is not installed the app breaks** we should check before we use git, and ensure robustness.
12-- [ ] **Emit a terminal `aborted` event for tool-phase interrupts** (`agent.ts`, `headless.ts`) — interrupting during tool execution currently returns `stopReason: "aborted"` without emitting the terminal `aborted` event required by the headless NDJSON spec.
10+- None right now.
1311
1412 ## Low priority (deffered until further notice)
1513
src/agent.test.ts+70−2
@@ -1,6 +1,6 @@
11 import type { Database } from "bun:sqlite";
22 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
44 import { tmpdir } from "node:os";
55 import { join } from "node:path";
66 import type {
@@ -975,7 +975,8 @@ describe("agent loop", () => {
975975 { type: "text", text: "Shell error: This operation was aborted" },
976976 ]);
977977
978- expect(events.some((event) => event.type === "aborted")).toBe(false);
978+ const abortedEvent = expectLastEvent(events, "aborted");
979+ expect(abortedEvent.message.stopReason).toBe("aborted");
979980 expect(
980981 events.filter((event) => event.type === "assistant_message"),
981982 ).toHaveLength(1);
@@ -991,6 +992,73 @@ describe("agent loop", () => {
991992 ]);
992993 });
993994
995+ test("interrupt before a non-signal-aware tool runs leaves the file unchanged", async () => {
996+ faux.setResponses([
997+ fauxAssistantMessage(
998+ [
999+ fauxToolCall("edit", {
1000+ path: "note.txt",
1001+ oldText: "before",
1002+ newText: "after",
1003+ }),
1004+ ],
1005+ { stopReason: "toolUse" },
1006+ ),
1007+ ]);
1008+ writeFileSync(join(tmp, "note.txt"), "before", "utf-8");
1009+
1010+ const controller = new AbortController();
1011+ const events: AgentEvent[] = [];
1012+ const toolPath = join(tmp, "note.txt");
1013+
1014+ const session = createSession(db, { cwd: tmp });
1015+ const userMsg = makeUser("abort before edit");
1016+ const turn = appendMessage(db, session.id, userMsg);
1017+
1018+ const result = await runAgentLoop({
1019+ db,
1020+ sessionId: session.id,
1021+ turn,
1022+ model: faux.getModel(),
1023+ systemPrompt: "Test",
1024+ tools: builtinToolDefs(),
1025+ toolHandlers: builtinToolHandlers(),
1026+ messages: [userMsg],
1027+ cwd: tmp,
1028+ signal: controller.signal,
1029+ onEvent: (event) => {
1030+ events.push(event);
1031+ if (event.type === "tool_start") {
1032+ controller.abort();
1033+ }
1034+ },
1035+ });
1036+
1037+ expect(result.stopReason).toBe("aborted");
1038+ expect(readFileSync(toolPath, "utf-8")).toBe("before");
1039+
1040+ const toolResult = result.messages[2];
1041+ expect(toolResult?.role).toBe("toolResult");
1042+ if (!toolResult || toolResult.role !== "toolResult") {
1043+ throw new Error("Expected tool result message");
1044+ }
1045+ expect(toolResult.isError).toBe(true);
1046+ expect(toolResult.content).toEqual([
1047+ { type: "text", text: "Tool edit failed: This operation was aborted" },
1048+ ]);
1049+
1050+ const startIndex = events.findIndex((event) => event.type === "tool_start");
1051+ const endIndex = events.findIndex((event) => event.type === "tool_end");
1052+ const resultIndex = events.findIndex(
1053+ (event) => event.type === "tool_result",
1054+ );
1055+ const abortedIndex = events.findIndex((event) => event.type === "aborted");
1056+ expect(startIndex).toBeGreaterThan(-1);
1057+ expect(startIndex).toBeLessThan(endIndex);
1058+ expect(endIndex).toBeLessThan(resultIndex);
1059+ expect(resultIndex).toBeLessThan(abortedIndex);
1060+ });
1061+
9941062 test("uses an explicit stream end result when no terminal event was emitted", async () => {
9951063 const api = "agent-stream-end-result-test";
9961064 const sourceId = "agent-stream-end-result-test-source";
src/agent.ts+38−15
@@ -525,19 +525,26 @@ async function executeToolCall(
525525
526526 let result: ToolExecResult;
527527 try {
528- result = await handler(
529- toolCall.arguments,
530- opts.cwd,
531- opts.signal,
532- (partial) => {
533- opts.onEvent?.({
534- type: "tool_delta",
535- toolCallId: toolCall.id,
536- name: toolCall.name,
537- result: partial,
538- });
539- },
540- );
528+ if (opts.signal?.aborted) {
529+ result = toolErrorResult(
530+ toolCall.name,
531+ new Error("This operation was aborted"),
532+ );
533+ } else {
534+ result = await handler(
535+ toolCall.arguments,
536+ opts.cwd,
537+ opts.signal,
538+ (partial) => {
539+ opts.onEvent?.({
540+ type: "tool_delta",
541+ toolCallId: toolCall.id,
542+ name: toolCall.name,
543+ result: partial,
544+ });
545+ },
546+ );
547+ }
541548 } catch (error) {
542549 result = toolErrorResult(toolCall.name, error);
543550 }
@@ -592,8 +599,17 @@ function appendToolResultMessage(
592599 export async function runAgentLoop(
593600 opts: RunAgentOpts,
594601 ): Promise<AgentLoopResult> {
595- const { db, sessionId, turn, messages, signal, onEvent, toolHandlers, cwd } =
596- opts;
602+ const {
603+ db,
604+ sessionId,
605+ turn,
606+ model,
607+ messages,
608+ signal,
609+ onEvent,
610+ toolHandlers,
611+ cwd,
612+ } = opts;
597613
598614 while (true) {
599615 const assistantMessage = await streamAssistantMessage(opts);
@@ -633,6 +649,13 @@ export async function runAgentLoop(
633649 );
634650
635651 if (signal?.aborted) {
652+ onEvent?.({
653+ type: "aborted",
654+ message: buildIncompleteAssistantMessage(
655+ { model, signal },
656+ assistantMessage,
657+ ),
658+ });
636659 return { messages, stopReason: "aborted" };
637660 }
638661 }
src/git.test.ts+36−0
@@ -68,6 +68,42 @@ describe("getGitState", () => {
6868 expect(state).toBeNull();
6969 });
7070
71+ test("returns null when git is not installed", async () => {
72+ const missingGit = Object.assign(
73+ new Error('Executable not found in $PATH: "git"'),
74+ {
75+ code: "ENOENT",
76+ path: "git",
77+ },
78+ );
79+
80+ const state = await getGitState("/tmp/no-git", {
81+ run: async () => {
82+ throw missingGit;
83+ },
84+ });
85+
86+ expect(state).toBeNull();
87+ });
88+
89+ test("rethrows ENOENT errors that are not missing-git failures", async () => {
90+ const invalidCwd = Object.assign(
91+ new Error("ENOENT: no such file or directory, posix_spawn 'git'"),
92+ {
93+ code: "ENOENT",
94+ path: "git",
95+ },
96+ );
97+
98+ await expect(
99+ getGitState("/tmp/missing-cwd", {
100+ run: async () => {
101+ throw invalidCwd;
102+ },
103+ }),
104+ ).rejects.toThrow(invalidCwd.message);
105+ });
106+
71107 test("builds git state by parsing command output", async () => {
72108 const calls: Array<{ args: string[]; cwd: string; trim: boolean }> = [];
73109 const responses = new Map<string, string | null>([
src/git.ts+57−7
@@ -61,6 +61,51 @@ async function run(
6161 return trim ? out.trim() : out;
6262 }
6363
64+function getErrorStringProperty(
65+ error: unknown,
66+ key: string,
67+): string | undefined {
68+ if (typeof error !== "object" || error === null) {
69+ return undefined;
70+ }
71+
72+ const value = Reflect.get(error, key);
73+ return typeof value === "string" ? value : undefined;
74+}
75+
76+function isMissingGitError(error: unknown): boolean {
77+ const code = getErrorStringProperty(error, "code");
78+ if (code !== "ENOENT") {
79+ return false;
80+ }
81+
82+ const message = getErrorStringProperty(error, "message");
83+ return (
84+ typeof message === "string" &&
85+ message.includes('Executable not found in $PATH: "git"')
86+ );
87+}
88+
89+async function safeRun(
90+ runGit: (
91+ args: string[],
92+ cwd: string,
93+ trim?: boolean,
94+ ) => Promise<string | null>,
95+ args: string[],
96+ cwd: string,
97+ trim = true,
98+): Promise<string | null> {
99+ try {
100+ return await runGit(args, cwd, trim);
101+ } catch (error) {
102+ if (isMissingGitError(error)) {
103+ return null;
104+ }
105+ throw error;
106+ }
107+}
108+
64109 function isUntrackedStatus(
65110 indexStatus: string,
66111 workingTreeStatus: string,
@@ -145,8 +190,8 @@ export function parseGitAheadBehind(output: string): {
145190 * Gather the current git state for a directory.
146191 *
147192 * Runs several fast git commands in parallel to collect branch, working
148- * tree status, and ahead/behind counts. Returns `null` if the directory
149- * is not inside a git repository.
193+ * tree status, and ahead/behind counts. Returns `null` if git is not
194+ * installed or the directory is not inside a git repository.
150195 *
151196 * @param cwd - The directory to query (can be a subdirectory of the repo).
152197 * @param opts - Optional runtime overrides used by tests.
@@ -165,18 +210,23 @@ export async function getGitState(
165210 const exec = opts?.run ?? run;
166211
167212 // Check if we're in a repo and get the root
168- const root = await exec(["rev-parse", "--show-toplevel"], cwd);
213+ const root = await safeRun(exec, ["rev-parse", "--show-toplevel"], cwd);
169214 if (root === null) return null;
170215
171216 // Run remaining commands in parallel
172217 const [branch, upstream, status, revList] = await Promise.all([
173- exec(["branch", "--show-current"], cwd),
174- exec(
218+ safeRun(exec, ["branch", "--show-current"], cwd),
219+ safeRun(
220+ exec,
175221 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
176222 cwd,
177223 ),
178- exec(["status", "--porcelain"], cwd, false),
179- exec(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], cwd),
224+ safeRun(exec, ["status", "--porcelain"], cwd, false),
225+ safeRun(
226+ exec,
227+ ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"],
228+ cwd,
229+ ),
180230 ]);
181231
182232 const { staged, modified, untracked } = parseGitStatus(status ?? "");
src/headless.test.ts+34−0
@@ -155,6 +155,40 @@ describe("headless", () => {
155155 ).toEqual(["user", "assistant", "toolResult", "assistant"]);
156156 });
157157
158+ test("runHeadlessPrompt emits a terminal aborted event when interrupted during tool execution", async () => {
159+ faux.setResponses([
160+ fauxAssistantMessage([fauxToolCall("shell", { command: "sleep 5" })], {
161+ stopReason: "toolUse",
162+ }),
163+ ]);
164+ const state = createTestState();
165+ const lines: string[] = [];
166+
167+ const stopReason = await runHeadlessPrompt(state, "interrupt the shell", {
168+ writeLine: (line) => {
169+ lines.push(line);
170+ const event = JSON.parse(line) as { type?: string };
171+ if (event.type === "tool_start") {
172+ state.abortController?.abort();
173+ }
174+ },
175+ });
176+
177+ const events = parseEventLines(lines);
178+ expect(stopReason).toBe("aborted");
179+ expect(events.some((event) => event.type === "tool_result")).toBe(true);
180+ expect(events.at(-1)?.type).toBe("aborted");
181+
182+ const abortedEvent = events.at(-1);
183+ const message = abortedEvent?.message;
184+ if (typeof message !== "object" || !message || !("stopReason" in message)) {
185+ throw new Error(
186+ "Expected the terminal aborted event to include a message",
187+ );
188+ }
189+ expect(message.stopReason).toBe("aborted");
190+ });
191+
158192 test("runHeadlessPrompt treats broken stdout pipes as a quiet shutdown", async () => {
159193 faux.setResponses([fauxAssistantMessage("Done.")]);
160194 const state = createTestState();
src/ui.test.ts+47−0
@@ -1655,6 +1655,53 @@ describe("ui rendering", () => {
16551655 }
16561656 });
16571657
1658+ test("Escape aborts a running shell tool once the input is blurred", async () => {
1659+ const state = createTestState();
1660+ const faux = registerFauxProvider();
1661+ const cwd = createTempDir();
1662+ state.model = faux.getModel();
1663+ state.cwd = cwd;
1664+ state.canonicalCwd = cwd;
1665+ faux.setResponses([
1666+ fauxAssistantMessage([fauxToolCall("shell", { command: "sleep 5" })], {
1667+ stopReason: "toolUse",
1668+ }),
1669+ ]);
1670+
1671+ try {
1672+ const controller = createInputController(state);
1673+ handleInput("interrupt the tool", state);
1674+
1675+ await waitFor(
1676+ () =>
1677+ state.running &&
1678+ state.activeTurnPromise !== null &&
1679+ state.messages.some((message) => message.role === "assistant"),
1680+ );
1681+
1682+ controller.onBlur();
1683+ const base = expectVStack(renderBaseLayout(state, 80, controller));
1684+ base.props.onKeyPress?.("escape");
1685+
1686+ const activeTurnPromise = state.activeTurnPromise;
1687+ if (!activeTurnPromise) {
1688+ throw new Error("Expected an active turn promise");
1689+ }
1690+ await activeTurnPromise;
1691+
1692+ expect(state.running).toBe(false);
1693+ expect(state.messages.map((message) => message.role)).toEqual([
1694+ "user",
1695+ "assistant",
1696+ "toolResult",
1697+ ]);
1698+ } finally {
1699+ await stopRunningTurn(state);
1700+ faux.unregister();
1701+ state.db.close();
1702+ }
1703+ });
1704+
16581705 test("Tab autocompletes the last file path in normal input mode", () => {
16591706 const state = createTestState();
16601707 const cwd = createTempDir();