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
feat(relay): remote session as a project tab (Stage 4 Task 6)
enes29e80e761c0b
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex f4437a3b4..19e5533e2 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -83,7 +83,6 @@ import { Facepile } from '../components/Facepile'import { PresenceNamePrompt } from '../components/PresenceNamePrompt'import { connectPresence, reportProject, usePresence } from '../state/presence'import { nodeTravel, projectTravel } from '../lib/presenceTravel'-import { RemoteSessionView } from './RemoteSessionView'import { RemoteAccessDialog } from '../components/RemoteAccessDialog'import { SshProjectDialog } from '../components/SshProjectDialog'import { transport } from '../terminal/local-transport'@@ -132,7 +131,8 @@ import {import { relativeTime } from '../lib/relativeTime'import { AgentIcon } from '../lib/agentIcons'import { branchClaudeSession } from '../lib/claudeBranch'-import { useSession } from '../session/session'+import { useSession, SessionProvider, sessionForProject, setActiveSession } from '../session/session'+import { openRelayTab, type RelayTab } from '../session/relay-tab'import { buildBackgroundLinkMaps, buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, type LinkEndpoint } from '../lib/noteLink'import { useSettings } from '../state/settings'import { activePermissionMode } from '../state/permissionMode'@@ -428,8 +428,9 @@ export function Canvas() {// When set, add a terminal to this project once its nodes have loaded into React Flow// (cross-project "add" from the sidebar, which must switch projects first).const pendingAddRef = useRef<string | null>(null)- // When set, a full-surface remote mirror of a connected host is shown over the local canvas.- const [remoteConnId, setRemoteConnId] = useState<string | null>(null)+ // Live relay tabs, keyed by relay connectionId, so a host/relay drop can dispose the right one+ // (a remote connection is now a project TAB, not a full-surface overlay — Stage 4 Task 6).+ const relayTabsRef = useRef<Map<string, RelayTab>>(new Map())const [remoteDialogOpen, setRemoteDialogOpen] = useState(false)// "Connect over SSH…" project-creation dialog (from the Welcome screen).const [sshDialogOpen, setSshDialogOpen] = useState(false)@@ -960,6 +961,10 @@ export function Canvas() {// screen) → null, which is exactly what the early returns below mean. reportProject dedups,// and Canvas deliberately never READS the presence store (see the connectPresence effect).reportProject(activeProjectId || null)+ // Track the active session by the tab we switched to, so non-component api accessors+ // (activeSessionApi() in scmDraft/worktrees) hit the active tab's core — the local session for+ // a local tab, the relay session for a remote tab. Resolution is by binding (never persisted).+ setActiveSession(sessionForProject(activeProjectId || '').id)if (!activeProjectId) returnconst project = useProjects.getState().getProject(activeProjectId)if (!project) return@@ -1774,30 +1779,50 @@ export function Canvas() {[addTerminal, scmCwd])- /** Open a terminal node bound to a remote host (RemoteTransport) for a live relay connection. */- // Tear down the active remote mirror: hide the view and disconnect the relay connection (ends- // the host<->client bridge; the host-side tmux sessions survive). Safe to call when none active.- const disconnectRemote = useCallback(() => {- setRemoteConnId((id) => {- if (id) void window.nodeTerminal.remoteClient.disconnect(id)- return null+ // Turn an approved (or approving) relay connection into a project TAB (Stage 4 Task 6): build the+ // bridged api, wait for mutual approval, then add a session-bound tab. `openRelayTab` guards the+ // approval wait so a pre-approval socket drop rejects instead of hanging. On a later host/relay+ // drop, dispose the tab's session (presence + relay socket teardown). Idempotent per connectionId.+ const mountRemoteMirror = useCallback((connectionId: string, label = 'Remote host') => {+ if (relayTabsRef.current.has(connectionId)) return+ void openRelayTab(connectionId, label, {+ relayClient: window.nodeTerminal.relayClient,+ addProject: (name) => useProjects.getState().addProject(name),+ setActiveProject: (id) => useProjects.getState().setActive(id),})- }, [])-- // Mount the host mirror for an already-established connection. Wires `onClosed` so a dropped- // host/relay tears the view down without leaking the listener.- const mountRemoteMirror = useCallback((connectionId: string) => {- setRemoteConnId(connectionId)+ .then((tab) => {+ relayTabsRef.current.set(connectionId, tab)+ // A host/relay drop after approval tears the tab's session down (once).+ const un = window.nodeTerminal.relayClient.onClosed(connectionId, () => {+ un()+ relayTabsRef.current.delete(connectionId)+ tab.dispose()+ })+ })+ .catch((err) => {+ window.alert(`Remote session did not open: ${(err as Error).message}`)+ })}, [])// "New Remote Connection" entry point (dock / palette): paste a host's pairing offer, connect,- // and open the live mirror over the local canvas. This is the primary remote entry (it replaces- // B4's lone remote-terminal-on-connect flow).+ // compare the SAS, confirm, and open the host as a project tab. This is the primary remote entry.const connectRemote = useCallback(async () => {const offer = (await promptDialog({ message: "Paste the host's pairing code:" }))?.trim()if (!offer) returntry {- const connectionId = await window.nodeTerminal.remoteClient.connect(offer)+ const connectionId = await window.nodeTerminal.relayClient.connect(offer)+ // Surface the SAS so this human can verify it matches the host's before confirming (the+ // mutual-approval gate — the confirm rides the ENCRYPTED tunnel in main; see relay-client.ts).+ const unSas = window.nodeTerminal.relayClient.onSas(connectionId, (sas) => {+ unSas()+ if (sas && window.confirm(`Verify this code matches the one shown on the host:\n\n${sas}`)) {+ window.nodeTerminal.relayClient.confirm(connectionId)+ } else {+ window.nodeTerminal.relayClient.disconnect(connectionId)+ }+ })+ // Build the tab now (registers the one-shot onApproved listener BEFORE approval fires — see+ // relay-api.ts gotcha 2); it resolves once both humans confirm.mountRemoteMirror(connectionId)} catch (err) {window.alert(`Could not connect: ${(err as Error).message}`)@@ -2194,14 +2219,6 @@ export function Canvas() {return () => window.removeEventListener('nodeterm:open-remote-terminal', onOpenRemote)}, [mountRemoteMirror])- // Tear the mirror down if the host/relay drops the active connection.- useEffect(() => {- if (!remoteConnId) return- return window.nodeTerminal.remoteClient.onClosed(remoteConnId, () => {- setRemoteConnId((id) => (id === remoteConnId ? null : id))- })- }, [remoteConnId])-/*** Move every node that was living in a worktree directory OFF that (now dead) path — back to the* group's own cwd, else the project's. `displacedByWorktree` decides who those are: descendants@@ -5212,6 +5229,12 @@ export function Canvas() {</div><div className="flow-wrap" ref={flowWrapRef}>+ {/* The active project's node subtree runs under ITS session (local for a local tab, the+ relay session for a remote tab). Keyed by session id so an api swap REMOUNTS the nodes+ (obligation 3): TerminalNode/EditorNode/ChatNode capture `api` in []-effects, so a live+ api change must remount them or they keep talking to the old core. For an all-local user+ the key is always 'local', so this never remounts — zero behavior change. */}+ <SessionProvider session={sessionForProject(activeProjectId || '')} key={sessionForProject(activeProjectId || '').id}><ReactFlownodes={allNodes}edges={displayEdges}@@ -5266,6 +5289,7 @@ export function Canvas() {<PresenceLayer /><StatusAwareMiniMap onNodeDoubleClick={goToNode} /></ReactFlow>+ </SessionProvider>{/* Mounted unconditionally, even when we are alone: the facepile renders null with no peers,but it is also what prunes the presence store's face cache — gating its mount on a peer@@ -5300,12 +5324,6 @@ export function Canvas() {onClose={() => setCloneDialogOpen(false)}onCloned={onRepoCloned}/>-- {remoteConnId && (- <div className="remote-session-overlay">- <RemoteSessionView connectionId={remoteConnId} onClose={disconnectRemote} />- </div>- )}</div>{remoteDialogOpen && <RemoteAccessDialog onClose={() => setRemoteDialogOpen(false)} />}diff --git a/src/renderer/components/PresenceNamePrompt.tsx b/src/renderer/components/PresenceNamePrompt.tsxindex c1598b941..6582c1631 100644--- a/src/renderer/components/PresenceNamePrompt.tsx+++ b/src/renderer/components/PresenceNamePrompt.tsx@@ -1,6 +1,7 @@import { useState } from 'react'import { NAME_MAX_LEN, PRESENCE_COLORS } from '@shared/presence'import { selectOthers, suggestIdentity, usePresence } from '../state/presence'+import { setMeAll } from '../session/session'/*** First-connect identity prompt: pick a name + color. Saved to localStorage@@ -17,7 +18,6 @@ import { selectOthers, suggestIdentity, usePresence } from '../state/presence'export function PresenceNamePrompt(): JSX.Element | null {const needsName = usePresence((s) => s.needsName)const otherCount = usePresence((s) => selectOthers(s).length)- const setMe = usePresence((s) => s.setMe)// suggestIdentity is read ONCE (lazy initializer): a peer joining later must not swap the// suggested color out from under a user who is mid-typing.const [draft] = useState(suggestIdentity)@@ -30,7 +30,9 @@ export function PresenceNamePrompt(): JSX.Element | null {const submit = (): void => {const trimmed = name.trim()if (!trimmed) return- setMe({ name: trimmed, color }) // saves + says hello again, which renames us on the hub+ // Re-hello EVERY live session, not just the local one (obligation 2): renaming yourself must+ // rename you on every connected core, or a remote peer keeps drawing your old name until reload.+ setMeAll({ name: trimmed, color }) // saves + says hello again on each session}return (diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 40ead62b7..46837361e 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -14,8 +14,7 @@ import { WebglAddon } from '@xterm/addon-webgl'import { WebLinksAddon } from '@xterm/addon-web-links'import { renderMarkdown } from '../lib/markdown'import { ChatPanel } from './ChatPanel'-import { transport as localTransport } from '../terminal/local-transport'-import { RemoteTransport } from '../terminal/remote-transport'+import { LocalTransport } from '../terminal/local-transport'import type { TerminalTransport } from '../terminal/transport'import { patchTerminalScale } from '../terminal/scale-fix'import { parseOsc52 } from '../terminal/osc52'@@ -306,13 +305,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// inside the once-mounted lifecycle effect is safe and never re-runs that effect). Core-bound// namespaces (pty, fs) go through it; app-global ones (clipboard, shell) stay on the global.const { api } = useSession()- // Pick the session layer: a remote-bound node (data.remote) talks to a host over the relay- // via RemoteTransport; otherwise the local PTY (LocalTransport). The connectionId is stable- // for a node's lifetime, so the instance is created once and held in a ref.+ // The transport is ALWAYS `LocalTransport` over THIS session's api — one protocol, no+ // RemoteTransport. For the local session `api.pty` is the preload; for a relay tab it is Task 5's+ // bridged pty (the relay tunnel), so LocalTransport over the bridged api IS the remote transport.+ // The session's api is stable for the node's lifetime, so the instance is created once and held.const transportRef = useRef<TerminalTransport | null>(null)if (!transportRef.current) {- const conn = (data.remote as { connectionId: string } | undefined)?.connectionId- transportRef.current = conn ? new RemoteTransport(conn) : localTransport+ transportRef.current = new LocalTransport(api)}const transport = transportRef.current// Scoped selectors (not the whole settings object) so this node only re-renders when adiff --git a/src/renderer/session/relay-tab.test.ts b/src/renderer/session/relay-tab.test.tsnew file mode 100644index 000000000..7eaa2de19--- /dev/null+++ b/src/renderer/session/relay-tab.test.ts@@ -0,0 +1,131 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { openRelayTab, type RelayTabDeps } from './relay-tab'+import {+ createSession,+ setActiveSession,+ sessionForProject,+ sessionCount,+ resetSessionsForTest,+} from './session'+import { LocalTransport } from '../terminal/local-transport'+import type { NodeTerminalApi } from '@shared/types'+import type { RelayApiHandle } from '../bridge/relay-api'++/** A fake relayClient.onClosed sink: keeps the callback so the test can fire a socket drop. */+function fakeRelayClient() {+ const closeCbs: Array<() => void> = []+ const unsub = vi.fn()+ return {+ onClosed: vi.fn((_connectionId: string, cb: () => void) => {+ closeCbs.push(cb)+ return unsub+ }),+ unsub,+ fireClose: () => closeCbs.forEach((cb) => cb()),+ }+}++/** A bridged relay api whose `pty.create` is a spy — this is what `LocalTransport(api)` must hit. */+function fakeBridgedApi() {+ const ptyCreate = vi.fn().mockResolvedValue({ sessionId: 's1', fresh: false })+ const api = {+ marker: 'relay-bridged',+ pty: { create: ptyCreate },+ presence: {+ hello: vi.fn().mockResolvedValue({ clientId: 'x', peers: [] }),+ onSync: vi.fn(() => () => {}),+ onPeer: vi.fn(() => () => {}),+ },+ } as unknown as NodeTerminalApi+ return { api, ptyCreate }+}++function makeDeps(over: Partial<RelayTabDeps> & { handle: RelayApiHandle }): {+ deps: RelayTabDeps+ addProject: ReturnType<typeof vi.fn>+ setActiveProject: ReturnType<typeof vi.fn>+} {+ const addProject = vi.fn((_label: string) => ({ id: 'proj-1' }))+ const setActiveProject = vi.fn()+ const deps: RelayTabDeps = {+ relayClient: over.relayClient ?? fakeRelayClient(),+ addProject: over.addProject ?? addProject,+ setActiveProject: over.setActiveProject ?? setActiveProject,+ buildApi: () => over.handle,+ timeoutMs: over.timeoutMs,+ }+ return { deps, addProject, setActiveProject }+}++beforeEach(() => {+ resetSessionsForTest()+ // A local session must exist so a disposed remote tab resolves back to it (not a throw).+ const local = createSession('local', { marker: 'local' } as unknown as NodeTerminalApi, 'This Mac')+ setActiveSession(local.id)+})++describe('openRelayTab (connect → tab → mount)', () => {+ it('an approving connection becomes a relay session, a bound tab, and the active session', async () => {+ const { api, ptyCreate } = fakeBridgedApi()+ const close = vi.fn()+ const handle: RelayApiHandle = { api, ready: () => Promise.resolve(), close }+ const { deps, addProject, setActiveProject } = makeDeps({ handle })++ const tab = await openRelayTab('conn-1', "Ayşe's Mac", deps)++ // A relay session now exists and the tab is bound to it.+ const session = sessionForProject(tab.projectId)+ expect(session.source).toBe('relay')+ expect(session.id).toBe(tab.sessionId)+ expect(session.api).toBe(api)+ expect(addProject).toHaveBeenCalledWith("Ayşe's Mac")+ expect(setActiveProject).toHaveBeenCalledWith('proj-1')++ // The one-protocol payoff: a TerminalNode under this session builds LocalTransport(session.api),+ // and its pty work hits the BRIDGED (remote) pty — not the local preload.+ await new LocalTransport(session.api).create({ persistKey: tab.sessionId } as never)+ expect(ptyCreate).toHaveBeenCalledTimes(1)++ // dispose() tears the session down (relay socket close) exactly once and unbinds the tab.+ expect(close).not.toHaveBeenCalled()+ tab.dispose()+ expect(close).toHaveBeenCalledTimes(1)+ expect(sessionForProject(tab.projectId).source).toBe('local') // unbound → local+ expect(sessionCount()).toBe(1) // only local remains+ })++ it('GUARD: a pre-approval socket drop REJECTS the bootstrap (never hangs) and closes the handle', async () => {+ const { api } = fakeBridgedApi()+ const close = vi.fn()+ // ready() that resolves only on approval and NEVER rejects — the hang risk from frame-transport.+ const handle: RelayApiHandle = { api, ready: () => new Promise<void>(() => {}), close }+ const relayClient = fakeRelayClient()+ const { deps } = makeDeps({ handle, relayClient })++ const bootstrap = openRelayTab('conn-2', 'doomed', deps)+ // The socket dies BEFORE either human approves.+ relayClient.fireClose()++ await expect(bootstrap).rejects.toThrow(/clos/i)+ expect(close).toHaveBeenCalledTimes(1) // the dead relay socket is torn down+ expect(sessionCount()).toBe(1) // no relay session was ever registered — only local+ })++ it('GUARD: a timeout backstop rejects a ready() that neither approves nor closes', async () => {+ vi.useFakeTimers()+ try {+ const { api } = fakeBridgedApi()+ const close = vi.fn()+ const handle: RelayApiHandle = { api, ready: () => new Promise<void>(() => {}), close }+ const { deps } = makeDeps({ handle, timeoutMs: 50 })++ const bootstrap = openRelayTab('conn-3', 'stuck', deps)+ const assertion = expect(bootstrap).rejects.toThrow(/tim(e|ed)/i)+ await vi.advanceTimersByTimeAsync(60)+ await assertion+ expect(close).toHaveBeenCalledTimes(1)+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/src/renderer/session/relay-tab.ts b/src/renderer/session/relay-tab.tsnew file mode 100644index 000000000..15b616355--- /dev/null+++ b/src/renderer/session/relay-tab.ts@@ -0,0 +1,118 @@+// openRelayTab — turn an approved (or approving) relay connection into a project TAB.+//+// docs/remote-sessions.md, Stage 4 Task 6: a remote desktop is a client of the host's core, so it+// opens as an ordinary project tab (not a full-screen overlay). This is the join point that wires+// Task 5's `buildRelayApi` into the 4a session registry:+// buildRelayApi(id) → createSession('relay', api, label) → a `projects` tab bound to it → active.+//+// TWO obligations this bootstrap owns (both would silently break the tab):+// • Construction order (relay-api.ts gotcha 2): `buildRelayApi` is called FIRST — its+// `RelayFrameTransport` registers the one-shot `onApproved` listener BEFORE we await `ready()`.+// Build it after approval already fired and `ready()` stays pending forever.+// • ready() can HANG (Task 5 review): `RelayFrameTransport.ready()` resolves only on `onApproved`+// and NEVER rejects; a socket drop BEFORE the SAS is approved would leave the bootstrap awaiting+// forever — a dead tab that never errors. So we RACE `ready()` against the connection's real+// close signal (relayClient.onClosed) plus a timeout backstop, and reject on either.++import type { RelayClientApi } from '@shared/types'+import { buildRelayApi, type RelayApiHandle } from '../bridge/relay-api'+import {+ createSession,+ bindProjectToSession,+ setActiveSession,+ holdSessionTeardown,+ disposeSession,+ getSessionStores,+} from './session'++/** Backstop for a `ready()` that neither approves nor closes (the network vanished without a FIN). */+const APPROVAL_TIMEOUT_MS = 60_000++export interface RelayTabDeps {+ /** The preload relay surface — only `onClosed` is needed here (to catch a pre-approval drop). */+ relayClient: Pick<RelayClientApi, 'onClosed'>+ /** Add a project tab (`useProjects.getState().addProject`) → the new project's id. */+ addProject: (label: string) => { id: string }+ /** Make the new tab active (`useProjects.getState().setActive`). */+ setActiveProject: (projectId: string) => void+ /** TEST SEAM: build the relay api handle. Production omits it → `buildRelayApi`. */+ buildApi?: (connectionId: string) => RelayApiHandle+ /** TEST SEAM: approval-timeout backstop (default `APPROVAL_TIMEOUT_MS`). */+ timeoutMs?: number+}++export interface RelayTab {+ sessionId: string+ projectId: string+ /** Tear the tab's session down (runs the held presence teardown + relay socket close, once). */+ dispose(): void+}++/**+ * Bootstrap a relay project tab. Resolves once the connection is mutually approved and the tab is+ * live; REJECTS (never hangs) if the socket drops or times out before approval.+ */+export async function openRelayTab(+ connectionId: string,+ label: string,+ deps: RelayTabDeps+): Promise<RelayTab> {+ const build = deps.buildApi ?? buildRelayApi+ // Built BEFORE we await ready() so the one-shot onApproved listener is registered in time.+ const handle = build(connectionId)++ try {+ await raceApproval(handle, connectionId, deps)+ } catch (err) {+ handle.close() // tear the dead/stuck relay socket down before surfacing the failure+ throw err+ }++ const session = createSession('relay', handle.api, label)+ // The teardowns the tab owes on disconnect (obligation 1): the presence subscription this session+ // just opened, and the relay socket. Both run exactly once in disposeSession.+ holdSessionTeardown(session.id, getSessionStores(session.id).presence.connect())+ holdSessionTeardown(session.id, () => handle.close())++ const project = deps.addProject(label)+ bindProjectToSession(project.id, session.id)+ setActiveSession(session.id)+ deps.setActiveProject(project.id)++ return {+ sessionId: session.id,+ projectId: project.id,+ dispose: () => disposeSession(session.id),+ }+}++/** Resolve on approval (`handle.ready()`); reject on a pre-approval socket drop or a timeout. */+function raceApproval(+ handle: RelayApiHandle,+ connectionId: string,+ deps: RelayTabDeps+): Promise<void> {+ return new Promise<void>((resolve, reject) => {+ let settled = false+ let unClose: () => void = () => {}+ let timer: ReturnType<typeof setTimeout> | null = null+ const finish = (fn: () => void) => {+ if (settled) return+ settled = true+ unClose()+ if (timer) clearTimeout(timer)+ fn()+ }+ unClose = deps.relayClient.onClosed(connectionId, () =>+ finish(() => reject(new Error('The relay connection closed before it was approved.')))+ )+ timer = setTimeout(+ () => finish(() => reject(new Error('Timed out waiting for the host to approve.'))),+ deps.timeoutMs ?? APPROVAL_TIMEOUT_MS+ )+ handle.ready().then(+ () => finish(resolve),+ (err) => finish(() => reject(err instanceof Error ? err : new Error(String(err))))+ )+ })+}diff --git a/src/renderer/session/session.test.ts b/src/renderer/session/session.test.tsindex 72dc2c1ab..865541b7a 100644--- a/src/renderer/session/session.test.ts+++ b/src/renderer/session/session.test.ts@@ -1,4 +1,4 @@-import { describe, it, expect, beforeEach } from 'vitest'+import { describe, it, expect, beforeEach, vi } from 'vitest'import {createSession,getSessionStores,@@ -8,8 +8,21 @@ import {sessionForProject,sessionCount,resetSessionsForTest,+ bindProjectToSession,+ disposeSession,+ holdSessionTeardown,+ setMeAll,} from './session'import type { NodeTerminalApi } from '@shared/types'+import type { PeerIdentity } from '@shared/presence'++/** A fake api whose `presence.hello` is a spy — so a re-hello is observable in node env+ * (createSession's presence store is built against this api by identity). */+function apiWithHelloSpy(marker: string): { api: NodeTerminalApi; hello: ReturnType<typeof vi.fn> } {+ const hello = vi.fn().mockResolvedValue({ clientId: `id-${marker}`, peers: [] })+ const api = { marker, presence: { hello } } as unknown as NodeTerminalApi+ return { api, hello }+}// A distinctive object we can assert is preserved BY IDENTITY (the behavior-unchanged guarantee).const fakeApi = { marker: 'preload' } as unknown as NodeTerminalApi@@ -106,3 +119,77 @@ describe('sessionForProject (runtime tab → session resolver, never persisted)'expect(sessionCount()).toBe(2)})})++describe('bindProjectToSession (4c remote-tab resolution)', () => {+ it('a bound project resolves to its remote session; an unbound one resolves to local', () => {+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, "Ayşe's Mac")++ bindProjectToSession('remote-tab', relay.id)+ expect(sessionForProject('remote-tab')).toBe(relay)+ // An unbound project stays on the LOCAL session even while a remote session exists — never the+ // merely-active one (the resolver is by binding, not by which tab is focused).+ expect(sessionForProject('some-local-tab')).toBe(local)+ // Even after the remote tab is made active, a local tab still resolves local.+ setActiveSession(relay.id)+ expect(sessionForProject('some-local-tab')).toBe(local)+ expect(sessionForProject('remote-tab')).toBe(relay)+ })++ it('rejects a binding to an unknown session id', () => {+ createSession('local', fakeApi, 'This Mac')+ expect(() => bindProjectToSession('p', 'relay-999')).toThrow()+ })+})++describe('disposeSession (obligation 1 — the missing disposal path)', () => {+ it('runs every held teardown exactly once, drops the session, and unbinds its projects', () => {+ const local = createSession('local', fakeApi, 'This Mac')+ setActiveSession(local.id)+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'remote')+ const presenceTeardown = vi.fn()+ const relayClose = vi.fn()+ holdSessionTeardown(relay.id, presenceTeardown)+ holdSessionTeardown(relay.id, relayClose)+ bindProjectToSession('remote-tab', relay.id)+ expect(sessionForProject('remote-tab')).toBe(relay)++ disposeSession(relay.id)++ expect(presenceTeardown).toHaveBeenCalledTimes(1)+ expect(relayClose).toHaveBeenCalledTimes(1)+ expect(sessionCount()).toBe(1) // only local remains+ // The binding is gone → the (now-dead) tab resolves back to the local session, never a throw.+ expect(sessionForProject('remote-tab')).toBe(local)++ // Idempotent: a second dispose (double close, revoke racing a socket drop) touches nothing.+ disposeSession(relay.id)+ expect(presenceTeardown).toHaveBeenCalledTimes(1)+ expect(relayClose).toHaveBeenCalledTimes(1)+ })++ it('disposing an unknown session id is a no-op', () => {+ expect(() => disposeSession('relay-nope')).not.toThrow()+ })+})++describe('setMeAll (obligation 2 — a rename re-helloes EVERY live session)', () => {+ it('re-helloes and updates identity on all registered sessions, not just the active one', () => {+ const a = apiWithHelloSpy('a')+ const b = apiWithHelloSpy('b')+ const s1 = createSession('local', a.api, 'This Mac')+ const s2 = createSession('relay', b.api, "Ayşe's Mac")+ setActiveSession(s1.id)++ const me: PeerIdentity = { name: 'Ada', color: '#0af' }+ setMeAll(me)++ // Every live session re-announced (setMe → sayHello → api.presence.hello) with the new identity.+ expect(a.hello).toHaveBeenCalledWith(me)+ expect(b.hello).toHaveBeenCalledWith(me)+ // …and each session's store reflects the new identity.+ expect(getSessionStores(s1.id).presence.store.getState().me).toEqual(me)+ expect(getSessionStores(s2.id).presence.store.getState().me).toEqual(me)+ })+})diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.tsindex 8f47b3441..ab5b13e77 100644--- a/src/renderer/session/session.ts+++ b/src/renderer/session/session.ts@@ -1,5 +1,6 @@import { createContext, createElement, useContext, type ReactNode } from 'react'import type { NodeTerminalApi } from '@shared/types'+import type { PeerIdentity } from '@shared/presence'import { createPresenceSession, type PresenceSession } from '../state/presence'import { agentStatusForApi, type AgentStatusSession } from '../state/agentStatus'@@ -25,9 +26,16 @@ export interface SessionStores {interface Entry {session: WorkspaceSessionstores: SessionStores+ /** Teardowns the tab that owns this session owes on disconnect (obligation 1): the presence+ * `connect()` subscription, the relay socket close. Run exactly once by `disposeSession`. */+ teardowns: Array<() => void>+ disposed: boolean}const SESSIONS = new Map<string, Entry>()+/** projectId → sessionId. Runtime-only (never persisted — see `sessionForProject`). A remote tab+ * binds here; a local tab is absent and resolves to the local session. */+const PROJECT_BINDINGS = new Map<string, string>()let activeId: string | null = nulllet remoteSeq = 0@@ -60,13 +68,44 @@ export function createSession(source: SessionSource, api: NodeTerminalApi, labelconst existing = SESSIONS.get(id)if (existing) return existing.sessionconst session: WorkspaceSession = { id, source, label, api, status: 'connected' }- SESSIONS.set(id, { session, stores: buildStores(api) })+ SESSIONS.set(id, { session, stores: buildStores(api), teardowns: [], disposed: false })return session}+/** Register a teardown the owning tab owes when this session is disposed (obligation 1): the+ * presence `connect()` teardown, the relay socket close. `disposeSession` runs them once, in order.+ * Throws for an unknown id so a caller can never silently strand a live subscription. */+export function holdSessionTeardown(sessionId: string, teardown: () => void): void {+ const e = SESSIONS.get(sessionId)+ if (!e) throw new Error(`[session] no session ${sessionId}`)+ e.teardowns.push(teardown)+}++/** 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. */+export function disposeSession(sessionId: string): void {+ const e = SESSIONS.get(sessionId)+ if (!e || e.disposed) return+ e.disposed = true+ // splice() so a teardown that (re-entrantly) calls disposeSession again finds nothing to re-run.+ for (const t of e.teardowns.splice(0)) {+ try {+ t()+ } catch (err) {+ console.warn('[session] teardown failed', err)+ }+ }+ SESSIONS.delete(sessionId)+ for (const [projectId, sid] of PROJECT_BINDINGS) if (sid === sessionId) PROJECT_BINDINGS.delete(projectId)+ if (activeId === sessionId) activeId = SESSIONS.has('local') ? 'local' : null+}+/** Test-only: clears the registry so each test starts with no sessions. */export function resetSessionsForTest(): void {SESSIONS.clear()+ PROJECT_BINDINGS.clear()activeId = nullremoteSeq = 0}@@ -97,12 +136,41 @@ export function sessionCount(): number {return SESSIONS.size}+/** Bind a project tab to a session (4c: a remote tab → its relay/server session). Runtime-only,+ * never persisted. Throws for an unknown session id so a tab can never bind to nothing. */+export function bindProjectToSession(projectId: string, sessionId: string): void {+ if (!SESSIONS.has(sessionId)) throw new Error(`[session] no session ${sessionId}`)+ PROJECT_BINDINGS.set(projectId, sessionId)+}++/** 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. */+function localOrActiveSession(): WorkspaceSession {+ const local = SESSIONS.get('local')+ return local ? local.session : getActiveSession()+}+/** 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). Today every project is on the local- * session; 4c returns the tab's bound session (local | relay | server). */-export function sessionForProject(_projectId: string): WorkspaceSession {- return getActiveSession()+ * 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. */+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()+}++/** Re-broadcast the local human's identity on EVERY live session (obligation 2). Renaming yourself+ * must re-hello every connected core, not just the one the rename UI happened to read — otherwise a+ * remote peer keeps drawing your old name until reload. `setMe` saves + says hello per session. */+export function setMeAll(identity: PeerIdentity): void {+ for (const e of SESSIONS.values()) e.stores.presence.store.getState().setMe(identity)}/** Hook wrapper over `sessionForProject` for components. Subscribes via `useSession()` so a