@@ -0,0 +1,163 @@
1+import { afterAll, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+import { runBashTool } from "./tool-bash.ts";
6+import { runEditTool } from "./tool-edit.ts";
7+import { runReadTool } from "./tool-read.ts";
8+import type { ToolRunnerEvent } from "./types.ts";
9+
10+const originalDataDir = Bun.env.MINI_CODER_DATA_DIR;
11+const testHome = await mkdtemp(join(tmpdir(), "mini-coder-errors-"));
12+const dataDir = join(testHome, "data");
13+Bun.env.MINI_CODER_DATA_DIR = dataDir;
14+
15+const sessionsDir = join(dataDir, "sessions");
16+const { handleArgv } = await import("./args.ts");
17+const { getAvailableProviders } = await import("./oauth.ts");
18+const { getSession, listSessionsForCwd } = await import("./session.ts");
19+
20+type ResultEvent = Extract<ToolRunnerEvent, { type: "result" }>;
21+
22+async function collectToolEvents(
23+ events: AsyncGenerator<ToolRunnerEvent>,
24+): Promise<ToolRunnerEvent[]> {
25+ const collected: ToolRunnerEvent[] = [];
26+
27+ for await (const event of events) {
28+ collected.push(event);
29+ }
30+
31+ return collected;
32+}
33+
34+function resultEvent(events: ToolRunnerEvent[]): ResultEvent {
35+ const result = events.findLast(
36+ (event): event is ResultEvent => event.type === "result",
37+ );
38+
39+ if (!result) {
40+ throw new Error("Tool did not yield a result");
41+ }
42+
43+ return result;
44+}
45+
46+async function toolResult(
47+ events: AsyncGenerator<ToolRunnerEvent>,
48+): Promise<ResultEvent> {
49+ return resultEvent(await collectToolEvents(events));
50+}
51+
52+beforeEach(async () => {
53+ await rm(dataDir, { recursive: true, force: true });
54+});
55+
56+afterAll(async () => {
57+ if (originalDataDir === undefined) {
58+ delete Bun.env.MINI_CODER_DATA_DIR;
59+ } else {
60+ Bun.env.MINI_CODER_DATA_DIR = originalDataDir;
61+ }
62+
63+ await rm(testHome, { recursive: true, force: true });
64+});
65+
66+describe("tool runner error handling", () => {
67+ test("read and edit report missing files as tool results", async () => {
68+ const missingPath = join(testHome, "missing.txt");
69+
70+ const readResult = await toolResult(runReadTool({ path: missingPath }));
71+ expect(readResult.text).toBe(`File not found: ${missingPath}`);
72+
73+ const editResult = await toolResult(
74+ runEditTool({ path: missingPath, oldText: "old", newText: "new" }),
75+ );
76+ expect(editResult.text).toBe(`File not found: ${missingPath}`);
77+ });
78+
79+ test("edit refuses unsafe writes and preserves the file", async () => {
80+ const path = join(testHome, "edit.txt");
81+ await writeFile(path, "one\none\n");
82+
83+ const ambiguous = await toolResult(
84+ runEditTool({ path, oldText: "one", newText: "two" }),
85+ );
86+ expect(ambiguous.text).toContain("Multiple matches found");
87+ expect(await Bun.file(path).text()).toBe("one\none\n");
88+
89+ const missing = await toolResult(
90+ runEditTool({ path, oldText: "missing", newText: "two" }),
91+ );
92+ expect(missing.text).toBe(`Old text not found in: ${path}`);
93+ expect(await Bun.file(path).text()).toBe("one\none\n");
94+
95+ const abortController = new AbortController();
96+ abortController.abort();
97+ await writeFile(path, "hello");
98+
99+ const aborted = await toolResult(
100+ runEditTool(
101+ { path, oldText: "hello", newText: "bye" },
102+ abortController.signal,
103+ ),
104+ );
105+ expect(aborted.text).toBe("Aborted before write.");
106+ expect(await Bun.file(path).text()).toBe("hello");
107+ });
108+
109+ test("bash reports non-zero exits instead of throwing", async () => {
110+ const result = await toolResult(
111+ runBashTool({ command: 'printf "bad"; exit 7' }),
112+ );
113+
114+ expect(result.text).toBe("bad\n\nExit code: 7");
115+ });
116+});
117+
118+describe("startup file error handling", () => {
119+ test("settings JSON parse failures are labelled", async () => {
120+ await mkdir(dataDir, { recursive: true });
121+ await writeFile(join(dataDir, "settings.json"), "{");
122+
123+ await expect(handleArgv([])).rejects.toThrow("Invalid settings JSON:");
124+ });
125+
126+ test("auth JSON parse failures are labelled", async () => {
127+ await mkdir(dataDir, { recursive: true });
128+ await writeFile(join(dataDir, "auth.json"), "{");
129+
130+ await expect(getAvailableProviders()).rejects.toThrow("Invalid auth JSON:");
131+ });
132+});
133+
134+describe("session file error handling", () => {
135+ test("listSessionsForCwd ignores missing dirs and bad session files", async () => {
136+ expect(await listSessionsForCwd()).toEqual([]);
137+
138+ await mkdir(sessionsDir, { recursive: true });
139+ await writeFile(join(sessionsDir, "broken.json"), "{");
140+ await writeFile(
141+ join(sessionsDir, "elsewhere.json"),
142+ JSON.stringify({ id: "elsewhere", cwd: "/elsewhere", messages: [] }),
143+ );
144+ await writeFile(
145+ join(sessionsDir, "ok.json"),
146+ JSON.stringify({
147+ id: "ok",
148+ cwd: process.cwd(),
149+ messages: [{ role: "user", content: "hi", timestamp: 2 }],
150+ }),
151+ );
152+
153+ const sessions = await listSessionsForCwd();
154+ expect(sessions.map((session) => session.id)).toEqual(["ok"]);
155+ });
156+
157+ test("getSession returns undefined for bad session files", async () => {
158+ await mkdir(sessionsDir, { recursive: true });
159+ await writeFile(join(sessionsDir, "broken.json"), "{");
160+
161+ expect(await getSession("broken")).toBeUndefined();
162+ });
163+});