xonecas.io
64875
Mc

mini-coder / commit 01a331b

fix: harden robustness around aborts, tool errors, and UI failures

xonecas2026-04-08 01a331b0070f817c922e84a3303323a998b978ac parent aa63af3

10 files changed

TODO.md+0−9
@@ -7,15 +7,6 @@ The spec.md and code are the sources of truth, not this file, don't assume anyth
77
88 ## Spec alignment
99
10-### Robustness
11-
12-- [ ] **Catch tool handler exceptions in the agent loop** (`agent.ts`) — if a built-in tool or future extension throws, the loop should convert that into an error tool result, still emit `tool_end`, append a `ToolResultMessage`, and continue or fail cleanly instead of crashing the loop.
13-- [ ] **Stop cleanly when interrupting during tool execution** (`agent.ts`) — aborting a running tool currently appends an error tool result and re-enters the model loop before the turn finally ends; `Escape` should end the turn immediately.
14-- [ ] **Fix the `/undo` abort race** (`ui.ts`) — aborting an active run and undoing immediately can still race with the agent loop writing the aborted assistant message. Track the active loop promise and wait for it to settle before removing the last conversational turn.
15-- [ ] **Surface submit/runtime errors in the TUI** (`ui.ts`) — failures from `submitMessage()` should append a persisted UI message to the conversation log instead of only going to `console.error`.
16-- [ ] **Harden `readImage` error handling** (`tools.ts`) — catch filesystem read errors after the existence check and return a tool error result instead of throwing.
17-- [ ] **Preserve existing line endings across edits** (`tools.ts`) — multi-line replacements currently use `newText` verbatim, which can create mixed LF/CRLF files despite the spec saying existing line endings are preserved.
18-
1910 ### Prompt and session context
2011
2112 - [ ] **Reload AGENTS.md, skills, and plugins on `/new`** (`index.ts`, `ui/commands.ts`) — they are only loaded at startup right now, but the spec says prompt context can change on `/new` or CWD change.
src/agent.test.ts+160−0
@@ -741,6 +741,85 @@ describe("agent loop", () => {
741741 expect(dbLast.stopReason).toBe("aborted");
742742 });
743743
744+ test("interrupt during tool execution ends the turn without re-entering the model loop", async () => {
745+ faux.setResponses([
746+ fauxAssistantMessage([fauxToolCall("shell", { command: "sleep 10" })], {
747+ stopReason: "toolUse",
748+ }),
749+ ]);
750+
751+ const controller = new AbortController();
752+ const events: AgentEvent[] = [];
753+ const toolHandlers = new Map<string, ToolHandler>([
754+ [
755+ "shell",
756+ async () => {
757+ controller.abort();
758+ return {
759+ content: [
760+ {
761+ type: "text",
762+ text: "Shell error: This operation was aborted",
763+ },
764+ ],
765+ isError: true,
766+ };
767+ },
768+ ],
769+ ]);
770+
771+ const session = createSession(db, { cwd: tmp });
772+ const userMsg = makeUser("run and interrupt");
773+ const turn = appendMessage(db, session.id, userMsg);
774+
775+ const result = await runAgentLoop({
776+ db,
777+ sessionId: session.id,
778+ turn,
779+ model: faux.getModel(),
780+ systemPrompt: "Test",
781+ tools: builtinToolDefs(),
782+ toolHandlers,
783+ messages: [userMsg],
784+ cwd: tmp,
785+ signal: controller.signal,
786+ onEvent: (event) => events.push(event),
787+ });
788+
789+ expect(result.stopReason).toBe("aborted");
790+ expect(result.messages).toHaveLength(3);
791+ expect(result.messages.map((message) => message.role)).toEqual([
792+ "user",
793+ "assistant",
794+ "toolResult",
795+ ]);
796+
797+ const toolResult = result.messages[2];
798+ expect(toolResult?.role).toBe("toolResult");
799+ if (!toolResult || toolResult.role !== "toolResult") {
800+ throw new Error("Expected tool result message");
801+ }
802+ expect(toolResult.isError).toBe(true);
803+ expect(toolResult.content).toEqual([
804+ { type: "text", text: "Shell error: This operation was aborted" },
805+ ]);
806+
807+ expect(events.some((event) => event.type === "aborted")).toBe(false);
808+ expect(
809+ events.filter((event) => event.type === "assistant_message"),
810+ ).toHaveLength(1);
811+ expect(events.filter((event) => event.type === "tool_result")).toHaveLength(
812+ 1,
813+ );
814+
815+ const dbMessages = loadMessages(db, session.id);
816+ expect(dbMessages.map((message) => message.role)).toEqual([
817+ "user",
818+ "assistant",
819+ "toolResult",
820+ ]);
821+ });
822+
744823 test("preserves thinking content on assistant messages", async () => {
745824 faux.setResponses([
746825 fauxAssistantMessage([
@@ -837,6 +916,87 @@ describe("agent loop", () => {
837916 }
838917 });
839918
919+ test("converts thrown tool handler errors into error tool results", async () => {
920+ faux.setResponses([
921+ fauxAssistantMessage([fauxToolCall("shell", { command: "explode" })], {
922+ stopReason: "toolUse",
923+ }),
924+ fauxAssistantMessage("Recovered after tool failure."),
925+ ]);
926+
927+ const events: AgentEvent[] = [];
928+ const toolHandlers = new Map<string, ToolHandler>([
929+ [
930+ "shell",
931+ () => {
932+ throw new Error("kaboom");
933+ },
934+ ],
935+ ]);
936+
937+ const session = createSession(db, { cwd: tmp });
938+ const userMsg = makeUser("run the failing tool");
939+ const turn = appendMessage(db, session.id, userMsg);
940+
941+ const result = await runAgentLoop({
942+ db,
943+ sessionId: session.id,
944+ turn,
945+ model: faux.getModel(),
946+ systemPrompt: "Test",
947+ tools: builtinToolDefs(),
948+ toolHandlers,
949+ messages: [userMsg],
950+ cwd: tmp,
951+ onEvent: (event) => events.push(event),
952+ });
953+
954+ expect(result.stopReason).toBe("stop");
955+ expect(result.messages).toHaveLength(4);
956+
957+ const toolResult = result.messages.find(
958+ (message) => message.role === "toolResult",
959+ );
960+ expect(toolResult).toBeDefined();
961+ if (!toolResult || toolResult.role !== "toolResult") {
962+ throw new Error("Expected tool result message");
963+ }
964+ expect(toolResult.isError).toBe(true);
965+ expect(toolResult.content).toEqual([
966+ { type: "text", text: "Tool shell failed: kaboom" },
967+ ]);
968+
969+ const toolStart = events.find((event) => event.type === "tool_start");
970+ const toolEnd = events.find((event) => event.type === "tool_end");
971+ const toolResultEvent = events.find(
972+ (event) => event.type === "tool_result",
973+ );
974+
975+ expect(toolStart).toBeDefined();
976+ expect(toolEnd).toBeDefined();
977+ expect(toolResultEvent).toBeDefined();
978+
979+ if (
980+ !toolStart ||
981+ toolStart.type !== "tool_start" ||
982+ !toolEnd ||
983+ toolEnd.type !== "tool_end" ||
984+ !toolResultEvent ||
985+ toolResultEvent.type !== "tool_result"
986+ ) {
987+ throw new Error("Expected tool start/end/result events");
988+ }
989+
990+ expect(toolEnd.result.isError).toBe(true);
991+ expect(toolEnd.result.content).toEqual([
992+ { type: "text", text: "Tool shell failed: kaboom" },
993+ ]);
994+ expect(events.indexOf(toolStart)).toBeLessThan(events.indexOf(toolEnd));
995+ expect(events.indexOf(toolEnd)).toBeLessThan(
996+ events.indexOf(toolResultEvent),
997+ );
998+ });
999+
8401000 test("stopReason 'length' returns without looping", async () => {
8411001 faux.setResponses([
8421002 fauxAssistantMessage("Partial response that hit the token limit", {
src/agent.ts+24−7
@@ -203,6 +203,15 @@ function mergeAssistantMessage(
203203 };
204204 }
205205
206+function toolErrorResult(name: string, error: unknown): ToolExecResult {
207+ const message = error instanceof Error ? error.message : String(error);
208+
209+ return {
210+ content: [{ type: "text", text: `Tool ${name} failed: ${message}` }],
211+ isError: true,
212+ };
213+}
214+
206215 // ---------------------------------------------------------------------------
207216 // Agent loop
208217 // ---------------------------------------------------------------------------
@@ -344,14 +353,18 @@ export async function runAgentLoop(
344353 args: toolCall.arguments,
345354 });
346355
347- result = await handler(toolCall.arguments, cwd, signal, (partial) => {
348- onEvent?.({
349- type: "tool_delta",
350- toolCallId: toolCall.id,
351- name: toolCall.name,
352- result: partial,
356+ try {
357+ result = await handler(toolCall.arguments, cwd, signal, (partial) => {
358+ onEvent?.({
359+ type: "tool_delta",
360+ toolCallId: toolCall.id,
361+ name: toolCall.name,
362+ result: partial,
363+ });
353364 });
354- });
365+ } catch (error) {
366+ result = toolErrorResult(toolCall.name, error);
367+ }
355368
356369 onEvent?.({
357370 type: "tool_end",
@@ -373,6 +386,10 @@ export async function runAgentLoop(
373386 messages.push(toolResultMessage);
374387 appendMessage(db, sessionId, toolResultMessage, turn);
375388 onEvent?.({ type: "tool_result", message: toolResultMessage });
389+
390+ if (signal?.aborted) {
391+ return { messages, stopReason: "aborted" };
392+ }
376393 }
377394
378395 // Loop back to stream with updated context
src/index.ts+3−0
@@ -330,6 +330,8 @@ export interface AppState {
330330 running: boolean;
331331 /** Abort controller for the current agent run. */
332332 abortController: AbortController | null;
333+ /** Promise for the active conversational turn, used to serialize cleanup like `/undo`. */
334+ activeTurnPromise: Promise<void> | null;
333335 /** Whether to show thinking content. */
334336 showReasoning: boolean;
335337 /** Whether to show full (un-truncated) tool output. */
@@ -415,6 +417,7 @@ export async function init(): Promise<AppState> {
415417 canonicalCwd,
416418 running: false,
417419 abortController: null,
420+ activeTurnPromise: null,
418421 showReasoning: startup.showReasoning,
419422 verbose: startup.verbose,
420423 };
src/tools.test.ts+40−0
@@ -131,6 +131,38 @@ describe("edit", () => {
131131 expect(readFile("crlf.txt")).toBe("line1\r\nreplaced\r\nline3\r\n");
132132 });
133133
134+ test("normalizes multi-line replacements to the file's CRLF line endings", () => {
135+ writeFile("crlf-multiline.txt", "start\r\nold a\r\nold b\r\nend\r\n");
136+ const result = executeEdit(
137+ {
138+ path: "crlf-multiline.txt",
139+ oldText: "old a\r\nold b",
140+ newText: "new a\nnew b",
141+ },
142+ tmp,
143+ );
144+
145+ expect(result.isError).toBe(false);
146+ expect(readFile("crlf-multiline.txt")).toBe(
147+ "start\r\nnew a\r\nnew b\r\nend\r\n",
148+ );
149+ });
150+
151+ test("normalizes multi-line replacements to the file's LF line endings", () => {
152+ writeFile("lf-multiline.txt", "start\nold a\nold b\nend\n");
153+ const result = executeEdit(
154+ {
155+ path: "lf-multiline.txt",
156+ oldText: "old a\nold b",
157+ newText: "new a\r\nnew b",
158+ },
159+ tmp,
160+ );
161+
162+ expect(result.isError).toBe(false);
163+ expect(readFile("lf-multiline.txt")).toBe("start\nnew a\nnew b\nend\n");
164+ });
165+
134166 test("handles UTF-8 content", () => {
135167 writeFile("utf8.txt", "こんにちは世界");
136168 const result = executeEdit(
@@ -445,6 +477,14 @@ describe("readImage", () => {
445477 expect(resultText(result)).toContain("not found");
446478 });
447479
480+ test("returns a tool error when reading the image file fails", () => {
481+ mkdirSync(join(tmp, "broken.png"));
482+ const result = executeReadImage({ path: "broken.png" }, tmp);
483+
484+ expect(result.isError).toBe(true);
485+ expect(resultText(result)).toContain("Failed to read image");
486+ });
487+
448488 test("resolves relative paths against cwd", () => {
449489 mkdirSync(join(tmp, "sub"), { recursive: true });
450490 writeFileSync(join(tmp, "sub", "img.png"), "png in sub");
src/tools.ts+36−7
@@ -37,6 +37,26 @@ function textResult(text: string, isError: boolean): ToolExecResult {
3737 return { content: [{ type: "text", text }], isError };
3838 }
3939
40+function detectLineEnding(content: string): "\n" | "\r\n" | null {
41+ if (content.includes("\r\n")) {
42+ return "\r\n";
43+ }
44+ if (content.includes("\n")) {
45+ return "\n";
46+ }
47+ return null;
48+}
49+
50+function normalizeLineEndings(
51+ content: string,
52+ lineEnding: "\n" | "\r\n",
53+): string {
54+ if (lineEnding === "\r\n") {
55+ return content.replace(/\r?\n/g, "\r\n");
56+ }
57+ return content.replace(/\r\n/g, "\n");
58+}
59+
4060 // ---------------------------------------------------------------------------
4161 // edit
4262 // ---------------------------------------------------------------------------
@@ -105,7 +125,11 @@ export function executeEdit(args: EditArgs, cwd: string): ToolExecResult {
105125 }
106126
107127 // Exactly one match — replace
108- const updated = content.replace(args.oldText, args.newText);
128+ const lineEnding = detectLineEnding(content);
129+ const newText = lineEnding
130+ ? normalizeLineEndings(args.newText, lineEnding)
131+ : args.newText;
132+ const updated = content.replace(args.oldText, newText);
109133 writeFileSync(filePath, updated, "utf-8");
110134 return textResult(`Edited ${args.path}`, false);
111135 }
@@ -489,13 +513,18 @@ export function executeReadImage(
489513 return textResult(`File not found: ${args.path}`, true);
490514 }
491515
492- const data = readFileSync(filePath);
493- const base64 = Buffer.from(data).toString("base64");
516+ try {
517+ const data = readFileSync(filePath);
518+ const base64 = Buffer.from(data).toString("base64");
494519
495- return {
496- content: [{ type: "image", data: base64, mimeType }],
497- isError: false,
498- };
520+ return {
521+ content: [{ type: "image", data: base64, mimeType }],
522+ isError: false,
523+ };
524+ } catch (error) {
525+ const message = error instanceof Error ? error.message : String(error);
526+ return textResult(`Failed to read image ${args.path}: ${message}`, true);
527+ }
499528 }
500529
501530 /** pi-ai tool definition for `readImage`. */
src/ui.commands.test.ts+1−0
@@ -66,6 +66,7 @@ function createTestState(): AppState {
6666 canonicalCwd: cwd,
6767 running: false,
6868 abortController: null,
69+ activeTurnPromise: null,
6970 showReasoning: true,
7071 verbose: false,
7172 };
src/ui.test.ts+177−0
@@ -142,6 +142,7 @@ function createTestState(): AppState {
142142 canonicalCwd: cwd,
143143 running: false,
144144 abortController: null,
145+ activeTurnPromise: null,
145146 showReasoning: DEFAULT_SHOW_REASONING,
146147 verbose: DEFAULT_VERBOSE,
147148 };
@@ -683,6 +684,182 @@ describe("ui rendering", () => {
683684 }
684685 });
685686
687+ test("submit/runtime errors are appended to the conversation log and persisted", async () => {
688+ const api = "ui-submit-error-test";
689+ const sourceId = "ui-submit-error-test-source";
690+ const model: Model<string> = {
691+ id: "ui-submit-error-model",
692+ name: "UI Submit Error Model",
693+ api,
694+ provider: "test",
695+ baseUrl: "http://localhost:0",
696+ reasoning: false,
697+ input: ["text"],
698+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
699+ contextWindow: 128000,
700+ maxTokens: 4096,
701+ };
702+
703+ registerApiProvider(
704+ {
705+ api,
706+ stream: () => {
707+ throw new Error("provider exploded");
708+ },
709+ streamSimple: () => {
710+ throw new Error("provider exploded");
711+ },
712+ },
713+ sourceId,
714+ );
715+
716+ const state = createTestState();
717+ state.cwd = process.cwd();
718+ state.canonicalCwd = process.cwd();
719+ state.model = model;
720+
721+ try {
722+ handleInput("hello", state);
723+
724+ await waitFor(() =>
725+ state.messages.some(
726+ (message) =>
727+ message.role === "ui" &&
728+ message.content === "Submit failed: provider exploded",
729+ ),
730+ );
731+ await waitFor(() => !state.running);
732+
733+ const sessionId = state.session?.id;
734+ if (!sessionId) {
735+ throw new Error("Expected a session to be created");
736+ }
737+
738+ const messages = loadMessages(state.db, sessionId);
739+ expect(messages.map((message) => message.role)).toEqual(["user", "ui"]);
740+ const uiMessage = messages[1];
741+ expect(uiMessage?.role).toBe("ui");
742+ if (!uiMessage || uiMessage.role !== "ui") {
743+ throw new Error("Expected persisted UI message");
744+ }
745+ expect(uiMessage.content).toBe("Submit failed: provider exploded");
746+ } finally {
747+ await stopRunningTurn(state);
748+ unregisterApiProviders(sourceId);
749+ state.db.close();
750+ }
751+ });
752+
753+ test("/undo waits for an aborted run to settle before deleting the turn", async () => {
754+ const api = "ui-undo-abort-race-test";
755+ const sourceId = "ui-undo-abort-race-test-source";
756+ const model: Model<string> = {
757+ id: "ui-undo-abort-race-model",
758+ name: "UI Undo Abort Race Model",
759+ api,
760+ provider: "test",
761+ baseUrl: "http://localhost:0",
762+ reasoning: false,
763+ input: ["text"],
764+ cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
765+ contextWindow: 128000,
766+ maxTokens: 4096,
767+ };
768+
769+ const buildAbortMessage = (): AssistantMessage => ({
770+ role: "assistant",
771+ content: [],
772+ api,
773+ provider: model.provider,
774+ model: model.id,
775+ usage: {
776+ input: 0,
777+ output: 0,
778+ cacheRead: 0,
779+ cacheWrite: 0,
780+ totalTokens: 0,
781+ cost: {
782+ input: 0,
783+ output: 0,
784+ cacheRead: 0,
785+ cacheWrite: 0,
786+ total: 0,
787+ },
788+ },
789+ stopReason: "aborted",
790+ errorMessage: "aborted",
791+ timestamp: Date.now(),
792+ });
793+
794+ const buildProviderStream = (signal?: AbortSignal) => {
795+ const stream = createAssistantMessageEventStream();
796+
797+ queueMicrotask(() => {
798+ const emitAbort = () => {
799+ const abortedMessage = buildAbortMessage();
800+ stream.push({
801+ type: "error",
802+ reason: "aborted",
803+ error: abortedMessage,
804+ });
805+ stream.end(abortedMessage);
806+ };
807+
808+ if (signal?.aborted) {
809+ setTimeout(emitAbort, 50);
810+ return;
811+ }
812+
813+ signal?.addEventListener(
814+ "abort",
815+ () => {
816+ setTimeout(emitAbort, 50);
817+ },
818+ { once: true },
819+ );
820+ });
821+
822+ return stream;
823+ };
824+
825+ registerApiProvider(
826+ {
827+ api,
828+ stream: (_model, _context, options) =>
829+ buildProviderStream(options?.signal),
830+ streamSimple: (_model, _context, options) =>
831+ buildProviderStream(options?.signal),
832+ },
833+ sourceId,
834+ );
835+
836+ const state = createTestState();
837+ state.cwd = process.cwd();
838+ state.canonicalCwd = process.cwd();
839+ state.model = model;
840+
841+ try {
842+ handleInput("hello", state);
843+
844+ await waitFor(() => state.running && state.session !== null);
845+ const sessionId = state.session?.id;
846+ if (!sessionId) {
847+ throw new Error("Expected a session to be created");
848+ }
849+
850+ handleInput("/undo", state);
851+
852+ await waitFor(() => !state.running);
853+ await waitFor(() => state.messages.length === 0);
854+
855+ expect(loadMessages(state.db, sessionId)).toEqual([]);
856+ } finally {
857+ await stopRunningTurn(state);
858+ unregisterApiProviders(sourceId);
859+ state.db.close();
860+ }
861+ });
862+
686863 test("/skill:name prepends the selected skill body to the submitted user message", async () => {
687864 const faux = registerFauxProvider();
688865 const state = createTestState();
src/ui/agent.ts+20−5
@@ -120,6 +120,10 @@ export function isEmptyUserContent(content: UserMessage["content"]): boolean {
120120 );
121121 }
122122
123+function getErrorMessage(error: unknown): string {
124+ return error instanceof Error ? error.message : String(error);
125+}
126+
123127 /**
124128 * Create the UI agent controller bound to runtime hooks supplied by `ui.ts`.
125129 *
@@ -146,9 +150,8 @@ export function createUiAgentController(
146150 readFileSync(skill.path, "utf-8"),
147151 ).trim();
148152 } catch (err) {
149- const message = err instanceof Error ? err.message : String(err);
150153 runtime.appendInfoMessage(
151- `Failed to read skill ${skillName}: ${message}`,
154+ `Failed to read skill ${skillName}: ${getErrorMessage(err)}`,
152155 state,
153156 );
154157 return null;
@@ -253,9 +256,21 @@ export function createUiAgentController(
253256 state: AppState,
254257 rawInput: string,
255258 ): void => {
256- submitMessage(content, state, rawInput).catch((err) => {
257- console.error("Submit error:", err);
258- });
259+ let submitPromise: Promise<void>;
260+ submitPromise = submitMessage(content, state, rawInput)
261+ .catch((err) => {
262+ runtime.appendInfoMessage(
263+ `Submit failed: ${getErrorMessage(err)}`,
264+ state,
265+ );
266+ })
267+ .finally(() => {
268+ if (state.activeTurnPromise === submitPromise) {
269+ state.activeTurnPromise = null;
270+ }
271+ });
272+
273+ state.activeTurnPromise = submitPromise;
259274 };
260275
261276 const handleAgentEvent = (event: AgentEvent, state: AppState): void => {
src/ui/commands.ts+17−3
@@ -38,6 +38,10 @@ const EFFORT_LEVELS: { label: string; value: ThinkingLevel }[] = [
3838 { label: "xhigh", value: "xhigh" },
3939 ];
4040
41+function getErrorMessage(error: unknown): string {
42+ return error instanceof Error ? error.message : String(error);
43+}
44+
4145 /** Runtime hooks injected from the stateful UI module. */
4246 export interface UiCommandRuntime {
4347 /** Open an overlay and trigger a re-render. */
@@ -343,10 +347,15 @@ export function createCommandController(
343347 runtime.appendInfoMessage("Forked session.", state);
344348 };
345349
346- const handleUndoCommand = (state: AppState): void => {
350+ const handleUndoCommand = async (state: AppState): Promise<void> => {
347351 if (state.running && state.abortController) {
348352 state.abortController.abort();
349353 }
354+
355+ if (state.activeTurnPromise) {
356+ await state.activeTurnPromise;
357+ }
358+
350359 if (!state.session) {
351360 return;
352361 }
@@ -442,7 +451,7 @@ export function createCommandController(
442451 if (provider) {
443452 performLogin(provider, state).catch((err) => {
444453 runtime.appendInfoMessage(
445- `Login failed: ${err instanceof Error ? err.message : String(err)}`,
454+ `Login failed: ${getErrorMessage(err)}`,
446455 state,
447456 );
448457 });
@@ -519,7 +528,12 @@ export function createCommandController(
519528 handleForkCommand(state);
520529 return true;
521530 case "undo":
522- handleUndoCommand(state);
531+ handleUndoCommand(state).catch((error) => {
532+ runtime.appendInfoMessage(
533+ `Undo failed: ${getErrorMessage(error)}`,
534+ state,
535+ );
536+ });
523537 return true;
524538 case "reasoning":
525539 handleReasoningCommand(state);