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-project): authoritative remote teardown + async create + lifecycle (final-review)
eneseebef7f0e549
diff --git a/src/main/index.ts b/src/main/index.tsindex 9a02b00e7..282e6fbaf 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -54,6 +54,8 @@ const sshStore = new SshStore()const ptyManager = new PtyManager()const workspaceStore = new WorkspaceStore()const gitService = new GitService()+// Set once the app window is ready; used by the quit hooks to tear down SSH-project masters.+let sshProjectManager: ReturnType<typeof initSshProject> | undefined// The single app window — kept at module scope so IPC handlers (e.g. notifications)// can check focus and route clicks back to the renderer.@@ -351,7 +353,7 @@ app.whenReady().then(async () => {initLicense(win)initRemoteHost(win, ptyManager)initRemoteClient(win, { isPackaged: app.isPackaged })- initSshProject(win)+ sshProjectManager = initSshProject(win)app.on('activate', () => {if (BrowserWindow.getAllWindows().length === 0) createWindow()@@ -360,7 +362,11 @@ app.whenReady().then(async () => {app.on('window-all-closed', () => {ptyManager.killAll()+ sshProjectManager?.disconnectAll()if (process.platform !== 'darwin') app.quit()})-app.on('before-quit', () => ptyManager.killAll())+app.on('before-quit', () => {+ ptyManager.killAll()+ sshProjectManager?.disconnectAll()+})diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.tsindex c54fe7396..0319315d8 100644--- a/src/main/pty-manager.ts+++ b/src/main/pty-manager.ts@@ -186,7 +186,8 @@ export class PtyManager {registerIpc(): void {ipcMain.handle(IPC.ptyCreate,- (event, options: PtyCreateOptions): PtyCreateResult => this.create(event.sender.id, options)+ (event, options: PtyCreateOptions): Promise<PtyCreateResult> =>+ this.create(event.sender.id, options))ipcMain.on(IPC.ptyWrite, (_event, sessionId: string, data: string) =>this.write(sessionId, data)@@ -207,7 +208,10 @@ export class PtyManager {)}- private create(webContentsId: number, options: PtyCreateOptions): PtyCreateResult {+ private async create(+ webContentsId: number,+ options: PtyCreateOptions+ ): Promise<PtyCreateResult> {// A tmux-backed session is "fresh" (cold start) when no live session exists to reattach to// — i.e. first open, or after a machine reboot killed the tmux server. Plain (non-tmux)// sessions are always fresh: they have no cross-restart continuity. The renderer uses this@@ -215,9 +219,15 @@ export class PtyManager {const tmuxBacked =!!this.tmuxPath && this.getSettings().tmuxEnabled && !!options.persistKey// For an SSH-project node, "fresh" is decided by the REMOTE tmux server (over the project's- // ControlMaster), not the local one. Falls through to the local tmux/plain logic otherwise.+ // ControlMaster), not the local one. The remote `has-session` is a full network round-trip,+ // so it MUST be async (`runAsync`) — a synchronous probe here would freeze every window/IPC+ // for its duration. Falls through to the local tmux/plain logic otherwise (a local socket+ // probe is cheap and stays synchronous).const fresh = options.sshRemote- ? !this.remoteSessionExists(options.sshRemote, sessionName(options.persistKey as string))+ ? !(await this.remoteSessionExists(+ options.sshRemote,+ sessionName(options.persistKey as string)+ )): tmuxBacked? !this.tmuxSessionExists(options.persistKey as string): true@@ -225,17 +235,16 @@ export class PtyManager {return { sessionId, fresh }}- /** Does the node's remote tmux session exist (over the project's ControlMaster)? */- private remoteSessionExists(+ /** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so the+ * network round-trip never blocks the main event loop. */+ private async remoteSessionExists(sshRemote: NonNullable<PtyCreateOptions['sshRemote']>,sessionId: string- ): boolean {+ ): Promise<boolean> {const ssh = findSsh()if (!ssh) return falsetry {- execFileSync(ssh, remoteTmuxHasSessionArgs(sshRemote.conn, sshRemote.controlPath, sessionId), {- stdio: 'ignore'- })+ await runAsync(ssh, remoteTmuxHasSessionArgs(sshRemote.conn, sshRemote.controlPath, sessionId))return true} catch {return false@@ -415,7 +424,11 @@ export class PtyManager {// tmux-backed sessions snapshot their scrollback to disk periodically so a machine reboot// (which kills the tmux server) can still replay recent output on cold restart. A remote// (ssh-project) node is persisted too — the snapshot is captured from the REMOTE tmux.- const remote = options.sshRemote && options.persistKey ? options.sshRemote : undefined+ // Mark the session remote ONLY when the remote branch above actually ran (`remoteSsh` resolved).+ // If ssh is missing, the node fell through to a LOCAL tmux/plain spawn, so it must NOT be+ // marked remote — otherwise destroy/capture would target a remote tmux that was never spawned+ // and silently leak the local session.+ const remote = options.sshRemote && options.persistKey && remoteSsh ? options.sshRemote : undefinedconst tmuxBacked = !!(this.tmuxPath && settings.tmuxEnabled && options.persistKey)const persisted = !!options.persistKey && (remote ? true : tmuxBacked)const session: Session = {diff --git a/src/main/remote-ssh/control-master.test.ts b/src/main/remote-ssh/control-master.test.tsindex f4eb7374a..70cc52ef9 100644--- a/src/main/remote-ssh/control-master.test.ts+++ b/src/main/remote-ssh/control-master.test.ts@@ -4,6 +4,8 @@ import {masterArgs,childArgs,remoteTmuxHasSessionArgs,+ remoteCapturePaneArgs,+ remoteTmuxPtyArgs,listDirArgs,RMT_TMUX_SOCKET} from './control-master'@@ -53,6 +55,26 @@ describe('remoteTmuxHasSessionArgs', () => {})})+describe('remoteCapturePaneArgs', () => {+ it('captures the whole scrollback (-S -) when full', () => {+ const args = remoteCapturePaneArgs(conn, '/s.sock', 'nt-x', true)+ expect(args[args.length - 1]).toBe(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t nt-x -S -`)+ })+ it('captures the recent ~200 lines (-S -200) when not full', () => {+ const args = remoteCapturePaneArgs(conn, '/s.sock', 'nt-x', false)+ expect(args[args.length - 1]).toBe(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t nt-x -S -200`)+ })+})++describe('remoteTmuxPtyArgs', () => {+ it('runs the remote tmux command as a forced-TTY child (-t then childArgs)', () => {+ const args = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-x', '/srv/app')+ expect(args[0]).toBe('-t')+ const cmd = args[args.length - 1]+ expect(args.slice(1)).toEqual(childArgs(conn, '/s.sock', cmd))+ })+})+describe('listDirArgs', () => {it('lists directory entries of a quoted absolute path', () => {expect(listDirArgs(conn, '/s.sock', '/srv/app')).toEqual([diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 59aae289f..590e16899 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -10,8 +10,10 @@ import {masterArgs,listDirArgs,exitMasterArgs,- checkMasterArgs+ checkMasterArgs,+ remoteTmuxKillArgs} from './control-master'+import { sessionName } from '../tmux-naming'interface Runners {userDataDir: string@@ -64,7 +66,16 @@ export class SshProjectManager {async connect(projectId: string, conn: SshConnection): Promise<{ controlPath: string }> {const existing = this.conns.get(projectId)- if (existing) return { controlPath: existing.controlPath }+ if (existing) {+ // Verify the cached master is still alive before reusing it — a dropped/timed-out master+ // would otherwise leave us reusing a dead socket. If `-O check` fails, surface+ // `reconnecting`, drop the stale entry, and fall through to re-establish.+ const { code } = await this.r.run(checkMasterArgs(existing.conn, existing.controlPath))+ if (code === 0) return { controlPath: existing.controlPath }+ this.r.onStatus({ projectId, status: 'reconnecting' })+ existing.master.kill()+ this.conns.delete(projectId)+ }const controlPath = controlPathFor(this.r.userDataDir, projectId)// Best-effort: the socket dir lives under <userData> in production. If it can't be made,// the master/`-O check` loop below fails and we report an error status anyway.@@ -97,6 +108,26 @@ export class SshProjectManager {return { path: dir, dirs: parseLsDirs(stdout) }}+ /**+ * Authoritatively end the given nodes' REMOTE tmux sessions over the project's live master.+ * Called on project delete BEFORE disconnect, so the remote `nt-<id>` sessions are killed+ * regardless of whether the nodes were mounted (only the active project's nodes are). `nodeIds`+ * are raw node ids; we map each to its `nt-<id>` session name (the same name `spawnSession` /+ * `remoteTmuxHasSessionArgs` use). Best-effort per id — a missing session is ignored.+ */+ async killSessions(projectId: string, nodeIds: string[]): Promise<void> {+ const c = this.conns.get(projectId)+ if (!c) return+ await Promise.all(+ nodeIds.map((id) =>+ this.r.run(remoteTmuxKillArgs(c.conn, c.controlPath, sessionName(id))).then(+ () => undefined,+ () => undefined+ )+ )+ )+ }+disconnect(projectId: string): void {const c = this.conns.get(projectId)if (!c) return@@ -105,6 +136,11 @@ export class SshProjectManager {this.conns.delete(projectId)this.r.onStatus({ projectId, status: 'disconnected' })}++ /** Tear down every live master (on app quit) so no `-N` master ssh child is orphaned. */+ disconnectAll(): void {+ for (const projectId of [...this.conns.keys()]) this.disconnect(projectId)+ }}export function initSshProject(win: BrowserWindow): SshProjectManager {@@ -126,6 +162,9 @@ export function initSshProject(win: BrowserWindow): SshProjectManager {mgr.connect(projectId, conn))ipcMain.handle(IPC.sshDisconnectProject, (_e, projectId: string) => mgr.disconnect(projectId))+ ipcMain.handle(IPC.sshKillSessions, (_e, projectId: string, nodeIds: string[]) =>+ mgr.killSessions(projectId, nodeIds)+ )ipcMain.handle(IPC.sshListDir, (_e, projectId: string, dir: string) => mgr.listDir(projectId, dir))return mgr}diff --git a/src/preload/index.ts b/src/preload/index.tsindex 8d463e7a7..05cdf87fe 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -87,6 +87,8 @@ const api: NodeTerminalApi = {sshProject: {connect: (projectId, conn) => ipcRenderer.invoke(IPC.sshConnectProject, projectId, conn),disconnect: (projectId) => ipcRenderer.invoke(IPC.sshDisconnectProject, projectId),+ killSessions: (projectId, nodeIds) =>+ ipcRenderer.invoke(IPC.sshKillSessions, projectId, nodeIds),listDir: (projectId, dir) => ipcRenderer.invoke(IPC.sshListDir, projectId, dir),onStatus: (cb) => {const h = (_e: unknown, e: unknown) => cb(e as never)diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 035ba3acc..7d756ae8b 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -2243,10 +2243,20 @@ export function Canvas() {if ((n.kind ?? 'terminal') === 'terminal') transport.destroy(n.id)useAgentStatus.getState().remove(n.id)})- // SSH project: tear down its ControlMaster (after the terminals' remote tmux sessions are- // ended above) and drop the cached controlPath.+ // SSH project: the per-node `transport.destroy` above only ends the REMOTE session for+ // the (mounted) ACTIVE project's nodes — a non-active project has no live local sessions,+ // so its remote `nt-<id>` sessions would leak. Drive the remote teardown authoritatively+ // from main, keyed on the project binding, and sequence it BEFORE disconnect (which kills+ // the master): kill every terminal node's remote session over the still-alive master, then+ // tear the master down. Drop the cached controlPath immediately.if (project?.ssh) {- void window.nodeTerminal.sshProject.disconnect(id)+ const nodeIds = project.nodes+ .filter((n) => (n.kind ?? 'terminal') === 'terminal')+ .map((n) => n.id)+ void window.nodeTerminal.sshProject+ .killSessions(id, nodeIds)+ .catch(() => {})+ .finally(() => void window.nodeTerminal.sshProject.disconnect(id))useSshConn.getState().clear(id)}store.deleteProject(id)diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 5ad957ab9..db9b263e6 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -66,6 +66,7 @@ export const IPC = {sshImport: 'ssh:import-candidates',sshConnectProject: 'ssh:connect-project',sshDisconnectProject: 'ssh:disconnect-project',+ sshKillSessions: 'ssh:kill-sessions',sshListDir: 'ssh:list-dir',sshProjectStatus: 'ssh-project:status',gitStatus: 'git:status',diff --git a/src/shared/types.ts b/src/shared/types.tsindex eb081c976..eae6982ae 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -318,6 +318,13 @@ export interface SshProjectApi {connect(projectId: string, server: import('./ssh').SshConnection): Promise<{ controlPath: string }>/** Tear down the master (remote tmux is unaffected). */disconnect(projectId: string): Promise<void>+ /**+ * End the given terminal nodes' REMOTE tmux sessions over the project's live master.+ * Authoritative teardown on project delete: works regardless of whether the nodes are+ * mounted, and must be awaited BEFORE disconnect (which kills the master). `nodeIds` are+ * raw node ids; main maps them to `nt-<id>` session names.+ */+ killSessions(projectId: string, nodeIds: string[]): Promise<void>/** List remote sub-directories of `path` (default ~). */listDir(projectId: string, path: string): Promise<{ path: string; dirs: string[] }>onStatus(cb: (e: { projectId: string; status: SshProjectStatus; error?: string }) => void): () => void