Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(claude): preserve user settings during hook installation

enes54fc5ca2939e
diff --git a/CLAUDE.md b/CLAUDE.md
index c6698c072..64440bf52 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2041,6 +2041,20 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
refuses TODAY, not on the cutoff** — which is why every token sweep must also call
`hookServer.forgetProvenNode`. `/hook/*` never 403s a missing token: the phone, the cross-instance
failover and every pre-token session legitimately have none.
+- **Shared Claude/Gemini settings are user data (issue #851).** The local hook install/remove
+ and Claude fullscreen writers share `core/agents/hooks/settings-file.ts`; SSH system/account
+ hook installs and fullscreen writes share `remote-settings-file.ts`. Only ENOENT / the remote
+ explicit missing-file status starts from `{}`. Empty/malformed/non-object/read-error settings
+ are preserved. Each transaction stages the complete output, takes a `.nodeterm-lock` directory,
+ compares its original bytes before rename, and preserves the file mode. Remote snapshots and
+ replacements travel on stdin, with a byte-count check against truncated transport; the shell
+ needs no Python/Node/jq. Local profiles resolve symlinks and lock/update the shared target,
+ rechecking resolution before publication; SSH skips a symlinked config safely. Grok's owned
+ file keeps its intentional malformed-file healing. A held or crash-left lock skips the update,
+ never gets stolen. External editors need not honor our lock: the final comparison detects edits
+ during merge/staging, but cannot eliminate an external write between comparison and rename.
+ No claim that the reporter's historical wipe was proven to take this path: the catch-to-empty
+ writer and its data loss were reproduced in fixture homes.
- **Fullscreen TUI (Claude)** — through the SAME `settings.json` seam the hook installer uses,
nodeterm ensures Claude's `"tui": "fullscreen"` so a session takes the alternate screen + mouse
and behaves natively in tmux (else a drag falls into copy-mode). Two guardrails: **write-if-absent**
@@ -2957,8 +2971,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
**from settings only** — never a dir named by the POST. **Removing a linked account only
forgets the record**: the `rm -rf` names `accountConfigDir(userData, id)` directly, so it is
structurally incapable of reaching outside the managed root even if the settings row is gone
- before the IPC lands. The hook installer writes `settings.json` THROUGH a symlink
- (`writeFileSync`) — a profile whose `settings.json` symlinks to `~/.claude/settings.json` (the
+ before the IPC lands. The hook installer resolves `settings.json` symlinks and atomically updates their target
+ (without replacing the link) — a profile whose `settings.json` symlinks to `~/.claude/settings.json` (the
two-profile layout) stays a symlink; pinned by `claude-accounts-link-symlink.test.ts`, and
switching that write to `renameAtomic` would be the regression (it replaces the link).
- **Observed account** (`ObservedClaudeAccount`, `NormalizedAgentEvent.account`) — which account
@@ -4599,8 +4613,8 @@ the target BEFORE both complete paths are quoted, then the shell preserves the w
while cleaning that exact temp. The temp leaf must stay independent of the target leaf — appending
`.uuid.tmp` to a valid `NAME_MAX` target makes the write impossible. It currently protects
filesystem API writes, tmux.conf, the private hook endpoint, node
-tokens, agent status and pending answers; generated hook scripts/config merges still use their
-existing direct writes and must not be described as atomic. Upload directories use UUIDs across app
+tokens, agent status and pending answers; some generated hook scripts/config merges still use direct writes; only the guarded shared
+Claude/Gemini settings transactions stage and rename here. Do not generalize that claim to every installer. Upload directories use UUIDs across app
processes. Downloads and media-cache copies use hidden UUID `.part` names; user-visible downloads
also hold an exclusive candidate lock until the rename and cleanup finish. Never simplify any of
those back to `<target>.tmp` / `<target>.part` or a read-only "does the destination exist?" check —
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 6573d6037..311ccff75 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -623,6 +623,18 @@ terminal opens keep their existing identity policy; Server Edition still require
for every control verb. Legacy mobile/SSH callers must present this instance’s node token for
command-bearing opens; this does not add a human-confirm dialog or change mobile transport APIs.
+## User-owned agent settings
+
+Claude/Gemini settings must go through the guarded transactions in
+`src/core/agents/hooks/{settings-file,remote-settings-file}.ts`. Only a confirmed missing file
+may start from `{}`; empty, malformed, non-object and unreadable files must survive unchanged.
+Keep unrelated settings and foreign hook handlers. Stage writes, serialize nodeterm writers,
+and compare the original bytes again before publishing; never use `cat … || echo '{}'` or a
+catch-all read fallback. Local symlinked profiles update the resolved target without replacing
+the link. SSH currently skips symlinked config files rather than guessing their target.
+A conflicting/stale lock skips installation; do not steal it from another process. These locks
+coordinate nodeterm, not external editors, so do not claim a filesystem-wide compare-and-swap.
+
## Testing
`npm test` must pass, and `npm run typecheck` is the fastest gate.
diff --git a/src/core/agents/hooks/claude-tui.test.ts b/src/core/agents/hooks/claude-tui.test.ts
index 5edc15a1d..fdddbeccc 100644
--- a/src/core/agents/hooks/claude-tui.test.ts
+++ b/src/core/agents/hooks/claude-tui.test.ts
@@ -68,11 +68,11 @@ describe('ensureFullscreenTuiInFile (fail-open file wrapper)', () => {
expect(readFileSync(p, 'utf8')).toBe('{ not json')
})
- it('an empty file is treated as {} and gets the key', () => {
+ it('preserves an empty file (it may be an interrupted user write)' , () => {
const p = path.join(dir, 'empty.json')
writeFileSync(p, '', 'utf8')
- expect(ensureFullscreenTuiInFile(p)).toBe(true)
+ expect(ensureFullscreenTuiInFile(p)).toBe(false)
expect(existsSync(p)).toBe(true)
- expect(JSON.parse(readFileSync(p, 'utf8'))).toEqual({ tui: TUI_FULLSCREEN })
+ expect(readFileSync(p, 'utf8')).toBe('')
})
})
diff --git a/src/core/agents/hooks/claude-tui.ts b/src/core/agents/hooks/claude-tui.ts
index 9424a0020..e68d8f4f3 100644
--- a/src/core/agents/hooks/claude-tui.ts
+++ b/src/core/agents/hooks/claude-tui.ts
@@ -9,10 +9,9 @@
// (FULLSCREEN_TUI_MIN_VERSION). This pure helper does not know the version; callers gate it.
//
// Merge semantics mirror install-helper.ts: pure transform on a parsed object (`ensureFullscreenTui`)
-// plus a thin fail-open file wrapper (`ensureFullscreenTuiInFile`) that tolerates a missing/empty/
-// corrupt settings.json the same way (defaults to `{}`), and only writes when something changed.
-import path from 'path'
-import { readFileSync, writeFileSync, mkdirSync } from 'fs'
+// plus a guarded file transaction. Only a missing file defaults to {}; malformed or unreadable
+// settings are preserved, and an existing tui value never causes a write.
+import { updateSettingsFile } from './settings-file'
/** The settings.json value that turns on Claude's fullscreen rendering. */
export const TUI_FULLSCREEN = 'fullscreen'
@@ -33,37 +32,9 @@ export function ensureFullscreenTui(config: TuiSettings): { config: TuiSettings;
/**
* Fail-open file wrapper for the local surfaces (system `~/.claude` + managed account dirs). Reads
* `configPath`, applies `ensureFullscreenTui`, and writes back ONLY if the key was added. Returns
- * whether it wrote. A read or write error is swallowed + warned, never thrown.
- *
- * A file that EXISTS but does not parse is left completely alone — unlike install-helper, which
- * normalizes it. The hook merge usually runs first and normalizes a corrupt file, but when it bails
- * early (its managed-script write failed) this pass would be the FIRST writer, and "replace the
- * user's settings with {tui:...}" is data loss a cosmetic rendering default can never justify.
- * Only a genuinely missing/empty file is treated as `{}`.
+ * whether it wrote. Errors skip the update without preventing a session from starting.
+ * Uses the same lock, validation and stale-snapshot protection as hook installation/removal.
*/
export function ensureFullscreenTuiInFile(configPath: string): boolean {
- let config: TuiSettings = {}
- let raw: string | null = null
- try {
- raw = readFileSync(configPath, 'utf8')
- } catch {
- raw = null // missing/unreadable → create from {}
- }
- if (raw !== null && raw.trim() !== '') {
- try {
- config = JSON.parse(raw) as TuiSettings
- } catch {
- return false // exists but unparseable: never replace the user's file
- }
- }
- const { config: next, changed } = ensureFullscreenTui(config)
- if (!changed) return false
- try {
- mkdirSync(path.dirname(configPath), { recursive: true })
- writeFileSync(configPath, JSON.stringify(next, null, 2), 'utf8')
- return true
- } catch (e) {
- console.warn('[claude-tui] fullscreen tui write failed', e)
- return false
- }
+ return updateSettingsFile(configPath, (config) => ensureFullscreenTui(config).config)
}
diff --git a/src/core/agents/hooks/install-helper.fs.test.ts b/src/core/agents/hooks/install-helper.fs.test.ts
index f12816fa7..640e2fe5f 100644
--- a/src/core/agents/hooks/install-helper.fs.test.ts
+++ b/src/core/agents/hooks/install-helper.fs.test.ts
@@ -81,3 +81,13 @@ describe('removeHooksFrom — uninstall also matched raw before the fix', () =>
expect(readConfig().hooks.Stop).toEqual([FOREIGN])
})
})
+
+describe('issue #851: shared settings are never healed by replacing user data', () => {
+ it.each(['{broken', '', 'null', '[]', '{"model":"keep","hooks":{"Stop":{}}}'])('preserves %s through install and uninstall', (raw) => {
+ writeFileSync(configPath(), raw)
+ install()
+ expect(readFileSync(configPath(), 'utf8')).toBe(raw)
+ removeHooksFrom({ configPath: configPath(), events: CLAUDE_HOOK_EVENTS, scriptFileName: 'claude.sh' })
+ expect(readFileSync(configPath(), 'utf8')).toBe(raw)
+ })
+})
diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.ts
index 9df5b72e1..0b8e15046 100644
--- a/src/core/agents/hooks/install-helper.ts
+++ b/src/core/agents/hooks/install-helper.ts
@@ -9,8 +9,10 @@
// the fresh one — matching on both sides through `normalizeHookCommand`, WITHOUT which
// Windows recognized none of its own entries and appended a fresh set per launch (#558);
// - preserve every other hook (other tools', other events);
-// - fail open: a missing/unparseable settings.json defaults to {} (install) / returns
-// early (remove); a write error is caught + warned, never thrown.
+// - fail open for sessions, preserve user settings on errors. Only ENOENT creates a new
+// shared config; malformed/read-error/concurrently modified files are left untouched.
+// Grok alone owns its config outright and can heal a malformed copy.
+import { updateSettingsFile } from './settings-file'
import path from 'path'
import { homedir } from 'os'
import { readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync } from 'fs'
@@ -42,9 +44,8 @@ export function writeManagedHookFileAtomic(
}
/**
- * Shared Claude/Gemini settings keep their existing write-through semantics so a user-owned
- * symlink and its target mode survive. Grok opts into atomic replacement for its nodeterm-owned
- * file under `$GROK_HOME/hooks/`.
+ * Legacy direct writer for owned config callers. Shared Claude/Gemini settings use the guarded
+ * updateSettingsFile transaction instead. Grok opts into atomic replacement for its owned file.
*/
export function writeManagedHookConfig(target: string, data: string, atomic = false): void {
if (atomic) writeManagedHookFileAtomic(target, data)
@@ -203,9 +204,23 @@ export function mergeManagedHook(
command: string,
events: readonly ManagedHookEvent[]
): HookSettings {
+ if (config.hooks !== undefined) {
+ if (!config.hooks || typeof config.hooks !== 'object' || Array.isArray(config.hooks)) throw new Error('Invalid hooks')
+ for (const defs of Object.values(config.hooks)) {
+ if (!Array.isArray(defs)) continue
+ for (const d of defs) {
+ if (!d || typeof d !== 'object' || (d.hooks !== undefined &&
+ (!Array.isArray(d.hooks) || d.hooks.some((h) => !h || typeof h !== 'object')))) throw new Error('Invalid hook handlers')
+ }
+ }
+ }
const isOurs = managedCommandMatcher(managedMarkerFor(command), true)
const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }
- const definitionsAt = (ev: string): HookDef[] => (Array.isArray(next.hooks![ev]) ? next.hooks![ev] : [])
+ const definitionsAt = (ev: string): HookDef[] => {
+ const defs = next.hooks![ev]
+ if (defs !== undefined && !Array.isArray(defs)) throw new Error('Invalid hook definitions')
+ return defs ?? []
+ }
for (const e of events) {
const ev = eventNameOf(e)
const matcher = matcherOf(e)
@@ -247,6 +262,10 @@ export function installHooksInto(opts: InstallHooksOptions): void {
if (!sp) return
const command = buildManagedHookCommand(sp)
+ if (!atomicConfig) {
+ updateSettingsFile(configPath, (config) => mergeManagedHook(config, command, events))
+ return
+ }
let config: Settings = {}
try {
config = JSON.parse(readFileSync(configPath, 'utf8')) as Settings
@@ -276,6 +295,19 @@ export function removeHooksFrom(opts: RemoveHooksOptions): void {
// Same normalized comparison as the installer — a raw `includes` left every entry behind on
// Windows (issue #558), so uninstall silently did nothing there.
const isOurs = managedCommandMatcher(`agent-hooks/${scriptFileName}`, false)
+ if (!atomicConfig) {
+ updateSettingsFile(configPath, (config: Settings) => {
+ if (!config.hooks) return config
+ for (const e of events) {
+ const ev = eventNameOf(e)
+ if (!Array.isArray(config.hooks[ev])) continue
+ config.hooks[ev] = stripManaged(config.hooks[ev], isOurs)
+ if (config.hooks[ev].length === 0) delete config.hooks[ev]
+ }
+ return config
+ })
+ return
+ }
let config: Settings
try {
config = JSON.parse(readFileSync(configPath, 'utf8')) as Settings
diff --git a/src/core/agents/hooks/remote-settings-file.ts b/src/core/agents/hooks/remote-settings-file.ts
new file mode 100644
index 000000000..e6f747952
--- /dev/null
+++ b/src/core/agents/hooks/remote-settings-file.ts
@@ -0,0 +1,49 @@
+// POSIX transport for the same guarded user-settings transaction as settings-file.ts.
+import { posixQuote } from '../../../shared/ssh'
+import { parseSettings } from './settings-file'
+
+type Result = { code: number; stdout: string }
+export type SettingsRunner = (command: string, stdin?: string) => Promise<Result>
+
+export async function updateRemoteSettingsFile(
+ file: string,
+ run: SettingsRunner,
+ update: (config: Record<string, unknown>) => Record<string, unknown>
+): Promise<boolean> {
+ const q = posixQuote(file)
+ const lock = posixQuote(`${file}.nodeterm-lock`)
+ try {
+ const read = await run(`if [ -L ${q} ]; then exit 1; elif [ -e ${q} ]; then [ -f ${q} ] && cat ${q}; else exit 44; fi`)
+ if (read.code !== 0 && read.code !== 44) return false
+ const before = read.code === 44 ? null : read.stdout
+ const config = before === null ? {} : parseSettings(before)
+ const original = JSON.stringify(config)
+ const updated = update(config)
+ if (before !== null && JSON.stringify(updated) === original) return false
+ const next = JSON.stringify(updated, null, 2)
+ // Both snapshots travel on stdin, never in argv. dd reads exactly the UTF-8 byte count;
+ // cat consumes the remaining new document. No remote Python/Node/jq dependency.
+ const count = Buffer.byteLength(before ?? '', 'utf8')
+ const unchanged = before === null
+ ? `[ ! -e ${q} ] && [ ! -L ${q} ]`
+ : `[ ! -L ${q} ] && [ -f ${q} ] && cmp -s "$nt_stage/before" ${q}`
+ const command = `umask 077
+mkdir -p "$(dirname ${q})" || exit 1
+mkdir ${lock} 2>/dev/null || exit 1
+nt_stage=''
+nt_lock=${lock}
+trap 'if [ -n "$nt_stage" ]; then rm -rf -- "$nt_stage"; fi; rmdir "$nt_lock"' EXIT
+nt_stage=$(mktemp -d "$(dirname ${q})/.nodeterm-settings-XXXXXXXX") || exit 1
+dd bs=1 count=${count} of="$nt_stage/before" 2>/dev/null || exit 1
+cat > "$nt_stage/next" || exit 1
+[ "$(wc -c < "$nt_stage/next")" -eq ${Buffer.byteLength(next, 'utf8')} ] || exit 1
+${unchanged} || exit 1
+${before === null ? ':' : `cp -p ${q} "$nt_stage/publish" || exit 1`}
+cat "$nt_stage/next" > "$nt_stage/publish" || exit 1
+${unchanged} || exit 1
+mv -f -- "$nt_stage/publish" ${q}`
+ return (await run(command, (before ?? '') + next)).code === 0
+ } catch {
+ return false
+ }
+}
diff --git a/src/core/agents/hooks/settings-file.read-error.test.ts b/src/core/agents/hooks/settings-file.read-error.test.ts
new file mode 100644
index 000000000..5c4e1cc74
--- /dev/null
+++ b/src/core/agents/hooks/settings-file.read-error.test.ts
@@ -0,0 +1,27 @@
+import { expect, it, vi } from 'vitest'
+import { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+vi.mock('fs', async (orig) => {
+ const actual = await orig<typeof import('fs')>()
+ return { ...actual, readFileSync: vi.fn(actual.readFileSync) }
+})
+import { updateSettingsFile } from './settings-file'
+import { ensureFullscreenTuiInFile } from './claude-tui'
+
+it.each(['EACCES', 'EIO'])('does not treat %s as missing settings', (code) => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'nt-read-error-'))
+ const file = path.join(dir, 'settings.json')
+ try {
+ writeFileSync(file, '{"model":"keep"}')
+ const fail = () => { throw Object.assign(new Error('fixture read failure'), { code }) }
+ vi.mocked(readFileSync).mockImplementation(fail)
+ expect(updateSettingsFile(file, () => ({ hooks: {} }))).toBe(false)
+ vi.mocked(readFileSync).mockImplementation(fail)
+ expect(ensureFullscreenTuiInFile(file)).toBe(false)
+ vi.mocked(readFileSync).mockReset()
+ expect(readFileSync(file, 'utf8')).toBe('{"model":"keep"}')
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+})
diff --git a/src/core/agents/hooks/settings-file.test.ts b/src/core/agents/hooks/settings-file.test.ts
new file mode 100644
index 000000000..2cc2e7696
--- /dev/null
+++ b/src/core/agents/hooks/settings-file.test.ts
@@ -0,0 +1,103 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, symlinkSync, lstatSync, chmodSync, statSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+import { spawnSync } from 'child_process'
+import { updateSettingsFile } from './settings-file'
+import { updateRemoteSettingsFile, type SettingsRunner } from './remote-settings-file'
+import { mergeManagedHook } from './install-helper'
+
+let dir: string
+let file: string
+beforeEach(() => {
+ dir = mkdtempSync(path.join(tmpdir(), "nt-settings-ö '"))
+ file = path.join(dir, 'settings.json')
+})
+afterEach(() => { vi.restoreAllMocks(); rmSync(dir, { recursive: true, force: true }) })
+const shell: SettingsRunner = async (command, stdin) => {
+ const result = spawnSync('/bin/sh', ['-c', command], { input: stdin, encoding: 'utf8' })
+ if (result.error) throw result.error
+ return { code: result.status ?? 1, stdout: result.stdout }
+}
+const merge = (config: Record<string, unknown>) => mergeManagedHook(config, "sh '/home/u/.nodeterm/agent-hooks/claude.sh'", ['Stop'])
+
+for (const remote of [false, true]) {
+ describe(remote ? 'remote settings shell transaction' : 'local settings transaction', () => {
+ const update = (transform = merge) => remote
+ ? updateRemoteSettingsFile(file, shell, transform)
+ : Promise.resolve(updateSettingsFile(file, transform))
+
+ it('creates a missing file and preserves settings, foreign handlers and mode on reinstall', async () => {
+ expect(await update()).toBe(true)
+ const foreign = { type: 'command', command: 'notify-me' }
+ const original = { outputStyle: 'caveman', model: 'opus[1m]', statusLine: { command: 'mine' }, hooks: {
+ Stop: [{ matcher: '*', hooks: [foreign, { type: 'command', command: "sh '/old/agent-hooks/claude.sh'" }] }]
+ } }
+ writeFileSync(file, JSON.stringify(original))
+ chmodSync(file, 0o640)
+ expect(await update()).toBe(true)
+ const result = JSON.parse(readFileSync(file, 'utf8'))
+ expect(result).toMatchObject({ outputStyle: original.outputStyle, model: original.model, statusLine: original.statusLine })
+ expect(result.hooks.Stop[0]).toEqual({ matcher: '*', hooks: [foreign] })
+ expect(statSync(file).mode & 0o777).toBe(0o640)
+ const once = readFileSync(file, 'utf8')
+ expect(await update()).toBe(false)
+ expect(readFileSync(file, 'utf8')).toBe(once)
+ })
+
+ it.each(['', '{broken', 'null', '[]', '42', '{"hooks":null}', '{"hooks":{"Stop":{}}}', '{"hooks":{"Stop":[null]}}', '{"hooks":{"Stop":[{"hooks":[null]}]}}'])('preserves malformed settings: %s', async (raw) => {
+ writeFileSync(file, raw)
+ expect(await update()).toBe(false)
+ expect(readFileSync(file, 'utf8')).toBe(raw)
+ })
+
+ it('does not replace a directory/read error with settings', async () => {
+ mkdirSync(file)
+ expect(await update()).toBe(false)
+ expect(lstatSync(file).isDirectory()).toBe(true)
+ })
+
+ it('preserves symlinks and unrelated target settings', async () => {
+ const target = path.join(dir, 'target')
+ writeFileSync(target, '{"model":"keep"}')
+ symlinkSync(target, file)
+ expect(await update()).toBe(!remote)
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ expect(JSON.parse(readFileSync(target, 'utf8')).model).toBe('keep')
+ })
+
+ it('leaves dangling symlinks untouched', async () => {
+ symlinkSync(path.join(dir, 'absent'), file)
+ expect(await update()).toBe(false)
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ })
+
+ it('does not take over another nodeterm writer lock', async () => {
+ writeFileSync(file, '{}')
+ mkdirSync(`${file}.nodeterm-lock`)
+ expect(await update()).toBe(false)
+ expect(readFileSync(file, 'utf8')).toBe('{}')
+ expect(lstatSync(`${file}.nodeterm-lock`).isDirectory()).toBe(true)
+ })
+
+ it.each([false, true])('refuses stale snapshots including concurrent creation (missing=%s)', async (missing) => {
+ if (!missing) writeFileSync(file, '{}')
+ const newer = '{"model":"newer", "hooks":{"Stop":[{"hooks":[{"command":"keep-me"}]}]}}'
+ expect(await update((config) => { writeFileSync(file, newer); return merge(config) })).toBe(false)
+ expect(readFileSync(file, 'utf8')).toBe(newer)
+ })
+ })
+}
+
+it('remote read failure is not absence, even with valid partial stdout', async () => {
+ const run = vi.fn(async () => ({ code: 1, stdout: '{}' }))
+ expect(await updateRemoteSettingsFile(file, run, merge)).toBe(false)
+ expect(run).toHaveBeenCalledTimes(1)
+})
+
+it('remote staged input truncation cannot publish a partial document', async () => {
+ writeFileSync(file, '{}')
+ const run: SettingsRunner = (cmd, input) => shell(cmd, input === undefined ? undefined : input.slice(0, -8))
+ expect(await updateRemoteSettingsFile(file, run, merge)).toBe(false)
+ expect(readFileSync(file, 'utf8')).toBe('{}')
+})
diff --git a/src/core/agents/hooks/settings-file.ts b/src/core/agents/hooks/settings-file.ts
new file mode 100644
index 000000000..8e164a7ed
--- /dev/null
+++ b/src/core/agents/hooks/settings-file.ts
@@ -0,0 +1,67 @@
+// User-owned JSON is never repaired by an installer. Only ENOENT means a new config.
+import { lstatSync, readFileSync, mkdirSync, rmdirSync, statSync, writeFileSync, rmSync, chmodSync, realpathSync } from 'fs'
+import path from 'path'
+import { renameAtomicSync, tempNameFor } from '../../fs-atomic'
+
+export function parseSettings(raw: string): Record<string, unknown> {
+ const value: unknown = JSON.parse(raw)
+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Settings must be an object')
+ return value as Record<string, unknown>
+}
+
+function snapshot(file: string): string | null {
+ try {
+ // Do not replace links (including dangling links), devices, or directories.
+ if (!lstatSync(file).isFile()) throw new Error('Settings must be a regular file')
+ return readFileSync(file, 'utf8')
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code === 'ENOENT') return null
+ throw e
+ }
+}
+
+function settingsTarget(file: string): string {
+ try {
+ return realpathSync(file)
+ } catch (e) {
+ if ((e as NodeJS.ErrnoException).code !== 'ENOENT') throw e
+ // A missing file is creatable; a dangling symlink is not ours to repair.
+ try { if (lstatSync(file).isSymbolicLink()) throw new Error('Dangling settings link') } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
+ }
+ return path.join(realpathSync(path.dirname(file)), path.basename(file))
+ }
+}
+
+/** Serialize our writers, stage before publishing, and refuse stale snapshots. Other programs
+ * do not honor our lock: the final comparison narrows, but cannot eliminate, their rename race. */
+export function updateSettingsFile(requested: string, update: (config: Record<string, unknown>) => Record<string, unknown>): boolean {
+ let lock = ''
+ let locked = false
+ let tmp: string | undefined
+ try {
+ mkdirSync(path.dirname(requested), { recursive: true })
+ const file = settingsTarget(requested)
+ lock = `${file}.nodeterm-lock`
+ mkdirSync(lock)
+ locked = true
+ const before = snapshot(file)
+ const config = before === null ? {} : parseSettings(before)
+ const original = JSON.stringify(config)
+ const updated = update(config)
+ if (before !== null && JSON.stringify(updated) === original) return false
+ const next = JSON.stringify(updated, null, 2)
+ tmp = tempNameFor(file)
+ const mode = before === null ? 0o600 : statSync(file).mode & 0o777
+ writeFileSync(tmp, next, { flag: 'wx', mode })
+ chmodSync(tmp, mode)
+ if (settingsTarget(requested) !== file || snapshot(file) !== before) return false
+ renameAtomicSync(tmp, file)
+ return true
+ } catch {
+ return false // fail open for the session, fail closed for the user's settings
+ } finally {
+ try { if (tmp) rmSync(tmp, { force: true }) } catch { /* best-effort cleanup */ }
+ try { if (locked) rmdirSync(lock) } catch { /* never break session startup */ }
+ }
+}
diff --git a/src/core/claude-accounts-link-symlink.test.ts b/src/core/claude-accounts-link-symlink.test.ts
index 7466abd0d..9014fd06d 100644
--- a/src/core/claude-accounts-link-symlink.test.ts
+++ b/src/core/claude-accounts-link-symlink.test.ts
@@ -12,11 +12,8 @@
* installer): the property under test is what the REAL writer does to a REAL symlink, and a mock
* of the writer is exactly the fixture that cannot discriminate.
*
- * MUTATION: swap `installHooksInto`'s `writeFileSync` for an unlink-then-write, or for the atomic
- * write-temp-then-rename this repo uses for PUBLISHED files, and the symlink assertion reddens.
- * (Atomic rename is the right rule for a file we own and the wrong one here: `renameAtomic`
- * REPLACES the link with the temp file, which is the fork this test exists to prevent. That is
- * why `installHooksInto` is left writing in place — the file belongs to the CLI, not to us.)
+ * MUTATION: publish the staged config to the symlink path instead of its resolved target.
+ * The symlink assertion must fail: atomic publication is safe only at the shared target.
*/
import { describe, it, expect, beforeEach, afterEach } from 'vitest'
import {
diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.ts
index f58826501..034bf3f39 100644
--- a/src/core/claude-accounts-service.ts
+++ b/src/core/claude-accounts-service.ts
@@ -247,7 +247,7 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {
}
// Same two writes an ADDED account gets, so a linked account reports agent status from its
// very next session. `installClaudeHooksInto` MERGES into an existing settings.json and writes
- // it back through `writeFileSync`, which follows a symlink — the two-profile layout where
+ // to its resolved target without replacing a symlink — the two-profile layout where
// `<dir>/settings.json` is a symlink into `~/.claude/` keeps its symlink and the shared target
// gains the managed hook (pinned by test).
installClaudeHooksInto(configDir)
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 802183d7b..a4fe2297d 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -34,7 +34,8 @@ function harness(
}
// resolve the remote $HOME probe → absolute remote paths build from this.
if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }
- if (joined.includes('cat /home/u/.claude/settings.json')) return { code: 0, stdout: '{}' }
+ if (joined.includes("cat '/home/u/.claude/settings.json'")) return { code: 0, stdout: '{}' }
+ if (joined.includes('else exit 44; fi')) return { code: 44, stdout: '' }
// the end-to-end tunnel verification curl (runs in ARGS, unlike the script's stdin curl).
if (joined.includes('%{http_code}')) return { code: 0, stdout: verifyAnswers.shift() ?? '204' }
return { code: 0, stdout: '' }
@@ -75,7 +76,7 @@ describe('RemoteHooks.setup', () => {
).toBe(true)
// managed script written to the absolute path + config merged with the guarded command.
expect(joined.some((j) => j.includes(`cat > '/home/u/.nodeterm/agent-hooks/claude.sh'`))).toBe(true)
- expect(joined.some((j) => j.includes(`cat > '/home/u/.claude/settings.json'`))).toBe(true)
+ expect(joined.some((j) => j.includes(`mv -f -- "$nt_stage/publish" '/home/u/.claude/settings.json'`))).toBe(true)
expect(calls.some((c) => (c.stdin ?? '').includes('--unix-socket'))).toBe(true)
// The merged command guards on the script still existing — a removed ~/.nodeterm must not
// make every prompt fail the hook (a non-zero UserPromptSubmit hook blocks the prompt).
@@ -197,7 +198,7 @@ describe('RemoteHooks.setup', () => {
if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }
if (joined.includes('-O forward')) return { code: ++forwards === 1 ? 1 : 0, stdout: '' }
if (joined.includes('%{http_code}')) return { code: 0, stdout: '204' }
- if (joined.includes('cat /home/u/.claude/settings.json')) return { code: 0, stdout: '{}' }
+ if (joined.includes("cat '/home/u/.claude/settings.json'")) return { code: 0, stdout: '{}' }
return { code: 0, stdout: '' }
})
const rh = new RemoteHooks({ run })
@@ -254,7 +255,7 @@ describe('RemoteHooks.setup — a hostile remote $HOME', () => {
(j) => j.includes('cat > ') && j.includes("/Users/Enes K/.nodeterm/hook-endpoint-p1.env'")
)
).toBe(true)
- expect(joined.some((j) => j.includes(`cat > '/Users/Enes K/.claude/settings.json'`))).toBe(true)
+ expect(joined.some((j) => j.includes(`mv -f -- "$nt_stage/publish" '/Users/Enes K/.claude/settings.json'`))).toBe(true)
// No path derived from $HOME survives UNQUOTED in any remote SHELL LINE (the last argv element
// of an ssh child is the command the remote shell parses; the `-R` forward spec is an ssh
// OPTION, not a shell word, so it is excluded by construction).
@@ -495,7 +496,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {
await rh.ensureFullscreenTui(conn, '/s.sock', '/home/u')
const write = calls.find((c) => isWriteTo(c.args, target))
expect(write).toBeTruthy()
- expect(JSON.parse(write!.stdin!)).toEqual({ hooks: { Stop: [] }, tui: 'fullscreen' })
+ expect(JSON.parse(write!.stdin!.slice(JSON.stringify({ hooks: { Stop: [] } }).length))).toEqual({ hooks: { Stop: [] }, tui: 'fullscreen' })
})
it('never overwrites an existing tui value (write-if-absent) — no write issued', async () => {
@@ -887,7 +888,7 @@ describe('RemoteHooks.setup — the host $HOME is data, not truth', () => {
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
expect(res?.endpointPath).toBe('/home/gökhan/.nodeterm/hook-endpoint-p1.env')
const joined = calls.map((c) => c.args.join(' '))
- expect(joined.some((j) => j.includes(`cat > '/home/gökhan/.claude/settings.json'`))).toBe(true)
+ expect(joined.some((j) => j.includes(`mv -f -- "$nt_stage/publish" '/home/gökhan/.claude/settings.json'`))).toBe(true)
})
})
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index bd064d53c..b485cea9e 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -11,6 +11,7 @@ import { GROK_EVENTS } from '../../core/agents/hooks/grok'
import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'
import { hookServer } from '../../core/agents/hook-server'
+import { updateRemoteSettingsFile } from '../../core/agents/hooks/remote-settings-file'
import { remoteAtomicWrite } from '../remote-atomic-write'
import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
@@ -36,7 +37,7 @@ import {
type HooksConfig as CodexHooksConfig
} from '../../core/agents/hooks/codex'
import { upsertHookTrustEntriesInContent } from '../../core/agents/hooks/codex-trust'
-import { ensureFullscreenTui, type TuiSettings } from '../../core/agents/hooks/claude-tui'
+import { ensureFullscreenTui } from '../../core/agents/hooks/claude-tui'
import {
CONTROL_SHIM_SCRIPT,
buildCanvasControlInstructions,
@@ -409,23 +410,9 @@ export class RemoteHooks {
),
buildManagedScript(target.agentId, REMOTE_IDENTITY_ROOT)
)
- const { stdout: cfgRaw } = await this.r.run(
- childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)
- )
- let cfg: HookSettings = {}
- try {
- cfg = JSON.parse(cfgRaw || '{}') as HookSettings
- } catch {
- cfg = {}
- }
- const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), target.events)
- await this.r.run(
- // `$(dirname …)` is itself QUOTED (same reason as installGrokRemote): a home with a
- // space would otherwise word-split into two mkdir args, the directory would never be
- // created, and the correctly-quoted `cat >` would then fail — silently, fail-open.
- childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),
- JSON.stringify(merged, null, 2)
- )
+ await updateRemoteSettingsFile(config,
+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),
+ (cfg) => mergeManagedHook(cfg, buildManagedHookCommand(script), target.events))
} catch {
/* fail-open: this agent's remote sessions run without status hooks */
}
@@ -644,20 +631,9 @@ export class RemoteHooks {
childArgs(conn, controlPath, `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),
buildManagedScript('claude', REMOTE_IDENTITY_ROOT)
)
- const { stdout: cfgRaw } = await this.r.run(
- childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)
- )
- let cfg: HookSettings = {}
- try {
- cfg = JSON.parse(cfgRaw || '{}') as HookSettings
- } catch {
- cfg = {}
- }
- const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), events)
- await this.r.run(
- childArgs(conn, controlPath, `mkdir -p ${posixQuote(accountDir)} && cat > ${posixQuote(config)}`),
- JSON.stringify(merged, null, 2)
- )
+ await updateRemoteSettingsFile(config,
+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),
+ (cfg) => mergeManagedHook(cfg, buildManagedHookCommand(script), events))
} catch {
/* fail-open: the account session simply runs without status hooks */
}
@@ -882,34 +858,9 @@ export class RemoteHooks {
/** Read-merge-write the fullscreen-tui key at one absolute remote config path, over the master.
* Same read-if-present, write-only-if-changed, fail-open mechanics as the hook merge above. */
private async ensureFullscreenTuiAt(conn: SshConnection, controlPath: string, config: string): Promise<void> {
- try {
- const { stdout: raw } = await this.r.run(
- childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)
- )
- let cfg: TuiSettings = {}
- if (raw.trim() && raw.trim() !== '{}') {
- try {
- cfg = JSON.parse(raw) as TuiSettings
- } catch {
- // The file EXISTS but does not parse (`|| echo '{}'` only fires when it is missing):
- // never replace the user's settings with {tui:...} — same guard as the local wrapper.
- return
- }
- }
- const { config: next, changed } = ensureFullscreenTui(cfg)
- if (!changed) return // key already present (any value) → never overwrite the user's `/tui`
- await this.r.run(
- // `$(dirname …)` QUOTED, like the other three sites. Unquoted, a home with a space
- // (`/Users/Enes Kirca`) word-splits the substitution into two mkdir args — measured
- // ARGC=2 — so junk directories are created, the correctly-quoted `cat >` then fails, and
- // the catch below swallows it. Symptom: fullscreen-TUI silently never written for any
- // macOS user whose home has a space in it.
- childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),
- JSON.stringify(next, null, 2)
- )
- } catch {
- /* fail-open: a failed remote read/write must never break the connect */
- }
+ await updateRemoteSettingsFile(config,
+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),
+ (cfg) => ensureFullscreenTui(cfg).config)
}
/**
diff --git a/src/main/remote-ssh/remote-settings-preservation.test.ts b/src/main/remote-ssh/remote-settings-preservation.test.ts
new file mode 100644
index 000000000..0b4b5a2c2
--- /dev/null
+++ b/src/main/remote-ssh/remote-settings-preservation.test.ts
@@ -0,0 +1,50 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { spawnSync } from 'child_process'
+import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'
+import path from 'path'
+import { tmpdir } from 'os'
+import { RemoteHooks } from './remote-hooks'
+
+let home: string
+beforeEach(() => { home = mkdtempSync(path.join(tmpdir(), 'nt-851-home-')) })
+afterEach(() => rmSync(home, { recursive: true, force: true }))
+const conn = { host: 'fixture', user: 'fixture' }
+for (const account of [false, true]) {
+ describe(account ? 'remote Claude account settings' : 'remote system Claude settings', () => {
+ async function install(raw: string, race = false) {
+ const file = path.join(home, account ? '.nodeterm/claude-accounts/acc/settings.json' : '.claude/settings.json')
+ mkdirSync(path.dirname(file), { recursive: true })
+ writeFileSync(file, raw)
+ let changes = 0
+ const rh = new RemoteHooks({ run: async (args, stdin) => {
+ const command = args.at(-1)!
+ if (race && stdin !== undefined && command.includes('.nodeterm-lock')) writeFileSync(file, JSON.stringify({ model: `concurrent-${++changes}` }))
+ const result = spawnSync('/bin/sh', ['-c', command], { input: stdin, encoding: 'utf8' })
+ if (result.error) throw result.error
+ return { code: result.status ?? 1, stdout: result.stdout }
+ } })
+ if (account) await rh.installIntoAccountDir(conn, '/fixture.sock', home, 'acc')
+ else await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`, {
+ agentId: 'claude', config: '.claude/settings.json', events: ['Stop']
+ })
+ if (account) await rh.ensureFullscreenTuiInAccountDir(conn, '/fixture.sock', home, 'acc')
+ else await rh.ensureFullscreenTui(conn, '/fixture.sock', home)
+ return readFileSync(file, 'utf8')
+ }
+
+ it.each(['{broken', '', 'null', '[]'])('neither hooks nor TUI destroys malformed settings: %s', async (raw) => {
+ expect(await install(raw)).toBe(raw)
+ })
+
+ it('preserves unrelated settings and foreign hooks through both writers', async () => {
+ const foreign = { hooks: [{ type: 'command', command: 'foreign-command' }] }
+ const result = JSON.parse(await install(JSON.stringify({ model: 'opus', outputStyle: 'caveman', hooks: { Stop: [foreign] } })))
+ expect(result).toMatchObject({ model: 'opus', outputStyle: 'caveman', tui: 'fullscreen' })
+ expect(result.hooks.Stop[0]).toEqual(foreign)
+ })
+
+ it('cannot overwrite another writer between the SSH read and publish', async () => {
+ expect(await install('{}', true)).toBe('{"model":"concurrent-2"}')
+ })
+ })
+}