Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(relay): a team tab's terminal node shows its host session's agent status
review4b5ed13a7147
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 01861c717..a2fa9e536 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -684,6 +684,7 @@ import {sessionForProject,boundSessionForProject,presenceForProject,+ agentStatusForProject,setActiveSession,disposeSession,holdSessionTeardown,@@ -2950,6 +2951,11 @@ export function Canvas() {// active id, so the outgoing project's nodes never remount under the incoming project's session.const flowOwnerProjectId = useFlowStoreOwner(allNodes, renderedProjectId)const nodeSession = sessionForProject(flowOwnerProjectId ?? '')+ // The same owner for imperative callbacks: a focus marks the node active / read in the agent-status+ // store of the session the node renders under (`agentStatusForProject(owner)`), never the active+ // project's — a handed-off SSH project and the team tab serving it share node ids.+ const flowOwnerProjectIdRef = useRef(flowOwnerProjectId)+ flowOwnerProjectIdRef.current = flowOwnerProjectId// Work that frames a just-loaded project waits for that same ownership (see flowLanding.ts).const flowLanding = useFlowLanding(flowOwnerProjectId)@@ -3552,8 +3558,11 @@ export function Canvas() {// the target terminal so the user can type without a second click.useTerminalFocus.getState().request(pending)}- useAgentStatus.getState().setActive(pending, true)- useAgentStatus.getState().clearUnread(pending)+ // `project.id` IS the flow-store owner here: flowLanding runs this only once React+ // Flow's store holds that project, so the node renders under its session.+ const statusStore = agentStatusForProject(project.id).store+ statusStore.getState().setActive(pending, true)+ statusStore.getState().clearUnread(pending)}}})@@ -11973,8 +11982,9 @@ export function Canvas() {// broken there. On the board, "go to" means OPEN THE CARD.if (isGlobalKanbanOpen() || isKanbanOpen(useProjects.getState().activeProjectId)) {useViewMode.getState().requestCard(nodeId)- useAgentStatus.getState().setActive(nodeId, true)- useAgentStatus.getState().clearUnread(nodeId)+ const statusStore = agentStatusForProject(flowOwnerProjectIdRef.current).store+ statusStore.getState().setActive(nodeId, true)+ statusStore.getState().clearUnread(nodeId)return}setNodes((ns) => ns.map((n) => ({ ...n, selected: n.id === nodeId })))@@ -11983,10 +11993,12 @@ export function Canvas() {// frames it but does not focus xterm on its own (the pan/hover guard owns that), which is// why a sidebar click used to need a second click/hover before typing worked.useTerminalFocus.getState().request(nodeId)- // Mark this node as watched and its completion as read. Read state is independent of the- // live `done` workflow state, so it remains under Waiting for your response.- useAgentStatus.getState().setActive(nodeId, true)- useAgentStatus.getState().clearUnread(nodeId)+ // Mark this node as watched and its completion as read, in the store of the session it+ // renders under (the flow-store owner's). Read state is independent of the live `done`+ // workflow state, so it remains under Waiting for your response.+ const statusStore = agentStatusForProject(flowOwnerProjectIdRef.current).store+ statusStore.getState().setActive(nodeId, true)+ statusStore.getState().clearUnread(nodeId)return}// `nodeOwner`, not the first project holding the id: a closed, handed-off SSH project sharesdiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 54b8e8d5a..e0a565282 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -276,7 +276,7 @@ import { announceUserClosedSession } from '../lib/lastSessionClose'import { useSettings } from '../state/settings'import { useCodexIdentity, codexSharedIdentity, codexFallbackText } from '../state/codexIdentity'import { ensureCodexLaunchCaps } from '../state/codexCli'-import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'+import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'import { useLaunchDelivery } from '../state/launchDelivery'import { erroredDeps, firstOpenInFlight as isFirstOpenInFlight, handedOverDeps, holdReason, interruptedDeps, launchTooltip } from '../lib/pendingLaunch'import { useStationHandovers } from '../state/stationHandovers'@@ -297,7 +297,8 @@ import { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'import { RunBar } from './RunBar'-import { isRemoteProjectId, useSession, useActiveSessionPresence } from '../session/session'+import { isRemoteProjectId, useSession, useSessionStores, useActiveSessionPresence } from '../session/session'+import { relayStatusGates } from '../terminal/relay-status-gates'import { isHostedReadOnly, useHostedReadOnly } from '../state/hostedTeams'import { isBrowserRuntime } from '../bridge/runtime'import { liveLinkUnavailable } from '../lib/liveLinkEntry'@@ -1356,29 +1357,30 @@ export function TerminalNode({// own session's presence instead is a follow-up.const presence = useActiveSessionPresence()/**- * THIS node's agent-status store, for the memory levers that must not kill live work — resolved- * the way the session registry resolves it (`buildStores` → `agentStatusForApi`, memoized by api- * identity), so this node is judged against the status table of the core it actually runs on.+ * THIS node's agent-status store: the store of the session it renders under, i.e. the status+ * table of the core it actually runs on. For the local session that is the default persisted+ * instance — the exact object `useAgentStatus` exports — so a local node reads and writes what it+ * always did. For a RELAY / team tab it is that session's keyless store, which the session's own+ * `agent:status` subscription feeds (`wireRelayAgentStatus`, plus the join-time snapshot), so the+ * node shows its HOST session's status: the badge, the unread dot, the session chip. Never the+ * default store for a relay node: a handed-off SSH project shares its node ids with the team tab+ * now serving them, and the two must not read or mark each other's status.*- * WHAT THAT MEANS TODAY, PLAINLY: for the local session this resolves to the default persisted- * instance — the exact object `useAgentStatus` exports — so local nodes are protected. For a- * RELAY tab it resolves to that core's keyless instance, and NOTHING WRITES THAT INSTANCE YET:- * Canvas's `agent:status` subscription sits above the per-project session provider and writes- * the default store, and `useSessionStores()` currently has no consumers at all. So a relay- * node's state always reads `undefined` here, and RELAY PARKS REMAIN UNPROTECTED — which now- * matters, because `persistent:false` can arrive from a tmux-less relay HOST, i.e. exactly a- * plain-shell agent session on someone else's machine.+ * What reads and writes it: the badge (`status`) and everything derived from it, every focus mark+ * (`setActive` / `clearUnread`: the dwell, a click, a "go to node" focus, selection, a file+ * insert, the lifecycle teardown), the OSC session-title chip, and the memory levers that must+ * not kill live work (`readAgentState`, `readAgentProcess`, the park's `readSessionEnded`). A+ * relay node's own status thereby also protects its park — `persistent:false` can arrive from a+ * tmux-less relay HOST, i.e. a plain-shell agent session on someone else's machine. The+ * status-driven readers that would act on THIS machine are switched off for a relay node by+ * `gates` below (`relayStatusGates`).*- * Resolving it this way regardless is deliberate and is the cheap half of the fix: routing relay- * agent-status into the per-session stores (`useSessionStores` / `SessionStores.agentStatus` is- * the intended seam) is a real feature and belongs in its own change. When it lands, this code- * lights up unchanged — no branch here to find and update.- *- * Scoped deliberately to the protection paths. The other status reads in this file predate- * per-session stores and are left exactly as they were; widening them is that same separate- * change.+ * Deliberately still on the default store (`useAgentStatus`): Eco / hibernation, restart, pause,+ * the liveness check, the cold restore and the pending-launch deps. Those features are refused on+ * relay sessions, so their reads only ever concern a local node. Stable for the session's+ * lifetime (memoized by api identity), so the once-mounted lifecycle effect may close over it.*/- const agentStatusStore = agentStatusForApi(api).store+ const agentStatusStore = useSessionStores().agentStatus.storeconst readAgentState = useCallback((): AgentState | undefined => agentStatusStore.getState().byId[id]?.state,[agentStatusStore, id]@@ -1933,7 +1935,10 @@ export function TerminalNode({shell: data.shell || useSettings.getState().settings.defaultShell || undefined})}- const status = useAgentStatus((s) => s.byId[id])+ const status = agentStatusStore((s) => s.byId[id])+ // Which status-driven readers this node may run (see relay-status-gates.ts): all of them on the+ // local session, none on a relay / team tab, whose status is its host's.+ const gates = relayStatusGates(session.source)/*** Which Claude account this node is ACTUALLY on. `data.accountId` is what nodeterm launched* it as and is immutable; `status.account` is what the session's hooks reported — the only@@ -2276,7 +2281,9 @@ export function TerminalNode({// markdown-of-output view (computed in the capture effect below) is shown as a fallback.// `chatAvailable` is split out because the label-row ⌘M hint names the face BEFORE it is open:// one value feeds both, so the hint cannot say "Chat view" while the chord opens markdown.- const chatAvailable = showChat && !!transcript.sessionId+ // `gates.chatView`: a relay / team tab keeps the Markdown output view (its transcript reads are+ // refused over the relay; the output view captures the host's pane).+ const chatAvailable = showChat && !!transcript.sessionId && gates.chatViewconst useChat = mdMode && chatAvailableuseContextEnsure(session.api.context, id, agentId, transcript.sessionId, transcript.cwd, accountForReads)const updateNodeInternals = useUpdateNodeInternals()@@ -2396,8 +2403,9 @@ export function TerminalNode({// actually running as, not the one the node was created with.accountId: accountForReads,// The transcript index reads claude's JSONL through the same resolver, so it is gated on the- // claude-transcript fact, NOT on the meter's `showUsage` — see lib/transcriptGates.ts.- searchTranscript: claudeTranscript,+ // claude-transcript fact, NOT on the meter's `showUsage` — see lib/transcriptGates.ts. And on+ // `gates.transcriptSearch`: it reads THIS machine's transcripts, never a relay host's.+ searchTranscript: gates.transcriptSearch && claudeTranscript,open: searchOpen,readBuffer})@@ -3570,7 +3578,7 @@ export function TerminalNode({// Ignore path/prompt-like titles (e.g. "user@host: ~/dir") which aren't session names.// This feeds the `session` chip only; the node title is synced from the transcript's// authoritative session name instead (see the readSessionName effect below).- if (title && !/[/:~]/.test(title)) useAgentStatus.getState().setSession(id, title)+ if (title && !/[/:~]/.test(title)) agentStatusStore.getState().setSession(id, title)}).dispose)}@@ -5184,7 +5192,7 @@ export function TerminalNode({// observer effect below, reads every input through a ref, and refuses on its own when// `offscreenLiveRef` is null. Clearing it on a respawn would drop a window that has been// counting down for minutes.- useAgentStatus.getState().setActive(id, false)+ agentStatusStore.getState().setActive(id, false)// Teammates stop seeing us in this node's header. releaseFocus, not reportFocus(null): on a// project switch every node unmounts, and an unconditional clear could undo the focus the// node we just moved into already published.@@ -5691,10 +5699,11 @@ export function TerminalNode({** `ack` (default true) says a human AIMED at this node, and two things follow from it. It marks* the node's finish read, which reaches past this machine (`clearUnread` → `ackDone` → the notch- * capsule and the paired phone). And it drops the hover guard, which is a POINTER contract: the- * guard makes a quick scroll pan the canvas until the dwell has elapsed, so a restore nobody- * pointed at must leave it armed, or the next pointer entry silently skips its dwell and the- * first wheel scrolls tmux instead. Keyboard focus does not need the guard down: it is an+ * capsule and the paired phone) on the local session; a relay session's store sends no ack, so+ * reading a team tab's finish clears this desktop's mark alone. And it drops the hover guard,+ * which is a POINTER contract: the guard makes a quick scroll pan the canvas until the dwell has+ * elapsed, so a restore nobody pointed at must leave it armed, or the next pointer entry silently+ * skips its dwell and the first wheel scrolls tmux instead. Keyboard focus does not need the guard down: it is an* overlay, and a programmatic `focus()` is not hit-tested.** Every gesture that reaches here aims at THIS node: a dwell, a click, a sidebar or notification@@ -5706,9 +5715,9 @@ export function TerminalNode({if (aimed) setArmed(false)focusXtermUnlessCovered(termRef.current, mdModeRef.current)useTerminalFocus.getState().remember(id)- useAgentStatus.getState().setActive(id, true)+ agentStatusStore.getState().setActive(id, true)if (aimed) {- useAgentStatus.getState().clearUnread(id)+ agentStatusStore.getState().clearUnread(id)}presence.reportFocus(id)}@@ -5768,8 +5777,8 @@ export function TerminalNode({}focusXtermUnlessCovered(termRef.current, mdModeRef.current)useTerminalFocus.getState().remember(id)- useAgentStatus.getState().setActive(id, true)- useAgentStatus.getState().clearUnread(id)+ agentStatusStore.getState().setActive(id, true)+ agentStatusStore.getState().clearUnread(id)// "I am working in this node" — the same signal the agent-status active flag uses, i.e. the// dwell has elapsed and the terminal actually took the keyboard (a mouse merely passing over// never gets here). Deduped in the store, so re-entering the same node costs nothing.@@ -5805,8 +5814,8 @@ export function TerminalNode({if (focusDrivesGuard(focusFollowsPointer)) setArmed(armed)},remember: () => useTerminalFocus.getState().remember(id),- isActive: () => useAgentStatus.getState().activeId === id,- setActive: (active) => useAgentStatus.getState().setActive(id, active),+ isActive: () => agentStatusStore.getState().activeId === id,+ setActive: (active) => agentStatusStore.getState().setActive(id, active),reportFocus: () => presence.reportFocus(id),releaseFocus: () => presence.releaseFocus(id)})@@ -5940,7 +5949,7 @@ export function TerminalNode({agentPane ? paneAgent : undefined,pasteReceipt.report)- useAgentStatus.getState().setActive(id, true)+ agentStatusStore.getState().setActive(id, true)presence.reportFocus(id)}@@ -6019,8 +6028,8 @@ export function TerminalNode({// Read state is separate from workflow state: selection clears the unread notification, while// an agent whose turn is done remains "Waiting for your response" until its next prompt starts.useEffect(() => {- if (selected) useAgentStatus.getState().clearUnread(id)- }, [selected, id])+ if (selected) agentStatusStore.getState().clearUnread(id)+ }, [selected, id, agentStatusStore])// Keep the node title in sync with the agent session's display name — the name shown in// `/resume` (`/rename` name, else auto name). This is the authoritative source: `/rename` doesn't@@ -6040,6 +6049,9 @@ export function TerminalNode({// ref (`accountForReadsRef`, refreshed every render) rather than the deps so a late observation// is picked up by the very next poll instead of tearing down and restarting the timer chain.useEffect(() => {+ // Not on a relay / team tab (`gates.titleSync`): the name would be read from the host and+ // adopted into the title, i.e. this tab would write the host's canvas on a timer.+ if (!gates.titleSync) returnif (!canReadTitleNode || data.titleAuto === false) returnconst sid = status?.sessionId ?? ''if (!sid) return@@ -6072,7 +6084,7 @@ export function TerminalNode({cancelled = trueif (timer) clearTimeout(timer)}- }, [id, canReadTitleNode, status?.sessionId, data.titleAuto, updateNodeData])+ }, [id, gates.titleSync, canReadTitleNode, status?.sessionId, data.titleAuto, updateNodeData])// Cmd/Ctrl+M toggles markdown view of this terminal's output — only when hovered, and never while// a board is up (the card modal owns the chord there; see `canvasOwnsMarkdownChord`).@@ -6491,8 +6503,10 @@ export function TerminalNode({{/* Deterministic hook-reply approvals (docs/hook-reply-approvals.md): when the node isblocked on a Claude permission request whose managed hook is holding open (pendingIdknown), answer it in one click — no keystrokes into the prompt. Vanishes the moment the- state leaves `blocked` (the store clears pendingId). */}- {status?.state === 'blocked' && status?.pendingId && (+ state leaves `blocked` (the store clears pendingId). Never on a relay / team tab+ (`gates.approvalButtons`): the answer goes to THIS machine's main, which holds no ticket+ for the host's session. */}+ {gates.approvalButtons && status?.state === 'blocked' && status?.pendingId && (<span className="term-node__approve nodrag">{/* Approve is hidden when THIS ticket is a held AskUserQuestion (lib/approveGate.ts);Deny still declines it. A held ExitPlanMode keeps Approve: the hook maps a plain@@ -6572,7 +6586,7 @@ export function TerminalNode({claude-transcript fact (see the `useTerminalSearch` call above), so keying the label onthe meter promised a codex/gemini node a conversation search it does not run. */}<Tooltip- label={claudeTranscript ? 'Search terminal + conversation' : 'Search this terminal'}+ label={gates.transcriptSearch && claudeTranscript ? 'Search terminal + conversation' : 'Search this terminal'}><buttonclassName="term-node__search nodrag"diff --git a/src/renderer/nodes/terminal-agent-status.source.test.ts b/src/renderer/nodes/terminal-agent-status.source.test.tsnew file mode 100644index 000000000..bc41e834b--- /dev/null+++ b/src/renderer/nodes/terminal-agent-status.source.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { resolve } from 'node:path'++/**+ * A terminal node reads and writes the agent status of the session it RUNS under (bug D, Task 5):+ * a team tab's node shows its host session's status, and its focus marks land in that session's+ * store, never in the default (local, persisted) one, which a handed-off SSH project shares node ids+ * with. A relay node also must not act on this machine through the status it now sees. Source pins:+ * TerminalNode and Canvas cannot be mounted here.+ */+const read = (rel: string) => readFileSync(resolve(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')+const src = read('./TerminalNode.tsx')+const canvas = read('../canvas/Canvas.tsx')++/** The text from `start` up to (not including) the first `end` after it; fails loudly if either is+ * missing, so a renamed anchor reads as a broken pin rather than an empty, passing slice. */+function between(text: string, start: string, end: string): string {+ const from = text.indexOf(start)+ expect(from, `anchor not found: ${start}`).toBeGreaterThanOrEqual(0)+ const to = text.indexOf(end, from + start.length)+ expect(to, `end anchor not found after ${start}: ${end}`).toBeGreaterThan(from)+ return text.slice(from, to)+}++describe('TerminalNode reads its own session store', () => {+ it('the node badge reads the session store, not the default one', () => {+ expect(src).toMatch(/const agentStatusStore = useSessionStores\(\)\.agentStatus\.store/)+ expect(src).not.toMatch(/useAgentStatus\(\(s\) => s\.byId\[id\]\)/)+ expect(src).toMatch(/agentStatusStore\(\(s\) => s\.byId\[id\]\)/) // the bound store is its own hook+ expect(src).toMatch(/const status = agentStatusStore\(\(s\) => s\.byId\[id\]\)/)+ })++ it('focus paths set active and clear unread on the session store', () => {+ // No active/unread write anywhere in the node goes to the default store.+ expect(src).not.toMatch(/useAgentStatus\.getState\(\)\.setActive\(/)+ expect(src).not.toMatch(/useAgentStatus\.getState\(\)\.clearUnread\(/)+ expect(src).not.toMatch(/useAgentStatus\.getState\(\)\.activeId/)++ const enterNow = between(src, 'const enterNow = (opts?: { ack?: boolean }) => {', '\n }\n')+ expect(enterNow).toContain('agentStatusStore.getState().setActive(id, true)')+ expect(enterNow).toContain('agentStatusStore.getState().clearUnread(id)')++ const dwell = between(src, 'const onBodyEnter = () => {', 'const onBodyLeave = () => {')+ expect(dwell).toContain('agentStatusStore.getState().setActive(id, true)')+ expect(dwell).toContain('agentStatusStore.getState().clearUnread(id)')++ const clickToFocus = between(src, 'useClickToFocus({', '\n })\n')+ expect(clickToFocus).toContain('isActive: () => agentStatusStore.getState().activeId === id')+ expect(clickToFocus).toContain('setActive: (active) => agentStatusStore.getState().setActive(id, active)')++ expect(src).toMatch(/if \(selected\) agentStatusStore\.getState\(\)\.clearUnread\(id\)/)+ // The lifecycle teardown and the file insert (drop / paste) mark the node on its own store too.+ expect(src).toContain('agentStatusStore.getState().setActive(id, false)')+ const insertFiles = between(src, 'const insertFiles = async (', 'const onBodyDrop = async')+ expect(insertFiles).toContain('agentStatusStore.getState().setActive(id, true)')+ })++ it('Approve/Deny, title sync, transcript search and the chat view are gated', () => {+ expect(src).toContain('relayStatusGates(session.source)')+ expect(src).toMatch(/const gates = relayStatusGates\(session\.source\)/)++ // Approve/Deny JSX inside `gates.approvalButtons &&`, and the only answerPermission calls are+ // inside that block.+ const approve = between(+ src,+ "{gates.approvalButtons && status?.state === 'blocked' && status?.pendingId && (",+ '{isUnread && ('+ )+ expect(approve).toContain('<span className="term-node__approve nodrag">')+ const calls = src.match(/answerPermission/g) ?? []+ expect(calls.length).toBeGreaterThan(0)+ expect(approve.match(/answerPermission/g)?.length).toBe(calls.length)++ // The title-sync effect returns early unless gates.titleSync, and re-runs when it changes.+ const titleSync = between(src, 'if (!gates.titleSync) return\n if (!canReadTitleNode || data.titleAuto === false) return', '}, [')+ expect(titleSync).toContain('api.pty.readSessionName(')+ expect(src).toMatch(/\}, \[id, gates\.titleSync, canReadTitleNode, status\?\.sessionId, data\.titleAuto, updateNodeData\]\)/)++ // The find bar's transcript leg (and the label that promises it) follow the gate.+ expect(src).toMatch(/searchTranscript: gates\.transcriptSearch && claudeTranscript,/)+ expect(src).toMatch(/label=\{gates\.transcriptSearch && claudeTranscript \? 'Search terminal \+ conversation' : 'Search this terminal'\}/)++ // ⌘M: a relay node keeps the Markdown output view.+ expect(src).toMatch(/const chatAvailable = showChat && !!transcript\.sessionId && gates\.chatView/)+ })+})++describe('Canvas focus paths', () => {+ it("Canvas's two focus blocks clear unread through agentStatusForProject", () => {+ // The cross-project focus a project landing finishes: its owner is `project.id` by construction+ // (flowLanding runs it only once React Flow's store holds that project).+ const landing = between(canvas, 'const pending = pendingFocusRef.current', '}, 0)')+ expect(landing).toContain('agentStatusForProject(project.id).store')+ expect(landing).not.toMatch(/useAgentStatus\.getState\(\)\.(setActive|clearUnread)/)++ // focusNodeById, both of its branches (board card and canvas).+ const focus = between(canvas, 'const focusNodeById = useCallback(', 'const owner = nodeOwner(')+ expect(focus).not.toMatch(/useAgentStatus\.getState\(\)\.(setActive|clearUnread)/)+ expect(focus.match(/agentStatusForProject\(flowOwnerProjectIdRef\.current\)\.store/g)?.length).toBe(2)+ expect(focus.match(/\.clearUnread\(nodeId\)/g)?.length).toBe(2)++ // The flow-store owner, never the active project, decides which store a focus writes.+ expect(canvas).not.toMatch(/agentStatusForProject\([^)]*activeProjectId/)+ expect(canvas).toMatch(/flowOwnerProjectIdRef\.current = flowOwnerProjectId/)+ })+})diff --git a/src/renderer/session/agent-status-for-project.test.ts b/src/renderer/session/agent-status-for-project.test.tsnew file mode 100644index 000000000..4a19fead4--- /dev/null+++ b/src/renderer/session/agent-status-for-project.test.ts@@ -0,0 +1,183 @@+// @vitest-environment jsdom+//+// Bug D, Task 5: every surface that shows a project's node resolves the agent-status store through+// the session that PROJECT belongs to (`agentStatusForProject`), never through the active project+// and never the default store by assumption. A handed-off SSH project (local session, default store)+// and the team tab now serving it (relay session, its own keyless store) hold the SAME node ids, so+// asking the wrong store shows one project's status on the other's node.+import { act, createElement } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { NodeTerminalApi, Project } from '@shared/types'+import {+ OFFLINE_RELAY_SESSION_ID,+ agentStatusForProject,+ bindProjectToSession,+ createSession,+ disposeSession,+ getSessionStores,+ resetSessionsForTest,+ sessionRegistryVersion,+ setActiveSession,+ setOfflineRelayApiFactory,+ setSessionStatus,+ subscribeSessionRegistry,+ takeSessionOffline,+ unbindProject,+ useSessionRegistryVersion+} from './session'+import { defaultAgentStatus } from '../state/agentStatus'+import { useProjects } from '../state/projects'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++// In the app the local session's api IS `window.nodeTerminal`, and state/agentStatus.ts seeds its+// api memo with that object at module load, which is what makes the local session's store the+// DEFAULT one. Hoisted so the seed happens before that import evaluates, exactly as in the app.+const LOCAL_API = vi.hoisted(() => {+ const api = { marker: 'local' }+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = api+ return api+}) as unknown as NodeTerminalApi+const RELAY_API = { marker: 'relay' } as unknown as NodeTerminalApi+const OFFLINE_API = { marker: 'offline' } as unknown as NodeTerminalApi++// The field shape: a closed, handed-off SSH project and the team tab serving the same canvas.+const SSH_PROJECT = 'project-ssh-handed-off'+const TEAM_PROJECT = 'project-team-tab'+const NODE = 'term-shared-node'++const project = (id: string, remote: boolean): Project =>+ ({ id, name: id, color: '#888', nodes: [], ...(remote ? { remote: true } : {}) }) as unknown as Project++beforeEach(() => {+ resetSessionsForTest()+ setActiveSession(createSession('local', LOCAL_API, 'This machine').id)+ setOfflineRelayApiFactory(() => OFFLINE_API)+ useProjects.setState({ projects: [project(SSH_PROJECT, false), project(TEAM_PROJECT, true)], activeProjectId: SSH_PROJECT })+})++afterEach(() => {+ setOfflineRelayApiFactory(null)+ useProjects.setState({ projects: [], activeProjectId: '' })+ defaultAgentStatus.store.setState({ byId: {}, activeId: null })+ localStorage.clear()+})++describe('agentStatusForProject', () => {+ it('a relay-bound project resolves to its session store', () => {+ const relay = createSession('relay', RELAY_API, 'Team')+ bindProjectToSession(TEAM_PROJECT, relay.id)+ expect(agentStatusForProject(TEAM_PROJECT)).toBe(getSessionStores(relay.id).agentStatus)+ expect(agentStatusForProject(TEAM_PROJECT)).not.toBe(defaultAgentStatus)+ })++ it('a local or unknown project, and null, resolve to the default store', () => {+ // The app's wiring, which every assertion below relies on: the local session's store IS the+ // default (persisted) instance.+ expect(getSessionStores('local').agentStatus).toBe(defaultAgentStatus)+ for (const id of [SSH_PROJECT, 'project-never-heard-of', '', null, undefined]) {+ expect(agentStatusForProject(id), String(id)).toBe(defaultAgentStatus)+ }+ // A local-less registry (a node-environment caller, a test) never throws and still answers the+ // default store.+ resetSessionsForTest()+ expect(() => agentStatusForProject(null)).not.toThrow()+ expect(agentStatusForProject(SSH_PROJECT)).toBe(defaultAgentStatus)+ })++ it('an unbound remote project resolves to the offline session store, which is empty', () => {+ // Never bound: the team tab is remote in the projects store.+ const offline = getSessionStores(OFFLINE_RELAY_SESSION_ID).agentStatus+ expect(agentStatusForProject(TEAM_PROJECT)).toBe(offline)+ expect(offline).not.toBe(defaultAgentStatus)+ expect(offline.store.getState().byId).toEqual({})++ // Bound, then its session disposed (the last team tab closed): the dead session's statuses do+ // not follow the tab anywhere, and the default store is not where it lands either.+ const relay = createSession('relay', RELAY_API, 'Team')+ bindProjectToSession(TEAM_PROJECT, relay.id)+ getSessionStores(relay.id).agentStatus.store.getState().setState(NODE, 'working', 'claude')+ disposeSession(relay.id)+ expect(agentStatusForProject(TEAM_PROJECT)).toBe(offline)+ expect(agentStatusForProject(TEAM_PROJECT).store.getState().byId[NODE]).toBeUndefined()+ expect(defaultAgentStatus.store.getState().byId[NODE]).toBeUndefined()+ })++ it('the same node id reads different statuses in the relay project and the local one', () => {+ const relay = createSession('relay', RELAY_API, 'Team')+ bindProjectToSession(TEAM_PROJECT, relay.id)+ // default store: byId[NODE].sessionId 'ssh'; relay store: byId[NODE].state 'working'+ defaultAgentStatus.store.getState().setSessionId(NODE, 'ssh')+ getSessionStores(relay.id).agentStatus.store.getState().setState(NODE, 'working', 'claude')++ expect(agentStatusForProject(SSH_PROJECT).store.getState().byId[NODE]?.state).toBeUndefined()+ expect(agentStatusForProject(TEAM_PROJECT).store.getState().byId[NODE]?.state).toBe('working')+ expect(agentStatusForProject(SSH_PROJECT).store.getState().byId[NODE]?.sessionId).toBe('ssh')+ expect(agentStatusForProject(TEAM_PROJECT).store.getState().byId[NODE]?.sessionId).toBeUndefined()+ })+})++describe('the session registry signal', () => {+ it('the registry version moves on create, bind, offline and dispose', () => {+ const heard: number[] = []+ const unsubscribe = subscribeSessionRegistry(() => heard.push(sessionRegistryVersion()))+ let version = sessionRegistryVersion()+ const moves = (what: string, mutate: () => void): void => {+ mutate()+ expect(sessionRegistryVersion(), what).toBeGreaterThan(version)+ version = sessionRegistryVersion()+ }+ let relayId = ''+ moves('create', () => {+ relayId = createSession('relay', RELAY_API, 'Team').id+ })+ moves('bind', () => bindProjectToSession(TEAM_PROJECT, relayId))+ moves('status', () => setSessionStatus(relayId, 'connecting'))+ moves('offline', () => takeSessionOffline(relayId))+ moves('unbind', () => unbindProject(TEAM_PROJECT))+ moves('dispose', () => disposeSession(relayId))+ expect(heard).toHaveLength(6)++ // A call that changes nothing does not move it: a repeat create returns the existing session,+ // a second dispose / offline / status finds nothing, an unbind of an unbound project removes+ // nothing.+ createSession('local', LOCAL_API, 'This machine')+ disposeSession(relayId)+ takeSessionOffline(relayId)+ setSessionStatus(relayId, 'connected')+ unbindProject(TEAM_PROJECT)+ expect(sessionRegistryVersion()).toBe(version)+ // Nor does re-binding a project to the session it is already bound to, or re-asserting the+ // status a session already has.+ const again = createSession('relay', RELAY_API, 'Team again').id+ bindProjectToSession(TEAM_PROJECT, again)+ version = sessionRegistryVersion()+ bindProjectToSession(TEAM_PROJECT, again)+ setSessionStatus(again, 'connected')+ expect(sessionRegistryVersion()).toBe(version)+ expect(heard).toHaveLength(8)++ unsubscribe()+ createSession('relay', RELAY_API, 'Team once more')+ expect(heard).toHaveLength(8)+ })++ it('useSessionRegistryVersion re-renders its component on a registry change', async () => {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ function Probe() {+ return createElement('span', null, String(useSessionRegistryVersion()))+ }+ await act(async () => root.render(createElement(Probe)))+ const before = Number(host.textContent)+ await act(async () => {+ bindProjectToSession(TEAM_PROJECT, createSession('relay', RELAY_API, 'Team').id)+ })+ expect(Number(host.textContent)).toBe(sessionRegistryVersion())+ expect(Number(host.textContent)).toBeGreaterThan(before)+ await act(async () => root.unmount())+ host.remove()+ })+})diff --git a/src/renderer/session/session.ts b/src/renderer/session/session.tsindex 8b9fb9b8c..cd1c06dc0 100644--- a/src/renderer/session/session.ts+++ b/src/renderer/session/session.ts@@ -1,8 +1,8 @@-import { createContext, createElement, useContext, type ReactNode } from 'react'+import { createContext, createElement, useContext, useSyncExternalStore, type ReactNode } from 'react'import type { NodeTerminalApi } from '@shared/types'import type { PeerIdentity } from '@shared/presence'import { createPresenceSession, defaultPresence, type PresenceSession } from '../state/presence'-import { agentStatusForApi, type AgentStatusSession } from '../state/agentStatus'+import { agentStatusForApi, defaultAgentStatus, type AgentStatusSession } from '../state/agentStatus'import { useProjects } from '../state/projects'export type SessionSource = 'local' | 'relay' | 'server'@@ -59,6 +59,40 @@ let offline: Entry | null = null* reconnect re-binds the same id. */const KNOWN_REMOTE = new Set<string>()+/** The registry signal: a version bumped by every mutation that can change what a project resolves+ * to (a session created, disposed, taken offline or re-statused; a project bound or unbound), and+ * the listeners told about it. For readers that cache a per-project store resolution+ * (`agentStatusForProject`) and must re-resolve when the registry moves under them. */+let registryVersion = 0+const registryListeners = new Set<() => void>()++/** Bump the version and tell every listener, synchronously. Called only where the registry really+ * changed (a no-op call does not bump), never from a render path. */+function bumpRegistry(): void {+ registryVersion+++ for (const cb of [...registryListeners]) cb()+}++/** Subscribe to registry changes. Bumped on createSession, disposeSession, takeSessionOffline,+ * setSessionStatus, bind and unbind — each only when it changed something. Returns unsubscribe. */+export function subscribeSessionRegistry(cb: () => void): () => void {+ registryListeners.add(cb)+ return () => {+ registryListeners.delete(cb)+ }+}++/** The registry's current version (see `subscribeSessionRegistry`). Monotonic for the app run. */+export function sessionRegistryVersion(): number {+ return registryVersion+}++/** `useSyncExternalStore` over the registry signal: re-renders the caller whenever a session or a+ * binding changes, so a memoized `agentStatusForProject(id)` can be keyed on it. */+export function useSessionRegistryVersion(): number {+ return useSyncExternalStore(subscribeSessionRegistry, sessionRegistryVersion)+}+/** 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@@ -89,6 +123,7 @@ export function createSession(source: SessionSource, api: NodeTerminalApi, labelif (existing) return existing.sessionconst session: WorkspaceSession = { id, source, label, api, status: 'connected' }SESSIONS.set(id, { session, stores: buildStores(api), teardowns: [], disposed: false })+ bumpRegistry()return session}@@ -128,6 +163,7 @@ export function disposeSession(sessionId: string): void {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+ bumpRegistry()}/** Set a session's live status (Stage 4 Task 7 — a relay tab going offline / reconnecting). No-op@@ -135,7 +171,9 @@ export function disposeSession(sessionId: string): void {* label (and the offline gate) read the current state without re-registering the session. */export function setSessionStatus(sessionId: string, status: WorkspaceSession['status']): void {const e = SESSIONS.get(sessionId)- if (e) e.session.status = status+ if (!e || e.session.status === status) return+ e.session.status = status+ bumpRegistry()}/** Take a session OFFLINE on an INVOLUNTARY socket drop (host/relay gone) — the counterpart of a@@ -149,6 +187,7 @@ export function takeSessionOffline(sessionId: string): void {if (!e || e.disposed || e.session.status === 'offline') returnrunTeardowns(e)e.session.status = 'offline'+ bumpRegistry()}/** Test-only: clears the registry so each test starts with no sessions. The offline-session@@ -242,14 +281,16 @@ export function sessionCount(): number {* 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}`)+ const changed = PROJECT_BINDINGS.get(projectId) !== sessionIdPROJECT_BINDINGS.set(projectId, sessionId)if (useProjects.getState().getProject(projectId)?.remote) KNOWN_REMOTE.add(projectId)+ if (changed) bumpRegistry()}/** Unbind ONE project (a hosted team stopped sharing it, or the user closed that one of the team's* tabs). The session lives on for its other tabs. No-op when unbound. */export function unbindProject(projectId: string): void {- PROJECT_BINDINGS.delete(projectId)+ if (PROJECT_BINDINGS.delete(projectId)) bumpRegistry()}/** Every project bound to `sessionId` (a hosted team's tabs, live or greyed). */@@ -356,8 +397,15 @@ export function useSession(): WorkspaceSession {return s}+/** The stores of the session this subtree renders under. Render-safe, unlike `getSessionStores`: a+ * node can re-render under a session disposed a moment ago (the last team tab closed, a revoke)+ * before Canvas re-keys its provider, and a throw here would take the canvas down. Both stores are+ * memoized by api identity (`createPresenceSession`, `agentStatusForApi`), so `buildStores` on the+ * dead session's api returns the very instances its entry held — never a fresh twin, and nothing+ * is re-subscribed (a store's `connect()` is a separate, held teardown). */export function useSessionStores(): SessionStores {- return getSessionStores(useSession().id)+ const session = useSession()+ return entryFor(session.id)?.stores ?? buildStores(session.api)}/** The presence store for a session id, with the render-safe fallback the two accessors below share:@@ -391,6 +439,31 @@ export function presenceForProject(projectId: string): PresenceSession {return presenceForSession(null) // unbound → the local session's presence (defaultPresence in-app)}+/** The agent-status store of the session a project belongs to. Never throws; null/undefined → local.+ *+ * Resolves exactly as `presenceForProject` does: a project bound to a live session → that+ * session's store (a relay / team tab's keyless store, fed by `wireRelayAgentStatus`); an unbound+ * REMOTE project → the OFFLINE relay session's store, which no core feeds (a dead core's tab reads+ * Unknown, never the local user's table); every other id — local, unknown, '', null — → the local+ * session's store, which in the app IS `defaultAgentStatus`, falling back to `defaultAgentStatus`+ * in a local-less registry. NOT the active project's: a handed-off SSH project (local) and the team+ * tab serving it (relay) hold the same node ids, so a reader that asked the active project would+ * show one project's status on the other's node. Allocation-free; safe in render. A caller that+ * caches the result re-resolves on `useSessionRegistryVersion()`. */+export function agentStatusForProject(projectId: string | null | undefined): AgentStatusSession {+ if (projectId) {+ const bound = boundSessionForProject(projectId)+ if (bound) {+ const e = entryFor(bound.id)+ if (e) return e.stores.agentStatus+ }+ const off = offlineForUnboundRemote(projectId)+ if (off) return off.stores.agentStatus+ }+ const local = SESSIONS.get('local')+ return local ? local.stores.agentStatus : defaultAgentStatus+}+/** 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`)diff --git a/src/renderer/terminal/relay-status-gates.test.ts b/src/renderer/terminal/relay-status-gates.test.tsnew file mode 100644index 000000000..247a7fb4a--- /dev/null+++ b/src/renderer/terminal/relay-status-gates.test.ts@@ -0,0 +1,25 @@+import { describe, expect, it } from 'vitest'+import type { SessionSource } from '../session/session'+import { relayStatusGates } from './relay-status-gates'++// A team tab's node now reads its host's status: a blocked node carries `pendingId`, and its session+// id is known. These four readers act on THIS machine (or write the host's canvas), so a node whose+// core lives elsewhere must not run them.+describe('relayStatusGates', () => {+ it('relayStatusGates switches every local-only reader off for a relay session', () => {+ expect(relayStatusGates('relay')).toEqual({ approvalButtons: false, titleSync: false, transcriptSearch: false, chatView: false })+ })++ it('a local session keeps them all', () => {+ expect(Object.values(relayStatusGates('local')).every(Boolean)).toBe(true)+ })++ it('a remote-server session is refused like a relay one: its core is elsewhere too', () => {+ expect(relayStatusGates('server')).toEqual(relayStatusGates('relay'))+ })++ it('a source the table does not know fails closed', () => {+ expect(relayStatusGates('future' as SessionSource)).toEqual(relayStatusGates('relay'))+ expect(relayStatusGates('constructor' as SessionSource)).toEqual(relayStatusGates('relay'))+ })+})diff --git a/src/renderer/terminal/relay-status-gates.ts b/src/renderer/terminal/relay-status-gates.tsnew file mode 100644index 000000000..f3f4ef5eb--- /dev/null+++ b/src/renderer/terminal/relay-status-gates.ts@@ -0,0 +1,56 @@+import type { SessionSource } from '../session/session'++/**+ * Which status-driven readers a terminal node may run, by the session it renders under (bug D).+ *+ * A team tab's node now reads its HOST session's agent status (Task 5), so a blocked relay node+ * carries a `pendingId` and its agent session id is known. Each reader below turns that status into+ * an action on THIS machine, or a write to the host's canvas, so a node whose core lives elsewhere+ * must not run it:+ * - `approvalButtons`: Approve/Deny answer through `window.nodeTerminal.answerPermission`, the+ * LOCAL main's permission server, which holds no ticket for the host's session.+ * - `titleSync`: the session-name poll adopts the name into the node's title, i.e. writes the+ * host's canvas on a timer, from every tab that has the node mounted.+ * - `transcriptSearch`: the find bar's transcript leg reads `window.nodeTerminal.claude`, this+ * machine's transcripts — a stranger's session, or nothing, for the host's id.+ * - `chatView`: ⌘M opens the transcript view instead of the Markdown output view; the relay api+ * refuses its reads (`stub.chat`), so a relay node keeps the Markdown output view, which captures+ * the host's pane over the session api.+ *+ * Only `'local'` runs them. That is the Electron app AND the Server Edition's own browser session,+ * whose core is the server it is served from (the same reading `offscreenCoreIsRemote` takes).+ * `'relay'` and `'server'` (a tab whose core is a remote Server Edition) both mean the core is+ * elsewhere and get nothing — the same split `offscreenCoreIsRemote` draws. A value this table does+ * not know fails closed, like a relay session.+ */+export interface RelayStatusGates {+ approvalButtons: boolean+ titleSync: boolean+ transcriptSearch: boolean+ chatView: boolean+}++const ALL: RelayStatusGates = Object.freeze({+ approvalButtons: true,+ titleSync: true,+ transcriptSearch: true,+ chatView: true+})+const NONE: RelayStatusGates = Object.freeze({+ approvalButtons: false,+ titleSync: false,+ transcriptSearch: false,+ chatView: false+})++const GATES: Readonly<Record<SessionSource, RelayStatusGates>> = Object.freeze({+ local: ALL,+ relay: NONE,+ server: NONE+})++/** The gates for a node rendering under a session of `source`. A shared frozen object per source,+ * so a caller may read it in render and put its fields in effect deps. */+export function relayStatusGates(source: SessionSource): RelayStatusGates {+ return Object.hasOwn(GATES, source) ? GATES[source] : NONE+}