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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(ssh): a remote write never leaves a truncated file
review9f4e341067c0
diff --git a/CLAUDE.md b/CLAUDE.mdindex 7a11ead8b..e81fd6986 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -6464,10 +6464,35 @@ SSH/scp staging follows the same ownership rule outside direct `fs` calls. Atomiwrites use `src/main/remote-atomic-write.ts`: a bounded `.nodeterm-<uuid>.tmp` leaf is placed besidethe target BEFORE both complete paths are quoted, then the shell preserves the write/move statuswhile 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; 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+`.uuid.tmp` to a valid `NAME_MAX` target makes the write impossible.++**A remote write is only complete if the host checked the byte count, and a rename alone does not+check it.** `cat` cannot tell "the body ended" from "the ssh channel ended": when the channel dies+before the body arrives (the ControlMaster killed or rebuilt on a reconnect, the runner's 15 s+timeout SIGTERMing the child, a dropped link) it reads EOF and EXITS 0. Measured against OpenSSH 9.6+with the master SIGKILLed and with the child SIGTERMed, both before the body: a bare+`cat > f && chmod 755 f` left `f` at 0 bytes and flipped 644 → 755, and the temp + `mv` shape+published the empty temp over a good file just the same. That is how, on 2026-09-28, a host's+`~/.nodeterm/nodeterm.sh` and `context.sh` were 0 bytes after a reconnect and every agent's canvas+call exited 0 with no output. So `remoteAtomicWrite(path, body, options)` takes the BODY, checks+`[ "$(wc -c < temp)" -eq <utf-8 bytes> ]` before the rename (a short temp exits+`REMOTE_WRITE_SHORT_BODY` = 65 with the target untouched), returns the `stdin` it was built for,+and refuses an empty body unless `allowEmpty` (only the generic `ssh-fs` write passes it — an editor+may save an empty file; nothing we GENERATE is ever empty). `runRemoteAtomicWrite` also THROWS on a+non-zero exit: the runners resolve on failure, and awaiting them and moving on is what made the+failure silent. Every remote write goes through it — filesystem API writes, tmux.conf, the hook+endpoint, node tokens, agent status, pending answers, session env files, the Codex relay and+launcher, every agent hook script, the canvas/context shims and skills, and our own grok/copilot+hook configs. The USER's files — Claude/Gemini `settings.json`, codex `hooks.json` and+`config.toml`, and the AGENTS.md / GEMINI.md / copilot-instructions.md instruction blocks — go+through `updateRemoteTextFile` / `updateRemoteSettingsFile` (`core/agents/hooks/remote-settings-file.ts`)+instead: the same byte check plus our lock, symlink resolution (a dotfile link stays a link),+mode preservation, and a compare-before-publish; a read that fails is never treated as an empty+file (the old `cat f || true` then `cat > f` replaced an unreadable AGENTS.md with our block alone).+The local installers for the same files use `writeManagedHookFileAtomic` / `mergeInstructionFile`.+`src/main/remote-ssh/remote-write.guard.test.ts` fails on any new bare `cat > <file>` in+src/{core,main,server}, and `remote-write-truncation.test.ts` runs every installer under a real+`/bin/sh` with the body cut off. Upload directories use UUIDs across appprocesses. Downloads and media-cache copies use hidden UUID `.part` names; user-visible downloadsalso hold an exclusive candidate lock until the rename and cleanup finish. Never simplify any ofthose back to `<target>.tmp` / `<target>.part` or a read-only "does the destination exist?" check —diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 45965b308..1cc308e69 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -415,6 +415,15 @@ anything else. Board-level fields survive every transform — `pullLinks` is onesee. Keep a remote temp's own leaf bounded: extending an already-valid maximum-length target leafwith a UUID suffix turns an atomic write into a guaranteed `ENAMETOOLONG` failure.+- **Never write a remote file with `cat > <file>`.** It truncates the file the moment the remote+ shell starts, and when the ssh channel dies before the body arrives `cat` exits 0 — a reconnect+ once left a host's canvas shims at 0 bytes with every agent call "succeeding" silently. Use+ `runRemoteAtomicWrite` / `remoteAtomicWrite` (`src/main/remote-atomic-write.ts`), which checks the+ byte count before renaming and throws when the write did not land, and for a file that belongs+ to the user (settings, config.toml, AGENTS.md) use `updateRemoteTextFile`, which also keeps its+ symlink and mode. A guard test fails on a new bare `cat >`. A remote runner RESOLVES on a+ non-zero exit, so check the result or use the helper that does.+- **A write ack is a claim about a WRITE, never about what the remote now holds.** Do not retirestate that records "the server still needs to be told X" just because the write returned true.The SSH mirror's writer acks the 5 s throttle's trailing write **optimistically** — it returnsdiff --git a/docs/atomic-writes.md b/docs/atomic-writes.mdindex e8aa49219..f4166ded8 100644--- a/docs/atomic-writes.md+++ b/docs/atomic-writes.md@@ -100,10 +100,22 @@ bounded name avoids lengthening an already maximum-length filename. Ordinary dowreserve the final candidate with an exclusive lock, so two app processes cannot both observe`report.pdf` as absent and overwrite each other after transferring. Candidate checks use `lstat`:a dangling symlink is an occupied directory entry, not evidence that the name is free. Atomic-remote stdin sites use-the same helper for filesystem writes, tmux.conf, the credential-bearing hook endpoint and node-tokens, agent status, and pending answers. Generated hook scripts/config merges still have direct-writes and are not covered by this atomicity claim.+remote stdin sites all use the same helper: filesystem writes, tmux.conf, the credential-bearing+hook endpoint and node tokens, agent status, pending answers, session env files, the Codex relay and+launcher, agent hook scripts, the canvas-control and context-link shims and skills, and our own+grok/copilot hook configs. The user's own files (settings.json, codex hooks.json/config.toml, the+AGENTS.md-style instruction files) go through the guarded text transaction in+`core/agents/hooks/remote-settings-file.ts`, which adds a lock, symlink resolution, mode+preservation and a compare-before-publish.++A remote rename is atomic but not, by itself, complete. `cat` exits 0 when the ssh channel ends+before the body does — the master killed or rebuilt on a reconnect, the runner's timeout, a dropped+link — so a temp can hold nothing, or half the body, and still be renamed into place. Measured+against OpenSSH 9.6 (2026-09-29): with the master SIGKILLed before the body arrived, both the old+`cat > f` writer and the old temp + `mv` writer left the target at 0 bytes. Every remote write+therefore checks the temp's byte count against the body's UTF-8 length before it renames, and+exits 65 (`REMOTE_WRITE_SHORT_BODY`) with the target untouched when they differ. That check is also+why `remoteAtomicWrite` takes the body: a command built for one body refuses any other stdin."Only one instance exists" and "the write queue serializes this" are true within one process andsilent about a second — and a second is not hypothetical: the Server Edition takes a `--data-dir`,diff --git a/src/core/agents/hooks/copilot.ts b/src/core/agents/hooks/copilot.tsindex 2b32a8b53..15059ee15 100644--- a/src/core/agents/hooks/copilot.ts+++ b/src/core/agents/hooks/copilot.ts@@ -9,7 +9,8 @@ import path from 'path'import { COPILOT_HOOK_EVENTS } from '@shared/agents/hook-events'import {buildManagedHookCommand,- installManagedHookScript+ installManagedHookScript,+ writeManagedHookFileAtomic} from './install-helper'const SCRIPT_FILE_NAME = 'copilot.sh'@@ -86,10 +87,10 @@ export function installCopilotHooks(): void {const configPath = copilotHookConfigPath()try {fs.mkdirSync(path.dirname(configPath), { recursive: true })- fs.writeFileSync(+ // Our own file, published by rename so copilot never reads it half written.+ writeManagedHookFileAtomic(configPath,- `${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`,- 'utf8'+ `${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`)} catch (e) {console.warn('[agent-hooks] copilot install failed', e)@@ -99,11 +100,7 @@ export function installCopilotHooks(): void {export function removeCopilotHooks(): void {const configPath = copilotHookConfigPath()try {- fs.writeFileSync(- configPath,- `${JSON.stringify({ version: 1, hooks: {} }, null, 2)}\n`,- 'utf8'- )+ writeManagedHookFileAtomic(configPath, `${JSON.stringify({ version: 1, hooks: {} }, null, 2)}\n`)} catch {/* fail open */}diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex d8091940f..7b414972e 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -36,6 +36,8 @@ export function writeManagedHookFileAtomic(const tmp = tempNameFor(target)try {writeFileSync(tmp, data, { encoding: 'utf8', flag: 'wx', ...(mode === undefined ? {} : { mode }) })+ // Exact, not umask-filtered: the rename carries the temp's mode, so set it before publishing.+ if (mode !== undefined) chmodSync(tmp, mode)publish(tmp, target)} catch (e) {rmSync(tmp, { force: true })diff --git a/src/core/agents/hooks/remote-settings-file.ts b/src/core/agents/hooks/remote-settings-file.tsindex a3e381734..c8f7a73b2 100644--- a/src/core/agents/hooks/remote-settings-file.ts+++ b/src/core/agents/hooks/remote-settings-file.ts@@ -33,40 +33,63 @@ const resolveTarget = `nt_resolve() {[ "$nt_links" -eq 0 ] || [ -f "$nt_file" ] || return 1}`-export async function updateRemoteSettingsFile(- file: string,+/** A literal remote path, or a shell-expandable one: `pathExpr` is spliced into the command as-is+ * (already quoted by the caller) after `prelude`, which may bind an untrusted value to a shell+ * variable first — see `openCodeInstructionsTarget` in remote-hooks. `label` names it in logs. */+export type RemoteTextTarget = string | { pathExpr: string; prelude?: string; label: string }++/** `unchanged` = the update asked for no change (or the file already matched); `failed` = nothing+ * was published because the read, the update, the lock or the publication failed. */+export type RemoteTextResult = 'written' | 'unchanged' | 'failed'++/**+ * The guarded read-modify-write for a remote file that belongs to the USER (settings.json, a codex+ * config.toml, an AGENTS.md): resolve symlinks so a dotfile link keeps pointing where it did, take+ * our lock, stage the new bytes, check that EXACTLY those bytes arrived, check the file still holds+ * what we read, and only then rename a copy that keeps the original's mode into place. A plain+ * `cat > file` does none of that — it truncates the user's file the moment the remote shell starts,+ * and an ssh channel that dies before the body arrives leaves it empty (measured, and it happened).+ *+ * `update` receives the current text (`null` = no file) and returns the new text, or `null` for "no+ * change". An empty result is refused: nothing this app writes into a user's file is ever empty.+ * `createMode` applies only when the file does not exist yet (default 600, as for settings).+ */+export async function updateRemoteTextFile(+ file: RemoteTextTarget,run: SettingsRunner,- update: (config: Record<string, unknown>) => Record<string, unknown>-): Promise<boolean> {- const requested = posixQuote(file)+ update: (before: string | null) => string | null,+ options: { createMode?: '600' | '644' } = {}+): Promise<RemoteTextResult> {+ const requested = typeof file === 'string' ? posixQuote(file) : file.pathExpr+ const prelude = typeof file === 'string' ? '' : (file.prelude ?? '')+ const label = typeof file === 'string' ? file : file.labeltry {- const read = await run(`${resolveTarget}+ const read = await run(`${prelude}${resolveTarget}umask 077mkdir -p "$(dirname ${requested})" || exit 1nt_resolve ${requested} || exit 1printf '%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')+ if (read.code !== 0 && read.code !== 44) throw new Error('Remote file 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')+ if (separator < 1 || !target.startsWith('/')) throw new Error('Remote file 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)- if (before !== null && JSON.stringify(updated) === original) return false- const next = JSON.stringify(updated, null, 2)+ const next = update(before)+ if (next === null) return 'unchanged'+ if (next === '') throw new Error('Refusing to publish an empty file')// 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 = `nt_resolve ${requested} && [ "$nt_file" = ${q} ] && ` + (before === null? `[ ! -e ${q} ] && [ ! -L ${q} ]`: `[ ! -L ${q} ] && [ -f ${q} ] && cmp -s "$nt_stage/before" ${q}`)- const command = `${resolveTarget}+ const create = before === null && options.createMode === '644' ? `chmod 644 "$nt_stage/publish" || exit 1` : ':'+ const command = `${prelude}${resolveTarget}umask 077mkdir ${lock} 2>/dev/null || exit 73nt_stage=''@@ -80,18 +103,43 @@ cat > "$nt_stage/next" || exit 1${unchanged} || exit 1${before === null ? ':' : `cp -p ${q} "$nt_stage/publish" || exit 1`}cat "$nt_stage/next" > "$nt_stage/publish" || exit 1+${create}${unchanged} || exit 1mv -f -- "$nt_stage/publish" ${q}`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+ console.warn(`[agent-hooks] Remote file lock unavailable: ${lockPath}. Installation skipped; if it persists, stop nodeterm writers and inspect/remove the stale lock before retrying.`)+ return 'failed'}- if (result.code !== 0) throw new Error('Remote settings publication failed (conflict or I/O error)')- return true+ if (result.code !== 0) throw new Error('Remote file publication failed (conflict or I/O error)')+ return 'written'} 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+ // Do not log the error: a parse error's message can include private file contents.+ console.warn(`[agent-hooks] Remote file unchanged: ${label} (read, parse, resolution or publication failed).`)+ return 'failed'}}++/** The same transaction for a JSON settings object, reporting all three outcomes. */+export function updateRemoteSettingsFileResult(+ file: string,+ run: SettingsRunner,+ update: (config: Record<string, unknown>) => Record<string, unknown>+): Promise<RemoteTextResult> {+ return updateRemoteTextFile(file, run, (before) => {+ const config = before === null ? {} : parseSettings(before)+ const original = JSON.stringify(config)+ const updated = update(config)+ if (before !== null && JSON.stringify(updated) === original) return null+ return JSON.stringify(updated, null, 2)+ })+}++/** True only when the file was written. */+export async function updateRemoteSettingsFile(+ file: string,+ run: SettingsRunner,+ update: (config: Record<string, unknown>) => Record<string, unknown>+): Promise<boolean> {+ return (await updateRemoteSettingsFileResult(file, run, update)) === 'written'+}diff --git a/src/core/agents/hooks/settings-file.test.ts b/src/core/agents/hooks/settings-file.test.tsindex 289db7df4..a326b8d25 100644--- a/src/core/agents/hooks/settings-file.test.ts+++ b/src/core/agents/hooks/settings-file.test.ts@@ -1,10 +1,10 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, symlinkSync, lstatSync, chmodSync, statSync } from 'fs'+import { mkdtempSync, mkdirSync, readFileSync, readdirSync, writeFileSync, rmSync, symlinkSync, lstatSync, chmodSync, statSync } from 'fs'import { tmpdir } from 'os'import path from 'path'import { spawn, spawnSync } from 'child_process'-import { updateSettingsFile } from './settings-file'-import { updateRemoteSettingsFile, type SettingsRunner } from './remote-settings-file'+import { mergeInstructionFile, updateSettingsFile, updateTextFile } from './settings-file'+import { updateRemoteSettingsFile, updateRemoteTextFile, type SettingsRunner } from './remote-settings-file'import { mergeManagedHook } from './install-helper'let dir: string@@ -226,3 +226,80 @@ it.skipIf(process.platform === 'win32')('an active shell writer excludes an alia// Successful owner cleanup permits the later retry.expect(await updateRemoteSettingsFile(target, shell, (config) => ({ ...config, model: 'retry' }))).toBe(true)})++// The same transaction for text files that belong to the user (a codex config.toml, an AGENTS.md):+// before this, those were written with a bare `cat >` remotely and `writeFileSync` locally.+for (const remote of [false, true]) {+ describe.skipIf(remote && process.platform === 'win32')(remote ? 'remote text transaction' : 'local text transaction', () => {+ const text = (update: (before: string | null) => string | null, createMode?: number) => remote+ ? updateRemoteTextFile(file, shell, update, { createMode: createMode === 0o644 ? '644' : undefined })+ : Promise.resolve(updateTextFile(file, update, { createMode }))++ it('creates a missing file with the requested mode and reports each outcome', async () => {+ expect(await text((before) => (before === null ? 'block\n' : null), 0o644)).toBe('written')+ expect(readFileSync(file, 'utf8')).toBe('block\n')+ if (process.platform !== 'win32') expect(statSync(file).mode & 0o777).toBe(0o644)+ expect(await text(() => null)).toBe('unchanged')+ })++ it('keeps an existing file\'s mode and refuses an empty result', async () => {+ writeFileSync(file, 'model = "o3"\n')+ chmodSync(file, 0o600)+ expect(await text((before) => `${before}# trust\n`)).toBe('written')+ expect(readFileSync(file, 'utf8')).toBe('model = "o3"\n# trust\n')+ if (process.platform !== 'win32') expect(statSync(file).mode & 0o777).toBe(0o600)+ expect(await text(() => '')).toBe('failed')+ expect(readFileSync(file, 'utf8')).toBe('model = "o3"\n# trust\n')+ })++ it.skipIf(process.platform === 'win32')('merges an instruction block through a dotfile link, keeping the link', async () => {+ const target = path.join(dir, 'dotfiles-AGENTS.md')+ writeFileSync(target, '# mine\n')+ symlinkSync(target, file)+ const merge = (existing: string) => `${existing}<!-- block -->\n`+ const result = remote+ ? await updateRemoteTextFile(file, shell, (before) => merge(before ?? ''), { createMode: '644' })+ : mergeInstructionFile(file, merge)+ expect(result).toBe('written')+ expect(lstatSync(file).isSymbolicLink()).toBe(true)+ expect(readFileSync(target, 'utf8')).toBe('# mine\n<!-- block -->\n')+ })++ it('never reads an unreadable file as empty', async () => {+ mkdirSync(file)+ const update = vi.fn(() => 'our block alone\n')+ expect(await text(update)).toBe('failed')+ expect(update).not.toHaveBeenCalled()+ expect(lstatSync(file).isDirectory()).toBe(true)+ })+ })+}++it.skipIf(process.platform === 'win32')('remote text: a body cut short on the wire publishes nothing', async () => {+ writeFileSync(file, 'model = "o3"\n')+ // The failure that left 0-byte files behind: the channel ends before the body does.+ const run: SettingsRunner = (cmd, input) => shell(cmd, input === undefined ? undefined : input.slice(0, 5))+ expect(await updateRemoteTextFile(file, run, (before) => `${before}# trust\n`)).toBe('failed')+ expect(readFileSync(file, 'utf8')).toBe('model = "o3"\n')+})++it.skipIf(process.platform === 'win32')('remote text: a shell-expanded path binds its untrusted part in the prelude', async () => {+ // The opencode target: `$NT_H` holds a host-reported $HOME, and must stay inert inside the+ // double-quoted expression while `${XDG_CONFIG_HOME:-…}` still expands on the host.+ const hostile = path.join(dir, 'h$(touch pwned)')+ mkdirSync(hostile)+ const target = {+ prelude: `NT_H='${hostile.replace(/'/g, "'\\''")}'; `,+ pathExpr: '"${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md"',+ label: 'opencode AGENTS.md'+ }+ const clean: SettingsRunner = async (command, stdin) => {+ const result = spawnSync('/bin/sh', ['-c', command], {+ input: stdin, encoding: 'utf8', cwd: dir, env: { PATH: process.env.PATH ?? '/usr/bin:/bin' }+ })+ return { code: result.status ?? 1, stdout: result.stdout }+ }+ expect(await updateRemoteTextFile(target, clean, () => 'block\n', { createMode: '644' })).toBe('written')+ expect(readFileSync(path.join(hostile, '.config', 'opencode', 'AGENTS.md'), 'utf8')).toBe('block\n')+ expect(readdirSync(dir)).not.toContain('pwned')+})diff --git a/src/core/agents/hooks/settings-file.ts b/src/core/agents/hooks/settings-file.tsindex dc4960488..9d38e05e5 100644--- a/src/core/agents/hooks/settings-file.ts+++ b/src/core/agents/hooks/settings-file.ts@@ -41,8 +41,16 @@ function settingsTarget(file: string): string {}/** 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 {+ * do not honor our lock: the final comparison narrows, but cannot eliminate, their rename race.+ *+ * `update` receives the current text (`null` = no file) and returns the new text, or `null` for+ * "no change". An empty result is refused. A symlinked file is updated through its link, and an+ * existing file keeps its mode; `createMode` applies only to a file that does not exist yet. */+export function updateTextFile(+ requested: string,+ update: (before: string | null) => string | null,+ options: { createMode?: number } = {}+): 'written' | 'unchanged' | 'failed' {let lock = ''let locked = falselet tmp: string | undefined@@ -56,22 +64,42 @@ export function updateSettingsFile(requested: string, update: (config: Record<st}locked = trueconst 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)+ const next = update(before)+ if (next === null) return 'unchanged'+ if (next === '') throw new Error('Refusing to publish an empty file')tmp = tempNameFor(file)- const mode = before === null ? 0o600 : statSync(file).mode & 0o777+ const mode = before === null ? (options.createMode ?? 0o600) : statSync(file).mode & 0o777writeFileSync(tmp, next, { flag: 'wx', mode })chmodSync(tmp, mode)- if (settingsTarget(requested) !== file || snapshot(file) !== before) return false+ if (settingsTarget(requested) !== file || snapshot(file) !== before) return 'failed'renameAtomicSync(tmp, file)- return true+ return 'written'} catch {- return false // fail open for the session, fail closed for the user's settings+ return 'failed' // fail open for the session, fail closed for the user's file} finally {try { if (tmp) rmSync(tmp, { force: true }) } catch { /* best-effort cleanup */ }try { if (locked) rmdirSync(lock) } catch { /* never break session startup */ }}}++/** Merge one marker-delimited block into a user's instruction file (AGENTS.md, GEMINI.md, …)+ * through the same transaction: the link and mode are kept, and an unreadable file is left alone+ * rather than read as empty and replaced by our block. */+export function mergeInstructionFile(file: string, merge: (existing: string) => string): 'written' | 'unchanged' | 'failed' {+ return updateTextFile(file, (before) => {+ const existing = before ?? ''+ const merged = merge(existing)+ return merged === existing ? null : merged+ }, { createMode: 0o644 })+}++/** The same transaction for a JSON settings object. True only when the file was written. */+export function updateSettingsFile(requested: string, update: (config: Record<string, unknown>) => Record<string, unknown>): boolean {+ return updateTextFile(requested, (before) => {+ const config = before === null ? {} : parseSettings(before)+ const original = JSON.stringify(config)+ const updated = update(config)+ if (before !== null && JSON.stringify(updated) === original) return null+ return JSON.stringify(updated, null, 2)+ }) === 'written'+}diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex fc2738e1a..bde486f51 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -18,6 +18,8 @@ import fs from 'fs'import os from 'os'import path from 'path'import { platform } from './platform'+import { writeManagedHookFileAtomic } from './agents/hooks/install-helper'+import { mergeInstructionFile } from './agents/hooks/settings-file'import { IPC } from '../shared/ipc'import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'import { type PtyManager } from './pty-manager'@@ -63,12 +65,8 @@ function skillPath(): string {function writeCliFiles(): void {const d = contextLinkDir()fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(cliShimPath(), buildContextShimScript(codexThreadIdentityRoot()))- try {- fs.chmodSync(cliShimPath(), 0o755)- } catch {- /* fail open */- }+ // Temp + rename, never a truncating write: agents execute this file (see canvas-control.ts).+ writeManagedHookFileAtomic(cliShimPath(), buildContextShimScript(codexThreadIdentityRoot()), undefined, 0o755)// Sweep the retired Electron-as-Node CLI off upgraders' disks: the shim no longer execs it,// and it would sit there pointing at a binary path that moves with every app update.try {@@ -81,7 +79,7 @@ function writeCliFiles(): void {function installSkill(): void {try {fs.mkdirSync(path.dirname(skillPath()), { recursive: true })- fs.writeFileSync(skillPath(), buildContextLinkSkillBody(cliShimPath()), 'utf8')+ writeManagedHookFileAtomic(skillPath(), buildContextLinkSkillBody(cliShimPath()))} catch (e) {console.warn('[context-link] skill install failed', e)}@@ -97,17 +95,9 @@ function installAgentInstructions(): void {path.join(opencodeConfigDir(), 'AGENTS.md')]for (const p of targets) {- try {- let existing = ''- try {- existing = fs.readFileSync(p, 'utf8')- } catch {- /* new file */- }- fs.mkdirSync(path.dirname(p), { recursive: true })- fs.writeFileSync(p, mergeInstructionsBlock(existing, block), 'utf8')- } catch (e) {- console.warn('[context-link] instructions install failed', p, e)+ // The user's file: the guarded transaction keeps its link and mode (see canvas-control.ts).+ if (mergeInstructionFile(p, (existing) => mergeInstructionsBlock(existing, block)) === 'failed') {+ console.warn('[context-link] instructions install failed', p)}}}diff --git a/src/main/canvas-control.ts b/src/main/canvas-control.tsindex ec9fbe777..7206a274f 100644--- a/src/main/canvas-control.ts+++ b/src/main/canvas-control.ts@@ -17,6 +17,8 @@ import {mergeCanvasControlBlock} from '../core/canvas-control-core'import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'+import { writeManagedHookFileAtomic } from '../core/agents/hooks/install-helper'+import { mergeInstructionFile } from '../core/agents/hooks/settings-file'import { opencodeConfigDir } from '../core/agents/hooks/opencode'import { copilotHomeDir } from '../core/agents/hooks/copilot'@@ -36,12 +38,9 @@ function skillBody(): string {function writeCliFiles(): void {const d = dir()fs.mkdirSync(d, { recursive: true })- fs.writeFileSync(shimPath(), buildControlShimScript(codexThreadIdentityRoot()))- try {- fs.chmodSync(shimPath(), 0o755)- } catch {- /* fail open */- }+ // Temp + rename, never a truncating write: agents execute this file, and a shim caught half+ // written is a canvas call that exits 0 having done nothing.+ writeManagedHookFileAtomic(shimPath(), buildControlShimScript(codexThreadIdentityRoot()), undefined, 0o755)// Sweep the retired Electron-as-Node CLI off upgraders' disks — the shim no longer execs it,// so it would sit there forever pointing at a binary path that moves with every app update.try {@@ -61,7 +60,7 @@ export function installCanvasSkillInto(configDir: string): void {const p = skillPathIn(configDir)try {fs.mkdirSync(path.dirname(p), { recursive: true })- fs.writeFileSync(p, skillBody(), 'utf8')+ writeManagedHookFileAtomic(p, skillBody())} catch (e) {console.warn('[canvas-control] skill install failed', p, e)}@@ -80,17 +79,10 @@ function installAgentInstructions(): void {path.join(opencodeConfigDir(), 'AGENTS.md')]for (const p of targets) {- try {- let existing = ''- try {- existing = fs.readFileSync(p, 'utf8')- } catch {- /* new file */- }- fs.mkdirSync(path.dirname(p), { recursive: true })- fs.writeFileSync(p, mergeCanvasControlBlock(existing, block), 'utf8')- } catch (e) {- console.warn('[canvas-control] instructions install failed', p, e)+ // The user's file: merged through the guarded transaction (link and mode kept, never read an+ // unreadable file as empty and replace it with our block).+ if (mergeInstructionFile(p, (existing) => mergeCanvasControlBlock(existing, block)) === 'failed') {+ console.warn('[canvas-control] instructions install failed', p)}}}diff --git a/src/main/index.ts b/src/main/index.tsindex 75ac063be..fb8fa9c99 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2780,7 +2780,7 @@ app.whenReady().then(async () => {if (!rt || !sshProjectManager) return falsetry {const { code } = await sshProjectManager.sshRun(- sshWriteArgs(rt.conn, rt.controlPath, filePath),+ sshWriteArgs(rt.conn, rt.controlPath, filePath, content),content)return code === 0diff --git a/src/main/remote-atomic-write.test.ts b/src/main/remote-atomic-write.test.tsindex 60727d7ca..25a84e917 100644--- a/src/main/remote-atomic-write.test.ts+++ b/src/main/remote-atomic-write.test.ts@@ -2,9 +2,9 @@ import { execFileSync, spawn, spawnSync, type ChildProcessWithoutNullStreams } fimport { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'fs'import os from 'os'import path from 'path'-import { afterEach, describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import { quoteRemotePath } from '../shared/ssh'-import { remoteAtomicWrite } from './remote-atomic-write'+import { remoteAtomicWrite, REMOTE_WRITE_SHORT_BODY, RemoteWriteError, runRemoteAtomicWrite } from './remote-atomic-write'const SHELL =process.platform === 'win32'@@ -57,13 +57,13 @@ async function waitForTemp(directory: string): Promise<void> {describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {it('mints a shell-safe, per-call UUID temp and cleans only that temp after publishing', () => {- const first = remoteAtomicWrite("~/a b/quo'te\\name.json", {+ const first = remoteAtomicWrite("~/a b/quo'te\\name.json", 'body', {restrictPermissions: true,- chmod600: true+ mode: '600'})- const second = remoteAtomicWrite("~/a b/quo'te\\name.json", {+ const second = remoteAtomicWrite("~/a b/quo'te\\name.json", 'body', {restrictPermissions: true,- chmod600: true+ mode: '600'})expect(first.temporaryPath).toMatch(/^~\/a b\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)@@ -71,6 +71,9 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {expect(first.command).toContain('umask 077; mkdir -p -- ~/' + "'a b'")expect(first.command).toContain(`cat > ${quoteRemotePath(first.temporaryPath)}`)expect(first.command).toContain(`chmod 600 -- ${quoteRemotePath(first.temporaryPath)}`)+ // The byte count of THIS body, checked on the temp before anything is published.+ expect(first.command).toContain(`[ "$(wc -c < ${quoteRemotePath(first.temporaryPath)})" -eq 4 ]`)+ expect(first.stdin).toBe('body')expect(first.command).toContain(`mv -f -- ${quoteRemotePath(first.temporaryPath)} ${quoteRemotePath("~/a b/quo'te\\name.json")}`)expect(first.command).toContain(`rm -f -- ${quoteRemotePath(first.temporaryPath)}`)expect(first.command).toContain('exit "$nt_status"')@@ -81,9 +84,9 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {roots.push(root)const nativeTarget = path.join(root, "space and 'quote.txt")const target = `${shellPath(root)}/space and 'quote.txt`- const write = remoteAtomicWrite(target, { restrictPermissions: true })+ const write = remoteAtomicWrite(target, 'payload', { restrictPermissions: true })- execFileSync(SHELL!, ['-c', write.command], { input: 'payload', stdio: ['pipe', 'pipe', 'pipe'] })+ execFileSync(SHELL!, ['-c', write.command], { input: write.stdin, stdio: ['pipe', 'pipe', 'pipe'] })expect(readFileSync(nativeTarget, 'utf8')).toBe('payload')expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])@@ -97,10 +100,10 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {const leaf = `${'x'.repeat(215)}.json`const nativeTarget = path.join(root, leaf)const target = `${shellPath(root)}/${leaf}`- const write = remoteAtomicWrite(target)+ const write = remoteAtomicWrite(target, 'long-name')execFileSync(SHELL!, ['-c', write.command], {- input: 'long-name',+ input: write.stdin,stdio: ['pipe', 'pipe', 'pipe']})@@ -115,9 +118,9 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-backslash-'))roots.push(root)const leaf = "space and 'quote\\name.txt"- const write = remoteAtomicWrite(`${root}/${leaf}`)+ const write = remoteAtomicWrite(`${root}/${leaf}`, 'literal')- execFileSync(SHELL!, ['-c', write.command], { input: 'literal', stdio: ['pipe', 'pipe', 'pipe'] })+ execFileSync(SHELL!, ['-c', write.command], { input: write.stdin, stdio: ['pipe', 'pipe', 'pipe'] })expect(readFileSync(path.join(root, leaf), 'utf8')).toBe('literal')expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])@@ -130,13 +133,13 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-private-'))roots.push(root)const target = path.join(root, 'token')- const write = remoteAtomicWrite(target, {+ const write = remoteAtomicWrite(target, 'credential', {restrictPermissions: true,- chmod600: true+ mode: '600'})execFileSync(SHELL!, ['-c', write.command], {- input: 'credential',+ input: write.stdin,stdio: ['pipe', 'pipe', 'pipe']})@@ -148,9 +151,9 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-failure-'))roots.push(root)const target = `${shellPath(root)}/state.json`- const write = remoteAtomicWrite(target, {+ const write = remoteAtomicWrite(target, 'not-published', {restrictPermissions: true,- chmod600: true+ mode: '600'})const nativeTarget = path.join(root, 'state.json')execFileSync(SHELL!, ['-c', `printf %s old > ${quoteRemotePath(target)}`])@@ -167,14 +170,14 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {it.skipIf(!SHELL)('uses option terminators for a relative path beginning with a dash', () => {const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-option-'))roots.push(root)- const write = remoteAtomicWrite('--target-directory=elsewhere', {+ const write = remoteAtomicWrite('--target-directory=elsewhere', 'literal-name', {restrictPermissions: true,- chmod600: true+ mode: '600'})execFileSync(SHELL!, ['-c', write.command], {cwd: root,- input: 'literal-name',+ input: write.stdin,stdio: ['pipe', 'pipe', 'pipe']})@@ -190,14 +193,15 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {const nativeTarget = path.join(root, 'state.json')const target = `${shellPath(root)}/state.json`- const privateWrite = () =>- remoteAtomicWrite(target, { restrictPermissions: true, chmod600: true }).command- const first = spawn(SHELL!, ['-c', privateWrite()], { stdio: 'pipe' })+ // Each writer's command is built for the body it will actually deliver across two writes.+ const privateWrite = (body: string) =>+ remoteAtomicWrite(target, body, { restrictPermissions: true, mode: '600' }).command+ const first = spawn(SHELL!, ['-c', privateWrite('first-wins')], { stdio: 'pipe' })const firstDone = finish(first)first.stdin.write('first-')await waitForTemp(root)- const second = spawn(SHELL!, ['-c', privateWrite()], { stdio: 'pipe' })+ const second = spawn(SHELL!, ['-c', privateWrite('second')], { stdio: 'pipe' })const secondDone = finish(second)second.stdin.end('second')expect(await secondDone).toEqual({ code: 0, stderr: '' })@@ -207,4 +211,101 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {expect(readFileSync(nativeTarget, 'utf8')).toBe('first-wins')expect(readdirSync(root).filter((name) => name.endsWith('.tmp'))).toEqual([])})++ // The failure that left a host with 0-byte canvas shims: the remote shell starts (and a bare+ // `cat > f` truncates f right there), then the ssh channel ends before the body arrives. `cat`+ // reads EOF and exits 0, so without a byte count the empty temp was renamed over a good file.+ it.skipIf(!SHELL)('keeps the previous file when the channel ends before the body arrives', () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-eof-'))+ roots.push(root)+ const nativeTarget = path.join(root, 'nodeterm.sh')+ const target = `${shellPath(root)}/nodeterm.sh`+ execFileSync(SHELL!, ['-c', `printf %s old-good-shim > ${quoteRemotePath(target)}`])+ const write = remoteAtomicWrite(target, '#!/bin/sh\necho new\n', { mode: '755' })++ // stdin closed with no data at all — what the host sees when the channel dies first.+ const result = spawnSync(SHELL!, ['-c', write.command], { input: '', encoding: 'utf8' })++ expect(result.status).toBe(REMOTE_WRITE_SHORT_BODY)+ expect(readFileSync(nativeTarget, 'utf8')).toBe('old-good-shim')+ expect(readdirSync(root)).toEqual(['nodeterm.sh'])+ })++ it.skipIf(!SHELL)('keeps the previous file when only part of the body arrives', () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-short-'))+ roots.push(root)+ const nativeTarget = path.join(root, 'config.toml')+ const target = `${shellPath(root)}/config.toml`+ execFileSync(SHELL!, ['-c', `printf %s 'model = "keep"' > ${quoteRemotePath(target)}`])+ // A multi-byte body: the count is UTF-8 bytes, which is what `wc -c` measures.+ const body = 'model = "keep"\n# ünïcødé trust block\n'+ const write = remoteAtomicWrite(target, body)++ const result = spawnSync(SHELL!, ['-c', write.command], {+ input: Buffer.from(body, 'utf8').subarray(0, 20),+ encoding: 'utf8'+ })++ expect(result.status).toBe(REMOTE_WRITE_SHORT_BODY)+ expect(readFileSync(nativeTarget, 'utf8')).toBe('model = "keep"')+ expect(readdirSync(root)).toEqual(['config.toml'])+ // …and the whole body, multi-byte characters included, is accepted.+ execFileSync(SHELL!, ['-c', write.command], { input: write.stdin })+ expect(readFileSync(nativeTarget, 'utf8')).toBe(body)+ })++ it.skipIf(!SHELL || process.platform === 'win32')(+ 'publishes a script with the requested mode over an existing file of another mode',+ () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-mode-'))+ roots.push(root)+ const target = path.join(root, 'nodeterm.sh')+ execFileSync(SHELL!, ['-c', `printf old > ${quoteRemotePath(target)} && chmod 644 ${quoteRemotePath(target)}`])+ const write = remoteAtomicWrite(target, '#!/bin/sh\n', { mode: '755' })++ execFileSync(SHELL!, ['-c', write.command], { input: write.stdin })++ expect(readFileSync(target, 'utf8')).toBe('#!/bin/sh\n')+ expect(statSync(target).mode & 0o777).toBe(0o755)+ expect(readdirSync(root)).toEqual(['nodeterm.sh'])+ }+ )++ it('refuses an empty body before any command exists, unless the caller allows one', () => {+ expect(() => remoteAtomicWrite('/h/.nodeterm/nodeterm.sh', '')).toThrow(/empty body/)+ const editorSave = remoteAtomicWrite('/h/notes.txt', '', { allowEmpty: true })+ expect(editorSave.command).toContain('-eq 0 ]')+ })++ it.skipIf(!SHELL)('an allowed empty write still lands (an editor saving an empty file)', () => {+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-remote-empty-'))+ roots.push(root)+ const target = `${shellPath(root)}/notes.txt`+ execFileSync(SHELL!, ['-c', `printf old > ${quoteRemotePath(target)}`])+ const write = remoteAtomicWrite(target, '', { allowEmpty: true })+ execFileSync(SHELL!, ['-c', write.command], { input: write.stdin })+ expect(readFileSync(path.join(root, 'notes.txt'), 'utf8')).toBe('')+ })+})++describe('runRemoteAtomicWrite', () => {+ it('never reaches the runner with an empty body', async () => {+ const run = vi.fn(async () => ({ code: 0 }))+ await expect(runRemoteAtomicWrite(run, '/h/.nodeterm/nodeterm.sh', '')).rejects.toThrow(/empty body/)+ expect(run).not.toHaveBeenCalled()+ })++ it('reports a write that did not land instead of resolving', async () => {+ const run = vi.fn(async () => ({ code: REMOTE_WRITE_SHORT_BODY }))+ const failure = runRemoteAtomicWrite(run, '/h/.nodeterm/nodeterm.sh', 'body')+ await expect(failure).rejects.toBeInstanceOf(RemoteWriteError)+ await expect(failure).rejects.toThrow('/h/.nodeterm/nodeterm.sh did not land (exit 65: the body did not arrive in full)')+ })++ it('hands the runner the body the command was built for', async () => {+ const run = vi.fn(async (_command: string, _stdin: string) => ({ code: 0 }))+ await runRemoteAtomicWrite(run, '/h/f', 'exact body')+ expect(run.mock.calls[0][1]).toBe('exact body')+ expect(run.mock.calls[0][0]).toContain('-eq 10 ]')+ })})diff --git a/src/main/remote-atomic-write.ts b/src/main/remote-atomic-write.tsindex 3ac52016c..428eed9df 100644--- a/src/main/remote-atomic-write.ts+++ b/src/main/remote-atomic-write.ts@@ -3,16 +3,32 @@ import { quoteRemotePath } from '../shared/ssh'export interface RemoteAtomicWrite {command: string+ /** The body the command was built for. Hand THIS to the runner's stdin: the command checks that+ * exactly its byte count arrived, so any other stdin is refused on the host. */+ stdin: stringtemporaryPath: string}+/**+ * Exit status of a write the host refused because the temp did not receive exactly the body's+ * bytes. 65 is sysexits' EX_DATAERR; nothing else in these commands exits with it, so a caller can+ * say "the body did not arrive in full" instead of guessing at a cause.+ */+export const REMOTE_WRITE_SHORT_BODY = 65++export type RemoteFileMode = '600' | '644' | '700' | '755'+export interface RemoteAtomicWriteOptions {/** Apply umask 077 before creating either the parent or the temp. */restrictPermissions?: boolean- /** Belt-and-braces for credential files: enforce 0600 on the temp before it is published. */- chmod600?: boolean+ /** Octal mode set on the temp before it is published; the rename carries it over. Omitted: the+ * temp keeps the mode `cat` created it with (the remote umask). */+ mode?: RemoteFileMode/** False when the caller already created and permissioned the parent directory. */makeParent?: boolean+ /** An editor may legitimately save an empty file. Nothing this app GENERATES is ever empty, so+ * an empty body is refused unless the caller says otherwise. */+ allowEmpty?: boolean}function remoteDirname(path: string): string {@@ -24,7 +40,20 @@ function remoteDirname(path: string): string {}/**- * Build the remote-shell half of a stdin → sibling-temp → rename write.+ * Build the remote-shell half of a stdin → sibling-temp → size check → rename write.+ *+ * WHY THE SIZE CHECK IS THE POINT, not an extra. `cat` cannot tell "the body ended" from "the+ * channel ended": when the ssh channel dies before the body arrives (the ControlMaster killed or+ * rebuilt, the runner's timeout SIGTERMing the child, a dropped link), `cat` reads EOF and exits 0.+ * Measured against OpenSSH 9.6 with the master killed mid-command: a bare `cat > f && chmod 755 f`+ * left `f` at 0 bytes and mode 755 (the chmod ran), and the temp + `mv` shape this function used to+ * build published the empty temp over a good file just the same. A rename only makes a write+ * atomic; it takes the byte count to make it COMPLETE. So the temp must hold exactly the body's+ * UTF-8 byte count before it may be published, and a short temp exits `REMOTE_WRITE_SHORT_BODY`+ * with the target untouched.+ *+ * `wc -c` output is compared inside `[ "…" -eq N ]`: BSD `wc` pads with spaces, which dash, bash+ * (also in POSIX mode) and busybox accept there, and zsh evaluates arithmetically.** The UUID is minted locally for every call. A fixed `<target>.tmp` lets overlapping SSH clients* share one inode: one rename can publish the other writer's partial bytes, then the loser cannot@@ -34,11 +63,18 @@ function remoteDirname(path: string): string {** The cleanup preserves the write/move status. Unique temps do not self-heal on the next write,* so a normal cat/mv failure must remove the exact temp this invocation owns.+ *+ * Throws on an empty body without `allowEmpty` — before any command exists, so nothing reaches ssh.*/export function remoteAtomicWrite(path: string,+ body: string,options: RemoteAtomicWriteOptions = {}): RemoteAtomicWrite {+ if (body === '' && !options.allowEmpty) {+ throw new Error(`refusing to write an empty body to ${path}`)+ }+ const bytes = Buffer.byteLength(body, 'utf8')const parentPath = remoteDirname(path)const temporaryLeaf = `.nodeterm-${randomUUID()}.tmp`// Keep the temp beside the target so mv remains one-filesystem atomic, but do not extend the@@ -55,10 +91,44 @@ export function remoteAtomicWrite(const parent = options.makeParent === false? '': `mkdir -p -- ${quoteRemotePath(parentPath)} && `- const protect = options.chmod600 ? ` && chmod 600 -- ${temporary}` : ''+ const complete = ` && { [ "$(wc -c < ${temporary})" -eq ${bytes} ] || (exit ${REMOTE_WRITE_SHORT_BODY}); }`+ const protect = options.mode ? ` && chmod ${options.mode} -- ${temporary}` : ''const command =- `${prefix}${parent}{ cat > ${temporary}${protect} && mv -f -- ${temporary} ${target}; ` ++ `${prefix}${parent}{ cat > ${temporary}${complete}${protect} && mv -f -- ${temporary} ${target}; ` +`nt_status=$?; ` +`rm -f -- ${temporary}; exit "$nt_status"; }`- return { command, temporaryPath }+ return { command, stdin: body, temporaryPath }+}++/** A remote write that did not land. The message names the path and the exit status only — never+ * the body, which can be a credential or a user's config. */+export class RemoteWriteError extends Error {+ constructor(+ readonly path: string,+ readonly code: number+ ) {+ super(+ `remote write of ${path} did not land (exit ${code}` ++ (code === REMOTE_WRITE_SHORT_BODY ? ': the body did not arrive in full' : '') ++ '); the previous file is unchanged'+ )+ this.name = 'RemoteWriteError'+ }+}++/**+ * Run one `remoteAtomicWrite` and REPORT the outcome: resolves when the file landed, throws a+ * `RemoteWriteError` when it did not. The runners in this app RESOLVE on a non-zero exit, and every+ * caller that awaited `run(...)` and moved on turned a failed write into a silent success — which+ * is how a host ended up with 0-byte canvas-control shims that exited 0 for every agent.+ */+export async function runRemoteAtomicWrite(+ run: (command: string, stdin: string) => Promise<{ code: number }>,+ path: string,+ body: string,+ options: RemoteAtomicWriteOptions = {}+): Promise<void> {+ const write = remoteAtomicWrite(path, body, options)+ const { code } = await run(write.command, write.stdin)+ if (code !== 0) throw new RemoteWriteError(path, code)}diff --git a/src/main/remote-ssh/legacy-hook-endpoint.test.ts b/src/main/remote-ssh/legacy-hook-endpoint.test.tsindex e9fb15c95..96e5eaebf 100644--- a/src/main/remote-ssh/legacy-hook-endpoint.test.ts+++ b/src/main/remote-ssh/legacy-hook-endpoint.test.ts@@ -26,6 +26,19 @@ describe.skipIf(process.platform === 'win32')('legacy SSH endpoint migration (reexpect(fs.statSync(file).mode & 0o777).toBe(0o600)expect(fs.readdirSync(path.dirname(file))).toEqual(['legacy.env'])})+ it.each([['no body at all', ''], ['a cut-short body', fresh.slice(0, 20)]])(+ 'keeps the old endpoint when the channel ends early (%s)',+ (_label, delivered) => {+ // `cat` exits 0 on EOF; only the byte count tells a cut-short stage from the real body.+ const file = fixture()+ fs.writeFileSync(file, old)+ const migration = legacyEndpointMigration(file, old, fresh, ['old-secret'])!+ const result = spawnSync('/bin/sh', ['-c', migration.command], { input: delivered })+ expect(result.status).not.toBe(0)+ expect(fs.readFileSync(file, 'utf8')).toBe(old)+ expect(fs.readdirSync(path.dirname(file))).toEqual(['legacy.env'])+ }+ )it('refuses an unknown owner and malformed credentials', () => {expect(legacyEndpointMigration(fixture(), old, fresh, ['other'])).toBeNull()expect(legacyEndpointMigration(fixture(), 'partial', fresh, [''])).toBeNull()diff --git a/src/main/remote-ssh/legacy-hook-endpoint.ts b/src/main/remote-ssh/legacy-hook-endpoint.tsindex cbeb9bc37..997177671 100644--- a/src/main/remote-ssh/legacy-hook-endpoint.ts+++ b/src/main/remote-ssh/legacy-hook-endpoint.ts@@ -15,9 +15,12 @@ export function legacyEndpointMigration(// A digest is public comparison data, never the old or new bearer. Both credentials stay// off argv. Refuse symlinks, concurrent changes and overlapping migration writers.const cleanup = posixQuote(`rm -f -- ${stage}; rmdir ${q}.migration-lock`)+ // The byte count: `cat` exits 0 on a channel that ended before the body did, and the digest+ // below vouches for the OLD file only — without it a short stage was published as the endpoint.+ const bytes = Buffer.byteLength(contents, 'utf8')const command = `umask 077; mkdir ${q}.migration-lock 2>/dev/null || exit 1; ` +`trap ${cleanup} EXIT; ` +- `cat > ${stage} && chmod 600 ${stage} && test ! -L ${q} && test -f ${q} && ` ++ `cat > ${stage} && [ "$(wc -c < ${stage})" -eq ${bytes} ] && chmod 600 ${stage} && test ! -L ${q} && test -f ${q} && ` +`test "$( (sha256sum < ${q} 2>/dev/null || shasum -a 256 < ${q}) | cut -d ' ' -f 1)" = '${digest}' && mv -f -- ${stage} ${q}`return { command, stdin: contents }}diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex f2784bf0e..100e021f0 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -47,6 +47,13 @@ function harness(return { rh: new RemoteHooks({ run }), calls, runs: calls, run, conn }}+/** A remote command that PUBLISHES `p`: every write now ends in a rename onto the quoted path —+ * our own files from a size-checked temp, the user's files from the guarded transaction. */+const writesTo = (cmd: string, p: string) => cmd.includes('mv -f -- ') && cmd.includes(`'${p}'`)+/** The temp an owned-file write stages into, when `cmd` publishes `p` (see remoteAtomicWrite). */+const tempFor = (cmd: string, p: string) =>+ writesTo(cmd, p) ? cmd.match(/cat > ('[^']*\.nodeterm-[0-9a-f-]{36}\.tmp')/)?.[1] : undefined+describe('RemoteHooks.setup', () => {it('migrates a legacy file using this installation’s previous qualified bearer', async () => {const legacy = "NODETERM_HOOK_TOKEN='previous-secret'\nNODETERM_HOOK_SOCK='/stale'\n"@@ -104,8 +111,13 @@ describe('RemoteHooks.setup', () => {/NODETERM_HOOK_SOCK='\/home\/u\/.nodeterm\/hook-[a-f0-9]{20}\.sock'/.test(c.stdin ?? ''))).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)+ // managed script written to the absolute path (size-checked temp, 755, renamed) + config+ // merged with the guarded command.+ const scriptWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/agent-hooks/claude.sh'))+ const scriptTemp = tempFor(scriptWrite ?? '', '/home/u/.nodeterm/agent-hooks/claude.sh')+ expect(scriptTemp).toBeTruthy()+ expect(scriptWrite).toContain(`chmod 755 -- ${scriptTemp}`)+ expect(scriptWrite).toContain(`[ "$(wc -c < ${scriptTemp})" -eq `)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@@ -144,24 +156,29 @@ describe('RemoteHooks.setup', () => {expect(res).not.toBeNull()const joined = calls.map((c) => c.args.join(' '))// codex managed script written to the absolute agent-hooks path (paths are posix-quoted).- expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/agent-hooks/codex.sh'"))).toBe(true)- // hooks.json merged with the [ -x ] guarded command (embedded as JSON in stdin).+ expect(joined.some((j) => writesTo(j, '/home/u/.nodeterm/agent-hooks/codex.sh'))).toBe(true)+ // hooks.json merged with the [ -x ] guarded command (embedded as JSON in stdin) — through the+ // guarded transaction, because hooks.json is the USER's file.expect(calls.some((c) =>- c.args.join(' ').includes("cat > '/home/u/.codex/hooks.json'") &&+ writesTo(c.cmd, '/home/u/.codex/hooks.json') &&+ c.cmd.includes('.nodeterm-lock') &&(c.stdin ?? '').includes("if [ -x '/home/u/.nodeterm/agent-hooks/codex.sh' ]"))).toBe(true)- // the part claude/gemini don't need: a config.toml trust block with a trusted_hash.+ // the part claude/gemini don't need: a config.toml trust block with a trusted_hash — the+ // user's file too, so the same transaction (never `cat > config.toml`).expect(calls.some((c) =>- c.args.join(' ').includes("cat > '/home/u/.codex/config.toml'") &&+ writesTo(c.cmd, '/home/u/.codex/config.toml') &&+ c.cmd.includes('.nodeterm-lock') &&(c.stdin ?? '').includes('[hooks.state.') &&(c.stdin ?? '').includes('trusted_hash = "sha256:'))).toBe(true)+ expect(joined.some((j) => j.includes("cat > '/home/u/.codex/"))).toBe(false)// no unexpanded tilde anywhere in the codex path work either.expect(joined.some((j) => j.includes('~/'))).toBe(false)})@@ -173,16 +190,18 @@ describe('RemoteHooks.setup', () => {const joined = args.join(' ')if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }if (joined.includes('%{http_code}')) return { code: 0, stdout: '204' }- // present-but-broken hooks.json (the `|| echo '{}'` only fires when the file is MISSING).- if (joined.includes("cat '/home/u/.codex/hooks.json'")) return { code: 0, stdout: '{ not json' }+ // present-but-broken hooks.json, as the guarded read reports it (resolved path, then bytes).+ if (joined.includes("nt_resolve '/home/u/.codex/hooks.json' || exit 1")) {+ return { code: 0, stdout: '/home/u/.codex/hooks.json\n{ not json' }+ }return { code: 0, stdout: '' }})await new RemoteHooks({ run }).setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })const joined = calls.map((c) => c.args.join(' '))// the script is still (idempotently) written, but neither hooks.json nor config.toml is rewritten.- expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/agent-hooks/codex.sh'"))).toBe(true)- expect(joined.some((j) => j.includes("cat > '/home/u/.codex/hooks.json'"))).toBe(false)- expect(joined.some((j) => j.includes("cat > '/home/u/.codex/config.toml'"))).toBe(false)+ expect(joined.some((j) => writesTo(j, '/home/u/.nodeterm/agent-hooks/codex.sh'))).toBe(true)+ expect(joined.some((j) => writesTo(j, '/home/u/.codex/hooks.json'))).toBe(false)+ expect(joined.some((j) => j.includes('/home/u/.codex/config.toml'))).toBe(false)})it('verifies the tunnel end-to-end and heals a stale forward with one rebind', async () => {@@ -465,16 +484,16 @@ describe('RemoteHooks.setup — grok', () => {expect(Object.keys(cfg.hooks).sort()).toEqual(GROK_EVENTS)})- it('quotes the remote dirname, so a $GROK_HOME containing a space still installs', async () => {+ it('quotes the remote parent, so a $GROK_HOME containing a space still installs', async () => {// isSafeRemoteGrokHome deliberately permits spaces. An unquoted `mkdir -p $(dirname '…')`- // word-splits into two args, never creates the directory, and the correctly-quoted `cat >`- // then fails — fail-open, so the only symptom is a host with no hooks and no diagnostic.+ // word-splits into two args, never creates the directory, and the correctly-quoted write+ // then fails — fail-open, so the only symptom is a host with no hooks.const { rh, conn, runs } = harness({responses: { '$HOME': '/home/dev', 'GROK_HOME': '/opt/my grok' }})await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })- const write = runs.find((r) => r.cmd.includes('cat > ') && r.cmd.includes('nodeterm-status.json'))- expect(write!.cmd).toContain(`mkdir -p "$(dirname '/opt/my grok/hooks/nodeterm-status.json')"`)+ const write = runs.find((r) => writesTo(r.cmd, '/opt/my grok/hooks/nodeterm-status.json'))+ expect(write!.cmd).toContain(`mkdir -p -- '/opt/my grok/hooks'`)})it('a grok failure never breaks the connect (fail open)', async () => {@@ -590,7 +609,7 @@ describe('RemoteHooks.teardown', () => {})describe('RemoteHooks.installCanvasControl', () => {- const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)+ const isWriteTo = (args: string[], p: string) => writesTo(args.join(' '), p)it('writes an executable shim + the skill, and merges every instruction-file block', async () => {const { rh, calls } = harness()@@ -598,7 +617,8 @@ describe('RemoteHooks.installCanvasControl', () => {const joined = calls.map((c) => c.args.join(' '))// The shim must land executable: the skill tells the agent to run it via `sh <path>`, but the// instruction blocks and a user's own habits may exec it directly.- expect(joined.some((j) => j.includes('cat > \'/home/u/.nodeterm/nodeterm.sh\'') && j.includes('chmod 755'))).toBe(true)+ const shimWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/nodeterm.sh')) ?? ''+ expect(shimWrite).toContain(`chmod 755 -- ${tempFor(shimWrite, '/home/u/.nodeterm/nodeterm.sh')}`)// It is the POSIX shim, NOT the retired Electron-as-Node one — nothing may reference a local// interpreter path, which is exactly what made the old CLI unusable off the desktop.const shim = calls.find((c) => isWriteTo(c.args, '/home/u/.nodeterm/nodeterm.sh'))?.stdin ?? ''@@ -625,18 +645,15 @@ describe('RemoteHooks.installCanvasControl', () => {it('preserves existing instruction-file content and rewrites its own block only', async () => {const existing = '# my notes\n\n<!-- nodeterm:manage-canvas:start -->\nSTALE\n<!-- nodeterm:manage-canvas:end -->\n'- const calls: { args: string[]; stdin?: string }[] = []- const run = vi.fn(async (args: string[], stdin?: string) => {- calls.push({ args, stdin })- const joined = args.join(' ')- if (joined.includes('.codex/AGENTS.md') && !joined.includes('cat >')) return { code: 0, stdout: existing }- return { code: 0, stdout: '' }- })- await new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')+ const { rh, calls } = harness({ responses: { '.codex/AGENTS.md': existing } })+ await rh.installCanvasControl(conn, '/s.sock', '/home/u')const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))- expect(write?.stdin).toContain('# my notes')- expect(write?.stdin).not.toContain('STALE')- expect(write?.stdin).toContain('nodeterm canvas')+ // The transaction's stdin is the snapshot it read, then the merged file.+ expect(write?.stdin?.startsWith(existing)).toBe(true)+ const merged = write!.stdin!.slice(existing.length)+ expect(merged).toContain('# my notes')+ expect(merged).not.toContain('STALE')+ expect(merged).toContain('nodeterm canvas')})it('skips the write when the block is already current (idempotent reconnects)', async () => {@@ -644,17 +661,12 @@ describe('RemoteHooks.installCanvasControl', () => {// time would churn the user's instruction files (and their mtimes) for nothing.const first = harness()await first.rh.installCanvasControl(conn, '/s.sock', '/home/u')- const merged = first.calls.find((c) => c.args.join(' ').includes('cat > \'/home/u/.gemini/GEMINI.md\''))?.stdin ?? ''+ // A missing file: the snapshot part of stdin is empty, so stdin IS the merged file.+ const merged = first.calls.find((c) => isWriteTo(c.args, '/home/u/.gemini/GEMINI.md'))?.stdin ?? ''expect(merged).toBeTruthy()- const calls: { args: string[]; stdin?: string }[] = []- const run = vi.fn(async (args: string[], stdin?: string) => {- calls.push({ args, stdin })- const joined = args.join(' ')- if (joined.includes('.gemini/GEMINI.md') && !joined.includes('cat >')) return { code: 0, stdout: merged }- return { code: 0, stdout: '' }- })- await new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')+ const { rh, calls } = harness({ responses: { '.gemini/GEMINI.md': merged } })+ await rh.installCanvasControl(conn, '/s.sock', '/home/u')expect(calls.some((c) => isWriteTo(c.args, '/home/u/.gemini/GEMINI.md'))).toBe(false)})@@ -678,13 +690,14 @@ describe('RemoteHooks.installCanvasControl', () => {})describe('RemoteHooks.installContextLink', () => {- const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)+ const isWriteTo = (args: string[], p: string) => writesTo(args.join(' '), p)it('writes an executable shim + the skill, and merges the instruction blocks', async () => {const { rh, calls } = harness()await rh.installContextLink(conn, '/s.sock', '/home/u')const joined = calls.map((c) => c.args.join(' '))- expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/context.sh'") && j.includes('chmod 755'))).toBe(true)+ const shimWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/context.sh')) ?? ''+ expect(shimWrite).toContain(`chmod 755 -- ${tempFor(shimWrite, '/home/u/.nodeterm/context.sh')}`)// The shim is the thin client: it POSTs and prints. All transcript parsing stays on the// desktop, which is what makes the host's missing `node` irrelevant.const shim = calls.find((c) => isWriteTo(c.args, '/home/u/.nodeterm/context.sh'))?.stdin ?? ''@@ -704,17 +717,12 @@ describe('RemoteHooks.installContextLink', () => {// not evict the other, or every connect would leave the host with exactly one of the two.const existing ='<!-- nodeterm:manage-canvas:start -->\nCANVAS BLOCK\n<!-- nodeterm:manage-canvas:end -->\n'- const calls: { args: string[]; stdin?: string }[] = []- const run = vi.fn(async (args: string[], stdin?: string) => {- calls.push({ args, stdin })- const joined = args.join(' ')- if (joined.includes('.codex/AGENTS.md') && !joined.includes('cat >')) return { code: 0, stdout: existing }- return { code: 0, stdout: '' }- })- await new RemoteHooks({ run }).installContextLink(conn, '/s.sock', '/home/u')+ const { rh, calls } = harness({ responses: { '.codex/AGENTS.md': existing } })+ await rh.installContextLink(conn, '/s.sock', '/home/u')const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))- expect(write?.stdin).toContain('CANVAS BLOCK')- expect(write?.stdin).toContain('nodeterm:get-linked-context:start')+ const merged = write!.stdin!.slice(existing.length)+ expect(merged).toContain('CANVAS BLOCK')+ expect(merged).toContain('nodeterm:get-linked-context:start')})it('installs the skill into a remote managed-account config dir', async () => {diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex f87b44a7f..d7f8b1d66 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -14,8 +14,12 @@ import { GROK_EVENTS } from '../../core/agents/hooks/grok'import { GROK_HOOK_FILE, REMOTE_GROK_HOME_PROBE, resolveReportedGrokHome } 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 {+ updateRemoteSettingsFile,+ updateRemoteSettingsFileResult,+ updateRemoteTextFile+} from '../../core/agents/hooks/remote-settings-file'+import { remoteAtomicWrite, runRemoteAtomicWrite, type RemoteAtomicWriteOptions } from '../remote-atomic-write'import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'import { buildManagedScript } from '../../core/agents/hooks/managed-script'import {@@ -39,7 +43,7 @@ import {buildManagedCommand as buildCodexManagedCommand,type HooksConfig as CodexHooksConfig} from '../../core/agents/hooks/codex'-import { upsertHookTrustEntriesInContent } from '../../core/agents/hooks/codex-trust'+import { upsertHookTrustEntriesInContent, type CodexTrustEntry } from '../../core/agents/hooks/codex-trust'import { ensureFullscreenTui } from '../../core/agents/hooks/claude-tui'import {CONTROL_SHIM_SCRIPT,@@ -56,11 +60,15 @@ import {import { posixQuote, type SshConnection } from '../../shared/ssh'import { describeTunnelProbe } from './tunnel-repair'-/** POSIX dirname of an absolute remote path. `path.dirname` would apply the LOCAL separator- * rules, which is wrong the moment the desktop is Windows and the host is Linux. */-function dirnameOf(p: string): string {- const i = p.lastIndexOf('/')- return i > 0 ? p.slice(0, i) : '/'+/**+ * Every install step in this file fails OPEN for the connect — a host that cannot take a hook must+ * not cost the user their terminals — but never SILENTLY. A failed write here once looked exactly+ * like a successful one, and agents then ran against empty shims for a whole session. The message+ * names the step and the error; a `RemoteWriteError` names only the path and the exit status, never+ * file contents.+ */+function warnNotInstalled(what: string, e: unknown): void {+ console.warn(`[remote-hooks] ${what} not installed on the host: ${e instanceof Error ? e.message : String(e)}`)}/**@@ -226,14 +234,14 @@ export class RemoteHooks {// never pointed at a socket that answers nothing. The file carries the hook bearer. A// direct `cat > endpoint` both exposed partial bytes and preserved an old permissive mode;// publish a new 0600 inode through an invocation-owned temp instead.- const endpointWrite = remoteAtomicWrite(endpoint, {- restrictPermissions: true,- chmod600: true,- makeParent: false- })+ const endpointWrite = remoteAtomicWrite(+ endpoint,+ remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`),+ { restrictPermissions: true, mode: '600', makeParent: false }+ )const endpointResult = await this.r.run(childArgs(conn, controlPath, endpointWrite.command),- remoteEndpointFileContents(sock, hook.token, hook.version, `${remoteDir}/node-tokens`)+ endpointWrite.stdin)if (endpointResult.code !== 0) {await this.r.run(hookForwardCancelArgs(conn, controlPath, sock, hook.port)).catch(() => {})@@ -383,15 +391,12 @@ export class RemoteHooks {try {// chmod on the TMP, so the mode is right before the name exists; `mv` within one dir is// a rename, which carries the tmp's 0600 over whatever the destination's mode was.- const write = remoteAtomicWrite(filePath, {- restrictPermissions: true,- chmod600: true,- makeParent: false- })- const w = await this.r.run(- childArgs(conn, controlPath, write.command),- `${token}\n` // newline-terminated: the client reads it with `head -n 1`+ const write = remoteAtomicWrite(+ filePath,+ `${token}\n`, // newline-terminated: the client reads it with `head -n 1`+ { restrictPermissions: true, mode: '600', makeParent: false })+ const w = await this.r.run(childArgs(conn, controlPath, write.command), write.stdin)// The runner RESOLVES on a non-zero exit — a failed write is a `code`, not a throw, and// reading only the throw is how this failure stayed invisible.wrote = w.code === 0@@ -445,19 +450,15 @@ export class RemoteHooks {try {const script = `${remoteDir}/agent-hooks/${target.agentId}.sh`const config = `${home}/${target.config}`- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`- ),- buildManagedScript(target.agentId, REMOTE_IDENTITY_ROOT)- )+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript(target.agentId, REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })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 */+ } catch (e) {+ // Fail-open for the connect, not silent: this agent's remote sessions run without status hooks.+ warnNotInstalled(`${target.agentId} status hook`, e)}}@@ -469,14 +470,9 @@ export class RemoteHooks {): Promise<void> {try {const script = `${remoteDir}/agent-hooks/codex.sh`- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`- ),- buildManagedScript('codex', REMOTE_IDENTITY_ROOT)- )+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript('codex', REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })// POSIX explicitly: the platform argument is the HOST's, never this desktop's. A Windows// desktop writes a `.cmd` command locally (issue #567) and must not put one on a Linux server.const command = buildCodexManagedCommand(script, 'linux')@@ -494,44 +490,34 @@ export class RemoteHooks {))const sourcePath = canonRaw.trim() || hooksFile-- // Read the current hooks.json. `|| echo '{}'` only fires when the file is MISSING, so a- // present-but-malformed file reaches JSON.parse and throws → we skip (never clobber it).- const { stdout: hooksRaw } = await this.r.run(- childArgs(conn, controlPath, `cat ${posixQuote(hooksFile)} 2>/dev/null || echo '{}'`)- )- let existing: CodexHooksConfig | null- try {- const parsed = JSON.parse(hooksRaw || '{}') as unknown- existing =- parsed && typeof parsed === 'object' && !Array.isArray(parsed)- ? (parsed as CodexHooksConfig)- : null- } catch {- existing = null- }- const built = buildCodexHooksAndTrust(existing, command, sourcePath)- if (!built) return // missing is fine ({}); unparseable/odd shape → leave the host's file alone-- await this.r.run(- childArgs(conn, controlPath, `mkdir -p ${posixQuote(codexHome)} && cat > ${posixQuote(hooksFile)}`),- `${JSON.stringify(built.config, null, 2)}\n`- )-- // Trust LAST: read config.toml, line-merge our trust blocks (preserving all other content),- // write back only if it changed. `|| true` so a missing config.toml reads as empty.- const { stdout: tomlRaw } = await this.r.run(- childArgs(conn, controlPath, `cat ${posixQuote(configToml)} 2>/dev/null || true`)- )- const nextToml = upsertHookTrustEntriesInContent(tomlRaw, built.trustEntries)- if (nextToml !== tomlRaw) {- await this.r.run(- childArgs(conn, controlPath, `mkdir -p ${posixQuote(codexHome)} && cat > ${posixQuote(configToml)}`),- nextToml- )- }- } catch {- /* fail-open: the remote codex session simply runs without status hooks */+ const runCmd = (cmd: string, stdin?: string) => this.r.run(childArgs(conn, controlPath, cmd), stdin)++ // hooks.json and config.toml are the USER's files, so both go through the guarded+ // transaction: symlinks kept, mode kept, exactly-the-body-arrived and the-file-is-still-what-+ // we-read both checked before anything is published. A missing file merges as `{}`; a+ // present-but-malformed one fails the parse and is left alone (never clobbered), and so is+ // an odd shape `buildCodexHooksAndTrust` refuses.+ // A holder, not a `let`: TS narrows a closure-assigned `let` back to its initial `null`.+ const trust: { entries: CodexTrustEntry[] | null } = { entries: null }+ const hooks = await updateRemoteSettingsFileResult(hooksFile, runCmd, (cfg) => {+ const built = buildCodexHooksAndTrust(cfg as CodexHooksConfig, command, sourcePath)+ if (!built) return cfg+ trust.entries = built.trustEntries+ return built.config as Record<string, unknown>+ })+ // Trust only a handler hooks.json now carries: a failed write leaves nothing to trust.+ const entries = trust.entries+ if (hooks === 'failed' || !entries) return++ // Trust LAST: line-merge our trust blocks (preserving all other content), write back only if+ // it changed. A missing config.toml reads as empty; 600 because it can hold credentials.+ await updateRemoteTextFile(configToml, runCmd, (before) => {+ const raw = before ?? ''+ const next = upsertHookTrustEntriesInContent(raw, entries)+ return next === raw ? null : next+ })+ } catch (e) {+ warnNotInstalled('codex status hook', e)}}@@ -566,14 +552,9 @@ export class RemoteHooks {const config = `${grokHome.replace(/\/$/, '')}/hooks/${GROK_HOOK_FILE}`const script = `${remoteDir}/agent-hooks/grok.sh`- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`- ),- buildManagedScript('grok', REMOTE_IDENTITY_ROOT)- )+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript('grok', REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })// `|| echo '{}'` fires ONLY when the file is missing — still the read that distinguishes a// missing file from an unreadable one. An unreadable one is then HEALED, not preserved: this// file is ours by name and we rewrite it wholesale, so there is no user content to lose.@@ -587,14 +568,11 @@ export class RemoteHooks {cfg = {}}const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), GROK_EVENTS)- // The `$(dirname …)` is QUOTED: a valid $GROK_HOME may contain spaces, which would otherwise- // word-split into two mkdir args, leave the directory absent, and fail the quoted `cat >`.- await this.r.run(- childArgs(conn, controlPath, `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`),- JSON.stringify(merged, null, 2)- )- } catch {- /* fail-open: the remote grok session simply runs without status hooks */+ // The parent is created by the atomic write as ONE quoted argument, so a valid $GROK_HOME+ // containing spaces still installs (an unquoted `$(dirname …)` split it into two mkdir args).+ await this.writeOwnedFile(conn, controlPath, config, JSON.stringify(merged, null, 2))+ } catch (e) {+ warnNotInstalled('grok status hook', e)}}@@ -609,24 +587,17 @@ export class RemoteHooks {const copilotHome = await this.resolveCopilotHome(conn, controlPath, home)const config = `${copilotHome.replace(/\/$/, '')}/hooks/${COPILOT_HOOK_FILE}`const script = `${remoteDir}/agent-hooks/copilot.sh`- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`- ),- buildManagedScript('copilot', REMOTE_IDENTITY_ROOT)- )- await this.r.run(- childArgs(- conn,- controlPath,- `mkdir -p "$(dirname ${posixQuote(config)})" && cat > ${posixQuote(config)}`- ),+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript('copilot', REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })+ await this.writeOwnedFile(+ conn,+ controlPath,+ config,`${JSON.stringify(buildCopilotHookConfig(buildManagedHookCommand(script)), null, 2)}\n`)- } catch {- /* fail-open: the remote copilot session simply runs without status hooks */+ } catch (e) {+ warnNotInstalled('copilot status hook', e)}}@@ -666,15 +637,14 @@ export class RemoteHooks {const config = `${accountDir}/settings.json`const events = AGENT_TARGETS.find((t) => t.agentId === 'claude')?.events ?? []// Idempotently (re)write the shared hook script — setup() may not have run (fail-open) yet.- await this.r.run(- childArgs(conn, controlPath, `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`),- buildManagedScript('claude', REMOTE_IDENTITY_ROOT)- )+ await this.writeOwnedFile(conn, controlPath, script, buildManagedScript('claude', REMOTE_IDENTITY_ROOT), {+ mode: '755'+ })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 */+ } catch (e) {+ warnNotInstalled('claude status hook for a managed account', e)}}@@ -723,8 +693,10 @@ export class RemoteHooks {for (const t of targets) {await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeCanvasControlBlock, t.prelude)}- } catch {- /* fail-open: the remote agent simply runs without canvas control */+ } catch (e) {+ // Fail-open for the connect, never silent: a shim that did not land is an agent whose canvas+ // calls fail, and this line is the only place that says why.+ warnNotInstalled('canvas control', e)}}@@ -751,8 +723,8 @@ export class RemoteHooks {'manage-nodeterm-canvas',buildCanvasSkillBody(shim))- } catch {- /* fail-open */+ } catch (e) {+ warnNotInstalled('a managed-account skill', e)}}@@ -787,8 +759,8 @@ export class RemoteHooks {for (const t of targets) {await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeInstructionsBlock, t.prelude)}- } catch {- /* fail-open: the remote agent simply runs without context link */+ } catch (e) {+ warnNotInstalled('context link', e)}}@@ -809,8 +781,8 @@ export class RemoteHooks {'get-linked-context',buildContextLinkSkillBody(shim))- } catch {- /* fail-open */+ } catch (e) {+ warnNotInstalled('a managed-account skill', e)}}@@ -820,11 +792,7 @@ export class RemoteHooks {shim: string,body: string): Promise<void> {- const q = posixQuote(shim)- await this.r.run(- childArgs(conn, controlPath, `mkdir -p ${posixQuote(dirnameOf(shim))} && cat > ${q} && chmod 755 ${q}`),- body- )+ await this.writeOwnedFile(conn, controlPath, shim, body, { mode: '755' })}private async writeRemoteSkill(@@ -834,10 +802,34 @@ export class RemoteHooks {name: string,body: string): Promise<void> {- const skill = `${configDir}/skills/${name}/SKILL.md`- await this.r.run(- childArgs(conn, controlPath, `mkdir -p ${posixQuote(dirnameOf(skill))} && cat > ${posixQuote(skill)}`),- body+ await this.writeOwnedFile(conn, controlPath, `${configDir}/skills/${name}/SKILL.md`, body)+ }++ /**+ * Publish one file WE own on the host — a hook script, a canvas/context shim, a skill, our own+ * grok/copilot hook config. Every one of these used to be `cat > <file>`, which truncates the+ * file the moment the remote shell starts: an ssh channel that died before the body arrived left+ * it EMPTY, and `cat` still exited 0. That is how a host ended up with 0-byte `nodeterm.sh` and+ * `context.sh` after a reconnect, on which every agent's canvas call exited 0 with no output.+ *+ * Now: an empty body is refused before any ssh, the body goes to a sibling temp, the host checks+ * that exactly its byte count arrived, and only then is it renamed over the previous file (which+ * is otherwise left exactly as it was). A write that did not land THROWS a `RemoteWriteError` —+ * the runner resolves on a non-zero exit, and awaiting it and moving on is what made the failure+ * silent. The caller's catch logs it and skips the steps that depend on the file.+ */+ private writeOwnedFile(+ conn: SshConnection,+ controlPath: string,+ path: string,+ body: string,+ options: RemoteAtomicWriteOptions = {}+ ): Promise<void> {+ return runRemoteAtomicWrite(+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),+ path,+ body,+ options)}@@ -857,19 +849,21 @@ export class RemoteHooks {merge: (existing: string, block: string) => string,prelude = ''): Promise<void> {- try {- const { stdout: existing } = await this.r.run(- childArgs(conn, controlPath, `${prelude}cat ${pathExpr} 2>/dev/null || true`)- )- const merged = merge(existing, block)- if (merged === existing) return- await this.r.run(- childArgs(conn, controlPath, `${prelude}mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`),- merged- )- } catch {- /* fail-open: one unwritable instruction file must never break the connect */- }+ // These are the USER's instruction files (often a dotfile symlink), so they get the same+ // guarded transaction as settings.json: the link and the mode are kept, and nothing is+ // published unless exactly the merged body arrived and the file still holds what we read. The+ // old `cat … || true` then `cat >` read an UNREADABLE file as empty and replaced the user's+ // text with our block alone. Never throws; a failure is logged and leaves the file as it was.+ await updateRemoteTextFile(+ { pathExpr, prelude, label: pathExpr },+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),+ (before) => {+ const existing = before ?? ''+ const merged = merge(existing, block)+ return merged === existing ? null : merged+ },+ { createMode: '644' }+ )}/**diff --git a/src/main/remote-ssh/remote-write-truncation.test.ts b/src/main/remote-ssh/remote-write-truncation.test.tsnew file mode 100644index 000000000..76f76c037--- /dev/null+++ b/src/main/remote-ssh/remote-write-truncation.test.ts@@ -0,0 +1,240 @@+// A remote write must never leave a truncated file — run for real, under /bin/sh, against a fake+// host tree.+//+// THE INCIDENT (2026-09-28): after the desktop's SSH reconnect, a host's `~/.nodeterm/nodeterm.sh`+// and `context.sh` were 0 bytes, and every agent's `sh nodeterm.sh <verb>` exited 0 with no+// output. The writer was `mkdir -p … && cat > <file> && chmod 755 <file>`, body on stdin. `cat >`+// truncates the file the moment the remote shell starts, and when the ssh channel ends before the+// body arrives `cat` reads EOF and EXITS 0 — so the chmod ran and the runner's non-zero ssh status+// was never looked at. Measured against OpenSSH 9.6 (master SIGKILLed, and the ssh child+// SIGTERMed as the runner's timeout does, both before the body arrived): the target went to+// 0 bytes and 644 → 755 every time. A stand-in ssh that closed stdin reproduced it with the runner+// resolving `code: 0`.+//+// The `cut` runner below is that failure: every command that carries a body gets NO body — the+// host sees stdin at EOF, exactly as when the channel dies first. Read commands run untouched.+import { spawnSync } from 'child_process'+import {+ chmodSync,+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ rmSync,+ statSync,+ symlinkSync,+ writeFileSync+} from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { CONTROL_SHIM_SCRIPT } from '../../core/canvas-control-core'+import { CONTEXT_SHIM_SCRIPT } from '../../core/context-link-core'+import { RemoteHooks, type RemoteRunner } from './remote-hooks'++const conn = { host: 'fixture', user: 'fixture' }+let home: string+let warn: { mock: { calls: unknown[][] } }++beforeEach(() => {+ home = mkdtempSync(path.join(tmpdir(), "nt-remote-write-' h-"))+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+})+afterEach(() => {+ vi.restoreAllMocks()+ rmSync(home, { recursive: true, force: true })+})++/** `cut`: every body is lost; a predicate: only the bodies of the commands it names are lost. */+function hostRunner(mode: 'deliver' | 'cut' | ((command: string) => boolean)): RemoteRunner & { calls: string[] } {+ const calls: string[] = []+ return {+ calls,+ run: async (args, stdin) => {+ const command = args.at(-1)!+ calls.push(command)+ const lose = mode === 'cut' || (typeof mode === 'function' && mode(command))+ const result = spawnSync('/bin/sh', ['-c', command], {+ // Only what the host shell would have: no GROK_HOME / COPILOT_HOME / XDG_* of the machine+ // running the tests may leak into the fake host.+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home },+ input: stdin === undefined ? undefined : lose ? '' : stdin,+ encoding: 'utf8'+ })+ if (result.error) throw result.error+ return { code: result.status ?? 1, stdout: result.stdout }+ }+ }+}++function seed(rel: string, content: string, mode = 0o644): string {+ const file = path.join(home, rel)+ mkdirSync(path.dirname(file), { recursive: true })+ writeFileSync(file, content)+ chmodSync(file, mode)+ return file+}+const read = (rel: string) => readFileSync(path.join(home, rel), 'utf8')+const modeOf = (rel: string) => statSync(path.join(home, rel)).mode & 0o777+/** Every temp an interrupted write owns must be gone — they do not self-heal on the next write. */+function leftovers(): string[] {+ const out: string[] = []+ const walk = (dir: string) => {+ for (const name of readdirSync(dir)) {+ const p = path.join(dir, name)+ if (/^\.nodeterm-/.test(name) || name.endsWith('.nodeterm-lock')) out.push(path.relative(home, p))+ if (lstatSync(p).isDirectory()) walk(p)+ }+ }+ walk(home)+ return out+}+const warned = (needle: string) =>+ warn.mock.calls.some((args: unknown[]) => args.some((a) => typeof a === 'string' && a.includes(needle)))++describe.skipIf(process.platform === 'win32')('remote writes never leave a truncated file (real /bin/sh)', () => {+ it('a normal connect lands both shims whole, executable, with no temp left behind', async () => {+ const rh = new RemoteHooks(hostRunner('deliver'))+ await rh.installCanvasControl(conn, '/fixture.sock', home)+ await rh.installContextLink(conn, '/fixture.sock', home)++ expect(read('.nodeterm/nodeterm.sh')).toBe(CONTROL_SHIM_SCRIPT)+ expect(read('.nodeterm/context.sh')).toBe(CONTEXT_SHIM_SCRIPT)+ expect(modeOf('.nodeterm/nodeterm.sh')).toBe(0o755)+ expect(modeOf('.nodeterm/context.sh')).toBe(0o755)+ expect(read('.claude/skills/manage-nodeterm-canvas/SKILL.md')).toContain('name: manage-nodeterm-canvas')+ expect(read('.codex/AGENTS.md')).toContain('nodeterm:manage-canvas:start')+ expect(read('.codex/AGENTS.md')).toContain('nodeterm:get-linked-context:start')+ // opencode's path is expanded by the host shell ($XDG_CONFIG_HOME unset → $HOME/.config).+ expect(read('.config/opencode/AGENTS.md')).toContain('nodeterm:manage-canvas:start')+ expect(leftovers()).toEqual([])+ })++ it('the incident: a channel that dies before the body leaves the previous shims intact, and says so', async () => {+ seed('.nodeterm/nodeterm.sh', '#!/bin/sh\necho previous-good-shim\n', 0o755)+ seed('.nodeterm/context.sh', '#!/bin/sh\necho previous-good-context\n', 0o755)+ seed('.claude/skills/manage-nodeterm-canvas/SKILL.md', 'previous skill\n')++ const rh = new RemoteHooks(hostRunner('cut'))+ await rh.installCanvasControl(conn, '/fixture.sock', home)+ await rh.installContextLink(conn, '/fixture.sock', home)++ // On the old code both were 0 bytes here, and an agent's `sh nodeterm.sh list` exited 0.+ expect(read('.nodeterm/nodeterm.sh')).toBe('#!/bin/sh\necho previous-good-shim\n')+ expect(read('.nodeterm/context.sh')).toBe('#!/bin/sh\necho previous-good-context\n')+ expect(read('.claude/skills/manage-nodeterm-canvas/SKILL.md')).toBe('previous skill\n')+ expect(leftovers()).toEqual([])+ // Not a silent success: the failure is reported, naming the file and the cause.+ expect(warned(`${home}/.nodeterm/nodeterm.sh did not land (exit 65: the body did not arrive in full)`)).toBe(true)+ expect(warned(`${home}/.nodeterm/context.sh did not land`)).toBe(true)+ })++ it('a channel that dies before the body leaves every agent hook script intact', async () => {+ const agents = ['claude', 'gemini', 'codex', 'grok', 'copilot']+ for (const a of agents) seed(`.nodeterm/agent-hooks/${a}.sh`, `#!/bin/sh\n# previous ${a}\n`, 0o755)+ const rh = new RemoteHooks(hostRunner('cut'))+ const remoteDir = `${home}/.nodeterm`+ await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, remoteDir, {+ agentId: 'claude', config: '.claude/settings.json', events: ['Stop']+ })+ await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, remoteDir, {+ agentId: 'gemini', config: '.gemini/settings.json', events: ['AfterAgent']+ })+ await rh['installCodexRemote'](conn, '/fixture.sock', home, remoteDir)+ await rh['installGrokRemote'](conn, '/fixture.sock', home, remoteDir)+ await rh['installCopilotRemote'](conn, '/fixture.sock', home, remoteDir)+ await rh.installIntoAccountDir(conn, '/fixture.sock', home, 'acc')++ for (const a of agents) expect(read(`.nodeterm/agent-hooks/${a}.sh`)).toBe(`#!/bin/sh\n# previous ${a}\n`)+ expect(leftovers()).toEqual([])+ for (const a of ['claude', 'gemini', 'codex', 'grok', 'copilot']) expect(warned(`${a} status hook not installed`)).toBe(true)+ })++ it("the USER's config files keep their previous content when the body never arrives", async () => {+ const toml = 'model = "o3"\n\n[mcp_servers.docs]\ncommand = "docs-mcp"\n'+ const hooks = '{\n "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": "my-own-hook" } ] } ] }\n}\n'+ const agents = '# my own agent notes\n'+ seed('.codex/config.toml', toml, 0o600)+ seed('.codex/hooks.json', hooks)+ seed('.codex/AGENTS.md', agents)+ seed('.gemini/GEMINI.md', agents)+ seed('.claude/settings.json', '{"model":"opus"}')++ // Only the bodies bound for the user's files are lost; our own scripts and shims land, so the+ // installers really do reach — and publish nothing into — the user's files.+ const usersFile = /(config\.toml|hooks\.json|AGENTS\.md|GEMINI\.md|settings\.json)/+ const rh = new RemoteHooks(hostRunner((command) => usersFile.test(command)))+ await rh['installCodexRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`)+ await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`, {+ agentId: 'claude', config: '.claude/settings.json', events: ['Stop']+ })+ await rh.installCanvasControl(conn, '/fixture.sock', home)+ await rh.installContextLink(conn, '/fixture.sock', home)++ expect(read('.codex/config.toml')).toBe(toml)+ expect(read('.codex/hooks.json')).toBe(hooks)+ expect(read('.codex/AGENTS.md')).toBe(agents)+ expect(read('.gemini/GEMINI.md')).toBe(agents)+ expect(read('.claude/settings.json')).toBe('{"model":"opus"}')+ expect(modeOf('.codex/config.toml')).toBe(0o600)+ expect(leftovers()).toEqual([])+ // The installers did run: our own files landed beside the untouched user files.+ expect(read('.nodeterm/agent-hooks/codex.sh')).toContain('#!/bin/sh')+ expect(read('.nodeterm/nodeterm.sh')).toBe(CONTROL_SHIM_SCRIPT)+ expect(warned(`Remote file unchanged: ${home}/.codex/hooks.json`)).toBe(true)+ // The instruction files are named by their quoted path expression (this $HOME has a quote in it).+ expect(+ warn.mock.calls.some((args: unknown[]) =>+ args.some((a) => typeof a === 'string' && a.includes('Remote file unchanged') && a.includes('/.codex/AGENTS.md'))+ )+ ).toBe(true)+ })++ it("a delivered connect merges into the user's codex files, keeping their content, mode and links", async () => {+ const toml = 'model = "o3"\n\n[mcp_servers.docs]\ncommand = "docs-mcp"\n'+ seed('.codex/config.toml', toml, 0o600)+ seed('.codex/hooks.json', '{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"my-own-hook"}]}]}}')+ // A dotfile-managed AGENTS.md: the link must still be a link afterwards.+ const real = seed('dotfiles/AGENTS.md', '# my own agent notes\n')+ symlinkSync(real, path.join(home, '.codex', 'AGENTS.md'))++ const rh = new RemoteHooks(hostRunner('deliver'))+ await rh['installCodexRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`)+ await rh.installCanvasControl(conn, '/fixture.sock', home)++ const nextToml = read('.codex/config.toml')+ expect(nextToml.startsWith(toml)).toBe(true)+ expect(nextToml).toContain('trusted_hash = "sha256:')+ expect(modeOf('.codex/config.toml')).toBe(0o600)+ const nextHooks = JSON.parse(read('.codex/hooks.json'))+ expect(JSON.stringify(nextHooks)).toContain('my-own-hook')+ expect(JSON.stringify(nextHooks)).toContain('agent-hooks/codex.sh')+ expect(read('.nodeterm/agent-hooks/codex.sh')).toContain('#!/bin/sh')+ expect(modeOf('.nodeterm/agent-hooks/codex.sh')).toBe(0o755)+ expect(lstatSync(path.join(home, '.codex', 'AGENTS.md')).isSymbolicLink()).toBe(true)+ expect(readFileSync(real, 'utf8')).toMatch(/^# my own agent notes\n[\s\S]*nodeterm:manage-canvas:start/)+ expect(leftovers()).toEqual([])+ })++ it('an unreadable instruction file is left alone, not read as empty and replaced by our block', async () => {+ // The old `cat file 2>/dev/null || true` turned a read failure into '' and then wrote our block+ // alone over the user's file. A directory in the file's place is the portable read failure.+ mkdirSync(path.join(home, '.gemini', 'GEMINI.md'), { recursive: true })+ const rh = new RemoteHooks(hostRunner('deliver'))+ await rh.installCanvasControl(conn, '/fixture.sock', home)+ expect(lstatSync(path.join(home, '.gemini', 'GEMINI.md')).isDirectory()).toBe(true)+ expect(warned('Remote file unchanged')).toBe(true)+ })++ it('an empty body is refused before any ssh', async () => {+ const runner = hostRunner('deliver')+ const rh = new RemoteHooks(runner)+ await expect(+ rh['writeOwnedFile'](conn, '/fixture.sock', `${home}/.nodeterm/nodeterm.sh`, '', { mode: '755' })+ ).rejects.toThrow(/empty body/)+ expect(runner.calls).toEqual([])+ expect(existsSync(path.join(home, '.nodeterm'))).toBe(false)+ })+})diff --git a/src/main/remote-ssh/remote-write.guard.test.ts b/src/main/remote-ssh/remote-write.guard.test.tsnew file mode 100644index 000000000..21c17af15--- /dev/null+++ b/src/main/remote-ssh/remote-write.guard.test.ts@@ -0,0 +1,96 @@+// No remote file is written with a bare `cat > <file>`.+//+// `cat > file` truncates the file the moment the remote shell starts, before a byte of the body has+// arrived, and `cat` cannot tell "the body ended" from "the ssh channel ended": when the channel+// dies first (the ControlMaster killed or rebuilt on a reconnect, the runner's timeout SIGTERMing+// the child, a dropped link) it reads EOF and exits 0. On 2026-09-28 that left a host's canvas+// shims at 0 bytes, and every agent's canvas call exited 0 with no output. Measured against+// OpenSSH 9.6, and reproduced under /bin/sh in `remote-write-truncation.test.ts`.+//+// Every one of those writers read as correct, because on a healthy link it IS correct — which is+// the argument for a scan rather than a comment. Remote writes go through `remoteAtomicWrite` /+// `runRemoteAtomicWrite` (sibling temp, exact byte count, rename) or, for the user's own files,+// `updateRemoteTextFile` / `updateRemoteSettingsFile` (the same, plus lock, link and mode).++import { describe, expect, it } from 'vitest'+import { readFileSync, readdirSync, statSync } from 'fs'+import { join, relative } from 'path'++const SOURCE_ROOT = join(__dirname, '..', '..')+const ROOTS = ['core', 'main', 'server'].map((d) => join(SOURCE_ROOT, d))++function sources(dir: string, out: string[] = []): string[] {+ for (const entry of readdirSync(dir)) {+ const p = join(dir, entry)+ if (statSync(p).isDirectory()) {+ if (entry !== 'node_modules') sources(p, out)+ } else if (/\.ts$/.test(entry) && !/\.test\.ts$/.test(entry)) {+ out.push(p)+ }+ }+ return out+}++/**+ * Files allowed to spell `cat >` into a real file, each with the reason. Every entry stages into a+ * temp it owns and checks the byte count before anything is published — or is not a remote write.+ */+const ALLOWED = new Map<string, string>([+ ['main/remote-atomic-write.ts', 'the helper: `cat` into its own temp, byte count checked, then rename'],+ [+ 'core/agents/hooks/remote-settings-file.ts',+ "the user-file transaction: `cat` into its own stage dir, byte count checked, then rename"+ ],+ [+ 'main/remote-ssh/legacy-hook-endpoint.ts',+ 'the endpoint migration: `cat` into its own stage, byte count and digest checked, then rename'+ ],+ ['main/ptmx-limit.ts', 'a LOCAL heredoc under the admin prompt; the body is in the command, not on stdin']+])++/** `cat >` into something other than /dev/null; `cat >>` appends and never truncates. */+const BARE_CAT_WRITE = /\bcat\s*>(?!>)(?!\s*\/dev\/null)/++function isComment(line: string): boolean {+ const t = line.trim()+ return t.startsWith('//') || t.startsWith('*') || t.startsWith('/*')+}++describe('no remote file is written with a bare `cat >`', () => {+ const files = ROOTS.flatMap((r) => sources(r))++ it('finds the source tree (a zero-file scan would pass silently)', () => {+ expect(files.length).toBeGreaterThan(100)+ })++ it('every `cat >` into a file is in the allowlist', () => {+ const offenders: string[] = []+ for (const file of files) {+ const rel = relative(SOURCE_ROOT, file).replace(/\\/g, '/')+ if (ALLOWED.has(rel)) continue+ readFileSync(file, 'utf8')+ .replace(/\r\n/g, '\n')+ .split('\n')+ .forEach((line, i) => {+ if (!isComment(line) && BARE_CAT_WRITE.test(line)) offenders.push(`${rel}:${i + 1}: ${line.trim()}`)+ })+ }+ expect(offenders).toEqual([])+ })++ it('the pattern catches the shapes that shipped, and not the drains', () => {+ // The writer that truncated the shims, and its siblings, exactly as they were spelled.+ expect(BARE_CAT_WRITE.test("mkdir -p ${dir} && cat > ${q} && chmod 755 ${q}")).toBe(true)+ expect(BARE_CAT_WRITE.test('`${prelude}mkdir -p "$(dirname ${pathExpr})" && cat > ${pathExpr}`')).toBe(true)+ expect(BARE_CAT_WRITE.test('umask 077; cat >${posixQuote(launcher)}')).toBe(true)+ // The hook commands drain stdin into /dev/null on purpose; an append never truncates.+ expect(BARE_CAT_WRITE.test("else cat >/dev/null 2>&1 || :; fi")).toBe(false)+ expect(BARE_CAT_WRITE.test("cat > /dev/null")).toBe(false)+ expect(BARE_CAT_WRITE.test('cat >> "$log"')).toBe(false)+ })++ it('every allowlisted file still exists (a stale entry would hide the next offender by name)', () => {+ const rels = new Set(files.map((f) => relative(SOURCE_ROOT, f).replace(/\\/g, '/')))+ expect([...ALLOWED.keys()].filter((k) => !rels.has(k))).toEqual([])+ })+})diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex a89705562..15b0e8df2 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -73,7 +73,7 @@ import { askpassServer } from './ssh-askpass'import { appSshAgent } from './ssh-agent'import { probeAgentSockToPin } from '../../core/remote-ssh/agent-probe'import { sessionName } from '../../core/tmux-naming'-import { remoteAtomicWrite } from '../remote-atomic-write'+import { remoteAtomicWrite, runRemoteAtomicWrite } from '../remote-atomic-write'import { isBoundedAnswerContent, PENDING_REQUEST_MAX_BYTES } from '../../core/agents/permission-decision'import { buildCodexLauncherScript } from '../../core/codex-identity-proxy'import {@@ -959,13 +959,11 @@ export class SshProjectManager {// write (mkdir perms, disk full, …) must leave it undefined so `remoteTmuxCommand`// never passes `-f <missing-conf>` (which makes tmux refuse to start → terminal dies).// The invocation-owned temp also keeps an older valid config intact if ssh drops.- const confWrite = remoteAtomicWrite(confPath)- const w = await this.r.run(- childArgs(conn, controlPath, confWrite.command),- // Lead-pane width applies on the host too: an agent team spawned in a remote- // session squeezes the lead exactly like a local one. 0/absent ⇒ pre-feature conf.- remoteTmuxConf(50000, this.r.leadPaneWidth?.() ?? 0)- )+ // Lead-pane width applies on the host too: an agent team spawned in a remote+ // session squeezes the lead exactly like a local one. 0/absent ⇒ pre-feature conf.+ // The size check inside the write keeps an old conf intact if the body never arrives.+ const confWrite = remoteAtomicWrite(confPath, remoteTmuxConf(50000, this.r.leadPaneWidth?.() ?? 0))+ const w = await this.r.run(childArgs(conn, controlPath, confWrite.command), confWrite.stdin)if (w.code === 0) {// source-file is best-effort (pushes options into a warm server); ignore its result.await this.r.run(childArgs(conn, controlPath, `${remoteTmuxPathPrologue()}tmux -L ${RMT_TMUX_SOCKET} source-file ${posixQuote(confPath)}`))@@ -1649,19 +1647,21 @@ export class SshProjectManager {if (c.controlPath !== controlPath) continue// Refuse a path that is not under a known-safe home shape — belt to the builder's braces.if (/[\0\n\r'"`$\\]/.test(remotePath) || !remotePath.startsWith('/')) return- const dir = remotePath.slice(0, remotePath.lastIndexOf('/'))- await this.r.run(- childArgs(- c.conn,- c.controlPath,- `umask 077; mkdir -p ${posixQuote(dir)} && cat > ${posixQuote(remotePath)}`- ),- content+ // Atomic AND complete: the remote command polls for this file and sources it the moment+ // it exists, so a `cat >` straight at the name could be sourced half-written, and a channel+ // that died before the body arrived left it empty with `cat` still exiting 0.+ await runRemoteAtomicWrite(+ (cmd, stdin) => this.r.run(childArgs(c.conn, c.controlPath, cmd), stdin),+ remotePath,+ content,+ { restrictPermissions: true, mode: '600' })return}- } catch {- /* fail-open: never let an env write reach a pty spawn */+ } catch (e) {+ // Fail-open: never let an env write reach a pty spawn. The agent then launches without its+ // env and fails loudly in its own pane; this line says why.+ console.warn(`[ssh-project] session env not staged: ${e instanceof Error ? e.message : String(e)}`)}}@@ -1799,16 +1799,14 @@ export class SshProjectManager {if (!c) returnconst file = this.statusFilePath(projectId, c)this.statusPushed.add(projectId)- await this.r- .run(- childArgs(- c.conn,- c.controlPath,- remoteAtomicWrite(file, { restrictPermissions: true }).command- ),- json- )- .catch(() => {})+ try {+ // The size check keeps the phone's last good doc if the body never arrives: an empty file+ // there is not "no agents", it is a document the phone cannot parse.+ const write = remoteAtomicWrite(file, json, { restrictPermissions: true })+ await this.r.run(childArgs(c.conn, c.controlPath, write.command), write.stdin)+ } catch {+ /* best-effort, see above */+ }}/**@@ -1905,17 +1903,14 @@ export class SshProjectManager {if (!/^[A-Za-z0-9_-]+$/.test(pendingId)) return falseif (typeof content !== 'string' || !isBoundedAnswerContent(content)) return falseconst file = `${this.pendingDirFor(c)}/${pendingId}.answer`- const { code } = await this.r- .run(- childArgs(- c.conn,- c.controlPath,- remoteAtomicWrite(file, { restrictPermissions: true }).command- ),- content- )- .catch(() => ({ code: 1, stdout: '' }))- return code === 0+ try {+ // The hook polls for this file, so it must never see a truncated answer under its name.+ const write = remoteAtomicWrite(file, content, { restrictPermissions: true })+ const { code } = await this.r.run(childArgs(c.conn, c.controlPath, write.command), write.stdin)+ return code === 0+ } catch {+ return false+ }}/**@@ -2123,26 +2118,26 @@ export class SshProjectManager {// multiplexed ssh child, body on stdin). CodeQL note: this file-data→network write is confined// to the authenticated SSH transport, and the payload is our OWN executable bundle, never a// credential (Property 1). `chmod 700` — owner-only, executable code.- const writeRelay = await this.r.run(- childArgs(- conn,- controlPath,- `umask 077; mkdir -p ${posixQuote(dir)} && cat > ${posixQuote(relay)} && chmod 700 ${posixQuote(relay)}`- ),- source- )- if (writeRelay.code !== 0) return null- // The launcher embeds the app-server start command (absolute node + codex only, no secret). Same- // SSH-tunnel-confined write; still only executable code.- const writeLauncher = await this.r.run(- childArgs(- conn,- controlPath,- `umask 077; cat > ${posixQuote(launcher)} && chmod 700 ${posixQuote(launcher)}`- ),- buildCodexLauncherScript(remoteCodexAppServerStartCommand(runtime, codex))- )- return writeLauncher.code === 0 ? { launcher, relay, runtime, codex } : null+ //+ // Both go through the atomic, size-checked write: a running Codex node executes these files, so+ // a `cat >` that the channel cut short (it truncates first) left every Codex node on the host+ // launching an empty or half-written launcher until the next connect.+ const runCmd = (cmd: string, stdin: string) => this.r.run(childArgs(conn, controlPath, cmd), stdin)+ try {+ await runRemoteAtomicWrite(runCmd, relay, source, { restrictPermissions: true, mode: '700' })+ // The launcher embeds the app-server start command (absolute node + codex only, no secret).+ // Same SSH-tunnel-confined write; still only executable code.+ await runRemoteAtomicWrite(+ runCmd,+ launcher,+ buildCodexLauncherScript(remoteCodexAppServerStartCommand(runtime, codex)),+ { restrictPermissions: true, mode: '700' }+ )+ } catch (e) {+ console.warn(`[ssh-project] codex runtime not installed on the host: ${e instanceof Error ? e.message : String(e)}`)+ return null+ }+ return { launcher, relay, runtime, codex }}/** Ensure one app-server is live for the system account plus each named managed account, anddiff --git a/src/main/ssh-fs.test.ts b/src/main/ssh-fs.test.tsindex 227cd8da4..55db6bb52 100644--- a/src/main/ssh-fs.test.ts+++ b/src/main/ssh-fs.test.ts@@ -18,8 +18,8 @@ describe('ssh-fs arg builders', () => {// ControlMaster killed at quit) mid-write left a HALF/EMPTY file behind — for .nodeterm/project.json// that read as "my project reset itself". Write a unique sibling temp, then mv into place.it('write mkdirs, cats to one per-call temp, then moves and cleans that temp (content via stdin)', () => {- const first = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')- const second = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt').join(' ')+ const first = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt', 'hello').join(' ')+ const second = sshWriteArgs(conn, '/s.sock', '/d/e/f.txt', 'hello').join(' ')const temp = first.match(/cat > '([^']+\.tmp)'/)?.[1]expect(temp).toMatch(/^\/d\/e\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)expect(second).not.toContain(`cat > '${temp}'`)@@ -28,6 +28,12 @@ describe('ssh-fs arg builders', () => {expect(j).toContain(`cat > '${temp}'`)expect(j).toContain(`mv -f -- '${temp}' '/d/e/f.txt'`)expect(j).toContain(`rm -f -- '${temp}'`)+ // `cat` exits 0 on a channel that ended early; only the byte count keeps a short temp from+ // being renamed over the file (it was: an empty project.json after a dropped connection).+ expect(j).toContain(`[ "$(wc -c < '${temp}')" -eq 5 ]`)+ })+ it('write allows an empty file (an editor may save one) and still checks its size', () => {+ expect(sshWriteArgs(conn, '/s', '/d/empty.txt', '').join(' ')).toContain('-eq 0 ]')})// CRITICAL: SSH projects default to a home-relative remoteCwd (`~`). quoteRemotePath must leave a// leading `~/` UNQUOTED so the remote shell tilde-expands it; the remainder stays single-quoted.@@ -35,7 +41,7 @@ describe('ssh-fs arg builders', () => {expect(sshListArgs(conn, '/s', '~/projects').join(' ')).toContain(`ls -Ap1 ~/'projects'`)})it('write keeps ~/ unquoted for the mkdir dirname, the unique temp and the mv', () => {- const j = sshWriteArgs(conn, '/s', '~/projects/file.txt').join(' ')+ const j = sshWriteArgs(conn, '/s', '~/projects/file.txt', 'x').join(' ')expect(j).toContain(`mkdir -p -- ~/'projects'`)const temp = j.match(/cat > ~\/'([^']+\.tmp)'/)?.[1]expect(temp).toMatch(/^projects\/\.nodeterm-[0-9a-f-]{36}\.tmp$/)diff --git a/src/main/ssh-fs.ts b/src/main/ssh-fs.tsindex df504e863..abc1ea348 100644--- a/src/main/ssh-fs.ts+++ b/src/main/ssh-fs.ts@@ -36,12 +36,15 @@ export function sshReadArgs(conn: SshConnection, cp: string, path: string): striexport function sshReadBinaryArgs(conn: SshConnection, cp: string, path: string): string[] {return childArgs(conn, cp, `base64 ${quoteRemotePath(path)}`)}-export function sshWriteArgs(conn: SshConnection, cp: string, path: string): string[] {+export function sshWriteArgs(conn: SshConnection, cp: string, path: string, content: string): string[] {// Atomic: `cat > file` truncates on open, so a connection dropped (or the ControlMaster killed// at app quit) mid-write leaves a half/empty file — fatal for .nodeterm/project.json. Stream to- // a unique sibling temp and mv into place; a write that dies leaves the target untouched.+ // a unique sibling temp and mv into place; a write that dies leaves the target untouched. The+ // byte count is what makes that true: `cat` exits 0 on a channel that ended early, and the+ // rename alone published the short temp. `content` MUST be what the caller sends on stdin.// Per-call uniqueness is load-bearing: two app instances can write this remote path at once.- return childArgs(conn, cp, remoteAtomicWrite(path).command)+ // An editor may legitimately save an empty file, so this generic write allows one.+ return childArgs(conn, cp, remoteAtomicWrite(path, content, { allowEmpty: true }).command)}export function sshMkdirArgs(conn: SshConnection, cp: string, path: string): string[] {return childArgs(conn, cp, `mkdir -p ${quoteRemotePath(path)}`)@@ -187,7 +190,7 @@ export class SshFs {async writeText(ref: SshFsRef, path: string, content: string): Promise<boolean> {try {- const { code } = await this.run(sshWriteArgs(ref.conn, ref.controlPath, path), content)+ const { code } = await this.run(sshWriteArgs(ref.conn, ref.controlPath, path, content), content)return code === 0} catch {return false