xonecas.io
64875
Mc

mini-coder / commit 2e83492

fix: harden error handling and add bun tests

xonecas2026-06-16 2e834928488ef2ef055d0f9fb114e65daa0db38f parent ba7e85e

6 files changed

src/args.ts+8−1
@@ -64,7 +64,14 @@ async function getSettings(): Promise<Settings | undefined> {
6464 }
6565
6666 const jsonText = await file.text();
67- const settings = JSON.parse(jsonText) as unknown;
67+ let settings: unknown;
68+
69+ try {
70+ settings = JSON.parse(jsonText) as unknown;
71+ } catch (err) {
72+ const message = err instanceof Error ? err.message : String(err);
73+ throw new Error(`Invalid settings JSON: ${message}`);
74+ }
6875
6976 return parseSettings(settings, "settings");
7077 }
src/error-handling.test.ts+163−0
@@ -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+});
src/oauth.ts+9−2
@@ -1,3 +1,4 @@
1+import { mkdir } from "node:fs/promises";
12 import readline from "node:readline";
23
34 import { getEnvApiKey, getProviders } from "@earendil-works/pi-ai";
@@ -10,7 +11,7 @@ import {
1011 type OAuthProviderId,
1112 type OAuthSelectPrompt,
1213 } from "@earendil-works/pi-ai/oauth";
13-import { AUTH_PATH as AUTH_FILE } from "./shared";
14+import { AUTH_PATH as AUTH_FILE, DATA_DIR } from "./shared";
1415 import type { CliOptions, SavedOAuthCreds } from "./types";
1516
1617 type ReadlineInterface = ReturnType<typeof readline.createInterface>;
@@ -134,13 +135,19 @@ export async function getApiKey(options: CliOptions) {
134135 export async function readCreds(): Promise<SavedOAuthCreds> {
135136 const file = Bun.file(AUTH_FILE);
136137 if (await file.exists()) {
137- return JSON.parse(await file.text());
138+ try {
139+ return JSON.parse(await file.text());
140+ } catch (err) {
141+ const message = err instanceof Error ? err.message : String(err);
142+ throw new Error(`Invalid auth JSON: ${message}`);
143+ }
138144 }
139145
140146 return {};
141147 }
142148
143149 async function writeCreds(creds: SavedOAuthCreds) {
150+ await mkdir(DATA_DIR, { recursive: true });
144151 await Bun.write(AUTH_FILE, JSON.stringify(await mergeCreds(creds)));
145152 }
146153
src/session.ts+9−4
@@ -16,11 +16,16 @@ export async function getSession(id: string): Promise<Session | undefined> {
1616 return;
1717 }
1818
19- const sessionJson = await file.text();
20- const parsed = JSON.parse(sessionJson) as unknown;
21- const valid = Value.Check(SessionSchema, parsed);
19+ try {
20+ const sessionJson = await file.text();
21+ const parsed = JSON.parse(sessionJson) as unknown;
22+ const valid = Value.Check(SessionSchema, parsed);
23+
24+ if (valid) return parsed;
25+ } catch {
26+ return;
27+ }
2228
23- if (valid) return parsed;
2429 return;
2530 }
2631
src/shared.ts+2−1
@@ -4,7 +4,8 @@ import { parseDocument } from "yaml";
44
55 // Mixed bag of helpers that can be shared across the codebase
66
7-export const DATA_DIR = join(homedir(), ".config", "mini-coder");
7+export const DATA_DIR =
8+ Bun.env.MINI_CODER_DATA_DIR ?? join(homedir(), ".config", "mini-coder");
89 export const SESSIONS_DIR = join(DATA_DIR, "sessions");
910 export const AUTH_PATH = join(DATA_DIR, "auth.json");
1011 export const SETTINGS_PATH = join(DATA_DIR, "settings.json");
src/tool-bash.ts+1−4
@@ -66,10 +66,7 @@ export async function* runBashTool(
6666
6767 const exitCode = await proc.exited;
6868
69- let result = `${output.length ? output : "(no ouput)"}\n\nExit code: ${exitCode}`;
70- if (output.length) {
71- result += `${output}`;
72- }
69+ const result = `${output.length ? output : "(no output)"}\n\nExit code: ${exitCode}`;
7370
7471 yield {
7572 type: "result",