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(ssh): host attachment — a remote node inside a local project

Claude Code31c685e900d1
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 18505cc8a..85bcc6e2a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -56,6 +56,7 @@ import {
useSharedGlyphActive
} from './SharedGlyphLayer'
import { SshReconnector } from '../lib/sshReconnect'
+import { hostAttachmentsFor } from '../lib/sshAttachments'
import { terminalKey } from '../terminal/terminal-config'
import {
setWebglGesture,
@@ -1711,6 +1712,32 @@ export function Canvas() {
// Local active project: ensure all git ops run local (no stale remote from a prior SSH tab).
void api.git.setActiveRemote(null)
}
+ // HOST ATTACHMENTS: remote nodes on this canvas whose machine is not the project's own — every
+ // remote node when the project is LOCAL. They have no project row to be connected from, so
+ // their masters are opened here, alongside the project's, under the stable attachment scope
+ // their terminals resolve (`sshConnectionIdForProject`). Idempotent in main, so a tab switch
+ // back is a no-op; failures are silent by design — the node's own 20s wait then its offline
+ // overlay is the user-visible half, and `requireRemote` guarantees nothing starts locally.
+ // NOTE: git routing is deliberately NOT armed for an attachment. The project's own cwd is what
+ // the Source Control panel is about, and an attached node must not repoint it at another host.
+ for (const attachment of hostAttachmentsFor(project.id, project.nodes, project.ssh?.server)) {
+ window.nodeTerminal.sshProject
+ .connect(attachment.scopeId, attachment.conn, attachment.remoteCwd)
+ .then((info) =>
+ useSshConn.getState().setConn(attachment.scopeId, {
+ ...info,
+ attachment: {
+ conn: attachment.conn,
+ hostKey: attachment.hostKey,
+ remoteCwd: attachment.remoteCwd,
+ ownerProjectId: project.id
+ }
+ })
+ )
+ .catch(() => {
+ /* the node's offline overlay + the reconnect coordinator own the retry */
+ })
+ }
loadingRef.current = true
const flow = nodeStatesToFlow(project.nodes)
setNodes(flow)
@@ -7680,7 +7707,21 @@ export function Canvas() {
const sshReconnectorRef = useRef<SshReconnector | null>(null)
useEffect(() => {
const rec = new SshReconnector({
- connect: async (projectId) => {
+ connect: async (scopeId) => {
+ // A HOST ATTACHMENT has no project row to read its endpoint from — the scope carries it.
+ // Reconnect it on its own loop (its master is its own) and leave git routing alone: the
+ // owning project is local, or points somewhere else entirely.
+ const attached = useSshConn.getState().getAttachment(scopeId)
+ if (attached) {
+ const info = await window.nodeTerminal.sshProject.connect(
+ scopeId,
+ attached.conn,
+ attached.remoteCwd
+ )
+ useSshConn.getState().setConn(scopeId, { ...info, attachment: attached })
+ return true
+ }
+ const projectId = scopeId
const project = useProjects.getState().getProject(projectId)
if (!project?.ssh) return false
const ssh = project.ssh
@@ -7693,7 +7734,9 @@ export function Canvas() {
useSshConn.getState().setConn(projectId, info)
return true
},
- respawn: (projectId, nodeIds) => {
+ respawn: (scopeId, nodeIds) => {
+ // The nodes live on the OWNING canvas, which for an attachment is not the scope id.
+ const projectId = useSshConn.getState().ownerProjectId(scopeId)
if (useProjects.getState().activeProjectId !== projectId) {
// The project was switched away between the drop and the reconnect: nothing is mounted,
// and any park is holding the DEAD pty (the node unmount-parked before the master came
@@ -8031,6 +8074,21 @@ export function Canvas() {
.finally(() => void window.nodeTerminal.sshProject.disconnect(id))
useSshConn.getState().clear(id)
}
+ // Host attachments this project owns: nothing else knows they exist (no project row), so
+ // deleting the canvas is the only chance to tear their masters down. Same order as above —
+ // kill the remote sessions over the live master, then drop it.
+ for (const scopeId of useSshConn.getState().attachmentScopesOf(id)) {
+ const nodeIds = project
+ ? hostAttachmentsFor(id, project.nodes, project.ssh?.server).find(
+ (a) => a.scopeId === scopeId
+ )?.nodeIds ?? []
+ : []
+ void window.nodeTerminal.sshProject
+ .killSessions(scopeId, nodeIds)
+ .catch(() => {})
+ .finally(() => void window.nodeTerminal.sshProject.disconnect(scopeId))
+ useSshConn.getState().clear(scopeId)
+ }
disposeRelayTabForProject(id)
store.deleteProject(id)
void writeDisk()
diff --git a/src/renderer/components/SshProjectDialog.tsx b/src/renderer/components/SshProjectDialog.tsx
index 828c2e24c..ba83e83c4 100644
--- a/src/renderer/components/SshProjectDialog.tsx
+++ b/src/renderer/components/SshProjectDialog.tsx
@@ -133,7 +133,11 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
// outlived the dialog for the rest of the app run.
connectBegunRef.current = true
await window.nodeTerminal.sshProject.connect(browseIdRef.current, srv)
- await list('~')
+ // Land in the machine's DEFAULT folder when it has one (Settings → Remote (SSH)); the
+ // point of configuring it is not to browse from `~` to the same place every time. Fall
+ // back to `~` if it no longer exists — a stale default must not dead-end the dialog.
+ const start = srv.remoteCwd?.trim() || '~'
+ await list(start).catch(() => list('~'))
setStep('browse')
} catch (err) {
setError((err as Error)?.message || 'Could not connect to the server.')
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index bf0459d65..e9bc68f4a 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -31,7 +31,7 @@ import {
CO_ATTACH_MOUSE_SEQ
} from '../../terminal/terminal-config'
import { useXtermVisualSettings } from '../../terminal/useXtermVisualSettings'
-import { resolveSshRemote, reportSshDrop } from '../../nodes/TerminalNode'
+import { resolveSshRemote, reportSshDrop, sshConnectionScope } from '../../nodes/TerminalNode'
import { buildSshArgs, type SshConnection } from '@shared/ssh'
/** The subset of a node's `data` a SECOND client needs to attach to its session the same way the
@@ -200,8 +200,13 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
void (async () => {
// Read here, not at click time: a modal only ever opens over the ACTIVE project, and the
- // reconnect coordinator is keyed by project (same assumption as resolveSshRemote's).
- const projectId = useProjects.getState().activeProjectId
+ // reconnect coordinator is keyed by CONNECTION SCOPE (same choice resolveSshRemote makes) —
+ // the project's own id, or the host attachment when this card's session is on a machine the
+ // project isn't.
+ const projectId =
+ spawn.sshRemoteTmux && spawn.ssh
+ ? sshConnectionScope(spawn.ssh)
+ : useProjects.getState().activeProjectId
// SSH-project node: resolve the live ControlMaster (may not be up yet on a cold load).
const sshRemote =
spawn.sshRemoteTmux && spawn.ssh
@@ -367,7 +372,10 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch }: Moda
const needsWrite = files.some((f) => !window.nodeTerminal.getPathForFile(f))
let paths: string[]
if (spawn.sshRemoteTmux) {
- const projectId = useProjects.getState().activeProjectId
+ // Uploads go over the master this card's PTY runs on — its scope, not the project's.
+ const projectId = spawn.ssh
+ ? sshConnectionScope(spawn.ssh)
+ : useProjects.getState().activeProjectId
setUploading(true)
try {
paths = await droppedPaths(files, { sshRemoteTmux: true, projectId })
diff --git a/src/renderer/components/settings/sections/SshSection.test.tsx b/src/renderer/components/settings/sections/SshSection.test.tsx
new file mode 100644
index 000000000..b31af4f73
--- /dev/null
+++ b/src/renderer/components/settings/sections/SshSection.test.tsx
@@ -0,0 +1,116 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { SshServer } from '@shared/ssh'
+import { useSshServers } from '../../../state/sshServers'
+import { SshSection } from './SshSection'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const SERVER: SshServer = {
+ id: 'ubuntu-1',
+ label: 'Ubuntu WSL',
+ host: 'devbox',
+ user: 'corvin',
+ port: 2222,
+ remoteCwd: '/home/corvin/projects/app'
+}
+
+describe('SshSection', () => {
+ let root: Root | undefined
+ let host: HTMLElement
+ let connect: ReturnType<typeof vi.fn>
+ let disconnect: ReturnType<typeof vi.fn>
+ let save: ReturnType<typeof vi.fn>
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ connect = vi.fn(async () => ({ controlPath: '/tmp/control' }))
+ disconnect = vi.fn(async () => {})
+ save = vi.fn(async () => [SERVER])
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ ssh: {
+ list: vi.fn(async () => [SERVER]),
+ save,
+ remove: vi.fn(async () => []),
+ importCandidates: vi.fn(async () => [])
+ },
+ sshProject: { connect, disconnect },
+ dialog: { selectFile: vi.fn(async () => null) }
+ }
+ useSshServers.setState({ servers: [SERVER] })
+ })
+
+ afterEach(() => {
+ act(() => root?.unmount())
+ root = undefined
+ host.remove()
+ })
+
+ const mount = (): void => {
+ root = createRoot(host)
+ act(() => root!.render(<SshSection isActive />))
+ }
+
+ const button = (label: string): HTMLButtonElement => {
+ const match = [...host.querySelectorAll('button')].find((el) => el.textContent?.includes(label))
+ if (!match) throw new Error(`button not found: ${label}`)
+ return match
+ }
+
+ const click = (el: Element): void => {
+ el.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ }
+
+ it('shows each machine’s default folder in the list', () => {
+ mount()
+ expect(host.textContent).toContain('Default folder: /home/corvin/projects/app')
+ })
+
+ it('tests the machine with its configured default folder and always disconnects', async () => {
+ mount()
+ act(() => click(button('Edit')))
+ await act(async () => click(button('Test connection')))
+
+ // Its OWN scope id — never a project's: joining a live project connection would report
+ // success without testing anything, and the disconnect would drop that project's terminals.
+ expect(connect).toHaveBeenCalledWith(
+ 'ssh-settings-test-ubuntu-1',
+ expect.objectContaining({ host: 'devbox', user: 'corvin', port: 2222 }),
+ '/home/corvin/projects/app'
+ )
+ expect(disconnect).toHaveBeenCalledWith('ssh-settings-test-ubuntu-1')
+ expect(host.textContent).toContain('Connection successful')
+ })
+
+ it('reports the failure and still tears the half-open master down', async () => {
+ connect.mockRejectedValueOnce(new Error('Permission denied (publickey)'))
+ mount()
+ act(() => click(button('Edit')))
+ await act(async () => click(button('Test connection')))
+
+ expect(host.textContent).toContain('Connection failed: Permission denied (publickey)')
+ expect(disconnect).toHaveBeenCalledWith('ssh-settings-test-ubuntu-1')
+ })
+
+ it('saves a blank default folder as `~` rather than an empty remote path', async () => {
+ mount()
+ act(() => click(button('Edit')))
+ const cwd = [...host.querySelectorAll('input')].find(
+ (el) => el.value === '/home/corvin/projects/app'
+ )!
+ act(() => {
+ const setter = Object.getOwnPropertyDescriptor(
+ HTMLInputElement.prototype,
+ 'value'
+ )!.set!
+ setter.call(cwd, ' ')
+ cwd.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await act(async () => click(button('Save')))
+
+ expect(save).toHaveBeenCalledWith(expect.objectContaining({ remoteCwd: '~' }))
+ })
+})
diff --git a/src/renderer/components/settings/sections/SshSection.tsx b/src/renderer/components/settings/sections/SshSection.tsx
index 4aee2ece8..5c87ea7c6 100644
--- a/src/renderer/components/settings/sections/SshSection.tsx
+++ b/src/renderer/components/settings/sections/SshSection.tsx
@@ -11,7 +11,10 @@ import { uuid } from '@renderer/lib/uuid'
const ROWS = {
servers: {
title: 'Saved SSH servers',
- keywords: ['ssh', 'remote', 'server', 'host', 'connect', 'identity', 'key']
+ keywords: [
+ 'ssh', 'remote', 'server', 'host', 'connect', 'identity', 'key',
+ 'test', 'folder', 'directory', 'cwd', 'working directory'
+ ]
}
}
const ENTRIES = Object.values(ROWS)
@@ -20,6 +23,8 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
const sshServers = useSshServers((s) => s.servers)
const [sshDraft, setSshDraft] = useState<SshServer | null>(null)
const [importMsg, setImportMsg] = useState<string | null>(null)
+ const [testMsg, setTestMsg] = useState<string | null>(null)
+ const [testing, setTesting] = useState(false)
useEffect(() => {
void useSshServers.getState().hydrate()
@@ -71,11 +76,39 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
!sshDraft.host.trim() ||
!sshDraft.user.trim()
+ /**
+ * Open a ControlMaster to the draft's endpoint, then close it — the same connect a project (or a
+ * host attachment) makes, so a green answer here means those will work too. It runs under its
+ * OWN scope id, never a project's: joining a live project connection would report success
+ * without testing anything, and disconnecting afterwards would drop that project's terminals.
+ */
+ const testConnection = async (): Promise<void> => {
+ if (!sshDraft || saveDisabled || testing) return
+ const connectionId = `ssh-settings-test-${sshDraft.id}`
+ setTesting(true)
+ setTestMsg(`Connecting to ${sshDraft.label}…`)
+ try {
+ await window.nodeTerminal.sshProject.connect(
+ connectionId,
+ sshDraft,
+ sshDraft.remoteCwd?.trim() || '~'
+ )
+ setTestMsg('Connection successful.')
+ } catch (error) {
+ setTestMsg(`Connection failed: ${error instanceof Error ? error.message : String(error)}`)
+ } finally {
+ // Always: a partially-established master left behind would be silently reused by the next
+ // test (and by anything else asking for this id), reporting a stale answer.
+ await window.nodeTerminal.sshProject.disconnect(connectionId).catch(() => {})
+ setTesting(false)
+ }
+ }
+
return (
<SettingsSection
id="ssh"
title="Remote (SSH)"
- description="Saved SSH servers appear under “New remote”. Opening remote terminals over SSH is free."
+ description="Saved SSH servers appear under “New remote”, and can host nodes on a local canvas. Opening remote terminals over SSH is free."
isActive={isActive}
searchEntries={ENTRIES}
>
@@ -86,12 +119,24 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
key={server.id}
className="flex items-center justify-between gap-4 rounded-md border border-border p-3"
>
- <span className="min-w-0 truncate text-sm text-text">
- {server.label} — {server.user}@{server.host}
- {server.port && server.port !== 22 ? `:${server.port}` : ''}
- </span>
+ <div className="min-w-0">
+ <div className="truncate text-sm text-text">
+ {server.label} — {server.user}@{server.host}
+ {server.port && server.port !== 22 ? `:${server.port}` : ''}
+ </div>
+ <div className="truncate text-xs text-muted">
+ Default folder: {server.remoteCwd || '~'}
+ </div>
+ </div>
<div className="flex shrink-0 gap-2">
- <Button onClick={() => setSshDraft(server)}>Edit</Button>
+ <Button
+ onClick={() => {
+ setTestMsg(null)
+ setSshDraft(server)
+ }}
+ >
+ Edit
+ </Button>
<Button
variant="ghost"
onClick={() => void useSshServers.getState().remove(server.id)}
@@ -150,6 +195,18 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
/>
}
/>
+ <FieldRow
+ label="Default working directory"
+ description="Folder new terminals on this machine open in, including ones attached to a local canvas."
+ control={
+ <Input
+ className="w-72 font-mono"
+ placeholder="~/projects/my-project"
+ value={sshDraft.remoteCwd ?? '~'}
+ onChange={(e) => setSshDraft({ ...sshDraft, remoteCwd: e.target.value })}
+ />
+ }
+ />
<FieldRow
label="Identity file"
description="Optional private key passed with -i."
@@ -186,16 +243,24 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
/>
}
/>
- <div className="flex justify-end gap-2 pt-1">
+ {testMsg ? <p className="text-xs text-muted">{testMsg}</p> : null}
+ <div className="flex flex-wrap justify-end gap-2 pt-1">
<Button variant="ghost" onClick={() => setSshDraft(null)}>
Cancel
</Button>
+ <Button disabled={saveDisabled || testing} onClick={() => void testConnection()}>
+ {testing ? 'Testing…' : 'Test connection'}
+ </Button>
<Button
variant="primary"
disabled={saveDisabled}
onClick={async () => {
- await useSshServers.getState().save(sshDraft)
+ await useSshServers.getState().save({
+ ...sshDraft,
+ remoteCwd: sshDraft.remoteCwd?.trim() || '~'
+ })
setSshDraft(null)
+ setTestMsg(null)
}}
>
Save
@@ -211,7 +276,8 @@ export function SshSection({ isActive }: { isActive: boolean }): React.JSX.Eleme
label: '',
host: '',
user: '',
- port: 22
+ port: 22,
+ remoteCwd: '~'
})
}
>
diff --git a/src/renderer/lib/sshAttachments.test.ts b/src/renderer/lib/sshAttachments.test.ts
new file mode 100644
index 000000000..b3db03295
--- /dev/null
+++ b/src/renderer/lib/sshAttachments.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest'
+import { sshAttachmentId, type SshConnection } from '@shared/ssh'
+import { hostAttachmentsFor, type AttachableNode } from './sshAttachments'
+
+const DEVBOX: SshConnection = { host: 'devbox', user: 'corvin', port: 2222 }
+const OTHER: SshConnection = { host: 'other', user: 'corvin' }
+
+const remote = (id: string, ssh: SshConnection, cwd?: string): AttachableNode => ({
+ id,
+ ssh,
+ sshRemoteTmux: true,
+ cwd
+})
+
+describe('hostAttachmentsFor', () => {
+ it('attaches every remote node of a LOCAL project to its host', () => {
+ const found = hostAttachmentsFor('local-1', [remote('n1', DEVBOX, '/srv/app')])
+ expect(found).toHaveLength(1)
+ expect(found[0].scopeId).toBe(sshAttachmentId('local-1', DEVBOX))
+ expect(found[0].hostKey).toBe('corvin@devbox')
+ expect(found[0].remoteCwd).toBe('/srv/app')
+ expect(found[0].nodeIds).toEqual(['n1'])
+ })
+
+ it('leaves an SSH project alone: its own master already serves its nodes', () => {
+ expect(hostAttachmentsFor('ssh-1', [remote('n1', DEVBOX)], DEVBOX)).toEqual([])
+ })
+
+ it('attaches a node inside an SSH project that points at a DIFFERENT machine', () => {
+ const found = hostAttachmentsFor('ssh-1', [remote('n1', DEVBOX), remote('n2', OTHER)], DEVBOX)
+ expect(found.map((a) => a.hostKey)).toEqual(['corvin@other'])
+ })
+
+ it('opens ONE master per machine, however many nodes are on it', () => {
+ const found = hostAttachmentsFor('local-1', [
+ remote('n1', DEVBOX, '/srv/app'),
+ remote('n2', { ...DEVBOX }, '/srv/other'),
+ remote('n3', OTHER)
+ ])
+ expect(found).toHaveLength(2)
+ const devbox = found.find((a) => a.hostKey === 'corvin@devbox')!
+ expect(devbox.nodeIds).toEqual(['n1', 'n2'])
+ // The connection is opened at the FIRST node's cwd; each node still spawns in its own.
+ expect(devbox.remoteCwd).toBe('/srv/app')
+ })
+
+ it('ignores a plain `ssh <host>` node — it runs ssh as its own local pty, no master needed', () => {
+ const local: AttachableNode = { id: 'n1', ssh: DEVBOX, sshRemoteTmux: false }
+ expect(hostAttachmentsFor('local-1', [local])).toEqual([])
+ })
+
+ it('ignores nodes with no ssh binding at all', () => {
+ expect(hostAttachmentsFor('local-1', [{ id: 'n1', cwd: '/home/me' }])).toEqual([])
+ })
+
+ it('gives two projects on the same machine their own scope', () => {
+ const a = hostAttachmentsFor('local-1', [remote('n1', DEVBOX)])[0]
+ const b = hostAttachmentsFor('local-2', [remote('n1', DEVBOX)])[0]
+ expect(a.scopeId).not.toBe(b.scopeId)
+ })
+
+ it('never returns the project id as a scope (that master is not this node’s)', () => {
+ for (const scope of hostAttachmentsFor('local-1', [remote('n1', DEVBOX), remote('n2', OTHER)])) {
+ expect(scope.scopeId).not.toBe('local-1')
+ }
+ })
+})
diff --git a/src/renderer/lib/sshAttachments.ts b/src/renderer/lib/sshAttachments.ts
new file mode 100644
index 000000000..8290ebec7
--- /dev/null
+++ b/src/renderer/lib/sshAttachments.ts
@@ -0,0 +1,62 @@
+import { sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
+
+/** One host a project's canvas has REMOTE nodes on, other than the project's own endpoint. */
+export interface HostAttachment {
+ /** Connection scope: `sshAttachmentId(projectId, conn)`. Keys `useSshConn`, the ControlMaster,
+ * and the reconnect loop, exactly as an SSH project's id does for its own nodes. */
+ scopeId: string
+ /** `user@host` — the machine, ignoring port/identity (same remote `$HOME`). */
+ hostKey: string
+ conn: SshConnection
+ /** The cwd the connection itself is opened with (the Explorer/scp base). The individual nodes
+ * still spawn in their OWN `cwd`; this is the first attached node's, as the representative. */
+ remoteCwd?: string
+ /** Node ids on this host — the connect banner and the reconnect flush work per scope. */
+ nodeIds: string[]
+}
+
+/** The subset of a persisted canvas node this needs. Deliberately structural: the caller passes
+ * either persisted node states or live React Flow `data`, and both satisfy it. */
+export interface AttachableNode {
+ id: string
+ ssh?: SshConnection
+ sshRemoteTmux?: boolean
+ cwd?: string
+}
+
+/**
+ * Which host attachments a project's canvas needs opened.
+ *
+ * A remote node whose endpoint IS the project's own is served by the project's ControlMaster and
+ * is not listed — that is main's whole model, and it stays untouched. Everything else is an
+ * attachment: every remote node on a LOCAL project, and a node pointed at a second host inside an
+ * SSH project. Grouped by scope, so one master serves every node on the same machine.
+ *
+ * `sshRemoteTmux` is required: a plain `ssh <host>` node (`createSshTerminalNode`) runs ssh as its
+ * own local PTY program and needs no master at all — opening one for it would be a connection the
+ * user never asked for.
+ */
+export function hostAttachmentsFor(
+ projectId: string,
+ nodes: readonly AttachableNode[],
+ projectServer?: SshConnection
+): HostAttachment[] {
+ const byScope = new Map<string, HostAttachment>()
+ for (const node of nodes) {
+ const conn = node.ssh
+ if (!conn || !node.sshRemoteTmux) continue
+ const scopeId = sshConnectionIdForProject(projectId, conn, projectServer)
+ if (scopeId === projectId) continue // the project's own master already serves this node
+ const existing = byScope.get(scopeId)
+ if (existing) existing.nodeIds.push(node.id)
+ else
+ byScope.set(scopeId, {
+ scopeId,
+ hostKey: sshHostKey(conn),
+ conn,
+ remoteCwd: node.cwd,
+ nodeIds: [node.id]
+ })
+ }
+ return [...byScope.values()]
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 793ad9d96..3e8b9c43a 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -142,7 +142,7 @@ import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from
import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, canReadTitle, createdAgentId, reportsOwnCopy, resumeCommand, agentConfig, agentLaunchProgram } from '@shared/agents/config'
import { withPermissionMode } from '@shared/agents/approval-mode'
import { ensureActivePermissionMode } from '../state/permissionMode'
-import { buildSshArgs, type SshConnection } from '@shared/ssh'
+import { buildSshArgs, sshConnectionIdForProject, type SshConnection } from '@shared/ssh'
import { hintLabel } from '@shared/platform-utils'
import { ColumnPill } from '../components/kanban/ColumnPill'
import { BoardLogPanel } from '../components/kanban/BoardLogPanel'
@@ -154,18 +154,37 @@ import { AgentMascot } from './AgentMascot'
* overlay it falls back to is cheap and self-healing, so waiting longer buys nothing. */
export const SSH_REMOTE_WAIT_MS = 20000
-/** The active project's live ControlMaster path, if any. Lets the caller tell "we will resolve in
- * a microtask" from "we are about to sit in the wait below" without duplicating the lookup. */
-export function currentControlPath(): string | undefined {
- return useSshConn.getState().getControlPath(useProjects.getState().activeProjectId)
+/**
+ * Which connection scope a remote node in the ACTIVE project runs over: the project's own id when
+ * the project IS that SSH endpoint, otherwise the project × endpoint host attachment — a remote
+ * node living in a local canvas (or in an SSH project pointed at a different host).
+ *
+ * A node only ever exists in the active project's React Flow, so the active project is its owner.
+ */
+export function sshConnectionScope(conn: SshConnection): string {
+ const { activeProjectId, getProject } = useProjects.getState()
+ return sshConnectionIdForProject(activeProjectId, conn, getProject(activeProjectId)?.ssh?.server)
+}
+
+/** The live ControlMaster path a remote node would run over, if any. Lets the caller tell "we will
+ * resolve in a microtask" from "we are about to sit in the wait below" without duplicating the
+ * lookup. Without a `conn` it answers for the active project's own connection. */
+export function currentControlPath(conn?: SshConnection): string | undefined {
+ return useSshConn
+ .getState()
+ .getControlPath(conn ? sshConnectionScope(conn) : useProjects.getState().activeProjectId)
}
/**
- * Resolve the `sshRemote` create option for an SSH-project terminal: the owning project's live
+ * Resolve the `sshRemote` create option for a remote terminal: its connection scope's live
* ControlMaster `controlPath` (set by Canvas's active-project effect on connect) plus the inline
* connection and remote cwd. The controlPath may not be ready yet on a cold app load (child
* effects run before the parent's connect resolves), so wait for it — briefly — before spawning.
*
+ * The scope is the OWNING PROJECT for an SSH project's own nodes and a HOST ATTACHMENT for a node
+ * whose endpoint isn't the project's — never a bare `activeProjectId`, which for an attached node
+ * would resolve the local project's (absent, or worse: a DIFFERENT host's) master.
+ *
* Returns undefined if no master appears within the window (connection failed). The caller must
* then spawn NOTHING — see `PtyCreateOptions.requireRemote`: a create without `sshRemote` does
* not degrade to "no session", it degrades to a LOCAL one wearing the remote node's identity.
@@ -184,7 +203,7 @@ export async function resolveSshRemote(
}
| undefined
> {
- const projectId = useProjects.getState().activeProjectId
+ const projectId = sshConnectionScope(conn)
let controlPath = useSshConn.getState().getControlPath(projectId)
if (!controlPath) {
controlPath = await new Promise<string | undefined>((resolve) => {
@@ -1390,7 +1409,10 @@ export function TerminalNode({
// `respawnNonce` ourselves: a respawn before the master is back would just re-run the same
// 20s wait and land right back here.
const reconnectOffline = (): void => {
- const projectId = useProjects.getState().activeProjectId
+ // The SCOPE, not the project: an attached node's master belongs to its host attachment, and
+ // retrying the local project's (nonexistent) connection would never bring this node back.
+ const conn = data.ssh as SshConnection | undefined
+ const projectId = conn ? sshConnectionScope(conn) : useProjects.getState().activeProjectId
if (projectId) sshRetryHandler?.(projectId, [id])
}
@@ -2296,10 +2318,11 @@ export function TerminalNode({
// `ssh` as a LOCAL pty program. Only the latter sets shell:'ssh' + buildSshArgs.
const sshRemoteTmux = !!data.sshRemoteTmux
const localSsh = !!ssh && !sshRemoteTmux
- // Owning project of an SSH-project terminal, captured at spawn time for the exit-255 drop
- // report below (a node only exists in the active project's React Flow, so the active
- // project is its owner — same assumption as resolveSshRemote).
- const sshProjectId = sshRemoteTmux ? useProjects.getState().activeProjectId : null
+ // Connection SCOPE of a remote terminal, captured at spawn time for the exit-255 drop report
+ // below. Same choice `resolveSshRemote` makes: the owning project for an SSH project's own
+ // node, the host attachment for a node attached to another endpoint — so the reconnect
+ // coordinator re-establishes the master this node actually died on.
+ const sshProjectId = sshRemoteTmux && ssh ? sshConnectionScope(ssh) : null
// Prefetch the persisted scrollback in parallel with the spawn so it's ready to replay the
// instant the session resolves (a cold restart after a reboot recreates the tmux session
// empty — see the `fresh` handling below). Cheap no-op ('') when there's no snapshot.
@@ -2328,7 +2351,7 @@ export function TerminalNode({
// or an unreachable host, and a terminal that is silently blank for that long reads as
// broken. Only when there is nothing to wait FOR is nothing printed (the common case: the
// master is already up and this resolves in a microtask).
- if (sshRemoteTmux && ssh && !currentControlPath()) {
+ if (sshRemoteTmux && ssh && !currentControlPath(ssh)) {
// Drop the overlay for the duration of the attempt (this respawn IS the retry the user or
// the coordinator asked for) so the line below is visible; it comes back if we fail.
setCo(termKey, { offline: false })
@@ -3664,7 +3687,12 @@ export function TerminalNode({
// Remote terminal: uploading over the ControlMaster takes seconds and pastes nothing until
// it's done, so show an overlay while it runs — without it a drop looks like it silently did
// nothing. (The upload + REMOTE-path resolution itself lives in the shared droppedPaths.)
- const projectId = useProjects.getState().activeProjectId
+ // Uploads go over the master this node's PTY runs on — its scope, which for an attached
+ // node is the host attachment, not the (local) project.
+ const dropConn = data.ssh as SshConnection | undefined
+ const projectId = dropConn
+ ? sshConnectionScope(dropConn)
+ : useProjects.getState().activeProjectId
if (uploadNoteTimer.current) clearTimeout(uploadNoteTimer.current)
setUploadNote({
text: `Uploading ${files.length === 1 ? files[0].name : `${files.length} files`}…`,
diff --git a/src/renderer/state/sshConn.test.ts b/src/renderer/state/sshConn.test.ts
index 183e2129b..f1b59e642 100644
--- a/src/renderer/state/sshConn.test.ts
+++ b/src/renderer/state/sshConn.test.ts
@@ -106,3 +106,56 @@ describe('useSshConn — tri-state probe answer + remote version (tab-menu hint)
expect(useSshConn.getState().getRemoteClaudeVersion('p1')).toBe('2.1.90 (Claude Code)')
})
})
+
+// A HOST ATTACHMENT — a remote node inside a canvas that is not that endpoint's SSH project —
+// has no project row anywhere. Its scope entry is the only record of how to reach the machine and
+// which canvas its nodes are on, so the reconnect coordinator reads it back out of here.
+describe('useSshConn — host attachments', () => {
+ const ATTACHMENT = {
+ conn: { host: 'devbox', user: 'corvin', port: 2222 },
+ hostKey: 'corvin@devbox',
+ remoteCwd: '/srv/app',
+ ownerProjectId: 'local-1'
+ }
+
+ it('answers the owning canvas for an attachment scope, and itself for an SSH project', () => {
+ const s = useSshConn.getState()
+ s.setConn('attached-local-1-deadbeef', { controlPath: '/tmp/a', attachment: ATTACHMENT })
+ s.setConn('ssh-project-1', { controlPath: '/tmp/b' })
+
+ expect(useSshConn.getState().ownerProjectId('attached-local-1-deadbeef')).toBe('local-1')
+ expect(useSshConn.getState().ownerProjectId('ssh-project-1')).toBe('ssh-project-1')
+ // Never undefined: an unknown scope answers itself, so a caller keyed on it still has an id.
+ expect(useSshConn.getState().ownerProjectId('nope')).toBe('nope')
+ })
+
+ it('an SSH project scope is not an attachment', () => {
+ useSshConn.getState().setConn('ssh-project-1', { controlPath: '/tmp/b' })
+ expect(useSshConn.getState().getAttachment('ssh-project-1')).toBeUndefined()
+ })
+
+ it('a RE-connect (bare IPC coordinates) keeps the routing facts', () => {
+ // The regression this guards: the reconnect loop heals the master, setConn overwrites the
+ // entry with what IPC returned, and the scope loses the only record of its endpoint — so the
+ // NEXT drop can never be reconnected, and the respawn goes to the wrong canvas.
+ const s = useSshConn.getState()
+ s.setConn('attached-local-1-deadbeef', { controlPath: '/tmp/a', attachment: ATTACHMENT })
+
+ s.setConn('attached-local-1-deadbeef', { controlPath: '/tmp/a2' })
+
+ const after = useSshConn.getState()
+ expect(after.getControlPath('attached-local-1-deadbeef')).toBe('/tmp/a2')
+ expect(after.getAttachment('attached-local-1-deadbeef')).toEqual(ATTACHMENT)
+ })
+
+ it('lists a project’s attachment scopes so its masters can be torn down with it', () => {
+ const s = useSshConn.getState()
+ s.setConn('a1', { controlPath: '/tmp/1', attachment: ATTACHMENT })
+ s.setConn('a2', { controlPath: '/tmp/2', attachment: { ...ATTACHMENT, hostKey: 'u@other' } })
+ s.setConn('a3', { controlPath: '/tmp/3', attachment: { ...ATTACHMENT, ownerProjectId: 'p2' } })
+ s.setConn('ssh-project-1', { controlPath: '/tmp/4' })
+
+ expect(useSshConn.getState().attachmentScopesOf('local-1').sort()).toEqual(['a1', 'a2'])
+ expect(useSshConn.getState().attachmentScopesOf('p2')).toEqual(['a3'])
+ })
+})
diff --git a/src/renderer/state/sshConn.ts b/src/renderer/state/sshConn.ts
index 5bd5f34d1..fd98f59d3 100644
--- a/src/renderer/state/sshConn.ts
+++ b/src/renderer/state/sshConn.ts
@@ -1,6 +1,8 @@
import { create } from 'zustand'
+import type { SshConnection } from '@shared/ssh'
-/** Live connection coordinates for one SSH project, returned by `sshProject.connect`. */
+/** Live connection coordinates for one connection scope, returned by `sshProject.connect`.
+ * A scope is an SSH PROJECT's id, or a host ATTACHMENT id — see `sshConnectionIdForProject`. */
export interface SshConnInfo {
/** ControlMaster socket path the project's terminals run their PTYs over. */
controlPath: string
@@ -22,6 +24,26 @@ export interface SshConnInfo {
/** The probed remote `claude --version` output (`null` = probe ran, claude not found). Feeds
* the tab menu's Auto hint; only present on a reused (already probed) connection. */
remoteClaudeVersion?: string | null
+ /**
+ * Routing facts for a HOST ATTACHMENT — a remote node living in a project that is not that
+ * endpoint's own SSH project. An SSH project can re-derive all of this from `getProject(id)`;
+ * an attachment has no project row of its own, so its scope carries them. Absent on a plain
+ * SSH-project entry, which is how the two are told apart.
+ */
+ attachment?: SshAttachment
+}
+
+/** What an attachment scope needs in order to be RE-connected (the reconnect coordinator) and to
+ * find the canvas its nodes are on (the respawn). Renderer-only: never persisted. */
+export interface SshAttachment {
+ /** The endpoint, snapshotted — the saved server may be edited or deleted underneath us. */
+ conn: SshConnection
+ /** `user@host` (`sshHostKey`) — for "am I already connected to this machine?" lookups. */
+ hostKey: string
+ /** Default remote folder for this attachment; `~` when the host has none configured. */
+ remoteCwd?: string
+ /** The LOCAL canvas project the attached nodes live on. */
+ ownerProjectId: string
}
/** What the remote probe has said so far — the tab menu's Auto hint reads differently for "not
@@ -30,11 +52,16 @@ export interface SshConnInfo {
export type SshAutoPermAnswer = 'yes' | 'no' | 'unknown'
/**
- * Transient map of SSH project id → its live connection info (ControlMaster `controlPath` +
+ * Transient map of CONNECTION SCOPE → its live connection info (ControlMaster `controlPath` +
* optional remote `hookEndpointPath`) returned by `sshProject.connect`. Not persisted: it's
* re-established on every launch by Canvas's active-project effect. A remote terminal node reads
- * its project's entry here to pass `sshRemote` into `transport.create`, so the PTY runs over the
- * project's master and (when present) the remote hook env is injected.
+ * its scope's entry here to pass `sshRemote` into `transport.create`, so the PTY runs over that
+ * master and (when present) the remote hook env is injected.
+ *
+ * A scope is USUALLY an SSH project's id. It is a host ATTACHMENT id (`sshAttachmentId`) when the
+ * node's endpoint is not its project's own — a remote node inside a LOCAL canvas. Both kinds live
+ * in this one map because everything downstream (connect, resolve, reconnect, disconnect) treats
+ * them identically; `attachment` is what distinguishes them.
*/
interface SshConnState {
byProject: Record<string, SshConnInfo>
@@ -53,6 +80,12 @@ interface SshConnState {
getHookEndpointPath(projectId: string): string | undefined
getTmuxConfPath(projectId: string): string | undefined
getRemoteHome(projectId: string): string | undefined
+ /** The routing facts of a HOST ATTACHMENT scope; undefined for an SSH project's own scope
+ * (which re-derives everything from its project row) and for anything not connected. */
+ getAttachment(scopeId: string): SshAttachment | undefined
+ /** The canvas project a connection scope's nodes live on: the owner for an attachment, the
+ * scope itself for an SSH project. Never undefined — callers key React Flow off it. */
+ ownerProjectId(scopeId: string): string
/** True ONLY when the remote CLI was probed and is known to accept `--permission-mode auto`.
* Not connected / never probed / older CLI all answer false (conservative — omit the flag). */
supportsAutoPermissionMode(projectId: string): boolean
@@ -68,6 +101,9 @@ interface SshConnState {
* design means "unknown" should win until the next probe lands, never a stale "yes". */
invalidateAutoPermissionMode(projectId: string): void
clear(projectId: string): void
+ /** Every attachment scope a project owns. Used to tear its masters down when the project is
+ * deleted — nothing else knows they exist (they have no project row). */
+ attachmentScopesOf(ownerProjectId: string): string[]
}
export const useSshConn = create<SshConnState>((set, get) => ({
@@ -76,7 +112,15 @@ export const useSshConn = create<SshConnState>((set, get) => ({
remoteClaudeVersionByProject: {},
setConn(projectId, info) {
set((s) => ({
- byProject: { ...s.byProject, [projectId]: info },
+ byProject: {
+ ...s.byProject,
+ // A RE-connect returns bare IPC coordinates with no attachment block; keep the one the
+ // scope already had, or the reconnect that just healed the master would erase the only
+ // record of how to reach it (and which canvas its nodes are on).
+ [projectId]: info.attachment
+ ? info
+ : { ...info, attachment: s.byProject[projectId]?.attachment }
+ },
// A reused (already probed) connection returns the answer with the connect result.
autoPermByProject:
info.claudeAutoPermissionMode === undefined
@@ -109,6 +153,12 @@ export const useSshConn = create<SshConnState>((set, get) => ({
getRemoteHome(projectId) {
return get().byProject[projectId]?.remoteHome
},
+ getAttachment(scopeId) {
+ return get().byProject[scopeId]?.attachment
+ },
+ ownerProjectId(scopeId) {
+ return get().byProject[scopeId]?.attachment?.ownerProjectId ?? scopeId
+ },
supportsAutoPermissionMode(projectId) {
return get().autoPermByProject[projectId] === true
},
@@ -141,5 +191,10 @@ export const useSshConn = create<SshConnState>((set, get) => ({
delete nextVersion[projectId]
return { byProject: next, autoPermByProject: nextAuto, remoteClaudeVersionByProject: nextVersion }
})
+ },
+ attachmentScopesOf(ownerProjectId) {
+ return Object.entries(get().byProject)
+ .filter(([, info]) => info.attachment?.ownerProjectId === ownerProjectId)
+ .map(([scopeId]) => scopeId)
}
}))
diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.ts
index 52cbc2e1c..51f69b995 100644
--- a/src/shared/ssh.test.ts
+++ b/src/shared/ssh.test.ts
@@ -9,6 +9,8 @@ import {
remoteTmuxCommand,
remoteTmuxConf,
parseLsDirs,
+ sshAttachmentId,
+ sshConnectionIdForProject,
sshHostKey
} from './ssh'
@@ -23,6 +25,62 @@ describe('sshHostKey', () => {
})
})
+describe('sshAttachmentId', () => {
+ it('shares one scope per project and endpoint without exposing the host in a filename', () => {
+ const a = sshAttachmentId('project-1', { host: 'ubuntu.lan', user: 'corvin', port: 22 })
+ expect(a).toBe(sshAttachmentId('project-1', { host: 'ubuntu.lan', user: 'corvin' }))
+ expect(a).not.toContain('ubuntu.lan')
+ expect(a).not.toBe(sshAttachmentId('project-2', { host: 'ubuntu.lan', user: 'corvin' }))
+ expect(a).not.toBe(sshAttachmentId('project-1', { host: 'ubuntu.lan', user: 'other' }))
+ })
+
+ it('separates two ports on the same host (two different sshd instances)', () => {
+ expect(sshAttachmentId('p', { host: 'h', user: 'u', port: 22 })).not.toBe(
+ sshAttachmentId('p', { host: 'h', user: 'u', port: 2222 })
+ )
+ })
+
+ it('is filesystem-safe: the ControlMaster socket path is built from it', () => {
+ expect(sshAttachmentId('p1', { host: 'a.very.long.hostname.example.com', user: 'u' })).toMatch(
+ /^attached-p1-[0-9a-f]{8}$/
+ )
+ })
+})
+
+describe('sshConnectionIdForProject', () => {
+ const ubuntu = { host: 'devbox', user: 'corvin', port: 2222 }
+
+ it('uses the project id when the project itself lives on that SSH endpoint', () => {
+ expect(sshConnectionIdForProject('project-1', ubuntu, { ...ubuntu })).toBe('project-1')
+ })
+
+ it('treats an omitted port as 22 on BOTH sides (same endpoint, one master)', () => {
+ const plain = { host: 'devbox', user: 'corvin' }
+ expect(sshConnectionIdForProject('p1', plain, { ...plain, port: 22 })).toBe('p1')
+ expect(sshConnectionIdForProject('p1', { ...plain, port: 22 }, plain)).toBe('p1')
+ })
+
+ it('uses the host attachment when a remote node lives in a local project', () => {
+ expect(sshConnectionIdForProject('project-1', ubuntu)).toBe(sshAttachmentId('project-1', ubuntu))
+ })
+
+ it("does not reuse an SSH project's connection for a node on another endpoint", () => {
+ expect(
+ sshConnectionIdForProject('project-1', ubuntu, {
+ host: 'another-host',
+ user: 'corvin',
+ port: 2222
+ })
+ ).toBe(sshAttachmentId('project-1', ubuntu))
+ })
+
+ it('never returns the project id for a node the project cannot serve', () => {
+ // The regression this guards: an attached node resolving the LOCAL project's (absent) master
+ // and, with no `sshRemote`, degrading into a local shell wearing the remote node's identity.
+ expect(sshConnectionIdForProject('local-project', ubuntu)).not.toBe('local-project')
+ })
+})
+
describe('parseSshConfig', () => {
it('parses a named host with HostName/User/Port/IdentityFile', () => {
const cfg = `Host prod
diff --git a/src/shared/ssh.ts b/src/shared/ssh.ts
index 25f114a6d..b9918f2bd 100644
--- a/src/shared/ssh.ts
+++ b/src/shared/ssh.ts
@@ -113,6 +113,54 @@ export function sshExtraArgsEnableLocalExec(extraArgs: string | undefined): bool
export interface SshServer extends SshConnection {
id: string
label: string
+ /** Default remote folder for anything opened on this machine — the "New remote" dialog's
+ * prefill, and the cwd of a node attached to this host from a LOCAL canvas project (which has
+ * no `remoteCwd` of its own to inherit). Optional; absent means `~`. */
+ remoteCwd?: string
+}
+
+/**
+ * Stable live-connection scope for an SSH host ATTACHED to a canvas project — i.e. a remote node
+ * living in a project that is not itself that endpoint's SSH project.
+ *
+ * Scoped by project AND endpoint, so two projects attaching the same host get their own
+ * ControlMaster (and their own reconnect loop), and one project attaching two hosts gets two. The
+ * endpoint is FNV-1a hashed rather than embedded: this id reaches the filesystem as part of the
+ * ControlMaster socket path, where a raw `user@host:port` would both leak the inventory and blow
+ * the sun_path length budget on a long hostname.
+ */
+export function sshAttachmentId(projectId: string, conn: SshConnection): string {
+ const input = `${conn.user}\0${conn.host}\0${conn.port ?? 22}`
+ let hash = 2166136261
+ for (let i = 0; i < input.length; i++) {
+ hash ^= input.charCodeAt(i)
+ hash = Math.imul(hash, 16777619)
+ }
+ return `attached-${projectId}-${(hash >>> 0).toString(16).padStart(8, '0')}`
+}
+
+/**
+ * Connection scope used by a remote node inside a project.
+ *
+ * An SSH PROJECT owns its ControlMaster under the project id — that is the whole of today's
+ * model, and this returns exactly that whenever the node's endpoint is the project's own. A
+ * remote node embedded in a LOCAL project (or in an SSH project pointed at a DIFFERENT host) owns
+ * a host attachment instead, under the stable project × endpoint id.
+ *
+ * Every consumer of that connection — spawn (`resolveSshRemote`), reconnect (`SshReconnector`),
+ * upload — must make the same choice, or a node resolves a master that was opened for someone
+ * else. Hence one function rather than the rule written out at each site.
+ */
+export function sshConnectionIdForProject(
+ projectId: string,
+ conn: SshConnection,
+ projectServer?: SshConnection
+): string {
+ const sameEndpoint =
+ projectServer?.host === conn.host &&
+ projectServer.user === conn.user &&
+ (projectServer.port ?? 22) === (conn.port ?? 22)
+ return sameEndpoint ? projectId : sshAttachmentId(projectId, conn)
}
/**