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(project-setup): full-endpoint ssh resolution + honest cancel semantics
enesba5af482f434
diff --git a/src/main/index.ts b/src/main/index.tsindex 03af5bfc5..039116676 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -358,12 +358,14 @@ const projectSetupService = new ProjectSetupService({trust: projectTrustStore,readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),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)+ // The ssh leg streams over the project's LIVE ControlMaster, resolved lazily (the manager is+ // created only once the window is ready) on the FULL endpoint — host+user+port+remoteCwd, not the+ // cwd alone: the default remoteCwd is `~`, and one `user@host` can be several machines on+ // different ports. A project with no matching live connection 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((endpoint) => sshProjectManager?.refForEndpoint(endpoint) ?? null)})registerProjectSetupHandlers(corePlatform, projectSetupService, {projectTargetInfo: (projectId) => workspaceStore.projectTargetInfo(projectId),diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 5cf630b76..420a26e89 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -963,6 +963,38 @@ export class SshProjectManager {return undefined}+ /**+ * Resolve the ref for the connection matching a FULL endpoint — host, user, effective port AND+ * remote cwd. Sibling of `refForRemoteCwd`, not a replacement: matching on cwd alone is fine for+ * the git-remote registry (a remote repo path is resolved from a node that already belongs to one+ * project), but wrong for anything keyed by a project's own SERVER, which is what running that+ * project's setup script is.+ *+ * Two ways cwd-only matching picks the wrong box, both reachable with ordinary config:+ * - The DEFAULT remoteCwd is `~`, so every project that never chose a directory collides with+ * every other one — the first connection in map order would win them all, forever.+ * - Same host and user on different PORTS are routinely different machines (containers, or hosts+ * behind one NAT), and a host/user-only check waves that straight through.+ *+ * `undefined` when nothing matches — a disconnected project and a wrong-endpoint one are the same+ * answer here, and the caller reports it rather than dialing a new connection.+ */+ refForEndpoint(endpoint: {+ host: string+ user: string+ port?: number+ remoteCwd: string+ }): { conn: SshConnection; controlPath: string } | undefined {+ const wantPort = endpoint.port ?? 22+ for (const c of this.conns.values()) {+ if (c.remoteCwd !== endpoint.remoteCwd) continue+ if (c.conn.host !== endpoint.host || c.conn.user !== endpoint.user) continue+ if ((c.conn.port ?? 22) !== wantPort) continue+ return { conn: c.conn, controlPath: c.controlPath }+ }+ return undefined+ }+/*** `user@host` of the connection whose ControlMaster has this pid, for the passphrase dialog.* The askpass helper reports the asking ssh process as its `$PPID` (see ssh-askpass.ts), whichdiff --git a/src/main/remote-ssh/ssh-setup-runner.test.ts b/src/main/remote-ssh/ssh-setup-runner.test.tsindex d9844f993..2189464a9 100644--- a/src/main/remote-ssh/ssh-setup-runner.test.ts+++ b/src/main/remote-ssh/ssh-setup-runner.test.ts@@ -10,7 +10,9 @@ vi.mock('node:child_process', async (importOriginal) => {return { ...actual, spawn: spawnMock }})-import { makeSshSetupRunner, type SshSetupRef } from './ssh-setup-runner'+import { makeSshSetupRunner, type SshSetupEndpoint, type SshSetupRef } from './ssh-setup-runner'+import { SshProjectManager } from './ssh-project'+import { controlPathFor } from '../../core/remote-ssh/control-master'/** The child `spawn` returns: an EventEmitter with `stdout`/`stderr` emitters and a spy `kill`. */class FakeChild extends EventEmitter {@@ -76,9 +78,9 @@ describe('makeSshSetupRunner', () => {script?: stringcwd?: stringenv?: Record<string, string>- resolveRef?: (remoteCwd: string) => SshSetupRef | null+ resolveRef?: (endpoint: SshSetupEndpoint) => SshSetupRef | nulltimeoutMs?: number- ssh?: typeof ssh | undefined+ ssh?: { server: { host: string; user: string; port?: number }; remoteCwd: string } | undefinedsignal?: AbortSignal} = {}) => {@@ -114,6 +116,42 @@ describe('makeSshSetupRunner', () => {expect(argv()).toContain('[email protected]')})+ it('hands the resolver the FULL endpoint, not just the remote cwd', async () => {+ const seen: SshSetupEndpoint[] = []+ const { promise } = run({+ ssh: { server: { host: 'example.test', user: 'deploy', port: 2222 }, remoteCwd: '/srv/app' },+ resolveRef: (e) => {+ seen.push(e)+ return { conn: { host: 'example.test', user: 'deploy', port: 2222 }, controlPath: '/tmp/c.sock' }+ }+ })+ child.emit('close', 0)+ await promise+ expect(seen).toEqual([{ host: 'example.test', user: 'deploy', port: 2222, remoteCwd: '/srv/app' }])+ })++ it('refuses a resolved connection on the WRONG PORT (same user@host is not the same machine)', async () => {+ const { promise, chunks } = run({+ ssh: { server: { host: 'example.test', user: 'deploy', port: 2222 }, remoteCwd: '/srv/app' },+ resolveRef: () => ({ conn: { host: 'example.test', user: 'deploy', port: 2022 }, controlPath: '/tmp/c.sock' })+ })+ const result = await promise+ expect(result.exitCode).toBe(255)+ expect(chunks.join('')).toContain('[email protected]:2022')+ expect(spawnMock).not.toHaveBeenCalled()+ })++ it('treats an absent port and an explicit 22 as the same endpoint', async () => {+ const { promise } = run({+ ssh: { server: { host: 'example.test', user: 'deploy', port: 22 }, remoteCwd: '/srv/app' },+ resolveRef: () => ref // conn has no `port` at all+ })+ child.emit('close', 0)+ const result = await promise+ expect(result.exitCode).toBe(0)+ expect(spawnMock).toHaveBeenCalledTimes(1)+ })+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)@@ -122,6 +160,26 @@ describe('makeSshSetupRunner', () => {expect(remoteCommand()).toContain(`sh -lc 'make build'`)})+ // The whole reason the `cd` uses quoteRemotePath instead of posixQuote: single quotes suppress+ // tilde expansion, and `~` is the DEFAULT remoteCwd — `cd '~/app'` would look for a directory+ // literally named `~`. Swapping back to posixQuote must fail this pair.+ it('leaves a leading ~ bare so the remote shell expands it, quoting the rest of the path', async () => {+ const { promise } = run({ cwd: '~/app' })+ child.emit('close', 0)+ await promise+ expect(remoteCommand()).toContain(`cd ~/'app' &&`)+ expect(remoteCommand()).not.toContain(`cd '~/app'`)+ })++ it('a bare ~ is the whole carve-out: a ~-prefixed hostile path is still fully quoted', async () => {+ const { promise } = run({ cwd: '~$(touch /tmp/pwned)' })+ child.emit('close', 0)+ await promise+ const cmd = remoteCommand()+ expect(cmd).toContain(`cd '~$(touch /tmp/pwned)' &&`)+ expect(unquotedPart(cmd)).not.toContain('$(')+ })+it('inlines the env as quoted assignments (ssh forwards no local env)', async () => {const { promise } = run({env: {@@ -204,6 +262,26 @@ describe('makeSshSetupRunner', () => {expect(spawnMock).toHaveBeenCalledTimes(1)})+ it('says out loud that a cancel does NOT stop the remote command', async () => {+ const controller = new AbortController()+ const { promise, chunks } = run({ signal: controller.signal, timeoutMs: 60_000 })+ controller.abort()+ child.emit('close', null)+ await promise+ const combined = chunks.join('')+ expect(combined).toContain('cancelled')+ expect(combined).toContain('may still be running')+ })++ it('says the same about a timeout kill', async () => {+ const { promise, chunks } = run({ timeoutMs: 10 })+ await new Promise((r) => setTimeout(r, 40))+ child.emit('close', null)+ await promise+ expect(chunks.join('')).toContain('timed out')+ expect(chunks.join('')).toContain('may still be running')+ })+it('refuses to start when already aborted', async () => {const controller = new AbortController()controller.abort()@@ -283,4 +361,80 @@ describe('makeSshSetupRunner', () => {expect(chunks.join('')).toContain('Connection refused')expect(spawnMock).toHaveBeenCalledTimes(1)})++ /**+ * The resolver seam against the REAL manager, wired exactly as `src/main/index.ts` wires it. A+ * fake resolver could not catch the two collisions that made cwd-only resolution wrong, because+ * the collision lives in the LOOKUP, not in the runner.+ */+ describe('resolved through SshProjectManager.refForEndpoint (as main wires it)', () => {+ const makeMgr = (): SshProjectManager =>+ new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster: vi.fn(() => ({ kill: vi.fn(), on: vi.fn() })),+ run: vi.fn(async () => ({ code: 0, stdout: '' })),+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 51234, token: 'tok', version: '1' }),+ onStatus: () => {}+ })++ const runVia = (mgr: SshProjectManager, target: { server: { host: string; user: string; port?: number }; remoteCwd: string }) => {+ const runner = makeSshSetupRunner((endpoint) => mgr.refForEndpoint(endpoint) ?? null, {+ sshPath: () => '/usr/bin/ssh',+ agentEnv: () => ({})+ })+ const chunks: string[] = []+ const promise = runner({+ script: 'echo hi',+ cwd: target.remoteCwd,+ env: {},+ onChunk: (t) => chunks.push(t),+ signal: new AbortController().signal,+ ssh: target+ })+ return { promise, chunks }+ }++ it('picks the connection on the TARGET port when one user@host is live on two ports', async () => {+ const mgr = makeMgr()+ await mgr.connect('p-2022', { host: 'h', user: 'u', port: 2022 }, '/srv/app')+ await mgr.connect('p-2222', { host: 'h', user: 'u', port: 2222 }, '/srv/app')++ const { promise } = runVia(mgr, { server: { host: 'h', user: 'u', port: 2222 }, remoteCwd: '/srv/app' })+ child.emit('close', 0)+ expect((await promise).exitCode).toBe(0)+ expect(argv()).toContain(`ControlPath=${controlPathFor('p-2222')}`)+ expect(argv().join(' ')).toContain('-p 2222')+ })++ it('refuses when only the WRONG-port connection is live — no spawn, no dial', async () => {+ const mgr = makeMgr()+ await mgr.connect('p-2022', { host: 'h', user: 'u', port: 2022 }, '/srv/app')++ const { promise, chunks } = runVia(mgr, { server: { host: 'h', user: 'u', port: 2222 }, remoteCwd: '/srv/app' })+ expect((await promise).exitCode).toBe(255)+ expect(chunks.join('')).toContain('u@h:2222')+ expect(spawnMock).not.toHaveBeenCalled()+ })++ it('two hosts sharing the default remoteCwd each resolve to their OWN connection', async () => {+ const mgr = makeMgr()+ await mgr.connect('p-a', { host: 'a.test', user: 'u' }, '~')+ await mgr.connect('p-b', { host: 'b.test', user: 'u' }, '~')++ const a = runVia(mgr, { server: { host: 'a.test', user: 'u' }, remoteCwd: '~' })+ child.emit('close', 0)+ expect((await a.promise).exitCode).toBe(0)+ expect(argv()).toContain(`ControlPath=${controlPathFor('p-a')}`)++ spawnMock.mockReset()+ const secondChild = new FakeChild()+ spawnMock.mockReturnValue(secondChild)+ const b = runVia(mgr, { server: { host: 'b.test', user: 'u' }, remoteCwd: '~' })+ secondChild.emit('close', 0)+ expect((await b.promise).exitCode).toBe(0)+ expect(argv()).toContain(`ControlPath=${controlPathFor('p-b')}`)+ expect(b.chunks.join('')).not.toContain('Cannot run')+ })+ })})diff --git a/src/main/remote-ssh/ssh-setup-runner.ts b/src/main/remote-ssh/ssh-setup-runner.tsindex 544012b94..9b633cfc4 100644--- a/src/main/remote-ssh/ssh-setup-runner.ts+++ b/src/main/remote-ssh/ssh-setup-runner.ts@@ -13,8 +13,33 @@ export interface SshSetupRef {controlPath: string}+/**+ * The FULL identity a setup run must be resolved against. Not just the remote cwd: the default+ * remoteCwd is `~`, so cwd alone collides across every project that never picked a directory, and+ * host+user alone collides across ports (containers / hosts behind one NAT are routinely the same+ * `user@host` on different ports). Resolving on anything less either runs the script on the wrong+ * machine or permanently refuses one of two legitimate projects. `port` absent = ssh's default 22.+ */+export interface SshSetupEndpoint {+ host: string+ user: string+ port?: number+ remoteCwd: string+}+type SshTarget = NonNullable<ProjectSetupTarget['ssh']>+/** `user@host` for a message, with the port only when it is not the default (a `:22` in every+ * refusal would be noise; a non-default port is exactly the detail that explains the refusal). */+function endpointLabel(e: { host: string; user: string; port?: number }): string {+ return e.port !== undefined && e.port !== 22 ? `${e.user}@${e.host}:${e.port}` : `${e.user}@${e.host}`+}++/** Same endpoint? Ports compare by EFFECTIVE value, so `undefined` and `22` are one host. */+function sameEndpoint(a: { host: string; user: string; port?: number }, b: { host: string; user: string; port?: number }): boolean {+ return a.host === b.host && a.user === b.user && (a.port ?? 22) === (b.port ?? 22)+}+/** `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. */@@ -86,7 +111,7 @@ export function buildSetupRemoteCommand(cwd: string, env: Record<string, string>* 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,+ resolveRef: (endpoint: SshSetupEndpoint) => SshSetupRef | null | undefined,opts?: { timeoutMs?: number; sshPath?: () => string; agentEnv?: () => Record<string, string> }): ProjectSetupRunner {const timeoutMs = opts?.timeoutMs ?? SETUP_TIMEOUT_MS@@ -118,9 +143,16 @@ export function makeSshSetupRunner(return}const target: SshTarget = ssh+ // The whole endpoint goes to the resolver, never the cwd alone — see `SshSetupEndpoint`.+ const endpoint: SshSetupEndpoint = {+ host: target.server.host,+ user: target.server.user,+ port: target.server.port,+ remoteCwd: target.remoteCwd+ }let ref: SshSetupRef | null | undefinedtry {- ref = resolveRef(target.remoteCwd)+ ref = resolveRef(endpoint)} 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@@ -129,17 +161,19 @@ export function makeSshSetupRunner(return}if (!ref) {- refuse(`Cannot run: not connected to ${target.server.user}@${target.server.host}.`)+ // "No live connection for THIS endpoint" — which covers both a disconnected project and one+ // whose only matching-cwd connection belongs to a different machine. Never a reason to dial:+ // connecting is the manager's job, and doing it here would be a login per failed run.+ refuse(`Cannot run: not connected to ${endpointLabel(endpoint)} (${endpoint.remoteCwd}).`)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) {+ // Defense in depth, not the primary check (the resolver owns matching): a resolver that ever+ // answered with a connection to a machine the target never named would execute the project's+ // script there. Cheap to verify, and the failure it prevents is unrecoverable.+ if (!sameEndpoint(ref.conn, target.server)) {refuse(- `Cannot run: the live connection for ${target.remoteCwd} is ` +- `${ref.conn.user}@${ref.conn.host}, not ${target.server.user}@${target.server.host}.`+ `Cannot run: the resolved connection for ${endpoint.remoteCwd} is ` ++ `${endpointLabel(ref.conn)}, not ${endpointLabel(endpoint)}.`)return}@@ -159,12 +193,26 @@ export function makeSshSetupRunner(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.)+ // SIGKILL the LOCAL ssh client, and no process group — unlike the local runner, which needs+ // `detached` + `kill(-pid)` because the script's children are on THIS machine holding OUR+ // pipes. Here the only local process is the mux client: killing it closes the channel, our+ // pipes close with it, and the run finishes promptly. That prompt finish is what cancel and+ // timeout actually owe the user.+ //+ // ── WHAT THIS DOES NOT DO: END THE REMOTE COMMAND ───────────────────────────────────────────+ // There is no `-t` here (a setup script must not be handed a tty), so the remote session has+ // no controlling terminal and sshd delivers NO SIGHUP when the channel closes — it just closes+ // the command's pipes. The remote `sh -lc …` therefore keeps running until it next writes to a+ // closed stdout and takes SIGPIPE, which for a quiet or output-buffered script may be a long+ // time, or never. Killing a local process group cannot change this: the work is on another+ // machine. (`detached` would additionally be its own liability — an orphaned mux client+ // outliving the app.)+ //+ // The consequence to know before trusting cancel: single-flight is enforced LOCALLY (the+ // service's runKey map, which this kill releases), so a re-run started right after a cancel+ // can race a still-live remote command — two `npm install`s in one checkout. Ending the remote+ // side for real would need a wrapper that records a remote pid and a second connection to kill+ // it; that is deliberately not in this task. The user is told instead (chunk below).const kill = (): void => {try {child.kill('SIGKILL')@@ -173,9 +221,19 @@ export function makeSshSetupRunner(}}- const timeoutTimer = setTimeout(kill, timeoutMs)+ // Say the true thing at the moment it becomes relevant, rather than letting "cancelled" imply+ // a stop that did not happen. (Swallowed if the run already blew the output cap — in which+ // case the truncation note has already told the user the transcript is incomplete.)+ const REMOTE_MAY_SURVIVE = 'the remote command may still be running on the host'+ const timeoutTimer = setTimeout(() => {+ append(`\n[timed out — killed the local ssh client; ${REMOTE_MAY_SURVIVE}]\n`)+ kill()+ }, timeoutMs)timeoutTimer.unref?.()- const onAbort = (): void => kill()+ const onAbort = (): void => {+ append(`\n[cancelled — killed the local ssh client; ${REMOTE_MAY_SURVIVE}]\n`)+ kill()+ }signal.addEventListener('abort', onAbort)const finish = (exitCode: number): void => {