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(hooks): restore blank settings and guarded SSH symlink updates

reviewb0d001894fa3
diff --git a/CLAUDE.md b/CLAUDE.md
index 64440bf52..4d999a18d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2044,14 +2044,16 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
- **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,
+ explicit missing-file status or a successfully read empty/whitespace file starts from `{}`.
+ 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
+ rechecking resolution before publication. SSH does the same with plain readlink + cd -P
+ (macOS-compatible, no GNU -f), bounding cycles and refusing dangling links/newline paths.
+ Grok's owned file heals malformed JSON and hook shapes by rebuilding its managed config.
+ A held or crash-left lock skips the update with a diagnostic naming the lock and instructing
+ the user to stop writers before inspecting/removing a stale lock; it 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.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 311ccff75..0de0aba61 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -626,13 +626,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
## 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.
+`src/core/agents/hooks/{settings-file,remote-settings-file}.ts`. Confirmed absence or a successfully read empty/whitespace file may start from `{}`;
+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
+catch-all read fallback. Local and SSH symlinked profiles update and lock the resolved target without replacing
+the link; recheck resolution before publishing. SSH uses plain readlink and cd -P (no GNU -f),
+and refuses dangling/cyclic links and newline paths. A conflicting/stale lock skips installation
+with a diagnostic naming the lock and safe manual recovery; 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
diff --git a/src/core/agents/hooks/claude-tui.test.ts b/src/core/agents/hooks/claude-tui.test.ts
index fdddbeccc..1e6426c13 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('preserves an empty file (it may be an interrupted user write)' , () => {
+ it('initializes a successfully read empty file' , () => {
const p = path.join(dir, 'empty.json')
writeFileSync(p, '', 'utf8')
- expect(ensureFullscreenTuiInFile(p)).toBe(false)
+ expect(ensureFullscreenTuiInFile(p)).toBe(true)
expect(existsSync(p)).toBe(true)
- expect(readFileSync(p, 'utf8')).toBe('')
+ expect(JSON.parse(readFileSync(p, 'utf8'))).toEqual({ tui: TUI_FULLSCREEN })
})
})
diff --git a/src/core/agents/hooks/install-helper.fs.test.ts b/src/core/agents/hooks/install-helper.fs.test.ts
index 640e2fe5f..322dd9c69 100644
--- a/src/core/agents/hooks/install-helper.fs.test.ts
+++ b/src/core/agents/hooks/install-helper.fs.test.ts
@@ -83,7 +83,7 @@ describe('removeHooksFrom — uninstall also matched raw before the fix', () =>
})
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) => {
+ 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)
@@ -91,3 +91,12 @@ describe('issue #851: shared settings are never healed by replacing user data',
expect(readFileSync(configPath(), 'utf8')).toBe(raw)
})
})
+
+
+describe('owned Grok config repair', () => {
+ it.each(['{broken', '{"hooks":[]}', '{"hooks":{"Stop":"x"}}', 'null'])('heals %s only for an owned config', (raw) => {
+ writeFileSync(configPath(), raw)
+ installHooksInto({ agentId: 'grok', scriptFileName: 'grok.sh', configPath: configPath(), events: ['Stop'], atomicConfig: true })
+ expect(readConfig().hooks.Stop[0].hooks[0].command).toContain('grok.sh')
+ })
+})
diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.ts
index 0b8e15046..8943063dc 100644
--- a/src/core/agents/hooks/install-helper.ts
+++ b/src/core/agents/hooks/install-helper.ts
@@ -269,10 +269,11 @@ export function installHooksInto(opts: InstallHooksOptions): void {
let config: Settings = {}
try {
config = JSON.parse(readFileSync(configPath, 'utf8')) as Settings
+ config = mergeManagedHook(config, command, events)
} catch {
- config = {}
+ // This branch owns the entire Grok config, including malformed hook shapes.
+ config = mergeManagedHook({}, command, events)
}
- config = mergeManagedHook(config, command, events)
try {
mkdirSync(path.dirname(configPath), { recursive: true })
writeManagedHookConfig(configPath, JSON.stringify(config, null, 2), atomicConfig)
diff --git a/src/core/agents/hooks/remote-settings-file.ts b/src/core/agents/hooks/remote-settings-file.ts
index e6f747952..a3e381734 100644
--- a/src/core/agents/hooks/remote-settings-file.ts
+++ b/src/core/agents/hooks/remote-settings-file.ts
@@ -5,17 +5,56 @@ import { parseSettings } from './settings-file'
type Result = { code: number; stdout: string }
export type SettingsRunner = (command: string, stdin?: string) => Promise<Result>
+// macOS readlink has no -f. Resolve each link relative to its physical parent with plain
+// readlink + cd -P instead; aliases then share one lock. Bound cycles and reject ambiguous
+// newline paths (the read protocol uses a line header). Never create dangling link targets.
+const resolveTarget = `nt_resolve() {
+ nt_file=$1
+ nt_links=0
+ while :; do
+ case "$nt_file" in *'
+'*) return 1;; esac
+ nt_parent=$(CDPATH= cd -P "$(dirname "$nt_file")" && pwd -P && printf '.') || return 1
+ nt_parent=\${nt_parent%.}
+ nt_parent=\${nt_parent%'
+'}
+ case "$nt_parent" in *'
+'*) return 1;; esac
+ nt_file="$nt_parent/$(basename "$nt_file")"
+ if [ ! -L "$nt_file" ]; then break; fi
+ nt_links=$((nt_links + 1))
+ [ "$nt_links" -le 40 ] || return 1
+ nt_link=$(readlink "$nt_file" && printf '.') || return 1
+ nt_link=\${nt_link%.}
+ nt_link=\${nt_link%'
+'}
+ case "$nt_link" in /*) nt_file=$nt_link;; *) nt_file="$nt_parent/$nt_link";; esac
+ done
+ [ "$nt_links" -eq 0 ] || [ -f "$nt_file" ] || return 1
+}`
+
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`)
+ const requested = posixQuote(file)
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 read = await run(`${resolveTarget}
+umask 077
+mkdir -p "$(dirname ${requested})" || exit 1
+nt_resolve ${requested} || exit 1
+printf '%s\\n' "$nt_file"
+if [ -e "$nt_file" ]; then [ -f "$nt_file" ] && cat "$nt_file"; else exit 44; fi`)
+ if (read.code !== 0 && read.code !== 44) throw new Error('Remote settings read failed')
+ const separator = read.stdout.indexOf('\n')
+ const target = read.stdout.slice(0, separator)
+ if (separator < 1 || !target.startsWith('/')) throw new Error('Remote settings target missing')
+ const q = posixQuote(target)
+ const lockPath = `${target}.nodeterm-lock`
+ const lock = posixQuote(lockPath)
+ if (read.code === 44 && read.stdout.slice(separator + 1) !== '') throw new Error('Invalid missing-file response')
+ const before = read.code === 44 ? null : read.stdout.slice(separator + 1)
const config = before === null ? {} : parseSettings(before)
const original = JSON.stringify(config)
const updated = update(config)
@@ -24,15 +63,16 @@ export async function updateRemoteSettingsFile(
// 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
+ const unchanged = `nt_resolve ${requested} && [ "$nt_file" = ${q} ] && ` + (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
+ : `[ ! -L ${q} ] && [ -f ${q} ] && cmp -s "$nt_stage/before" ${q}`)
+ const command = `${resolveTarget}
+umask 077
+mkdir ${lock} 2>/dev/null || exit 73
nt_stage=''
nt_lock=${lock}
-trap 'if [ -n "$nt_stage" ]; then rm -rf -- "$nt_stage"; fi; rmdir "$nt_lock"' EXIT
+trap 'if [ -n "$nt_stage" ]; then rm -rf -- "$nt_stage"; fi; rmdir "$nt_lock"' 0
+trap 'exit 1' HUP INT TERM
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
@@ -42,8 +82,16 @@ ${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
+ const result = await run(command, (before ?? '') + next)
+ if (result.code === 73) {
+ console.warn(`[agent-hooks] Remote settings lock unavailable: ${lockPath}. Installation skipped; if it persists, stop nodeterm writers and inspect/remove the stale lock before retrying.`)
+ return false
+ }
+ if (result.code !== 0) throw new Error('Remote settings publication failed (conflict or I/O error)')
+ return true
} catch {
+ // Do not log parse errors: their messages can include private settings contents.
+ console.warn(`[agent-hooks] Remote settings unchanged: ${file} (read, parse, resolution or publication failed).`)
return false
}
}
diff --git a/src/core/agents/hooks/settings-file.test.ts b/src/core/agents/hooks/settings-file.test.ts
index feff02a73..f1c08e414 100644
--- a/src/core/agents/hooks/settings-file.test.ts
+++ b/src/core/agents/hooks/settings-file.test.ts
@@ -2,7 +2,7 @@ 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 { spawn, spawnSync } from 'child_process'
import { updateSettingsFile } from './settings-file'
import { updateRemoteSettingsFile, type SettingsRunner } from './remote-settings-file'
import { mergeManagedHook } from './install-helper'
@@ -22,7 +22,7 @@ const shell: SettingsRunner = async (command, stdin) => {
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', () => {
+ describe.skipIf(remote && process.platform === 'win32')(remote ? 'remote settings shell transaction' : 'local settings transaction', () => {
const update = (transform = merge) => remote
? updateRemoteSettingsFile(file, shell, transform)
: Promise.resolve(updateSettingsFile(file, transform))
@@ -42,26 +42,47 @@ for (const remote of [false, true]) {
const once = readFileSync(file, 'utf8')
expect(await update()).toBe(false)
expect(readFileSync(file, 'utf8')).toBe(once)
- expect(statSync(file).mode & 0o777).toBe(0o640)
+ if (process.platform !== 'win32') expect(statSync(file).mode & 0o777).toBe(0o640)
})
- it.each(['', '{broken', 'null', '[]', '42', '{"hooks":null}', '{"hooks":{"Stop":{}}}', '{"hooks":{"Stop":[null]}}', '{"hooks":{"Stop":[{"hooks":[null]}]}}'])('preserves malformed settings: %s', async (raw) => {
+ it.each(['{broken', 'null', '[]', '42', '{"hooks":null}', '{"hooks":[]}', '{"hooks":{"Stop":"x"}}', '{"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.each(['', ' \t\r\n'])('installs into successfully read blank settings: %j', async (raw) => {
+ writeFileSync(file, raw)
+ expect(await update()).toBe(true)
+ expect(JSON.parse(readFileSync(file, 'utf8')).hooks.Stop).toHaveLength(1)
+ })
+
+ it.skipIf(process.platform === 'win32')('refuses symlink retargeting during the update', async () => {
+ const target = path.join(dir, 'first')
+ const other = path.join(dir, 'second')
+ writeFileSync(target, '{}')
+ writeFileSync(other, '{}')
+ symlinkSync(target, file)
+ expect(await update((config) => {
+ rmSync(file)
+ symlinkSync(other, file)
+ return merge(config)
+ })).toBe(false)
+ expect(readFileSync(target, 'utf8')).toBe('{}')
+ expect(readFileSync(other, 'utf8')).toBe('{}')
+ })
+
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 () => {
+ it.skipIf(process.platform === 'win32')('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(await update()).toBe(true)
expect(lstatSync(file).isSymbolicLink()).toBe(true)
expect(JSON.parse(readFileSync(target, 'utf8')).model).toBe('keep')
})
@@ -73,7 +94,7 @@ for (const remote of [false, true]) {
expect(lstatSync(file).isFIFO()).toBe(true)
})
- it('leaves dangling symlinks untouched', async () => {
+ it.skipIf(process.platform === 'win32')('leaves dangling symlinks untouched', async () => {
symlinkSync(path.join(dir, 'absent'), file)
expect(await update()).toBe(false)
expect(lstatSync(file).isSymbolicLink()).toBe(true)
@@ -82,9 +103,12 @@ for (const remote of [false, true]) {
it('does not take over another nodeterm writer lock', async () => {
writeFileSync(file, '{}')
mkdirSync(`${file}.nodeterm-lock`)
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {})
expect(await update()).toBe(false)
expect(readFileSync(file, 'utf8')).toBe('{}')
expect(lstatSync(`${file}.nodeterm-lock`).isDirectory()).toBe(true)
+ expect(warning).toHaveBeenCalledWith(expect.stringContaining(`${file}.nodeterm-lock`))
+ expect(warning).toHaveBeenCalledWith(expect.stringContaining('stop nodeterm writers'))
})
it.each([false, true])('refuses stale snapshots including concurrent creation (missing=%s)', async (missing) => {
@@ -96,15 +120,109 @@ for (const remote of [false, true]) {
})
}
-it('remote read failure is not absence, even with valid partial stdout', async () => {
- const run = vi.fn(async () => ({ code: 1, stdout: '{}' }))
+it.each(['', '{}', '/tmp/settings.json\n{}'])('remote read failure is not absence: %j', async (stdout) => {
+ 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 () => {
+it.skipIf(process.platform === 'win32')('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('{}')
})
+
+// These are real POSIX shell fixtures; SSH's target filesystem is POSIX even for a Windows viewer.
+describe.skipIf(process.platform === 'win32')('remote link aliases', () => {
+ it('follows relative link chains and physical parent directories with portable readlink', async () => {
+ const real = path.join(dir, 'real')
+ mkdirSync(real)
+ writeFileSync(path.join(real, 'target'), '{"model":"keep"}')
+ symlinkSync('target', path.join(real, 'middle'))
+ symlinkSync('real', path.join(dir, 'alias'))
+ symlinkSync('alias/middle', file)
+ // Model BSD readlink: reject GNU-only canonicalization flags, delegate plain readlink.
+ const run: SettingsRunner = (cmd, input) => shell(`readlink() { [ "$#" -eq 1 ] || return 1; command readlink "$1"; }
+${cmd}`, input)
+ expect(await updateRemoteSettingsFile(file, run, merge)).toBe(true)
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ expect(lstatSync(path.join(real, 'middle')).isSymbolicLink()).toBe(true)
+ expect(JSON.parse(readFileSync(file, 'utf8')).model).toBe('keep')
+ })
+
+ it('refuses a failed readlink and a newline target without replacing the link', async () => {
+ const target = path.join(dir, 'target\n')
+ writeFileSync(target, '{"model":"keep"}')
+ symlinkSync('target\n', file)
+ expect(await updateRemoteSettingsFile(file, shell, merge)).toBe(false)
+ const failed: SettingsRunner = (cmd, input) => shell(`readlink() { return 1; }\n${cmd}`, input)
+ expect(await updateRemoteSettingsFile(file, failed, merge)).toBe(false)
+ expect(readFileSync(target, 'utf8')).toBe('{"model":"keep"}')
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ })
+
+ it('rejects cycles without creating settings', async () => {
+ symlinkSync('second', file)
+ symlinkSync('settings.json', path.join(dir, 'second'))
+ expect(await updateRemoteSettingsFile(file, shell, merge)).toBe(false)
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ })
+
+ it('serializes aliases against a writer holding the canonical target lock', async () => {
+ const target = path.join(dir, 'target')
+ writeFileSync(target, '{}')
+ symlinkSync('target', file)
+ mkdirSync(`${target}.nodeterm-lock`)
+ expect(await updateRemoteSettingsFile(file, shell, merge)).toBe(false)
+ expect(readFileSync(target, 'utf8')).toBe('{}')
+ expect(lstatSync(`${target}.nodeterm-lock`).isDirectory()).toBe(true)
+ })
+
+ it('refuses a competing alias write after the read', async () => {
+ const target = path.join(dir, 'target')
+ writeFileSync(target, '{}')
+ symlinkSync('target', file)
+ const run: SettingsRunner = async (cmd, input) => {
+ if (input !== undefined) {
+ expect(await updateRemoteSettingsFile(target, shell, (config) => ({ ...config, model: 'winner' }))).toBe(true)
+ }
+ return shell(cmd, input)
+ }
+ expect(await updateRemoteSettingsFile(file, run, merge)).toBe(false)
+ expect(JSON.parse(readFileSync(target, 'utf8'))).toEqual({ model: 'winner' })
+ expect(lstatSync(file).isSymbolicLink()).toBe(true)
+ })
+})
+
+
+it.skipIf(process.platform === 'win32')('an active shell writer excludes an alias writer until publication', async () => {
+ const target = path.join(dir, 'target')
+ writeFileSync(target, '{}')
+ symlinkSync('target', file)
+ let contender: boolean | undefined
+ const run: SettingsRunner = async (cmd, input) => {
+ if (input === undefined) return shell(cmd)
+ return new Promise((resolve, reject) => {
+ // Signal only AFTER lock acquisition; withholding stdin pauses the first transaction
+ // at dd while the second runs. No sleeps, live SSH hosts or user settings involved.
+ const child = spawn('/bin/sh', ['-c', cmd.replace("nt_stage=''", "printf 'locked\\n'\nnt_stage=''" )])
+ child.on('error', reject)
+ child.stdin.on('error', reject)
+ child.stderr.resume()
+ child.stdout.once('data', async () => {
+ try {
+ contender = await updateRemoteSettingsFile(target, shell, (config) => ({ ...config, model: 'contender' }))
+ child.stdin.end(input)
+ } catch (error) { child.kill(); reject(error) }
+ })
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout: '' }))
+ })
+ }
+ expect(await updateRemoteSettingsFile(file, run, merge)).toBe(true)
+ expect(contender).toBe(false)
+ expect(JSON.parse(readFileSync(target, 'utf8')).hooks.Stop).toHaveLength(1)
+ expect(JSON.parse(readFileSync(target, 'utf8')).model).toBeUndefined()
+ // Successful owner cleanup permits the later retry.
+ expect(await updateRemoteSettingsFile(target, shell, (config) => ({ ...config, model: 'retry' }))).toBe(true)
+})
diff --git a/src/core/agents/hooks/settings-file.ts b/src/core/agents/hooks/settings-file.ts
index 691f2c4f5..dc4960488 100644
--- a/src/core/agents/hooks/settings-file.ts
+++ b/src/core/agents/hooks/settings-file.ts
@@ -4,7 +4,7 @@ import path from 'path'
import { renameAtomicSync, tempNameFor } from '../../fs-atomic'
export function parseSettings(raw: string): Record<string, unknown> {
- const value: unknown = JSON.parse(raw)
+ const value: unknown = raw.trim() === '' ? {} : 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>
}
@@ -50,7 +50,10 @@ export function updateSettingsFile(requested: string, update: (config: Record<st
mkdirSync(path.dirname(requested), { recursive: true })
const file = settingsTarget(requested)
lock = `${file}.nodeterm-lock`
- mkdirSync(lock)
+ try { mkdirSync(lock) } catch (error) {
+ console.warn(`[agent-hooks] Settings lock unavailable: ${lock}. Installation skipped; if it persists, stop nodeterm writers and inspect/remove the stale lock before retrying.`)
+ throw error
+ }
locked = true
const before = snapshot(file)
const config = before === null ? {} : parseSettings(before)
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index a4fe2297d..3865be347 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -29,13 +29,14 @@ function harness(
calls.push({ args, stdin, cmd: joined })
if (opts.failOn && joined.includes(opts.failOn)) throw new Error(`fake ssh failed: ${opts.failOn}`)
if (opts.failCodeOn && joined.includes(opts.failCodeOn)) return { code: 1, stdout: '' }
+ const resolved = joined.match(/nt_resolve '([^']+)' \|\| exit 1/)?.[1]
for (const [needle, stdout] of Object.entries(opts.responses ?? {})) {
- if (joined.includes(needle)) return { code: 0, stdout }
+ if (joined.includes(needle)) return { code: 0, stdout: resolved ? `${resolved}\n${stdout}` : stdout }
}
// 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('else exit 44; fi')) return { code: 44, stdout: '' }
+ if (resolved) return { code: 44, stdout: `${resolved}\n` }
// 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: '' }
@@ -489,7 +490,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {
const calls: { args: string[]; stdin?: string }[] = []
const run = vi.fn(async (args: string[], stdin?: string) => {
calls.push({ args, stdin })
- if (isReadOf(args, target)) return { code: 0, stdout: JSON.stringify({ hooks: { Stop: [] } }) }
+ if (isReadOf(args, target)) return { code: 0, stdout: `${target}\n` + JSON.stringify({ hooks: { Stop: [] } }) }
return { code: 0, stdout: '' }
})
const rh = new RemoteHooks({ run })
@@ -504,7 +505,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {
const calls: { args: string[]; stdin?: string }[] = []
const run = vi.fn(async (args: string[]) => {
calls.push({ args })
- if (isReadOf(args, target)) return { code: 0, stdout: JSON.stringify({ tui: 'default' }) }
+ if (isReadOf(args, target)) return { code: 0, stdout: `${target}\n` + JSON.stringify({ tui: 'default' }) }
return { code: 0, stdout: '' }
})
const rh = new RemoteHooks({ run })
@@ -517,7 +518,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {
const calls: { args: string[]; stdin?: string }[] = []
const run = vi.fn(async (args: string[], stdin?: string) => {
calls.push({ args, stdin })
- return { code: 0, stdout: '{}' } // any read → empty settings
+ return { code: 0, stdout: `${target}\n{}` } // resolved target header + empty settings
})
const rh = new RemoteHooks({ run })
await rh.ensureFullscreenTuiInAccountDir(conn, '/s.sock', '/home/u', 'acc-1')
diff --git a/src/main/remote-ssh/remote-settings-preservation.test.ts b/src/main/remote-ssh/remote-settings-preservation.test.ts
index 0b4b5a2c2..ae852004c 100644
--- a/src/main/remote-ssh/remote-settings-preservation.test.ts
+++ b/src/main/remote-ssh/remote-settings-preservation.test.ts
@@ -10,7 +10,7 @@ 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', () => {
+ describe.skipIf(process.platform === 'win32')(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 })
@@ -32,10 +32,16 @@ for (const account of [false, true]) {
return readFileSync(file, 'utf8')
}
- it.each(['{broken', '', 'null', '[]'])('neither hooks nor TUI destroys malformed settings: %s', async (raw) => {
+ it.each(['{broken', 'null', '[]'])('neither hooks nor TUI destroys malformed settings: %s', async (raw) => {
expect(await install(raw)).toBe(raw)
})
+ it.each(['', ' \t\n'])('installs hooks and TUI into blank settings: %j', async (raw) => {
+ const result = JSON.parse(await install(raw))
+ expect(result.tui).toBe('fullscreen')
+ expect(result.hooks.Stop).toHaveLength(1)
+ })
+
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] } })))