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): never read a remote node's transcript from this machine
reviewb02bf984eb0d
diff --git a/CLAUDE.md b/CLAUDE.mdindex 91784a8d0..2f60fca48 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2466,6 +2466,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`locatedTranscriptSessions` so a dead one can be dropped on an empty read (the panel's Retrywould otherwise replay it forever) — a HOOK-fed ref is never dropped that way, since an emptyread there is usually a transient master hiccup and forgetting it sends the next read local.+ **A remote node never falls through to this machine** (2026-09-28): the handler decides+ remoteness from the SHELL's records (`isRemoteNode` dep — live remote pty or+ `workspaceStore.sshProjectIdForNode`, never a renderer flag) and applies `remoteOnly` to the+ paged ⌘M read, the legacy read, the find-bar index (`[]`) and `transcriptExists` (`unknown`).+ The host locate is tri-state (`locateRemoteTranscriptRef`): a CLEAN MISS is `found:false`, a+ failure to ask is `unreadable` ("Couldn't read the transcript.") — the phone's `chat.page` shares+ the same deps and the same distinction. Before this, a mounted SSH node whose locate missed (or+ whose master was down) read THIS machine's resolver, cwd-newest fallback included.It is generated shell, so `remote-transcript-locate.test.ts` runs it for real under `/bin/sh`against a fake host tree — keep it that way. (2) **The cwd fallback keeps `accountId`** in BOTH`resolveTranscript` and `contextEnsure`; without it a managed-account node fell back to thediff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.mdindex 7c25217f0..3ebdf06c8 100644--- a/docs/mobile-chat-view.md+++ b/docs/mobile-chat-view.md@@ -103,7 +103,7 @@ as `hostBridge.chat` in `main/index.ts`, forwarded by both phone hosts).| verb | params | reply | does ||---|---|---|---|-| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | Only for agents with a chat view — `canChat(capabilityAgentId(agent))` (claude, grok, and custom agents whose base harness is one of them); anything else is refused before any read. `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; grok unpaged) + `model`/`effort`, `version: 1`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id; the fallbacks apply only when the renderer does not answer within 3 s or knows none. **Remote (SSH-project) nodes are read REMOTE-ONLY** (`remoteOnly`): over the live pty's ControlMaster, else the node's PROJECT's master (an idle tab / any node after a restart has no pty), and never from this machine's disk — a remote node with no reachable master, or a host that did not answer, is `Could not read the transcript.`, not an empty page. The cwd rides ONLY for a remote node with a known id (the host-side locate needs it); locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `found:false`. `found:false` therefore always means "looked, and there is no transcript". The reply's `page.sessionId` is exactly the id that read used (absent when none was resolved); the phone should PREFER it over the mirror's `sessionId` as the page's thread identity — the mirror lags — every 4 s on SSH, up to ~30 s on relay (`projects.list` off-LAN) — so right after `/clear` or a resume it still names the old session while the page already comes from the new transcript, and merging by byte `key` across the two would splice threads. `sessionId` is present on a `found:false` page too (an id was resolved, its transcript is missing — e.g. a fresh session that has not written yet): a new id on such a page alone is NOT a confirmed thread switch, so the phone must not clear the thread on it. Additive field: `version` stays 1, and an older desktop simply omits it (fall back to the mirror). |+| `chat.page` | `{nodeId, before?, maxBytes?}` | `{page: ChatPage}` | Only for agents with a chat view — `canChat(capabilityAgentId(agent))` (claude, grok, and custom agents whose base harness is one of them); anything else is refused before any read. `readChatTranscript` with the ⌘M panel's own deps (paged ALWAYS — an absent page is the default 256 KB tail; grok unpaged) + `model`/`effort`, `version: 1`. Session id: the RENDERER's agent-status id first (what ⌘M reads — after a desktop restart a hook-fed id lives only there), then the mirror's, then the node's minted id; the fallbacks apply only when the renderer does not answer within 3 s or knows none. **Remote (SSH-project) nodes are read REMOTE-ONLY** (`remoteOnly`): over the live pty's ControlMaster, else the node's PROJECT's master (an idle tab / any node after a restart has no pty), and never from this machine's disk — a remote node with no reachable master, or a host that did not answer, is `Could not read the transcript.`, not an empty page. The host-side locate is TRI-STATE (`locateRemoteTranscriptRef`, `src/main/remote-transcript-page.ts`): a CLEAN MISS (the host looked and has no such file, or there is no session id to look for) is `found:false`, and only a failure to ask (no master, no resolved home, a failed ssh, a path outside the jail, a failed ranged read) is the error. The desktop ⌘M panel reads through the SAME deps and the same rule: its IPC handler decides remoteness from the shell's own records (`isRemoteNode` — live remote pty or `workspaceStore.sshProjectIdForNode`, never a renderer flag) and applies `remoteOnly` to the paged read, the legacy unpaged read, the find-bar index and the presence probe (`unknown`), and shows `unreadable` as "Couldn't read the transcript." The cwd rides ONLY for a remote node with a known id (the host-side locate needs it); locally a known-but-dead id must not fall back to the cwd's newest transcript (another node's), and with no id at all ⇒ `found:false`. `found:false` therefore always means "looked, and there is no transcript". The reply's `page.sessionId` is exactly the id that read used (absent when none was resolved); the phone should PREFER it over the mirror's `sessionId` as the page's thread identity — the mirror lags — every 4 s on SSH, up to ~30 s on relay (`projects.list` off-LAN) — so right after `/clear` or a resume it still names the old session while the page already comes from the new transcript, and merging by byte `key` across the two would splice threads. `sessionId` is present on a `found:false` page too (an id was resolved, its transcript is missing — e.g. a fresh session that has not written yet): a new id on such a page alone is NOT a confirmed thread switch, so the phone must not clear the thread on it. Additive field: `version` stays 1, and an older desktop simply omits it (fall back to the mirror). || `chat.status` | `{nodeId}` | `{status: ChatStatus}` | the renderer's agent-status entry (`state` null = unknown, `held`, hibernated/paused/dropped/sessionEnded) + `structuredAnswers` = the held ticket is in main's structured-ticket ledger (script revision ≥ 5) + the host mirror's `hostRefuses`/`refusal` + `version: 1`. || `chat.send` | `{nodeId, text}` | `ChatSendOutcome` = `{result, reason?}` | text capped at 64000 UTF-16 units RAW, then ESC + C0/C1 stripped (`\n`, `\t` kept; `sanitizeChatText`); refused FIRST (`reason` `working`/`dialog`) when the host's mirror says the agent is working / waiting / blocked or holds a question or approval ticket (renderer state is transient after a reload); refused `busy` while another send to the same node is still in flight (held until that send SETTLES, capped at 30 s); then the renderer runs the ⌘M composer's gate at send time (`chatSendRefusal` = `agentProcessInPane` + state ∈ {done, unknown} → its own kind as `reason`) plus "no held request" (`dialog`), then `pty.sendText`. `'sent'` only for `sendText === true`; a paste the pane refused is `refused`/`failed`. || `agent.answer` | `{nodeId, pendingId, answer}` | `{ok: boolean}` | `answerHeldPermission` with the node's own I/O (local fs, or the SSH project's ControlMaster — the same `heldPermissionIoFor` the desktop answer path uses): validated against the pending request file, structured-ticket gated, no `setMode auto`. The `pendingId` must belong to THIS node — one of the mirror's approval tickets for it, or the renderer's `held.pendingId` (plans / questions) — else `{ok:false}` with no I/O and no answered event. Success emits the same optimistic "answered" event. |diff --git a/src/core/transcript-ipc.test.ts b/src/core/transcript-ipc.test.tsindex 893d485f1..7e002fa27 100644--- a/src/core/transcript-ipc.test.ts+++ b/src/core/transcript-ipc.test.ts@@ -524,3 +524,71 @@ describe('readChatTranscript — remoteOnly (a node the host KNOWS is remote)',expect(res.unreadable).toBeUndefined()})})++// ⌘M (the renderer's `chat:read-transcript`) never said which node was remote, so a mounted SSH+// node whose host locate missed — or whose master was down — fell through to THIS machine's+// resolver, cwd-newest fallback included: a wrong-machine, wrong-session read. The shell now+// decides remoteness from its own records (`isRemoteNode`), never from anything the renderer sends.+describe('registerTranscriptIpc — a node the SHELL knows is remote (isRemoteNode)', () => {+ const pagedFor = (nodeId: string) =>+ f.handlers[IPC.chatReadTranscript](SID, CWD, undefined, nodeId, 'claude', {}) as Promise<ChatTranscriptResult>+ const exists = (nodeId: string) =>+ f.handlers[IPC.transcriptExists](SID, undefined, nodeId) as Promise<string>+ const notFound = { messages: [], found: false, olderCursor: null, unmatchedResults: [] }++ it('host looked, no file (clean miss) → found:false, NOT unreadable, and no local read', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ const pathFor = vi.fn(() => undefined)+ registerTranscriptIpc({ pathFor, isRemoteNode: () => true, readRemotePage: async () => ({ ok: false, absent: true }) })+ expect(await pagedFor('nt-ssh')).toEqual(notFound)+ expect(pathFor).not.toHaveBeenCalled()+ })++ it('master down (the remote leg cannot resolve a remote node) → unreadable, no local read', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ const pathFor = vi.fn(() => undefined)+ registerTranscriptIpc({ pathFor, isRemoteNode: () => true, readRemotePage: async () => null })+ expect(await pagedFor('nt-ssh')).toEqual({ ...notFound, unreadable: true })+ expect(pathFor).not.toHaveBeenCalled()+ })++ it('a local node is unchanged: a null remote leg still reads this machine', async () => {+ writeTranscript(lines(assistantLine('local')))+ const isRemoteNode = vi.fn(() => false)+ registerTranscriptIpc({ isRemoteNode, readRemotePage: async () => null })+ const res = await pagedFor('nt-local')+ expect(res.found).toBe(true)+ expect(res.messages[0].parts[0]).toMatchObject({ text: 'local' })+ expect(isRemoteNode).toHaveBeenCalledWith('nt-local')+ })++ it('the legacy unpaged read does not leak either', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ registerTranscriptIpc({ isRemoteNode: () => true, readRemote: async () => null })+ expect(await chat('nt-ssh')).toEqual({ messages: [], found: false })+ })++ it('the find-bar index (claude:read-transcript) does not index this machine for a remote node', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ registerTranscriptIpc({ isRemoteNode: () => true, readRemote: async () => null })+ expect(await search('nt-ssh')).toEqual([])+ })++ it('presence of a remote node the remote leg could not ask is unknown — never a local scan', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ registerTranscriptIpc({ isRemoteNode: () => true, remoteExists: async () => null })+ expect(await exists('nt-ssh')).toBe('unknown')+ })+})++describe('readChatTranscript — the phone path (remoteOnly) tells a clean miss from a failure', () => {+ it('a clean miss on the host is found:false without unreadable', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ const res = await readChatTranscript(+ { sessionId: SID, cwd: CWD, nodeId: 'nt-1', agentId: 'claude', remoteOnly: true },+ {},+ { readRemotePage: async () => ({ ok: false, absent: true }) }+ )+ expect(res).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })+ })+})diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.tsindex 28cc7c8ed..a58b6a080 100644--- a/src/core/transcript-ipc.ts+++ b/src/core/transcript-ipc.ts@@ -63,14 +63,24 @@ export interface TranscriptIpcDeps {* ONE page of a REMOTE node's transcript — a ranged read on the host, so a paged ⌘M open moves* a window over ssh instead of the legacy 5 MB tail. `null` = not a remote session (same* convention as `readRemote`); `{ok:false}` = it IS remote and the host could not be read, which- * must end as not-found rather than fall through to THIS machine's disk. `data` is the file's+ * must end as not-found rather than fall through to THIS machine's disk; `{ok:false, absent:true}`+ * = it IS remote and the host LOOKED and has no such transcript (or there is no session id to look+ * for) — a clean miss, which is `found:false` WITHOUT `unreadable`. `data` is the file's* bytes from absolute offset `start` (one lookbehind byte included — see `parseChatWindow`).* Electron-only.*/readRemotePage?(q: TranscriptQuery, page: ChatTranscriptPage): Promise<RemoteTranscriptPage | null>+ /**+ * Is this node an SSH-project node — from the SHELL's own records (its workspace store, its live+ * pty), never from anything the renderer sends. Every channel below then applies `remoteOnly`:+ * a remote node whose remote leg cannot answer is a miss or a failure, never a read of THIS+ * machine's disk (claude's cwd-newest fallback there adopts a stranger's local session). Absent+ * (the Server Edition — it runs ON the host) = no node is remote, which is correct there.+ */+ isRemoteNode?(nodeId: string): boolean}-export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false }+export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false; absent?: true }/** How much a window with no complete line grows per re-read. ×4 reaches the 5 MB cap from the* default 256 KB tail in three extra reads, and from the 64 KB minimum in four. */@@ -143,7 +153,7 @@ async function readChatPage(if (readRemotePage) {const remote = await readRemotePage(q, page)if (remote !== null) {- if (!remote.ok) return unreadablePage()+ if (!remote.ok) return remote.absent ? notFoundPage() : unreadablePage()// A growth re-read that suddenly says "not remote" (null) is a failed read too — never a// reason to go read THIS machine's disk halfway through a remote page.return parseGrowingWindow(page, remote, async (p) => {@@ -189,8 +199,8 @@ export interface ChatReadQuery {accountId?: stringnodeId?: stringagentId?: string- /** See `TranscriptQuery.remoteOnly`. Honoured on the PAGED read (the only one the phone uses) and- * by grok's local-only reader; the legacy unpaged read ignores it. */+ /** See `TranscriptQuery.remoteOnly`. Honoured by every read: paged, legacy unpaged, and grok's+ * local-only reader. */remoteOnly?: boolean}@@ -233,6 +243,8 @@ export async function readChatTranscript(// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read failed// (master down, transcript gone), and the panel must be able to say so.if (remote !== null) return { messages: parseChatMessages(remote.split('\n')), found: !!remote }+ // A known-remote node the remote leg could not resolve: not found — never THIS machine's disk.+ if (remoteOnly) return { messages: [], found: false }const p = await resolveTranscript({ sessionId, cwd, accountId }, deps.pathFor)return p? { messages: await readChatMessages(p), found: true }@@ -242,6 +254,9 @@ export async function readChatTranscript(export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {const remoteText = (q: TranscriptQuery): Promise<string | null> =>deps.readRemote ? deps.readRemote(q) : Promise.resolve(null)+ // Decided HERE from the shell's records, for every channel — the renderer's arguments carry no+ // remoteness, and must not: a renderer flag would be one more thing a forged call could lie about.+ const isRemote = (nodeId: string | undefined): boolean => !!nodeId && !!deps.isRemoteNode?.(nodeId)platform().handle(IPC.claudeReadTranscript,@@ -253,6 +268,8 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {): Promise<TranscriptLine[]> => {const remote = await remoteText({ sessionId, cwd, accountId, nodeId })if (remote !== null) return parseTranscriptLines(remote)+ // The find bar must not index THIS machine's transcript for a remote node.+ if (isRemote(nodeId)) return []const p = await resolveTranscript({ sessionId, cwd, accountId }, deps.pathFor)return p ? readTranscriptLines(p) : []}@@ -271,6 +288,9 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {// only ever existed on the other one, and answer `absent` about it.const remote = deps.remoteExists ? await deps.remoteExists({ sessionId, cwd: undefined, accountId, nodeId }) : nullif (remote !== null) return remote+ // Remote by the shell's records but the remote leg could not ask (no live pty yet): `unknown`,+ // never a local scan whose `absent` would drop a resume.+ if (isRemote(nodeId)) return 'unknown'// 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)@@ -296,6 +316,10 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {agentId: string | undefined,rawPage?: unknown): Promise<ChatTranscriptResult> =>- readChatTranscript({ sessionId, cwd, accountId, nodeId, agentId }, rawPage, deps)+ readChatTranscript(+ { sessionId, cwd, accountId, nodeId, agentId, ...(isRemote(nodeId) ? { remoteOnly: true } : {}) },+ rawPage,+ deps+ ))}diff --git a/src/main/index.ts b/src/main/index.tsindex d1c36260f..35244a77c 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -234,9 +234,11 @@ import { createHostChat, mirrorChatSendRefusal } from './remote/host-chat'import type { ChatSendOutcome, HostChatReply, RendererChatStatus } from '../shared/mobile-chat'import {createReadRemotePage,+ locateRemoteTranscriptRef,remoteTargetForNode,forgetLocatedRef,rememberHookRef,+ type RemoteRefLookup,type RemoteTranscriptRefCache} from './remote-transcript-page'import { createRemoteContextTail } from './remote-context-tail'@@ -2523,6 +2525,39 @@ app.whenReady().then(async () => {// the returned shape is byte-identical to the local reader.const REMOTE_TRANSCRIPT_CAP = 5 * 1024 * 1024+ // Is this node remote by the shell's OWN records: a live remote pty, or an SSH-project node (an+ // idle tab, or any node after a restart, has no pty). Never a renderer-supplied flag.+ const isRemoteTranscriptNode = (nodeId: string): boolean =>+ !!ptyManager.sshRemoteForNode(nodeId) || workspaceStore.sshProjectIdForNode(nodeId) !== undefined+ // The tri-state host locate (ref / clean miss / could not ask) — see `locateRemoteTranscriptRef`.+ const locateRemoteRef = (+ q: { sessionId: string | undefined; cwd: string | undefined; accountId: string | undefined; nodeId: string | undefined },+ target: (nodeId: string) => { conn: import('../shared/ssh').SshConnection; controlPath: string } | undefined+ ): Promise<RemoteRefLookup> =>+ locateRemoteTranscriptRef(q, {+ cache: remoteTranscriptRefs,+ isRemote: isRemoteTranscriptNode,+ target,+ remoteHome: (controlPath) => sshProjectManager?.remoteHomeForControlPath(controlPath) ?? undefined,+ command: (remoteHome, { sessionId, cwd, accountId }) => {+ 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+ }+ }+ return locateRemoteTranscriptCommand(remoteTranscriptRoots(remoteHome, accountDir), cwd, sessionId)+ },+ run: (rt, cmd) =>+ sshProjectManager+ ? sshProjectManager.sshRun(childArgs(rt.conn, rt.controlPath, cmd))+ : Promise.resolve({ code: 1, stdout: '' }),+ isSafePath: (p, remoteHome) => isSafeRemoteTranscriptPath(p, remoteHome)+ })+/*** The remote ref for a session, resolving it on the HOST when no hook event has registered one.*@@ -2531,8 +2566,8 @@ app.whenReady().then(async () => {* would search this machine's disk for a session that exists only on the host (finding nothing,* or another local session that happens to share the cwd). Asking the host directly is what the* node id buys us; a hit is cached under the sessionId so the title poll and the next read get- * it for free. Fail-open at every step: no node id / not an SSH session / no resolved home /- * a failed ssh call all mean "not remote", which is the pre-existing local path.+ * it for free. Every "no ref" (a clean miss or a failure) collapses to `undefined` here, which is+ * what these fall-back callers want; a caller that must tell them apart uses `locateRemoteRef`.** `remote` overrides the live-pty lookup for callers that already know which host the node runs* on. `PtyManager.kill()` forgets a session on detach, so a backgrounded project's nodes are@@ -2546,45 +2581,11 @@ app.whenReady().then(async () => {nodeId: string | undefined,remote?: { conn: import('../shared/ssh').SshConnection; controlPath: string }): Promise<RemoteFileRef | undefined> => {- if (!sessionId) return undefined- const cached = remoteTranscriptBySession.get(sessionId)- if (cached) return cached- if (!nodeId) return undefined- const rt = remote ?? ptyManager.sshRemoteForNode(nodeId)- if (!rt || !sshProjectManager) return undefined- const remoteHome = sshProjectManager.remoteHomeForControlPath(rt.controlPath)- if (!remoteHome) return undefined- 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),- cwd,- sessionId+ const r = await locateRemoteRef(+ { sessionId, cwd, accountId, nodeId },+ (id) => remote ?? ptyManager.sshRemoteForNode(id))- if (!cmd) return undefined- let located: string | undefined- try {- const { code, stdout } = await sshProjectManager.sshRun(- childArgs(rt.conn, rt.controlPath, cmd)- )- located = code === 0 ? parseLocatedTranscript(stdout) : undefined- } catch {- return undefined- }- // Jailed exactly like a hook-supplied path: the command only ever emits paths under our own- // roots, but the answer still crosses a machine boundary before we read it.- if (!located || !isSafeRemoteTranscriptPath(located, remoteHome)) return undefined- const ref: RemoteFileRef = { conn: rt.conn, controlPath: rt.controlPath, path: located }- remoteTranscriptBySession.set(sessionId, ref)- locatedTranscriptSessions.add(sessionId)- return ref+ return typeof r === 'object' ? r : undefined}/**@@ -2685,7 +2686,7 @@ app.whenReady().then(async () => {const transcriptIpcDeps: TranscriptIpcDeps = {pathFor: (sessionId) => contextTail.pathFor(sessionId),readRemote: async ({ sessionId, cwd, accountId, nodeId }) => {- const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)+ const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId, nodeId ? sshTargetForNode(nodeId) : undefined)return ref ? await readRemoteTranscript(sessionId!, ref) : null},// The paged ⌘M read: a RANGED read on the host (window + file size in one ssh round trip)@@ -2694,12 +2695,16 @@ app.whenReady().then(async () => {// `readRemoteTranscript`; the path it reads is already jailed by `isSafeRemoteTranscriptPath`.readRemotePage: createReadRemotePage({cache: remoteTranscriptRefs,- refFor: ({ sessionId, cwd, accountId, nodeId }) =>- remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId, nodeId ? sshTargetForNode(nodeId) : undefined),+ // Tri-state: a clean miss on the host ('absent') and a failure to ask ('unreadable') end+ // differently — "no transcript" vs "couldn't read" — on the ⌘M panel and the phone alike.+ refFor: (q) => locateRemoteRef(q, sshTargetForNode),readPage: (ref, before, maxBytes) => remoteFile.readTranscriptPage(ref, before, maxBytes)}),remoteExists: async ({ sessionId, accountId, nodeId }) =>- sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null+ sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null,+ // Remoteness from THIS shell's records (live pty or SSH project), so every read channel refuses+ // to answer a remote node from this machine's disk — ⌘M, the find-bar index, presence.+ isRemoteNode: isRemoteTranscriptNode}registerTranscriptIpc(transcriptIpcDeps)diff --git a/src/main/remote-transcript-page.test.ts b/src/main/remote-transcript-page.test.tsindex 54ebc3b6c..bff5c023c 100644--- a/src/main/remote-transcript-page.test.ts+++ b/src/main/remote-transcript-page.test.ts@@ -1,5 +1,5 @@import { describe, expect, it, vi } from 'vitest'-import { createReadRemotePage, forgetLocatedRef, rememberHookRef, remoteTargetForNode, type RemoteTranscriptRefCache } from './remote-transcript-page'+import { createReadRemotePage, forgetLocatedRef, locateRemoteTranscriptRef, rememberHookRef, remoteTargetForNode, type RemoteTranscriptRefCache } from './remote-transcript-page'import type { RemoteFileRef } from './remote-ssh/remote-file'const ref = (path: string): RemoteFileRef => ({@@ -93,3 +93,66 @@ describe('remoteTargetForNode (which master a remote transcript read goes over)'expect(remoteTargetForNode('n', { live: () => undefined, projectIdFor: () => 'p', refForProject: () => undefined })).toBeUndefined()})})++describe('createReadRemotePage — a clean miss vs a failure', () => {+ it("the host looked and found nothing ('absent') is a clean miss, not a failed read", async () => {+ const readPage = vi.fn()+ const read = createReadRemotePage({ cache: cache(), refFor: async () => 'absent', readPage })+ expect(await read(q, PAGE)).toEqual({ ok: false, absent: true })+ expect(readPage).not.toHaveBeenCalled()+ })+ it("a remote session that could not be located ('unreadable') is a failed read", async () => {+ const read = createReadRemotePage({ cache: cache(), refFor: async () => 'unreadable', readPage: vi.fn() })+ expect(await read(q, PAGE)).toEqual({ ok: false })+ })+})++describe('locateRemoteTranscriptRef (the host-side locate, tri-state)', () => {+ const target = { conn: { host: 'h', user: 'u' } as RemoteFileRef['conn'], controlPath: '/cm' }+ const base = (over: Partial<Parameters<typeof locateRemoteTranscriptRef>[1]> = {}) => ({+ cache: cache(),+ isRemote: () => true,+ target: () => target,+ remoteHome: () => '/home/u',+ command: () => 'locate-cmd',+ run: vi.fn(async () => ({ code: 0, stdout: '/home/u/.claude/projects/-w/sid.jsonl\n' })),+ isSafePath: () => true,+ ...over+ })++ it('a located, jailed path is a ref — cached and marked as located by us', async () => {+ const d = base()+ const r = await locateRemoteTranscriptRef(q, d)+ expect(r).toEqual({ ...target, path: '/home/u/.claude/projects/-w/sid.jsonl' })+ expect(d.cache.bySession.get('sid')).toEqual(r)+ expect(d.cache.located.has('sid')).toBe(true)+ })+ it('a cached ref wins without asking the host', async () => {+ const d = base()+ d.cache.bySession.set('sid', ref('/cached'))+ expect(await locateRemoteTranscriptRef(q, d)).toEqual(ref('/cached'))+ expect(d.run).not.toHaveBeenCalled()+ })+ it("the host answered with no file (exit 0, empty) → 'absent'", async () => {+ expect(await locateRemoteTranscriptRef(q, base({ run: vi.fn(async () => ({ code: 0, stdout: '' })) }))).toBe('absent')+ })+ it("a remote node with no session id → 'absent' (nothing to look for), a local one → undefined", async () => {+ expect(await locateRemoteTranscriptRef({ ...q, sessionId: undefined }, base())).toBe('absent')+ expect(await locateRemoteTranscriptRef({ ...q, sessionId: undefined }, base({ isRemote: () => false }))).toBeUndefined()+ })+ it("an id no locate command accepts → 'absent'", async () => {+ expect(await locateRemoteTranscriptRef(q, base({ command: () => null }))).toBe('absent')+ })+ it("master down: a remote node with no reachable master → 'unreadable'; a local node → undefined", async () => {+ expect(await locateRemoteTranscriptRef(q, base({ target: () => undefined }))).toBe('unreadable')+ expect(await locateRemoteTranscriptRef(q, base({ target: () => undefined, isRemote: () => false }))).toBeUndefined()+ })+ it("no resolved home, a failed ssh (non-zero / throw), or a path outside the jail → 'unreadable'", async () => {+ expect(await locateRemoteTranscriptRef(q, base({ remoteHome: () => undefined }))).toBe('unreadable')+ expect(await locateRemoteTranscriptRef(q, base({ run: vi.fn(async () => ({ code: 255, stdout: '' })) }))).toBe('unreadable')+ expect(+ await locateRemoteTranscriptRef(q, base({ run: vi.fn(async () => { throw new Error('ssh') }) }))+ ).toBe('unreadable')+ expect(await locateRemoteTranscriptRef(q, base({ isSafePath: () => false }))).toBe('unreadable')+ })+})diff --git a/src/main/remote-transcript-page.ts b/src/main/remote-transcript-page.tsindex 5ca43dbae..2cc2600e5 100644--- a/src/main/remote-transcript-page.ts+++ b/src/main/remote-transcript-page.ts@@ -7,6 +7,7 @@ import type { RemoteTranscriptPage, TranscriptQuery } from '../core/transcript-iimport type { ChatTranscriptPage } from '../shared/chat-page'import type { TranscriptPage } from '../core/remote-ssh/transcript-window'import type { RemoteFileRef } from './remote-ssh/remote-file'+import { parseLocatedTranscript } from '../core/remote-transcript-locate'/** Remote transcript refs by sessionId, and which of them we located ourselves (vs hook-fed). */export interface RemoteTranscriptRefCache {@@ -28,16 +29,82 @@ export function rememberHookRef(cache: RemoteTranscriptRefCache, sessionId: stricache.located.delete(sessionId)}+/**+ * What a host-side locate answered. A ref; `'absent'` = the node IS remote and the host LOOKED and+ * has no such transcript (or there is no session id to look for) — a clean miss; `'unreadable'` =+ * the node IS remote and we could not ask (no master, no resolved home, a failed ssh, a path outside+ * the jail); `undefined` = not a remote session at all (take the local path).+ */+export type RemoteRefLookup = RemoteFileRef | 'absent' | 'unreadable' | undefined++/**+ * Locate a session's transcript ON the host, keeping "the host said no" apart from "we could not+ * ask". The two used to collapse into one `undefined` — correct for a reader that falls back, and+ * wrong for the ⌘M panel and the phone, which must say "no transcript" for the first and "couldn't+ * read" (a retry heals it) for the second. `locateRemoteTranscriptCommand` exits 0 on a clean miss+ * precisely so that "no transcript" is an ANSWER; this is the reader of that property.+ *+ * A hit is cached under the sessionId and marked as located by us (see `forgetLocatedRef`).+ */+export async function locateRemoteTranscriptRef<T extends { conn: RemoteFileRef['conn']; controlPath: string }>(+ q: Pick<TranscriptQuery, 'sessionId' | 'cwd' | 'accountId' | 'nodeId'>,+ deps: {+ cache: RemoteTranscriptRefCache+ /** The shell's own records say this node is remote (SSH project or live remote pty). */+ isRemote(nodeId: string): boolean+ /** The master to ask over, or undefined when there is none right now. */+ target(nodeId: string): T | undefined+ remoteHome(controlPath: string): string | undefined+ /** The locate shell line, or null when no transcript can exist for the id (malformed). */+ command(remoteHome: string, q: Pick<TranscriptQuery, 'sessionId' | 'cwd' | 'accountId'> & { sessionId: string }): string | null+ run(target: T, cmd: string): Promise<{ code: number; stdout: string }>+ isSafePath(path: string, remoteHome: string): boolean+ }+): Promise<RemoteRefLookup> {+ const remote = !!q.nodeId && deps.isRemote(q.nodeId)+ if (!q.sessionId) return remote ? 'absent' : undefined+ const cached = deps.cache.bySession.get(q.sessionId)+ if (cached) return cached+ if (!q.nodeId) return undefined+ const rt = deps.target(q.nodeId)+ // A live remote target makes the node remote whatever the records say.+ if (!rt) return remote ? 'unreadable' : undefined+ const home = deps.remoteHome(rt.controlPath)+ if (!home) return 'unreadable'+ const cmd = deps.command(home, { ...q, sessionId: q.sessionId })+ // No command = an id no transcript file can carry: nothing to find, not a failure to look.+ if (!cmd) return 'absent'+ let stdout: string+ try {+ const r = await deps.run(rt, cmd)+ if (r.code !== 0) return 'unreadable'+ stdout = r.stdout+ } catch {+ return 'unreadable'+ }+ const located = parseLocatedTranscript(stdout)+ if (!located) return 'absent'+ // Jailed exactly like a hook-supplied path: the answer crossed a machine boundary.+ if (!deps.isSafePath(located, home)) return 'unreadable'+ const ref: RemoteFileRef = { conn: rt.conn, controlPath: rt.controlPath, path: located }+ deps.cache.bySession.set(q.sessionId, ref)+ deps.cache.located.add(q.sessionId)+ return ref+}+export function createReadRemotePage(deps: {cache: RemoteTranscriptRefCache- /** The session's remote ref (cached, or located on the host); undefined = not a remote session. */- refFor(q: TranscriptQuery): Promise<RemoteFileRef | undefined>+ /** The session's remote ref (cached, or located on the host), or why there is none — see+ * `RemoteRefLookup`; undefined = not a remote session. */+ refFor(q: TranscriptQuery): Promise<RemoteRefLookup>/** Strict ranged read (`RemoteFile.readTranscriptPage`): throws on any failure. */readPage(ref: RemoteFileRef, before: number | null, maxBytes: number): Promise<TranscriptPage>}): (q: TranscriptQuery, page: ChatTranscriptPage) => Promise<RemoteTranscriptPage | null> {return async (q, page) => {const ref = await deps.refFor(q)- if (!ref) return null+ if (ref === undefined) return null+ if (ref === 'absent') return { ok: false, absent: true }+ if (ref === 'unreadable') return { ok: false }try {const w = await deps.readPage(ref, page.before, page.maxBytes)return { ok: true, data: w.data, start: w.start }diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 69f6ba8bd..462002bef 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -262,7 +262,9 @@ export function ChatPanel({return}setThread(emptyThread(identity))- setLoadState('missing')+ // A read that FAILED (the host did not answer, a remote node with no reachable master)+ // is not "no transcript": it gets the error copy, and ↻ is the way out.+ setLoadState(res.unreadable ? 'error' : 'missing')return}setThread((t) => applyTail(t, identity, res, { carryUnconfirmed: live }))diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsxindex a3fe14198..1f82175d1 100644--- a/src/renderer/nodes/ChatPanel.ux.test.tsx+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx@@ -226,6 +226,27 @@ describe('ChatPanel loading', () => {})})+describe('ChatPanel empty states', () => {+ // A read that FAILED (the host did not answer, a remote node with no reachable master) is not the+ // same sentence as "there is no transcript": one heals on retry, the other never will.+ it('an unreadable first read says it could not read the transcript', async () => {+ await render()+ await act(async () => {+ pending[0].resolve({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })+ })+ expect(msgs().textContent).toContain("Couldn't read the transcript.")+ expect(msgs().textContent).not.toContain('No transcript found')+ })++ it('a clean miss still says no transcript was found', async () => {+ await render()+ await act(async () => {+ pending[0].resolve({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })+ })+ expect(msgs().textContent).toContain('No transcript found for this session.')+ })+})+describe('ChatPanel scroll-follow', () => {it('pins to the bottom on a load when the user was already at the bottom', async () => {await render()