Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(canvas): keep a closed session's transcript readable

enes546456e04c5c
diff --git a/CLAUDE.md b/CLAUDE.md
index 588ebeaec..02029c4ce 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -379,6 +379,24 @@ project's nodes only.** The contract:
count). Server Edition: all renderer-side; the ws-bridge `sessionMemory` is real, so badges
describe the server machine; the `sshProject` legs only run for `project.ssh`, which that
shell never has.
+- **Closing a NODE keeps a pointer to its transcript** (issue #531). The per-project
+ `closedSessions` ledger records the agent session id as `ClosedSessionEntry.sessionId`, captured
+ at delete time from the live `agentStatus` entry — which that same delete drops, so this is the
+ last instant it exists anywhere — falling back to the minted `node.agentSessionId`. It is a
+ POINTER, never a copy: the `.jsonl` the agent CLI owns stays the only text, and a second store of
+ transcript text would age, drift and need its own retention policy. The "Recently closed" row
+ spends it on the **existing ⌘M reader** (`ChatPanel` in `readOnly` mode, hosted by
+ `ClosedTranscriptDialog`), so resolution, the `{found}` vs empty distinction and Retry cannot
+ drift from the live-node path. Two rules: it rides `IndexEntryV3.closedSessions` and is therefore
+ **machine-local** — a session id is a `$HOME`-anchored fact about one person's machine, and
+ `projectToFile` must never emit it — and it is **re-checked as a string** in
+ `sanitizeLoadedClosedSessions`, because workspace.json is hand-editable and the value goes
+ straight to a resolver. `closedTranscriptTarget` (pure) owns the refusals and NAMES each: a
+ REMOTE session is refused (its transcript is on the host; locating it over the ControlMaster is
+ separate work and must not hold the local fix hostage) and a pre-#531 entry says its id was never
+ recorded. Only the "this was never an agent" refusal may render as nothing — for the others a
+ vanished control would leave the user believing that closing destroyed the record, which is the
+ belief this exists to correct.
- A project's `cwd` (folder picker, `dialog:select-folder`) is passed to terminal/Claude
node factories so new terminals open there. **Folder ↔ project is deduped:** "Open folder…"
reuses the existing project with that `cwd` (and its nodes) instead of creating a duplicate.
diff --git a/src/core/workspace-files.closed-history.test.ts b/src/core/workspace-files.closed-history.test.ts
index 4cea0d00d..d8082fc37 100644
--- a/src/core/workspace-files.closed-history.test.ts
+++ b/src/core/workspace-files.closed-history.test.ts
@@ -111,4 +111,30 @@ describe('sanitizeLoadedClosedSessions', () => {
expect(out).toHaveLength(CLOSED_SESSIONS_CAP)
expect(out?.[0].id).toBe('e0')
})
+
+ // Issue #531: the transcript pointer. It is the fact the whole feature rests on, so it must
+ // survive the round trip — and it is handed to a resolver, so its KIND is re-checked here
+ // rather than trusted from the type (workspace.json is hand-editable).
+ it('keeps a string sessionId', () => {
+ const out = sanitizeLoadedClosedSessions([{ ...closedEntry('e1'), sessionId: 'sess-1' }])
+ expect(out?.[0].sessionId).toBe('sess-1')
+ })
+
+ it('drops a non-string or empty sessionId instead of passing it to the transcript readers', () => {
+ for (const bad of [42, {}, [], null, '']) {
+ const out = sanitizeLoadedClosedSessions([{ ...closedEntry('e1'), sessionId: bad } as never])
+ expect(out).toHaveLength(1)
+ expect(out?.[0].sessionId).toBeUndefined()
+ }
+ })
+})
+
+describe('the transcript pointer stays machine-local', () => {
+ it('is never written into the git-shared project file', () => {
+ const entries = [{ ...closedEntry('e1'), sessionId: 'sess-1' }]
+ const file = projectToFile(project({ cwd: '/tmp/x', closedSessions: entries }), 1, 'now')
+ // A session id is a $HOME-anchored fact about ONE person's machine; shipping it to everyone
+ // who clones the repo is exactly what the closedSessions machine-local rule exists to prevent.
+ expect(JSON.stringify(file)).not.toContain('sess-1')
+ })
})
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index ef18f558e..faf80c888 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -413,7 +413,18 @@ export function sanitizeLoadedClosedSessions(x: unknown): ClosedSessionEntry[] |
if (!validClosedSessions(x)) return undefined
const capped = x.slice(0, CLOSED_SESSIONS_CAP)
if (!capped.length) return undefined
- return capped.map((e) => ({ ...e, node: sanitizeNodeTriggers([e.node])[0] }))
+ return capped.map((e) => {
+ // `sessionId` (issue #531) is handed straight to the transcript readers, so it is re-checked
+ // as a STRING here rather than trusted from the type — workspace.json is hand-editable, and a
+ // number or object would ride the IPC into a resolver that expects to call `.test()` on it.
+ // Core's own `SESSION_ID_RE` still gates the value's SHAPE; this only gates its kind.
+ const { sessionId, ...rest } = e
+ return {
+ ...rest,
+ ...(typeof sessionId === 'string' && sessionId ? { sessionId } : {}),
+ node: sanitizeNodeTriggers([e.node])[0]
+ }
+ })
}
/**
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index e438ba49a..e0bdf0118 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -179,6 +179,7 @@ import { ShortcutCaptureBanner } from '../components/ShortcutCaptureBanner'
import { ConflictBar } from '../components/ConflictBar'
import { ConfirmDialog } from '../components/ConfirmDialog'
import { CapabilityNotice } from '../components/CapabilityNotice'
+import { ClosedTranscriptDialog } from '../components/ClosedTranscriptDialog'
import { SetupConsentDialog } from '../components/SetupConsentDialog'
import { ConsentNotice } from '../remote/ConsentNotice'
import { peerApprovalView } from '@shared/remote/approval'
@@ -437,6 +438,7 @@ import type { SshServer } from '@shared/ssh'
import { sshHostKey } from '@shared/ssh'
import type {
CanvasNodeState,
+ ClosedSessionEntry,
NodeKind,
Project,
ProjectKanban,
@@ -1130,6 +1132,9 @@ export function Canvas() {
// A client has finished the handshake and is awaiting this host's approval (carries the SAS).
const [pendingPeer, setPendingPeerState] = useState<PendingPeerState | null>(null)
const [confirm, setConfirmState] = useState<ConfirmState | null>(null)
+ // The closed-session entry whose transcript is on screen (issue #531), or null. A SNAPSHOT of
+ // the ledger row, not a reference into the store: reading it needs only the pointer it carries.
+ const [closedTranscript, setClosedTranscript] = useState<ClosedSessionEntry | null>(null)
// Node to center once its project finishes loading (cross-project notification click).
const pendingFocusRef = useRef<string | null>(null)
// One-shot: the next active-project load keeps the CURRENT camera instead of applying the
@@ -4818,11 +4823,20 @@ export function Canvas() {
// the TOP of deleteNodes, before transport.destroy/setNodes, so a throw here would make
// Delete do nothing at all on that surface. See lib/uuid.ts (the same call already broke
// "Add agent" once).
- const closedEntries = buildClosedSessionEntries(set, nodesRef.current, deletedAt, (nodeId) => {
- const id = uuid()
- closedSessionIdByNode.set(nodeId, id)
- return id
- })
+ const closedEntries = buildClosedSessionEntries(
+ set,
+ nodesRef.current,
+ deletedAt,
+ (nodeId) => {
+ const id = uuid()
+ closedSessionIdByNode.set(nodeId, id)
+ return id
+ },
+ // Issue #531. The agent-status entry is dropped a few lines below, and the live session
+ // id lives nowhere else — so this is the last instant the pointer to the node's
+ // transcript exists. Read it BEFORE the teardown, not after.
+ (nodeId) => useAgentStatus.getState().byId[nodeId]?.sessionId
+ )
if (closedEntries.length) {
useProjects.getState().recordClosedSessions(
useProjects.getState().activeProjectId ?? '',
@@ -6715,6 +6729,19 @@ export function Canvas() {
* may not be the ACTIVE project, so nothing else here is guaranteed to flush it to disk. Force
* an explicit save rather than relying on the active-canvas debounce (`markDirty`), which only
* covers the active project. */
+ /**
+ * Issue #531 — read a closed session's transcript without reopening (or resuming) anything.
+ * The entry is looked up at CLICK time rather than carried by the row, so a ledger the user
+ * has since pruned cannot open a dialog for a record that no longer exists.
+ */
+ const openClosedTranscript = useCallback((projectId: string, entryId: string) => {
+ const entry = useProjects
+ .getState()
+ .projects.find((p) => p.id === projectId)
+ ?.closedSessions?.find((e) => e.id === entryId)
+ if (entry) setClosedTranscript(entry)
+ }, [])
+
const reopenClosedSessionCommand = useCallback(
(projectId: string, entryId: string): boolean => {
const consumed = useProjects.getState().consumeClosedSession(projectId, entryId)
@@ -12796,6 +12823,7 @@ export function Canvas() {
useProjects.getState().discardClosedSession(projectId, entryId)
void writeDisk()
}}
+ onOpenClosedTranscript={openClosedTranscript}
onMouseEnter={openSessionsPeek}
onMouseLeave={closeSessionsPeekSoon}
/>
@@ -12806,6 +12834,12 @@ export function Canvas() {
answer machine-locally — see components/CapabilityNotice.tsx and its test. */}
<CapabilityNotice />
+ {/* A closed session's conversation, read through the same ⌘M reader a live node uses
+ (issue #531 — closing a node used to make its finished work unverifiable). */}
+ {closedTranscript && (
+ <ClosedTranscriptDialog entry={closedTranscript} onClose={() => setClosedTranscript(null)} />
+ )}
+
{/* The trust gate for a git-shared setup/archive script, mounted ONCE for the whole app on
the same layer as the clone notice: main raises it (a manual run, or a worktree's setup)
and it must be answerable wherever the user is, not only while a settings pane happens to
diff --git a/src/renderer/canvas/canvas-wiring.test.tsx b/src/renderer/canvas/canvas-wiring.test.tsx
index 68454ec82..7eaaea6b5 100644
--- a/src/renderer/canvas/canvas-wiring.test.tsx
+++ b/src/renderer/canvas/canvas-wiring.test.tsx
@@ -172,7 +172,7 @@ describe('deleteNodes also records persisted closed-session history', () => {
it('builds entries from the full pre-delete tree and the same "now" used for reopenHistory', () => {
expect(CANVAS_SRC).toContain('const deletedAt = Date.now()')
expect(CANVAS_SRC).toContain(
- 'buildClosedSessionEntries(set, nodesRef.current, deletedAt, (nodeId) => {'
+ 'buildClosedSessionEntries(\n set,\n nodesRef.current,\n deletedAt,'
)
// The reopenHistory push reuses the SAME `deletedAt`, not a second `Date.now()` call — the
// two ledgers must agree on when this batch closed, not just approximately.
@@ -198,6 +198,20 @@ describe('deleteNodes also records persisted closed-session history', () => {
expect(CANVAS_SRC).toContain('closedSessionId: closedSessionIdByNode.get(n.id)')
})
+ it('captures the live agent session id BEFORE the agent-status entry is dropped', () => {
+ // Issue #531: the live session id is the only pointer to a closed node's transcript, and it
+ // lives nowhere but the transient agent-status store — which this same delete clears. Read it
+ // out of order and the ledger records `undefined`, and the conversation becomes unreachable
+ // with nothing on screen saying so.
+ const build = CANVAS_SRC.indexOf('buildClosedSessionEntries(')
+ expect(build).toBeGreaterThan(0)
+ const capture = CANVAS_SRC.indexOf('useAgentStatus.getState().byId[nodeId]?.sessionId', build)
+ expect(capture).toBeGreaterThan(build)
+ const clear = CANVAS_SRC.indexOf('useAgentStatus.getState().clear', build)
+ // A clear inside deleteNodes must come after the capture (or not exist at all).
+ if (clear !== -1) expect(clear).toBeGreaterThan(capture)
+ })
+
it('records into the store only when entries were actually built', () => {
expect(CANVAS_SRC).toContain('if (closedEntries.length) {')
expect(CANVAS_SRC).toContain('.recordClosedSessions(')
diff --git a/src/renderer/components/ClosedHistorySection.test.tsx b/src/renderer/components/ClosedHistorySection.test.tsx
index f27491c83..2a3eafb79 100644
--- a/src/renderer/components/ClosedHistorySection.test.tsx
+++ b/src/renderer/components/ClosedHistorySection.test.tsx
@@ -25,7 +25,8 @@ const projects: Project[] = [
const noop = () => {}
const baseProps = {
nowMs: 1000, collapsed: false, onToggleCollapse: noop,
- onReopenProject: noop, onDeleteProject: noop, onReopenSession: noop, onDiscardSession: noop
+ onReopenProject: noop, onDeleteProject: noop, onReopenSession: noop, onDiscardSession: noop,
+ onOpenTranscript: noop
}
describe('ClosedHistorySection', () => {
@@ -124,6 +125,66 @@ describe('ClosedHistorySection', () => {
expect(onReopenSession).not.toHaveBeenCalled()
})
+ // Issue #531 — the way back to a closed session's conversation.
+ describe('the transcript control', () => {
+ const agentProject = (over: Record<string, unknown> = {}, entryOver: Record<string, unknown> = {}): Project[] => [
+ {
+ id: 'p2', name: 'open-proj', color: '#fff', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [],
+ closedSessions: [{
+ id: 'e1', closedAt: 200,
+ node: {
+ id: 'a1', kind: 'terminal', position: { x: 0, y: 0 }, title: 'reviewer', color: '#fff',
+ group: null, cwd: '/repo', agentId: 'claude', ...over
+ },
+ absolutePosition: { x: 0, y: 0 },
+ ...entryOver
+ }]
+ } as unknown as Project
+ ]
+
+ it('opens the transcript for a closed agent session, without also triggering reopen', async () => {
+ const onOpenTranscript = vi.fn()
+ const onReopenSession = vi.fn()
+ await render(
+ <ClosedHistorySection
+ {...baseProps} projects={agentProject({}, { sessionId: 's1' })}
+ onOpenTranscript={onOpenTranscript} onReopenSession={onReopenSession}
+ />
+ )
+ const btn = host.querySelector('.sessions-sidebar__history-transcript') as HTMLButtonElement
+ expect(btn).toBeTruthy()
+ expect(btn.disabled).toBe(false)
+ await act(async () => btn.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+ expect(onOpenTranscript).toHaveBeenCalledWith('p2', 'e1')
+ expect(onReopenSession).not.toHaveBeenCalled()
+ })
+
+ it('shows the control DISABLED with its reason when the id was never recorded', async () => {
+ // A silently-absent control would leave the user believing closing destroyed the record.
+ await render(<ClosedHistorySection {...baseProps} projects={agentProject()} />)
+ const btn = host.querySelector('.sessions-sidebar__history-transcript') as HTMLButtonElement
+ expect(btn).toBeTruthy()
+ expect(btn.disabled).toBe(true)
+ expect(btn.title).toContain('session id')
+ })
+
+ it('shows it disabled for a remote session, naming the host as the reason', async () => {
+ await render(
+ <ClosedHistorySection
+ {...baseProps} projects={agentProject({ sshRemoteTmux: true }, { sessionId: 's1' })}
+ />
+ )
+ const btn = host.querySelector('.sessions-sidebar__history-transcript') as HTMLButtonElement
+ expect(btn.disabled).toBe(true)
+ expect(btn.title).toContain('remote host')
+ })
+
+ it('renders no control at all for a plain terminal — it never had a conversation', async () => {
+ await render(<ClosedHistorySection {...baseProps} projects={projects} />)
+ expect(host.querySelector('.sessions-sidebar__history-transcript')).toBeNull()
+ })
+ })
+
it('collapsed hides the row list but keeps the header', async () => {
await render(<ClosedHistorySection {...baseProps} projects={projects} collapsed={true} />)
expect(host.textContent).toContain('Recently closed')
diff --git a/src/renderer/components/ClosedHistorySection.tsx b/src/renderer/components/ClosedHistorySection.tsx
index 3ae92d215..6a0a73a6b 100644
--- a/src/renderer/components/ClosedHistorySection.tsx
+++ b/src/renderer/components/ClosedHistorySection.tsx
@@ -1,5 +1,5 @@
import type { Project } from '@shared/types'
-import { mergeClosedHistory } from '../lib/closedHistory'
+import { closedTranscriptTarget, mergeClosedHistory } from '../lib/closedHistory'
import { sessionStateAgeLabel } from '../lib/sessionList'
import { ProjectGlyph } from './ProjectGlyph'
@@ -12,6 +12,8 @@ export interface ClosedHistorySectionProps {
onDeleteProject(id: string): void
onReopenSession(projectId: string, entryId: string): void
onDiscardSession(projectId: string, entryId: string): void
+ /** Open the closed session's transcript (issue #531). */
+ onOpenTranscript(projectId: string, entryId: string): void
}
/** Sidebar section listing recently closed projects (tabs) and recently closed sessions
@@ -102,6 +104,31 @@ export function ClosedHistorySection(props: ClosedHistorySectionProps): JSX.Elem
<span className="sessions-sidebar__history-age">
{sessionStateAgeLabel(row.closedAt, props.nowMs)}
</span>
+ {/* Issue #531: a closed agent session's conversation is still on disk, and this
+ is the way back to it. Rendered DISABLED with the reason when it cannot be
+ read (no recorded id, a remote host) rather than omitted — a missing row
+ teaches nothing, and "closing destroys the record" is exactly the belief this
+ change exists to correct. Absent entirely for a node that never had a
+ transcript to begin with. */}
+ {(() => {
+ const t = closedTranscriptTarget(row.entry)
+ if (!t.ok && t.kind === 'no-agent') return null
+ return (
+ <button
+ className="sessions-sidebar__history-transcript"
+ aria-label="Read transcript"
+ title={t.ok ? 'Read this session’s transcript' : t.reason}
+ disabled={!t.ok}
+ onClick={(e) => {
+ e.stopPropagation()
+ if (t.ok) props.onOpenTranscript(row.projectId, row.entry.id)
+ }}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ 💬
+ </button>
+ )
+ })()}
<button
className="sessions-sidebar__history-del"
aria-label="Discard"
diff --git a/src/renderer/components/ClosedTranscriptDialog.tsx b/src/renderer/components/ClosedTranscriptDialog.tsx
new file mode 100644
index 000000000..882b2c1b4
--- /dev/null
+++ b/src/renderer/components/ClosedTranscriptDialog.tsx
@@ -0,0 +1,81 @@
+import { Suspense, lazy, useEffect, useRef } from 'react'
+import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
+import type { ClosedSessionEntry } from '@shared/types'
+import { closedTranscriptTarget } from '../lib/closedHistory'
+
+// Same code split as the ⌘M panel on a terminal node: the transcript reader and the markdown
+// renderer are not on the path to painting a canvas, and this dialog opens on a click.
+const ChatPanel = lazy(() => import('../nodes/ChatPanel').then((m) => ({ default: m.ChatPanel })))
+
+export interface ClosedTranscriptDialogProps {
+ entry: ClosedSessionEntry
+ onClose(): void
+}
+
+/**
+ * Reads a CLOSED session's conversation (issue #531).
+ *
+ * Closing a node used to destroy the only pointer to its transcript — the live session id, held
+ * in the transient agent-status store — so work that was finished and merged could never be
+ * checked afterwards, even though the `.jsonl` the agent CLI owns was still sitting on disk. The
+ * ledger now keeps that pointer (`ClosedSessionEntry.sessionId`) and this dialog spends it on the
+ * EXISTING reader: it is `ChatPanel` in read-only mode, so resolution, the found-vs-empty
+ * distinction and Retry are the ⌘M panel's, not a second implementation that would drift from it.
+ *
+ * A node that cannot be read says why (`closedTranscriptTarget`) instead of offering nothing.
+ */
+export function ClosedTranscriptDialog({ entry, onClose }: ClosedTranscriptDialogProps) {
+ const isTop = useDialogStack()
+ const boxRef = useRef<HTMLDivElement>(null)
+ const target = closedTranscriptTarget(entry)
+
+ // Escape closes while this is the top dialog. Focus the box so the key arrives even when the
+ // click that opened it left focus on a sidebar row.
+ useEffect(() => {
+ boxRef.current?.focus()
+ }, [])
+
+ return createPortal(
+ <div className="confirm-overlay" onClick={onClose}>
+ <div
+ ref={boxRef}
+ className="confirm closed-transcript"
+ tabIndex={-1}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ if (e.key === 'Escape' && isTop()) {
+ e.preventDefault()
+ onClose()
+ }
+ }}
+ >
+ {target.ok ? (
+ <Suspense fallback={null}>
+ <ChatPanel
+ nodeId={target.nodeId}
+ sessionId={target.sessionId}
+ cwd={target.cwd}
+ accountId={target.accountId}
+ agentId={target.agentId}
+ readOnly
+ title={entry.node.title || 'Closed session'}
+ hint="Esc to close"
+ />
+ </Suspense>
+ ) : (
+ <div className="closed-transcript__empty">
+ <p className="confirm__msg">{entry.node.title || 'Closed session'}</p>
+ <p className="closed-transcript__reason">{target.reason}</p>
+ </div>
+ )}
+ <div className="confirm__actions">
+ <button className="confirm__btn" onClick={onClose}>
+ Close
+ </button>
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index 3a6a7b645..06f0ecee7 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -72,6 +72,8 @@ export interface SessionsSidebarProps {
onDeleteProject(id: string): void
onReopenClosedSession(projectId: string, entryId: string): void
onDiscardClosedSession(projectId: string, entryId: string): void
+ /** Read a closed session's transcript (issue #531). */
+ onOpenClosedTranscript(projectId: string, entryId: string): void
onMouseEnter?(): void
onMouseLeave?(): void
}
@@ -717,6 +719,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
onDeleteProject={props.onDeleteProject}
onReopenSession={props.onReopenClosedSession}
onDiscardSession={props.onDiscardClosedSession}
+ onOpenTranscript={props.onOpenClosedTranscript}
/>
</aside>
)
diff --git a/src/renderer/lib/closedHistory.test.ts b/src/renderer/lib/closedHistory.test.ts
index 64bf6e8c5..ad5a39d1c 100644
--- a/src/renderer/lib/closedHistory.test.ts
+++ b/src/renderer/lib/closedHistory.test.ts
@@ -1,5 +1,10 @@
import { describe, it, expect } from 'vitest'
-import { buildClosedSessionEntries, stateToReopenSnapshot, mergeClosedHistory } from './closedHistory'
+import {
+ buildClosedSessionEntries,
+ closedTranscriptTarget,
+ stateToReopenSnapshot,
+ mergeClosedHistory
+} from './closedHistory'
import type { CanvasNode } from '@renderer/state/workspace'
import type { ClosedSessionEntry, Project } from '@shared/types'
@@ -136,3 +141,97 @@ describe('mergeClosedHistory', () => {
expect(rows).toHaveLength(0)
})
})
+
+// Issue #531: closing a node used to destroy the ONLY pointer to its transcript (the live session
+// id, held in the transient agent-status store), so finished work could never be read back.
+describe('the closed-session transcript pointer', () => {
+ const agentNode = (over: Record<string, unknown> = {}): CanvasNode =>
+ node({
+ id: 'a1',
+ data: { title: 'reviewer', color: '#fff', group: null, cwd: '/repo', agentId: 'claude', ...over }
+ } as Partial<CanvasNode>)
+
+ it('records the LIVE session id at close', () => {
+ const entries = buildClosedSessionEntries(
+ new Set(['a1']),
+ [agentNode()],
+ 1,
+ () => 'e1',
+ (id) => (id === 'a1' ? 'live-sess' : undefined)
+ )
+ expect(entries[0].sessionId).toBe('live-sess')
+ })
+
+ it('falls back to the minted agentSessionId when no hook event ever named a live one', () => {
+ const entries = buildClosedSessionEntries(
+ new Set(['a1']),
+ [agentNode({ agentSessionId: 'minted-sess' })],
+ 1,
+ () => 'e1',
+ () => undefined
+ )
+ expect(entries[0].sessionId).toBe('minted-sess')
+ })
+
+ it('prefers the live id over the minted one — a resume replaces the session that was minted', () => {
+ const entries = buildClosedSessionEntries(
+ new Set(['a1']),
+ [agentNode({ agentSessionId: 'minted-sess' })],
+ 1,
+ () => 'e1',
+ () => 'live-sess'
+ )
+ expect(entries[0].sessionId).toBe('live-sess')
+ })
+
+ it('omits the field entirely when neither id exists, rather than writing undefined', () => {
+ const entries = buildClosedSessionEntries(new Set(['n1']), [node()], 1, () => 'e1')
+ expect('sessionId' in entries[0]).toBe(false)
+ })
+})
+
+describe('closedTranscriptTarget', () => {
+ const entry = (
+ over: Partial<ClosedSessionEntry> = {},
+ nodeOver: Record<string, unknown> = {}
+ ): ClosedSessionEntry =>
+ ({
+ id: 'e1',
+ closedAt: 1,
+ absolutePosition: { x: 0, y: 0 },
+ node: {
+ id: 'a1', kind: 'terminal', position: { x: 0, y: 0 }, title: 'reviewer', color: '#fff',
+ group: null, cwd: '/repo', agentId: 'claude', ...nodeOver
+ },
+ ...over
+ }) as ClosedSessionEntry
+
+ it('hands back exactly the arguments the Cmd+M reader takes', () => {
+ const t = closedTranscriptTarget(entry({ sessionId: 's1' }, { accountId: 'acc-2' }))
+ expect(t).toEqual({
+ ok: true, sessionId: 's1', agentId: 'claude', cwd: '/repo', accountId: 'acc-2', nodeId: 'a1'
+ })
+ })
+
+ it('refuses a node whose agent has no readable transcript, as the kind a surface may hide', () => {
+ expect(closedTranscriptTarget(entry({ sessionId: 's1' }, { agentId: undefined }))).toMatchObject({
+ ok: false, kind: 'no-agent'
+ })
+ })
+
+ it('refuses a REMOTE session by name — its transcript is on the host', () => {
+ expect(closedTranscriptTarget(entry({ sessionId: 's1' }, { sshRemoteTmux: true }))).toMatchObject({
+ ok: false, kind: 'remote'
+ })
+ expect(closedTranscriptTarget(entry({ sessionId: 's1' }, { ssh: { host: 'h', user: 'u' } }))).toMatchObject({
+ ok: false, kind: 'remote'
+ })
+ })
+
+ it('refuses an entry with no recorded id (closed by a pre-#531 build) with its own reason', () => {
+ const t = closedTranscriptTarget(entry())
+ expect(t).toMatchObject({ ok: false, kind: 'no-session-id' })
+ // Not the hideable kind: the user closed a real agent session and the record is genuinely gone.
+ expect(t.ok === false && t.kind !== 'no-agent').toBe(true)
+ })
+})
diff --git a/src/renderer/lib/closedHistory.ts b/src/renderer/lib/closedHistory.ts
index eb9db058b..67c69b8ba 100644
--- a/src/renderer/lib/closedHistory.ts
+++ b/src/renderer/lib/closedHistory.ts
@@ -1,4 +1,5 @@
import type { CanvasNodeState, ClosedSessionEntry, Project } from '@shared/types'
+import { canChat, createdAgentId } from '@shared/agents/config'
import { flowToNodeStates, type CanvasNode } from '@renderer/state/workspace'
import { snapshotNode, type ReopenNodeSnapshot, type RestorableNodeKind } from './reopenNode'
import { absolutePosition, type FocusableNode } from './nodeFocus'
@@ -23,20 +24,86 @@ export function buildClosedSessionEntries(
deletedIds: ReadonlySet<string>,
allNodes: readonly CanvasNode[],
now: number,
- makeId: (nodeId: string) => string
+ makeId: (nodeId: string) => string,
+ /**
+ * The LIVE agent session id for a node, from the transient `agentStatus` store. Optional so
+ * every pre-#531 caller is unchanged, but `deleteNodes` passes it: the store entry is dropped
+ * with the node, so this is the last moment the id exists anywhere (see
+ * `ClosedSessionEntry.sessionId`).
+ */
+ liveSessionId?: (nodeId: string) => string | undefined
): ClosedSessionEntry[] {
return allNodes
.filter((n) => deletedIds.has(n.id))
.filter((n) => snapshotNode(n, allNodes as readonly FocusableNode[]) !== null)
- .map((n) => ({
- id: makeId(n.id),
- closedAt: now,
- node: flowToNodeStates([n])[0],
- absolutePosition: absolutePosition(
- { id: n.id, position: n.position, parentId: n.parentId },
- allNodes as readonly FocusableNode[]
- )
- }))
+ .map((n) => {
+ const node = flowToNodeStates([n])[0]
+ // Live id first (it is the session the node was actually running — a resume replaces the
+ // minted one), then the minted id as the durable fallback.
+ const sessionId = liveSessionId?.(n.id) || node.agentSessionId
+ return {
+ id: makeId(n.id),
+ closedAt: now,
+ node,
+ absolutePosition: absolutePosition(
+ { id: n.id, position: n.position, parentId: n.parentId },
+ allNodes as readonly FocusableNode[]
+ ),
+ ...(sessionId ? { sessionId } : {})
+ }
+ })
+}
+
+/**
+ * Whether a closed session's transcript can still be read, and through what.
+ *
+ * `ok` carries exactly the arguments `chat.readTranscript` takes, so the recovery path is the
+ * EXISTING ⌘M reader rather than a second one — including its `{found}` discipline, which is what
+ * keeps "the agent pruned this transcript" from rendering as an empty conversation.
+ *
+ * Every refusal names its reason, because a silently missing affordance teaches nothing: the two
+ * that exist are a session whose id was never recorded (closed by a build older than #531, or a
+ * node that never ran an agent) and a REMOTE one, whose transcript lives on the host — the local
+ * resolvers would search this machine and, via `resolveTranscript`'s cwd fallback, could answer
+ * with an unrelated local session. Reading a closed remote station is real work (locate-by-session
+ * over the ControlMaster, for a project that may not even be connected) and deliberately not held
+ * hostage to the local fix.
+ */
+export type ClosedTranscriptTarget =
+ | { ok: true; sessionId: string; agentId: string; cwd?: string; accountId?: string; nodeId: string }
+ | { ok: false; kind: 'no-agent' | 'remote' | 'no-session-id'; reason: string }
+
+export function closedTranscriptTarget(entry: ClosedSessionEntry): ClosedTranscriptTarget {
+ const n = entry.node
+ const agentId = createdAgentId(n)
+ // `no-agent` is the one refusal a surface may render as NOTHING: a plain terminal or a sticky
+ // note never had a conversation, so a disabled "read transcript" control on it would be noise.
+ // The other two are losses worth naming.
+ if (!agentId || !canChat(agentId)) {
+ return { ok: false, kind: 'no-agent', reason: 'This session has no readable transcript.' }
+ }
+ if (n.ssh || n.sshRemoteTmux) {
+ return {
+ ok: false,
+ kind: 'remote',
+ reason: 'This session ran on a remote host; its transcript is not readable after close yet.'
+ }
+ }
+ if (!entry.sessionId) {
+ return {
+ ok: false,
+ kind: 'no-session-id',
+ reason: 'No session id was recorded for this session, so its transcript cannot be found.'
+ }
+ }
+ return {
+ ok: true,
+ sessionId: entry.sessionId,
+ agentId,
+ cwd: n.cwd,
+ accountId: n.accountId,
+ nodeId: n.id
+ }
}
/**
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 386041022..2992cd152 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -26,6 +26,17 @@ interface ChatPanelProps {
* tests green while restoring that leak in full. Required makes the compiler the proof: the
* wiring cannot be dropped silently, with no render test needed to notice. */
agentId: string
+ /**
+ * Read a transcript with no live session behind it (issue #531: a CLOSED node's conversation,
+ * opened from "Recently closed"). Hides the composer — `pty.sendText` would be aimed at a node
+ * id that no longer exists — and names the bar for what it is. Absent = the ⌘M panel on a live
+ * node, byte-identical to before.
+ */
+ readOnly?: boolean
+ /** Bar caption. Defaults to the ⌘M panel's own 'Chat'. */
+ title?: string
+ /** Rendered at the right of the bar in place of the ⌘M exit hint. */
+ hint?: string
}
/**
@@ -63,7 +74,16 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
* session via pty.sendText. Phase 1 reloads the transcript whenever a turn finishes
* (working -> idle); live streaming is a later phase. Replaces the markdown-of-output overlay.
*/
-export function ChatPanel({ nodeId, sessionId, cwd, accountId, agentId }: ChatPanelProps) {
+export function ChatPanel({
+ nodeId,
+ sessionId,
+ cwd,
+ accountId,
+ agentId,
+ readOnly,
+ title,
+ hint
+}: 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 } = useSession()
@@ -135,8 +155,8 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId, agentId }: ChatPa
return (
<div className="term-chat nodrag nowheel">
<div className="term-chat__bar">
- <span>Chat</span>
- <span className="term-chat__hint">{mdChip ? `${mdChip} to exit` : 'Exit'}</span>
+ <span>{title ?? 'Chat'}</span>
+ <span className="term-chat__hint">{hint ?? (mdChip ? `${mdChip} to exit` : 'Exit')}</span>
</div>
<div className="term-chat__msgs" ref={msgsRef}>
{messages.length === 0 && loadState !== 'loading' && (
@@ -170,6 +190,7 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId, agentId }: ChatPa
</div>
))}
</div>
+ {!readOnly && (
<div className="term-chat__compose">
<textarea
className="term-chat__input"
@@ -187,6 +208,7 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId, agentId }: ChatPa
rows={2}
/>
</div>
+ )}
</div>
)
}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 03ee692ba..1b8559525 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -7370,6 +7370,47 @@ button.group-node__setup:disabled {
.sessions-sidebar__history-item:hover .sessions-sidebar__history-del { opacity: 1; }
.sessions-sidebar__history-del:hover { background: rgba(255, 69, 58, 0.15); color: var(--danger); }
+/* "Read transcript" on a closed session row (issue #531) — same reveal-on-hover affordance as the
+ discard ×, beside it. Kept visible while DISABLED so the reason (in its title) is reachable:
+ a control that vanishes when it cannot act teaches nothing about why. */
+.sessions-sidebar__history-transcript {
+ flex: none;
+ width: 18px;
+ height: 18px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ border-radius: 5px;
+ color: var(--muted);
+ font-size: 11px;
+ line-height: 1;
+ cursor: pointer;
+ opacity: 0;
+ transition: opacity 0.12s, background 0.12s;
+}
+.sessions-sidebar__history-item:hover .sessions-sidebar__history-transcript { opacity: 1; }
+.sessions-sidebar__history-transcript:hover { background: var(--panel-header); }
+.sessions-sidebar__history-transcript:disabled { cursor: default; opacity: 0; }
+.sessions-sidebar__history-item:hover .sessions-sidebar__history-transcript:disabled { opacity: 0.35; }
+
+/* The closed-session transcript dialog: a plain confirm box sized to hold the chat panel. */
+.closed-transcript {
+ width: min(760px, 92vw);
+ max-width: none;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+.closed-transcript .term-chat {
+ height: min(60vh, 520px);
+ border-radius: 8px;
+ overflow: hidden;
+}
+.closed-transcript__empty { display: flex; flex-direction: column; gap: 6px; }
+.closed-transcript__reason { margin: 0; color: var(--muted); font-size: 12px; line-height: 1.4; }
+
.ss-group__head { display: flex; align-items: center; gap: 6px; padding: 6px 6px; cursor: pointer; border-radius: 6px; border: 1px solid transparent; }
.ss-group__head:hover { background: var(--panel-header); }
/* Project sections read as bands: monogram + heavier head + breathing room between projects. */
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5e956163c..f3b87f9d6 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -429,6 +429,24 @@ export interface ClosedSessionEntry {
closedAt: number
node: CanvasNodeState
absolutePosition: { x: number; y: number }
+ /**
+ * The agent session this node was running when it was closed — a POINTER to the transcript the
+ * agent CLI already owns, never a copy of its text (issue #531). It is the one fact that dies
+ * with the node and cannot be recovered afterwards: the live id is held only in the transient
+ * `agentStatus` store, whose entry is dropped on delete, while the transcript `.jsonl` itself
+ * stays on disk under the agent's own root. Without it a closed station's work cannot be read
+ * back at all, which is what made "close the node once its branch is merged" quietly destructive.
+ *
+ * Captured at close from the hook-fed live id, falling back to `node.agentSessionId` (the id
+ * nodeterm minted at creation) — the two agree whenever both exist, and each covers a case the
+ * other misses (a RESUMED session has no minted id; a node that never emitted a hook event has
+ * no live one).
+ *
+ * MACHINE-LOCAL by construction: `closedSessions` rides `IndexEntryV3`, never the git-shared
+ * `.nodeterm/project.json` (see `Project.closedSessions`), so a session id — a `$HOME`-anchored
+ * fact about one person's machine — is never shipped to everyone who clones the repo.
+ */
+ sessionId?: string
}
/**