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(chat): ⌘M chat view falls back to the node's launch session id
review0faab7a79017
diff --git a/CLAUDE.md b/CLAUDE.mdindex cb49604f9..c7d0bd232 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3330,6 +3330,26 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`E_UNSUPPORTED`; ChatPanel catches it and says so instead of leaving the initial `[]` on screenas an empty conversation. Same `nodeId` rides `claude.readTranscript`, so the find-bar searchesa remote node's transcript too.+ **Which session id is read is ONE rule, `transcriptSessionFor`** (`renderer/lib/transcriptSession.ts`,+ 2026-10): the hook-confirmed `agentStatus.sessionId`, else the id the node was LAUNCHED with+ (`data.agentSessionId` — minted with `--session-id`, or the id "Open recent" resumed). The canvas+ node, the ⌘M hint, the kanban card, the card modal and its viewer all ask it. Before, Chat (and+ the meter) were gated on the hook id alone, so a node whose hook events never reached this app —+ an SSH session pinned for life to a dead hook endpoint, the 107-of-128 case in "A reused+ ControlMaster…" — opened "Markdown view" and showed no meter while its transcript sat on disk+ under an id the node itself had on record; others in the same project opened Chat. The fallback+ is HONEST, because the persisted id can be stale (`/clear` / `/resume` in the CLI moves to+ another session; nothing rewrites `agentSessionId` from hooks): (1) ChatPanel's+ `sessionFallback` prints one quiet line saying so, and the meter's popover says "From the session+ this node was started with"; (2) the read carries **no cwd** (`transcriptReadCwd`), because+ claude's resolver answers a missing id with the newest transcript in the folder — under a+ fallback id that would be a stranger's conversation; the remote locator globs by id without a+ cwd, so SSH nodes are still read on their host; (3) plan/question answer controls are never+ offered on a fallback thread (an answer is a WRITE bound to the live `held` ticket). The composer+ still sends (it types into the pane, which is right whatever the transcript). The persisted id is+ the CREATED agent's, which is exactly the agent both mount sites pick the reader by, and it is+ re-validated against `SAFE_SESSION_ID` (hand-editable project.json). The find bar's transcript+ index still uses the hook id only (it has claude's cwd fallback and no `remoteOnly` here).**Both channels live in `core/transcript-ipc.ts` (`registerTranscriptIpc`), so the ServerEdition serves them too** — it used to have no handler at all, which is why ⌘M in the browserread as an empty conversation on EVERY session. The remote leg is an injected depdiff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 83bf106ad..5528c8a80 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -2606,8 +2606,10 @@ export class PtyManager {// CREATES when the host's session died (that is exactly what `sessionExists` is asked ahead of,// and what `fresh` reports). What makes them override-less is narrower and true either way: the// relay host passes only `{cols, rows}` (host-service.ts), so those spawns carry no- // `ownerProjectId` — and no cwd, agent, account or hook env either. A mirrored client that- // lands on a re-created session gets the same bare login shell it got before this feature.+ // `ownerProjectId` — and no cwd, agent or account either. (They DO get the base hook env:+ // `persistKey` is set and `sshRemote` is not, so `buildPtyEnv(persistKey)` below runs — node id+ // and endpoint, but none of the agent-gated vars.) A mirrored client that lands on a re-created+ // session gets the same bare login shell it got before this feature.const projectOverrides = await this.projectSpawnOverrides(options)// Resolved HERE for the same synchronous-spawnSession reason as projectOverrides — and the// relay host's detached callers pass no `sshRemote` at all, so this is the one path that needsdiff --git a/src/renderer/canvas/toKanbanSession.ts b/src/renderer/canvas/toKanbanSession.tsindex 979385815..d4b193ed7 100644--- a/src/renderer/canvas/toKanbanSession.ts+++ b/src/renderer/canvas/toKanbanSession.ts@@ -60,7 +60,8 @@ export function toKanbanSession(n: CanvasNode): KanbanSession | null {accountId: n.data.accountId as string | undefined,ssh: n.data.ssh as SshConnection | undefined,sshRemoteTmux: !!n.data.sshRemoteTmux,- terminalFontSize: n.data.terminalFontSize as number | undefined+ terminalFontSize: n.data.terminalFontSize as number | undefined,+ agentSessionId: n.data.agentSessionId as string | undefined}}}diff --git a/src/renderer/canvas/toKanbanSessionState.ts b/src/renderer/canvas/toKanbanSessionState.tsindex a7aef2d93..60757faf7 100644--- a/src/renderer/canvas/toKanbanSessionState.ts+++ b/src/renderer/canvas/toKanbanSessionState.ts@@ -53,7 +53,8 @@ export function toKanbanSessionState(n: CanvasNodeState): KanbanSession | null {accountId: n.accountId,ssh: n.ssh,sshRemoteTmux: !!n.sshRemoteTmux,- terminalFontSize: n.terminalFontSize+ terminalFontSize: n.terminalFontSize,+ agentSessionId: n.agentSessionId}return {id: n.id,diff --git a/src/renderer/components/ContextMeter.tsx b/src/renderer/components/ContextMeter.tsxindex 1aa527503..edbe0dcdf 100644--- a/src/renderer/components/ContextMeter.tsx+++ b/src/renderer/components/ContextMeter.tsx@@ -8,11 +8,14 @@ import { barFillPercent, contextFillColor, contextPillText, formatModelLabel, fo* Per-Claude-node context-window meter. A small header pill (mini-bar + "NN%") that toggles* a popover with token figures and model. Renders nothing until the session has usage data.*/-export function ContextMeter({ sessionId, nodeId, remote = false, agentId }: {+export function ContextMeter({ sessionId, nodeId, remote = false, agentId, fromLaunchId = false }: {sessionId: string | nullnodeId?: stringremote?: booleanagentId?: string+ /** `sessionId` is the node's persisted launch id, not a hook-confirmed one+ * (lib/transcriptSession.ts): the popover says so, since it may be an older session. */+ fromLaunchId?: boolean}): JSX.Element | null {const scoped = remote && !!agentId && capabilityAgentId(agentId) === 'codex'// A copied rollout has the same session id on two hosts. SSH Codex observations belong@@ -57,6 +60,9 @@ export function ContextMeter({ sessionId, nodeId, remote = false, agentId }: {gemini joined USAGE_CAPABLE — a codex popover would have claimed to be claude. */}{usage.model ? `${usage.model} · ` : ''}Updated {formatTimeAgo(usage.updatedAt)}</div>+ {fromLaunchId && (+ <div className="ctx-popover__sub">From the session this node was started with.</div>+ )}</div>)}<buttondiff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 82b486aab..b2760b235 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -63,6 +63,7 @@ import { NoteMarkdown } from '../NoteMarkdown'import { relativeTime } from '../../lib/relativeTime'import { TerminalMarkdownView } from '../../nodes/TerminalMarkdownView'import { canChat } from '@shared/agents/config'+import { transcriptSessionFor } from '../../lib/transcriptSession'import { effectiveAccountId } from '../../lib/accountChip'import { useSettings } from '../../state/settings'import { chipFor, commandTooltip } from '../../lib/keybindingOverrides'@@ -192,7 +193,14 @@ export function CardModal({ session, projectId, projectName, projectColor, columconst createdAgent = session.agentId ?? session.spawn.agentIdconst claudeAccounts = useSettings((s) => s.settings.claudeAccounts)const accountForReads = effectiveAccountId(session.spawn.accountId, observedAccount, claudeAccounts)- const useChat = mdOpen && !!createdAgent && canChat(createdAgent) && !!agentSessionId+ // The same session rule as the canvas node (lib/transcriptSession.ts): the hook-confirmed id, else+ // the id the node was launched with — so a node whose hooks never reach this app still gets Chat.+ const transcript = transcriptSessionFor({+ live: agentSessionId,+ persisted: session.spawn.agentSessionId,+ cwd: session.spawn.cwd+ })+ const useChat = mdOpen && !!createdAgent && canChat(createdAgent) && !!transcript.sessionIdconst captureFull = useCallback((nodeId: string) => api.pty.capture(nodeId, true), [api])const mdChip = chipFor('node.toggleMarkdown')// The chord (main-intercepted on desktop, bridged in the browser) toggles THIS view while the@@ -499,7 +507,7 @@ export function CardModal({ session, projectId, projectName, projectColor, colum{isTerminal && (<>{/* Same context-window pill + popover as the node header (null until usage data). */}- <ContextMeter sessionId={agentSessionId ?? null} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? observedAgentId} />+ <ContextMeter sessionId={transcript.sessionId ?? null} fromLaunchId={transcript.fallback} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? observedAgentId} /><buttonclassName="kanban-modal__action"title={commandTooltip(mdOpen ? 'Back to the live terminal' : 'Markdown / chat view', 'node.toggleMarkdown')}@@ -667,7 +675,8 @@ export function CardModal({ session, projectId, projectName, projectColor, colum<ChatPanelkey={session.id}nodeId={session.id}- sessionId={agentSessionId}+ sessionId={transcript.sessionId}+ sessionFallback={transcript.fallback}cwd={session.spawn.cwd}accountId={accountForReads}agentId={createdAgent!}diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsxindex aacd07a47..a67f1777c 100644--- a/src/renderer/components/kanban/ModalTerminal.tsx+++ b/src/renderer/components/kanban/ModalTerminal.tsx@@ -1,4 +1,5 @@import { useContextEnsure } from '../../terminal/useContextEnsure'+import { transcriptSessionFor } from '../../lib/transcriptSession'import { FIND_DECORATIONS } from '../../lib/palette'import { ptyRefusal } from '@shared/pty-refusal'@@ -101,6 +102,9 @@ export interface ModalSpawn {* the SAME session, so it renders at the node's size, not the global one — and, being a* co-attach subscriber, re-reports its grid when that changes like any font change. */terminalFontSize?: number+ /** The session id the node was launched with (`data.agentSessionId`) — the transcript readers'+ * fallback when no hook confirmed one (lib/transcriptSession.ts). Never used to spawn. */+ agentSessionId?: string}/**@@ -196,7 +200,9 @@ export function ModalTerminal({const observedAccount = useAgentStatus((s) => s.byId[nodeId]?.account)// …resolved against the live account list, so linking the dir repoints the reader at once.const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)- useContextEnsure(api.context, nodeId, spawn.agentId ?? observedAgentId, agentSessionId, spawn.cwd,+ // MIRROR TerminalNode: the meter's rehydration reads the same session the ⌘M view does.+ const transcript = transcriptSessionFor({ live: agentSessionId, persisted: spawn.agentSessionId, cwd: spawn.cwd })+ useContextEnsure(api.context, nodeId, spawn.agentId ?? observedAgentId, transcript.sessionId, transcript.cwd,effectiveAccountId(spawn.accountId, observedAccount, claudeAccounts))// One shallow-compared subscription for the whole appearance slice — see useXtermVisualSettings.// MIRROR TerminalNode: scoped to the OWNING project (`owningProjectId`, the active one — a modaldiff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex 08f4fb360..b846d0910 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -6,6 +6,7 @@ import { LiveLinkChip, showsLiveLinks } from '../LiveLinkChip'import type { SessionSource } from '../../session/session'import { useWatchLinks } from '../../state/watchLinks'import { ContextMeter } from '../ContextMeter'+import { transcriptSessionFor } from '../../lib/transcriptSession'import { isRemoteSessionNode } from '@shared/worktree'import { NodeIconView } from '../NodeIcon'import { LabelChips } from './LabelChips'@@ -66,6 +67,8 @@ export const SessionCard = memo(function SessionCard({// (see its loopSig comment) and StatusAwareMiniMap demonstrates: subscribe where the value is// read, so the re-render is confined to the one thing that changed.const status = useAgentStatus((s) => s.byId[session.id])+ // The card's meter follows the same session rule as the node and the card modal.+ const cardTranscript = transcriptSessionFor({ live: status?.sessionId, persisted: session.spawn.agentSessionId, cwd: session.spawn.cwd })// The board is the canvas's other view of the same node (CONTRIBUTING), so the card carries the// node header's account chip from the same helper — created-with account, else what the session// was observed running as.@@ -230,7 +233,7 @@ export const SessionCard = memo(function SessionCard({<span className="kanban-card__stickytext">{stickyPreview}</span>) : (<>- <ContextMeter sessionId={status?.sessionId ?? null} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? status?.agentId} />+ <ContextMeter sessionId={cardTranscript.sessionId ?? null} fromLaunchId={cardTranscript.fallback} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? status?.agentId} /><AccountChip chip={accountChip} /><LiveLinkChip nodeId={session.id} source={liveLinkSource} className="kanban-card__live" />{sessionName && (diff --git a/src/renderer/lib/transcriptSession.test.ts b/src/renderer/lib/transcriptSession.test.tsnew file mode 100644index 000000000..fc91be390--- /dev/null+++ b/src/renderer/lib/transcriptSession.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'vitest'+import { transcriptSessionFor } from './transcriptSession'++const LIVE = '11111111-1111-4111-8111-111111111111'+const MINTED = '22222222-2222-4222-8222-222222222222'++describe('transcriptSessionFor', () => {+ it('prefers the hook-confirmed id and keeps the cwd', () => {+ expect(transcriptSessionFor({ live: LIVE, persisted: MINTED, cwd: '/w' })).toEqual({+ sessionId: LIVE,+ fallback: false,+ cwd: '/w'+ })+ })++ it('falls back to the persisted launch id when no hook ever named one', () => {+ expect(transcriptSessionFor({ live: undefined, persisted: MINTED, cwd: '/w' })).toEqual({+ sessionId: MINTED,+ fallback: true,+ // strictly by id: claude's cwd-newest fallback must not answer for a stale launch id+ cwd: undefined+ })+ expect(transcriptSessionFor({ live: null, persisted: ` ${MINTED} `, cwd: '/w' }).sessionId).toBe(MINTED)+ expect(transcriptSessionFor({ live: '', persisted: MINTED, cwd: '/w' }).fallback).toBe(true)+ })++ it('refuses a persisted id that is not a safe session id (hand-edited project.json)', () => {+ for (const bad of ['-rf', '../x', 'a b', '$(id)', '', ' ', 42, {}, null, 'x'.repeat(300)]) {+ expect(transcriptSessionFor({ live: undefined, persisted: bad, cwd: '/w' })).toEqual({+ sessionId: undefined,+ fallback: false,+ cwd: '/w'+ })+ }+ })++ it('has nothing to offer when neither id is known', () => {+ expect(transcriptSessionFor({ live: undefined, persisted: undefined, cwd: undefined })).toEqual({+ sessionId: undefined,+ fallback: false,+ cwd: undefined+ })+ })+})diff --git a/src/renderer/lib/transcriptSession.ts b/src/renderer/lib/transcriptSession.tsnew file mode 100644index 000000000..74f9ca410--- /dev/null+++ b/src/renderer/lib/transcriptSession.ts@@ -0,0 +1,65 @@+import { SAFE_SESSION_ID } from '@shared/session-id'++/**+ * Which session a node's transcript READERS (the ⌘M chat view, the context meter's mount-time+ * rehydration) look at — the one rule the canvas node and the kanban card modal share.+ *+ * Two sources, in this order (the same order cold restore uses, `TerminalNode`'s `priorId`):+ * 1. the LIVE id a hook reported (`agentStatus.sessionId`) — it follows `/clear`, `/resume` and+ * `--fork-session` moving the CLI to another session, so it is the only one that can be current;+ * 2. the id nodeterm launched the node with and persisted (`data.agentSessionId` — minted with+ * `--session-id`, or the id "Open recent" resumed).+ * Without (2) a node whose hooks never reach this app — an SSH session pinned to a dead hook tunnel+ * for its whole life, a session started where no hook endpoint was advertised — could NEVER open the+ * chat view or show a meter: it fell back to the markdown-of-output view while its transcript sat on+ * disk under an id the node itself had on record.+ *+ * The fallback is honest about what it is (`fallback: true`), because the persisted id can be STALE:+ * a `/clear` or `/resume` inside the CLI moves it to another session while the node's record stays.+ * Callers must therefore:+ * - say so in the view (the chat panel prints one quiet line);+ * - never use it for anything that WRITES or answers (plan/question answer cards stay bound to the+ * live `held` ticket, which only a hook can deliver);+ * - read it STRICTLY by id — `cwd` comes back `undefined` here, because claude's resolver falls back+ * to the NEWEST transcript in the cwd when the id misses (a cleaned-up transcript, an id that+ * never ran), and under a fallback id that would put a stranger's conversation on screen under+ * "the conversation this node was started with". A remote node's host locator globs by id without+ * a cwd, so the remote leg is unaffected.+ *+ * The persisted id belongs to the node's CREATED agent (`createdAgentId(data)`), which is exactly the+ * agent both mount sites pick the reader by — so the fallback can never hand one agent's id to+ * another agent's resolver. Keep it that way: do not feed it to a reader chosen by an observed agent.+ *+ * `persisted` is hand-editable project.json data, so it is re-validated against `SAFE_SESSION_ID`+ * rather than trusted by type; an invalid one is simply no fallback. The live id is passed through+ * as before (its own validation lives where hook events are ingested).+ */+export interface TranscriptSession {+ /** The id to read by; `undefined` = no session known (the view stays on the output markdown). */+ sessionId: string | undefined+ /** True when `sessionId` is the node's persisted launch id, not one a hook confirmed. */+ fallback: boolean+ /** The cwd to hand the reader: the node's own for a hook-confirmed id, `undefined` for a fallback. */+ cwd: string | undefined+}++export function transcriptSessionFor(input: {+ live: string | null | undefined+ persisted: unknown+ cwd: string | undefined+}): TranscriptSession {+ if (input.live) return { sessionId: input.live, fallback: false, cwd: input.cwd }+ const p = typeof input.persisted === 'string' ? input.persisted.trim() : ''+ if (p && SAFE_SESSION_ID.test(p)) return { sessionId: p, fallback: true, cwd: transcriptReadCwd(input.cwd, true) }+ return { sessionId: undefined, fallback: false, cwd: input.cwd }+}++/** The cwd a transcript READ may carry: none for a fallback id (see above). The chat panel asks+ * this itself because it also needs the node's real cwd for the composer's `@` file list. */+export function transcriptReadCwd(cwd: string | undefined, fallback: boolean): string | undefined {+ return fallback ? undefined : cwd+}++/** The chat panel's one quiet line while it reads the fallback id. */+export const FALLBACK_SESSION_NOTE =+ 'Showing the conversation this node was started with — it may be older if the session changed in the terminal.'diff --git a/src/renderer/nodes/ChatPanel.sessionFallback.test.tsx b/src/renderer/nodes/ChatPanel.sessionFallback.test.tsxnew file mode 100644index 000000000..cf25a6ec2--- /dev/null+++ b/src/renderer/nodes/ChatPanel.sessionFallback.test.tsx@@ -0,0 +1,107 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ChatMessage } from '@shared/types'+import type { HeldPermission } from '@shared/agents/permission-answer'+import { useAgentStatus } from '../state/agentStatus'+import { FALLBACK_SESSION_NOTE } from '../lib/transcriptSession'++/**+ * The ⌘M panel reading a node's PERSISTED launch id (no hook-confirmed one — lib/transcriptSession.ts).+ * Pins the three honesty rules: the quiet note is shown, the read carries NO cwd (claude's resolver+ * would otherwise answer a missing id with the newest transcript in that folder — another session),+ * and plan/question answer controls are never offered (an answer is a write bound to the live ticket).+ */++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const { session, reads, readTranscript } = vi.hoisted(() => {+ const reads: { messages: unknown[] } = { messages: [] }+ const readTranscript = vi.fn(async (..._args: unknown[]) => ({+ messages: reads.messages,+ found: true,+ olderCursor: null,+ unmatchedResults: []+ }))+ const session = {+ api: {+ chat: { readTranscript },+ pty: { sendText: vi.fn(async () => true as const) },+ answerPermission: vi.fn(async () => true)+ }+ }+ return { session, reads, readTranscript }+})+vi.mock('../session/session', () => ({ useSession: () => session }))++import { ChatPanel } from './ChatPanel'++const NODE = 'n-chat-fallback'+let host: HTMLDivElement+let root: Root++const planMsg: ChatMessage = {+ role: 'assistant',+ key: 0,+ parts: [{ kind: 'tool', name: 'ExitPlanMode', arg: '', body: '# Plan' }]+}++async function mount(props: { sessionFallback?: boolean }): Promise<void> {+ await act(async () => {+ root.render(<ChatPanel nodeId={NODE} sessionId="s-minted" cwd="/work/repo" agentId="claude" {...props} />)+ })+}+const note = (): string | null => host.querySelector('.term-chat__fallback-note')?.textContent ?? null+const answerButtons = (): number => host.querySelectorAll('.term-chat__tool-card button').length++beforeEach(() => {+ readTranscript.mockClear()+ reads.messages = [planMsg]+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(async () => {+ await act(async () => root.unmount())+ host.remove()+ useAgentStatus.setState((s) => {+ const byId = { ...s.byId }+ delete byId[NODE]+ return { byId }+ })+})++async function holdPlan(): Promise<void> {+ const held: HeldPermission = { pendingId: 'p-1', toolName: 'ExitPlanMode' }+ await act(async () => {+ useAgentStatus.getState().setState(NODE, 'blocked', 'claude', false, held.pendingId, true, false, held)+ })+}++describe('ChatPanel on a fallback session id', () => {+ it('says it is showing the launch conversation and reads strictly by id', async () => {+ await mount({ sessionFallback: true })+ expect(note()).toBe(FALLBACK_SESSION_NOTE)+ expect(readTranscript).toHaveBeenCalled()+ for (const call of readTranscript.mock.calls) {+ expect(call[0]).toBe('s-minted')+ expect(call[1]).toBeUndefined() // no cwd: no cwd-newest fallback to another session+ }+ })++ it('never offers answer controls, even while a matching plan ticket is held', async () => {+ await holdPlan()+ await mount({ sessionFallback: true })+ expect(host.querySelectorAll('.term-chat__tool-card').length).toBe(1)+ expect(answerButtons()).toBe(0)+ })++ it('a hook-confirmed id is unchanged: no note, cwd carried, controls offered', async () => {+ await holdPlan()+ await mount({})+ expect(note()).toBeNull()+ expect(readTranscript.mock.calls[0][1]).toBe('/work/repo')+ expect(answerButtons()).toBeGreaterThan(0)+ })+})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 83fc38b88..842daedef 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -43,6 +43,7 @@ import type { PermissionAnswer } from '@shared/agents/permission-answer'import { ChatComposer } from './ChatComposer'import { ChatTurnActions } from './ChatTurnActions'import { assistantTurnEnds } from '../lib/chatThread'+import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.@@ -98,6 +99,13 @@ interface ChatPanelProps {* index (this machine, or a relay peer's core).*/sshProjectId?: string+ /**+ * `sessionId` is the node's PERSISTED launch id, not one a hook confirmed (lib/transcriptSession.ts).+ * It can be stale after a `/clear` or `/resume` inside the CLI, so the panel says so in one quiet+ * line, reads strictly by id (no cwd — claude's cwd-newest fallback would show another session),+ * and never offers plan/question answer controls. Absent = a hook-confirmed id, as before.+ */+ sessionFallback?: boolean}/**@@ -186,14 +194,17 @@ export function ChatPanel({hint,pathsForFiles,onShowTerminal,- sshProjectId+ sshProjectId,+ sessionFallback}: ChatPanelProps) {// This node's core api (stable for the session — the chat transcript and the tmux session// both live on the core this panel's project belongs to).const { api, source } = useSession()// Which transcript this panel reads. Keys are byte offsets into ONE file, so a thread is only// ever merged with a read of the same identity (see lib/chatPaging.ts).- const identity = JSON.stringify([nodeId, sessionId ?? null, cwd ?? null, accountId ?? null, agentId])+ // The cwd a transcript read carries: none while reading the fallback id (the composer keeps `cwd`).+ const readCwd = transcriptReadCwd(cwd, sessionFallback === true)+ const identity = JSON.stringify([nodeId, sessionId ?? null, readCwd ?? null, accountId ?? null, agentId])const [thread, setThread] = useState<ChatThread>(() => emptyThread(identity))const messages = thread.messages// Read by the async handlers, which must decide against the thread as it is NOW, not as it was@@ -270,8 +281,13 @@ export function ChatPanel({const [boundCard, setBoundCard] = useState<(BoundAnswerCard & { identity: string }) | null>(null)const previousBound = boundCard && boundCard.identity === identity ? boundCard : nullconst cardState = useMemo(- () => (!readOnly && refusal === 'dialog' ? answerCardState(messages, held, threadHeldFor, previousBound) : null),- [readOnly, refusal, messages, held, threadHeldFor, previousBound]+ // Never on a fallback id: an answer is a WRITE bound to the live `held` ticket, and a thread read+ // from the node's launch id may not be the conversation that ticket belongs to.+ () =>+ !readOnly && !sessionFallback && refusal === 'dialog'+ ? answerCardState(messages, held, threadHeldFor, previousBound)+ : null,+ [readOnly, sessionFallback, refusal, messages, held, threadHeldFor, previousBound])const answerCard = cardState?.kind === 'active' ? cardState : nullconst updatingCard = cardState?.kind === 'updating' ? cardState.card : null@@ -381,7 +397,7 @@ export function ChatPanel({// keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently// presenting itself as an empty conversation. Only the newest TAIL window is read — older// history pages in on scroll-up, and a reload merges by key instead of discarding it.- void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {+ void api.chat.readTranscript(sessionId, readCwd, accountId, nodeId, agentId, {maxBytes: CHAT_TAIL_PAGE_BYTES,// A hook-driven refresh the user did not ask for: an expensive reader (opencode's export) may// space these out. An open, ↻, Retry or a held-request rebind is never marked.@@ -449,7 +465,7 @@ export function ChatPanel({settleHeldReload(threadHeldForRef.current)})- }, [api, sessionId, cwd, accountId, nodeId, agentId, identity])+ }, [api, sessionId, readCwd, accountId, nodeId, agentId, identity])loadRef.current = load// Fetch the next OLDER page and prepend it. One in flight at a time; a result that arrives@@ -477,7 +493,7 @@ export function ChatPanel({})}}- void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {+ void api.chat.readTranscript(sessionId, readCwd, accountId, nodeId, agentId, {before,maxBytes: CHAT_OLDER_PAGE_BYTES}).then(@@ -499,7 +515,7 @@ export function ChatPanel({setOlderState('error')})- }, [api, sessionId, cwd, accountId, nodeId, agentId, identity, thread.olderCursor, thread.identity])+ }, [api, sessionId, readCwd, accountId, nodeId, agentId, identity, thread.olderCursor, thread.identity])// Initial load.useEffect(() => {@@ -892,6 +908,11 @@ export function ChatPanel({<span className="term-chat__hint">{hint ?? (mdChip ? `${mdChip} to exit` : 'Exit')}</span></span></div>+ {sessionFallback && (+ <div className="term-chat__fallback-note" role="note">+ {FALLBACK_SESSION_NOTE}+ </div>+ )}<div className="term-chat__msgs" ref={msgsRef} onScroll={onScroll}>{initialLoading && (<ChatLoadingStatus text={EMPTY_TEXT.loading.title} />diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex fede07c04..d21d4111c 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -228,6 +228,7 @@ import { IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyimport { NodeLabels } from '../components/kanban/NodeLabels'import { MdViewHintButton } from '../components/MdViewHintButton'import { mdViewHint } from '../lib/mdViewHint'+import { transcriptSessionFor } from '../lib/transcriptSession'import { Tooltip } from '../components/Tooltip'import { useTerminalSearch } from '../terminal/useTerminalSearch'import { useCopyFeedback } from '../terminal/useCopyFeedback'@@ -2219,13 +2220,21 @@ export function TerminalNode({.map((depId) => ((getNode(depId) as CanvasNode | undefined)?.data.title as string) || depId).join(', '): ''+ // Which session this node's transcript READERS look at: the hook-confirmed id, else the id the+ // node was launched with (`data.agentSessionId`) — ONE rule shared with the kanban card modal+ // (lib/transcriptSession.ts). A fallback reads strictly by id and says so in the chat panel.+ const transcript = transcriptSessionFor({+ live: status?.sessionId,+ persisted: data.agentSessionId,+ cwd: (data.cwd as string) || undefined+ })// Use the chat panel only for a chat-capable agent with a known session; otherwise the// 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 && !!status?.sessionId+ const chatAvailable = showChat && !!transcript.sessionIdconst useChat = mdMode && chatAvailable- useContextEnsure(session.api.context, id, agentId, status?.sessionId, (data.cwd as string) || undefined, accountForReads)+ useContextEnsure(session.api.context, id, agentId, transcript.sessionId, transcript.cwd, accountForReads)const updateNodeInternals = useUpdateNodeInternals()const [searchOpen, setSearchOpen] = useState(false)@@ -6178,7 +6187,7 @@ export function TerminalNode({SSH {(data.ssh as SshConnection).user}@{(data.ssh as SshConnection).host}</span>) : null}- {showUsage && <ContextMeter sessionId={status?.sessionId ?? null} nodeId={id} remote={!!remoteSession} agentId={agentId} />}+ {showUsage && <ContextMeter sessionId={transcript.sessionId ?? null} fromLaunchId={transcript.fallback} nodeId={id} remote={!!remoteSession} agentId={agentId} />}{/* Who else is in this node. Subscribes to presence itself — see PresenceChips. */}<PresenceChips nodeId={id} />{/* This terminal is broadcast by a live link — never hideable (live-link.guard.test.ts).@@ -6803,7 +6812,8 @@ export function TerminalNode({<Suspense fallback={<ChatPanelFallback />}><ChatPanelnodeId={id}- sessionId={status?.sessionId}+ sessionId={transcript.sessionId}+ sessionFallback={transcript.fallback}cwd={data.cwd as string | undefined}// A READER (the ⌘M transcript view) takes the account the session actually RUNS// as, never the creation-time one, so a plain terminal launched underdiff --git a/src/renderer/nodes/chat-session-fallback-wiring.test.ts b/src/renderer/nodes/chat-session-fallback-wiring.test.tsnew file mode 100644index 000000000..3c76d099a--- /dev/null+++ b/src/renderer/nodes/chat-session-fallback-wiring.test.ts@@ -0,0 +1,62 @@+// The ⌘M Chat view (and the context meter) on a node whose hooks never reached this app.+//+// The RULE is pure and tested in `lib/transcriptSession.test.ts`, and ChatPanel's honesty half in+// `ChatPanel.sessionFallback.test.tsx`. What only the source can show is that every place that+// picks "the session to read this node's transcript by" asks that ONE rule — the canvas node, the+// kanban card, the card modal and its live viewer — and hands the panel the `sessionFallback` flag.+// Before this, the canvas node gated Chat on `!!status?.sessionId` alone, so a node whose hook+// events never arrived (an SSH session pinned to a dead hook tunnel) could never open Chat or show+// a meter, while the session id it was launched with sat in `data.agentSessionId`.++import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'+import { toKanbanSession } from '../canvas/toKanbanSession'+import { toKanbanSessionState } from '../canvas/toKanbanSessionState'+import type { CanvasNode } from '../state/workspace'+import type { CanvasNodeState } from '@shared/types'++const read = (rel: string): string =>+ fs.readFileSync(path.resolve(__dirname, rel), 'utf8').replace(/\r\n/g, '\n')++const terminalNode = read('TerminalNode.tsx')+const cardModal = read('../components/kanban/CardModal.tsx')+const modalTerminal = read('../components/kanban/ModalTerminal.tsx')+const sessionCard = read('../components/kanban/SessionCard.tsx')++describe('chat view session fallback wiring', () => {+ it('the canvas node gates Chat, the ⌘M hint and the meter on the shared rule', () => {+ expect(terminalNode).toContain('transcriptSessionFor({')+ expect(terminalNode).toContain('persisted: data.agentSessionId')+ expect(terminalNode).toMatch(/const chatAvailable = showChat && !!transcript\.sessionId/)+ expect(terminalNode).not.toMatch(/chatAvailable = showChat && !!status\?\.sessionId/)+ expect(terminalNode).toMatch(/useContextEnsure\([^)]*transcript\.sessionId, transcript\.cwd/)+ expect(terminalNode).toMatch(/sessionId=\{transcript\.sessionId\}\s*\n\s*sessionFallback=\{transcript\.fallback\}/)+ expect(terminalNode).toMatch(/sessionId=\{transcript\.sessionId \?\? null\}/)+ })++ it('the card modal uses the same rule for Chat and its meter', () => {+ expect(cardModal).toContain('transcriptSessionFor({')+ expect(cardModal).toContain('persisted: session.spawn.agentSessionId')+ expect(cardModal).toMatch(/canChat\(createdAgent\) && !!transcript\.sessionId/)+ expect(cardModal).toMatch(/sessionId=\{transcript\.sessionId\}\s*\n\s*sessionFallback=\{transcript\.fallback\}/)+ expect(cardModal).toMatch(/<ContextMeter sessionId=\{transcript\.sessionId \?\? null\}/)+ })++ it('the modal viewer and the board card ask it too', () => {+ expect(modalTerminal).toMatch(/transcriptSessionFor\(\{ live: agentSessionId, persisted: spawn\.agentSessionId/)+ expect(sessionCard).toMatch(/transcriptSessionFor\(\{ live: status\?\.sessionId, persisted: session\.spawn\.agentSessionId/)+ })++ it('both card projections carry the persisted id to the board', () => {+ const live = {+ id: 't1',+ type: 'terminal',+ position: { x: 0, y: 0 },+ data: { title: 'x', agentId: 'claude', agentSessionId: 'sess-1' }+ } as unknown as CanvasNode+ expect(toKanbanSession(live)?.spawn.agentSessionId).toBe('sess-1')+ const stored = { id: 't1', kind: 'terminal', agentId: 'claude', agentSessionId: 'sess-1' } as unknown as CanvasNodeState+ expect(toKanbanSessionState(stored)?.spawn.agentSessionId).toBe('sess-1')+ })+})diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 937600e7d..dcbdf01ec 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -3248,6 +3248,16 @@ body,.term-chat__hint {opacity: 0.6;}+/* The view is reading the node's persisted launch id, not a hook-confirmed one (ChatPanel+ `sessionFallback`): one quiet line, never an alarm — it is usually the right conversation. */+.term-chat__fallback-note {+ flex: 0 0 auto;+ padding: 4px 12px;+ font-size: 11px;+ line-height: 1.4;+ color: var(--muted);+ border-bottom: 1px solid rgba(var(--tint-rgb), 0.06);+}.term-chat__msgs {flex: 1 1 auto;overflow-y: auto;