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(kanban): card modal and terminals refuse to start a remote project's node locally

reviewebc623ae3f64
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index f7d609a7d..b5c0ab671 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -90,9 +90,11 @@ const ChatPanel = lazy(() => import('../../nodes/ChatPanel').then((m) => ({ defa
interface CardModalProps {
session: KanbanSession
/** The project whose board this card is on — the active one on the per-project board, the lane's
- * on the Omni board. The modal sits OUTSIDE that project's `SessionProvider` (`useSession()`
- * here is the app's local session), so anything that depends on which machine the node runs
- * on resolves through this id: the LIVE chip (R57) and the "Share live link" action (H4). */
+ * on the Omni board. Both boards mount the modal under THAT project's session
+ * (`ProjectSessionScope`: `sessionForProject(projectId)` + `OwningProjectContext`), so
+ * `useSession()` here and in the terminal, chat and file views below is the core the node runs
+ * on — a team tab's relay session, never this desktop's local one. The LIVE chip (R57) and the
+ * "Share live link" action (H4) still resolve through this id. */
projectId: string
/** Owning project, supplied by the board (not necessarily the active project in Omni). */
projectName?: string
diff --git a/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
index d69a7e32b..82dc49c01 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
@@ -28,7 +28,9 @@ vi.mock('../../session/session', () => ({
? { id: 'hosted-session', source: 'relay', api: hostedApi }
: projectId === 'relay'
? { id: 'relay-session', source: 'relay', api: hostedApi }
- : { id: 'local', source: 'local', api: localApi }
+ : { id: 'local', source: 'local', api: localApi },
+ // The card modal's `ProjectSessionScope` provides the lane's session; `useSession` is mocked above.
+ SessionProvider: ({ children }: { children: unknown }) => children
}))
vi.mock('../../state/hostedTeams', () => ({
isHostedReadOnly: (sessionId: string) => sessionId === 'hosted-session'
diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsx
index 373efcebc..328dfc044 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@ -18,6 +18,7 @@ import { markCanvasCovered } from '../../lib/canvasCovered'
import { showCanvas, useViewMode } from '../../state/viewMode'
import { KanbanScopeSwitch } from './KanbanScopeSwitch'
import { sessionForProject } from '../../session/session'
+import { ProjectSessionScope } from '../../session/owning-project'
import { isHostedReadOnly } from '../../state/hostedTeams'
import { activePermissionMode } from '../../state/permissionMode'
import { CardModal } from './CardModal'
@@ -348,6 +349,9 @@ const Swimlane = memo(function Swimlane({
<ContextMenu x={cardMenu.x} y={cardMenu.y} zIndex={60} items={cardMenuItems(cardMenu.nodeId)} onClose={() => setCardMenu(null)} />
)}
{modalNodeId && byId.has(modalNodeId) && (
+ // The overview renders under App's LOCAL provider: the modal runs under THIS lane's
+ // project's session, so a team lane's terminal attaches to the host's core.
+ <ProjectSessionScope projectId={projectId}>
<CardModal
projectName={projectName}
projectColor={projectColor}
@@ -372,6 +376,7 @@ const Swimlane = memo(function Swimlane({
team={teams.get(modalNodeId) ?? NO_STATIONS}
onTravel={(nodeId) => { setModalNodeId(null); travel(nodeId) }}
/>
+ </ProjectSessionScope>
)}
</div>
)
diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
index 498ac38ba..c735dd837 100644
--- a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
@@ -12,7 +12,10 @@ import { defaultKanban } from '../../lib/kanban'
import type { MenuItem } from '../ContextMenu'
vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
+ sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
+ SessionProvider: ({ children }: { children: unknown }) => children
}))
vi.mock('./CardModal', () => ({
CardModal: (p: { session: { id: string }; initialView?: string; onDelete?: () => void; onSetColor?: (c: string) => void }) => (
diff --git a/src/renderer/components/kanban/KanbanView.keyboard.test.tsx b/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
index b9b4f3cd5..d1954cdf2 100644
--- a/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
@@ -13,7 +13,10 @@ import { runBoardKey } from '../../lib/boardKeys'
import { popDialog, pushDialog, resetDialogStack } from '../dialog-stack'
vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
+ sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
+ SessionProvider: ({ children }: { children: unknown }) => children
}))
// The real modal is exercised by CardModal.test; here it only has to be a dialog on the stack that
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index 1a2aef40f..6668dd73e 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -45,6 +45,7 @@ import { NO_ISSUE_RUNS, boundRunsByIssue, type IssueRun } from '../../lib/issueR
import { useGitHubIssues } from '../../state/githubIssues'
import { useAgentStatus } from '../../state/agentStatus'
import { useSession } from '../../session/session'
+import { ProjectSessionScope } from '../../session/owning-project'
import { KanbanSourceFilter, type KanbanSource } from './KanbanSourceFilter'
import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'
import { ConfirmDialog } from '../ConfirmDialog'
@@ -1279,6 +1280,9 @@ export const KanbanView = memo(function KanbanView({
/>
)}
{modalNodeId && byId.has(modalNodeId) && (
+ // The board renders under App's LOCAL provider, outside Canvas's node subtree: the modal
+ // runs under ITS project's session, so a team tab's terminal attaches to the host's core.
+ <ProjectSessionScope projectId={projectId}>
<CardModal
projectName={projectName}
projectColor={projectColor}
@@ -1316,6 +1320,7 @@ export const KanbanView = memo(function KanbanView({
onOpenNode(nodeId)
}}
/>
+ </ProjectSessionScope>
)}
{modalIssue && (
<GitHubIssueSummaryModal
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 7aeaf8821..9adffa052 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -21,6 +21,7 @@ import { FindBar } from '../FindBar'
import { useAgentStatus } from '../../state/agentStatus'
import { useProjects } from '../../state/projects'
import { useSession } from '../../session/session'
+import { spawnBelongsElsewhere, useOwningProjectId } from '../../session/owning-project'
import { isHostedReadOnly } from '../../state/hostedTeams'
import { useSettings } from '../../state/settings'
import { isMacPlatform, isWindowsPlatform } from '@shared/platform-utils'
@@ -161,6 +162,11 @@ export function ModalTerminal({
// Read at click time from the lifecycle effect, which runs once per mount.
const projectIdRef = useRef(projectId)
projectIdRef.current = projectId
+ // MIRROR TerminalNode: the project this viewer's node belongs to, as the board's
+ // `ProjectSessionScope` provides it — read by the create path below, which runs once per mount.
+ const owningProject = useOwningProjectId()
+ const owningProjectRef = useRef(owningProject)
+ owningProjectRef.current = owningProject
const onOpenFileRef = useRef(onOpenFile)
onOpenFileRef.current = onOpenFile
// MIRROR TerminalNode: the path dialect belongs to the core that owns the filesystem, never this
@@ -491,18 +497,34 @@ export function ModalTerminal({
return false
})
+ // MIRROR TerminalNode's `dialsSsh`: a RELAY card's SSH-project node lives on the HOST's side,
+ // so this machine never dials for it (session/relay-ssh.ts). Its create goes to the host's
+ // core with `requireRemote`, which joins the session when the host holds it live and refuses
+ // otherwise. This machine has no master to resolve for it and must not refuse it for lacking one.
+ const dialsSsh = !!spawn.sshRemoteTmux && session.source !== 'relay'
void (async () => {
- // Read here, not at click time: a modal only ever opens over the ACTIVE project, and the
- // 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.
+ // MIRROR TerminalNode: a node of a REMOTE project (a relay / hosted team tab) under a session
+ // that is not a relay session would create the host's node id on THIS desktop's core. The
+ // board mounts the modal under the card's project session (`ProjectSessionScope`), so this
+ // is the defensive half: start nothing, before any SSH resolve.
+ const owner = owningProjectRef.current
+ if (spawnBelongsElsewhere(useProjects.getState().getProject(owner ?? ''), session.source)) {
+ term.write(
+ '\r\n\x1b[90m[this terminal belongs to a remote project that is not connected here — nothing was started on this machine]\x1b[0m\r\n'
+ )
+ return
+ }
+ // Read here, not at click time. A dialing node's 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. Any other node's pane is owned
+ // by the CARD's project (the Omni board opens cards of every project), else the active one.
const projectId =
- spawn.sshRemoteTmux && spawn.ssh
+ dialsSsh && spawn.ssh
? sshConnectionScope(spawn.ssh)
- : useProjects.getState().activeProjectId
+ : (owner ?? 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
+ dialsSsh && spawn.ssh
? await resolveSshRemote(spawn.ssh, spawn.cwd, { nodeId, pty: api.pty })
: undefined
if (dead) return
@@ -510,7 +532,7 @@ export function ModalTerminal({
// core's LOCAL tmux branch, and opening a card for a remote session would silently start a
// local shell under that node's id — see PtyCreateOptions.requireRemote. The card says so
// and the node is queued for the reconnect coordinator, exactly like the canvas node.
- if (spawn.sshRemoteTmux && !sshRemote) {
+ if (dialsSsh && !sshRemote) {
term.write(
`\r\n\x1b[90m[not connected — this session lives on ${spawn.ssh ? `${spawn.ssh.user}@${spawn.ssh.host}` : 'the remote host'}; nothing was started locally]\x1b[0m\r\n`
)
@@ -556,7 +578,7 @@ export function ModalTerminal({
if (res.unavailable) {
const refusal = ptyRefusal(res.unavailable)
term.write(`\r\n\x1b[90m[${refusal.message}]\x1b[0m\r\n`)
- if (refusal.connectionLost && projectId) reportSshDrop(projectId, nodeId)
+ if (refusal.connectionLost && projectId && dialsSsh) reportSshDrop(projectId, nodeId)
return
}
// Another client permanently deleted this node's session — never resurrect it (no live session
diff --git a/src/renderer/components/kanban/cardModalSession.test.tsx b/src/renderer/components/kanban/cardModalSession.test.tsx
new file mode 100644
index 000000000..e7033efb0
--- /dev/null
+++ b/src/renderer/components/kanban/cardModalSession.test.tsx
@@ -0,0 +1,206 @@
+// @vitest-environment jsdom
+//
+// Bug F, the card-modal path (report-F.md, "Other paths": DETERMINISTIC). Both kanban boards render
+// OUTSIDE Canvas's node-subtree SessionProvider, inside App's LOCAL provider. Opening a team tab's
+// terminal card therefore mounted its ModalTerminal under the local session, and the modal's
+// `pty.create` (persistKey = the HOST's node id) created that id on this desktop's own core.
+//
+// The fix (F2b): each board mounts its card modal under `sessionForProject(<the card's project>)`
+// — keyed by the session id — and provides `OwningProjectContext` with the card's project, so the
+// modal's terminal (and everything else it asks `useSession()` for) talks to the core that owns the
+// node. A local project's modal still resolves to the local session, byte-identically.
+//
+// Plus the source pins for F2c (the create-time refusal in TerminalNode + ModalTerminal) and the
+// relay-ssh.ts header (F4): those components have no render harness (xterm + fit addon in jsdom).
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { CanvasNodeState, NodeTerminalApi, Project, ProjectKanban } from '@shared/types'
+import { KanbanView, type KanbanSession } from './KanbanView'
+import { GlobalKanbanView } from './GlobalKanbanView'
+import { useProjects } from '../../state/projects'
+import { useViewMode } from '../../state/viewMode'
+import {
+ bindProjectToSession,
+ createSession,
+ resetSessionsForTest,
+ SessionProvider,
+ setActiveSession,
+ type WorkspaceSession
+} from '../../session/session'
+
+/** What the probe CardModal saw at each render: the session it runs under and its owning project. */
+const probe = vi.hoisted(() => ({
+ seen: [] as Array<{ session: string; source: string; owner: string | null; projectId: string }>
+}))
+
+vi.mock('./CardModal', async () => {
+ const session = await import('../../session/session')
+ const owning = await import('../../session/owning-project')
+ return {
+ CardModal: ({ projectId }: { projectId: string }) => {
+ const s = session.useSession()
+ probe.seen.push({ session: s.id, source: s.source, owner: owning.useOwningProjectId(), projectId })
+ return null
+ }
+ }
+})
+vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
+
+const LOCAL_PROJECT = 'p-local'
+const TEAM_PROJECT = 'p-team'
+
+let root: Root | null = null
+let host: HTMLElement
+let local: WorkspaceSession
+let relay: WorkspaceSession
+
+const terminal = (id: string): CanvasNodeState =>
+ ({ id, kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 200, height: 200 }, title: id, color: '#fff', group: null }) as CanvasNodeState
+const project = (id: string, nodes: CanvasNodeState[], remote = false): Project =>
+ ({ id, name: id, color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes, ...(remote ? { remote: true } : {}) }) as unknown as Project
+const card = (id: string): KanbanSession =>
+ ({ id, title: id, color: '#fff', kind: 'terminal', spawn: {} }) as unknown as KanbanSession
+const board = (): ProjectKanban => ({ columns: [{ id: 'todo', title: 'To Do', color: '#888' }], assignments: [] }) as unknown as ProjectKanban
+
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ boardLog: { list: async () => [], onChanged: () => () => {} },
+ settings: { save: async () => {} }
+ }
+ probe.seen.length = 0
+ resetSessionsForTest()
+ local = createSession('local', window.nodeTerminal, 'This computer')
+ setActiveSession(local.id)
+ relay = createSession('relay', { boardLog: { list: async () => [], onChanged: () => () => {} } } as unknown as NodeTerminalApi, 'Team')
+ useProjects.setState({
+ projects: [project(LOCAL_PROJECT, [terminal('n-local')]), project(TEAM_PROJECT, [terminal('n-team')], true)],
+ activeProjectId: LOCAL_PROJECT
+ } as never)
+ bindProjectToSession(TEAM_PROJECT, relay.id)
+ useViewMode.setState({ requestedCardNodeId: null } as never)
+})
+afterEach(() => {
+ if (root) act(() => root!.unmount())
+ root = null
+ host?.remove()
+ document.body.innerHTML = ''
+ resetSessionsForTest()
+ vi.unstubAllGlobals()
+})
+
+/** Render under App's LOCAL provider — where both boards really live (outside Canvas's subtree). */
+function render(el: JSX.Element): void {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ act(() => root!.render(<SessionProvider session={local}>{el}</SessionProvider>))
+}
+const openCard = (nodeId: string): void => act(() => useViewMode.getState().requestCard(nodeId))
+const noop = (): void => {}
+
+function renderProjectBoard(projectId: string, nodeId: string): void {
+ useProjects.setState({ activeProjectId: projectId } as never)
+ render(
+ <KanbanView board={board()} sessions={[card(nodeId)]} onChange={noop} onOpenNode={noop}
+ onCreateNode={noop} onRenameNode={noop} onEditSticky={noop} onDeleteNode={noop}
+ onModalNodeChange={noop} onBrowserNav={noop} onSetIcon={noop} />
+ )
+}
+
+describe('the per-project board mounts its card modal under the card project\'s session', () => {
+ it('a team tab\'s card runs under its relay session, owned by the team project', () => {
+ renderProjectBoard(TEAM_PROJECT, 'n-team')
+ openCard('n-team')
+ expect(probe.seen.length).toBeGreaterThan(0)
+ expect(probe.seen.at(-1)).toEqual({ session: relay.id, source: 'relay', owner: TEAM_PROJECT, projectId: TEAM_PROJECT })
+ })
+
+ it('a local project\'s card still runs under the local session', () => {
+ renderProjectBoard(LOCAL_PROJECT, 'n-local')
+ openCard('n-local')
+ expect(probe.seen.at(-1)).toEqual({ session: 'local', source: 'local', owner: LOCAL_PROJECT, projectId: LOCAL_PROJECT })
+ })
+})
+
+describe('the Omni board mounts each lane\'s card modal under THAT lane\'s session', () => {
+ it('a team lane\'s card runs under the relay session even while a local project is active', () => {
+ render(<GlobalKanbanView />)
+ openCard('n-team')
+ expect(probe.seen.length).toBeGreaterThan(0)
+ expect(probe.seen.at(-1)).toEqual({ session: relay.id, source: 'relay', owner: TEAM_PROJECT, projectId: TEAM_PROJECT })
+ })
+
+ it('a local lane\'s card runs under the local session', () => {
+ useProjects.setState({ activeProjectId: TEAM_PROJECT } as never)
+ render(<GlobalKanbanView />)
+ openCard('n-local')
+ expect(probe.seen.at(-1)).toEqual({ session: 'local', source: 'local', owner: LOCAL_PROJECT, projectId: LOCAL_PROJECT })
+ })
+})
+
+// ── Source pins (F2c, F4): TerminalNode and ModalTerminal have no render harness ─────────────────
+const read = (rel: string): string => readFileSync(join(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')
+const REFUSAL =
+ '[this terminal belongs to a remote project that is not connected here — nothing was started on this machine]'
+
+describe('both terminals refuse to spawn locally for a remote project (F2c)', () => {
+ it('TerminalNode asks spawnBelongsElsewhere after the noSpawn return, before any SSH resolve or create', () => {
+ const src = read('../../nodes/TerminalNode.tsx')
+ expect(src).toContain('const owningProject = useOwningProjectId()')
+ expect(src).toContain('owningProjectRef.current = owningProject')
+ const noSpawn = src.indexOf('if (noSpawn) return')
+ const ask = src.indexOf('spawnBelongsElsewhere(', noSpawn)
+ const refusal = src.indexOf(REFUSAL, ask)
+ const resolve = src.indexOf('await resolveSshRemote(', noSpawn)
+ const create = src.indexOf('transport\n .create({', noSpawn)
+ expect(noSpawn).toBeGreaterThan(-1)
+ expect(ask).toBeGreaterThan(noSpawn)
+ expect(refusal).toBeGreaterThan(ask)
+ expect(resolve).toBeGreaterThan(refusal)
+ expect(create).toBeGreaterThan(resolve)
+ expect(src).toContain('ownerProjectId: sshProjectId ?? owningProjectRef.current ?? useProjects.getState().activeProjectId')
+ })
+
+ it('ModalTerminal asks spawnBelongsElsewhere before its SSH resolve and its create', () => {
+ const src = read('ModalTerminal.tsx')
+ expect(src).toContain('const owningProject = useOwningProjectId()')
+ expect(src).toContain('owningProjectRef.current = owningProject')
+ const ask = src.indexOf('spawnBelongsElsewhere(')
+ const refusal = src.indexOf(REFUSAL, ask)
+ const resolve = src.indexOf('await resolveSshRemote(', ask)
+ const create = src.indexOf('const res = await transport.create({', ask)
+ expect(ask).toBeGreaterThan(-1)
+ expect(refusal).toBeGreaterThan(ask)
+ expect(resolve).toBeGreaterThan(refusal)
+ expect(create).toBeGreaterThan(resolve)
+ // A non-dialing card's pane is owned by the CARD's project, not whichever is active.
+ expect(src).toContain('const owner = owningProjectRef.current')
+ expect(src).toContain(': (owner ?? useProjects.getState().activeProjectId)')
+ expect(src).toContain('ownerProjectId: projectId,')
+ })
+
+ it('ModalTerminal gates the SSH dial on session.source like TerminalNode\'s dialsSsh', () => {
+ const src = read('ModalTerminal.tsx')
+ expect(src).toContain("const dialsSsh = !!spawn.sshRemoteTmux && session.source !== 'relay'")
+ expect(src).toMatch(/dialsSsh && spawn\.ssh\n\s+\? await resolveSshRemote\(/)
+ expect(src).toContain('if (dialsSsh && !sshRemote) {')
+ // The relay host joins its own session with requireRemote; it has no master to dial.
+ expect(src).not.toMatch(/spawn\.sshRemoteTmux && spawn\.ssh\n\s+\? await resolveSshRemote\(/)
+ expect(src).not.toContain('if (spawn.sshRemoteTmux && !sshRemote) {')
+ expect(src).toContain('requireRemote: spawn.sshRemoteTmux')
+ })
+})
+
+describe('relay-ssh.ts no longer claims sshRemoteTmux survives for a shared project (F4)', () => {
+ it('says the host adopts it (flag dropped) and names what keeps its nodes off this core', () => {
+ const src = read('../../session/relay-ssh.ts')
+ expect(src).not.toContain('It keeps `requireRemote` on the create the tab sends to the HOST\'s core')
+ expect(src).toContain('localizeAdoptedNode')
+ expect(src).toContain('spawnBelongsElsewhere')
+ })
+})
diff --git a/src/renderer/nodes/DinoNode.tsx b/src/renderer/nodes/DinoNode.tsx
index cdd223d5b..efc5b87e7 100644
--- a/src/renderer/nodes/DinoNode.tsx
+++ b/src/renderer/nodes/DinoNode.tsx
@@ -30,9 +30,11 @@ export function DinoNode({ id, data, selected }: NodeProps<CanvasNode>) {
const hostRef = useRef<HTMLDivElement>(null)
const gameRef = useRef<ReturnType<typeof createDinoGame> | null>(null)
- // The active session's presence. DinoNode renders under Canvas's active-session provider, which is
- // KEYED on `session.id` (Canvas.tsx), so this node REMOUNTS on a session swap — the mount-time
- // `presence` capture below is therefore always the current session's, no ref needed.
+ // The active project's presence. DinoNode renders under the SessionProvider Canvas keys on the
+ // session of the project React Flow's STORE holds (`useFlowStoreOwner`, Canvas.tsx), so this node
+ // REMOUNTS on a session swap — once the store holds the incoming project, which by then is also the
+ // active one. The mount-time `presence` capture below is therefore the current session's, no ref
+ // needed.
const presence = useActiveSessionPresence()
// The peer (if any) broadcasting a live dino for THIS node, and our own id for the tiebreak.
// selectDino excludes self and already applies the lowest-clientId rule, so `peer` is the one
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index fc5e7f252..f3d0e3023 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -356,6 +356,7 @@ import { applyIconChoice } from '../lib/nodeIconChoice'
import { normalizeNodeIcon } from '@shared/node-icon'
import { connectHostAttachment } from '../lib/sshAttachments'
import { projectMayDialSsh } from '../session/relay-ssh'
+import { spawnBelongsElsewhere, useOwningProjectId } from '../session/owning-project'
import { waitForSshRemote } from '../lib/sshRemoteWait'
/** Which physical modifier the registry's abstract `Cmd` resolves to for the find-bar chord. */
@@ -1314,6 +1315,11 @@ export function TerminalNode({
// namespaces (pty, fs) go through it; app-global ones (clipboard, shell) stay on the global.
const session = useSession()
const { api } = session
+ // The project whose nodes this node's subtree renders (Canvas: the project React Flow's store
+ // holds). Read by the create path in the once-mounted lifecycle effect, so a ref.
+ const owningProject = useOwningProjectId()
+ const owningProjectRef = useRef(owningProject)
+ owningProjectRef.current = owningProject
// A hosted team tab whose role is below Editor (false everywhere else): no "Restart in folder" —
// it recycles the session, which the host refuses for them.
const hostedReadOnly = useHostedReadOnly(session.id)
@@ -1334,10 +1340,14 @@ export function TerminalNode({
live = false
}
}, [api])
- // The ACTIVE session's presence — where our focus/blur casts go. This node renders under Canvas's
- // active-session provider, so a relay tab reports focus over the relay core and a local tab hits
- // `defaultPresence` (byte-identical to before). Stable for the node's lifetime (a tab switch
- // unmounts the node), so capturing it in the once-mounted lifecycle effect below is safe, like `api`.
+ // The ACTIVE project's presence — where our focus/blur casts go. It follows the active project,
+ // not this node's provider: Canvas keys the node subtree's SessionProvider on the project React
+ // Flow's STORE holds (`useFlowStoreOwner`), which flips one commit after the active id. A node
+ // mounts once the store holds its project, and by then that project is the active one, so the
+ // value captured by the once-mounted lifecycle effect below is the presence of the core this node
+ // runs on: a relay tab reports focus over the relay core, a local tab hits `defaultPresence`
+ // (byte-identical to before). Render-time reads may briefly see the incoming project's presence
+ // while an outgoing node waits to unmount.
const presence = useActiveSessionPresence()
/**
* THIS node's agent-status store, for the memory levers that must not kill live work — resolved
@@ -3570,6 +3580,16 @@ export function TerminalNode({
// happily start a brand-new tmux session — resurrecting a terminal its owner deliberately
// killed, or reviving this node in our STALE cwd. The overlay explains the state instead.
if (noSpawn) return
+ // A node of a REMOTE project (a relay / hosted team tab) under a session that is not a relay
+ // session — this desktop's own core — would create the host's node id HERE. Canvas keys the
+ // subtree on the project React Flow's store holds, and an unbound remote tab resolves to the
+ // offline relay session, so this is the last line: start nothing, before any SSH resolve.
+ if (spawnBelongsElsewhere(useProjects.getState().getProject(owningProjectRef.current ?? ''), session.source)) {
+ term.write(
+ '\r\n\x1b[90m[this terminal belongs to a remote project that is not connected here — nothing was started on this machine]\x1b[0m\r\n'
+ )
+ return
+ }
// SSH-project terminal: the project's live ControlMaster controlPath is established by
// Canvas's active-project effect. On a cold app load child effects run before that parent
// connect, so wait for it (briefly) before spawning. In Phase 1 a node only exists in the
@@ -3630,10 +3650,11 @@ export function TerminalNode({
persistKey: id,
// The project that OWNS this node, for the runtime pane-ownership ledger (agent
// messaging, src/core/agents/pane-ownership.ts): the ssh project's own scope for a remote
- // node, else the active project whose canvas this node lives on. Recorded main-side ONLY
- // on a genuine fresh spawn, so a second project opening another's live node id cannot
- // claim it. Machine-local id, never the git-shared project.json id.
- ownerProjectId: sshProjectId ?? useProjects.getState().activeProjectId,
+ // node, else the project whose nodes this subtree renders (`OwningProjectContext` — not
+ // necessarily the active one during a switch), else the active project. Recorded
+ // main-side ONLY on a genuine fresh spawn, so a second project opening another's live
+ // node id cannot claim it. Machine-local id, never the git-shared project.json id.
+ ownerProjectId: sshProjectId ?? owningProjectRef.current ?? useProjects.getState().activeProjectId,
// Only orders the remote spawn queue: on-screen terminals attach before offscreen ones
// on a project switch (terminal/on-screen.ts, core/remote-ssh/pty-spawn-gate.ts).
onScreen: elementOnScreen(container),
diff --git a/src/renderer/session/owning-project.test.ts b/src/renderer/session/owning-project.test.ts
new file mode 100644
index 000000000..68df128de
--- /dev/null
+++ b/src/renderer/session/owning-project.test.ts
@@ -0,0 +1,28 @@
+import { describe, expect, it } from 'vitest'
+import { spawnBelongsElsewhere } from './owning-project'
+
+// The create-time half of bug F's defense (F2c): a node of a REMOTE project (a hosted team / relay
+// tab) that finds itself under a session which is not a relay session must start nothing — that
+// session is this desktop's own core, and the node id belongs to the host.
+describe('spawnBelongsElsewhere', () => {
+ it('a remote project under a non-relay session belongs elsewhere', () => {
+ expect(spawnBelongsElsewhere({ remote: true }, 'local')).toBe(true)
+ expect(spawnBelongsElsewhere({ remote: true }, 'server')).toBe(true)
+ })
+
+ it('a remote project under a relay session is where it belongs', () => {
+ expect(spawnBelongsElsewhere({ remote: true }, 'relay')).toBe(false)
+ })
+
+ it('a local project never belongs elsewhere, whatever the session', () => {
+ expect(spawnBelongsElsewhere({}, 'local')).toBe(false)
+ expect(spawnBelongsElsewhere({ remote: false }, 'local')).toBe(false)
+ expect(spawnBelongsElsewhere({}, 'relay')).toBe(false)
+ expect(spawnBelongsElsewhere({}, 'server')).toBe(false)
+ })
+
+ it('an unknown project is not evidence of anything', () => {
+ expect(spawnBelongsElsewhere(undefined, 'local')).toBe(false)
+ expect(spawnBelongsElsewhere(undefined, 'relay')).toBe(false)
+ })
+})
diff --git a/src/renderer/session/owning-project.ts b/src/renderer/session/owning-project.ts
index a5f41489a..170b79ca9 100644
--- a/src/renderer/session/owning-project.ts
+++ b/src/renderer/session/owning-project.ts
@@ -1,14 +1,17 @@
-import { createContext, useContext } from 'react'
-import type { SessionSource } from './session'
+import { createContext, createElement, useContext, type ReactNode } from 'react'
+import { SessionProvider, sessionForProject, type SessionSource } from './session'
/**
* The project whose nodes the surrounding subtree renders — set by Canvas around `<ReactFlow>`
- * (to the project React Flow's store holds, `useFlowStoreOwner`) and by a card modal around its
- * terminal. `null` = not known: outside any provider, or before React Flow has held a project.
+ * (to the project React Flow's store holds, `useFlowStoreOwner`) and by `ProjectSessionScope`
+ * around a surface that mounts a node outside the canvas (the kanban card modal, on both boards).
+ * `null` = not known: outside any provider, or before React Flow has held a project.
*
* It exists beside the SessionProvider because a session alone cannot say whether a node is in
- * the right place: a remote project with no live relay binding resolves to the LOCAL session, so a
- * terminal that asked only for its session would happily create its host-side id on this core.
+ * the right place. An unbound remote project resolves to the offline relay session, whose calls
+ * all reject — but a node of a remote project that ends up under a LOCAL session anyway (a provider
+ * keyed on the wrong project, a surface mounted outside any project's provider) would create its
+ * host-side id on this core. The terminal asks `spawnBelongsElsewhere` with this id before it spawns.
*/
export const OwningProjectContext = createContext<string | null>(null)
@@ -25,3 +28,22 @@ export function useOwningProjectId(): string | null {
export function spawnBelongsElsewhere(project: { remote?: boolean } | undefined, source: SessionSource): boolean {
return !!project?.remote && source !== 'relay'
}
+
+/**
+ * Mount `children` the way a node of `projectId` is mounted on the canvas: under THAT project's
+ * session (`sessionForProject` — the relay session for a bound team tab, the offline relay session
+ * for an unbound one, the local session for a local project), keyed by the session id so a session
+ * change remounts them, with `OwningProjectContext` set to the project. For a surface that renders a
+ * project's node outside Canvas's node subtree — the kanban boards live under App's LOCAL provider,
+ * so a card modal mounted there would otherwise attach a team tab's terminal to this desktop's core.
+ *
+ * The session is resolved at render (the registry is runtime, not reactive), like Canvas's.
+ */
+export function ProjectSessionScope({ projectId, children }: { projectId: string; children: ReactNode }) {
+ const session = sessionForProject(projectId)
+ return createElement(SessionProvider, {
+ session,
+ key: session.id,
+ children: createElement(OwningProjectContext.Provider, { value: projectId }, children)
+ })
+}
diff --git a/src/renderer/session/relay-ssh.ts b/src/renderer/session/relay-ssh.ts
index 0eca4c643..77b0f0bee 100644
--- a/src/renderer/session/relay-ssh.ts
+++ b/src/renderer/session/relay-ssh.ts
@@ -19,9 +19,18 @@ import { withoutCoreOrigin } from '@shared/node-exec'
* (`projectMayDialSsh`) — defence in depth: either half alone closes the hole.
*
* What survives:
- * - `sshRemoteTmux` on a node — a plain boolean. It keeps `requireRemote` on the create the tab
- * sends to the HOST's core, which then co-attaches when the host holds the session live and
- * refuses otherwise; it never creates a local session on the host under the node's identity.
+ * - `sshRemoteTmux` on a node — a plain boolean — but only on nodes that still CARRY it: the
+ * host's SSH-project nodes it is serving over the relay as they are. On such a node it keeps
+ * `requireRemote` on the create the tab sends to the HOST's core, which then co-attaches when
+ * the host holds the session live and refuses otherwise; it never creates a local session on
+ * the host under the node's identity. A project shared from SSH WITH A TEAM is different: the
+ * host ADOPTS it (`team bootstrap` → `localizeAdoptedNode` drops `sshRemoteTmux`/`ssh`/`sshFs`,
+ * correct for the host, which now runs those sessions itself), so its nodes reach the tab as
+ * plain terminals and nothing on the node says "remote". What keeps them off THIS core is the
+ * session keying — Canvas's node subtree and the card modal run under the project's relay
+ * session (an unbound one under the offline relay session) — and `spawnBelongsElsewhere`
+ * (session/owning-project.ts), which refuses a remote project's spawn under any other session.
+ * Do NOT re-stamp `sshRemoteTmux` onto those nodes: the host would refuse its own sessions.
* - `relaySsh` on the project — display-only strings for the tab's `SSH user@host` chip. It is not
* an `SshConnection` and nothing that dials reads it.
* - A plain `ssh <host>` node (`ssh` without `sshRemoteTmux`) keeps its connection: its create runs