Skip to content

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

fix(ssh): publish on macOS hosts, and install canvas + context tools as one chain

review108eb44afed6
diff --git a/CLAUDE.md b/CLAUDE.md
index bce471f41..407df50df 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6522,7 +6522,18 @@ file (the old `cat f || true` then `cat > f` replaced an unreadable AGENTS.md wi
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 app
+`/bin/sh` with the body cut off.
+**Never `chmod <mode> -- <file>` in a remote command.** BSD/macOS chmod does not permute: its
+getopt stops at the MODE operand, so the `--` after it is a FILE named `--` ("No such file or
+directory", exit 1) and the `&&` chain never publishes. `mkdir -p --`, `mv -f --` and `rm -f --` are
+fine (their `--` comes before any operand). That spelling shipped from v0.3.3 (fbc65ad8) for the
+hook endpoint and node tokens, so `setup()` returned null on every macOS SSH host — no status
+hooks, canvas control or context link there. The real-shell tests put a non-permuting chmod
+(`POSIXLY_CORRECT=1` GNU chmod) first on PATH for every mode-bearing caller.
+**Canvas control and context link install as ONE chain** (`RemoteHooks.installAgentTools`): they
+merge different blocks into the same AGENTS.md / GEMINI.md, and the transaction lets only one of two
+racing writers publish a snapshot — fired side by side they lost 16–19 of 48 blocks over 8 fresh
+hosts. Upload directories use UUIDs across app
processes. Downloads and media-cache copies use hidden UUID `.part` names; user-visible downloads
also hold an exclusive candidate lock until the rename and cleanup finish. Never simplify any of
those back to `<target>.tmp` / `<target>.part` or a read-only "does the destination exist?" check —
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 689e51738..0d1a34b6d 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -424,6 +424,10 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
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.
+- **Never write `chmod <mode> -- <file>` into a remote command.** macOS (BSD) chmod stops parsing
+ options at the mode, so the `--` becomes a file operand and the command fails there while passing
+ on Linux. To test it on Linux, put a `POSIXLY_CORRECT=1` wrapper around GNU chmod first on PATH.
+
- **A write ack is a claim about a WRITE, never about what the remote now holds.** Do not retire
state 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 returns
diff --git a/src/core/agents/hooks/remote-settings-file.ts b/src/core/agents/hooks/remote-settings-file.ts
index c8f7a73b2..aa0a053b8 100644
--- a/src/core/agents/hooks/remote-settings-file.ts
+++ b/src/core/agents/hooks/remote-settings-file.ts
@@ -108,7 +108,7 @@ ${unchanged} || exit 1
mv -f -- "$nt_stage/publish" ${q}`
const result = await run(command, (before ?? '') + next)
if (result.code === 73) {
- 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.`)
+ console.warn(`[agent-hooks] Remote file lock held: ${lockPath}. Another nodeterm writer is updating this file right now, so this installation skipped it; the next connect tries again. A lock that stays after every writer has finished was left by an interrupted one: stop nodeterm writers, then remove it.`)
return 'failed'
}
if (result.code !== 0) throw new Error('Remote file publication failed (conflict or I/O error)')
diff --git a/src/core/agents/hooks/settings-file.ts b/src/core/agents/hooks/settings-file.ts
index 9d38e05e5..2f982bb6d 100644
--- a/src/core/agents/hooks/settings-file.ts
+++ b/src/core/agents/hooks/settings-file.ts
@@ -59,7 +59,7 @@ export function updateTextFile(
const file = settingsTarget(requested)
lock = `${file}.nodeterm-lock`
try { mkdirSync(lock) } catch (error) {
- console.warn(`[agent-hooks] Settings lock unavailable: ${lock}. Installation skipped; if it persists, stop nodeterm writers and inspect/remove the stale lock before retrying.`)
+ console.warn(`[agent-hooks] Settings lock held: ${lock}. Another nodeterm writer is updating this file right now, so this installation skipped it; the next launch tries again. A lock that stays after every writer has finished was left by an interrupted one: stop nodeterm writers, then remove it.`)
throw error
}
locked = true
diff --git a/src/main/remote-atomic-write.test.ts b/src/main/remote-atomic-write.test.ts
index 25a84e917..8cfbf6c57 100644
--- a/src/main/remote-atomic-write.test.ts
+++ b/src/main/remote-atomic-write.test.ts
@@ -1,5 +1,5 @@
import { execFileSync, spawn, spawnSync, type ChildProcessWithoutNullStreams } from 'child_process'
-import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'fs'
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'fs'
import os from 'os'
import path from 'path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -70,7 +70,7 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {
expect(second.temporaryPath).not.toBe(first.temporaryPath)
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)}`)
+ 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')
@@ -288,6 +288,74 @@ describe('remoteAtomicWrite', { timeout: REAL_SHELL_TIMEOUT_MS }, () => {
})
})
+// BSD/macOS chmod does not permute: its getopt stops at the MODE operand, so in `chmod 600 -- f`
+// the `--` is a FILE operand ("chmod: --: No such file or directory", exit 1) and the publish never
+// happens. GNU chmod with POSIXLY_CORRECT parses the same way, which is how CI can stand in for a
+// macOS host. `chmod <mode> -- <temp>` shipped from v0.3.3 for the hook endpoint and node tokens.
+describe.skipIf(!SHELL || process.platform === 'win32')('publishing under a non-permuting chmod (BSD/macOS)', () => {
+ function bsdChmodPath(): string {
+ const bin = mkdtempSync(path.join(os.tmpdir(), 'nt-bsd-chmod-'))
+ roots.push(bin)
+ const real = execFileSync(SHELL!, ['-c', 'command -v chmod'], { encoding: 'utf8' }).trim()
+ writeFileSync(path.join(bin, 'chmod'), `#!/bin/sh\nPOSIXLY_CORRECT=1 exec '${real}' "$@"\n`)
+ chmodSync(path.join(bin, 'chmod'), 0o755)
+ return `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}`
+ }
+
+ it('the stand-in really is non-permuting (else every case below proves nothing)', () => {
+ const PATH = bsdChmodPath()
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-bsd-control-'))
+ roots.push(root)
+ writeFileSync(path.join(root, 'f'), 'x')
+ const refused = spawnSync(SHELL!, ['-c', 'chmod 600 -- f'], { cwd: root, env: { ...process.env, PATH }, encoding: 'utf8' })
+ expect(refused.status).not.toBe(0)
+ expect(refused.stderr).toContain('--')
+ const accepted = spawnSync(SHELL!, ['-c', 'chmod 600 f'], { cwd: root, env: { ...process.env, PATH } })
+ expect(accepted.status).toBe(0)
+ })
+
+ // Every mode a caller passes: 600 (hook endpoint, node tokens, session env), 700 (Codex relay and
+ // launcher), 755 (hook scripts, canvas/context shims), 644 (the type allows it).
+ // Under BOTH parsers: a non-permuting chmod reads everything after the mode as a file, while a
+ // PERMUTING one (GNU, the Linux default) would take a temp starting with `-` as options — which is
+ // what the `./` prefix is for.
+ it.each([
+ ...(['600', '644', '700', '755'] as const).map((mode) => ({ mode, chmod: 'non-permuting' as const })),
+ ...(['600', '644', '700', '755'] as const).map((mode) => ({ mode, chmod: 'host default' as const }))
+ ])('publishes mode $mode at every temp-path shape ($chmod chmod)', ({ mode, chmod }) => {
+ const PATH = chmod === 'non-permuting' ? bsdChmodPath() : (process.env.PATH ?? '/usr/bin:/bin')
+ const root = mkdtempSync(path.join(os.tmpdir(), 'nt-bsd-publish-'))
+ roots.push(root)
+ mkdirSync(path.join(root, '-dash'))
+ const cases: { target: string; native: string }[] = [
+ { target: path.join(root, 'absolute.sh'), native: path.join(root, 'absolute.sh') },
+ { target: 'relative-leaf.sh', native: path.join(root, 'relative-leaf.sh') },
+ // A relative parent that starts with `-` would read as an option; it gets `./`.
+ { target: '-dash/under-dash.sh', native: path.join(root, '-dash', 'under-dash.sh') }
+ ]
+ for (const { target, native } of cases) {
+ const write = remoteAtomicWrite(target, '#!/bin/sh\n', { restrictPermissions: mode === '600', mode })
+ const result = spawnSync(SHELL!, ['-c', write.command], {
+ cwd: root,
+ env: { ...process.env, PATH },
+ input: write.stdin,
+ encoding: 'utf8'
+ })
+ expect({ target, status: result.status, stderr: result.stderr }).toEqual({ target, status: 0, stderr: '' })
+ expect(readFileSync(native, 'utf8')).toBe('#!/bin/sh\n')
+ expect(statSync(native).mode & 0o777).toBe(parseInt(mode, 8))
+ }
+ expect(readdirSync(root).filter((n) => n.endsWith('.tmp'))).toEqual([])
+ expect(readdirSync(path.join(root, '-dash')).filter((n) => n.endsWith('.tmp'))).toEqual([])
+ })
+
+ it('never spells `chmod <mode> --`', () => {
+ for (const mode of ['600', '644', '700', '755'] as const) {
+ expect(remoteAtomicWrite('/h/f', 'x', { mode }).command).not.toMatch(/chmod \d+ --/)
+ }
+ })
+})
+
describe('runRemoteAtomicWrite', () => {
it('never reaches the runner with an empty body', async () => {
const run = vi.fn(async () => ({ code: 0 }))
diff --git a/src/main/remote-atomic-write.ts b/src/main/remote-atomic-write.ts
index 428eed9df..1171b4d7c 100644
--- a/src/main/remote-atomic-write.ts
+++ b/src/main/remote-atomic-write.ts
@@ -92,7 +92,14 @@ export function remoteAtomicWrite(
? ''
: `mkdir -p -- ${quoteRemotePath(parentPath)} && `
const complete = ` && { [ "$(wc -c < ${temporary})" -eq ${bytes} ] || (exit ${REMOTE_WRITE_SHORT_BODY}); }`
- const protect = options.mode ? ` && chmod ${options.mode} -- ${temporary}` : ''
+ // NEVER `chmod <mode> -- <file>`. BSD/macOS chmod does not permute: its getopt stops at the MODE
+ // operand, so a `--` after it is read as a FILE named `--` ("chmod: --: No such file or
+ // directory", exit 1) and the publish never happens. That spelling shipped from v0.3.3 on, for the
+ // hook endpoint and node tokens, so every write of them to a macOS host failed. The `--` is not
+ // needed: the temp is absolute, `~/…` or a `.nodeterm-…` leaf; only a relative parent starting
+ // with `-` could look like an option, and that one gets `./`.
+ const chmodTarget = temporaryPath.startsWith('-') ? quoteRemotePath(`./${temporaryPath}`) : temporary
+ const protect = options.mode ? ` && chmod ${options.mode} ${chmodTarget}` : ''
const command =
`${prefix}${parent}{ cat > ${temporary}${complete}${protect} && mv -f -- ${temporary} ${target}; ` +
`nt_status=$?; ` +
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 100e021f0..3793dde8e 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -98,7 +98,7 @@ describe('RemoteHooks.setup', () => {
/cat > ('\/home\/u\/\.nodeterm\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
)?.[1]
expect(endpointTemp).toBeTruthy()
- expect(endpointWrite?.cmd).toContain(`chmod 600 -- ${endpointTemp}`)
+ expect(endpointWrite?.cmd).toContain(`chmod 600 ${endpointTemp}`)
expect(endpointWrite?.cmd).toContain(
`mv -f -- ${endpointTemp} '/home/u/.nodeterm/hook-endpoint-p1-${owner}.env'`
)
@@ -116,7 +116,7 @@ describe('RemoteHooks.setup', () => {
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(`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)
@@ -618,7 +618,7 @@ describe('RemoteHooks.installCanvasControl', () => {
// 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.
const shimWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/nodeterm.sh')) ?? ''
- expect(shimWrite).toContain(`chmod 755 -- ${tempFor(shimWrite, '/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 ?? ''
@@ -697,7 +697,7 @@ describe('RemoteHooks.installContextLink', () => {
await rh.installContextLink(conn, '/s.sock', '/home/u')
const joined = calls.map((c) => c.args.join(' '))
const shimWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/context.sh')) ?? ''
- expect(shimWrite).toContain(`chmod 755 -- ${tempFor(shimWrite, '/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 ?? ''
@@ -780,7 +780,7 @@ describe('RemoteHooks.writeNodeTokens', () => {
/cat > ('\/home\/u\/\.nodeterm\/node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp')/
)?.[1]
expect(temp).toBeTruthy()
- expect(writes[0].cmd).toContain(`chmod 600 -- ${temp}`)
+ expect(writes[0].cmd).toContain(`chmod 600 ${temp}`)
expect(writes[0].cmd).toContain(
`mv -f -- ${temp} '/home/u/.nodeterm/node-tokens/node-1'`
)
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index d7f8b1d66..1c89d0f01 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -648,6 +648,21 @@ export class RemoteHooks {
}
}
+ /**
+ * Canvas control, THEN context link, never both at once.
+ *
+ * They merge DIFFERENT marker blocks into the SAME instruction files (codex AGENTS.md, GEMINI.md,
+ * opencode AGENTS.md), and the guarded transaction publishes a file only if it still holds what
+ * the writer read — so two writers racing on one file cannot both land: the second one finds the
+ * file changed, or our lock held, and skips it. Fired side by side on a connect (as they were),
+ * a fresh host routinely ended up with ONE of the two blocks per file until a later connect. Both
+ * installers fail open, so this never throws.
+ */
+ async installAgentTools(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {
+ await this.installCanvasControl(conn, controlPath, remoteHome)
+ await this.installContextLink(conn, controlPath, remoteHome)
+ }
+
/**
* Install the canvas-control CLI + its discovery docs on the REMOTE host, so an agent running
* in an SSH project can create and organize canvas nodes exactly like a local one.
diff --git a/src/main/remote-ssh/remote-write-truncation.test.ts b/src/main/remote-ssh/remote-write-truncation.test.ts
index 76f76c037..61878555e 100644
--- a/src/main/remote-ssh/remote-write-truncation.test.ts
+++ b/src/main/remote-ssh/remote-write-truncation.test.ts
@@ -13,7 +13,7 @@
//
// 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 { execFileSync, spawn, spawnSync } from 'child_process'
import {
chmodSync,
existsSync,
@@ -33,33 +33,59 @@ 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'
+import { SshProjectManager } from './ssh-project'
const conn = { host: 'fixture', user: 'fixture' }
let home: string
+let bsdBin: string
let warn: { mock: { calls: unknown[][] } }
beforeEach(() => {
home = mkdtempSync(path.join(tmpdir(), "nt-remote-write-' h-"))
warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ // Every fake host runs a NON-PERMUTING chmod first on PATH, as a macOS host has: BSD chmod stops
+ // parsing options at the mode, so `chmod 600 -- f` treats `--` as a file and fails. GNU chmod
+ // under POSIXLY_CORRECT parses the same way. See remote-atomic-write.test.ts for the control.
+ bsdBin = mkdtempSync(path.join(tmpdir(), 'nt-bsd-chmod-'))
+ if (process.platform !== 'win32') {
+ const real = execFileSync('/bin/sh', ['-c', 'command -v chmod'], { encoding: 'utf8' }).trim()
+ writeFileSync(path.join(bsdBin, 'chmod'), `#!/bin/sh\nPOSIXLY_CORRECT=1 exec '${real}' "$@"\n`)
+ chmodSync(path.join(bsdBin, 'chmod'), 0o755)
+ }
})
afterEach(() => {
vi.restoreAllMocks()
rmSync(home, { recursive: true, force: true })
+ rmSync(bsdBin, { recursive: true, force: true })
})
+const hostEnv = (h: string) => ({ PATH: `${bsdBin}:${process.env.PATH ?? '/usr/bin:/bin'}`, HOME: h })
+/** The two runner calls that are not a remote shell command: the mux `-O forward/cancel` and the
+ * tunnel's own curl probe, which answers only through a live reverse forward. */
+function fakeTransport(args: string[], command: string): { code: number; stdout: string } | null {
+ if (args[0] === '-O') return { code: 0, stdout: '' }
+ if (command.includes('%{http_code}')) return { code: 0, stdout: '204' }
+ return null
+}
+
/** `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[] } {
+function hostRunner(
+ mode: 'deliver' | 'cut' | ((command: string) => boolean),
+ h: () => string = () => home
+): RemoteRunner & { calls: string[] } {
const calls: string[] = []
return {
calls,
run: async (args, stdin) => {
const command = args.at(-1)!
calls.push(command)
+ const faked = fakeTransport(args, command)
+ if (faked) return faked
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 },
+ env: hostEnv(h()),
input: stdin === undefined ? undefined : lose ? '' : stdin,
encoding: 'utf8'
})
@@ -238,3 +264,144 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a trunc
expect(existsSync(path.join(home, '.nodeterm'))).toBe(false)
})
})
+
+describe.skipIf(process.platform === 'win32')('every mode-bearing caller publishes on a macOS host (non-permuting chmod)', () => {
+ it('setup(): the hook endpoint lands 0600, every agent hook script 0755', async () => {
+ const rh = new RemoteHooks(hostRunner('deliver'))
+ const res = await rh.setup('p1', conn, '/fixture.sock', { port: 51234, token: 'tok', version: '1' })
+ // On a host whose chmod does not permute, `chmod 600 -- <temp>` failed the endpoint write, so
+ // setup returned null and the host got no status hooks, canvas control or context link at all.
+ expect(res).not.toBeNull()
+ const endpoint = res!.endpointPath
+ expect(readFileSync(endpoint, 'utf8')).toContain("NODETERM_HOOK_TOKEN='tok'")
+ expect(statSync(endpoint).mode & 0o777).toBe(0o600)
+ for (const a of ['claude', 'gemini', 'codex', 'grok', 'copilot']) {
+ expect(modeOf(`.nodeterm/agent-hooks/${a}.sh`)).toBe(0o755)
+ }
+ expect(leftovers()).toEqual([])
+ })
+
+ it('node tokens land 0600', async () => {
+ const rh = new RemoteHooks(hostRunner('deliver'))
+ await rh.writeNodeTokens(conn, '/fixture.sock', home, ['n-1', 'n-2'], (id) => `token-${id}`)
+ for (const id of ['n-1', 'n-2']) {
+ expect(read(`.nodeterm/node-tokens/${id}`)).toBe(`token-${id}\n`)
+ expect(modeOf(`.nodeterm/node-tokens/${id}`)).toBe(0o600)
+ }
+ })
+
+ it('the canvas/context shims and a managed-account hook script land 0755', async () => {
+ const rh = new RemoteHooks(hostRunner('deliver'))
+ await rh.installAgentTools(conn, '/fixture.sock', home)
+ await rh.installIntoAccountDir(conn, '/fixture.sock', home, 'acc')
+ expect(modeOf('.nodeterm/nodeterm.sh')).toBe(0o755)
+ expect(modeOf('.nodeterm/context.sh')).toBe(0o755)
+ expect(modeOf('.nodeterm/agent-hooks/claude.sh')).toBe(0o755)
+ })
+
+ describe('ssh-project writers', () => {
+ // writeSessionEnvFile refuses a path holding a quote, so these use a plain home.
+ let plain: string
+ beforeEach(() => { plain = mkdtempSync(path.join(tmpdir(), 'nt-rw-plain-')) })
+ afterEach(() => rmSync(plain, { recursive: true, force: true }))
+
+ function manager(): SshProjectManager {
+ const runner = hostRunner('deliver', () => plain)
+ const run = vi.fn(async (args: string[], stdin?: string) => {
+ const command = args.at(-1)!
+ // The login-shell probe for node/codex/curl: answer it like a host that has all three.
+ if (command.includes('command -v node')) {
+ return { code: 0, stdout: '/usr/bin/node\n/usr/bin/codex\n/usr/bin/curl\n' }
+ }
+ return runner.run(args, stdin)
+ })
+ const mgr = new SshProjectManager({
+ userDataDir: plain,
+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),
+ run,
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ codexRelaySource: async () => '// relay bundle\n',
+ onStatus: () => {}
+ } as never)
+ ;(mgr as unknown as { conns: Map<string, unknown> }).conns.set('p1', {
+ conn,
+ controlPath: '/fixture.sock',
+ master: { kill: () => {}, on: () => {} },
+ remoteCwd: '~'
+ })
+ return mgr
+ }
+
+ it('a session env file lands 0600', async () => {
+ const file = path.join(plain, '.nodeterm', 'env', 'nt-n1.env')
+ await manager().writeSessionEnvFile('/fixture.sock', file, "export KEY='v'\n")
+ expect(readFileSync(file, 'utf8')).toBe("export KEY='v'\n")
+ expect(statSync(file).mode & 0o777).toBe(0o600)
+ expect(warned('session env not staged')).toBe(false)
+ })
+
+ it('the Codex relay and launcher land 0700', async () => {
+ const mgr = manager()
+ const installed = await (
+ mgr as unknown as { installRemoteCodexRuntime: (c: unknown, cp: string, h: string) => Promise<unknown> }
+ ).installRemoteCodexRuntime(conn, '/fixture.sock', plain)
+ expect(installed).not.toBeNull()
+ for (const f of ['codex-relay.js', 'nodeterm-codex']) {
+ expect(statSync(path.join(plain, '.nodeterm', 'bin', f)).mode & 0o777).toBe(0o700)
+ }
+ expect(readFileSync(path.join(plain, '.nodeterm', 'bin', 'codex-relay.js'), 'utf8')).toBe('// relay bundle\n')
+ })
+ })
+})
+
+describe.skipIf(process.platform === 'win32')('canvas control and context link share instruction files', () => {
+ /** Real concurrency: each command runs in its own /bin/sh process, and the runner resolves when it
+ * exits, so two installers in flight genuinely interleave on the host. */
+ function asyncHostRunner(h: string): RemoteRunner {
+ return {
+ run: (args, stdin) => {
+ const command = args.at(-1)!
+ const faked = fakeTransport(args, command)
+ if (faked) return Promise.resolve(faked)
+ return new Promise((resolve, reject) => {
+ const child = spawn('/bin/sh', ['-c', command], { env: hostEnv(h) })
+ let stdout = ''
+ child.stdout.setEncoding('utf8')
+ child.stdout.on('data', (c: string) => { stdout += c })
+ child.stdin.on('error', () => {})
+ child.on('error', reject)
+ child.on('close', (code) => resolve({ code: code ?? 1, stdout }))
+ child.stdin.end(stdin ?? '')
+ })
+ }
+ }
+ }
+
+ // ~25 real shell processes per host; the budget is for a loaded CI runner, not the work.
+ it('a fresh connect leaves BOTH blocks in every shared file (8 fresh hosts)', { timeout: 60_000 }, async () => {
+ const shared = ['.codex/AGENTS.md', '.gemini/GEMINI.md', '.config/opencode/AGENTS.md']
+ const missing: string[] = []
+ for (let i = 0; i < 8; i++) {
+ const h = mkdtempSync(path.join(tmpdir(), 'nt-rw-fresh-'))
+ try {
+ await new RemoteHooks(asyncHostRunner(h)).installAgentTools(conn, '/fixture.sock', h)
+ for (const f of shared) {
+ const text = readFileSync(path.join(h, f), 'utf8')
+ if (!text.includes('nodeterm:manage-canvas:start')) missing.push(`${i}:${f}:canvas`)
+ if (!text.includes('nodeterm:get-linked-context:start')) missing.push(`${i}:${f}:context`)
+ }
+ } finally {
+ rmSync(h, { recursive: true, force: true })
+ }
+ }
+ expect(missing).toEqual([])
+ })
+
+ it('the connect path runs them as one chain, never side by side', () => {
+ const src = readFileSync(path.join(__dirname, 'ssh-project.ts'), 'utf8').replace(/\r\n/g, '\n')
+ const code = src.split('\n').filter((l) => !/^\s*(\/\/|\*)/.test(l)).join('\n')
+ expect(code).toContain('this.remoteHooks.installAgentTools(')
+ expect(code).not.toMatch(/void this\.remoteHooks\.install(CanvasControl|ContextLink)\(/)
+ })
+})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 15b0e8df2..644f48005 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -980,8 +980,9 @@ export class SshProjectManager {
// canvas control as unavailable. Not awaited: it is several remote round-trips of pure
// best-effort setup, and holding the connect on them would delay every terminal.
if (remoteHome && hookEndpointPath) {
- void this.remoteHooks.installCanvasControl(conn, controlPath, remoteHome)
- void this.remoteHooks.installContextLink(conn, controlPath, remoteHome)
+ // ONE chain, not two: both merge into the same instruction files, and two writers racing
+ // on one file cannot both publish (see RemoteHooks.installAgentTools).
+ void this.remoteHooks.installAgentTools(conn, controlPath, remoteHome)
// Per-node tokens for every node of this project (the endpoint file written just above
// is what tells the host's hook script where to find them, which is also why this is
// gated on `hookEndpointPath`: a token nothing can be pointed at is a wasted round-trip).