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): route an SSH project's nodes by the project, never spawn them locally (#1238)
eneskirca7cc35308ea9e
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1395e5a9a..b453ff670 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -856,6 +856,25 @@ Lifecycle, by intent:The refusal is **only** in `spawnNew` — a co-attach JOIN to a live session for that node id isstill correct. An offline node reports itself to `SshReconnector`, so the canvas heals itself;`retryNow` (banner Reconnect / node Reconnect) skips the backoff and clears the refuse window.+ **Whether a node is remote comes from its PROJECT, never from its own fields** (issue #1186,+ `@shared/ssh-project-nodes`). `requireRemote`/`sshRemoteTmux` used to be stamped only by this+ machine's node factories, but an SSH project's `project.json` lives on the host and other writers+ put nodes into it — above all the host's own desktop, which opens the same folder as a LOCAL+ project (`cwd: "."`, no `ssh` fields). Such a node ran on the VIEWING machine in an unrelated+ folder, under the id the host was running. Three layers: (1) `fileToProject` routes every session+ node of an SSH project to the project's host (`routeSshProjectNodes`: `ssh` = the project server,+ `sshRemoteTmux`, cwd resolved POSIX-style against `remoteCwd`; editor/video/files get `sshFs`),+ and `persistedCanvases` / `getNodeResolved` read the cache the same way; (2) `projectToFile`+ writes the SSH mirror NEUTRAL (`neutralSshProjectNodes` drops those fields, cwd back to `./x`),+ because the file is shared LAYOUT — a node stamped "runs over ssh on <host>" cannot run on the+ host's own desktop at all; (3) core refuses a local spawn whose `ownerProjectId` is an SSH project+ (`PtyManager.setSshProjectCheck`, wired in BOTH shells from the index) even without+ `requireRemote`. Kept as written: a plain `ssh <host>` terminal (`ssh` without `sshRemoteTmux` —+ `shell: 'ssh'` at the spawn) and a foreign host ATTACHMENT (`sshRemoteTmux` + another host). The one+ local terminal an SSH canvas may hold is a LOCAL-account login node, marked in memory only+ (`renderer/lib/localOnSshCanvas.ts` → `localOnSshCanvas` on the create; a scoped relay guest's is+ deleted); after a restart it routes to the host like any other node. **Downgrade:** a build older+ than this one reads the neutral file's nodes as local (the bug it already had for host-made nodes).**The phone's relay `pty.attach` is the other way in, and it is closed the same way**(`PtyManager.prepareRelayAttach`, pure routing in `core/relay-attach-plan.ts`). It used to call`attachDetached(nodeId)` → `tmux new-session -A` on the LOCAL socket for whatever id the phonediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 4debbb264..8dd19c98b 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -613,6 +613,15 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneSSH node became a local shell in this machine's `$HOME`. CLAUDE.md, "A remote node is NEVERspawned locally".+- **An SSH project's node runs on the project's host — ask the project, not the node.** Node+ fields like `sshRemoteTmux` arrive through a shared `project.json` that the host's own desktop and+ teammates also write, so a node without them must still never become a local shell (issue #1186).+ `fileToProject` derives the routing from the project's SSH record, the file written back to the+ host stays neutral, and core refuses a local spawn owned by an SSH project+ (`PtyManager.setSshProjectCheck`). A new path that turns stored nodes into live ones or spawns a+ terminal goes through those, not through the node's fields alone. CLAUDE.md, "A remote node is+ NEVER spawned locally".+- **Phone keys and store links are platform-neutral.** New paired keys are stamped`nodeterm-mobile-<id>`, but revoke must keep matching the legacy `nodeterm-ios-<id>` stamp everyexisting iPhone carries (`src/main/pairing-core.ts`). Link to a store only throughdiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex c5f8d8d13..e9887505b 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -1266,6 +1266,8 @@ export class PtyManager {private overridesInFlight = new Map<string, Promise<ProjectSpawnOverrides | null>>()/** "Which SSH host owns this node?", from the persisted index — see `setRemoteNodeOwner`. */private remoteNodeOwner: RemoteNodeOwnerResolver | null = null+ /** "Is this project an SSH project?", from the index — see `setSshProjectCheck`. */+ private isSshProject: ((projectId: string) => boolean) | null = null/** Machine-local records the relay host's attach is decided from — see `setRelayNodeResolver`. */private relayNodes: RelayNodeResolver | null = null/** Host-authoritative launch facts for a phone's `pty.attach { launch }` (see relay-launch.ts).@@ -1930,6 +1932,16 @@ export class PtyManager {this.remoteNodeOwner = resolve}+ /**+ * Wire "is this machine-local project id an SSH project?", answered from the workspace INDEX —+ * the machine-local record, never a node's own fields (issue #1186). With it, `spawnRefusal`+ * refuses a local spawn for a node whose owning project runs on another machine even when the+ * caller forgot to route it remotely. Unwired (tests, early boot) = no such refusal.+ */+ setSshProjectCheck(check: ((projectId: string) => boolean) | null): void {+ this.isSshProject = check+ }+/*** The project's contribution to THIS spawn — bounded and fail-open on every path.*@@ -2739,6 +2751,22 @@ export class PtyManager {if (options.requireRemote && !(options.sshRemote && options.persistKey && findSsh())) {return 'ssh'}+ // The same refusal when the caller did NOT say `requireRemote` but the node belongs to an SSH+ // project (issue #1186). `requireRemote` comes from the node's own fields, and those reach a+ // node through a SHARED file the host's desktop, a teammate or git also write — a node without+ // them used to become a local shell (an agent shown inside the SSH project, running on this+ // machine in an unrelated folder, under the id the host was running). The owning project is+ // the machine-local fact. Exempt: a plain `ssh <host>` terminal (its program IS ssh) and the+ // renderer's explicit local-login mark (`localOnSshCanvas`).+ if (+ !options.sshRemote &&+ options.ownerProjectId &&+ options.shell !== 'ssh' &&+ options.localOnSshCanvas !== true &&+ this.isSshProject?.(options.ownerProjectId)+ ) {+ return 'ssh'+ }// A managed remote Codex account needs a known id and a safe resolved home so the// remote env builder can supply its private CODEX_HOME. Otherwise a fresh spawn would// silently use the host's system login. Agent-less login terminals use this same gate.diff --git a/src/core/pty-require-remote.test.ts b/src/core/pty-require-remote.test.tsindex 934c9d93b..3b7917f79 100644--- a/src/core/pty-require-remote.test.ts+++ b/src/core/pty-require-remote.test.ts@@ -59,13 +59,15 @@ vi.mock('./pty-devices', async (importOriginal) => ({describe('pty create: requireRemote never falls back to a local shell', () => {let fake: FakePlatform+ let manager: import('./pty-manager').PtyManagerbeforeEach(async () => {spawned.length = 0fake = fakePlatform()initPlatform(fake)const { PtyManager } = await import('./pty-manager')- new PtyManager().registerIpc()+ manager = new PtyManager()+ manager.registerIpc()})afterEach(() => {resetPlatformForTests()@@ -107,4 +109,43 @@ describe('pty create: requireRemote never falls back to a local shell', () => {expect(joined.unavailable).toBeUndefined()expect(joined.sessionId).toBe(first.sessionId)})++ // Issue #1186: `requireRemote` comes from the node's own fields, which reach a node through a+ // SHARED file the host's desktop also writes. The owning project — a machine-local fact — must+ // refuse the local spawn on its own when a caller forgot to route the node.+ describe('a node owned by an SSH project (issue #1186)', () => {+ const sshProjects = new Set(['ssh-p'])+ beforeEach(() => manager.setSshProjectCheck((id) => sshProjects.has(id)))++ it('refuses a local spawn with no requireRemote and no sshRemote', async () => {+ const res = await create(ALICE, { ownerProjectId: 'ssh-p', cwd: '.', agentId: 'codex' })+ expect(spawned).toHaveLength(0)+ expect(res.unavailable).toBe('ssh')+ })++ it('a LOCAL project still spawns locally', async () => {+ const res = await create(ALICE, { ownerProjectId: 'local-p', cwd: '/srv/app' })+ expect(spawned).toHaveLength(1)+ expect(res.unavailable).toBeUndefined()+ })++ it('a plain `ssh <host>` terminal is a local pty by design and still spawns', async () => {+ const res = await create(ALICE, { ownerProjectId: 'ssh-p', shell: 'ssh', shellArgs: ['-p', '22', 'u@h'] })+ expect(spawned).toHaveLength(1)+ expect(res.unavailable).toBeUndefined()+ })++ it('the renderer-marked local login node still spawns', async () => {+ const res = await create(ALICE, { ownerProjectId: 'ssh-p', localOnSshCanvas: true })+ expect(spawned).toHaveLength(1)+ expect(res.unavailable).toBeUndefined()+ })++ it('unwired: no refusal (the pre-check behaviour)', async () => {+ manager.setSshProjectCheck(null)+ const res = await create(ALICE, { ownerProjectId: 'ssh-p' })+ expect(spawned).toHaveLength(1)+ expect(res.unavailable).toBeUndefined()+ })+ })})diff --git a/src/core/relay/scoped-guest-policy.test.ts b/src/core/relay/scoped-guest-policy.test.tsindex fecc005e0..82636d77e 100644--- a/src/core/relay/scoped-guest-policy.test.ts+++ b/src/core/relay/scoped-guest-policy.test.ts@@ -95,6 +95,10 @@ describe('scoped guest — terminals', () => {})expect(d.allow && (d.args?.[0] as Record<string, unknown>).sshRemote).toBeUndefined()})+ it('drops a guest-sent local-login mark (issue #1186: this machine\'s UI sets it, never a peer)', () => {+ const d = decide(IPC.ptyCreate, { persistKey: 'a1', cols: 1, rows: 1, localOnSshCanvas: true })+ expect(d.allow && (d.args?.[0] as Record<string, unknown>).localOnSshCanvas).toBeUndefined()+ })it('forces requireRemote for an SSH project, whatever the guest sent (never a local shell)', () => {const remote = { ...deps(), projectIsRemote: (p: string) => p === 'alpha' }const d = decideScopedAccess('alpha', remote, IPC.ptyCreate, [diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex a4dcffabe..1489221f9 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -257,6 +257,9 @@ const ptyCreate: Check = (a, s) => {if (!nodeInScope(opts.persistKey, s)) return no(NODE_OUTSIDE)if (opts.ownerProjectId !== undefined && opts.ownerProjectId !== s.projectId) return no(OUTSIDE)delete opts.sshRemote+ // The local-login exemption from the SSH-project refusal is this machine's own UI's mark, never+ // a guest's (issue #1186).+ delete opts.localOnSshCanvasif (s.deps.projectIsRemote?.(s.projectId)) opts.requireRemote = trueconst root = rootOf(s)if (opts.cwd === undefined || opts.cwd === null || opts.cwd === '') {diff --git a/src/core/workspace-files.ssh-routing.test.ts b/src/core/workspace-files.ssh-routing.test.tsnew file mode 100644index 000000000..dc9ddf645--- /dev/null+++ b/src/core/workspace-files.ssh-routing.test.ts@@ -0,0 +1,127 @@+// Issue #1186: an SSH project's nodes run on the project's host, whatever the shared file says.+import { describe, it, expect } from 'vitest'+import type { CanvasNodeState, Project } from '../shared/types'+import { fileToProject, projectToFile, type ProjectFileV1 } from './workspace-files'++const server = { id: 'mini', label: 'Mini', host: 'mini.local', user: 'host', port: 22 }+const ssh = { server, remoteCwd: '/Users/host/project' }++function file(nodes: CanvasNodeState[]): ProjectFileV1 {+ return {+ version: 1,+ rev: 1,+ savedAt: '2026-10-12T00:00:00.000Z',+ id: 'shared-project',+ name: 'example',+ color: '#10a37f',+ viewport: { x: 0, y: 0, zoom: 1 },+ nodes+ } as ProjectFileV1+}++const base = { position: { x: 0, y: 0 }, size: { width: 700, height: 700 }, color: '#10a37f', group: null }++describe('SSH project node routing (issue #1186)', () => {+ it('routes a host-created Codex node (portable cwd, no ssh fields) to the project host', () => {+ // The issue's reproduction, verbatim in shape.+ const p = fileToProject(+ file([{ id: 'term-example', kind: 'terminal', title: 'Codex', cwd: '.', agentId: 'codex', ...base } as CanvasNodeState]),+ { id: 'ssh-viewer', ssh }+ )+ const n = p.nodes[0]+ expect(n.cwd).toBe('/Users/host/project')+ expect(n.sshRemoteTmux).toBe(true)+ expect(n.ssh?.host).toBe('mini.local')+ })++ it('routes a node with no kind (read as terminal) and resolves ./sub and a missing cwd', () => {+ const p = fileToProject(+ file([+ { id: 'a', title: 'A', cwd: './sub/dir', ...base } as CanvasNodeState,+ { id: 'b', kind: 'terminal', title: 'B', ...base } as CanvasNodeState,+ { id: 'c', kind: 'terminal', title: 'C', cwd: 'C:\\Users\\x', ...base } as CanvasNodeState+ ]),+ { id: 'ssh-viewer', ssh }+ )+ expect(p.nodes.map((n) => [n.cwd, n.sshRemoteTmux])).toEqual([+ ['/Users/host/project/sub/dir', true],+ ['/Users/host/project', true],+ ['/Users/host/project', true]+ ])+ })++ it('a forged "local" node cannot opt out: sshRemoteTmux:false is overridden', () => {+ const p = fileToProject(+ file([{ id: 'x', kind: 'terminal', title: 'X', cwd: '/tmp', sshRemoteTmux: false, ...base } as CanvasNodeState]),+ { id: 'ssh-viewer', ssh }+ )+ expect(p.nodes[0].sshRemoteTmux).toBe(true)+ expect(p.nodes[0].ssh?.host).toBe('mini.local')+ expect(p.nodes[0].cwd).toBe('/tmp')+ })++ it('keeps a plain ssh terminal and a foreign host attachment as they are', () => {+ const plain = { id: 'p', kind: 'terminal', title: 'P', ssh: { host: 'other', user: 'u' }, ...base } as CanvasNodeState+ const attached = {+ id: 'q', kind: 'terminal', title: 'Q', cwd: '/srv', sshRemoteTmux: true,+ ssh: { host: 'other', user: 'u' }, ...base+ } as CanvasNodeState+ const p = fileToProject(file([plain, attached]), { id: 'ssh-viewer', ssh })+ expect(p.nodes[0].sshRemoteTmux).toBeUndefined()+ expect(p.nodes[0].ssh?.host).toBe('other')+ expect(p.nodes[1].ssh?.host).toBe('other')+ expect(p.nodes[1].cwd).toBe('/srv')+ })++ it('marks editor/video/files nodes as remote-fs', () => {+ const p = fileToProject(+ file([+ { id: 'e', kind: 'editor', title: 'E', filePath: '/Users/host/project/a.ts', ...base } as CanvasNodeState,+ { id: 'f', kind: 'files', title: 'F', cwd: './src', ...base } as CanvasNodeState,+ { id: 's', kind: 'sticky', title: 'S', ...base } as CanvasNodeState+ ]),+ { id: 'ssh-viewer', ssh }+ )+ expect(p.nodes[0].sshFs).toBe(true)+ expect(p.nodes[1].sshFs).toBe(true)+ expect(p.nodes[1].cwd).toBe('/Users/host/project/src')+ expect(p.nodes[2].sshFs).toBeUndefined()+ })++ it('a LOCAL project is untouched', () => {+ const p = fileToProject(+ file([{ id: 'l', kind: 'terminal', title: 'L', cwd: '.', ...base } as CanvasNodeState]),+ { id: 'local', cwd: '/home/me/proj' }+ )+ expect(p.nodes[0].cwd).toBe('/home/me/proj')+ expect(p.nodes[0].sshRemoteTmux).toBeUndefined()+ expect(p.nodes[0].ssh).toBeUndefined()+ })++ it('the file written to the host carries layout, not this machine routing — and round-trips', () => {+ const project: Project = {+ id: 'ssh-viewer',+ name: 'example',+ color: '#10a37f',+ viewport: { x: 0, y: 0, zoom: 1 },+ ssh,+ nodes: [+ { id: 'own', kind: 'terminal', title: 'Own', cwd: '/Users/host/project/sub', ssh: { ...server }, sshRemoteTmux: true, ...base } as CanvasNodeState,+ { id: 'ed', kind: 'editor', title: 'Ed', filePath: '/Users/host/project/a.ts', sshFs: true, ...base } as CanvasNodeState,+ { id: 'att', kind: 'terminal', title: 'Att', cwd: '/srv', ssh: { host: 'other', user: 'u' }, sshRemoteTmux: true, ...base } as CanvasNodeState+ ]+ }+ const f = projectToFile(project, 3, '2026-10-16T00:00:00.000Z', project.id)+ const own = f.nodes.find((n) => n.id === 'own')!+ expect(own.ssh).toBeUndefined()+ expect(own.sshRemoteTmux).toBeUndefined()+ expect(own.cwd).toBe('./sub')+ expect(f.nodes.find((n) => n.id === 'ed')!.sshFs).toBeUndefined()+ // A foreign attachment keeps its routing: the project cannot tell where it runs.+ expect(f.nodes.find((n) => n.id === 'att')!.sshRemoteTmux).toBe(true)+ // ...and the next load puts it all back.+ const back = fileToProject(f, { id: 'ssh-viewer', ssh })+ expect(back.nodes.find((n) => n.id === 'own')).toMatchObject({ cwd: '/Users/host/project/sub', sshRemoteTmux: true })+ expect(back.nodes.find((n) => n.id === 'ed')!.sshFs).toBe(true)+ })+})diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.tsindex b8fe10a57..1c5e2af8c 100644--- a/src/core/workspace-files.ts+++ b/src/core/workspace-files.ts@@ -1,5 +1,6 @@import path from 'path'import { healPathAsName } from '../shared/project-name'+import { neutralSshProjectNodes, routeSshProjectNodes } from '../shared/ssh-project-nodes'import type { AgentPermissionMode } from '../shared/agents/config'import { collisionSeed, derivedProjectId, legacyFileId } from '../shared/project-id'import {@@ -357,7 +358,13 @@ export function projectToFile(// reached the live nodes some other way (a peer mutation, a hand edit) is never written into// the shared file as if it were ours.const nodes = sanitizeNodeTriggers(- stripSharedNodeExec(p.cwd ? toPortableNodes(p.nodes, p.cwd) : p.nodes)+ stripSharedNodeExec(+ p.cwd+ ? toPortableNodes(p.nodes, p.cwd)+ : // The SSH mirror records shared LAYOUT, not where this machine runs a node: the host's own+ // desktop opens the same file as a local project (issue #1186). Re-derived on every load.+ neutralSshProjectNodes(p.nodes, p.ssh)+ ))const icon = sanitizeProjectIcon(p.icon)// The SECOND seam for layouts. Live project data is reachable by a peer canvas mutation and by a@@ -686,7 +693,15 @@ export function fileToProject(// loadedAgentBrowserPartition; without it a cloned project.json forges another project's jar.nodes: sanitizeNodeTriggers(sanitizeBrowserPartitions(- applyLocalNodeExec(base.cwd ? resolveNodes(f.nodes, base.cwd) : f.nodes, base.localExec),+ applyLocalNodeExec(+ base.cwd+ ? resolveNodes(f.nodes, base.cwd)+ : // An SSH project's nodes run on ITS host, whatever the shared file says (issue #1186):+ // the host's own desktop, a teammate or git writes nodes into that file without this+ // machine's routing fields. See @shared/ssh-project-nodes.+ routeSshProjectNodes(f.nodes, base.ssh),+ base.localExec+ ),base.id)),diff --git a/src/core/workspace-store.relay-placements.test.ts b/src/core/workspace-store.relay-placements.test.tsindex 936b990f3..2f5bd01ea 100644--- a/src/core/workspace-store.relay-placements.test.ts+++ b/src/core/workspace-store.relay-placements.test.ts@@ -49,3 +49,30 @@ describe('WorkspaceStore.relayNodePlacements', () => {expect(store.relayNodePlacements('nope')).toEqual([])})})++// Issue #1186: an SSH project's cache holds the shared file's NEUTRAL form (no routing fields — the+// host's own desktop wrote some of those nodes). Every reader that decides where a node runs must see+// it routed to the project's host, with its cwd resolved against the remote folder.+describe('SSH project nodes read back routed (issue #1186)', () => {+ it('relayNodePlacements and getNodeResolved route a host-created node', async () => {+ const server = { id: 'mini', label: 'Mini', host: 'mini.local', user: 'host', port: 22 }+ const store = new WorkspaceStore()+ await store.save(+ ws([+ {+ ...project('ssh-p', undefined, [node('host-made', { cwd: '.', agentId: 'codex' })]),+ ssh: { server, remoteCwd: '/Users/host/project' }+ }+ ])+ )+ // What landed in the machine-local cache is the neutral form…+ expect(store.getNode('host-made')?.sshRemoteTmux).toBeUndefined()+ // …and what the routing readers see is the host.+ const resolved = store.getNodeResolved('host-made')+ expect(resolved).toMatchObject({ sshRemoteTmux: true, cwd: '/Users/host/project' })+ expect(resolved?.ssh?.host).toBe('mini.local')+ const [placement] = store.relayNodePlacements('host-made')+ expect(placement.projectServer?.host).toBe('mini.local')+ expect(placement.node).toMatchObject({ sshRemoteTmux: true, cwd: '/Users/host/project' })+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex 9f3b9f334..4aadd7751 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -40,6 +40,7 @@ import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './primport { editProjectCardLabels, ensureProjectBoard, setProjectCardColumn, type CardLabelEdit } from './project-kanban-write'import { boardLabels, cardMeta } from '../shared/kanban-labels'import { localizeAdoptedNode } from '../shared/adopt-cwd'+import { routeSshProjectNode, routeSshProjectNodes } from '../shared/ssh-project-nodes'import { clampProjectName, folderName } from '../shared/project-name'import { SYSTEM_NODE_COLORS } from '../shared/node-colors'import { codedError } from './relay/admin-error'@@ -2066,15 +2067,19 @@ export class WorkspaceStore {* cwds portable (`./sub`), and this resolves them against the project root exactly as* `fileToProject` / `persistedCanvases` do. For callers that hand the cwd to a resolver keyed on* the absolute path (the phone Chat verbs' transcript read). `getNode` keeps the stored form so- * its existing callers are unchanged.+ * its existing callers are unchanged. An SSH project's node comes back ROUTED (its host, its+ * remote cwd — `routeSshProjectNode`, issue #1186), since its cache holds the neutral shared form.*/getNodeResolved(nodeId: string): CanvasNodeState | undefined {const hit = this.findNode(nodeId)if (!hit) return undefined+ if (hit.ssh) return routeSshProjectNode(hit.node, hit.ssh)return hit.root ? resolveNodes([hit.node], hit.root)[0] : hit.node}- private findNode(nodeId: string): { node: CanvasNodeState; root?: string } | undefined {+ private findNode(+ nodeId: string+ ): { node: CanvasNodeState; root?: string; ssh?: Project['ssh'] } | undefined {for (const e of this.index?.entries ?? []) {let nodes: CanvasNodeState[] | undefinedif (e.project) nodes = e.project.nodes@@ -2091,7 +2096,12 @@ export class WorkspaceStore {}const node = nodes?.find((n) => n.id === nodeId)// Only a local ref's nodes come off the shared file in portable form.- if (node) return { node, root: !e.project && !e.cache && e.cwd ? e.cwd : undefined }+ if (node)+ return {+ node,+ root: !e.project && !e.cache && e.cwd ? e.cwd : undefined,+ ...(!e.project && e.cache && e.ssh ? { ssh: e.ssh } : {})+ }}return undefined}@@ -2261,7 +2271,9 @@ export class WorkspaceStore {} else if (e.cache) {out.push({id: e.id,- nodes: e.cache.nodes,+ // Routed exactly as `fileToProject` routes them (issue #1186): the cache is the shared+ // file's neutral form, and callers decide where a node runs from what this returns.+ nodes: routeSshProjectNodes(e.cache.nodes, e.ssh),bridges: sanitizeLinks(e.cache.bridges),ropes: sanitizeLinks(e.cache.ropes)})diff --git a/src/main/index.ts b/src/main/index.tsindex ba6322be2..37f744755 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -666,6 +666,10 @@ ptyManager.setRemoteNodeOwner((nodeId) => {remote: ref ? { conn: ref.conn, controlPath: ref.controlPath } : undefined}})+// The core half of "a remote node is never spawned locally" for a node whose OWN fields do not say+// it is remote (issue #1186): those fields arrive through the SSH project's shared file, which the+// host's desktop also writes. The owning project's index entry is the machine-local fact.+ptyManager.setSshProjectCheck((projectId) => workspaceStore.sshProjectIds().includes(projectId))// WHERE a phone's relay `pty.attach` runs, and with what env — decided in core// (`PtyManager.prepareRelayAttach` / `core/relay-attach-plan.ts`) from THIS machine's records, never// from the phone's words. Before this the relay attach ran `tmux new-session -A` on the LOCAL socketdiff --git a/src/main/ssh-project-spawn-wiring.test.ts b/src/main/ssh-project-spawn-wiring.test.tsnew file mode 100644index 000000000..7c0ce0ec2--- /dev/null+++ b/src/main/ssh-project-spawn-wiring.test.ts@@ -0,0 +1,28 @@+// Issue #1186: the core refusal "a node owned by an SSH project is never spawned locally" only exists+// when a shell WIRES the index predicate into PtyManager — an unwired setter compiles and does+// nothing. Pinned at source level, like the other wire tests in this directory.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'+import path from 'node:path'++const read = (rel: string): string =>+ readFileSync(path.join(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')++describe('SSH-project spawn refusal wiring (issue #1186)', () => {+ it('both shells wire setSshProjectCheck to the index', () => {+ for (const file of ['main/index.ts', 'server/index.ts']) {+ expect(read(file)).toMatch(+ /ptyManager\.setSshProjectCheck\(\(projectId\) => workspaceStore\.sshProjectIds\(\)\.includes\(projectId\)\)/+ )+ }+ })++ it('both spawn sites forward the in-memory local-login mark, and only Canvas sets it', () => {+ expect(read('renderer/nodes/TerminalNode.tsx')).toMatch(/isLocalOnSshCanvas\(id\) \? \{ localOnSshCanvas: true \}/)+ expect(read('renderer/components/kanban/ModalTerminal.tsx')).toMatch(+ /isLocalOnSshCanvas\(nodeId\) \? \{ localOnSshCanvas: true \}/+ )+ const canvas = read('renderer/canvas/Canvas.tsx')+ expect(canvas.match(/markLocalOnSshCanvas\(login\.id\)/g)?.length).toBe(2)+ })+})diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 72f0c1a37..87e3b2113 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1,5 +1,6 @@import { PrepareUpdateDialog } from '../components/PrepareUpdateDialog'import type { PrepNode } from '../lib/updatePrep'+import { markLocalOnSshCanvas } from '../lib/localOnSshCanvas'import { useDevPortScanner } from './useDevPortScanner'import { withCodexNoDaemon } from '@shared/agents/codex-daemon'import { codexApprovalCaps } from '../state/codexCli'@@ -6421,10 +6422,11 @@ export function Canvas() {// `$HOME`; there is no local directory that project could honestly offer.const { getProject, activeProjectId: pid } = useProjects.getState()const cwd = getProject(pid)?.cwd- setNodes((ns) => [- ...ns.map((n) => ({ ...n, selected: false })),- { ...createAccountLoginNode(accountId, ns.length, viewCenter(), ssh, cwd), selected: true }- ])+ const login = createAccountLoginNode(accountId, nodesRef.current.length, viewCenter(), ssh, cwd)+ // A LOCAL login dropped onto an SSH project's canvas is the one terminal there that runs on+ // this machine (issue #1186) — say so to core, from memory only (lib/localOnSshCanvas.ts).+ if (!ssh && getProject(pid)?.ssh) markLocalOnSshCanvas(login.id)+ setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), { ...login, selected: true }])markDirty()// The event fires from the full-screen Settings overlay — close it so the user actually// sees the login node (it spawns at viewCenter, selected). The defensive return above@@ -6465,13 +6467,10 @@ export function Canvas() {// `createTerminalNode` prefers `ssh.remoteCwd` — because a local path names nothing there.const { getProject, activeProjectId: pid } = useProjects.getState()const cwd = getProject(pid)?.cwd- setNodes((ns) => [- ...ns.map((n) => ({ ...n, selected: false })),- {- ...createCodexAccountLoginNode(accountId, ns.length, viewCenter(), cwd, ssh),- selected: true- }- ])+ const login = createCodexAccountLoginNode(accountId, nodesRef.current.length, viewCenter(), cwd, ssh)+ // Same local-login exemption as the Claude branch (issue #1186).+ if (!ssh && getProject(pid)?.ssh) markLocalOnSshCanvas(login.id)+ setNodes((ns) => [...ns.map((n) => ({ ...n, selected: false })), { ...login, selected: true }])markDirty()// Same reason as the Claude branch: the event fires from the full-screen Settings overlay,// which would otherwise hide the login node the user has to interact with.diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex da08e8aeb..f24ee7802 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -1,6 +1,7 @@import { useContextEnsure } from '../../terminal/useContextEnsure'import { transcriptSessionFor } from '../../lib/transcriptSession'import { FIND_DECORATIONS } from '../../lib/palette'+import { isLocalOnSshCanvas } from '../../lib/localOnSshCanvas'import { ptyRefusal } from '@shared/pty-refusal'import { patchImeModeSwitch } from '../../terminal/ime-mode-switch'@@ -535,7 +536,9 @@ export function ModalTerminal({agentId: spawn.agentId,accountId: spawn.accountId,sshRemote,- requireRemote: spawn.sshRemoteTmux+ requireRemote: spawn.sshRemoteTmux,+ // Same local-login exemption as the canvas node (issue #1186).+ ...(isLocalOnSshCanvas(nodeId) ? { localOnSshCanvas: true } : {})})// Refused core-side (the master died inside our round-trip, or `ssh` is missing).if (res.unavailable) {diff --git a/src/renderer/lib/localOnSshCanvas.ts b/src/renderer/lib/localOnSshCanvas.tsnew file mode 100644index 000000000..533cf6cac--- /dev/null+++ b/src/renderer/lib/localOnSshCanvas.ts@@ -0,0 +1,18 @@+// The ONE kind of node allowed to run on THIS machine while it sits on an SSH project's canvas+// (issue #1186): the login node Settings → Accounts drops onto whatever canvas is active when the+// user adds a LOCAL account. Every other terminal of an SSH project runs on the project's host, and+// core refuses a local spawn for it (`PtyManager.setSshProjectCheck`).+//+// In memory only, on purpose. The mark must not travel through anything another writer can touch —+// node data reaches the SSH project's shared file on the host — so it lives here for this app run and+// is set by exactly one caller (Canvas's add-account-login listener). After a restart the node is an+// ordinary node of the SSH project again and runs on the host.+const marked = new Set<string>()++export function markLocalOnSshCanvas(nodeId: string): void {+ marked.add(nodeId)+}++export function isLocalOnSshCanvas(nodeId: string): boolean {+ return marked.has(nodeId)+}diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 63ca221fc..fdc11cc9c 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -1,6 +1,7 @@import { elementOnScreen } from '../terminal/on-screen'import { useContextEnsure } from '../terminal/useContextEnsure'import { canPlainApprove, sendHeaderAnswer } from '../lib/approveGate'+import { isLocalOnSshCanvas } from '../lib/localOnSshCanvas'import { FIND_DECORATIONS } from '../lib/palette'import { ptyRefusal } from '@shared/pty-refusal'@@ -3635,7 +3636,10 @@ export function TerminalNode({sshRemote,// Belt AND braces: the guard above cannot see a `ssh` executable that has gone missing,// which is core's other route into the local branch.- requireRemote: sshRemoteTmux+ requireRemote: sshRemoteTmux,+ // The one local terminal an SSH project's canvas may hold (issue #1186): core refuses+ // every other local spawn owned by an SSH project. In-memory mark, never node data.+ ...(isLocalOnSshCanvas(id) ? { localOnSshCanvas: true } : {})}).then(async ({diff --git a/src/server/index.ts b/src/server/index.tsindex 3c2153d5f..e2d3e14b3 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -414,6 +414,10 @@ export async function startServer(// on the desktop it would also reach relay peers. A headless server with nobody attached simply// gets no answer, the prompt expires, and the shared value stays unused: fail closed on the// grant, fail open on the spawn.+ // A node owned by an SSH project is never spawned on THIS machine (issue #1186). This shell has+ // no SSH-project manager, so such a node cannot run anywhere here — refusing is the honest answer,+ // the same one the desktop gives while that project's ControlMaster is down.+ ptyManager.setSshProjectCheck((projectId) => workspaceStore.sshProjectIds().includes(projectId))ptyManager.setProjectSpawnOverrides(makeProjectSpawnOverrides({readSettings: (projectId) => workspaceStore.readProjectSettings(projectId),diff --git a/src/shared/ssh-project-nodes.test.ts b/src/shared/ssh-project-nodes.test.tsnew file mode 100644index 000000000..4b3503ad5--- /dev/null+++ b/src/shared/ssh-project-nodes.test.ts@@ -0,0 +1,25 @@+import { describe, it, expect } from 'vitest'+import { portableRemoteCwd, remoteNodeCwd } from './ssh-project-nodes'++describe('remoteNodeCwd / portableRemoteCwd', () => {+ it('resolves portable and relative paths against the remote folder, POSIX-style', () => {+ expect(remoteNodeCwd('.', '/srv/p')).toBe('/srv/p')+ expect(remoteNodeCwd('./a/b', '/srv/p/')).toBe('/srv/p/a/b')+ expect(remoteNodeCwd('a', '~')).toBe('~/a')+ expect(remoteNodeCwd(undefined, '~/p')).toBe('~/p')+ expect(remoteNodeCwd(42, '/srv/p')).toBe('/srv/p')+ })+ it('keeps the host’s own absolute and home paths, drops another OS’s', () => {+ expect(remoteNodeCwd('/etc', '/srv/p')).toBe('/etc')+ expect(remoteNodeCwd('~/x', '/srv/p')).toBe('~/x')+ expect(remoteNodeCwd('C:\\work', '/srv/p')).toBe('/srv/p')+ expect(remoteNodeCwd('\\\\share\\x', '/srv/p')).toBe('/srv/p')+ })+ it('portable form is the inverse inside the folder and leaves the outside alone', () => {+ expect(portableRemoteCwd('/srv/p', '/srv/p')).toBe('.')+ expect(portableRemoteCwd('/srv/p/a', '/srv/p/')).toBe('./a')+ expect(portableRemoteCwd('/srv/px', '/srv/p')).toBe('/srv/px')+ expect(portableRemoteCwd('~/p/a', '~/p')).toBe('./a')+ expect(portableRemoteCwd(undefined, '/srv/p')).toBeUndefined()+ })+})diff --git a/src/shared/ssh-project-nodes.ts b/src/shared/ssh-project-nodes.tsnew file mode 100644index 000000000..a98eddbd4--- /dev/null+++ b/src/shared/ssh-project-nodes.ts@@ -0,0 +1,129 @@+// Where an SSH project's nodes RUN is decided by the PROJECT, never by the node's own fields+// (issue #1186).+//+// An SSH project's `.nodeterm/project.json` lives on the remote host, and other writers put nodes+// into it: the host's own desktop (which opened the same folder as a LOCAL project — its nodes carry+// a portable `cwd: "."` and no `ssh`/`sshRemoteTmux`, because on the host they ARE local), a+// teammate, git, a hand edit. Routing used to come only from `data.sshRemoteTmux`, stamped by the+// node factories at creation on THIS machine, so every node another writer added was treated as a+// LOCAL terminal: an agent shown inside the SSH project ran on this machine, in whatever directory+// "." meant here, under the same `nt-<id>` the host was running.+//+// Two halves, both pure:+// - `routeSshProjectNodes` (READ): every session node of an SSH project runs on the project's host,+// with its cwd resolved against the project's remote folder. Applied wherever an SSH project's+// nodes are turned into canvas state (`fileToProject`) or read back for a routing decision+// (`WorkspaceStore.persistedCanvases` / `getNodeResolved`).+// - `neutralSshProjectNodes` (WRITE): the same fields are taken back OUT of the file we write to+// the host. The file is shared with whoever else opens that folder — above all the host's own+// desktop, for which a node stamped "runs over ssh on <host>" is a node that cannot run at all.+// The file therefore records shared LAYOUT, and each machine derives where a node runs from its+// own machine-local record of the project.+//+// Two node shapes keep their own routing, because the node's fields say something the project+// cannot: a plain `ssh <host>` terminal (`ssh` without `sshRemoteTmux` — a LOCAL pty whose program+// is `ssh`), and a host ATTACHMENT (`sshRemoteTmux` with an `ssh` naming another host). Neither can+// put a local shell on this machine that the user did not already get from the same field in any+// local project.+import type { CanvasNodeState } from './types'+import type { SshConnection } from './ssh'++export interface SshProjectBinding {+ server: SshConnection+ remoteCwd: string+}++/** Kinds that run a pty session (`nodeStatesToFlow` reads a missing kind as `terminal`). */+const isSessionKind = (n: CanvasNodeState): boolean => n.kind === undefined || n.kind === 'terminal'+/** Kinds whose file access goes over the project's remote fs when `sshFs` is set. */+const isRemoteFsKind = (n: CanvasNodeState): boolean =>+ n.kind === 'editor' || n.kind === 'video' || n.kind === 'files'++const isWindowsPath = (p: string): boolean => /^[A-Za-z]:[\\/]/.test(p) || p.startsWith('\\')++/**+ * A node cwd as the REMOTE shell must see it. Portable `.`/`./x` (and a bare relative path) are+ * joined onto the project's remote folder with POSIX separators; an absolute POSIX path or a `~`+ * path is the host's already. A missing cwd, or one only another OS could have written (a Windows+ * drive path), falls back to the project folder rather than to the remote `$HOME`.+ */+export function remoteNodeCwd(cwd: unknown, remoteCwd: string): string {+ if (typeof cwd !== 'string' || cwd === '' || cwd === '.' || cwd === './') return remoteCwd+ if (cwd.startsWith('/') || cwd === '~' || cwd.startsWith('~/')) return cwd+ if (isWindowsPath(cwd)) return remoteCwd+ const rel = cwd.startsWith('./') ? cwd.slice(2) : cwd+ return `${remoteCwd.replace(/\/+$/, '')}/${rel}`+}++/** The portable inverse of `remoteNodeCwd` for the shared file: a path inside the project folder+ * becomes `.`/`./x`, so a machine that opened the same folder LOCALLY resolves it against its own+ * root. Anything outside the folder is left as written. */+export function portableRemoteCwd(cwd: string | undefined, remoteCwd: string): string | undefined {+ if (typeof cwd !== 'string') return cwd+ const root = remoteCwd.replace(/\/+$/, '')+ if (!root) return cwd+ if (cwd === root || cwd === `${root}/`) return '.'+ if (cwd.startsWith(`${root}/`)) return `./${cwd.slice(root.length + 1)}`+ return cwd+}++/** A plain `ssh <host>` terminal: a local pty whose program is `ssh`. */+const isPlainSshTerminal = (n: CanvasNodeState): boolean => !!n.ssh && n.sshRemoteTmux !== true++/** A remote session attached to ANOTHER host than the project's own (see `sshConnectionIdForProject`). */+const isForeignAttachment = (n: CanvasNodeState, server: SshConnection): boolean =>+ n.sshRemoteTmux === true && !!n.ssh?.host && n.ssh.host !== server.host++/** One node, routed by its SSH project (see the file header). */+export function routeSshProjectNode(n: CanvasNodeState, binding: SshProjectBinding): CanvasNodeState {+ if (isSessionKind(n)) {+ if (isPlainSshTerminal(n) || isForeignAttachment(n, binding.server)) return n+ return {+ ...n,+ ssh: { ...binding.server },+ sshRemoteTmux: true,+ cwd: remoteNodeCwd(n.cwd, binding.remoteCwd)+ }+ }+ if (isRemoteFsKind(n)) {+ return {+ ...n,+ sshFs: true,+ ...(n.kind === 'files' ? { cwd: remoteNodeCwd(n.cwd, binding.remoteCwd) } : {})+ }+ }+ return n+}++export function routeSshProjectNodes(+ nodes: CanvasNodeState[],+ binding: SshProjectBinding | undefined+): CanvasNodeState[] {+ if (!binding) return nodes+ return nodes.map((n) => routeSshProjectNode(n, binding))+}++/** One node, as written to the SSH project's shared file (see the file header). */+export function neutralSshProjectNode(n: CanvasNodeState, binding: SshProjectBinding): CanvasNodeState {+ if (isSessionKind(n)) {+ if (n.sshRemoteTmux !== true || isForeignAttachment(n, binding.server)) return n+ const { ssh: _ssh, sshRemoteTmux: _tmux, ...rest } = n+ const cwd = portableRemoteCwd(n.cwd, binding.remoteCwd)+ return { ...rest, ...(cwd === undefined ? {} : { cwd }) }+ }+ if (isRemoteFsKind(n) && n.sshFs !== undefined) {+ const { sshFs: _fs, ...rest } = n+ if (n.kind !== 'files') return rest+ const cwd = portableRemoteCwd(n.cwd, binding.remoteCwd)+ return { ...rest, ...(cwd === undefined ? {} : { cwd }) }+ }+ return n+}++export function neutralSshProjectNodes(+ nodes: CanvasNodeState[],+ binding: SshProjectBinding | undefined+): CanvasNodeState[] {+ if (!binding) return nodes+ return nodes.map((n) => neutralSshProjectNode(n, binding))+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex c699d0a68..183742193 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -213,6 +213,15 @@ export interface PtyCreateOptions {* "not connected" overlay and re-spawns when the master is back.*/requireRemote?: boolean+ /**+ * The ONE way a terminal may run on THIS machine while it sits on an SSH project's canvas: the+ * local-account login node Settings → Accounts drops onto whatever canvas is active. Core refuses+ * every other local spawn whose `ownerProjectId` is an SSH project (`PtyManager.setSshProjectCheck`,+ * issue #1186) — the node fields that route a node remotely come from a shared file, and a node+ * that lacks them must never become a local shell. Set only from an in-memory, never-persisted+ * renderer mark (`renderer/lib/localOnSshCanvas.ts`), never from node data.+ */+ localOnSshCanvas?: boolean/*** Hosted-relay VIEWERS may watch a terminal but never start one: refuse a create that would spawn* a NEW session (`unavailable: 'join-only'`), while a co-attach join or a warm tmux reattach still