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(session): an unbound remote tab resolves to an offline relay session

reviewd68ca4250bc3
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 9aa73950b..6c2642749 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -657,6 +657,7 @@ import {
useSession,
SessionProvider,
sessionForProject,
+ boundSessionForProject,
presenceForProject,
setActiveSession,
disposeSession,
@@ -1692,10 +1693,12 @@ export function Canvas() {
//
// Dispose by the project BINDING, not by iterating relayTabsRef: an INVOLUNTARY drop already
// removed the tab from relayTabsRef (it went offline) but KEPT the session bound, so only
- // `sessionForProject` still reaches it — iterating relayTabsRef alone would orphan the offline
- // session in the registry forever. `disposeSession` is idempotent: it runs the held teardowns for
- // a still-live tab, no-ops them for an already-offline one, and unbinds + drops the entry either
- // way. We also sweep any live relayTabsRef entry for the project so a dead connectionId can't linger.
+ // `boundSessionForProject` still reaches it — iterating relayTabsRef alone would orphan the offline
+ // session in the registry forever. (The live binding only: an UNBOUND remote tab resolves through
+ // `sessionForProject` to the offline relay sentinel, which owns nothing and is never disposed.)
+ // `disposeSession` is idempotent: it runs the held teardowns for a still-live tab, no-ops them for
+ // an already-offline one, and unbinds + drops the entry either way. We also sweep any live
+ // relayTabsRef entry for the project so a dead connectionId can't linger.
const disposeRelayTabForProject = useCallback((projectId: string) => {
// One of a hosted team's several tabs: dismiss just this one. The team's connection lives on
// for the others (and the joiner keeps reconnecting into one that is still open).
@@ -1706,15 +1709,15 @@ export function Canvas() {
}
// A hosted tab's team stops trying to come back into it, in any phase (R40). A no-op otherwise.
hostedJoinerRef.current?.tabClosed(projectId)
- const s = sessionForProject(projectId)
+ const s = boundSessionForProject(projectId)
for (const [connectionId, tab] of relayTabsRef.current) {
// By session too: a team's last tab may be one a share event opened after the mount. Never
// while the connection still serves other tabs (one closed earlier lingers in `projectIds`).
- const ours = tab.projectIds.includes(projectId) || (s.source === 'relay' && tab.sessionId === s.id)
+ const ours = tab.projectIds.includes(projectId) || (s?.source === 'relay' && tab.sessionId === s.id)
const othersBound = projectIdsBoundToSession(tab.sessionId).some((id) => id !== projectId)
if (ours && !othersBound) relayTabsRef.current.delete(connectionId)
}
- if (s.source === 'relay') {
+ if (s?.source === 'relay') {
disposeSession(s.id)
useHostedTeams.getState().forget(s.id) // a no-op for a Team Access relay tab
}
@@ -5628,9 +5631,10 @@ export function Canvas() {
.then((tab): HostedMountOutcome | null => {
relayTabsRef.current.set(connectionId, tab)
// The session's api, read ONCE while the mount's tab is surely bound to it: a share event
- // may close that tab later, and resolving through it then would answer the local session.
- const bound = sessionForProject(tab.projectId)
- const api = bound.id === tab.sessionId ? bound.api : null
+ // may close that tab later, and resolving through it then would answer no session at all.
+ // The live binding only — never the offline sentinel an unbound remote tab falls back to.
+ const bound = boundSessionForProject(tab.projectId)
+ const api = bound?.id === tab.sessionId ? bound.api : null
if (reconnectProjectId) {
// The fresh session is now bound to the tab (openRelayTab rebound the SAME project id),
// so it is finally safe to drop the stale offline session it replaced. Disposing only
@@ -5783,7 +5787,9 @@ export function Canvas() {
bookmarks: async () => (await window.nodeTerminal.relayHosted?.bookmarks()) ?? [],
removeBookmark: (hostId) => window.nodeTerminal.relayHosted.removeBookmark(hostId),
mount: (connectionId, req, hooks) => {
- const bound = req.reconnectProjectId ? sessionForProject(req.reconnectProjectId) : null
+ // The live binding only: the stale session a reconnect replaces is never the offline
+ // sentinel an unbound remote tab resolves to (it would be "disposed" after the rebind).
+ const bound = req.reconnectProjectId ? boundSessionForProject(req.reconnectProjectId) : null
return confirmAndMount(
connectionId,
req.label || 'Hosted team',
@@ -5863,8 +5869,9 @@ export function Canvas() {
// A hosted team's tab reconnects from its bookmark: no code to paste.
if (hostedJoinerRef.current?.reconnectTab(projectId)) return
const label = useProjects.getState().getProject(projectId)?.name ?? 'Remote host'
- const bound = sessionForProject(projectId)
- const staleSessionId = bound.source === 'relay' ? bound.id : undefined
+ // The live binding only (never the offline sentinel): an unbound tab has no stale session.
+ const bound = boundSessionForProject(projectId)
+ const staleSessionId = bound?.source === 'relay' ? bound.id : undefined
void reconnectRelayTab(projectId, {
promptForOffer: async () => {
const offer = await promptDialog({ message: "Paste the host's new pairing code:" })
diff --git a/src/renderer/canvas/hosted-team.source.test.ts b/src/renderer/canvas/hosted-team.source.test.ts
index 8b53ebba0..e3767c9f4 100644
--- a/src/renderer/canvas/hosted-team.source.test.ts
+++ b/src/renderer/canvas/hosted-team.source.test.ts
@@ -73,7 +73,7 @@ describe('hosted team glue in Canvas', () => {
it('share events follow the host live: keep the screen, reconcile the joiner from the store either way', () => {
const body = between('const mountRemoteMirror = useCallback(', 'const confirmAndMount = useCallback(')
// The api is read once, right after the mount; the event's load never re-resolves it through a tab.
- const capture = body.indexOf('const bound = sessionForProject(tab.projectId)')
+ const capture = body.indexOf('const bound = boundSessionForProject(tab.projectId)')
const listen = body.indexOf('api.hosted.onSharedChanged((p) => {')
expect(capture).toBeGreaterThan(-1)
expect(listen).toBeGreaterThan(capture)
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index f24ee7802..7aeaf8821 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -539,7 +539,19 @@ export function ModalTerminal({
requireRemote: spawn.sshRemoteTmux,
// Same local-login exemption as the canvas node (issue #1186).
...(isLocalOnSshCanvas(nodeId) ? { localOnSshCanvas: true } : {})
- })
+ }).catch((err: unknown): Error => (err instanceof Error ? err : new Error(String(err))))
+ // A create that REJECTS started nothing — the core could not be asked (a relay tab whose
+ // connection is gone, e.g. the offline relay session, answers every call with E_DISCONNECTED).
+ // Say so, like TerminalNode's spawn-error overlay, instead of a blank viewer and an unhandled
+ // rejection out of this effect.
+ if (res instanceof Error) {
+ if (!dead) {
+ // eslint-disable-next-line no-control-regex -- the message is written INTO the terminal
+ const why = res.message.replace(/[\x00-\x1f\x7f]/g, ' ')
+ term.write(`\r\n\x1b[90m[this terminal could not be started: ${why}]\x1b[0m\r\n`)
+ }
+ return
+ }
// Refused core-side (the master died inside our round-trip, or `ssh` is missing).
if (res.unavailable) {
const refusal = ptyRefusal(res.unavailable)
diff --git a/src/renderer/session/localSession.ts b/src/renderer/session/localSession.ts
index a87a44070..11e9eebb0 100644
--- a/src/renderer/session/localSession.ts
+++ b/src/renderer/session/localSession.ts
@@ -1,5 +1,7 @@
import { createSession, setActiveSession, type WorkspaceSession } from './session'
import { thisMachineCap } from '../lib/machineName'
+// Side effect: registers the offline relay session an unbound remote tab resolves to (never local).
+import './offline-relay-session'
/** The single local session: its api is the preload object by identity. Built once at boot.
*
diff --git a/src/renderer/session/offline-relay-session.test.ts b/src/renderer/session/offline-relay-session.test.ts
new file mode 100644
index 000000000..4cbbd191e
--- /dev/null
+++ b/src/renderer/session/offline-relay-session.test.ts
@@ -0,0 +1,485 @@
+// @vitest-environment jsdom
+//
+// Bug F, root cause F2a (report-F.md): a REMOTE project (a hosted team / relay tab) whose relay
+// binding is gone — the session was disposed (the last team tab closed), or the binding dropped —
+// resolved to the LOCAL session in `sessionForProject`. Its nodes stay mounted (the welcome-screen
+// bail-out keeps the previous array in React Flow), the provider key flips to 'local', and every
+// one of them remounts and creates its host-side node id on THIS desktop's core.
+//
+// The fix: such a project resolves to an OFFLINE relay session (`OFFLINE_RELAY_SESSION_ID`) whose
+// api is a relay api over a dead transport, so every core-bound call (pty.create first) REJECTS at
+// once and nothing reaches the local core. Lifecycle code that asks "which relay session is bound to
+// this tab?" asks `boundSessionForProject`, which never answers the sentinel.
+//
+// The ported scenarios run the node subtree through the REAL `useFlowStoreOwner` + `useNodesEpoch`
+// (Canvas's keying since Task 2) under a real React Flow, with a probe node that applies
+// TerminalNode's create rule (see flowStoreOwner.test.tsx for the full replica and its source pin).
+import { act, createElement, useEffect, useState } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { ReactFlow, ReactFlowProvider, type NodeProps } from '@xyflow/react'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { CanvasNodeState, NodeTerminalApi, Project, PtyCreateOptions } from '@shared/types'
+import { E_DISCONNECTED } from '../../shared/rpc'
+import { useProjects } from '../state/projects'
+import {
+ OFFLINE_RELAY_SESSION_ID,
+ activeSessionApi,
+ bindProjectToSession,
+ boundSessionForProject,
+ createSession,
+ disposeSession,
+ getActiveSession,
+ getSessionStores,
+ isOfflineRelaySession,
+ presenceForProject,
+ projectIdsBoundToSession,
+ resetSessionsForTest,
+ sessionCount,
+ sessionForProject,
+ SessionProvider,
+ setActiveSession,
+ setOfflineRelayApiFactory,
+ unbindProject,
+ useSession
+} from './session'
+import { deadRelayTransport, offlineRelayApi } from './offline-relay-session'
+import { sanitizeRelayProject } from './relay-ssh'
+import { localizeAdoptedNode } from '../../shared/adopt-cwd'
+import { LocalTransport } from '../terminal/local-transport'
+import { nodeStatesToFlow, type CanvasNode } from '../state/workspace'
+import { useNodesEpoch } from '../canvas/nodesEpoch'
+import { useFlowStoreOwner } from '../canvas/flowStoreOwner'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+// ── The field run's ids (2026-10-03) ─────────────────────────────────────────────────────────────
+const TEAM_ALPHA = 'project-musvmmle-8443e887' // the host's proj-alpha = the team tab's id
+const LOCAL_ONE = 'project-local-one'
+const AGENT = 'term-musuoygd-979507b8'
+const PLAIN = 'term-musur58h-4ab48dbe'
+const HOST_HOME = '/home/e2e'
+
+const sshServer = { host: 'h.example', user: 'e2e', port: 22 }
+/** The team tab's nodes: the desktop SSH project's nodes, adopted (localized) by the host and
+ * passed through the relay ingest — plain terminals, `sshRemoteTmux` gone. */
+function teamTabProject(): Project {
+ const hostNodes = [
+ { id: AGENT, kind: 'terminal', agentId: 'claude' },
+ { id: PLAIN, kind: 'terminal' }
+ ].map(
+ (n) =>
+ ({
+ ...n,
+ title: n.id,
+ color: '#888',
+ position: { x: 0, y: n.id === AGENT ? 0 : 400 },
+ size: { width: 600, height: 360 },
+ cwd: '~/proj-alpha',
+ ssh: sshServer,
+ sshRemoteTmux: true
+ }) as unknown as CanvasNodeState
+ )
+ const adopted = sanitizeRelayProject({
+ id: TEAM_ALPHA,
+ name: 'proj-alpha',
+ color: '#888',
+ cwd: `${HOST_HOME}/proj-alpha`,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: hostNodes.map((n) => localizeAdoptedNode(n, HOST_HOME))
+ } as unknown as Project)
+ // `openRelayTab` adopts the host's project with `remote: true` (relay-tab.ts).
+ return { ...adopted, remote: true }
+}
+
+function localProject(): Project {
+ return {
+ id: LOCAL_ONE,
+ name: 'local-one',
+ color: '#888',
+ cwd: '/root/work',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: []
+ } as unknown as Project
+}
+
+// ── Two cores ─────────────────────────────────────────────────────────────────────────────────────
+type Core = 'local' | 'host'
+type Create = PtyCreateOptions & { core: Core }
+let creates: Create[] = []
+/** Every probe mount: which session it ran under and how its create settled. */
+let outcomes: Array<{ session: string; id: string; result: 'created' | 'rejected' | 'refused'; code?: string }> = []
+function fakeApi(core: Core): NodeTerminalApi {
+ return {
+ core,
+ pty: {
+ create: vi.fn(async (o: PtyCreateOptions) => {
+ creates.push({ ...o, core })
+ return { sessionId: `${core}-${o.persistKey}`, fresh: true }
+ }),
+ kill: vi.fn()
+ }
+ } as unknown as NodeTerminalApi
+}
+
+let localApi: NodeTerminalApi
+let savedNodeTerminal: unknown
+
+// ── The probe: TerminalNode's create rule, with TerminalNode's catch (spawnError) ────────────────
+function ProbeTerminal({ id, data }: NodeProps<CanvasNode>) {
+ const session = useSession()
+ useEffect(() => {
+ const sshRemoteTmux = !!data.sshRemoteTmux
+ // `dialsSsh = sshRemoteTmux && session.source !== 'relay'` — no master exists in this test.
+ if (sshRemoteTmux && session.source !== 'relay') {
+ outcomes.push({ session: session.id, id, result: 'refused' })
+ return
+ }
+ new LocalTransport(session.api)
+ .create({
+ cols: 80,
+ rows: 24,
+ cwd: data.cwd as string | undefined,
+ persistKey: id,
+ agentId: data.agentId as string | undefined,
+ requireRemote: sshRemoteTmux
+ })
+ .then(
+ () => outcomes.push({ session: session.id, id, result: 'created' }),
+ (err: { code?: string }) => outcomes.push({ session: session.id, id, result: 'rejected', code: err?.code })
+ )
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- mount-once, like the real lifecycle effect
+ }, [])
+ return createElement('div', { style: { width: 600, height: 360 } })
+}
+const nodeTypes = { terminal: ProbeTerminal }
+
+/** Canvas, cut down to the lines that matter: the active-project load effect (with its
+ * welcome-screen bail-out), and the node subtree keyed on the project React Flow's STORE holds. */
+function CanvasReplica() {
+ const activeProjectId = useProjects((s) => s.activeProjectId)
+ const [nodes, setNodes] = useState<CanvasNode[]>([])
+ const { renderedProjectId, installEpoch } = useNodesEpoch(nodes)
+ const owner = useFlowStoreOwner(nodes, renderedProjectId)
+ const nodeSession = sessionForProject(owner ?? '')
+ useEffect(() => {
+ if (!activeProjectId) {
+ installEpoch(null)
+ return
+ }
+ const flow = nodeStatesToFlow(useProjects.getState().getProject(activeProjectId)?.nodes ?? [])
+ setNodes(flow)
+ installEpoch(activeProjectId, flow)
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [activeProjectId])
+ return createElement(SessionProvider, {
+ session: nodeSession,
+ key: nodeSession.id,
+ children: createElement(
+ 'div',
+ { style: { width: 1200, height: 900 } },
+ createElement(ReactFlow, { nodes, edges: [], nodeTypes })
+ )
+ })
+}
+
+let root: Root | null = null
+let host: HTMLDivElement | null = null
+const tree = () => createElement(ReactFlowProvider, null, createElement(CanvasReplica))
+async function mount(): Promise<void> {
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+ await act(async () => root!.render(tree()))
+ await settle()
+}
+async function rerender(): Promise<void> {
+ await act(async () => root!.render(tree()))
+ await settle()
+}
+async function settle(): Promise<void> {
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 0))
+ })
+}
+const teamIds = [AGENT, PLAIN]
+const localCreatesOfTeamNodes = (): Create[] =>
+ creates.filter((c) => c.core === 'local' && teamIds.includes(c.persistKey as string))
+
+const timeout = (ms: number) => new Promise<'timeout'>((r) => setTimeout(() => r('timeout'), ms))
+
+beforeEach(() => {
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe(): void {}
+ unobserve(): void {}
+ disconnect(): void {}
+ }
+ )
+ creates = []
+ outcomes = []
+ // The local session's api IS `window.nodeTerminal` in the app; the offline relay api spreads it
+ // (`...local`) for the app-global namespaces, exactly as a real relay tab's api does.
+ localApi = fakeApi('local')
+ savedNodeTerminal = (window as unknown as { nodeTerminal?: unknown }).nodeTerminal
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = localApi
+ resetSessionsForTest()
+ setActiveSession(createSession('local', localApi, 'This machine').id)
+ // Production registers the factory as a side effect of importing the module (localSession.ts
+ // imports it); re-register per test because test (g) unregisters it.
+ setOfflineRelayApiFactory(offlineRelayApi)
+ useProjects.setState({ projects: [teamTabProject(), localProject()], activeProjectId: TEAM_ALPHA })
+})
+
+afterEach(async () => {
+ await act(async () => root?.unmount())
+ root = null
+ host?.remove()
+ host = null
+ setOfflineRelayApiFactory(offlineRelayApi)
+ useProjects.setState({ projects: [], activeProjectId: '' })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = savedNodeTerminal
+ vi.unstubAllGlobals()
+})
+
+describe('deadRelayTransport', () => {
+ it('reports the connection closed synchronously on every send, stores no listener, never becomes ready', async () => {
+ const t = deadRelayTransport()
+ const closes = vi.fn()
+ t.onClose(closes)
+ t.onMessage(() => {
+ throw new Error('a dead transport delivers nothing')
+ })
+ t.send('{"t":"req","id":1}')
+ expect(closes).toHaveBeenCalledTimes(1)
+ t.send('{"t":"req","id":2}')
+ expect(closes).toHaveBeenCalledTimes(2)
+ await expect(t.ready()).rejects.toMatchObject({ code: E_DISCONNECTED })
+ })
+})
+
+describe('an unbound REMOTE project resolves to the offline relay session', () => {
+ it('(a) is relay-shaped, offline, the sentinel id, and never the local session', () => {
+ const s = sessionForProject(TEAM_ALPHA)
+ expect(s.source).toBe('relay')
+ expect(s.status).toBe('offline')
+ expect(s.id).toBe(OFFLINE_RELAY_SESSION_ID)
+ expect(s.label).toBe('Disconnected')
+ expect(isOfflineRelaySession(s)).toBe(true)
+ expect(s).not.toBe(sessionForProject(LOCAL_ONE))
+ expect(s.api).not.toBe(localApi)
+ // Created once per registry: every caller gets the same object (a stable provider value/key).
+ expect(sessionForProject(TEAM_ALPHA)).toBe(s)
+ })
+
+ it('(b) its pty.create REJECTS at once (never hangs) and the local core is never asked', async () => {
+ const api = sessionForProject(TEAM_ALPHA).api
+ const settled = await Promise.race([
+ api.pty.create({ cols: 80, rows: 24, persistKey: AGENT } as PtyCreateOptions).then(
+ () => 'resolved' as const,
+ (err: { code?: string }) => err
+ ),
+ timeout(200)
+ ])
+ expect(settled).not.toBe('timeout')
+ expect(settled).not.toBe('resolved')
+ expect(settled).toMatchObject({ code: E_DISCONNECTED })
+ // Through the same seam TerminalNode uses.
+ await expect(
+ new LocalTransport(api).create({ cols: 80, rows: 24, persistKey: PLAIN } as PtyCreateOptions)
+ ).rejects.toMatchObject({ code: E_DISCONNECTED })
+ expect(localApi.pty.create).not.toHaveBeenCalled()
+ })
+
+ it('(c) a LOCAL unbound project still resolves to the local session', () => {
+ const s = sessionForProject(LOCAL_ONE)
+ expect(s.id).toBe('local')
+ expect(s.api).toBe(localApi)
+ // So does an id the store does not know (a deleted project, '' on the welcome screen).
+ expect(sessionForProject('').id).toBe('local')
+ expect(sessionForProject('project-unknown').id).toBe('local')
+ })
+
+ it('(d) boundSessionForProject answers the live binding only — never the sentinel, never a fallback', () => {
+ expect(boundSessionForProject(TEAM_ALPHA)).toBeNull()
+ expect(boundSessionForProject(LOCAL_ONE)).toBeNull()
+ const relay = createSession('relay', fakeApi('host'), 'e2ehost')
+ bindProjectToSession(TEAM_ALPHA, relay.id)
+ expect(boundSessionForProject(TEAM_ALPHA)).toBe(relay)
+ expect(sessionForProject(TEAM_ALPHA)).toBe(relay)
+ // A stale binding (session disposed) is pruned exactly like sessionForProject prunes it.
+ disposeSession(relay.id)
+ expect(boundSessionForProject(TEAM_ALPHA)).toBeNull()
+ expect(projectIdsBoundToSession(relay.id)).toEqual([])
+ expect(sessionForProject(TEAM_ALPHA).id).toBe(OFFLINE_RELAY_SESSION_ID)
+ // A tab can never bind to the sentinel, so a binding can never name it.
+ expect(() => bindProjectToSession(TEAM_ALPHA, OFFLINE_RELAY_SESSION_ID)).toThrow()
+ })
+
+ it('(e) sessionCount() does not count the sentinel', () => {
+ expect(sessionForProject(TEAM_ALPHA).id).toBe(OFFLINE_RELAY_SESSION_ID)
+ expect(sessionCount()).toBe(1)
+ })
+
+ it('(f) disposeSession(OFFLINE_RELAY_SESSION_ID) is a no-op', () => {
+ const s = sessionForProject(TEAM_ALPHA)
+ disposeSession(OFFLINE_RELAY_SESSION_ID)
+ expect(sessionForProject(TEAM_ALPHA)).toBe(s)
+ expect(getActiveSession().id).toBe('local')
+ expect(sessionCount()).toBe(1)
+ })
+
+ it('(g) with no factory registered, the old local fallback stands', () => {
+ setOfflineRelayApiFactory(null)
+ expect(sessionForProject(TEAM_ALPHA).id).toBe('local')
+ setOfflineRelayApiFactory(offlineRelayApi)
+ expect(sessionForProject(TEAM_ALPHA).id).toBe(OFFLINE_RELAY_SESSION_ID)
+ })
+
+ it('answers its own stores and is accepted as the active session (Canvas activates sessionForProject(active).id)', () => {
+ const s = sessionForProject(TEAM_ALPHA)
+ const stores = getSessionStores(OFFLINE_RELAY_SESSION_ID)
+ // Its own stores — never the local session's (a dead core's status must not touch local unread).
+ expect(stores).not.toBe(getSessionStores('local'))
+ expect(stores.agentStatus).not.toBe(getSessionStores('local').agentStatus)
+ expect(stores.presence).not.toBe(getSessionStores('local').presence)
+ setActiveSession(s.id)
+ expect(getActiveSession()).toBe(s)
+ expect(activeSessionApi()).toBe(s.api)
+ // Dropping the factory while the sentinel is active falls back to local, never a dangling id.
+ setOfflineRelayApiFactory(null)
+ expect(getActiveSession().id).toBe('local')
+ })
+
+ it('presenceForProject resolves exactly as sessionForProject does (offline presence, never local)', () => {
+ expect(presenceForProject(TEAM_ALPHA)).toBe(getSessionStores(OFFLINE_RELAY_SESSION_ID).presence)
+ expect(presenceForProject(LOCAL_ONE)).toBe(getSessionStores('local').presence)
+ const relay = createSession('relay', fakeApi('host'), 'e2ehost')
+ bindProjectToSession(TEAM_ALPHA, relay.id)
+ expect(presenceForProject(TEAM_ALPHA)).toBe(getSessionStores(relay.id).presence)
+ })
+
+ it('is recreated after resetSessionsForTest (once per registry)', () => {
+ const first = sessionForProject(TEAM_ALPHA)
+ resetSessionsForTest()
+ createSession('local', localApi, 'This machine')
+ const second = sessionForProject(TEAM_ALPHA)
+ expect(second.id).toBe(OFFLINE_RELAY_SESSION_ID)
+ expect(second).not.toBe(first)
+ })
+})
+
+describe('ported repro scenarios: a team tab without a live binding creates nothing on the local core', () => {
+ it('a team tab that loses its binding while its nodes are mounted', async () => {
+ const relay = createSession('relay', fakeApi('host'), 'e2ehost')
+ bindProjectToSession(TEAM_ALPHA, relay.id)
+ await mount()
+ // Healthy first: both team nodes were created on the HOST.
+ expect(creates.filter((c) => c.core === 'host').map((c) => c.persistKey).sort()).toEqual(teamIds.slice().sort())
+ creates = []
+ outcomes = []
+ await act(async () => unbindProject(TEAM_ALPHA))
+ await rerender()
+ expect(localCreatesOfTeamNodes()).toEqual([])
+ // The remount ran under the offline sentinel and its creates were refused by the dead transport.
+ expect(outcomes.map((o) => [o.session, o.result]).sort()).toEqual([
+ [OFFLINE_RELAY_SESSION_ID, 'rejected'],
+ [OFFLINE_RELAY_SESSION_ID, 'rejected']
+ ])
+ expect(outcomes.every((o) => o.code === E_DISCONNECTED)).toBe(true)
+ expect(localApi.pty.create).not.toHaveBeenCalled()
+ })
+
+ it('closing the LAST team tab (welcome screen) leaves its nodes mounted under the offline sentinel', async () => {
+ useProjects.setState({ projects: [teamTabProject()], activeProjectId: TEAM_ALPHA })
+ const relay = createSession('relay', fakeApi('host'), 'e2ehost')
+ bindProjectToSession(TEAM_ALPHA, relay.id)
+ await mount()
+ creates = []
+ outcomes = []
+ // `performCloseProject` → `disposeRelayTabForProject` (last tab: disposeSession) → `closeProject`
+ // → activeProjectId '' → the load effect bails out and leaves the team's nodes mounted.
+ await act(async () => disposeSession(relay.id))
+ await act(async () => {
+ useProjects.getState().closeProject(TEAM_ALPHA)
+ })
+ await settle()
+ expect(useProjects.getState().activeProjectId).toBe('')
+ expect(localCreatesOfTeamNodes()).toEqual([])
+ expect(outcomes.map((o) => o.session)).toEqual([OFFLINE_RELAY_SESSION_ID, OFFLINE_RELAY_SESSION_ID])
+ expect(outcomes.every((o) => o.result === 'rejected')).toBe(true)
+ expect(localApi.pty.create).not.toHaveBeenCalled()
+ })
+
+ it('a local project is untouched: its nodes keep the local session', async () => {
+ useProjects.setState({
+ projects: [
+ teamTabProject(),
+ { ...localProject(), nodes: [{ id: 'term-local-1', kind: 'terminal', title: 't', color: '#888', position: { x: 0, y: 0 }, size: { width: 600, height: 360 }, cwd: '/root/work' } as unknown as CanvasNodeState] }
+ ],
+ activeProjectId: LOCAL_ONE
+ })
+ await mount()
+ expect(outcomes).toEqual([{ session: 'local', id: 'term-local-1', result: 'created' }])
+ expect(creates.map((c) => [c.core, c.persistKey])).toEqual([['local', 'term-local-1']])
+ })
+})
+
+describe('source pins', () => {
+ const read = (rel: string): string => readFileSync(join(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')
+
+ it('localSession.ts imports the offline relay session module, so production always registers the factory', () => {
+ expect(read('localSession.ts')).toMatch(/^import '\.\/offline-relay-session'$/m)
+ })
+
+ // Canvas's relay LIFECYCLE sites ask "which relay session is bound to this tab?" — dispose it,
+ // read its api once, hand it over as the stale session a reconnect replaces. `sessionForProject`
+ // now answers the offline sentinel for an unbound remote tab, which must never be disposed or
+ // passed as `staleSessionId`, so each of these asks `boundSessionForProject` (no fallback).
+ // Note `boundSessionForProject(` does not contain the lowercase `sessionForProject(`.
+ it('Canvas relay lifecycle sites ask boundSessionForProject, never sessionForProject', () => {
+ const canvas = read('../canvas/Canvas.tsx')
+ const between = (start: string, end: string): string => {
+ const a = canvas.indexOf(start)
+ const b = canvas.indexOf(end, a + start.length)
+ expect(a, start).toBeGreaterThan(-1)
+ expect(b, end).toBeGreaterThan(a)
+ return canvas.slice(a, b)
+ }
+ const sites = [
+ between('const disposeRelayTabForProject = useCallback(', '}, [teamTabs])'),
+ between('.then((tab): HostedMountOutcome | null => {', 'if (reconnectProjectId) {'),
+ between('mount: (connectionId, req, hooks) => {', 'return confirmAndMount('),
+ between('const reconnectRelay = useCallback(', 'void reconnectRelayTab(projectId, {')
+ ]
+ for (const body of sites) {
+ expect(body).toContain('boundSessionForProject(')
+ expect(body).not.toContain('sessionForProject(')
+ }
+ })
+
+ it('offline-relay-session.ts registers the factory at module load', () => {
+ expect(read('offline-relay-session.ts')).toMatch(/^setOfflineRelayApiFactory\(offlineRelayApi\)$/m)
+ })
+
+ // ModalTerminal has no render harness (an xterm + fit addon in jsdom). Its create rejection —
+ // what the offline session answers once the card modal runs under its project's session — must
+ // land on the terminal as a refusal BEFORE anything reads the result, never as a blank viewer and
+ // an unhandled rejection out of the effect. (TerminalNode's `.catch` → spawnError overlay is the
+ // canvas twin; the ported scenarios above exercise the rejection itself.)
+ it('ModalTerminal turns a rejected create into a written refusal before reading the result', () => {
+ const src = read('../components/kanban/ModalTerminal.tsx')
+ const create = src.indexOf('const res = await transport.create({')
+ const caught = src.indexOf('}).catch((err: unknown): Error =>', create)
+ const guard = src.indexOf('if (res instanceof Error) {', caught)
+ const written = src.indexOf('[this terminal could not be started: ${why}]', guard)
+ const firstRead = src.indexOf('res.unavailable', create)
+ expect(create).toBeGreaterThan(-1)
+ expect(caught).toBeGreaterThan(create)
+ expect(guard).toBeGreaterThan(caught)
+ expect(written).toBeGreaterThan(guard)
+ expect(firstRead).toBeGreaterThan(written)
+ })
+})
diff --git a/src/renderer/session/offline-relay-session.ts b/src/renderer/session/offline-relay-session.ts
new file mode 100644
index 000000000..7bf640181
--- /dev/null
+++ b/src/renderer/session/offline-relay-session.ts
@@ -0,0 +1,43 @@
+import type { NodeTerminalApi } from '@shared/types'
+import { E_DISCONNECTED } from '../../shared/rpc'
+import { buildRelayApi } from '../bridge/relay-api'
+import type { FrameTransport } from '../bridge/frame-transport'
+import { OFFLINE_RELAY_SESSION_ID, setOfflineRelayApiFactory } from './session'
+
+/**
+ * A relay carrier that is already gone. `send` reports the connection closed SYNCHRONOUSLY, every
+ * time: `RpcClient.request` registers its pending entry before it sends, so the close fails that
+ * request at once with `E_DISCONNECTED` instead of leaving it pending forever (a promise that never
+ * settles strands every caller's cleanup — see `RpcClient.failPending`). Casts go nowhere, nothing
+ * ever arrives (`onMessage` keeps no listener), and `ready()` rejects.
+ */
+export function deadRelayTransport(): FrameTransport {
+ const closeCbs: Array<() => void> = []
+ return {
+ send: () => {
+ for (const cb of closeCbs) cb()
+ },
+ onMessage: () => {},
+ onClose: (cb) => {
+ closeCbs.push(cb)
+ },
+ // A fresh rejection per call, so constructing the transport leaves no unhandled rejection.
+ ready: () =>
+ Promise.reject(
+ Object.assign(new Error('This tab is not connected to its host.'), { code: E_DISCONNECTED })
+ )
+ }
+}
+
+/**
+ * The api of the offline relay session an unbound REMOTE project resolves to (session.ts,
+ * `sessionForProject`). It is a real relay api — the same core-bound / local split a live relay tab
+ * has — over a dead carrier, so everything core-bound (pty, fs, git, workspace, files, …) rejects and
+ * nothing a node mounts can reach THIS machine's core under a node id that lives on another machine.
+ * Built here rather than in session.ts because relay-api imports session.ts.
+ */
+export function offlineRelayApi(): NodeTerminalApi {
+ return buildRelayApi(OFFLINE_RELAY_SESSION_ID, deadRelayTransport()).api
+}
+
+setOfflineRelayApiFactory(offlineRelayApi)
diff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.ts
index 2dcd26cc2..5abbb69ad 100644
--- a/src/renderer/session/relay-tab.test.ts
+++ b/src/renderer/session/relay-tab.test.ts
@@ -15,7 +15,11 @@ import {
resetSessionsForTest,
projectIdsBoundToSession,
bindProjectToSession,
+ boundSessionForProject,
+ setOfflineRelayApiFactory,
+ OFFLINE_RELAY_SESSION_ID,
} from './session'
+import { useProjects } from '../state/projects'
import { LocalTransport } from '../terminal/local-transport'
import { planActiveProjectDials } from '../lib/sshAttachments'
import type { NodeTerminalApi, Project, Workspace } from '@shared/types'
@@ -113,10 +117,40 @@ describe('openRelayTab (connect → tab → mount)', () => {
expect(close).not.toHaveBeenCalled()
tab.dispose()
expect(close).toHaveBeenCalledTimes(1)
- expect(sessionForProject(tab.projectId).source).toBe('local') // unbound → local
+ // Unbound → local, because THIS test's projects store does not hold 'proj-1' (addProject is a
+ // spy), so nothing says the tab is remote. A remote tab resolves to the offline relay session
+ // instead — the next test.
+ expect(useProjects.getState().getProject(tab.projectId)).toBeUndefined()
+ expect(sessionForProject(tab.projectId).source).toBe('local')
expect(sessionCount()).toBe(1) // only local remains
})
+ it('a disposed tab whose project is REMOTE in the store resolves to the offline relay session, never local', async () => {
+ const { api } = fakeBridgedApi()
+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close: vi.fn() }
+ const { deps } = makeDeps({ handle })
+ // The relay ingest adopts the host's project with `remote: true` (openRelayTab's adopt path).
+ useProjects.setState({ projects: [{ id: 'proj-1', name: "Ayşe's Mac", remote: true } as unknown as Project] })
+ const offlineApi = { marker: 'offline-relay' } as unknown as NodeTerminalApi
+ setOfflineRelayApiFactory(() => offlineApi)
+ try {
+ const tab = await openRelayTab('conn-1', "Ayşe's Mac", deps)
+ expect(boundSessionForProject(tab.projectId)?.id).toBe(tab.sessionId)
+ tab.dispose()
+ const s = sessionForProject(tab.projectId)
+ expect(s.id).toBe(OFFLINE_RELAY_SESSION_ID)
+ expect(s.source).toBe('relay')
+ expect(s.status).toBe('offline')
+ expect(s.api).toBe(offlineApi)
+ // The lifecycle question — "which relay session is bound to this tab?" — has no answer now.
+ expect(boundSessionForProject(tab.projectId)).toBeNull()
+ expect(sessionCount()).toBe(1) // the sentinel is not a registered session
+ } finally {
+ setOfflineRelayApiFactory(null)
+ useProjects.setState({ projects: [], activeProjectId: '' })
+ }
+ })
+
it('populates the tab by ADOPTING the host\'s scoped project (nodes intact, remote:true)', async () => {
const hostProject = {
id: 'host-proj',
diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.ts
index a1e658c43..e1a13dd92 100644
--- a/src/renderer/session/session.ts
+++ b/src/renderer/session/session.ts
@@ -40,6 +40,17 @@ const PROJECT_BINDINGS = new Map<string, string>()
let activeId: string | null = null
let remoteSeq = 0
+/** The id of the OFFLINE relay session: what a REMOTE project (a relay / hosted team tab) with no
+ * live binding resolves to — its session was disposed (the last team tab closed) or its binding
+ * dropped. Never a registered session: it is not in `SESSIONS`, never counted, never bound, never
+ * disposed. No real session can carry it (relay ids are `relay-<n>`). */
+export const OFFLINE_RELAY_SESSION_ID = 'relay-offline'
+/** Builds the offline session's api. Injected (offline-relay-session.ts, imported by localSession.ts)
+ * because the api is a relay api, and bridge/relay-api.ts imports this module. */
+let offlineApiFactory: (() => NodeTerminalApi) | null = null
+/** The offline session, built lazily on first use, once per registry. */
+let offline: Entry | null = null
+
/** The per-session store instances. `createPresenceSession` is memoized BY API IDENTITY, so the
* one-store-per-core guarantee needs no source branch here: the local session's api is
* `window.nodeTerminal`, which resolves to the module's default presence instance — the exact
@@ -95,10 +106,13 @@ function runTeardowns(e: Entry): void {
}
/** Tear a session down (obligation 1 — the missing disposal path a remote tab needs on disconnect):
- * run every held teardown EXACTLY ONCE, drop the entry, and unbind its projects so their (now
- * dead) tabs resolve back to the local session. Idempotent and no-op for an unknown id — a double
- * close, or a revoke racing a socket drop, must touch nothing the second time. */
+ * run every held teardown EXACTLY ONCE, drop the entry, and unbind its projects. Their (now dead)
+ * tabs then resolve through `sessionForProject`'s fallback: the OFFLINE relay session for a remote
+ * project, the local session for any other. Idempotent and no-op for an unknown id — a double
+ * close, or a revoke racing a socket drop, must touch nothing the second time — and for the offline
+ * session, which is not registered and owns nothing to tear down. */
export function disposeSession(sessionId: string): void {
+ if (sessionId === OFFLINE_RELAY_SESSION_ID) return
const e = SESSIONS.get(sessionId)
if (!e || e.disposed) return
e.disposed = true
@@ -129,28 +143,79 @@ export function takeSessionOffline(sessionId: string): void {
e.session.status = 'offline'
}
-/** Test-only: clears the registry so each test starts with no sessions. */
+/** Test-only: clears the registry so each test starts with no sessions. The offline-session
+ * FACTORY survives (it is registered once, at module load); the offline session itself is dropped
+ * and rebuilt on next use. */
export function resetSessionsForTest(): void {
SESSIONS.clear()
PROJECT_BINDINGS.clear()
activeId = null
remoteSeq = 0
+ offline = null
+}
+
+/** Register (or, with `null`, drop) the builder of the offline relay session's api. Production
+ * registers it once, as a side effect of importing offline-relay-session.ts (localSession.ts does).
+ * With no factory an unbound remote project falls back to the local session as it did before the
+ * offline session existed — which is what a bare unit test of this module gets. A change drops the
+ * offline session built from the previous factory (and hands `active` back to local if it was it). */
+export function setOfflineRelayApiFactory(factory: (() => NodeTerminalApi) | null): void {
+ offlineApiFactory = factory
+ offline = null
+ if (activeId === OFFLINE_RELAY_SESSION_ID) activeId = SESSIONS.has('local') ? 'local' : null
+}
+
+/** The offline relay session's entry, built on first use: `source 'relay'` (so every relay gate in
+ * the renderer treats the tab as the remote tab it is), `status 'offline'`, its OWN stores (a dead
+ * core's status must never touch the local user's persisted unread/session table). `null` when no
+ * factory is registered. */
+function offlineEntry(): Entry | null {
+ if (!offlineApiFactory) return null
+ if (!offline) {
+ const api = offlineApiFactory()
+ const session: WorkspaceSession = {
+ id: OFFLINE_RELAY_SESSION_ID,
+ source: 'relay',
+ label: 'Disconnected',
+ api,
+ status: 'offline'
+ }
+ offline = { session, stores: buildStores(api), teardowns: [], disposed: false }
+ }
+ return offline
}
-export function getSessionStores(sessionId: string): SessionStores {
+/** A registered session's entry, or the offline session's for its id. For the accessors that must
+ * accept whatever `sessionForProject` returned (stores, the active session) — never for binding,
+ * teardown or status, which belong to registered sessions only. */
+function entryFor(sessionId: string): Entry | undefined {
const e = SESSIONS.get(sessionId)
+ if (e) return e
+ return sessionId === OFFLINE_RELAY_SESSION_ID ? (offlineEntry() ?? undefined) : undefined
+}
+
+/** True for the offline relay session (see `OFFLINE_RELAY_SESSION_ID`). */
+export function isOfflineRelaySession(s: WorkspaceSession): boolean {
+ return s.id === OFFLINE_RELAY_SESSION_ID
+}
+
+export function getSessionStores(sessionId: string): SessionStores {
+ const e = entryFor(sessionId)
if (!e) throw new Error(`[session] no session ${sessionId}`)
return e.stores
}
+/** Accepts the offline session too: Canvas activates `sessionForProject(activeProjectId).id`, which
+ * for an unbound remote tab is the offline session. */
export function setActiveSession(sessionId: string): void {
- if (!SESSIONS.has(sessionId)) throw new Error(`[session] no session ${sessionId}`)
+ if (!entryFor(sessionId)) throw new Error(`[session] no session ${sessionId}`)
activeId = sessionId
}
export function getActiveSession(): WorkspaceSession {
- if (!activeId) throw new Error('[session] no active session')
- return SESSIONS.get(activeId)!.session
+ const e = activeId ? entryFor(activeId) : undefined
+ if (!e) throw new Error('[session] no active session')
+ return e.session
}
export function activeSessionApi(): NodeTerminalApi {
@@ -158,7 +223,8 @@ export function activeSessionApi(): NodeTerminalApi {
}
/** How many sessions are registered. `1` for a solo user today — UI affordances that only make
- * sense with multiple cores (the tab session label) gate on `> 1` so the solo UI is unchanged. */
+ * sense with multiple cores (the tab session label) gate on `> 1` so the solo UI is unchanged.
+ * The offline relay session is not registered and never counted. */
export function sessionCount(): number {
return SESSIONS.size
}
@@ -181,27 +247,52 @@ export function projectIdsBoundToSession(sessionId: string): string[] {
return [...PROJECT_BINDINGS].filter(([, sid]) => sid === sessionId).map(([projectId]) => projectId)
}
-/** The local session (the fallback every unbound tab resolves to), or the active one if — in a
- * node-environment test — no 'local' session was created. */
+/** The local session (the fallback every unbound LOCAL tab resolves to), or the active one if — in
+ * a node-environment test — no 'local' session was created. */
function localOrActiveSession(): WorkspaceSession {
const local = SESSIONS.get('local')
return local ? local.session : getActiveSession()
}
+/** The LIVE session bound to a project, or `null` — no fallback of any kind. This is the question
+ * relay lifecycle code asks ("which relay session is bound to this tab?": dispose it, reconnect
+ * it, hand its id over as the stale one), and it must never be answered by the offline session or
+ * the local one. A binding whose session was disposed is pruned (as `sessionForProject` prunes it). */
+export function boundSessionForProject(projectId: string): WorkspaceSession | null {
+ const boundId = PROJECT_BINDINGS.get(projectId)
+ if (!boundId) return null
+ const e = SESSIONS.get(boundId)
+ if (e) return e.session
+ PROJECT_BINDINGS.delete(projectId) // stale binding (session disposed)
+ return null
+}
+
/** Which session a project belongs to. Runtime-only — NEVER persisted (workspace.json /
* project.json are shared across machines; a session id is meaningless off this machine — see
* the toWorkspace tripwire in state/projects.test.ts). A remote tab resolves to its BOUND session;
* every other (local) tab resolves to the local session — by binding, NOT by which tab is active,
- * so a focused remote tab never makes a background local tab resolve remote. A binding whose
- * session was disposed is pruned and falls back to local. */
+ * so a focused remote tab never makes a background local tab resolve remote.
+ *
+ * A REMOTE project (`remote` in the projects store: a relay / hosted team tab) with no live binding
+ * — its session was disposed (the last team tab closed) or its binding dropped — resolves to the
+ * OFFLINE relay session, never the local one: its node ids live on another machine, and a node
+ * still mounted under the local session would create them on this desktop's core (bug F). Every
+ * core-bound call on the offline session rejects. A stale binding is pruned. An id the store does
+ * not know (a deleted project, '' on the welcome screen) is not evidence of anything remote and
+ * resolves local, as does a remote project when no offline factory is registered. */
export function sessionForProject(projectId: string): WorkspaceSession {
- const boundId = PROJECT_BINDINGS.get(projectId)
- if (boundId) {
- const e = SESSIONS.get(boundId)
- if (e) return e.session
- PROJECT_BINDINGS.delete(projectId) // stale binding (session disposed) → resolve local
- }
- return localOrActiveSession()
+ const bound = boundSessionForProject(projectId)
+ if (bound) return bound
+ const off = offlineForUnboundRemote(projectId)
+ return off ? off.session : localOrActiveSession()
+}
+
+/** The offline session's entry when `projectId` is a REMOTE project of the projects store — the
+ * one rule `sessionForProject` and `presenceForProject` share. The caller has already found no
+ * live binding. `null` for any other id, or when no offline factory is registered. */
+function offlineForUnboundRemote(projectId: string): Entry | null {
+ if (!projectId || !useProjects.getState().getProject(projectId)?.remote) return null
+ return offlineEntry()
}
/** The projects bound to a live session whose api IS `api`, i.e. the tabs one relay connection
@@ -247,7 +338,7 @@ export function useSessionStores(): SessionStores {
* static `state/presence` imports use), so a local tab is byte-identical. Never throws. */
function presenceForSession(sessionId: string | null): PresenceSession {
if (sessionId) {
- const e = SESSIONS.get(sessionId)
+ const e = entryFor(sessionId)
if (e) return e.stores.presence
}
const local = SESSIONS.get('local')
@@ -255,38 +346,44 @@ function presenceForSession(sessionId: string | null): PresenceSession {
}
/** The presence store for the session a project belongs to — the provider-INDEPENDENT resolution
- * the active-session presence hook is built on. Runs through `sessionForProject` (a relay tab →
- * its bound session, every local tab → the local session), so a local tab yields `defaultPresence`
- * (byte-identical to the historical `state/presence` default the components read today). Exported
- * for unit tests — the hook itself needs a React tree. Allocation-free; never throws in render. */
+ * the active-session presence hook is built on. Resolves exactly as `sessionForProject` does (a
+ * relay tab → its bound session, an unbound REMOTE tab → the offline relay session, every other
+ * tab → the local session), so a local tab yields `defaultPresence` (byte-identical to the
+ * historical `state/presence` default the components read today). Exported for unit tests — the
+ * hook itself needs a React tree. Allocation-free; never throws in render. */
export function presenceForProject(projectId: string): PresenceSession {
- // Mirror `sessionForProject`'s resolution (bound → its session; stale binding pruned; unbound →
- // LOCAL, never the merely-active), but resolve to the presence store and NEVER throw in render:
- // an empty/local-less registry (a node-env test) falls back to `defaultPresence`.
- const boundId = PROJECT_BINDINGS.get(projectId)
- if (boundId) {
- const e = SESSIONS.get(boundId)
- if (e) return e.stores.presence
- PROJECT_BINDINGS.delete(projectId) // stale binding (session disposed) → resolve local
- }
+ // Mirror `sessionForProject`'s resolution (bound → its session; stale binding pruned; unbound
+ // remote → the offline session; unbound → LOCAL, never the merely-active), but resolve to the
+ // presence store and NEVER throw in render: an empty/local-less registry (a node-env test) falls
+ // back to `defaultPresence`.
+ const bound = boundSessionForProject(projectId)
+ if (bound) return presenceForSession(bound.id)
+ const off = offlineForUnboundRemote(projectId)
+ if (off) return off.stores.presence
return presenceForSession(null) // unbound → the local session's presence (defaultPresence in-app)
}
-/** The ACTIVE session's presence store. Resolves the active session REACTIVELY from the projects
- * store — NOT from the `SessionProvider` context — so it yields the identical session Canvas's
- * provider is keyed on (`sessionForProject(activeProjectId)`) whether the caller renders inside
- * that provider (`PresenceLayer`, `PresenceChips`) or outside it (`Facepile`, `PresenceNamePrompt`),
- * and re-renders on a tab switch (activeProjectId changes). A local tab yields `defaultPresence`;
- * a relay tab yields the relay session's presence. */
+/** The ACTIVE project's presence store (`presenceForProject(activeProjectId)`), resolved
+ * REACTIVELY from the projects store — NOT from the `SessionProvider` context — so callers inside
+ * Canvas's tree (`PresenceLayer`, `PresenceChips`) and outside it (`Facepile`, `PresenceNamePrompt`)
+ * agree, and re-render on a tab switch (activeProjectId changes). A local tab yields
+ * `defaultPresence`; a relay tab yields its relay session's presence; an unbound remote tab the
+ * offline relay session's (it reaches no core).
+ *
+ * This is NOT the session Canvas keys its node subtree on: that follows the project whose nodes
+ * React Flow's store holds (`useFlowStoreOwner`), which during a project switch is still the
+ * OUTGOING project for a commit. A node that must act on its own core reads `useSession()`. */
export function useActiveSessionPresence(): PresenceSession {
const activeProjectId = useProjects((s) => s.activeProjectId)
return presenceForProject(activeProjectId ?? '')
}
-/** The ACTIVE session's core API — where the cursor/chat casts go — resolved provider-independently
- * from the projects store, matching `useActiveSessionPresence` session-for-session (both go through
- * `sessionForProject(activeProjectId)`, and presence is keyed by that session's api identity). A
- * local tab yields `window.nodeTerminal`; a relay tab yields the relay session's api. */
+/** The ACTIVE project's core API — where the cursor/chat casts go — resolved provider-independently
+ * from the projects store (`sessionForProject(activeProjectId)`), matching `useActiveSessionPresence`
+ * session-for-session (presence is keyed by that session's api identity). A local tab yields
+ * `window.nodeTerminal`; a relay tab yields the relay session's api; an unbound remote tab the
+ * offline relay session's, whose casts go nowhere. Like the presence hook, this follows the ACTIVE
+ * project, not the project the node subtree belongs to (`useSession()` — see above). */
export function useActiveSessionApi(): NodeTerminalApi {
const activeProjectId = useProjects((s) => s.activeProjectId)
return sessionForProject(activeProjectId ?? '').api