Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

fix(config): preserve malformed Claude config files

hsien wei1ea876c1cba7
diff --git a/src/main/config.ts b/src/main/config.ts
index 9c080b7f..e0ae05ed 100644
--- a/src/main/config.ts
+++ b/src/main/config.ts
@@ -779,28 +779,20 @@ export function ensureHarnessHome(path: string): { ok: boolean; error?: string }
}
}
-/** Idempotently pre-accept Claude Code's first-run prompts so agents spawned with
- * `--permission-mode bypassPermissions` start cleanly. Without this, a fresh
- * install shows an interactive "WARNING: Bypass Permissions mode … 1. No, exit /
- * 2. Yes, I accept" prompt that the PTY can't answer in time, so the agent exits
- * code 1 on its own (reported by multiple users).
- *
- * Two separate gates, written only when they aren't already satisfied (so we
- * rarely touch files a running `claude` also writes):
- * 1. `~/.claude/settings.json` → `skipDangerousModePermissionPrompt` +
- * `skipAutoPermissionPrompt` — these gate the bypass-mode warning (global).
- * 2. `~/.claude.json` → `projects[cwd].hasTrustDialogAccepted` — the per-folder
- * "do you trust the files in this folder?" dialog. */
-export function ensureClaudePermissionsAccepted(cwd?: string): void {
- const home = homedir();
- if (!home) return;
- // 1) Global bypass-mode warning gate.
+function ensureClaudeGlobalPermissions(home: string): void {
try {
const dir = join(home, '.claude');
const p = join(dir, 'settings.json');
let s: Record<string, unknown> = {};
if (existsSync(p)) {
- try { s = JSON.parse(readFileSync(p, 'utf8')) as Record<string, unknown>; } catch { s = {}; }
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(p, 'utf8'));
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return;
+ s = parsed as Record<string, unknown>;
+ } catch {
+ // Existing unreadable or malformed user config is not safe to mutate.
+ return;
+ }
}
if (s.skipDangerousModePermissionPrompt !== true || s.skipAutoPermissionPrompt !== true) {
s.skipDangerousModePermissionPrompt = true;
@@ -809,19 +801,55 @@ export function ensureClaudePermissionsAccepted(cwd?: string): void {
writeFileSync(p, JSON.stringify(s, null, 2), 'utf8');
}
} catch { /* best-effort; never block a spawn */ }
- // 2) Per-folder trust dialog gate (only when this cwd isn't already trusted).
- if (cwd) {
- try {
- const p = join(home, '.claude.json');
- let c: { projects?: Record<string, { hasTrustDialogAccepted?: boolean }> } = {};
- if (existsSync(p)) {
- try { c = JSON.parse(readFileSync(p, 'utf8')); } catch { c = {}; }
- }
- if (c.projects?.[cwd]?.hasTrustDialogAccepted !== true) {
- c.projects = c.projects ?? {};
- c.projects[cwd] = { ...(c.projects[cwd] ?? {}), hasTrustDialogAccepted: true };
- writeFileSync(p, JSON.stringify(c, null, 2), 'utf8');
+}
+
+type ClaudeProjectConfig = Record<string, unknown> & { hasTrustDialogAccepted?: boolean };
+type ClaudeConfig = Record<string, unknown> & { projects?: Record<string, ClaudeProjectConfig> };
+
+function ensureClaudeProjectTrust(home: string, cwd: string): void {
+ try {
+ const p = join(home, '.claude.json');
+ let c: ClaudeConfig = {};
+ if (existsSync(p)) {
+ try {
+ const parsed: unknown = JSON.parse(readFileSync(p, 'utf8'));
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return;
+ c = parsed as ClaudeConfig;
+ } catch {
+ // Existing unreadable or malformed user config is not safe to mutate.
+ return;
}
- } catch { /* best-effort */ }
+ }
+ if (c.projects?.[cwd]?.hasTrustDialogAccepted !== true) {
+ c.projects = c.projects ?? {};
+ c.projects[cwd] = { ...(c.projects[cwd] ?? {}), hasTrustDialogAccepted: true };
+ writeFileSync(p, JSON.stringify(c, null, 2), 'utf8');
+ }
+ } catch { /* best-effort; never block a spawn */ }
+}
+
+/** Idempotently pre-accept Claude Code's first-run prompts so agents spawned with
+ * `--permission-mode bypassPermissions` start cleanly. Without this, a fresh
+ * install shows an interactive "WARNING: Bypass Permissions mode … 1. No, exit /
+ * 2. Yes, I accept" prompt that the PTY can't answer in time, so the agent exits
+ * code 1 on its own (reported by multiple users).
+ *
+ * Two separate gates, written only when they aren't already satisfied (so we
+ * rarely touch files a running `claude` also writes):
+ * 1. `~/.claude/settings.json` → `skipDangerousModePermissionPrompt` +
+ * `skipAutoPermissionPrompt` — these gate the bypass-mode warning (global).
+ * 2. `~/.claude.json` → `projects[cwd].hasTrustDialogAccepted` — the per-folder
+ * "do you trust the files in this folder?" dialog.
+ *
+ * Each file is an independent best-effort boundary: unsafe existing contents
+ * are preserved without preventing the other file from being handled safely. */
+export function ensureClaudePermissionsAccepted(cwd?: string): void {
+ let home: string;
+ try { home = homedir(); } catch { return; }
+ if (!home) return;
+
+ ensureClaudeGlobalPermissions(home);
+ if (cwd) {
+ ensureClaudeProjectTrust(home, cwd);
}
}
diff --git a/test/claude-permissions-config.test.cjs b/test/claude-permissions-config.test.cjs
new file mode 100644
index 00000000..528c298e
--- /dev/null
+++ b/test/claude-permissions-config.test.cjs
@@ -0,0 +1,149 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const loadTs = require('./load-ts.cjs');
+
+// ensureClaudePermissionsAccepted() writes below os.homedir(). Redirect both
+// home variables before loading config.ts so this test can never touch the
+// user's real Claude configuration.
+const realHome = process.env.HOME;
+const realUserProfile = process.env.USERPROFILE;
+const home = fs.mkdtempSync(path.join(os.tmpdir(), 'md-claude-config-'));
+process.env.HOME = home;
+process.env.USERPROFILE = home;
+assert.equal(os.homedir(), home, 'home redirect failed; refusing to run against the real home');
+
+const userData = path.join(home, 'user-data');
+const electron = require.resolve('electron');
+require.cache[electron] = {
+ id: electron,
+ filename: electron,
+ loaded: true,
+ exports: { app: { getPath: () => userData } }
+};
+
+const { ensureClaudePermissionsAccepted } = loadTs('src/main/config.ts');
+const settingsDir = path.join(home, '.claude');
+const settingsPath = path.join(settingsDir, 'settings.json');
+const projectConfigPath = path.join(home, '.claude.json');
+const cwd = path.join(home, 'workspace', 'project');
+
+function writeSettings(contents) {
+ fs.mkdirSync(settingsDir, { recursive: true });
+ fs.writeFileSync(settingsPath, contents, 'utf8');
+}
+
+function resetConfigs() {
+ fs.rmSync(settingsDir, { recursive: true, force: true });
+ fs.rmSync(projectConfigPath, { force: true });
+}
+
+test.beforeEach(resetConfigs);
+test.after(() => {
+ if (realHome === undefined) delete process.env.HOME;
+ else process.env.HOME = realHome;
+ if (realUserProfile === undefined) delete process.env.USERPROFILE;
+ else process.env.USERPROFILE = realUserProfile;
+ fs.rmSync(home, { recursive: true, force: true });
+});
+
+test('preserves malformed Claude config files byte-for-byte', () => {
+ const malformedSettings = '{\n "env": {\n "CUSTOM_VALUE": "preserve-me"\n },\n';
+ const malformedProjectConfig = '{\n "projects": {\n';
+ writeSettings(malformedSettings);
+ fs.writeFileSync(projectConfigPath, malformedProjectConfig, 'utf8');
+
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.equal(fs.readFileSync(settingsPath, 'utf8'), malformedSettings);
+ assert.equal(fs.readFileSync(projectConfigPath, 'utf8'), malformedProjectConfig);
+});
+
+test('merges required fields into valid configs without losing unrelated data', () => {
+ writeSettings(JSON.stringify({
+ env: { CUSTOM_VALUE: 'preserve-me' },
+ hooks: { example: true }
+ }, null, 2));
+ fs.writeFileSync(projectConfigPath, JSON.stringify({
+ numStartups: 7,
+ projects: {
+ [cwd]: { allowedTools: ['Read'], custom: 'keep' },
+ '/another/project': { hasTrustDialogAccepted: false }
+ }
+ }, null, 2));
+
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.deepEqual(JSON.parse(fs.readFileSync(settingsPath, 'utf8')), {
+ env: { CUSTOM_VALUE: 'preserve-me' },
+ hooks: { example: true },
+ skipDangerousModePermissionPrompt: true,
+ skipAutoPermissionPrompt: true
+ });
+ assert.deepEqual(JSON.parse(fs.readFileSync(projectConfigPath, 'utf8')), {
+ numStartups: 7,
+ projects: {
+ [cwd]: {
+ allowedTools: ['Read'],
+ custom: 'keep',
+ hasTrustDialogAccepted: true
+ },
+ '/another/project': { hasTrustDialogAccepted: false }
+ }
+ });
+});
+
+test('creates minimal config files when they are missing', () => {
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.deepEqual(JSON.parse(fs.readFileSync(settingsPath, 'utf8')), {
+ skipDangerousModePermissionPrompt: true,
+ skipAutoPermissionPrompt: true
+ });
+ assert.deepEqual(JSON.parse(fs.readFileSync(projectConfigPath, 'utf8')), {
+ projects: { [cwd]: { hasTrustDialogAccepted: true } }
+ });
+});
+
+test('a malformed settings file does not prevent safe project trust updates', () => {
+ const malformedSettings = '{ "preserve": true,';
+ writeSettings(malformedSettings);
+ fs.writeFileSync(projectConfigPath, JSON.stringify({ custom: 'keep' }), 'utf8');
+
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.equal(fs.readFileSync(settingsPath, 'utf8'), malformedSettings);
+ assert.deepEqual(JSON.parse(fs.readFileSync(projectConfigPath, 'utf8')), {
+ custom: 'keep',
+ projects: { [cwd]: { hasTrustDialogAccepted: true } }
+ });
+});
+
+test('does not rewrite configs that already contain every required field', () => {
+ const settings = '{"skipDangerousModePermissionPrompt":true,"skipAutoPermissionPrompt":true}\n';
+ const projectConfig = JSON.stringify({
+ projects: { [cwd]: { hasTrustDialogAccepted: true } }
+ }) + '\n';
+ writeSettings(settings);
+ fs.writeFileSync(projectConfigPath, projectConfig, 'utf8');
+
+ ensureClaudePermissionsAccepted(cwd);
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.equal(fs.readFileSync(settingsPath, 'utf8'), settings);
+ assert.equal(fs.readFileSync(projectConfigPath, 'utf8'), projectConfig);
+});
+
+test('preserves existing config files with unsafe JSON root shapes', () => {
+ writeSettings('null\n');
+ fs.writeFileSync(projectConfigPath, '["keep"]\n', 'utf8');
+
+ ensureClaudePermissionsAccepted(cwd);
+
+ assert.equal(fs.readFileSync(settingsPath, 'utf8'), 'null\n');
+ assert.equal(fs.readFileSync(projectConfigPath, 'utf8'), '["keep"]\n');
+});