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.

feat(project-setup): streaming ssh runner for manual setup runs

enese99929d639ad
diff --git a/src/core/project-setup-runner-local.ts b/src/core/project-setup-runner-local.ts
index f19d3895c..0e09f504d 100644
--- a/src/core/project-setup-runner-local.ts
+++ b/src/core/project-setup-runner-local.ts
@@ -2,22 +2,13 @@ import { execFile, spawn } from 'child_process'
import path from 'path'
import { findInPathString, shellPathNow } from './exec-path'
import type { ProjectSetupRunner, ProjectSetupTarget } from './project-setup-service'
+import { SETUP_OUTPUT_CAP, SETUP_TIMEOUT_MS, createSetupOutputStream } from './setup-output-stream'
import type { WorktreeListResult } from '../shared/worktree'
-/** Combined stdout+stderr budget for one run — the SAME cap `ProjectSetupEvent.chunk` documents
- * ("stdout+stderr interleaved, capped"). Deliberately one shared budget rather than one per
- * stream: a script that floods only stderr must not get 1MB total just because stdout stayed
- * quiet. */
-export const SETUP_OUTPUT_CAP = 512 * 1024
-/** SIGKILL a run that outlives this — a hung `setupScript` must never wedge the single-flight
- * slot forever. Test-injectable via `opts.timeoutMs` so a suite doesn't wait 10 real minutes. */
-export const SETUP_TIMEOUT_MS = 10 * 60 * 1000
-/** Chunks are batched to `onChunk` at most this often (plus one final flush on exit), matching
- * the debounce the brief calls for — a script that `echo`s in a tight loop must not turn into
- * an event per line. */
-const FLUSH_DEBOUNCE_MS = 150
-
-const TRUNCATION_NOTE = '\n[output truncated — exceeded 512KB]\n'
+// The cap/timeout/debounce/truncation rules moved to `setup-output-stream.ts` when the SSH runner
+// arrived — both runners MUST report the same way (see that file). Re-exported here because this
+// module was their original home and callers/tests import them from it.
+export { SETUP_OUTPUT_CAP, SETUP_TIMEOUT_MS }
/** Resolve a configured shell to an absolute path via the cached login-shell PATH (exec-path.ts) —
* a GUI process's inherited PATH misses Homebrew/nvm/etc, the same problem commit-message.ts's
@@ -49,50 +40,7 @@ export function makeLocalSetupRunner(opts?: { shell?: string; timeoutMs?: number
return
}
- let totalBytes = 0
- let truncated = false
- let pending = ''
- let flushTimer: ReturnType<typeof setTimeout> | null = null
-
- const flush = (): void => {
- if (flushTimer) {
- clearTimeout(flushTimer)
- flushTimer = null
- }
- if (!pending) return
- const text = pending
- pending = ''
- onChunk(text)
- }
-
- const scheduleFlush = (): void => {
- if (flushTimer) return
- flushTimer = setTimeout(flush, FLUSH_DEBOUNCE_MS)
- flushTimer.unref?.()
- }
-
- const append = (text: string): void => {
- if (!text || truncated) return
- const remaining = SETUP_OUTPUT_CAP - totalBytes
- if (remaining <= 0) {
- truncated = true
- pending += TRUNCATION_NOTE
- scheduleFlush()
- return
- }
- const asBytes = Buffer.byteLength(text, 'utf-8')
- if (asBytes <= remaining) {
- pending += text
- totalBytes += asBytes
- } else {
- const cut = Buffer.from(text, 'utf-8').subarray(0, remaining).toString('utf-8')
- pending += cut
- totalBytes += Buffer.byteLength(cut, 'utf-8')
- truncated = true
- pending += TRUNCATION_NOTE
- }
- scheduleFlush()
- }
+ const { append, flush } = createSetupOutputStream(onChunk)
const isWin = process.platform === 'win32'
const shellBin = resolveShellBin(shell)
diff --git a/src/core/setup-output-stream.ts b/src/core/setup-output-stream.ts
new file mode 100644
index 000000000..277690c64
--- /dev/null
+++ b/src/core/setup-output-stream.ts
@@ -0,0 +1,87 @@
+/**
+ * The output discipline every `ProjectSetupRunner` shares: one capped budget, debounced chunk
+ * delivery, exactly one truncation note.
+ *
+ * Extracted from the local runner when the SSH runner arrived, because the rules here are a
+ * CONTRACT the service layer and the UI both depend on ("stdout+stderr interleaved, capped",
+ * one event per burst rather than per line) — not an implementation detail either runner is free
+ * to drift on. Two copies would drift: the first cap bump or note reword would land in one file
+ * and be forgotten in the other, and the UI would silently show two different truncation stories
+ * depending on whether the project happened to be local or remote.
+ */
+
+/** Combined stdout+stderr budget for one run — the SAME cap `ProjectSetupEvent.chunk` documents
+ * ("stdout+stderr interleaved, capped"). Deliberately one shared budget rather than one per
+ * stream: a script that floods only stderr must not get 1MB total just because stdout stayed
+ * quiet. */
+export const SETUP_OUTPUT_CAP = 512 * 1024
+
+/** SIGKILL a run that outlives this — a hung `setupScript` must never wedge the single-flight
+ * slot forever. Test-injectable via each runner's `opts.timeoutMs` so a suite doesn't wait 10
+ * real minutes. */
+export const SETUP_TIMEOUT_MS = 10 * 60 * 1000
+
+/** Chunks are batched to `onChunk` at most this often (plus one final flush on exit), matching
+ * the debounce the brief calls for — a script that `echo`s in a tight loop must not turn into
+ * an event per line. */
+const FLUSH_DEBOUNCE_MS = 150
+
+const TRUNCATION_NOTE = '\n[output truncated — exceeded 512KB]\n'
+
+export interface SetupOutputStream {
+ /** Feed decoded output (either stream). Past the cap this appends the truncation note ONCE and
+ * drops everything after it. */
+ append(text: string): void
+ /** Deliver whatever is buffered now and cancel the pending debounce — call this exactly once,
+ * from the runner's `finish`, so the tail of a run is never lost to an unfired timer. */
+ flush(): void
+}
+
+export function createSetupOutputStream(onChunk: (text: string) => void): SetupOutputStream {
+ let totalBytes = 0
+ let truncated = false
+ let pending = ''
+ let flushTimer: ReturnType<typeof setTimeout> | null = null
+
+ const flush = (): void => {
+ if (flushTimer) {
+ clearTimeout(flushTimer)
+ flushTimer = null
+ }
+ if (!pending) return
+ const text = pending
+ pending = ''
+ onChunk(text)
+ }
+
+ const scheduleFlush = (): void => {
+ if (flushTimer) return
+ flushTimer = setTimeout(flush, FLUSH_DEBOUNCE_MS)
+ flushTimer.unref?.()
+ }
+
+ const append = (text: string): void => {
+ if (!text || truncated) return
+ const remaining = SETUP_OUTPUT_CAP - totalBytes
+ if (remaining <= 0) {
+ truncated = true
+ pending += TRUNCATION_NOTE
+ scheduleFlush()
+ return
+ }
+ const asBytes = Buffer.byteLength(text, 'utf-8')
+ if (asBytes <= remaining) {
+ pending += text
+ totalBytes += asBytes
+ } else {
+ const cut = Buffer.from(text, 'utf-8').subarray(0, remaining).toString('utf-8')
+ pending += cut
+ totalBytes += Buffer.byteLength(cut, 'utf-8')
+ truncated = true
+ pending += TRUNCATION_NOTE
+ }
+ scheduleFlush()
+ }
+
+ return { append, flush }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index dc669506a..03af5bfc5 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -67,6 +67,7 @@ import { ProjectTrustStore } from '../core/project-trust-store'
import { ProjectSetupService } from '../core/project-setup-service'
import { registerProjectSetupHandlers } from '../core/project-setup-handlers'
import { makeLocalSetupRunner } from '../core/project-setup-runner-local'
+import { makeSshSetupRunner } from './remote-ssh/ssh-setup-runner'
import { registerGitHubIntegration } from '../core/github/integration'
import { runGitHubCliCommand } from '../core/github/credentials'
import {
@@ -356,9 +357,13 @@ const projectTrustStore = new ProjectTrustStore()
const projectSetupService = new ProjectSetupService({
trust: projectTrustStore,
readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),
- runLocal: makeLocalSetupRunner()
- // runSsh: a later task's manual-run leg. Until wired, an ssh target's run answers
- // `{status:'skipped', reason:'unavailable'}` — same as any other missing runner.
+ runLocal: makeLocalSetupRunner(),
+ // The ssh leg streams over the project's LIVE ControlMaster, resolved lazily by remote cwd (the
+ // manager is created only once the window is ready) — the same seam remote git uses. A
+ // disconnected project resolves to null and the runner reports that as a failed run rather than
+ // dialing a fresh connection. Server Edition has no ssh-project manager at all, so it wires
+ // `runLocal` only and an ssh target there stays `{status:'skipped', reason:'unavailable'}`.
+ runSsh: makeSshSetupRunner((remoteCwd) => sshProjectManager?.refForRemoteCwd(remoteCwd) ?? null)
})
registerProjectSetupHandlers(corePlatform, projectSetupService, {
projectTargetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),
diff --git a/src/main/remote-ssh/ssh-setup-runner.test.ts b/src/main/remote-ssh/ssh-setup-runner.test.ts
new file mode 100644
index 000000000..d9844f993
--- /dev/null
+++ b/src/main/remote-ssh/ssh-setup-runner.test.ts
@@ -0,0 +1,286 @@
+import { EventEmitter } from 'events'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { SshConnection } from '../../shared/ssh'
+
+const spawnMock = vi.hoisted(() => vi.fn())
+// Partial: `spawn` is the seam under test, but the same module object backs every OTHER
+// `child_process` import in the graph (exec-path's `execFile`), and a bare stub breaks those.
+vi.mock('node:child_process', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('node:child_process')>()
+ return { ...actual, spawn: spawnMock }
+})
+
+import { makeSshSetupRunner, type SshSetupRef } from './ssh-setup-runner'
+
+/** The child `spawn` returns: an EventEmitter with `stdout`/`stderr` emitters and a spy `kill`. */
+class FakeChild extends EventEmitter {
+ stdout = new EventEmitter()
+ stderr = new EventEmitter()
+ pid = 4242
+ kill = vi.fn(() => true)
+}
+
+const conn: SshConnection = { host: 'example.test', user: 'deploy' }
+const ssh = { server: { host: 'example.test', user: 'deploy' }, remoteCwd: '/srv/app' }
+const ref: SshSetupRef = { conn, controlPath: '/tmp/nt-ctl/example.test-deploy.sock' }
+
+/**
+ * Everything in `cmd` that is NOT inside a single-quoted region. The injection assertion the brief
+ * asks for: a hostile script may contain `$(rm -rf /)`, but every byte of it must land INSIDE a
+ * quoted argument, so the unquoted residue is only the shell syntax WE wrote.
+ */
+function unquotedPart(cmd: string): string {
+ let out = ''
+ let inQuotes = false
+ let i = 0
+ while (i < cmd.length) {
+ const ch = cmd[i]
+ if (inQuotes) {
+ if (ch === "'") inQuotes = false
+ i += 1
+ continue
+ }
+ if (ch === "'") {
+ inQuotes = true
+ i += 1
+ continue
+ }
+ // Outside quotes a backslash escapes the next byte — `'\''` (posixQuote's escape for an
+ // embedded quote) must not be mistaken for "quote closed, then quote reopened".
+ if (ch === '\\') {
+ i += 2
+ continue
+ }
+ out += ch
+ i += 1
+ }
+ expect(inQuotes).toBe(false) // an unbalanced quote would itself be an injection hole
+ return out
+}
+
+describe('makeSshSetupRunner', () => {
+ let child: FakeChild
+
+ beforeEach(() => {
+ spawnMock.mockReset()
+ child = new FakeChild()
+ spawnMock.mockReturnValue(child)
+ })
+
+ afterEach(() => {
+ vi.restoreAllMocks()
+ })
+
+ const run = (
+ opts: {
+ script?: string
+ cwd?: string
+ env?: Record<string, string>
+ resolveRef?: (remoteCwd: string) => SshSetupRef | null
+ timeoutMs?: number
+ ssh?: typeof ssh | undefined
+ signal?: AbortSignal
+ } = {}
+ ) => {
+ const runner = makeSshSetupRunner(opts.resolveRef ?? (() => ref), {
+ timeoutMs: opts.timeoutMs,
+ sshPath: () => '/usr/bin/ssh',
+ agentEnv: () => ({ SSH_AUTH_SOCK: '/tmp/nt-agent.sock' })
+ })
+ const chunks: string[] = []
+ const controller = new AbortController()
+ const promise = runner({
+ script: opts.script ?? 'npm install',
+ cwd: opts.cwd ?? '/srv/app',
+ env: opts.env ?? {},
+ onChunk: (t) => chunks.push(t),
+ signal: opts.signal ?? controller.signal,
+ ssh: 'ssh' in opts ? opts.ssh : ssh
+ })
+ return { promise, chunks, controller }
+ }
+
+ const argv = (): string[] => spawnMock.mock.calls[0][1] as string[]
+ const remoteCommand = (): string => argv()[argv().length - 1]
+
+ it('spawns ONE ssh child whose argv carries the ControlPath', async () => {
+ const { promise } = run()
+ child.emit('close', 0)
+ await promise
+ expect(spawnMock).toHaveBeenCalledTimes(1)
+ expect(spawnMock.mock.calls[0][0]).toBe('/usr/bin/ssh')
+ expect(argv()).toContain(`ControlPath=${ref.controlPath}`)
+ expect(argv()).toContain('ControlMaster=auto')
+ expect(argv()).toContain('[email protected]')
+ })
+
+ it('the remote command cds into the quoted remote cwd and runs the script through sh -lc', async () => {
+ const { promise } = run({ script: 'make build', cwd: '/srv/app' })
+ child.emit('close', 0)
+ await promise
+ expect(remoteCommand()).toContain(`cd '/srv/app' &&`)
+ expect(remoteCommand()).toContain(`sh -lc 'make build'`)
+ })
+
+ it('inlines the env as quoted assignments (ssh forwards no local env)', async () => {
+ const { promise } = run({
+ env: {
+ NODETERM_ROOT_PATH: '/srv/app',
+ NODETERM_WORKTREE_PATH: '/srv/app',
+ NODETERM_PROJECT_NAME: "my app's repo"
+ }
+ })
+ child.emit('close', 0)
+ await promise
+ const cmd = remoteCommand()
+ expect(cmd).toContain(`NODETERM_ROOT_PATH='/srv/app'`)
+ expect(cmd).toContain(`NODETERM_WORKTREE_PATH='/srv/app'`)
+ expect(cmd).toContain(`NODETERM_PROJECT_NAME='my app'\\''s repo'`)
+ // Assignments must precede `sh`, or they are arguments rather than environment.
+ expect(cmd.indexOf('NODETERM_ROOT_PATH=')).toBeLessThan(cmd.indexOf('sh -lc'))
+ })
+
+ it('omits an env entry whose NAME cannot be a shell identifier rather than splicing it', async () => {
+ const { promise } = run({ env: { 'BAD;NAME': 'x', GOOD: 'y' } })
+ child.emit('close', 0)
+ await promise
+ expect(remoteCommand()).not.toContain('BAD')
+ expect(remoteCommand()).toContain(`GOOD='y'`)
+ })
+
+ it('a hostile script and a hostile project name land ONLY inside quoted arguments', async () => {
+ const { promise } = run({
+ script: `'$(rm -rf /)'; echo pwned \`id\``,
+ cwd: "/srv/'; rm -rf /; '",
+ env: { NODETERM_PROJECT_NAME: `x'$(id)'y` }
+ })
+ child.emit('close', 0)
+ await promise
+ const residue = unquotedPart(remoteCommand())
+ expect(residue).not.toContain('$(')
+ expect(residue).not.toContain('`')
+ expect(residue).not.toContain('rm -rf')
+ expect(residue).not.toContain('pwned')
+ expect(residue).not.toContain('id')
+ // What SHOULD remain unquoted is only our own syntax.
+ expect(residue.replace(/\s+/g, ' ').trim()).toContain('cd && ')
+ })
+
+ it('streams stderr as chunks too', async () => {
+ const { promise, chunks } = run()
+ child.stderr.emit('data', Buffer.from('warning: node_modules is stale\n'))
+ child.stdout.emit('data', Buffer.from('ok\n'))
+ child.emit('close', 0)
+ const result = await promise
+ expect(result.exitCode).toBe(0)
+ expect(chunks.join('')).toContain('warning: node_modules is stale')
+ expect(chunks.join('')).toContain('ok')
+ })
+
+ it('coalesces rapid writes into fewer chunks than writes (debounced)', async () => {
+ const { promise, chunks } = run()
+ for (let i = 0; i < 5; i++) child.stdout.emit('data', Buffer.from(`line ${i}\n`))
+ child.emit('close', 0)
+ await promise
+ expect(chunks.length).toBeLessThan(5)
+ expect(chunks.join('')).toContain('line 4')
+ })
+
+ it('propagates the remote exit code', async () => {
+ const { promise } = run()
+ child.emit('close', 7)
+ const result = await promise
+ expect(result.exitCode).toBe(7)
+ })
+
+ it('an abort kills the ssh client (and never spawns a second one)', async () => {
+ const controller = new AbortController()
+ const { promise } = run({ signal: controller.signal, timeoutMs: 60_000 })
+ controller.abort()
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL')
+ child.emit('close', null)
+ const result = await promise
+ expect(result.exitCode).not.toBe(0)
+ expect(spawnMock).toHaveBeenCalledTimes(1)
+ })
+
+ it('refuses to start when already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+ const { promise } = run({ signal: controller.signal })
+ const result = await promise
+ expect(result.exitCode).toBe(143)
+ expect(spawnMock).not.toHaveBeenCalled()
+ })
+
+ it('SIGKILLs a run that outlives the timeout', async () => {
+ const { promise } = run({ timeoutMs: 10 })
+ await new Promise((r) => setTimeout(r, 40))
+ expect(child.kill).toHaveBeenCalledWith('SIGKILL')
+ child.emit('close', null)
+ await promise
+ })
+
+ it('never rejects: a spawn error resolves 255 with the message as a chunk', async () => {
+ const { promise, chunks } = run()
+ child.emit('error', new Error('spawn /usr/bin/ssh ENOENT'))
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('')).toContain('ENOENT')
+ })
+
+ it('a disconnected project (no ref) fails with 255 and an explanation — no spawn, no retry', async () => {
+ const { promise, chunks } = run({ resolveRef: () => null })
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('').length).toBeGreaterThan(0)
+ expect(spawnMock).not.toHaveBeenCalled()
+ })
+
+ it('refuses when the resolved connection is a DIFFERENT host than the target names', async () => {
+ const otherHost: SshSetupRef = { conn: { host: 'evil.test', user: 'deploy' }, controlPath: '/tmp/x.sock' }
+ const { promise, chunks } = run({ resolveRef: () => otherHost })
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('')).toContain('evil.test')
+ expect(spawnMock).not.toHaveBeenCalled()
+ })
+
+ it('refuses a run with no ssh target at all', async () => {
+ const { promise } = run({ ssh: undefined })
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(spawnMock).not.toHaveBeenCalled()
+ })
+
+ it('never rejects when the ref resolver itself throws', async () => {
+ const { promise, chunks } = run({
+ resolveRef: () => {
+ throw new Error('manager exploded')
+ }
+ })
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('')).toContain('manager exploded')
+ })
+
+ it('never rejects when spawn throws synchronously', async () => {
+ spawnMock.mockImplementation(() => {
+ throw new Error('Invalid argument')
+ })
+ const { promise, chunks } = run()
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('')).toContain('Invalid argument')
+ })
+
+ it('a dead master (ssh exits 255) surfaces ssh stderr and does not respawn', async () => {
+ const { promise, chunks } = run()
+ child.stderr.emit('data', Buffer.from('ssh: connect to host example.test port 22: Connection refused\n'))
+ child.emit('close', 255)
+ const result = await promise
+ expect(result.exitCode).toBe(255)
+ expect(chunks.join('')).toContain('Connection refused')
+ expect(spawnMock).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/main/remote-ssh/ssh-setup-runner.ts b/src/main/remote-ssh/ssh-setup-runner.ts
new file mode 100644
index 000000000..544012b94
--- /dev/null
+++ b/src/main/remote-ssh/ssh-setup-runner.ts
@@ -0,0 +1,200 @@
+import { spawn } from 'node:child_process'
+import { childArgs } from '../../core/remote-ssh/control-master'
+import { findExecutableSync } from '../../core/exec-path'
+import type { ProjectSetupRunner, ProjectSetupTarget } from '../../core/project-setup-service'
+import { SETUP_TIMEOUT_MS, createSetupOutputStream } from '../../core/setup-output-stream'
+import { posixQuote, quoteRemotePath, type SshConnection } from '../../shared/ssh'
+import { appSshAgent } from './ssh-agent'
+
+/** What the runner needs to reach a host: the connection it belongs to plus its ControlMaster
+ * socket — exactly `SshProjectManager.refForRemoteCwd`'s return shape. */
+export interface SshSetupRef {
+ conn: SshConnection
+ controlPath: string
+}
+
+type SshTarget = NonNullable<ProjectSetupTarget['ssh']>
+
+/** `ssh` itself uses 255 for "could not run the command at all" (auth failure, dead link, unknown
+ * host). Every refusal below reports the same code deliberately: to the UI, "the remote never ran
+ * your script" is one fact, whether it was ssh or this file that decided so. */
+const SSH_FAILURE_CODE = 255
+
+/** A shell only accepts `NAME=value` for a NAME that is a valid identifier. A key outside this set
+ * cannot be expressed as an assignment at all — it is dropped rather than emitted, because the
+ * only alternatives are `env 'weird key'=v` (still refused by most shells) or splicing something
+ * the remote shell would reparse. Values need no such rule: `posixQuote` can represent any byte
+ * sequence except NUL, and NUL cannot survive argv anyway, so a NUL-bearing value is dropped too. */
+const SHELL_IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/
+
+let cachedSsh: string | null | undefined
+/** Absolute `ssh`, resolved the way `ssh-project.ts`'s private `sshBin()` does — a GUI process does
+ * not inherit the login shell's PATH. Same memoization rule: only cache a MISS once the async PATH
+ * probe has settled, so an early call cannot pin `ssh` to the bare name forever. */
+function defaultSshPath(): string {
+ if (cachedSsh !== undefined) return cachedSsh ?? 'ssh'
+ const found = findExecutableSync('ssh', ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'])
+ cachedSsh = found
+ return found ?? 'ssh'
+}
+
+/**
+ * The remote one-liner a setup run executes.
+ *
+ * ```
+ * cd <cwd> && NAME=<v> … sh -lc <script>
+ * ```
+ *
+ * `ssh` forwards NO local environment (`SendEnv` needs matching `AcceptEnv` on the host, which we
+ * do not control), so the three `NODETERM_*` values the service hands us must ride inline as
+ * assignments prefixing the command — that form exports them into `sh` without touching the
+ * caller's own environment.
+ *
+ * EVERY interpolated value is one quoted token: the script is attacker-controlled by construction
+ * (it arrives through a git-shared `project.json`, and the trust gate approves it for EXECUTION —
+ * not for rewriting the command around it), and a project name or remote cwd is no better. The one
+ * deliberate exception is a LEADING `~` in the cwd (`quoteRemotePath`): single quotes suppress
+ * tilde expansion, so `'~/app'` would `cd` into a literal directory named `~`. Only the tilde is
+ * left bare; the remainder of the path stays quoted, so a directory name still cannot inject.
+ */
+export function buildSetupRemoteCommand(cwd: string, env: Record<string, string>, script: string): string {
+ const assignments: string[] = []
+ for (const [key, value] of Object.entries(env)) {
+ // Cannot be represented safely → omit the assignment. The script then sees the variable unset,
+ // which a `${NODETERM_ROOT_PATH:-}` can handle; a spliced command it could not.
+ if (!SHELL_IDENTIFIER.test(key)) continue
+ if (value.includes('\0')) continue
+ assignments.push(`${key}=${posixQuote(value)}`)
+ }
+ const prefix = assignments.length ? `${assignments.join(' ')} ` : ''
+ return `cd ${quoteRemotePath(cwd)} && ${prefix}sh -lc ${posixQuote(script)}`
+}
+
+/**
+ * The SSH half of `ProjectSetupRunner` — the first STREAMING remote exec in the tree.
+ *
+ * `sshRun`/`execFile` (ssh-project.ts) is deliberately not reused: it buffers, drops stderr, and
+ * reaps at 15s, none of which a `npm install` that prints for four minutes survives. This spawns
+ * the child itself and pipes both streams through the same capped+debounced discipline as the
+ * local runner (`setup-output-stream.ts`), so a run reports identically wherever it executes.
+ *
+ * ── EXACTLY ONE CHILD, EVER ─────────────────────────────────────────────────────────────────────
+ * `childArgs` carries `ControlMaster=auto`: when the master socket is dead each child does NOT
+ * multiplex, it opens a full connection — a real login. A retry loop here would be the 72k-logins/day
+ * shape this repo already lived through once (see pane-probe.ts's warning, and the ssh-controlmaster
+ * memory). So a dead master is a FAILURE of the run — 255 plus ssh's own stderr as the explanation —
+ * never something to retry. The manager's watchdog is what repairs masters; this file only reports.
+ */
+export function makeSshSetupRunner(
+ resolveRef: (remoteCwd: string) => SshSetupRef | null | undefined,
+ opts?: { timeoutMs?: number; sshPath?: () => string; agentEnv?: () => Record<string, string> }
+): ProjectSetupRunner {
+ const timeoutMs = opts?.timeoutMs ?? SETUP_TIMEOUT_MS
+ const sshPath = opts?.sshPath ?? defaultSshPath
+ // The app-private agent holds the unlocked key for this app run; a tty-less child has no askpass
+ // wiring of its own, so without it a run against an encrypted key fails auth (ssh-project.ts:1662
+ // passes the same env for the same reason).
+ const agentEnv = opts?.agentEnv ?? (() => appSshAgent.env())
+
+ return ({ script, cwd, env, onChunk, signal, ssh }) =>
+ new Promise((resolve) => {
+ const { append, flush } = createSetupOutputStream(onChunk)
+ // A refusal is reported exactly like a failed script: a chunk the user can read plus a
+ // non-zero exit. The service layer has one failure shape, never two.
+ const refuse = (message: string): void => {
+ append(`${message}\n`)
+ flush()
+ resolve({ exitCode: SSH_FAILURE_CODE })
+ }
+
+ // Already aborted before we ever spawned (a cancel raced the consent gate) — starting an ssh
+ // child now would leak a connection nobody is waiting for.
+ if (signal.aborted) {
+ resolve({ exitCode: 143 })
+ return
+ }
+ if (!ssh) {
+ refuse('Cannot run: this project has no SSH target.')
+ return
+ }
+ const target: SshTarget = ssh
+ let ref: SshSetupRef | null | undefined
+ try {
+ ref = resolveRef(target.remoteCwd)
+ } catch (e) {
+ // The injected resolver reaches into the ssh-project manager; a throw there must degrade to
+ // a reported failure, never to a rejected runner promise (`ProjectSetupRunner` NEVER
+ // rejects — the service would report it as `failed` with no exit code and no explanation).
+ refuse(`Cannot run: ${(e as Error).message}`)
+ return
+ }
+ if (!ref) {
+ refuse(`Cannot run: not connected to ${target.server.user}@${target.server.host}.`)
+ return
+ }
+ // The ref is resolved by remote PATH, and two different hosts can absolutely both have
+ // `/srv/app`. Running the project's script against whichever connection happened to match the
+ // path first would execute it on a machine the target never named — so the resolved
+ // connection must BE the one the (machine-local, non-renderer) target describes.
+ if (ref.conn.host !== target.server.host || ref.conn.user !== target.server.user) {
+ refuse(
+ `Cannot run: the live connection for ${target.remoteCwd} is ` +
+ `${ref.conn.user}@${ref.conn.host}, not ${target.server.user}@${target.server.host}.`
+ )
+ return
+ }
+
+ const remote = buildSetupRemoteCommand(cwd, env, script)
+ let child: ReturnType<typeof spawn>
+ try {
+ child = spawn(sshPath(), childArgs(ref.conn, ref.controlPath, remote), {
+ stdio: ['ignore', 'pipe', 'pipe'],
+ windowsHide: true,
+ env: { ...process.env, ...agentEnv() }
+ })
+ } catch (e) {
+ // `spawn` throws SYNCHRONOUSLY for a malformed invocation (a NUL byte in an argument, a bad
+ // option object) — only ENOENT & co. arrive as an `error` event. Same reported shape either way.
+ refuse(`Cannot run: ${(e as Error).message}`)
+ return
+ }
+
+ // NO process group here, unlike the local runner's `detached` + `kill(-pid)`. The thing worth
+ // killing lives on the OTHER machine, and killing a process group locally cannot reach it:
+ // what ends the remote work is the CHANNEL closing. SIGKILL on the local ssh client tears the
+ // session down, the remote sshd sees EOF and SIGHUPs the command it started, and our pipes
+ // close because the only process holding them is this child. (A `detached` ssh client would
+ // also be a nohup-shaped liability of its own: an orphaned mux client outliving the app.)
+ const kill = (): void => {
+ try {
+ child.kill('SIGKILL')
+ } catch {
+ // Already gone between our check and this call — nothing left to kill.
+ }
+ }
+
+ const timeoutTimer = setTimeout(kill, timeoutMs)
+ timeoutTimer.unref?.()
+ const onAbort = (): void => kill()
+ signal.addEventListener('abort', onAbort)
+
+ const finish = (exitCode: number): void => {
+ clearTimeout(timeoutTimer)
+ signal.removeEventListener('abort', onAbort)
+ flush() // final flush — whatever the debounce timer hadn't fired yet
+ resolve({ exitCode })
+ }
+
+ child.stdout?.on('data', (d: Buffer) => append(d.toString('utf-8')))
+ // stderr is STREAMED, not dropped (`sshRun` drops it): for a setup script it carries the
+ // compiler/installer diagnostics, and for a broken link it carries ssh's own explanation —
+ // which is the only thing that distinguishes "your script failed" from "the host is gone".
+ child.stderr?.on('data', (d: Buffer) => append(d.toString('utf-8')))
+ // Never reject: a spawn failure (ssh binary missing, EACCES) reports like any other run.
+ child.on('error', (e) => {
+ append(`${(e as Error).message}\n`)
+ finish(SSH_FAILURE_CODE)
+ })
+ child.on('close', (code) => finish(code ?? 1))
+ })
+}