xonecas.io
64875
Mc

mini-coder / commit 14ef2a1

fix: harden local state loading and browser launch

xonecas2026-04-10 14ef2a1c121c41a57d1803cf380b12f48dc54f5a parent f0816dc

15 files changed

src/git.test.ts+2−0
@@ -124,6 +124,7 @@ describe("getGitState", () => {
124124 test("returns zero ahead/behind when no upstream", async () => {
125125 await initRepo();
126126 const state = expectGitState(await getGitState(tmp));
127+ expect(state.upstream).toBeNull();
127128 expect(state.ahead).toBe(0);
128129 expect(state.behind).toBe(0);
129130 });
@@ -147,6 +148,7 @@ describe("getGitState", () => {
147148 await git("commit -m second", work);
148149
149150 const state = expectGitState(await getGitState(work));
151+ expect(state.upstream).toBeOneOf(["origin/main", "origin/master"]);
150152 expect(state.ahead).toBe(1);
151153 expect(state.behind).toBe(0);
152154 });
src/git.ts+8−1
@@ -23,6 +23,8 @@ export interface GitState {
2323 root: string;
2424 /** Current branch name (empty string for detached HEAD). */
2525 branch: string;
26+ /** Upstream tracking ref such as `origin/main`, or `null` when none exists. */
27+ upstream: string | null;
2628 /** Number of staged (index) changes. */
2729 staged: number;
2830 /** Number of unstaged working-tree modifications. */
@@ -135,8 +137,12 @@ export async function getGitState(cwd: string): Promise<GitState | null> {
135137 if (root === null) return null;
136138
137139 // Run remaining commands in parallel
138- const [branch, status, revList] = await Promise.all([
140+ const [branch, upstream, status, revList] = await Promise.all([
139141 run(["branch", "--show-current"], cwd),
142+ run(
143+ ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
144+ cwd,
145+ ),
140146 run(["status", "--porcelain"], cwd, false),
141147 run(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], cwd),
142148 ]);
@@ -155,6 +161,7 @@ export async function getGitState(cwd: string): Promise<GitState | null> {
155161 return {
156162 root,
157163 branch: branch ?? "",
164+ upstream,
158165 staged,
159166 modified,
160167 untracked,
src/index.test.ts+11−0
@@ -6,6 +6,7 @@ import { pathToFileURL } from "node:url";
66 import {
77 type AppState,
88 didOAuthCredentialsChange,
9+ loadOAuthCredentials,
910 loadPromptContext,
1011 reloadPromptContext,
1112 } from "./index.ts";
@@ -176,6 +177,16 @@ test("didOAuthCredentialsChange compares refreshed credentials structurally", ()
176177 ).toBe(true);
177178 });
178179
180+test("loadOAuthCredentials throws a helpful error when the auth file contains invalid JSON", () => {
181+ const dir = createTempDir();
182+ const path = join(dir, "auth.json");
183+ writeFileSync(path, "{not json", "utf-8");
184+
185+ expect(() => loadOAuthCredentials(path)).toThrow(
186+ `Failed to read OAuth credentials ${path}:`,
187+ );
188+});
189+
179190 test("loadPromptContext loads AGENTS.md, skills, plugins, and theme overrides", async () => {
180191 const project = createTempDir();
181192 const pluginPath = join(project, "plugin.ts");
src/index.ts+30−9
@@ -10,7 +10,7 @@
1010
1111 import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1212 import { homedir } from "node:os";
13-import { join } from "node:path";
13+import { dirname, join } from "node:path";
1414 import { isDeepStrictEqual } from "node:util";
1515 import type {
1616 KnownProvider,
@@ -98,24 +98,45 @@ export const MAX_SESSIONS_PER_CWD = 20;
9898 /** Maximum raw prompt-history entries to retain globally. */
9999 export const MAX_PROMPT_HISTORY = 1_000;
100100
101+function getErrorMessage(error: unknown): string {
102+ return error instanceof Error ? error.message : String(error);
103+}
104+
101105 // ---------------------------------------------------------------------------
102106 // OAuth credential persistence
103107 // ---------------------------------------------------------------------------
104108
105109 /** Load saved OAuth credentials from disk. */
106-function loadOAuthCredentials(): Record<string, OAuthCredentials> {
107- if (!existsSync(AUTH_PATH)) return {};
110+function loadOAuthCredentials(
111+ path = AUTH_PATH,
112+): Record<string, OAuthCredentials> {
113+ if (!existsSync(path)) return {};
114+
115+ let parsed: unknown;
108116 try {
109- return JSON.parse(readFileSync(AUTH_PATH, "utf-8"));
110- } catch {
111- return {};
117+ parsed = JSON.parse(readFileSync(path, "utf-8")) as unknown;
118+ } catch (error) {
119+ throw new Error(
120+ `Failed to read OAuth credentials ${path}: ${getErrorMessage(error)}`,
121+ );
112122 }
123+
124+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
125+ throw new Error(
126+ `Failed to read OAuth credentials ${path}: expected a JSON object`,
127+ );
128+ }
129+
130+ return parsed as Record<string, OAuthCredentials>;
113131 }
114132
115133 /** Save OAuth credentials to disk. */
116-function saveOAuthCredentials(creds: Record<string, OAuthCredentials>): void {
117- mkdirSync(DATA_DIR, { recursive: true });
118- writeFileSync(AUTH_PATH, JSON.stringify(creds, null, 2), "utf-8");
134+function saveOAuthCredentials(
135+ creds: Record<string, OAuthCredentials>,
136+ path = AUTH_PATH,
137+): void {
138+ mkdirSync(dirname(path), { recursive: true });
139+ writeFileSync(path, JSON.stringify(creds, null, 2), "utf-8");
119140 }
120141
121142 /** Return whether refreshed OAuth credentials differ from the persisted value. */
src/prompt.test.ts+37−0
@@ -1,5 +1,6 @@
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
22 import {
3+ chmodSync,
34 mkdirSync,
45 mkdtempSync,
56 rmSync,
@@ -157,6 +158,18 @@ describe("discoverAgentsMd", () => {
157158 const files = discoverAgentsMd(project, home);
158159 expect(files.map((file) => file.content)).toEqual(["Project instructions"]);
159160 });
161+
162+ test("skips unreadable AGENTS.md files", () => {
163+ const unreadablePath = join(tmp, "AGENTS.md");
164+ writeFileSync(unreadablePath, "secret instructions");
165+ chmodSync(unreadablePath, 0o000);
166+
167+ try {
168+ expect(discoverAgentsMd(tmp, resolve(tmp))).toEqual([]);
169+ } finally {
170+ chmodSync(unreadablePath, 0o600);
171+ }
172+ });
160173 });
161174
162175 // ---------------------------------------------------------------------------
@@ -199,6 +212,7 @@ describe("formatGitLine", () => {
199212 const state: GitState = {
200213 root: "/repo",
201214 branch: "main",
215+ upstream: "origin/main",
202216 staged: 3,
203217 modified: 1,
204218 untracked: 2,
@@ -216,6 +230,7 @@ describe("formatGitLine", () => {
216230 const state: GitState = {
217231 root: "/repo",
218232 branch: "main",
233+ upstream: null,
219234 staged: 0,
220235 modified: 0,
221236 untracked: 0,
@@ -231,6 +246,7 @@ describe("formatGitLine", () => {
231246 const state: GitState = {
232247 root: "/repo",
233248 branch: "feature",
249+ upstream: null,
234250 staged: 0,
235251 modified: 2,
236252 untracked: 0,
@@ -246,6 +262,7 @@ describe("formatGitLine", () => {
246262 const state: GitState = {
247263 root: "/repo",
248264 branch: "dev",
265+ upstream: "upstream/dev",
249266 staged: 1,
250267 modified: 0,
251268 untracked: 0,
@@ -261,6 +278,7 @@ describe("formatGitLine", () => {
261278 const state: GitState = {
262279 root: "/repo",
263280 branch: "main",
281+ upstream: "origin/main",
264282 staged: 0,
265283 modified: 0,
266284 untracked: 0,
@@ -276,6 +294,7 @@ describe("formatGitLine", () => {
276294 const state: GitState = {
277295 root: "/repo",
278296 branch: "main",
297+ upstream: "origin/main",
279298 staged: 0,
280299 modified: 0,
281300 untracked: 0,
@@ -286,6 +305,22 @@ describe("formatGitLine", () => {
286305 const line = formatGitLine(state);
287306 expect(line).toBe("Git: branch main | −4 vs origin/main");
288307 });
308+
309+ test("uses the actual upstream ref instead of assuming origin", () => {
310+ const state: GitState = {
311+ root: "/repo",
312+ branch: "feature",
313+ upstream: "fork/main",
314+ staged: 0,
315+ modified: 0,
316+ untracked: 0,
317+ ahead: 2,
318+ behind: 1,
319+ };
320+
321+ const line = formatGitLine(state);
322+ expect(line).toBe("Git: branch feature | +2 −1 vs fork/main");
323+ });
289324 });
290325
291326 // ---------------------------------------------------------------------------
@@ -325,6 +360,7 @@ describe("buildSystemPrompt", () => {
325360 git: {
326361 root: "/home/user/project",
327362 branch: "main",
363+ upstream: "origin/main",
328364 staged: 3,
329365 modified: 1,
330366 untracked: 2,
@@ -430,6 +466,7 @@ describe("buildSystemPrompt", () => {
430466 git: {
431467 root: "/project",
432468 branch: "main",
469+ upstream: null,
433470 staged: 0,
434471 modified: 0,
435472 untracked: 0,
src/prompt.ts+12−5
@@ -99,10 +99,15 @@ function readAgentsMdFile(dir: string): AgentsMdFile | null {
9999 if (!existsSync(filePath)) {
100100 return null;
101101 }
102- return {
103- path: filePath,
104- content: readFileSync(filePath, "utf-8"),
105- };
102+
103+ try {
104+ return {
105+ path: filePath,
106+ content: readFileSync(filePath, "utf-8"),
107+ };
108+ } catch {
109+ return null;
110+ }
106111 }
107112
108113 /**
@@ -152,6 +157,7 @@ export function discoverAgentsMd(
152157 *
153158 * Fields are omitted when their values are zero. The git line format:
154159 * `Git: branch main | 3 staged, 1 modified, 2 untracked | +5 −2 vs origin/main`
160+ * where the trailing upstream label reflects the repository's actual tracking ref.
155161 *
156162 * @param state - The git state to format.
157163 * @returns Formatted git status line.
@@ -171,7 +177,8 @@ export function formatGitLine(state: GitState): string {
171177 const ab: string[] = [];
172178 if (state.ahead > 0) ab.push(`+${state.ahead}`);
173179 if (state.behind > 0) ab.push(`\u2212${state.behind}`);
174- parts.push(`${ab.join(" ")} vs origin/${state.branch}`);
180+ const upstream = state.upstream ? ` vs ${state.upstream}` : "";
181+ parts.push(`${ab.join(" ")}${upstream}`);
175182 }
176183
177184 return parts.join(" | ");
src/session.test.ts+33−0
@@ -179,6 +179,21 @@ describe("session persistence", () => {
179179 db.close();
180180 });
181181
182+ test("listSessions_firstUserPreview_returnsNullWhenTheFirstMessageRowIsInvalid", () => {
183+ const db = openDatabase(":memory:");
184+ const session = createSession(db, { cwd: "/tmp/test" });
185+
186+ db.run(
187+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
188+ [session.id, 1, "not json", Date.now()],
189+ );
190+
191+ const [entry] = listSessions(db, "/tmp/test");
192+
193+ expect(entry?.firstUserPreview).toBeNull();
194+ db.close();
195+ });
196+
182197 test("deleteSession removes session and cascades to messages", () => {
183198 const db = openDatabase(":memory:");
184199 const session = createSession(db, { cwd: "/tmp/test" });
@@ -253,6 +268,24 @@ describe("message persistence and turn numbering", () => {
253268 db.close();
254269 });
255270
271+ test("loadMessages skips invalid persisted rows and keeps valid messages", () => {
272+ const db = openDatabase(":memory:");
273+ const session = createSession(db, { cwd: "/tmp/test" });
274+
275+ const turn = appendMessage(db, session.id, makeUser("hello"));
276+ db.run(
277+ "INSERT INTO messages (session_id, turn, data, created_at) VALUES (?, ?, ?, ?)",
278+ [session.id, turn, "not json", Date.now()],
279+ );
280+ appendMessage(db, session.id, makeAssistant("hi"), turn);
281+
282+ const msgs = loadMessages(db, session.id);
283+ expect(msgs).toHaveLength(2);
284+ expect(msgs[0]?.role).toBe("user");
285+ expect(msgs[1]?.role).toBe("assistant");
286+ db.close();
287+ });
288+
256289 test("UI messages store turn as NULL and do not consume conversational turn numbers", () => {
257290 const db = openDatabase(":memory:");
258291 const session = createSession(db, { cwd: "/tmp/test" });
src/session.ts+211−6
@@ -10,7 +10,12 @@
1010 */
1111
1212 import { Database } from "bun:sqlite";
13-import type { AssistantMessage, Message } from "@mariozechner/pi-ai";
13+import type {
14+ AssistantMessage,
15+ Message,
16+ ToolResultMessage,
17+ UserMessage,
18+} from "@mariozechner/pi-ai";
1419
1520 // ---------------------------------------------------------------------------
1621 // Types
@@ -140,6 +145,21 @@ type MaxTurnRow = { max_turn: number | null };
140145 /** Row shape for `SELECT data` queries. */
141146 type DataRow = { data: string };
142147
148+const EMPTY_ASSISTANT_USAGE: AssistantMessage["usage"] = {
149+ input: 0,
150+ output: 0,
151+ cacheRead: 0,
152+ cacheWrite: 0,
153+ totalTokens: 0,
154+ cost: {
155+ input: 0,
156+ output: 0,
157+ cacheRead: 0,
158+ cacheWrite: 0,
159+ total: 0,
160+ },
161+};
162+
143163 /** Row shape returned by `SELECT * FROM prompt_history`. */
144164 type PromptHistoryRow = {
145165 id: number;
@@ -319,14 +339,189 @@ function getMultipartUserPreview(
319339 return collapsePreviewText(text);
320340 }
321341
342+function isTextContentBlock(
343+ value: unknown,
344+): value is { type: "text"; text: string } {
345+ const record = toRecord(value);
346+ return record?.type === "text" && typeof record.text === "string";
347+}
348+
349+function isImageContentBlock(
350+ value: unknown,
351+): value is { type: "image"; data: string; mimeType: string } {
352+ const record = toRecord(value);
353+ return (
354+ record?.type === "image" &&
355+ typeof record.data === "string" &&
356+ typeof record.mimeType === "string"
357+ );
358+}
359+
360+function isThinkingContentBlock(
361+ value: unknown,
362+): value is Extract<AssistantMessage["content"][number], { type: "thinking" }> {
363+ const record = toRecord(value);
364+ return record?.type === "thinking" && typeof record.thinking === "string";
365+}
366+
367+function isToolCallContentBlock(
368+ value: unknown,
369+): value is Extract<AssistantMessage["content"][number], { type: "toolCall" }> {
370+ const record = toRecord(value);
371+ return (
372+ record?.type === "toolCall" &&
373+ typeof record.id === "string" &&
374+ typeof record.name === "string" &&
375+ toRecord(record.arguments) !== null
376+ );
377+}
378+
379+function isAssistantUsage(value: unknown): value is AssistantMessage["usage"] {
380+ const usageRecord = toRecord(value);
381+ const costRecord = toRecord(usageRecord?.cost);
382+ return (
383+ usageRecord !== null &&
384+ costRecord !== null &&
385+ readFiniteNumber(usageRecord, "input") !== null &&
386+ readFiniteNumber(usageRecord, "output") !== null &&
387+ readFiniteNumber(usageRecord, "cacheRead") !== null &&
388+ readFiniteNumber(usageRecord, "cacheWrite") !== null &&
389+ readFiniteNumber(usageRecord, "totalTokens") !== null &&
390+ readFiniteNumber(costRecord, "input") !== null &&
391+ readFiniteNumber(costRecord, "output") !== null &&
392+ readFiniteNumber(costRecord, "cacheRead") !== null &&
393+ readFiniteNumber(costRecord, "cacheWrite") !== null &&
394+ readFiniteNumber(costRecord, "total") !== null
395+ );
396+}
397+
398+function isStopReason(value: unknown): value is AssistantMessage["stopReason"] {
399+ return (
400+ value === "stop" ||
401+ value === "length" ||
402+ value === "toolUse" ||
403+ value === "error" ||
404+ value === "aborted"
405+ );
406+}
407+
408+function isUserMessageRecord(value: unknown): value is UserMessage {
409+ const record = toRecord(value);
410+ if (!record || record.role !== "user") {
411+ return false;
412+ }
413+
414+ return (
415+ readFiniteNumber(record, "timestamp") !== null &&
416+ (typeof record.content === "string" ||
417+ (Array.isArray(record.content) &&
418+ record.content.every(
419+ (block) => isTextContentBlock(block) || isImageContentBlock(block),
420+ )))
421+ );
422+}
423+
424+function parseAssistantMessageRecord(value: unknown): AssistantMessage | null {
425+ const record = toRecord(value);
426+ if (!record || record.role !== "assistant") {
427+ return null;
428+ }
429+
430+ const timestamp = readFiniteNumber(record, "timestamp");
431+ if (
432+ !Array.isArray(record.content) ||
433+ !record.content.every(
434+ (block) =>
435+ isTextContentBlock(block) ||
436+ isThinkingContentBlock(block) ||
437+ isToolCallContentBlock(block),
438+ ) ||
439+ typeof record.api !== "string" ||
440+ typeof record.provider !== "string" ||
441+ typeof record.model !== "string" ||
442+ !isStopReason(record.stopReason) ||
443+ (record.errorMessage !== undefined &&
444+ typeof record.errorMessage !== "string") ||
445+ timestamp === null
446+ ) {
447+ return null;
448+ }
449+
450+ return {
451+ role: "assistant",
452+ content: record.content,
453+ api: record.api,
454+ provider: record.provider,
455+ model: record.model,
456+ usage: isAssistantUsage(record.usage)
457+ ? record.usage
458+ : structuredClone(EMPTY_ASSISTANT_USAGE),
459+ stopReason: record.stopReason,
460+ ...(typeof record.errorMessage === "string"
461+ ? { errorMessage: record.errorMessage }
462+ : {}),
463+ timestamp,
464+ };
465+}
466+
467+function isToolResultMessageRecord(value: unknown): value is ToolResultMessage {
468+ const record = toRecord(value);
469+ if (!record || record.role !== "toolResult") {
470+ return false;
471+ }
472+
473+ return (
474+ typeof record.toolCallId === "string" &&
475+ typeof record.toolName === "string" &&
476+ typeof record.isError === "boolean" &&
477+ Array.isArray(record.content) &&
478+ record.content.every(
479+ (block) => isTextContentBlock(block) || isImageContentBlock(block),
480+ ) &&
481+ readFiniteNumber(record, "timestamp") !== null
482+ );
483+}
484+
485+function isUiMessageRecord(value: unknown): value is UiMessage {
486+ const record = toRecord(value);
487+ if (!record || record.role !== "ui") {
488+ return false;
489+ }
490+
491+ return (
492+ record.kind === "info" &&
493+ typeof record.content === "string" &&
494+ readFiniteNumber(record, "timestamp") !== null
495+ );
496+}
497+
498+function parsePersistedMessage(data: string): PersistedMessage | null {
499+ let parsed: unknown;
500+ try {
501+ parsed = JSON.parse(data) as unknown;
502+ } catch {
503+ return null;
504+ }
505+
506+ if (
507+ isUserMessageRecord(parsed) ||
508+ isToolResultMessageRecord(parsed) ||
509+ isUiMessageRecord(parsed)
510+ ) {
511+ return parsed;
512+ }
513+
514+ return parseAssistantMessageRecord(parsed);
515+}
516+
322517 /** Read the first-user preview cached by the session-list query. */
323518 function readFirstUserPreview(messageData: string | null): string | null {
324519 if (!messageData) {
325520 return null;
326521 }
327522
328- const message = JSON.parse(messageData) as PersistedMessage;
329- if (message.role !== "user") {
523+ const message = parsePersistedMessage(messageData);
524+ if (!message || message.role !== "user") {
330525 return null;
331526 }
332527
@@ -434,7 +629,7 @@ export function filterModelMessages(
434629 }
435630
436631 function toRecord(value: unknown): Record<string, unknown> | null {
437- return typeof value === "object" && value !== null
632+ return typeof value === "object" && value !== null && !Array.isArray(value)
438633 ? (value as Record<string, unknown>)
439634 : null;
440635 }
@@ -620,7 +815,8 @@ export function appendMessage(
620815 * Load all messages for a session in insertion order.
621816 *
622817 * Messages are deserialized from their JSON representation back into
623- * persisted app messages. The ordering matches the original append order
818+ * persisted app messages. Invalid rows are skipped so corrupted session data
819+ * does not crash the app. The ordering matches the original append order
624820 * (by autoincrement `id`), preserving the conversation flow.
625821 *
626822 * @param db - Open database handle.
@@ -633,7 +829,16 @@ export function loadMessages(
633829 sessionId: string,
634830 ): PersistedMessage[] {
635831 const rows = db.query<DataRow, [string]>(SQL.loadMessages).all(sessionId);
636- return rows.map((row) => JSON.parse(row.data) as PersistedMessage);
832+ const messages: PersistedMessage[] = [];
833+
834+ for (const row of rows) {
835+ const message = parsePersistedMessage(row.data);
836+ if (message) {
837+ messages.push(message);
838+ }
839+ }
840+
841+ return messages;
637842 }
638843
639844 // ---------------------------------------------------------------------------
src/settings.test.ts+16−2
@@ -52,12 +52,26 @@ describe("settings", () => {
5252 expect(loadSettings(path)).toEqual(settings);
5353 });
5454
55- test("loadSettings ignores invalid JSON", () => {
55+ test("loadSettings throws a helpful error when the file contains invalid JSON", () => {
5656 const dir = createTempDir();
5757 const path = join(dir, "settings.json");
5858 writeFileSync(path, "{not json", "utf-8");
5959
60- expect(loadSettings(path)).toEqual({});
60+ expect(() => loadSettings(path)).toThrow(
61+ `Failed to read settings ${path}:`,
62+ );
63+ });
64+
65+ test("updateSettings preserves an invalid settings file instead of overwriting it", () => {
66+ const dir = createTempDir();
67+ const path = join(dir, "settings.json");
68+ const invalidJson = "{not json";
69+ writeFileSync(path, invalidJson, "utf-8");
70+
71+ expect(() => updateSettings(path, { verbose: true })).toThrow(
72+ `Failed to read settings ${path}:`,
73+ );
74+ expect(readFileSync(path, "utf-8")).toBe(invalidJson);
6175 });
6276
6377 test("loadSettings keeps valid fields and drops invalid ones", () => {
src/settings.ts+10−3
@@ -51,10 +51,15 @@ const THINKING_LEVELS = new Set<ThinkingLevel>([
5151 "xhigh",
5252 ]);
5353
54+function getErrorMessage(error: unknown): string {
55+ return error instanceof Error ? error.message : String(error);
56+}
57+
5458 /**
5559 * Load and validate user settings from disk.
5660 *
57- * Invalid or missing files are treated as empty settings.
61+ * Missing files are treated as empty settings. Invalid JSON or unreadable files
62+ * fail with a descriptive error instead of silently discarding saved state.
5863 *
5964 * @param path - Absolute path to `settings.json`.
6065 * @returns The validated settings object.
@@ -67,8 +72,10 @@ export function loadSettings(path: string): UserSettings {
6772 try {
6873 const raw = JSON.parse(readFileSync(path, "utf-8")) as unknown;
6974 return sanitizeSettings(raw);
70- } catch {
71- return {};
75+ } catch (error) {
76+ throw new Error(
77+ `Failed to read settings ${path}: ${getErrorMessage(error)}`,
78+ );
7279 }
7380 }
7481
src/skills.test.ts+22−1
@@ -1,5 +1,11 @@
11 import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+import {
3+ chmodSync,
4+ mkdirSync,
5+ mkdtempSync,
6+ rmSync,
7+ writeFileSync,
8+} from "node:fs";
39 import { tmpdir } from "node:os";
410 import { join } from "node:path";
511 import { buildSkillCatalog, discoverSkills, type Skill } from "./skills.ts";
@@ -205,6 +211,21 @@ describe("discoverSkills", () => {
205211 expect(skills[0]!.name).toBe("quoted-name");
206212 expect(skills[0]!.description).toBe("A quoted description");
207213 });
214+
215+ test("skips unreadable SKILL.md files", () => {
216+ const skillPath = writeSkill(
217+ tmp,
218+ "secret-skill",
219+ ["---", "name: secret-skill", "description: Hidden", "---"].join("\n"),
220+ );
221+ chmodSync(skillPath, 0o000);
222+
223+ try {
224+ expect(discoverSkills([tmp])).toEqual([]);
225+ } finally {
226+ chmodSync(skillPath, 0o600);
227+ }
228+ });
208229 });
209230
210231 // ---------------------------------------------------------------------------
src/skills.ts+11−7
@@ -183,13 +183,17 @@ function readSkill(basePath: string, entry: string): Skill | null {
183183 return null;
184184 }
185185
186- const content = readFileSync(skillPath, "utf-8");
187- const frontmatter = parseFrontmatter(content);
188- return {
189- name: frontmatter.name ?? entry,
190- description: frontmatter.description ?? "",
191- path: skillPath,
192- };
186+ try {
187+ const content = readFileSync(skillPath, "utf-8");
188+ const frontmatter = parseFrontmatter(content);
189+ return {
190+ name: frontmatter.name ?? entry,
191+ description: frontmatter.description ?? "",
192+ path: skillPath,
193+ };
194+ } catch {
195+ return null;
196+ }
193197 }
194198
195199 /**
src/ui.test.ts+32−0
@@ -38,6 +38,7 @@ import {
3838 type InputController,
3939 isQuitInput,
4040 isQuitKey,
41+ openInBrowser,
4142 renderActiveOverlay,
4243 renderBaseLayout,
4344 renderInputArea,
@@ -262,6 +263,37 @@ describe("ui rendering", () => {
262263 expect(isQuitKey("escape", "")).toBe(false);
263264 });
264265
266+ test("openInBrowser launches the platform opener with argv instead of a shell command", () => {
267+ const calls: {
268+ command: string;
269+ args: string[];
270+ options: { detached: boolean; stdio: "ignore" };
271+ }[] = [];
272+ let unrefCalled = false;
273+ const url = "https://example.com/$(printf injected)";
274+
275+ openInBrowser(url, {
276+ platform: "linux",
277+ spawn: (command, args, options) => {
278+ calls.push({ command, args, options });
279+ return {
280+ unref: () => {
281+ unrefCalled = true;
282+ },
283+ };
284+ },
285+ });
286+
287+ expect(calls).toEqual([
288+ {
289+ command: "xdg-open",
290+ args: [url],
291+ options: { detached: true, stdio: "ignore" },
292+ },
293+ ]);
294+ expect(unrefCalled).toBe(true);
295+ });
296+
265297 test("committing a streamed response preserves hidden reasoning placeholder order", async () => {
266298 const api = "ui-hidden-reasoning-order-test";
267299 const sourceId = "ui-hidden-reasoning-order-test-source";
src/ui.ts+44−5
@@ -8,7 +8,7 @@
88 * @module
99 */
1010
11-import { exec } from "node:child_process";
11+import { spawn } from "node:child_process";
1212 import { platform } from "node:os";
1313 import {
1414 cel,
@@ -379,10 +379,49 @@ export function renderInputArea(
379379 // Runtime helpers and controllers
380380 // ---------------------------------------------------------------------------
381381
382-/** Open a URL in the user's default browser. */
383-function openInBrowser(url: string): void {
384- const cmd = platform() === "darwin" ? "open" : "xdg-open";
385- exec(`${cmd} ${JSON.stringify(url)}`);
382+/** Browser process handle used by the platform opener helper. */
383+interface BrowserOpenProcess {
384+ /** Detach the browser opener so the app does not wait on it. */
385+ unref: () => void;
386+ /** Optional error listener used by real child-process implementations. */
387+ on?: (event: "error", listener: (error: Error) => void) => void;
388+}
389+
390+/** Optional runtime overrides for browser launching. */
391+interface OpenInBrowserRuntime {
392+ /** Platform used to choose the opener binary. */
393+ platform?: NodeJS.Platform;
394+ /** Process launcher used for tests. */
395+ spawn?: (
396+ command: string,
397+ args: string[],
398+ options: { detached: boolean; stdio: "ignore" },
399+ ) => BrowserOpenProcess;
400+}
401+
402+/** Open a URL in the user's default browser without invoking a shell. */
403+export function openInBrowser(
404+ url: string,
405+ runtime?: OpenInBrowserRuntime,
406+): void {
407+ const command =
408+ (runtime?.platform ?? platform()) === "darwin" ? "open" : "xdg-open";
409+ const launch =
410+ runtime?.spawn ??
411+ ((
412+ cmd: string,
413+ args: string[],
414+ options: { detached: boolean; stdio: "ignore" },
415+ ) => {
416+ return spawn(cmd, args, options);
417+ });
418+ const child = launch(command, [url], {
419+ detached: true,
420+ stdio: "ignore",
421+ });
422+
423+ child.on?.("error", () => {});
424+ child.unref();
386425 }
387426
388427 function scrollConversationToBottom(): void {
src/ui/status.test.ts+1−0
@@ -137,6 +137,7 @@ describe("ui/status", () => {
137137 state.git = {
138138 root: state.cwd,
139139 branch: "main",
140+ upstream: "origin/main",
140141 staged: 1,
141142 modified: 2,
142143 untracked: 3,