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): close four findings from the follow-up model bug hunt

parsa222edf121f03af3
diff --git a/src/main/remote-ssh/ssh-agent.ts b/src/main/remote-ssh/ssh-agent.ts
index 5e3ee80f5..a472f4146 100644
--- a/src/main/remote-ssh/ssh-agent.ts
+++ b/src/main/remote-ssh/ssh-agent.ts
@@ -65,12 +65,30 @@ interface AgentChild {
on(event: string, cb: (...args: unknown[]) => void): void
}
+/** NT_MULTI sandboxes carry their identity in NT_USER_DATA; every other instance derives it from
+ * its real userData dir. The second half matters because a bare `npm run dev` (app name
+ * "node-terminal") and the installed app ("nodeterm") have different userData dirs, so the
+ * single-instance lock does not stop them running side by side - under one fixed key the second
+ * instance's start() rmSync's the first one's LIVE socket and its quit unlinks it again, leaving
+ * that app silently agentless (a prompt per reconnect) for the rest of its run. Guarded require:
+ * under plain node (vitest) the electron module is only a binary-path string with no `app`. */
+function defaultDataDirKey(): string {
+ if (process.env.NT_USER_DATA) return process.env.NT_USER_DATA
+ try {
+ const { app } = require('electron') as { app?: { getPath(name: string): string } }
+ if (app) return app.getPath('userData')
+ } catch {
+ // plain node (tests): no electron runtime
+ }
+ return 'default'
+}
+
/** The socket lives in the same short, space-free home dir as the ControlMaster sockets: a unix
* socket path is capped near 104 bytes, which userData (~/Library/Application Support/…) eats.
* Keyed by data dir like `controlPathFor` is keyed by project id, so a second instance
- * (`NT_MULTI=1`, ./dev-test.sh) binds its own socket instead of unlinking the first one's and
- * silently leaving that app agentless when it quits. */
-export function agentSockPath(dataDirKey = process.env.NT_USER_DATA ?? 'default'): string {
+ * (`NT_MULTI=1`, ./dev-test.sh, a dev build next to the installed app) binds its own socket
+ * instead of unlinking the first one's and silently leaving that app agentless when it quits. */
+export function agentSockPath(dataDirKey = defaultDataDirKey()): string {
const id = createHash('sha256').update(dataDirKey).digest('hex').slice(0, 8)
return path.join(os.homedir(), '.nodeterm', `agent-${id}.sock`)
}
@@ -101,6 +119,15 @@ export class AppSshAgent {
}
private async spawnAndWait(): Promise<void> {
+ // Publish the socket for the CORE ssh spawners that cannot import this file: remote PTYs
+ // (pty-manager) and remote git (remote-git) shell out to ssh themselves, and `childArgs` uses
+ // `ControlMaster=auto`, so with the master down one of them authenticates for real. Left
+ // inheriting the ambient socket, a remote PTY (which HAS a tty) prompts for the passphrase in
+ // the pane and, for anyone with `AddKeysToAgent yes` in their own ~/.ssh/config, loads the key
+ // into their login agent permanently. Published BEFORE anything that can fail, for the same
+ // fail-closed reason as `env()`: a sync throw below must degrade to prompting, never to the
+ // ambient agent.
+ process.env[APP_AGENT_ENV] = this.sockPath
try {
mkdirSync(path.dirname(this.sockPath), { recursive: true, mode: 0o700 })
// `ssh-agent -a` refuses to bind over an existing file, and a crash leaves one behind.
@@ -121,14 +148,6 @@ export class AppSshAgent {
this.child = null
return
}
- // Publish the socket for the CORE ssh spawners that cannot import this file: remote PTYs
- // (pty-manager) and remote git (remote-git) shell out to ssh themselves, and `childArgs` uses
- // `ControlMaster=auto`, so with the master down one of them authenticates for real. Left
- // inheriting the ambient socket, a remote PTY (which HAS a tty) prompts for the passphrase in
- // the pane and, for anyone with `AddKeysToAgent yes` in their own ~/.ssh/config, loads the key
- // into their login agent permanently. Set even when the spawn failed, for the same fail-closed
- // reason as `env()`.
- process.env[APP_AGENT_ENV] = this.sockPath
// The socket appears a few ms after exec. Bounded: past this we simply proceed, and ssh prompts.
const deadline = Date.now() + 1_000
while (this.child && !existsSync(this.sockPath) && Date.now() < deadline) {
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index b5cfc62cd..6982b5759 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -1302,6 +1302,44 @@ describe('SshProjectManager', () => {
expect(spawnMaster).toHaveBeenCalledTimes(1)
})
+ it('a final disconnect DURING the pre-registration probes cancels the attempt instead of leaking a master', async () => {
+ // The window: connectOnce is still inside mkdir/stat/ensureAgent and has put nothing in
+ // `conns` yet, so a project delete (or a cancelled connect-dialog browse) has no master to
+ // tear down. Pre-fix, disconnect() returned untouched and the attempt completed as a master
+ // nothing owned: revalidateAll kept it alive until quit, and with `conns` pinned non-empty
+ // the idle key-forget never fired again.
+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)
+ vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))
+ let releaseAgent!: () => void
+ const gate = new Promise<void>((r) => {
+ releaseAgent = r
+ })
+ const master = { kill: vi.fn(), on: vi.fn() }
+ const onIdle = vi.fn()
+ const onStatus = vi.fn()
+ const mgr = new SshProjectManager({
+ userDataDir: '/ud',
+ spawnMaster: vi.fn(() => master),
+ run: vi.fn(async () => ({ code: 0, stdout: '' })),
+ runScp: vi.fn(async () => ({ code: 0 })),
+ getHook: () => ({ port: 1, token: 't', version: '1' }),
+ onStatus,
+ onIdle,
+ ensureAgent: vi.fn(() => gate)
+ })
+ const attempt = mgr.connect('p1', { host: 'h', user: 'u' })
+ attempt.catch(() => {}) // settled and asserted below
+ await new Promise((r) => setImmediate(r)) // let the attempt park inside ensureAgent
+ await mgr.disconnect('p1', { final: true }) // the project is deleted mid-attempt
+ // Nothing is connected, and the delete is user-facing: this IS the manager going idle.
+ expect(onIdle).toHaveBeenCalledTimes(1)
+ releaseAgent()
+ await expect(attempt).rejects.toThrow(/cancelled/)
+ // The just-spawned master was killed, nothing registered, and 'connected' never fired.
+ expect(master.kill).toHaveBeenCalled()
+ expect(onStatus.mock.calls.map((c) => c[0].status)).not.toContain('connected')
+ })
+
it('reports idle ONLY on a user-facing disconnect that leaves nothing connected', async () => {
// `onIdle` is what forgets the unlocked key. Internal teardowns empty `conns` routinely (an
// endpoint edit, a failed connect, the watchdog dropping a stale master), and treating those
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 1312959b0..e68723799 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -269,7 +269,10 @@ export class SshProjectManager {
/** One in-flight connect attempt per project, so concurrent callers share it (see connect).
* The conn the attempt was started with rides along so a joiner with an EDITED endpoint can
* be detected instead of silently receiving a connection to the old server. */
- private inFlight = new Map<string, { conn: SshConnection; attempt: Promise<ConnectResult> }>()
+ private inFlight = new Map<
+ string,
+ { conn: SshConnection; attempt: Promise<ConnectResult>; ticket: symbol }
+ >()
private watchdog?: ReturnType<typeof setInterval>
constructor(private r: Runners) {
this.remoteHooks = new RemoteHooks({ run: r.run })
@@ -347,17 +350,22 @@ export class SshProjectManager {
const after = (): Promise<ConnectResult> => this.connect(projectId, conn, remoteCwd)
return inFlight.attempt.then(after, after)
}
- const attempt = this.connectOnce(projectId, conn, remoteCwd).finally(() => {
+ // The ticket is this attempt's claim on the project id. `disconnect` cancels a
+ // pre-registration attempt by dropping the entry that holds it; connectOnce re-checks the
+ // ticket before registering its master (see there).
+ const ticket = Symbol('ssh-connect-attempt')
+ const attempt = this.connectOnce(projectId, conn, remoteCwd, ticket).finally(() => {
if (this.inFlight.get(projectId)?.attempt === attempt) this.inFlight.delete(projectId)
})
- this.inFlight.set(projectId, { conn, attempt })
+ this.inFlight.set(projectId, { conn, attempt, ticket })
return attempt
}
private async connectOnce(
projectId: string,
conn: SshConnection,
- remoteCwd?: string
+ remoteCwd?: string,
+ ticket?: symbol
): Promise<ConnectResult> {
const existing = this.conns.get(projectId)
if (existing && !sameEndpoint(existing.conn, conn)) {
@@ -459,6 +467,17 @@ export class SshProjectManager {
await this.r.ensureAgent?.().catch(() => {})
master = this.r.spawnMaster(masterArgs(conn, controlPath), this.r.masterEnvFor?.(conn.identityFile) ?? {})
}
+ // A disconnect can land while this attempt is still in the probes above, BEFORE any conns
+ // entry exists to tear down - its only lever is dropping this attempt's inFlight ticket
+ // (see disconnect). Registering the master anyway would resurrect a connection nothing owns
+ // (a deleted project, a cancelled connect-dialog browse): revalidateAll faithfully keeps
+ // every conns entry alive for the rest of the run, and a stuck entry also pins `conns`
+ // non-empty so the app agent's idle forget never fires. Kill whatever was just spawned or
+ // adopted and fail the attempt instead.
+ if (ticket && this.inFlight.get(projectId)?.ticket !== ticket) {
+ master.kill()
+ throw new Error('SSH connect cancelled')
+ }
this.conns.set(projectId, { conn, controlPath, master, remoteCwd })
// Wait until the master answers `-O check`. The bound is the master PROCESS, not a fixed
// attempt count: while the spawned ssh is alive it is connecting, authenticating, or waiting
@@ -1208,7 +1227,16 @@ export class SshProjectManager {
*/
async disconnect(projectId: string, opts?: { keepInFlight?: boolean; final?: boolean }): Promise<void> {
const c = this.conns.get(projectId)
- if (!c) return
+ if (!c) {
+ // No registered master, but an attempt may still be in flight for this id, inside
+ // connectOnce's pre-registration probes. Dropping its coalescing entry is what cancels
+ // it: connectOnce re-checks its ticket before registering the master. Returning without
+ // this left the attempt to complete as a master for a deleted project (or a cancelled
+ // browse) that only quit could remove.
+ if (!opts?.keepInFlight) this.inFlight.delete(projectId)
+ if (opts?.final && this.conns.size === 0) this.r.onIdle?.()
+ return
+ }
// Remove the pushed agent-status mirror while the master is still alive: a file left behind
// would freeze the phone's badges at the last event (the heartbeat that lets the phone detect
// staleness dies with this connection). Best-effort.
diff --git a/src/renderer/components/SshProjectDialog.tsx b/src/renderer/components/SshProjectDialog.tsx
index 4630802fe..828c2e24c 100644
--- a/src/renderer/components/SshProjectDialog.tsx
+++ b/src/renderer/components/SshProjectDialog.tsx
@@ -69,12 +69,12 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
const [mkdirErr, setMkdirErr] = useState('')
// Stable id for the temporary browse master, generated once.
const browseIdRef = useRef(`ssh-browse-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`)
- const connectedRef = useRef(false)
+ const connectBegunRef = useRef(false)
// Tear down the temporary browse master (best-effort) once it's no longer needed.
const disconnectBrowse = useCallback(() => {
- if (connectedRef.current) {
- connectedRef.current = false
+ if (connectBegunRef.current) {
+ connectBegunRef.current = false
void window.nodeTerminal.sshProject.disconnect(browseIdRef.current)
}
}, [])
@@ -126,8 +126,13 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
setError('')
setStep('connecting')
try {
+ // Mark BEFORE the await: from the moment connect() is issued there is a master (or an
+ // in-flight attempt) that close/unmount must tear down. Marking only on success meant
+ // cancelling during 'connecting' skipped disconnectBrowse entirely, and once the attempt
+ // later landed (a slow host, or parked on the passphrase prompt) the browse master
+ // outlived the dialog for the rest of the app run.
+ connectBegunRef.current = true
await window.nodeTerminal.sshProject.connect(browseIdRef.current, srv)
- connectedRef.current = true
await list('~')
setStep('browse')
} catch (err) {