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): make a host attachment reachable before, and without, its first connect

Claude Code96acaeb443b7
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 85bcc6e2a..5b95054be 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -56,7 +56,11 @@ import {
useSharedGlyphActive
} from './SharedGlyphLayer'
import { SshReconnector } from '../lib/sshReconnect'
-import { hostAttachmentsFor } from '../lib/sshAttachments'
+import {
+ hostAttachmentsFor,
+ connectHostAttachment,
+ type SshConnectFn
+} from '../lib/sshAttachments'
import { terminalKey } from '../terminal/terminal-config'
import {
setWebglGesture,
@@ -187,6 +191,11 @@ import { buildHibernationCandidates } from '../lib/hibernationCandidates'
import { applyLoopDismiss } from '../lib/loopCard'
import { prepareQuickOpenFiles, type QuickOpenIndexedFile } from '../lib/quickOpenSearch'
import { isSafeQuickOpenRelPath } from '@shared/quick-open-filter'
+
+/** The real `sshProject.connect`, bound once. Passed into `connectHostAttachment` rather than
+ * reached for inside it, so that helper stays testable without an Electron preload. */
+const sshConnect: SshConnectFn = (scopeId, conn, remoteCwd) =>
+ window.nodeTerminal.sshProject.connect(scopeId, conn, remoteCwd)
import { opensInEditor } from '../lib/openTarget'
import { newEntryPath, parentDir } from '../lib/explorerCreate'
import { useProjects } from '../state/projects'
@@ -1715,28 +1724,24 @@ export function Canvas() {
// 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.
+ // their terminals resolve (`sshConnectionIdForProject`). This is a PRE-WARM only: a node added
+ // at runtime dials for itself from `resolveSshRemote`, and `connectHostAttachment` collapses
+ // both into one connect. 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 */
- })
+ void connectHostAttachment(
+ attachment.scopeId,
+ {
+ conn: attachment.conn,
+ hostKey: attachment.hostKey,
+ remoteCwd: attachment.remoteCwd,
+ ownerProjectId: project.id
+ },
+ sshConnect
+ )
}
loadingRef.current = true
const flow = nodeStatesToFlow(project.nodes)
@@ -7708,19 +7713,12 @@ export function Canvas() {
useEffect(() => {
const rec = new SshReconnector({
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.
+ // A HOST ATTACHMENT has no project row to read its endpoint from — `registerAttachment`
+ // put it on record before the first dial, precisely so a connect that never succeeded is
+ // still reachable here. 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
- }
+ if (attached) return connectHostAttachment(scopeId, attached, sshConnect)
const projectId = scopeId
const project = useProjects.getState().getProject(projectId)
if (!project?.ssh) return false
@@ -8087,7 +8085,7 @@ export function Canvas() {
.killSessions(scopeId, nodeIds)
.catch(() => {})
.finally(() => void window.nodeTerminal.sshProject.disconnect(scopeId))
- useSshConn.getState().clear(scopeId)
+ useSshConn.getState().clearAttachment(scopeId)
}
disposeRelayTabForProject(id)
store.deleteProject(id)
diff --git a/src/renderer/components/SshProjectDialog.test.tsx b/src/renderer/components/SshProjectDialog.test.tsx
index 1f1ca0fa2..e96b81fd9 100644
--- a/src/renderer/components/SshProjectDialog.test.tsx
+++ b/src/renderer/components/SshProjectDialog.test.tsx
@@ -94,3 +94,87 @@ describe('SshProjectDialog browse-master teardown', () => {
expect(onClose).toHaveBeenCalled()
})
})
+
+// Where the browse LANDS when the machine has a default folder configured. `listDir` cannot report
+// a missing directory — it echoes the path back with `dirs: []` whether the folder is gone or
+// merely empty — so existence is checked against the PARENT's listing. Getting that wrong drops
+// the user into a nonexistent path with "Use this folder" enabled.
+describe('SshProjectDialog default folder', () => {
+ let root: Root | undefined
+ let host: HTMLElement
+ let listDir: ReturnType<typeof vi.fn>
+
+ const WITH_DEFAULT: SshServer = { ...SERVER, remoteCwd: '/home/u/projects/app' }
+
+ beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ listDir = vi.fn(async (_id: string, dir: string) => ({ path: dir, dirs: [] }))
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ sshProject: {
+ connect: vi.fn(async () => ({ controlPath: '/tmp/cm' })),
+ disconnect: vi.fn(async () => {}),
+ listDir,
+ mkdir: vi.fn(async () => true)
+ }
+ }
+ useSshServers.setState({ servers: [WITH_DEFAULT] })
+ })
+
+ afterEach(() => {
+ act(() => root?.unmount())
+ root = undefined
+ host.remove()
+ })
+
+ const open = async (): Promise<void> => {
+ root = createRoot(host)
+ await act(async () => {
+ root!.render(<SshProjectDialog onCreate={vi.fn()} onManage={vi.fn()} onClose={vi.fn()} />)
+ })
+ await act(async () => {
+ const row = [...document.querySelectorAll('button')].find((b) =>
+ b.textContent?.includes('testbox')
+ )!
+ row.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ })
+ }
+
+ it('lands in the configured default folder when it exists', async () => {
+ listDir.mockImplementation(async (_id: string, dir: string) => ({
+ path: dir,
+ dirs: dir === '/home/u/projects' ? ['app'] : []
+ }))
+
+ await open()
+
+ expect(listDir).toHaveBeenCalledWith(expect.any(String), '/home/u/projects/app')
+ })
+
+ it('an EMPTY default folder is still the right place to land', async () => {
+ // The regression a `dirs.length === 0` test would introduce: a real, empty default folder is
+ // indistinguishable from a missing one by its own listing, so it must be judged by the parent.
+ listDir.mockImplementation(async (_id: string, dir: string) => ({
+ path: dir,
+ dirs: dir === '/home/u/projects' ? ['app'] : []
+ }))
+
+ await open()
+
+ const landed = listDir.mock.calls.at(-1)
+ expect(landed?.[1]).toBe('/home/u/projects/app')
+ })
+
+ it('falls back to ~ when the configured default is gone', async () => {
+ // The parent lists without it: the folder was renamed or deleted on the host since it was set.
+ listDir.mockImplementation(async (_id: string, dir: string) => ({
+ path: dir,
+ dirs: dir === '/home/u/projects' ? ['something-else'] : []
+ }))
+
+ await open()
+
+ expect(listDir).not.toHaveBeenCalledWith(expect.any(String), '/home/u/projects/app')
+ expect(listDir.mock.calls.at(-1)?.[1]).toBe('~')
+ })
+})
diff --git a/src/renderer/components/SshProjectDialog.tsx b/src/renderer/components/SshProjectDialog.tsx
index ba83e83c4..a24eb9897 100644
--- a/src/renderer/components/SshProjectDialog.tsx
+++ b/src/renderer/components/SshProjectDialog.tsx
@@ -98,6 +98,21 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
// Disconnect the browse master if the dialog unmounts without an explicit close.
useEffect(() => () => disconnectBrowse(), [disconnectBrowse])
+ /** Does `dir` exist on the remote? Asked of its PARENT's listing, because a `listDir` of a
+ * missing directory succeeds and answers `{ path: dir, dirs: [] }`. `~` is taken on faith. */
+ const dirExists = useCallback(async (dir: string): Promise<boolean> => {
+ if (dir === '~') return true
+ try {
+ const parent = await window.nodeTerminal.sshProject.listDir(
+ browseIdRef.current,
+ parentDir(dir)
+ )
+ return parent.dirs.includes(baseName(dir))
+ } catch {
+ return false
+ }
+ }, [])
+
const list = useCallback(async (dir: string) => {
const res = await window.nodeTerminal.sshProject.listDir(browseIdRef.current, dir)
setPath(res.path)
@@ -134,10 +149,15 @@ export function SshProjectDialog({ onCreate, onManage, onClose }: SshProjectDial
connectBegunRef.current = true
await window.nodeTerminal.sshProject.connect(browseIdRef.current, srv)
// 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.
+ // point of configuring it is not to browse from `~` to the same place every time.
+ //
+ // A stale default must not dead-end the dialog, and `listDir` cannot say so on its own:
+ // it echoes the path back and returns `dirs: []` whether the folder is missing or merely
+ // empty (`ls` failing is not an error it surfaces). So EXISTENCE is checked against the
+ // parent's listing before landing there — which also keeps a real, empty default working,
+ // unlike treating an empty listing as the failure signal.
const start = srv.remoteCwd?.trim() || '~'
- await list(start).catch(() => list('~'))
+ await list((await dirExists(start)) ? start : '~')
setStep('browse')
} catch (err) {
setError((err as Error)?.message || 'Could not connect to the server.')
diff --git a/src/renderer/components/settings/sections/SshSection.tsx b/src/renderer/components/settings/sections/SshSection.tsx
index 5c87ea7c6..232dd30f6 100644
--- a/src/renderer/components/settings/sections/SshSection.tsx
+++ b/src/renderer/components/settings/sections/SshSection.tsx
@@ -196,8 +196,8 @@ 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."
+ label="Default folder"
+ description="Where browsing this machine starts: the folder “New remote” opens at, and the one Test connection dials."
control={
<Input
className="w-72 font-mono"
diff --git a/src/renderer/lib/sshAttachments.test.ts b/src/renderer/lib/sshAttachments.test.ts
index b3db03295..2789eb025 100644
--- a/src/renderer/lib/sshAttachments.test.ts
+++ b/src/renderer/lib/sshAttachments.test.ts
@@ -1,6 +1,12 @@
-import { describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import { sshAttachmentId, type SshConnection } from '@shared/ssh'
-import { hostAttachmentsFor, type AttachableNode } from './sshAttachments'
+import { useSshConn } from '../state/sshConn'
+import {
+ connectHostAttachment,
+ hostAttachmentsFor,
+ resetHostAttachmentDials,
+ type AttachableNode
+} from './sshAttachments'
const DEVBOX: SshConnection = { host: 'devbox', user: 'corvin', port: 2222 }
const OTHER: SshConnection = { host: 'other', user: 'corvin' }
@@ -65,3 +71,102 @@ describe('hostAttachmentsFor', () => {
}
})
})
+
+describe('connectHostAttachment', () => {
+ const ATTACHMENT = {
+ conn: DEVBOX,
+ hostKey: 'corvin@devbox',
+ remoteCwd: '/srv/app',
+ ownerProjectId: 'local-1'
+ }
+
+ beforeEach(() => {
+ resetHostAttachmentDials()
+ useSshConn.setState({
+ byProject: {},
+ attachments: {},
+ autoPermByProject: {},
+ remoteClaudeVersionByProject: {}
+ })
+ })
+
+ it('records the endpoint BEFORE dialing, not after it succeeds', async () => {
+ // Ordering, not end state: main emits `status:'connected'` from inside its connect, over the
+ // same IPC pipe, so that event lands BEFORE this promise resolves. Anything reading the scope
+ // at that moment — `ownerProjectId`, which decides whether respawn bumps the nonce or takes
+ // the "switched away" branch — must already find the record.
+ let seenDuringDial: unknown
+ const connect = vi.fn(async () => {
+ seenDuringDial = useSshConn.getState().getAttachment('a1')
+ return { controlPath: '/tmp/cm' }
+ })
+
+ await connectHostAttachment('a1', ATTACHMENT, connect)
+
+ expect(seenDuringDial).toEqual(ATTACHMENT)
+ expect(useSshConn.getState().ownerProjectId('a1')).toBe('local-1')
+ })
+
+ it('keeps the endpoint on record when the FIRST connect fails', async () => {
+ // A cold load against a sleeping host. The reconnect coordinator's connect dep reads the
+ // endpoint back out of the store; without this it returns false on every backoff step and
+ // the offline overlay's Reconnect is inert for the rest of the app run.
+ const connect = vi.fn(async () => {
+ throw new Error('ssh: connect to host devbox port 2222: Host is down')
+ })
+
+ await expect(connectHostAttachment('a1', ATTACHMENT, connect)).resolves.toBe(false)
+
+ expect(useSshConn.getState().getAttachment('a1')).toEqual(ATTACHMENT)
+ expect(useSshConn.getState().getControlPath('a1')).toBeUndefined()
+ })
+
+ it('a failed dial does not poison the scope against the retry', async () => {
+ const connect = vi
+ .fn<() => Promise<{ controlPath: string }>>()
+ .mockRejectedValueOnce(new Error('Host is down'))
+ .mockResolvedValueOnce({ controlPath: '/tmp/cm' })
+
+ expect(await connectHostAttachment('a1', ATTACHMENT, connect)).toBe(false)
+ expect(await connectHostAttachment('a1', ATTACHMENT, connect)).toBe(true)
+
+ expect(connect).toHaveBeenCalledTimes(2)
+ expect(useSshConn.getState().getControlPath('a1')).toBe('/tmp/cm')
+ })
+
+ it('collapses concurrent callers into ONE dial', async () => {
+ // Every node on the machine calls this at spawn, on top of Canvas's pre-warm.
+ const connect = vi.fn(async () => ({ controlPath: '/tmp/cm' }))
+
+ const all = await Promise.all([
+ connectHostAttachment('a1', ATTACHMENT, connect),
+ connectHostAttachment('a1', ATTACHMENT, connect),
+ connectHostAttachment('a1', ATTACHMENT, connect)
+ ])
+
+ expect(all).toEqual([true, true, true])
+ expect(connect).toHaveBeenCalledTimes(1)
+ })
+
+ it('short-circuits on a live master but still refreshes the record', async () => {
+ const connect = vi.fn(async () => ({ controlPath: '/tmp/other' }))
+ useSshConn.getState().setConn('a1', { controlPath: '/tmp/live' })
+
+ expect(await connectHostAttachment('a1', ATTACHMENT, connect)).toBe(true)
+
+ expect(connect).not.toHaveBeenCalled()
+ // A tab switch back adopts the live master; the NEXT drop still needs the endpoint on record.
+ expect(useSshConn.getState().getAttachment('a1')).toEqual(ATTACHMENT)
+ })
+
+ it('dials each machine separately', async () => {
+ const connect = vi.fn(async () => ({ controlPath: '/tmp/cm' }))
+
+ await Promise.all([
+ connectHostAttachment('a1', ATTACHMENT, connect),
+ connectHostAttachment('a2', { ...ATTACHMENT, conn: OTHER, hostKey: 'corvin@other' }, connect)
+ ])
+
+ expect(connect).toHaveBeenCalledTimes(2)
+ })
+})
diff --git a/src/renderer/lib/sshAttachments.ts b/src/renderer/lib/sshAttachments.ts
index 8290ebec7..a9408b5bc 100644
--- a/src/renderer/lib/sshAttachments.ts
+++ b/src/renderer/lib/sshAttachments.ts
@@ -1,4 +1,5 @@
import { sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
+import { useSshConn, type SshAttachment, type SshConnInfo } from '../state/sshConn'
/** One host a project's canvas has REMOTE nodes on, other than the project's own endpoint. */
export interface HostAttachment {
@@ -60,3 +61,63 @@ export function hostAttachmentsFor(
}
return [...byScope.values()]
}
+
+/** `window.nodeTerminal.sshProject.connect`, injected so this is testable without Electron. */
+export type SshConnectFn = (
+ scopeId: string,
+ conn: SshConnection,
+ remoteCwd?: string
+) => Promise<SshConnInfo>
+
+/** Dials in flight, keyed by scope: several nodes on one machine must produce ONE connect. */
+const dialing = new Map<string, Promise<boolean>>()
+
+/**
+ * Ensure an attachment's ControlMaster is up, and make sure the scope is REACHABLE either way.
+ *
+ * Three orderings this gets right, each of which was a live bug:
+ *
+ * 1. The attachment is registered BEFORE the dial. A first connect that fails is exactly what the
+ * reconnect coordinator is for, and its `connect` dep has nowhere else to learn the endpoint —
+ * recording on success only left a cold load against a sleeping host permanently offline, the
+ * offline overlay's Reconnect included.
+ * 2. Also before the dial, because main emits `status:'connected'` from inside its connect — over
+ * the same IPC pipe, so it ARRIVES BEFORE the invoke reply. The reconnector's `onConnected`
+ * then maps scope → owning canvas through `ownerProjectId`, and a record written afterwards is
+ * written too late: the respawn takes the "switched away" branch and never bumps the nonce.
+ * 3. Concurrent callers share one dial. Every node on a machine calls this at spawn; without the
+ * in-flight map they would each open a master.
+ *
+ * Idempotent and safe to call on every spawn: a live `controlPath` short-circuits.
+ */
+export function connectHostAttachment(
+ scopeId: string,
+ attachment: SshAttachment,
+ connect: SshConnectFn
+): Promise<boolean> {
+ const store = useSshConn.getState()
+ // Registered even on the short-circuit path: an attachment adopted from an already-live master
+ // (a tab switch back) still needs its endpoint on record for the NEXT drop.
+ store.registerAttachment(scopeId, attachment)
+ if (store.getControlPath(scopeId)) return Promise.resolve(true)
+ const inFlight = dialing.get(scopeId)
+ if (inFlight) return inFlight
+ const attempt = connect(scopeId, attachment.conn, attachment.remoteCwd)
+ .then((info) => {
+ useSshConn.getState().setConn(scopeId, info)
+ return true
+ })
+ .catch(() => false)
+ // Cleared whatever happened: a failed dial must not poison the scope against the retry the
+ // reconnect coordinator is about to make.
+ .finally(() => {
+ dialing.delete(scopeId)
+ })
+ dialing.set(scopeId, attempt)
+ return attempt
+}
+
+/** Test seam only: forget in-flight dials between cases. */
+export function resetHostAttachmentDials(): void {
+ dialing.clear()
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 3e8b9c43a..e9a795bcf 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -142,11 +142,12 @@ 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, sshConnectionIdForProject, type SshConnection } from '@shared/ssh'
+import { buildSshArgs, sshConnectionIdForProject, sshHostKey, type SshConnection } from '@shared/ssh'
import { hintLabel } from '@shared/platform-utils'
import { ColumnPill } from '../components/kanban/ColumnPill'
import { BoardLogPanel } from '../components/kanban/BoardLogPanel'
import { AgentMascot } from './AgentMascot'
+import { connectHostAttachment } from '../lib/sshAttachments'
/** How long a remote terminal waits for its project's ControlMaster before giving up and showing
* the offline overlay. Sized for the SLOW-but-fine case (a cold app load whose connect is still
@@ -203,7 +204,26 @@ export async function resolveSshRemote(
}
| undefined
> {
+ const activeProjectId = useProjects.getState().activeProjectId
const projectId = sshConnectionScope(conn)
+ // A HOST ATTACHMENT dials for itself, HERE, because nothing else will. Canvas's active-project
+ // effect pre-warms the attachments it can SEE in the stored canvas, but a node created at
+ // runtime — the remote account-login retry drops one into whatever tab is active — never
+ // appears in that pass, and would otherwise wait out the window under a scope no master exists
+ // for and then sit offline forever. Idempotent and deduped, so the pre-warm and every node on
+ // the machine collapse into one connect; the wait below is what actually blocks on it.
+ if (projectId !== activeProjectId) {
+ void connectHostAttachment(
+ projectId,
+ {
+ conn,
+ hostKey: sshHostKey(conn),
+ remoteCwd: cwd,
+ ownerProjectId: activeProjectId
+ },
+ (scopeId, c, remoteCwd) => window.nodeTerminal.sshProject.connect(scopeId, c, remoteCwd)
+ )
+ }
let controlPath = useSshConn.getState().getControlPath(projectId)
if (!controlPath) {
controlPath = await new Promise<string | undefined>((resolve) => {
diff --git a/src/renderer/state/sshConn.test.ts b/src/renderer/state/sshConn.test.ts
index f1b59e642..11535a225 100644
--- a/src/renderer/state/sshConn.test.ts
+++ b/src/renderer/state/sshConn.test.ts
@@ -2,7 +2,12 @@ import { describe, it, expect, beforeEach } from 'vitest'
import { useSshConn } from './sshConn'
beforeEach(() => {
- useSshConn.setState({ byProject: {}, autoPermByProject: {}, remoteClaudeVersionByProject: {} })
+ useSshConn.setState({
+ byProject: {},
+ attachments: {},
+ autoPermByProject: {},
+ remoteClaudeVersionByProject: {}
+ })
})
// If a project's SSH server gets repointed to a DIFFERENT host whose claude CLI is older, the
@@ -107,9 +112,9 @@ describe('useSshConn — tri-state probe answer + remote version (tab-menu hint)
})
})
-// 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.
+// A HOST ATTACHMENT — a remote node inside a canvas that is not that endpoint's SSH project — has
+// no project row anywhere. The record here is the ONLY way back to the machine, and it is kept in
+// its own map (not on the connection) precisely so it survives a connect that never succeeded.
describe('useSshConn — host attachments', () => {
const ATTACHMENT = {
conn: { host: 'devbox', user: 'corvin', port: 2222 },
@@ -120,7 +125,7 @@ describe('useSshConn — host attachments', () => {
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.registerAttachment('attached-local-1-deadbeef', ATTACHMENT)
s.setConn('ssh-project-1', { controlPath: '/tmp/b' })
expect(useSshConn.getState().ownerProjectId('attached-local-1-deadbeef')).toBe('local-1')
@@ -134,28 +139,48 @@ describe('useSshConn — host attachments', () => {
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.
+ it('a registered attachment survives with NO connection at all', () => {
+ // The regression this guards: recording the routing facts on the connect RESULT. A cold load
+ // against a sleeping host then has no endpoint on record, so the reconnect coordinator's
+ // connect dep returns false on every backoff step and the offline overlay's Reconnect is
+ // inert for the rest of the app run.
+ useSshConn.getState().registerAttachment('a1', ATTACHMENT)
+
+ expect(useSshConn.getState().getControlPath('a1')).toBeUndefined()
+ expect(useSshConn.getState().getAttachment('a1')).toEqual(ATTACHMENT)
+ expect(useSshConn.getState().ownerProjectId('a1')).toBe('local-1')
+ })
+
+ it('a RE-connect does not disturb the routing facts', () => {
const s = useSshConn.getState()
- s.setConn('attached-local-1-deadbeef', { controlPath: '/tmp/a', attachment: ATTACHMENT })
+ s.registerAttachment('a1', ATTACHMENT)
- s.setConn('attached-local-1-deadbeef', { controlPath: '/tmp/a2' })
+ s.setConn('a1', { 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)
+ expect(useSshConn.getState().getControlPath('a1')).toBe('/tmp/a2')
+ expect(useSshConn.getState().getAttachment('a1')).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.registerAttachment('a1', ATTACHMENT)
+ s.registerAttachment('a2', { ...ATTACHMENT, hostKey: 'u@other' })
+ s.registerAttachment('a3', { ...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'])
})
+
+ it('clearAttachment forgets both the routing facts and the connection', () => {
+ const s = useSshConn.getState()
+ s.registerAttachment('a1', ATTACHMENT)
+ s.setConn('a1', { controlPath: '/tmp/a' })
+
+ s.clearAttachment('a1')
+
+ expect(useSshConn.getState().getAttachment('a1')).toBeUndefined()
+ expect(useSshConn.getState().getControlPath('a1')).toBeUndefined()
+ expect(useSshConn.getState().attachmentScopesOf('local-1')).toEqual([])
+ })
})
diff --git a/src/renderer/state/sshConn.ts b/src/renderer/state/sshConn.ts
index fd98f59d3..378c74036 100644
--- a/src/renderer/state/sshConn.ts
+++ b/src/renderer/state/sshConn.ts
@@ -24,23 +24,25 @@ 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. */
+/**
+ * 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 this is the only record of it.
+ *
+ * Kept in its OWN map, not on `SshConnInfo`, because it must exist BEFORE the connection does and
+ * must SURVIVE its failure: the reconnect coordinator reads the endpoint back out of here to
+ * redial, and the respawn reads the owning canvas out of here to know where the nodes are. Both
+ * of those run precisely when there is no live connection to hang the facts off. 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. */
+ /** The folder the CONNECTION is opened at (the scp/Explorer base); nodes spawn in their own. */
remoteCwd?: string
/** The LOCAL canvas project the attached nodes live on. */
ownerProjectId: string
@@ -65,6 +67,9 @@ export type SshAutoPermAnswer = 'yes' | 'no' | 'unknown'
*/
interface SshConnState {
byProject: Record<string, SshConnInfo>
+ /** Attachment scope id → how to reach it and whose canvas it serves. Written BEFORE the dial
+ * (see `registerAttachment`), so it outlives a failed connect. */
+ attachments: Record<string, SshAttachment>
/** project id → "the remote CLI accepts `--permission-mode auto`". Kept OUTSIDE `byProject`
* because the remote probe runs after connect and can land before OR after the connect promise
* writes the entry — a separate map makes the two orders equivalent. */
@@ -80,12 +85,21 @@ interface SshConnState {
getHookEndpointPath(projectId: string): string | undefined
getTmuxConfPath(projectId: string): string | undefined
getRemoteHome(projectId: string): string | undefined
+ /**
+ * Record how to reach an attachment scope. Call this BEFORE dialing, not after: a first connect
+ * that FAILS is exactly the case the reconnect coordinator exists for, and it has nowhere else
+ * to learn the endpoint from. Recording on success only made a cold load against a sleeping
+ * host unrecoverable for the rest of the app run.
+ */
+ registerAttachment(scopeId: string, attachment: SshAttachment): void
/** 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. */
+ * (which re-derives everything from its project row) and for a scope never registered. */
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
+ /** Forget an attachment entirely (its canvas was deleted). Also drops any live connection info. */
+ clearAttachment(scopeId: string): void
/** 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
@@ -108,19 +122,12 @@ interface SshConnState {
export const useSshConn = create<SshConnState>((set, get) => ({
byProject: {},
+ attachments: {},
autoPermByProject: {},
remoteClaudeVersionByProject: {},
setConn(projectId, info) {
set((s) => ({
- 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 }
- },
+ byProject: { ...s.byProject, [projectId]: info },
// A reused (already probed) connection returns the answer with the connect result.
autoPermByProject:
info.claudeAutoPermissionMode === undefined
@@ -153,11 +160,23 @@ export const useSshConn = create<SshConnState>((set, get) => ({
getRemoteHome(projectId) {
return get().byProject[projectId]?.remoteHome
},
+ registerAttachment(scopeId, attachment) {
+ set((s) => ({ attachments: { ...s.attachments, [scopeId]: attachment } }))
+ },
getAttachment(scopeId) {
- return get().byProject[scopeId]?.attachment
+ return get().attachments[scopeId]
},
ownerProjectId(scopeId) {
- return get().byProject[scopeId]?.attachment?.ownerProjectId ?? scopeId
+ return get().attachments[scopeId]?.ownerProjectId ?? scopeId
+ },
+ clearAttachment(scopeId) {
+ set((s) => {
+ const next = { ...s.attachments }
+ delete next[scopeId]
+ const conns = { ...s.byProject }
+ delete conns[scopeId]
+ return { attachments: next, byProject: conns }
+ })
},
supportsAutoPermissionMode(projectId) {
return get().autoPermByProject[projectId] === true
@@ -193,8 +212,8 @@ export const useSshConn = create<SshConnState>((set, get) => ({
})
},
attachmentScopesOf(ownerProjectId) {
- return Object.entries(get().byProject)
- .filter(([, info]) => info.attachment?.ownerProjectId === ownerProjectId)
+ return Object.entries(get().attachments)
+ .filter(([, a]) => a.ownerProjectId === ownerProjectId)
.map(([scopeId]) => scopeId)
}
}))
diff --git a/src/shared/ssh.test.ts b/src/shared/ssh.test.ts
index 51f69b995..e9463efe2 100644
--- a/src/shared/ssh.test.ts
+++ b/src/shared/ssh.test.ts
@@ -54,16 +54,30 @@ describe('sshConnectionIdForProject', () => {
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('a LOCAL project has no binding, so every remote node on it is an attachment', () => {
+ expect(sshConnectionIdForProject('local-1', ubuntu, undefined)).toBe(
+ sshAttachmentId('local-1', ubuntu)
+ )
})
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('serves a node naming the same HOST from the project, whatever user it was saved with', () => {
+ // An SSH project's canvas lives in `<remoteCwd>/.nodeterm/project.json` ON THE HOST, shared
+ // with everyone who opens that folder — so a node's persisted `user` is whoever CREATED it.
+ // If alice's nodes sent bob off to open a second master as `alice@box`, bob's whole canvas
+ // would fail (or sit on an askpass prompt) the moment he opened the project.
+ expect(
+ sshConnectionIdForProject('project-1', { host: 'devbox', user: 'alice', port: 2222 }, ubuntu)
+ ).toBe('project-1')
+ // Same for a port saved from a setup that reaches the machine differently.
+ expect(
+ sshConnectionIdForProject('project-1', { host: 'devbox', user: 'corvin', port: 22 }, ubuntu)
+ ).toBe('project-1')
+ })
+
it("does not reuse an SSH project's connection for a node on another endpoint", () => {
expect(
sshConnectionIdForProject('project-1', ubuntu, {
diff --git a/src/shared/ssh.ts b/src/shared/ssh.ts
index b9918f2bd..75a415fd0 100644
--- a/src/shared/ssh.ts
+++ b/src/shared/ssh.ts
@@ -113,9 +113,9 @@ 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 `~`. */
+ /** Where browsing this machine STARTS: the folder the "New remote" project dialog opens at, and
+ * the folder Test connection dials. It is a starting point, not an inherited default — a node's
+ * cwd comes from the project or node it was created in, never from here. Absent means `~`. */
remoteCwd?: string
}
@@ -143,24 +143,33 @@ export function sshAttachmentId(projectId: string, conn: SshConnection): string
* 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.
+ * model, and this returns exactly that whenever the project's own binding already reaches the
+ * node's machine. A remote node embedded in a LOCAL project (or in an SSH project bound to a
+ * DIFFERENT machine) 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.
+ *
+ * ## Why the project's binding wins on a HOST match, user and port included
+ *
+ * A node's `ssh` is a SNAPSHOT persisted into the canvas, and an SSH project's canvas lives in
+ * `<remoteCwd>/.nodeterm/project.json` ON THE HOST — shared with everyone who opens that folder.
+ * So the `user` (and port) on a node is whoever created it, not whoever is reading it: alice's
+ * nodes say `alice@box`, and when bob opens the same project as `bob@box` every one of them would
+ * ask for a second master dialing `alice@box` — which fails for bob, or worse sits on an askpass
+ * prompt. The project's binding is the authority on how THIS user reaches that machine, so a node
+ * naming the same host is served by it.
+ *
+ * The cost is a deliberate one: inside an SSH project you cannot pin a node to a second ACCOUNT on
+ * the same host. A different machine still gets its own attachment, which is the case this is for.
*/
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)
+ return projectServer?.host === conn.host ? projectId : sshAttachmentId(projectId, conn)
}
/**