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(agents): cold restore falls back to a bare launch when the transcript is gone

enese39c2f0dc41c
diff --git a/CLAUDE.md b/CLAUDE.md
index 7bbde2e50..3e1f7c08d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -737,6 +737,50 @@ session (you can't keep a live OS process across a reboot):
flag — and instead records the pane its fresh shell settled on (`agentStatus.hibernatedPane`),
so a later explicit Resume can recognize it even for a default shell outside the wake's
`isShellCommand` allowlist.
+ **A persisted session id is not evidence the conversation still exists**, and a dead one is not a
+ no-op: `claude --resume <dead id>` prints *"No conversation found with session ID: <uuid>"* and
+ EXITS, leaving the pane at a bare shell under a node still wearing its agent badge. Measured
+ 2026-09-09 on the reporting host (`nodeterm-rmt`, 108 live sessions): **20** panes sat in exactly
+ that state, and not one of those 20 ids had a `<id>.jsonl` anywhere under the system
+ `~/.claude/projects` or the managed account root. Claude's own 30-day cleanup, a `/clear`, a
+ removed account and an id minted for a session that never ran all produce it. So the cold-restore
+ branch now asks `chat.transcriptExists` first (`transcript:exists`, served by
+ `registerTranscriptIpc` in BOTH shells) and, on a POSITIVE `absent`, launches the agent **bare**
+ and raises a slim `CoState.lostSession` banner on the node — "The previous conversation could not
+ be found — this agent started fresh." — instead of opening a blank session in silence. Three
+ rules make that safe:
+ - **The answer is a TRI-state** (`TranscriptPresence`: `present | absent | unknown`) and only
+ `absent` drops the id. The two errors are wildly asymmetric — wrongly resuming a dead id costs
+ one line and a bare shell (today's bug), wrongly dropping a LIVE id strands work the user
+ believes is continuing — so an unreadable root, a `readdir` that threw, a downed ControlMaster,
+ a relay tab, a rejected call and an id we would not put on a command line are ALL `unknown` =
+ resume exactly as before. `transcriptPresence` (`core/transcript-reader.ts`) is
+ `resolveTranscriptPath` plus that one distinction, not a second way of finding a transcript,
+ and a root that does not exist at all still answers `unknown` on purpose: cold restore runs at
+ boot, where a not-yet-mounted `$HOME` is indistinguishable from an empty one.
+ - **The remote leg's `unknown` is TERMINAL, never a fallthrough.** A remote session's transcript
+ is on the host, so searching this machine for it would find nothing and report `absent` about
+ the wrong computer. `remoteTranscriptPresence` (`src/main`) exists beside
+ `remoteTranscriptRefFor` rather than reusing it because that function collapses "not remote" /
+ "no home" / "ssh failed" / "the host looked and there is nothing" into one `undefined` — fine
+ for a reader that falls back, fatal for a caller that acts on absence.
+ `locateRemoteTranscriptCommand` was already built for this distinction (it exits 0 on a clean
+ miss, "so no transcript is an ANSWER, not a failed ssh"), and that is the property this reads;
+ it is deliberately more permissive than the local leg (it searches the account root AND the
+ system root), which errs toward `present` = keep the resume.
+ - **Claude only**, gated by `readsClaudeTranscript` — a codex/gemini/grok id misses this
+ resolver by construction every time, so probing one would answer `absent` for a healthy
+ session and drop its resume. Those agents keep the pre-existing behaviour until the probe
+ learns their layouts (`handoff/locate.ts` has the per-agent locators; that is the seam).
+ Decision logic is the pure `terminal/cold-resume-session.ts`. **Adding a `CoState` field owes the
+ hand-written equality list in `setCo`** — a patch touching only an uncompared field is SWALLOWED
+ and its banner silently never renders (it happened once to `spawnError`);
+ `nodes/cold-resume-wiring.test.ts` now asserts every field of the interface appears there.
+ Surfaces: Desktop full; Server Edition full (the handler is core, the ws-bridge leg is real, and
+ that shell runs on the host whose transcripts it reads, so it needs no remote leg); relay tabs
+ answer `unknown` and resume as before. **Not yet on the kanban CARD MODAL** — `ModalTerminal`
+ reads no `CoState`, so a user who only ever opens the session from the board does not see the
+ notice; the honest fix is a shared node-notice surface rather than a second copy of the banner.
### We have our own VT emulator — check it before asking tmux
@@ -1429,8 +1473,9 @@ else, and its context links must keep classifying across restarts).
never judged. **A second thing this catches, unplanned:** in the same sweep 9 of 149 panes sat at a
bare shell because a cold-restore `--resume` had answered *"No conversation found with session
ID"* — the persisted `sessionId` outlived its transcript. The chip surfaces those too, but the
- Resume it offers replays the same dead id; making cold restore fall back to a bare launch when the
- transcript is gone is a separate, unbuilt fix.
+ Resume it offers still replays that dead id — but cold restore no longer creates the state: it
+ probes `transcript:exists` first and launches bare on a positive `absent`, saying so on the node
+ (see **Cold restore** above). Re-measured on the same host 2026-09-09: **20** of 108.
- **Hook server (loopback HTTP)** — `src/core/agents/hook-server.ts` is a main-process
loopback HTTP server (per-session bearer token, fail-open) that the installed hook scripts
POST to; it replaced the old `fs.watch` signal-log mechanism. `buildPtyEnv` injects the
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 65aef4472..b433ff770 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -162,7 +162,11 @@ bug.
**A failed read is never evidence of absence.** "Could not measure" and "there is nothing" are
different facts and must stay distinguishable at every layer. Collapsing them is how a panel ends up
-reporting "no sessions" on a host running thirty.
+reporting "no sessions" on a host running thirty. When something ACTS on the negative, give it three
+answers rather than two — `present | absent | unknown` (`TranscriptPresence` is the shape) — and let
+only the positive finding trigger the action. Ask which of the two mistakes is recoverable: cold
+restore wrongly resuming a dead session id costs an error line, while wrongly dropping a live one
+opens a blank conversation over work the user believed was continuing.
**Degrade to nothing, never to something wrong.** A probe that fails means the bare, safe command —
never a substituted nearest match. A hand-editable value that is unrecognised must yield the safe
diff --git a/src/core/transcript-ipc.test.ts b/src/core/transcript-ipc.test.ts
index aea958c51..6bae361e4 100644
--- a/src/core/transcript-ipc.test.ts
+++ b/src/core/transcript-ipc.test.ts
@@ -172,3 +172,103 @@ describe('registerTranscriptIpc — the chat channel is routed by AGENT', () =>
expect(res.messages.length).toBe(1)
})
})
+
+// ─────────────────────────────────────────────────────────────────────────────────────────────
+// `transcript:exists` — the tri-state cold restore acts on.
+//
+// The whole point of the third state is that `absent` is a POSITIVE finding and `unknown` is
+// "we could not look". Cold restore drops a `--resume <id>` on `absent` only, so every test here
+// is really asking: can anything that is merely uninformed reach that branch?
+// ─────────────────────────────────────────────────────────────────────────────────────────────
+describe('registerTranscriptIpc — transcript presence', () => {
+ const exists = (
+ sid: string | undefined = SID,
+ accountId?: string,
+ nodeId?: string
+ ): Promise<string> => f.handlers[IPC.transcriptExists](sid, accountId, nodeId) as Promise<string>
+
+ it('finds a transcript that is there', async () => {
+ writeTranscript(lines(userLine('merhaba')))
+ registerTranscriptIpc()
+ expect(await exists()).toBe('present')
+ })
+
+ it('reports `absent` for an id whose transcript is gone, with the root readable', async () => {
+ // The measured field case: the session id outlived its `.jsonl`. Another session's file sits
+ // in the same project dir, which is what makes the root readable AND proves the answer is
+ // about this id rather than about the directory being empty.
+ writeTranscript(lines(userLine('someone else')), '11111111-2222-3333-4444-555555555555.jsonl')
+ registerTranscriptIpc()
+ expect(await exists()).toBe('absent')
+ })
+
+ it('never answers from the cwd — a sibling transcript is not this session', async () => {
+ // `resolveTranscript`'s cwd fallback returns the NEWEST transcript in the project dir. If this
+ // channel used it, every dead id in a busy directory would read as `present` and the whole fix
+ // would silently do nothing. The file below is exactly what that fallback would return.
+ writeTranscript(lines(userLine('newest')), '99999999-2222-3333-4444-555555555555.jsonl')
+ registerTranscriptIpc()
+ expect(await exists()).toBe('absent')
+ })
+
+ it('says `unknown` when the transcript root cannot be read at all', async () => {
+ // No `~/.claude/projects`. A home that is not mounted yet looks exactly like this, and cold
+ // restore runs at boot — so the miss is not evidence.
+ registerTranscriptIpc()
+ expect(await exists()).toBe('unknown')
+ })
+
+ it('says `unknown` for a malformed id rather than claiming it is gone', async () => {
+ writeTranscript(lines(userLine('merhaba')))
+ registerTranscriptIpc()
+ expect(await exists('../../etc/passwd')).toBe('unknown')
+ expect(await exists('')).toBe('unknown')
+ })
+
+ it('scopes to the account — a system transcript is not the managed account road', async () => {
+ writeTranscript(lines(userLine('system session')))
+ registerTranscriptIpc()
+ expect(await exists(SID, 'acct-1')).toBe('unknown') // that account has no root yet
+ })
+
+ it('verifies the hook-fed path instead of trusting it', async () => {
+ // `pathFor` is authoritative while it is live, but a transcript can be deleted under it. A
+ // dead hint must fall through to the scan, not answer `present`.
+ registerTranscriptIpc({ pathFor: () => path.join(home, 'gone', SID + '.jsonl') })
+ expect(await exists()).toBe('unknown') // no root either, so we could not look
+ const p = writeTranscript(lines(userLine('merhaba')))
+ expect(p).toContain(SID)
+ expect(await exists()).toBe('present') // the scan finds the real one
+ })
+
+ describe('the remote leg', () => {
+ it('takes the host answer', async () => {
+ registerTranscriptIpc({ remoteExists: async () => 'absent' })
+ // A LOCAL transcript with this id exists; the node is remote, so it is irrelevant.
+ writeTranscript(lines(userLine('a local file with the same id')))
+ expect(await exists(SID, undefined, 'node-1')).toBe('absent')
+ })
+
+ it('does NOT fall through to the local disk when the host could not answer', async () => {
+ // The rule this exists for: a remote session's transcript lives on the host. Searching THIS
+ // machine for it would find nothing and report `absent` about the wrong computer, and cold
+ // restore would then drop a live remote conversation because an ssh call blipped.
+ writeTranscript(lines(userLine('unrelated')), '11111111-2222-3333-4444-555555555555.jsonl')
+ registerTranscriptIpc({ remoteExists: async () => 'unknown' })
+ expect(await exists(SID, undefined, 'node-1')).toBe('unknown')
+ })
+
+ it('takes the local path when the session is not remote at all (null)', async () => {
+ writeTranscript(lines(userLine('merhaba')))
+ registerTranscriptIpc({ remoteExists: async () => null })
+ expect(await exists()).toBe('present')
+ })
+
+ it('is skipped entirely when no remote leg is injected (Server Edition)', async () => {
+ // That shell runs ON the host whose transcripts these are, so local IS the complete answer.
+ writeTranscript(lines(userLine('merhaba')))
+ registerTranscriptIpc()
+ expect(await exists(SID, undefined, 'node-1')).toBe('present')
+ })
+ })
+})
diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.ts
index 38a7e4980..8cf0d6644 100644
--- a/src/core/transcript-ipc.ts
+++ b/src/core/transcript-ipc.ts
@@ -9,8 +9,9 @@
// The remote (SSH-project) leg stays an injected dep: it needs a ControlMaster, which only the
// Electron shell has. Absent deps ⇒ local-only, which is the correct and complete answer on the
// server — it runs ON the host whose transcripts it is reading.
+import fsp from 'node:fs/promises'
import { IPC } from '../shared/ipc'
-import type { ChatTranscriptResult, TranscriptLine } from '../shared/types'
+import type { ChatTranscriptResult, TranscriptLine, TranscriptPresence } from '../shared/types'
import { platform } from './platform'
import { chatMessagesFromGrok } from './grok-chat'
import { locateGrok } from './handoff/locate'
@@ -21,6 +22,7 @@ import {
readChatMessages,
readTranscriptLines,
resolveTranscriptPath,
+ transcriptPresence,
transcriptPathForCwd,
SESSION_ID_RE
} from './transcript-reader'
@@ -42,6 +44,15 @@ export interface TranscriptIpcDeps {
* could not be resolved). Electron-only — the server has no SSH-project manager.
*/
readRemote?(q: TranscriptQuery): Promise<string | null>
+ /**
+ * Does the transcript exist on the HOST — or `null` when this is not a remote session, which is
+ * the signal to take the local path below. Same `null` convention as `readRemote`.
+ *
+ * It must return `'unknown'` (not `null`) for a remote session it failed to ask, or the local
+ * resolver would run against THIS machine's disk for a session that only ever existed on the
+ * host and report `absent` — the one answer that destroys a resume. Electron-only.
+ */
+ remoteExists?(q: TranscriptQuery): Promise<TranscriptPresence | null>
}
/**
@@ -81,6 +92,34 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {
}
)
+ platform().handle(
+ IPC.transcriptExists,
+ async (
+ sessionId: string | undefined,
+ accountId: string | undefined,
+ nodeId: string | undefined
+ ): Promise<TranscriptPresence> => {
+ if (!sessionId) return 'unknown'
+ // Remote first, and its `'unknown'` is TERMINAL. Falling through to the local resolver for
+ // a remote session whose host we could not reach would search this machine for a file that
+ // only ever existed on the other one, and answer `absent` about it.
+ const remote = deps.remoteExists ? await deps.remoteExists({ sessionId, cwd: undefined, accountId, nodeId }) : null
+ if (remote !== null) return remote
+ // A live context tail's own path is the authoritative hint — but it is a HINT, so it is
+ // verified rather than trusted: the file it names can have been deleted since.
+ const hinted = deps.pathFor?.(sessionId)
+ if (hinted) {
+ try {
+ await fsp.access(hinted)
+ return 'present'
+ } catch {
+ /* fall through to the scan */
+ }
+ }
+ return transcriptPresence(sessionId, accountId)
+ }
+ )
+
platform().handle(
IPC.chatReadTranscript,
async (
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index cdbc7f051..e554dcb0c 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -245,6 +245,37 @@ export async function resolveTranscriptPath(
return undefined
}
+/**
+ * Does a transcript for this session id exist under the account's root — `present`, `absent`, or
+ * `unknown` because we could not look?
+ *
+ * `resolveTranscriptPath` above answers `undefined` for BOTH "there is no such transcript" and
+ * "the root could not be read", which is fine for every reader (they all fall back to a cwd scan
+ * or return nothing) and fatal for the one caller that acts on absence: cold restore drops a dead
+ * `--resume <id>` on `absent`, and a `$HOME` that is momentarily unreadable must never be allowed
+ * to look like a deleted conversation. So this is the resolver plus exactly one more question —
+ * NOT a second way of finding a transcript.
+ *
+ * Deliberately sessionId-ONLY: there is no cwd fallback here. `resolveTranscript`'s fallback
+ * answers with the newest transcript in a project directory, which is a different session's file
+ * and would report `present` for an id that is genuinely gone.
+ */
+export async function transcriptPresence(
+ sessionId: string,
+ accountId?: string
+): Promise<'present' | 'absent' | 'unknown'> {
+ if (!SESSION_ID_RE.test(sessionId)) return 'unknown'
+ if (await resolveTranscriptPath(sessionId, accountId)) return 'present'
+ // The miss is only meaningful if the root was readable. Probed with `readdir`, the same call
+ // the scan above makes — an `access` can succeed on a directory a `readdir` is refused.
+ try {
+ await fs.promises.readdir(transcriptRoot(accountId))
+ } catch {
+ return 'unknown'
+ }
+ return 'absent'
+}
+
// Read only the last `cap` bytes of a file as UTF-8 (whole file if smaller). Drops the partial
// leading line on a capped read. Cheaper than readCappedTail for tiny scans (session title).
//
diff --git a/src/main/index.ts b/src/main/index.ts
index d2c1f4202..26e834003 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -71,6 +71,7 @@ import {
type AgentMessagingDeps
} from '../core/agents/agent-messaging'
import type { RemoteLogExec } from '../core/board-log'
+import type { TranscriptPresence } from '../shared/types'
import { boardLogRemotePath } from '../core/board-log'
import { PtyManager } from '../core/pty-manager'
import { WorkspaceStore } from '../core/workspace-store'
@@ -2362,6 +2363,66 @@ app.whenReady().then(async () => {
return ref
}
+ /**
+ * Does a remote node's transcript still exist ON THE HOST — `present` / `absent` / `unknown` —
+ * or `null` when this is not a remote session at all (take the local path).
+ *
+ * `remoteTranscriptRefFor` above cannot answer this: it collapses "not a remote session", "no
+ * resolved home", "the ssh call failed" and "the host looked and there is nothing" into one
+ * `undefined`, which is correct for a READER (they all fall back) and wrong for the caller that
+ * acts on absence. `locateRemoteTranscriptCommand` was already written for exactly this
+ * distinction — it exits 0 on a clean miss, "so no transcript is an ANSWER, not a failed ssh"
+ * — and that is the property this reads.
+ *
+ * Every step that cannot decide answers `unknown`, never `absent`. The one caller drops a
+ * `--resume <id>` on `absent`, and a momentarily dead ControlMaster must not be able to look
+ * like a deleted conversation.
+ */
+ const remoteTranscriptPresence = async (
+ sessionId: string,
+ accountId: string | undefined,
+ nodeId: string | undefined
+ ): Promise<TranscriptPresence | null> => {
+ if (!nodeId) return null
+ const rt = ptyManager.sshRemoteForNode(nodeId)
+ // Not a remote session — the caller takes the LOCAL path, which is the right disk to read.
+ if (!rt) return null
+ // From here on the session IS remote, so every failure is `unknown`: falling back to the
+ // local resolver would search this machine for a file that only lives on the host.
+ if (remoteTranscriptBySession.has(sessionId)) return 'present'
+ if (!sshProjectManager) return 'unknown'
+ const remoteHome = sshProjectManager.remoteHomeForControlPath(rt.controlPath)
+ if (!remoteHome) return 'unknown'
+ let accountDir: string | undefined
+ if (accountId) {
+ // A hand-edited project.json can carry any string; the helper validates and throws.
+ try {
+ accountDir = remoteAccountConfigDirAbs(remoteHome, accountId)
+ } catch {
+ accountDir = undefined
+ }
+ }
+ const cmd = locateRemoteTranscriptCommand(
+ remoteTranscriptRoots(remoteHome, accountDir),
+ undefined,
+ sessionId
+ )
+ if (!cmd) return 'unknown'
+ try {
+ const { code, stdout } = await sshProjectManager.sshRun(
+ childArgs(rt.conn, rt.controlPath, cmd)
+ )
+ if (code !== 0) return 'unknown'
+ const located = parseLocatedTranscript(stdout)
+ // Jailed exactly like a hook-supplied path: a located path we would refuse to READ must not
+ // be reported as a transcript that exists either.
+ if (located && isSafeRemoteTranscriptPath(located, remoteHome)) return 'present'
+ return located ? 'unknown' : 'absent'
+ } catch {
+ return 'unknown'
+ }
+ }
+
/**
* Read a remote transcript through a ref, forgetting refs WE located once they stop reading.
* `cap` is the tail window in bytes; it defaults to the full reader's cap, so every caller that
@@ -2394,7 +2455,9 @@ app.whenReady().then(async () => {
readRemote: async ({ sessionId, cwd, accountId, nodeId }) => {
const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)
return ref ? await readRemoteTranscript(sessionId!, ref) : null
- }
+ },
+ remoteExists: async ({ sessionId, accountId, nodeId }) =>
+ sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null
})
initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d9354caec..ca4254256 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -539,7 +539,9 @@ const api: NodeTerminalApi = {
},
chat: {
readTranscript: (sessionId, cwd, accountId, nodeId, agentId) =>
- ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId)
+ ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId),
+ transcriptExists: (sessionId, accountId, nodeId) =>
+ ipcRenderer.invoke(IPC.transcriptExists, sessionId, accountId, nodeId)
},
claudeAccounts: {
add: (ctx) => ipcRenderer.invoke(IPC.claudeAccountsAdd, ctx),
diff --git a/src/renderer/bridge/relay-api.ts b/src/renderer/bridge/relay-api.ts
index a9bc917d0..2b719d138 100644
--- a/src/renderer/bridge/relay-api.ts
+++ b/src/renderer/bridge/relay-api.ts
@@ -143,9 +143,12 @@ export function buildRelayApi(connectionId: string, transport?: FrameTransport):
// ── Deferred over the relay in v1 — documented degrades (a clean refusal, not a wrong-machine
// silent no-op): ──
- // `chat` is now just readTranscript (the SDK chat node was removed). It has no relay builder:
- // reading a transcript over the relay would read THIS machine's transcript, not the host's, so
- // refuse with E_UNSUPPORTED instead. contextLink / transcripts / handoff stay LOCAL by way of
+ // `chat` is now just readTranscript + transcriptExists (the SDK chat node was removed). It has
+ // no relay builder: reading a transcript over the relay would read THIS machine's transcript,
+ // not the host's, so `readTranscript` refuses with E_UNSUPPORTED instead. `transcriptExists`
+ // takes the stub's `'unknown'` for the same reason and the opposite shape — its consumer acts
+ // on a NEGATIVE, so answering about the wrong machine would drop a live conversation's
+ // `--resume`; `unknown` is exactly "we could not look", i.e. resume as before. contextLink / transcripts / handoff stay LOCAL by way of
// `...local` (a v1 degrade: they read/write on this machine, not the host). boardLog is now
// bridged to the host (see above) — it no longer rides `...local`.
chat: stub.chat,
diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.ts
index d34f7145a..3f239a0e8 100644
--- a/src/renderer/bridge/stubs.ts
+++ b/src/renderer/bridge/stubs.ts
@@ -355,7 +355,12 @@ export function buildStubApi(): Omit<
materializeShared: () => Promise.resolve([])
},
chat: {
- readTranscript: U('chat.readTranscript')
+ readTranscript: U('chat.readTranscript'),
+ // Resolves rather than rejects, like the two `cliCaps` above and for the same reason: cold
+ // restore awaits this on the boot path, and its whole contract is that anything it cannot
+ // judge is `unknown` ⇒ resume exactly as before. A rejection here would be a second way of
+ // saying the same thing that every caller would have to remember to catch.
+ transcriptExists: () => Promise.resolve('unknown' as const)
},
claudeAccounts: {
add: U('claudeAccounts.add'),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 442e9fff5..d28812fe9 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -23,6 +23,7 @@ import {
type LogRecord,
type BoardLogReadResult,
type ChatTranscriptResult,
+ type TranscriptPresence,
type ClaudeApi,
type ClaudeCliCaps,
type GrokApi,
@@ -899,7 +900,20 @@ export function buildTranscriptApi(
accountId,
nodeId,
agentId
- ) as Promise<ChatTranscriptResult>
+ ) as Promise<ChatTranscriptResult>,
+ // A REAL implementation, not a stub: the server runs on the machine holding these
+ // transcripts, so its answer is as good as the desktop's local leg. A failed request
+ // degrades to `unknown` (never `absent`) — cold restore acts on a negative, so the wrong
+ // degrade would drop a live conversation's `--resume` because a socket blipped.
+ transcriptExists: (sessionId, accountId, nodeId) =>
+ (
+ client.request(
+ IPC.transcriptExists,
+ sessionId,
+ accountId,
+ nodeId
+ ) as Promise<TranscriptPresence>
+ ).catch(() => 'unknown' as const)
},
claudeReadTranscript: (sessionId, cwd, accountId, nodeId) =>
client.request(
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 472693909..565f67f91 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -126,6 +126,8 @@ import {
type PauseOutcome,
type ResumePhaseOutcome
} from '../terminal/agent-restart'
+import { coldResumeDecision, shouldProbeTranscript } from '../terminal/cold-resume-session'
+import type { TranscriptPresence } from '@shared/types'
import {
looksDropped,
looksDroppedCandidate,
@@ -820,6 +822,17 @@ interface CoState {
* respawn clears it.
*/
staleCwd: boolean
+ /**
+ * This node COLD-STARTED and the conversation its persisted session id names is gone, so the
+ * agent was launched bare instead of resuming a dead id (see `cold-resume-session.ts`).
+ *
+ * A slim banner rather than an overlay, for the same reason `staleCwd` is one: the terminal
+ * underneath is alive and working — the agent started, it simply started fresh. Nothing to
+ * retry, so the only control is a dismiss. Announced at all because the alternative is what
+ * this fixes from the other side: a fresh conversation opened in silence, under a node whose
+ * title, badge and history all still describe the old one.
+ */
+ lostSession: boolean
}
const NO_CO: CoState = {
letterbox: false,
@@ -827,7 +840,8 @@ const NO_CO: CoState = {
ended: false,
offline: false,
spawnError: null,
- staleCwd: false
+ staleCwd: false,
+ lostSession: false
}
const coStates = new Map<string, CoState>()
const coSubs = new Map<string, (s: CoState) => void>()
@@ -1035,7 +1049,8 @@ function setCo(key: string, patch: Partial<CoState>): void {
next.ended === prev.ended &&
next.offline === prev.offline &&
next.spawnError === prev.spawnError &&
- next.staleCwd === prev.staleCwd
+ next.staleCwd === prev.staleCwd &&
+ next.lostSession === prev.lostSession
)
return
coStates.set(key, next)
@@ -1859,6 +1874,7 @@ export function TerminalNode({
}))
}
const dismissStaleCwd = (): void => setCo(termKey, { staleCwd: false })
+ const dismissLostSession = (): void => setCo(termKey, { lostSession: false })
// "Not connected" (CoState.offline): the host was unreachable, so this node has no session
// anywhere. Ask the coordinator to re-establish the project's master NOW — it flushes the
@@ -3022,6 +3038,10 @@ export function TerminalNode({
// Truthful on EVERY result, not only when set: a clean respawn ("Restart in folder", or
// any refresh that landed on a healthy session) must take the banner down with it.
setCo(termKey, { staleCwd: !!staleCwd })
+ // Same rule for the lost-conversation notice, and it is cleared HERE (before the
+ // cold-restore branch below can raise it) so a respawn that resumes cleanly — or any
+ // warm reattach, which never reaches that branch at all — takes the old banner down.
+ setCo(termKey, { lostSession: false })
// Catch up a size change that landed while the spawn was in flight (applyFit skips the
// IPC until sessionId is set, and the observer won't re-fire without another change).
applyFit()
@@ -3343,6 +3363,26 @@ export function TerminalNode({
// relaunched empty while their transcripts sat on disk, unreachable.
const st = useAgentStatus.getState().byId[id]
const priorId = st?.sessionId || data.agentSessionId
+ // …and is that conversation still THERE? A persisted id outlives its transcript
+ // (claude's 30-day cleanup, a `/clear`, a removed account, an id minted for a session
+ // that never ran), and `claude --resume <dead id>` prints "No conversation found with
+ // session ID" and exits — leaving the pane at a bare shell with an agent badge over it.
+ // Measured on one host: 20 of 108 live sessions sat in exactly that state.
+ //
+ // Only a POSITIVE `absent` drops the id (see `coldResumeDecision` for why the two errors
+ // are not symmetric). `data.accountId` is the right scope and `accountForReads` is not:
+ // the question is whether the command we are about to type will find the conversation,
+ // and that command runs under the config dir `data.accountId` names.
+ const presence = shouldProbeTranscript(priorId, agentId)
+ ? await api.chat
+ .transcriptExists(priorId!, data.accountId, id)
+ .catch((): TranscriptPresence => 'unknown')
+ : ('unknown' as TranscriptPresence)
+ const resume = coldResumeDecision(priorId, presence)
+ // Say so rather than starting a fresh conversation in silence. `life.dead` first, like
+ // the spawn-rejection handler below: a node unmounted mid-probe must not publish into a
+ // key the next mount reads.
+ if (resume.lostSession && !life.dead) setCo(termKey, { lostSession: true })
// Re-resolve the mode at relaunch: it's a property of how a session is launched, not
// a persisted property of the node, so the current setting wins after a reboot. Awaited
// (not the sync `activePermissionMode`) because this fires on mount: right after a machine
@@ -3372,7 +3412,7 @@ export function TerminalNode({
{
agentId,
customAgent,
- sessionId: priorId || undefined,
+ sessionId: resume.sessionId,
permissionMode: mode,
model: data.agentModel,
sharedIdentity: shared,
@@ -5394,6 +5434,33 @@ export function TerminalNode({
</button>
</div>
)}
+ {/* Lost conversation: the cold restore could not find the transcript its persisted session
+ id names, so the agent was launched BARE. Same slim top banner as staleCwd above, and
+ for the same reason — the terminal underneath is alive; only its history is missing.
+ Yields to staleCwd (a dead working directory is the bigger problem, and two stacked
+ banners would cover the screen). No action button: there is nothing to retry, the
+ conversation is gone. */}
+ {!co.closed &&
+ !co.ended &&
+ !co.spawnError &&
+ !co.offline &&
+ !co.staleCwd &&
+ co.lostSession &&
+ !offscreenDown && (
+ <div className="term-node__stalecwd nodrag">
+ <span className="term-node__stalecwd-text">
+ The previous conversation could not be found — this agent started fresh.
+ </span>
+ <button
+ className="term-node__stalecwd-dismiss"
+ onClick={dismissLostSession}
+ title="Dismiss"
+ aria-label="Dismiss"
+ >
+ ×
+ </button>
+ </div>
+ )}
{armed && !mdMode && (
<div
className="term-hover-guard"
diff --git a/src/renderer/nodes/cold-resume-wiring.test.ts b/src/renderer/nodes/cold-resume-wiring.test.ts
new file mode 100644
index 000000000..30fb177a0
--- /dev/null
+++ b/src/renderer/nodes/cold-resume-wiring.test.ts
@@ -0,0 +1,77 @@
+// TerminalNode's cold-restore wiring, and the CoState trap that comes with a new field.
+//
+// The DECISION is pure and behaviourally tested in `terminal/cold-resume-session.test.ts`; the
+// resolver behind it in `core/transcript-ipc.test.ts`. What only the source can show is that the
+// node asks before it resumes, that it resumes with the decision's id rather than the raw one,
+// and that its new banner is actually reachable — which in this file is not a given: `setCo`
+// compares fields by hand, so a field left out of that list is written and then SWALLOWED, with
+// the banner silently never rendering. That has already happened once (`spawnError`), which is
+// why the comment there says "If you add a CoState field, add it here" — and why this test asks
+// for EVERY field rather than for the one being added today.
+
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+
+const src = fs.readFileSync(path.resolve(__dirname, 'TerminalNode.tsx'), 'utf8').replace(/\r\n/g, '\n')
+
+/** The `interface CoState { … }` body. */
+function coStateBody(): string {
+ const start = src.indexOf('interface CoState {')
+ expect(start, 'CoState must still exist').toBeGreaterThan(-1)
+ const end = src.indexOf('const NO_CO: CoState', start)
+ expect(end).toBeGreaterThan(start)
+ return src.slice(start, end)
+}
+
+/** The equality guard inside `setCo`. */
+function setCoGuard(): string {
+ const start = src.indexOf('function setCo(')
+ expect(start, 'setCo must still exist').toBeGreaterThan(-1)
+ const end = src.indexOf('coStates.set(key, next)', start)
+ expect(end).toBeGreaterThan(start)
+ return src.slice(start, end)
+}
+
+describe('setCo compares every CoState field (the swallowed-write trap)', () => {
+ it('names each field in the equality guard, so no patch is silently dropped', () => {
+ const fields = [...coStateBody().matchAll(/^ {2}(\w+):/gm)].map((m) => m[1])
+ // Sanity: the scrape found the shape it expects, not zero fields.
+ expect(fields).toContain('spawnError')
+ expect(fields).toContain('lostSession')
+ const guard = setCoGuard()
+ for (const f of fields) {
+ expect(guard, `setCo must compare CoState.${f} or a { ${f} } patch is swallowed`).toContain(
+ `next.${f} === prev.${f}`
+ )
+ }
+ })
+})
+
+describe('cold restore checks the transcript before resuming a persisted id', () => {
+ it('probes through the shared gate + decision, never inline', () => {
+ expect(src).toContain(
+ "import { coldResumeDecision, shouldProbeTranscript } from '../terminal/cold-resume-session'"
+ )
+ expect(src).toMatch(/shouldProbeTranscript\(priorId, agentId\)/)
+ expect(src).toMatch(/coldResumeDecision\(priorId, presence\)/)
+ })
+
+ it('resumes with the DECISION’s id, not the raw persisted one', () => {
+ // The whole fix is this one substitution. `sessionId: priorId` would compile, pass every
+ // other test here, and do nothing at all.
+ expect(src).toContain('sessionId: resume.sessionId')
+ expect(src).not.toContain('sessionId: priorId || undefined')
+ })
+
+ it('never rejects — an unreachable probe degrades to `unknown`, i.e. resume as before', () => {
+ expect(src).toMatch(/\.catch\(\(\): TranscriptPresence => 'unknown'\)/)
+ })
+
+ it('says so when it drops an id, and only when it did', () => {
+ expect(src).toMatch(/if \(resume\.lostSession && !life\.dead\) setCo\(termKey, \{ lostSession: true \}\)/)
+ // Cleared on every create result, so a clean respawn — or a warm reattach, which never
+ // reaches the cold-restore branch — takes an old banner down.
+ expect(src).toContain('setCo(termKey, { lostSession: false })')
+ })
+})
diff --git a/src/renderer/terminal/cold-resume-session.test.ts b/src/renderer/terminal/cold-resume-session.test.ts
new file mode 100644
index 000000000..431660105
--- /dev/null
+++ b/src/renderer/terminal/cold-resume-session.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest'
+import { coldResumeDecision, shouldProbeTranscript } from './cold-resume-session'
+
+const ID = '46b36ce2-dd77-4f5e-a89e-4a0e831e83df'
+
+describe('coldResumeDecision — only a positive `absent` drops the resume', () => {
+ it('drops the id and raises the notice when the transcript is gone', () => {
+ expect(coldResumeDecision(ID, 'absent')).toEqual({ sessionId: undefined, lostSession: true })
+ })
+
+ it('resumes when the transcript is there', () => {
+ expect(coldResumeDecision(ID, 'present')).toEqual({ sessionId: ID, lostSession: false })
+ })
+
+ it('resumes on `unknown` — a probe that could not look is not evidence of deletion', () => {
+ // The asymmetry this encodes: wrongly resuming a dead id costs one error line and a bare
+ // shell; wrongly dropping a LIVE id silently opens a blank conversation over work the user
+ // believes is continuing. `unknown` must therefore behave exactly as it did before the probe.
+ expect(coldResumeDecision(ID, 'unknown')).toEqual({ sessionId: ID, lostSession: false })
+ })
+
+ it('raises no notice when there was no id to lose', () => {
+ // A first open has nothing persisted. `absent` is meaningless there, and a banner saying a
+ // conversation could not be found would be an invented failure.
+ for (const p of ['absent', 'present', 'unknown'] as const) {
+ expect(coldResumeDecision(undefined, p)).toEqual({ sessionId: undefined, lostSession: false })
+ }
+ })
+
+ it('normalises an empty id to undefined rather than resuming with ""', () => {
+ expect(coldResumeDecision('', 'unknown')).toEqual({ sessionId: undefined, lostSession: false })
+ })
+})
+
+describe('shouldProbeTranscript — who may be asked', () => {
+ it('asks for claude, whose transcripts this probe actually resolves', () => {
+ expect(shouldProbeTranscript(ID, 'claude')).toBe(true)
+ })
+
+ it('never asks for an agent whose id this resolver cannot find', () => {
+ // codex/gemini/grok ids miss claude's resolver by construction — EVERY time — so a probe
+ // would answer `absent` for a perfectly good session and drop its resume. These agents keep
+ // today's behaviour until the probe learns their layouts.
+ for (const a of ['codex', 'gemini', 'grok', 'copilot', 'opencode'] as const) {
+ expect(shouldProbeTranscript(ID, a)).toBe(false)
+ }
+ })
+
+ it('never asks without an id, and never asks for a plain terminal', () => {
+ expect(shouldProbeTranscript(undefined, 'claude')).toBe(false)
+ expect(shouldProbeTranscript('', 'claude')).toBe(false)
+ expect(shouldProbeTranscript(ID, undefined)).toBe(false)
+ })
+})
diff --git a/src/renderer/terminal/cold-resume-session.ts b/src/renderer/terminal/cold-resume-session.ts
new file mode 100644
index 000000000..7ba27131d
--- /dev/null
+++ b/src/renderer/terminal/cold-resume-session.ts
@@ -0,0 +1,75 @@
+/**
+ * Cold restore's last question before it types `claude --resume <id>`: is that conversation still
+ * there?
+ *
+ * ## What goes wrong without this
+ *
+ * A cold start (reboot, first open, a reaped tmux server) relaunches an agent node's CLI and
+ * resumes the session id nodeterm persisted for it — the live one from hooks, else the id minted at
+ * node creation. Neither is evidence the transcript still EXISTS. Claude's own 30-day cleanup
+ * removes old ones, a `/clear` mints a new id, a managed account can be removed, a minted id
+ * belongs to a session that never ran. When the id is dead the CLI prints
+ *
+ * No conversation found with session ID: <uuid>
+ *
+ * and exits, leaving the pane at a bare shell. Nothing noticed: the node kept its agent badge,
+ * the terminal looked idle, and the only evidence was one line of scrollback.
+ *
+ * MEASURED on the reporting host (2026-09-09, `nodeterm-rmt` socket, 108 live sessions): **20**
+ * panes sat at a bare shell showing exactly that line, and not one of the 20 session ids had a
+ * `<id>.jsonl` anywhere under the system `~/.claude/projects` or the managed account root. The
+ * ids outlived their transcripts; the resume was never going to work.
+ *
+ * ## The rule
+ *
+ * `absent` — and ONLY `absent` — drops the id, so the node launches the agent bare instead of
+ * resuming something that is gone. A bare launch loses nothing that was still there: the
+ * conversation it would have resumed does not exist.
+ *
+ * `unknown` resumes exactly as before. That is not caution for its own sake — the cost of the two
+ * errors is wildly asymmetric. Wrongly resuming a dead id reproduces today's bug (one bad line,
+ * a bare shell, recoverable). Wrongly dropping a LIVE id silently starts a blank conversation and
+ * strands work the user believed was continuing, with the original still on disk and nothing on
+ * screen pointing at it. So an unreadable transcript root, a downed ControlMaster, a relay tab,
+ * a surface with no reader and a rejected call all mean "resume".
+ *
+ * ## Why the agent gate is `readsClaudeTranscript`
+ *
+ * The probe resolves a claude-shaped `<id>.jsonl` under a claude config dir. A codex, gemini or
+ * grok id misses that resolver by construction — every time — so asking it about one would answer
+ * `absent` for a perfectly good session and drop its resume. Those agents keep today's behaviour
+ * unchanged until someone teaches the probe their layouts (`handoff/locate.ts` already has
+ * `locateCodex` / `locateGemini` / `locateGrok` by sessionId — that is the seam).
+ */
+import type { TranscriptPresence } from '@shared/types'
+import type { AgentId } from '@shared/agents/config'
+import { readsClaudeTranscript } from '@renderer/lib/transcriptGates'
+
+/** Is there anything worth asking about? Cheap gate, so the common paths pay no round trip. */
+export function shouldProbeTranscript(
+ priorId: string | undefined,
+ agentId: AgentId | undefined
+): boolean {
+ return !!priorId && readsClaudeTranscript(agentId)
+}
+
+export interface ColdResumeDecision {
+ /** The id to resume with — `undefined` means launch the agent bare. */
+ sessionId: string | undefined
+ /** Did we DROP an id because its transcript is gone? Drives the node's notice. */
+ lostSession: boolean
+}
+
+/**
+ * Turn the probe's answer into the id cold restore resumes with.
+ *
+ * Pure and total: every input that is not a positive `absent` on a real id resumes with that id,
+ * which is byte-for-byte the pre-existing behaviour.
+ */
+export function coldResumeDecision(
+ priorId: string | undefined,
+ presence: TranscriptPresence
+): ColdResumeDecision {
+ if (priorId && presence === 'absent') return { sessionId: undefined, lostSession: true }
+ return { sessionId: priorId || undefined, lostSession: false }
+}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index fb322ceed..68a1c1976 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -39,6 +39,10 @@ export const IPC = {
ptyRaiseDeviceLimit: 'pty:raise-device-limit',
claudeReadTranscript: 'claude:read-transcript',
chatReadTranscript: 'chat:read-transcript',
+ /** Does a claude-shaped transcript exist for this session id? Tri-state
+ * (`present | absent | unknown`) — see `TranscriptPresence`. The one caller that ACTS on a
+ * negative is cold restore, so "we could not look" must never read as "it is gone". */
+ transcriptExists: 'transcript:exists',
claudeAccountsAdd: 'claude-accounts:add',
claudeAccountsWaitLogin: 'claude-accounts:wait-login',
claudeAccountsCancelWait: 'claude-accounts:cancel-wait',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 609b10b9c..5d4cfefe4 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2465,6 +2465,18 @@ export interface ChatTranscriptResult {
found: boolean
}
+/**
+ * Three answers to "is there a transcript for this session id?", because two are not enough.
+ *
+ * `absent` is a POSITIVE finding — we read the place it would be and it is not there. `unknown`
+ * is "we could not look": an unreadable root, a downed ControlMaster, a surface with no reader,
+ * an id we would not put on a command line anyway. The only consumer that acts on a negative is
+ * cold restore (it launches the agent bare instead of resuming a dead id), and for it the two
+ * must never collapse: dropping a resume on `unknown` would throw away a live conversation
+ * because an ssh call blipped.
+ */
+export type TranscriptPresence = 'present' | 'absent' | 'unknown'
+
export interface ChatApi {
/**
* Reads an agent session transcript as structured chat messages.
@@ -2484,6 +2496,23 @@ export interface ChatApi {
nodeId?: string,
agentId?: string
): Promise<ChatTranscriptResult>
+
+ /**
+ * Is the transcript this session id names still on disk?
+ *
+ * Resolved STRICTLY by `sessionId` — no cwd fallback, which would answer `present` from another
+ * session's newest file. `nodeId` lets an SSH-project node be asked on its HOST. Never rejects:
+ * anything it cannot judge is `unknown`.
+ *
+ * Claude-shaped transcripts only (`readsClaudeTranscript` is the caller-side gate) — every other
+ * agent's id misses this resolver by construction, and reporting that as `absent` would drop a
+ * perfectly good resume.
+ */
+ transcriptExists(
+ sessionId: string,
+ accountId?: string,
+ nodeId?: string
+ ): Promise<TranscriptPresence>
}
/** Optional SSH context for account ops. When `projectId` names a connected SSH project, the