Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(chat): ⌘M resolves the transcript it was actually asked for — and says so when it can't
enes4c0177e9fb9d
diff --git a/src/core/remote-transcript-locate.test.ts b/src/core/remote-transcript-locate.test.tsnew file mode 100644index 000000000..28e539fe3--- /dev/null+++ b/src/core/remote-transcript-locate.test.ts@@ -0,0 +1,115 @@+// The remote locator is generated shell — the compiler checks nothing about it, so these tests+// run the emitted command for REAL under /bin/sh against a fake host tree (same discipline as+// canvas-control-shim.test.ts and remote-claude-usage.test.ts).+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { promisify } from 'util'+import {+ locateRemoteTranscriptCommand,+ parseLocatedTranscript,+ remoteTranscriptRoots+} from './remote-transcript-locate'+import { encodeTranscriptDir } from './transcript-reader'++const run = promisify(execFile)+const SID = '46b36ce2-dd77-4f5e-a89e-4a0e831e83df'++let home: string+const sh = async (cmd: string): Promise<string> => (await runShell(cmd)).stdout+/** Runs the generated command and reports the exit code instead of throwing on non-zero. */+const runShell = async (cmd: string): Promise<{ stdout: string; code: number }> => {+ try {+ const { stdout } = await run('/bin/sh', ['-c', cmd])+ return { stdout, code: 0 }+ } catch (e) {+ const err = e as { stdout?: string; code?: number }+ return { stdout: err.stdout ?? '', code: err.code ?? 1 }+ }+}+const touch = (p: string, body = '{}\n'): void => {+ fs.mkdirSync(path.dirname(p), { recursive: true })+ fs.writeFileSync(p, body)+}++beforeAll(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-remote-transcript-'))+})+afterAll(() => {+ fs.rmSync(home, { recursive: true, force: true })+})++describe('remoteTranscriptRoots', () => {+ it('puts the account root before the system one and strips trailing slashes', () => {+ expect(remoteTranscriptRoots('/home/u/', '/home/u/.nodeterm/claude-accounts/acc1/')).toEqual([+ '/home/u/.nodeterm/claude-accounts/acc1/projects',+ '/home/u/.claude/projects'+ ])+ })+ it('is the system root alone without an account', () => {+ expect(remoteTranscriptRoots('/home/u')).toEqual(['/home/u/.claude/projects'])+ })+})++describe('locateRemoteTranscriptCommand', () => {+ it('refuses a session id that is not a session id (no command at all)', () => {+ expect(locateRemoteTranscriptCommand(['/r'], '/w', '../../etc/passwd')).toBeNull()+ expect(locateRemoteTranscriptCommand([], '/w', SID)).toBeNull()+ })++ it('finds the transcript at the exact cwd path', async () => {+ const cwd = '/srv/app.v2'+ const p = `${home}/.claude/projects/${encodeTranscriptDir(cwd)}/${SID}.jsonl`+ touch(p)+ const cmd = locateRemoteTranscriptCommand(remoteTranscriptRoots(home), cwd, SID)!+ expect(parseLocatedTranscript(await sh(cmd))).toBe(p)+ })++ it('falls back to the glob when the session lives under a DIFFERENT cwd', async () => {+ // The node's cwd and the session's cwd disagree (the user cd'ed) — the exact probe misses.+ const sid = '11111111-1111-4111-8111-111111111111'+ const p = `${home}/.claude/projects/-srv-elsewhere/${sid}.jsonl`+ touch(p)+ const cmd = locateRemoteTranscriptCommand(remoteTranscriptRoots(home), '/no/such/dir', sid)!+ expect(parseLocatedTranscript(await sh(cmd))).toBe(p)+ })++ it('prefers the managed account root over the system one', async () => {+ const sid = '22222222-2222-4222-8222-222222222222'+ const accDir = `${home}/.nodeterm/claude-accounts/acc1`+ const cwd = '/srv/shared'+ const enc = encodeTranscriptDir(cwd)+ touch(`${home}/.claude/projects/${enc}/${sid}.jsonl`)+ touch(`${accDir}/projects/${enc}/${sid}.jsonl`)+ const cmd = locateRemoteTranscriptCommand(remoteTranscriptRoots(home, accDir), cwd, sid)!+ expect(parseLocatedTranscript(await sh(cmd))).toBe(`${accDir}/projects/${enc}/${sid}.jsonl`)+ })++ // A clean miss must EXIT 0: main reads the path only when `code === 0`, and an ssh call that+ // reports failure for "this session has no transcript" is indistinguishable from a dead master.+ it('prints nothing and exits 0 when the session is on no root', async () => {+ const cmd = locateRemoteTranscriptCommand(+ [`${home}/.nowhere/projects`],+ '/srv/app',+ '33333333-3333-4333-8333-333333333333'+ )!+ const { stdout, code } = await runShell(cmd)+ expect(code).toBe(0)+ expect(parseLocatedTranscript(stdout)).toBeUndefined()+ })++ it('survives a home directory with a space (quoting, not word splitting)', async () => {+ const spaced = fs.mkdtempSync(path.join(os.tmpdir(), 'nt space '))+ try {+ const cwd = '/srv/app'+ const p = `${spaced}/.claude/projects/${encodeTranscriptDir(cwd)}/${SID}.jsonl`+ touch(p)+ const cmd = locateRemoteTranscriptCommand(remoteTranscriptRoots(spaced), cwd, SID)!+ expect(parseLocatedTranscript(await sh(cmd))).toBe(p)+ } finally {+ fs.rmSync(spaced, { recursive: true, force: true })+ }+ })+})diff --git a/src/core/remote-transcript-locate.ts b/src/core/remote-transcript-locate.tsnew file mode 100644index 000000000..09047bfda--- /dev/null+++ b/src/core/remote-transcript-locate.ts@@ -0,0 +1,68 @@+// Locating a REMOTE (SSH-project) Claude transcript when no live hook event has fed one.+//+// `remoteTranscriptBySession` (src/main) is filled ONLY by hook POSTs, and a tmux session+// outlives the app — so after an app restart an idle remote agent node has no ref at all, and+// the local resolvers then search THIS machine's disk for a session that exists only on the+// host. That is the "⌘M says there is no conversation" case: it healed itself the moment the+// user sent one prompt (the next hook event registered the ref), which is exactly what made it+// look intermittent.+//+// These are pure string builders. `src/main` runs the command over the project's ControlMaster+// and jails the answer with `isSafeRemoteTranscriptPath` before reading it.+import { posixQuote } from '../shared/ssh'+import { SESSION_ID_RE, encodeTranscriptDir } from './transcript-reader'++/**+ * Transcript roots to search on the host: the node's managed-account root first (that is where+ * its session actually lives when it runs under one), then the system `~/.claude/projects`.+ * Both are kept because a node's persisted `accountId` and the dir its CLI actually used can+ * disagree (an account removed since, a session started before the account was assigned) — and+ * every root here is inside what `isSafeRemoteTranscriptPath` already admits.+ */+export function remoteTranscriptRoots(remoteHome: string, accountConfigDir?: string): string[] {+ const home = remoteHome.replace(/\/+$/, '')+ const roots: string[] = []+ if (accountConfigDir) roots.push(`${accountConfigDir.replace(/\/+$/, '')}/projects`)+ roots.push(`${home}/.claude/projects`)+ return roots+}++/**+ * One POSIX `sh` line that prints the first existing transcript for `sessionId`, or nothing.+ *+ * Ordered by cost: the exact `<root>/<encoded cwd>/<id>.jsonl` first (one stat per root), then a+ * glob across every project dir — the session's cwd can differ from the node's (the user `cd`ed,+ * or the node was created elsewhere), and without the glob those resolve to nothing at all.+ *+ * The `*` is deliberately left OUTSIDE the quotes: quoting the whole pattern would make sh look+ * for a literal star. Everything interpolated is app-built (the roots) or validated (`sessionId`+ * against `SESSION_ID_RE`, which admits no '/' or '.'), so nothing here can escape the roots.+ * Returns null for an unusable session id rather than emitting a command that cannot match.+ */+export function locateRemoteTranscriptCommand(+ roots: string[],+ cwd: string | undefined,+ sessionId: string+): string | null {+ if (!roots.length || !SESSION_ID_RE.test(sessionId)) return null+ const leaf = posixQuote(`${sessionId}.jsonl`)+ const candidates: string[] = []+ if (cwd) {+ const dir = encodeTranscriptDir(cwd)+ for (const r of roots) candidates.push(posixQuote(`${r}/${dir}/${sessionId}.jsonl`))+ }+ for (const r of roots) candidates.push(`${posixQuote(r)}/*/${leaf}`)+ // A glob that matches nothing stays literal in sh, so `[ -f ]` simply rejects it. The trailing+ // `:` keeps the exit status 0 on a clean miss: the loop's last command would otherwise be the+ // failed `[ -f ]`, and "no transcript for this session" is an ANSWER, not a failed ssh call.+ return `for f in ${candidates.join(' ')}; do [ -f "$f" ] && { printf '%s\\n' "$f"; break; }; done; :`+}++/** First non-empty line of the locator's stdout — the resolved path, or undefined. */+export function parseLocatedTranscript(stdout: string): string | undefined {+ for (const line of stdout.split('\n')) {+ const s = line.trim()+ if (s) return s+ }+ return undefined+}diff --git a/src/core/transcript-ipc.test.ts b/src/core/transcript-ipc.test.tsnew file mode 100644index 000000000..d31a75fb8--- /dev/null+++ b/src/core/transcript-ipc.test.ts@@ -0,0 +1,105 @@+// The read channels both shells now serve. What these pin down is the DISTINCTION the ⌘M panel+// depends on: "resolved, and the session has said nothing" vs "nothing resolved at all" — the two+// used to be the same empty array, which is how a failed resolution reached the user as an empty+// conversation.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { fakePlatform } from './platform-fake'+import { initPlatform, resetPlatformForTests } from './platform'+import { registerTranscriptIpc } from './transcript-ipc'+import { IPC } from '../shared/ipc'+import type { ChatTranscriptResult, TranscriptLine } from '../shared/types'++const SID = '46b36ce2-dd77-4f5e-a89e-4a0e831e83df'+const CWD = '/srv/app'++const lines = (...raw: object[]): string => raw.map((o) => JSON.stringify(o)).join('\n') + '\n'+const userLine = (text: string) => ({ type: 'user', message: { content: text } })+const assistantLine = (text: string) => ({+ type: 'assistant',+ message: { content: [{ type: 'text', text }] }+})++let home: string+let f: ReturnType<typeof fakePlatform>++const chat = (nodeId?: string) =>+ f.handlers[IPC.chatReadTranscript](SID, CWD, undefined, nodeId) as Promise<ChatTranscriptResult>+const search = (nodeId?: string) =>+ f.handlers[IPC.claudeReadTranscript](SID, CWD, undefined, nodeId) as Promise<TranscriptLine[]>++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-transcript-ipc-'))+ vi.spyOn(os, 'homedir').mockReturnValue(home)+ f = fakePlatform()+ initPlatform(f)+})+afterEach(() => {+ vi.restoreAllMocks()+ resetPlatformForTests()+ fs.rmSync(home, { recursive: true, force: true })+})++const writeTranscript = (body: string, name = `${SID}.jsonl`): string => {+ const dir = path.join(home, '.claude', 'projects', '-srv-app')+ fs.mkdirSync(dir, { recursive: true })+ const p = path.join(dir, name)+ fs.writeFileSync(p, body)+ return p+}++describe('registerTranscriptIpc — local resolution', () => {+ it('reads the session transcript and reports it found', async () => {+ writeTranscript(lines(userLine('merhaba'), assistantLine('selam')))+ registerTranscriptIpc()+ const res = await chat()+ expect(res.found).toBe(true)+ expect(res.messages.map((m) => m.role)).toEqual(['user', 'assistant'])+ })++ it('distinguishes an EMPTY session (found) from an unresolvable one (not found)', async () => {+ // A transcript that exists but carries no renderable message — a session that was created and+ // never spoken to. Real: 27 of 135 transcripts on the dev box look exactly like this.+ writeTranscript(lines({ type: 'bridge-session', sessionId: SID }))+ registerTranscriptIpc()+ expect(await chat()).toEqual({ messages: [], found: true })++ fs.rmSync(path.join(home, '.claude'), { recursive: true, force: true })+ expect(await chat()).toEqual({ messages: [], found: false })+ })++ it('prefers a hook-fed path over the sessionId scan', async () => {+ writeTranscript(lines(assistantLine('scanned')))+ const hooked = path.join(home, 'elsewhere.jsonl')+ fs.writeFileSync(hooked, lines(assistantLine('hook-fed')))+ registerTranscriptIpc({ pathFor: () => hooked })+ const res = await chat()+ expect(res.messages[0].parts[0]).toMatchObject({ kind: 'text', text: 'hook-fed' })+ })+})++describe('registerTranscriptIpc — the injected remote leg', () => {+ it('wins over local resolution and feeds both channels', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ registerTranscriptIpc({ readRemote: async () => lines(assistantLine('the HOST')) })+ const res = await chat('nt-1')+ expect(res.found).toBe(true)+ expect(res.messages[0].parts[0]).toMatchObject({ text: 'the HOST' })+ expect((await search('nt-1')).map((l) => l.text)).toEqual(['the HOST'])+ })++ it('null means "not a remote session" — the local path still runs', async () => {+ writeTranscript(lines(assistantLine('local')))+ registerTranscriptIpc({ readRemote: async () => null })+ expect((await chat('nt-1')).messages[0].parts[0]).toMatchObject({ text: 'local' })+ })++ it('a remote read that came back EMPTY is not found — it is a failed read, not an empty chat', async () => {+ // The transcript resolved on the host but could not be read (master down, file deleted).+ // Reporting `found: true` here would render it as "No conversation yet." and hide the failure.+ registerTranscriptIpc({ readRemote: async () => '' })+ expect(await chat('nt-1')).toEqual({ messages: [], found: false })+ })+})diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.tsnew file mode 100644index 000000000..824f26482--- /dev/null+++ b/src/core/transcript-ipc.ts@@ -0,0 +1,99 @@+// The two transcript READ channels — the ⌘M chat view (`chat:read-transcript`) and the find-bar's+// full-transcript index (`claude:read-transcript`) — registered through the CorePlatform seam so+// BOTH shells serve them.+//+// This lived inline in `src/main/index.ts`, which is exactly the failure mode the seam exists to+// prevent: the Server Edition had no handler at all, its bridge stub rejected, and the chat panel+// (which never caught the rejection) presented every browser session as an empty conversation.+//+// 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 { IPC } from '../shared/ipc'+import type { ChatTranscriptResult, TranscriptLine } from '../shared/types'+import { platform } from './platform'+import {+ parseChatMessages,+ parseTranscriptLines,+ readChatMessages,+ readTranscriptLines,+ resolveTranscriptPath,+ transcriptPathForCwd,+ SESSION_ID_RE+} from './transcript-reader'++/** What a read is asked for. `nodeId` is only meaningful to the remote leg. */+export interface TranscriptQuery {+ sessionId: string | undefined+ cwd: string | undefined+ accountId: string | undefined+ nodeId: string | undefined+}++export interface TranscriptIpcDeps {+ /** Transcript path a live context tail already knows for this session (hook-fed — authoritative+ * when present). Optional: the sessionId scan below finds any transcript in a standard root. */+ pathFor?(sessionId: string): string | undefined+ /**+ * Tail text of a REMOTE node's transcript, or null when this is not a remote session (or it+ * could not be resolved). Electron-only — the server has no SSH-project manager.+ */+ readRemote?(q: TranscriptQuery): Promise<string | null>+}++/**+ * Resolve a session's transcript path: the exact session file when a (valid) sessionId is known,+ * else the node's cwd — durable, and needing no live hook event. `accountId` scopes BOTH legs to+ * the same root: dropping it on the fallback sent a managed-account node to the system root, where+ * it found nothing or adopted an unrelated session's newest transcript.+ */+export async function resolveTranscript(+ q: Pick<TranscriptQuery, 'sessionId' | 'cwd' | 'accountId'>,+ pathFor?: (sessionId: string) => string | undefined+): Promise<string | undefined> {+ let p: string | undefined+ if (q.sessionId && SESSION_ID_RE.test(q.sessionId)) {+ p = pathFor?.(q.sessionId) ?? (await resolveTranscriptPath(q.sessionId, q.accountId))+ }+ if (!p && q.cwd) p = await transcriptPathForCwd(q.cwd, q.accountId)+ return p+}++export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {+ const remoteText = (q: TranscriptQuery): Promise<string | null> =>+ deps.readRemote ? deps.readRemote(q) : Promise.resolve(null)++ platform().handle(+ IPC.claudeReadTranscript,+ async (+ sessionId: string | undefined,+ cwd: string | undefined,+ accountId: string | undefined,+ nodeId: string | undefined+ ): Promise<TranscriptLine[]> => {+ const remote = await remoteText({ sessionId, cwd, accountId, nodeId })+ if (remote !== null) return parseTranscriptLines(remote)+ const p = await resolveTranscript({ sessionId, cwd, accountId }, deps.pathFor)+ return p ? readTranscriptLines(p) : []+ }+ )++ platform().handle(+ IPC.chatReadTranscript,+ async (+ sessionId: string | undefined,+ cwd: string | undefined,+ accountId: string | undefined,+ nodeId: string | undefined+ ): Promise<ChatTranscriptResult> => {+ const remote = await remoteText({ sessionId, cwd, accountId, nodeId })+ // 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 }+ const p = await resolveTranscript({ sessionId, cwd, accountId }, deps.pathFor)+ return p+ ? { messages: await readChatMessages(p), found: true }+ : { messages: [], found: false }+ }+ )+}diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex c908dfd95..1f204e391 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -332,13 +332,20 @@ export async function readSessionName(// reattaching to a session this app instance didn't spawn. (Encoding leaves no '/', so it// can't traverse.) Limitation: multiple Claude nodes in the SAME cwd resolve to the same// newest transcript — the sessionId path above is preferred when known for that reason.++/** The per-cwd directory name Claude uses under a transcript root. Exported because the REMOTE+ * locator (remote-transcript-locate.ts) must encode a host path the identical way — a second+ * copy that drifted would make the exact-path probe silently never hit. */+export function encodeTranscriptDir(cwd: string): string {+ return cwd.replace(/[/.]/g, '-')+}+export async function transcriptPathForCwd(cwd: string,accountId?: string): Promise<string | undefined> {if (!cwd) return undefined- const encoded = cwd.replace(/[/.]/g, '-')- const dir = path.join(transcriptRoot(accountId), encoded)+ const dir = path.join(transcriptRoot(accountId), encodeTranscriptDir(cwd))let entries: string[]try {entries = await fs.promises.readdir(dir)diff --git a/src/main/index.ts b/src/main/index.tsindex b37074aec..ffda5c415 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -74,17 +74,17 @@ import { createSubagentTail } from '../core/subagent-tail'import { createContextTail, type TaskNotification } from '../core/context-tail'import { isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'import {- readTranscriptLines,- readChatMessages,readSessionName,setRemoteTranscriptReader,TITLE_TAIL_BYTES,- resolveTranscriptPath,- transcriptPathForCwd,- parseTranscriptLines,- parseChatMessages,SESSION_ID_RE} from '../core/transcript-reader'+import {+ locateRemoteTranscriptCommand,+ parseLocatedTranscript,+ remoteTranscriptRoots+} from '../core/remote-transcript-locate'+import { registerTranscriptIpc, resolveTranscript } from '../core/transcript-ipc'import { createRemoteContextTail } from './remote-context-tail'import { createRemoteSubagentTail } from './remote-subagent-tail'import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'@@ -1122,6 +1122,10 @@ app.whenReady().then(async () => {// search/chat read handlers (which receive only sessionId + cwd) read remotely without a// nodeId. Only remote sessions are ever inserted, so local reads stay on the local reader.const remoteTranscriptBySession = new Map<string, RemoteFileRef>()+ // Subset of the above that WE located by asking the host (no hook event ever fed it). Tracked+ // separately so a stale entry can be dropped on a failed read without touching the hook-fed+ // ones — see `readRemoteTranscript`.+ const locatedTranscriptSessions = new Set<string>()// Route the session-name read (the node-title poll) through the same remote ref. An SSH// project's agent runs on the remote host, so its transcript is NOT under the local// `~/.claude/projects` — without this, `/rename` never reached the node title on remote nodes@@ -1164,59 +1168,94 @@ app.whenReady().then(async () => {}return undefined}- // Resolve a session's transcript path: prefer the exact session path when a (valid)- // sessionId is known; otherwise fall back to the node's cwd, which is durable and doesn't- // need a live hook event.- const resolveTranscript = async (- sessionId: string | undefined,- cwd: string | undefined,- accountId?: string- ): Promise<string | undefined> => {- let p: string | undefined- if (sessionId && SESSION_ID_RE.test(sessionId)) {- p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId, accountId))- }- if (!p && cwd) p = await transcriptPathForCwd(cwd)- return p- }-// Read at most the last 5 MB of a transcript (mirrors transcript-reader's READ_CAP_BYTES) —// the remote read fetches the tail over ssh, then reuses the SAME pure parsers as local, so// the returned shape is byte-identical to the local reader.const REMOTE_TRANSCRIPT_CAP = 5 * 1024 * 1024- corePlatform.handle(- IPC.claudeReadTranscript,- async (- sessionId: string | undefined,- cwd: string | undefined,- accountId: string | undefined- ) => {- const ref = sessionId ? remoteTranscriptBySession.get(sessionId) : undefined- if (ref) {- const text = await remoteFile.readTail(ref, REMOTE_TRANSCRIPT_CAP)- return parseTranscriptLines(text)++ /**+ * The remote ref for a session, resolving it on the HOST when no hook event has registered one.+ *+ * `remoteTranscriptBySession` is fed only by hook POSTs, and a tmux session outlives the app —+ * so after an app restart an IDLE remote agent node has no ref, and the local resolvers below+ * 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.+ */+ const remoteTranscriptRefFor = async (+ sessionId: string | undefined,+ cwd: string | undefined,+ accountId: string | undefined,+ nodeId: string | undefined+ ): Promise<RemoteFileRef | undefined> => {+ if (!sessionId) return undefined+ const cached = remoteTranscriptBySession.get(sessionId)+ if (cached) return cached+ if (!nodeId) return undefined+ const rt = 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 p = await resolveTranscript(sessionId, cwd, accountId)- return p ? readTranscriptLines(p) : []}- )+ const cmd = locateRemoteTranscriptCommand(+ remoteTranscriptRoots(remoteHome, accountDir),+ cwd,+ sessionId+ )+ 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+ }- corePlatform.handle(- IPC.chatReadTranscript,- async (- sessionId: string | undefined,- cwd: string | undefined,- accountId: string | undefined- ) => {- const ref = sessionId ? remoteTranscriptBySession.get(sessionId) : undefined- if (ref) {- const text = await remoteFile.readTail(ref, REMOTE_TRANSCRIPT_CAP)- return parseChatMessages(text.split('\n'))- }- const p = await resolveTranscript(sessionId, cwd, accountId)- return p ? readChatMessages(p) : []+ /**+ * Read a remote transcript through a ref, forgetting refs WE located once they stop reading.+ * Without this the panel's Retry replays a dead path forever (the transcript was deleted, or the+ * session moved) because the cache lookup comes first. A hook-fed ref is deliberately left in+ * place on an empty read — that is usually a transient master hiccup, and dropping it would send+ * the next read down the LOCAL resolver, i.e. to the wrong machine.+ */+ const readRemoteTranscript = async (sessionId: string, ref: RemoteFileRef): Promise<string> => {+ const text = await remoteFile.readTail(ref, REMOTE_TRANSCRIPT_CAP)+ if (!text && locatedTranscriptSessions.delete(sessionId)) {+ remoteTranscriptBySession.delete(sessionId)}- )+ return text+ }++ // Both read channels now live in core (the Server Edition serves the very same handlers); the+ // ONE thing this shell adds is the remote leg, which needs a ControlMaster. `null` means "not a+ // remote session", which is the signal for core to take its local path.+ registerTranscriptIpc({+ pathFor: (sessionId) => contextTail.pathFor(sessionId),+ readRemote: async ({ sessionId, cwd, accountId, nodeId }) => {+ const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)+ return ref ? await readRemoteTranscript(sessionId!, ref) : null+ }+ })initTranscriptIndex(() => settingsStore.get().claudeAccounts ?? [])corePlatform.handle(IPC.transcriptSearch, (query: string) => searchTranscripts(query))@@ -1224,10 +1263,12 @@ app.whenReady().then(async () => {// (the continuing session may be idle after a restart). Track under the sessionId (the key// the meter looks up); cwd is only a path fallback. contextTail.track reads immediately and// the 1s interval keeps it fresh while tracked.+ // Shares core's `resolveTranscript` with the read channels — including its `accountId`-scoped+ // cwd fallback. This copy dropped the account, so a managed-account node could track (and then+ // meter, and then SERVE as the chat's first-choice path) an unrelated session's transcript.corePlatform.on(IPC.contextEnsure, async (sessionId?: string, cwd?: string, accountId?: string) => {if (!sessionId || !SESSION_ID_RE.test(sessionId)) return- let p = contextTail.pathFor(sessionId) ?? (await resolveTranscriptPath(sessionId, accountId))- if (!p && cwd) p = await transcriptPathForCwd(cwd)+ const p = await resolveTranscript({ sessionId, cwd, accountId }, (s) => contextTail.pathFor(s))if (p) contextTail.track(sessionId, p)})// The remote half of a handoff. Same three-line shape as the context-link deps above and for@@ -1440,6 +1481,7 @@ app.whenReady().then(async () => {if (p.hook_event_name === 'SessionEnd' && p.session_id) {remoteContextTail.untrack(p.session_id)remoteTranscriptBySession.delete(p.session_id)+ locatedTranscriptSessions.delete(p.session_id)}if (p.tool_use_id && p.tool_name && SUBAGENT_TOOLS.has(p.tool_name) && transcriptPath) {const toolUseId = p.tool_use_id@@ -1524,6 +1566,7 @@ app.whenReady().then(async () => {contextTail.untrack(sessionId)remoteContextTail.untrack(sessionId)remoteTranscriptBySession.delete(sessionId)+ locatedTranscriptSessions.delete(sessionId)nodeContextSession.delete(nodeId)}const subs = nodeSubagents.get(nodeId)diff --git a/src/preload/index.ts b/src/preload/index.tsindex 88f44d6e7..f647496d8 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -380,12 +380,12 @@ const api: NodeTerminalApi = {},claude: {cliCaps: () => ipcRenderer.invoke(IPC.claudeCliCaps),- readTranscript: (sessionId, cwd, accountId) =>- ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId)+ readTranscript: (sessionId, cwd, accountId, nodeId) =>+ ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId, nodeId)},chat: {- readTranscript: (sessionId, cwd, accountId) =>- ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId)+ readTranscript: (sessionId, cwd, accountId, nodeId) =>+ ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId)},claudeAccounts: {add: (ctx) => ipcRenderer.invoke(IPC.claudeAccountsAdd, ctx),diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex a4431c883..f31c98230 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -18,6 +18,7 @@ import {UNKNOWN_CLAUDE_CLI_CAPS,type BoardLogApi,type BoardLogReadResult,+ type ChatTranscriptResult,type ClaudeApi,type ClaudeCliCaps,type ContextApi,@@ -38,6 +39,7 @@ import {type SpeechApi,type SpeechModelInfo,type TmuxStatus,+ type TranscriptLine,type Workspace,type WorkspaceApi} from '../../shared/types'@@ -557,7 +559,12 @@ function buildUsageApi(client: RpcClient): Pick<NodeTerminalApi, 'usage'> {* `--permission-mode auto` version gate as desktop instead of silently no-opping into "auto* unsupported" — which would strip the flag from every Claude launch in the Server Edition.* A failed request degrades to the fail-open caps (bare command), never a rejection: the launch- * path awaits this. `readTranscript` has no server handler yet, so it keeps the stub's reject.+ * path awaits this.+ *+ * `readTranscript` stays STUBBED here on purpose. This builder is shared with the relay+ * (`relay-api.ts`), where the transcripts that matter live on the HOST while this namespace's+ * only real member is a capability probe — the Server Edition gets the real reader from+ * `buildTranscriptApi` below instead, which the relay does not use.*/export function buildClaudeApi(client: RpcClient, stub: ClaudeApi): ClaudeApi {return {@@ -569,6 +576,40 @@ export function buildClaudeApi(client: RpcClient, stub: ClaudeApi): ClaudeApi {}}+/**+ * The two transcript READ channels, now that `registerTranscriptIpc` serves them in the server+ * shell too. Before this the browser had no handler at all: the stub rejected, the ⌘M panel never+ * caught it, and every Server Edition session read as an empty conversation.+ *+ * Server Edition ONLY (see buildClaudeApi's note): the server runs on the machine whose+ * transcripts these are, so no `nodeId` remote leg is needed — the argument still rides along+ * because the channel is shared with desktop.+ */+export function buildTranscriptApi(+ client: RpcClient+): Pick<NodeTerminalApi, 'chat'> & { claudeReadTranscript: ClaudeApi['readTranscript'] } {+ return {+ chat: {+ readTranscript: (sessionId, cwd, accountId, nodeId) =>+ client.request(+ IPC.chatReadTranscript,+ sessionId,+ cwd,+ accountId,+ nodeId+ ) as Promise<ChatTranscriptResult>+ },+ claudeReadTranscript: (sessionId, cwd, accountId, nodeId) =>+ client.request(+ IPC.claudeReadTranscript,+ sessionId,+ cwd,+ accountId,+ nodeId+ ) as Promise<TranscriptLine[]>+ }+}+/** WS URL for the current page: same host, `/ws`, ws→http / wss→https. */function wsUrl(): string {const scheme = location.protocol === 'https:' ? 'wss' : 'ws'@@ -683,8 +724,15 @@ export async function installWsBridge(): Promise<boolean> {...buildPresenceApi(client),...buildSpeechApi(client),...buildUsageApi(client),- // Only `cliCaps` is real here — the rest of the namespace stays stubbed (see buildClaudeApi).- claude: buildClaudeApi(client, stubApi.claude),+ // `claude` is assembled from two builders: `cliCaps` from the relay-shared one, and the+ // transcript reader from the Server-Edition-only one (which also supplies `chat`).+ ...(() => {+ const t = buildTranscriptApi(client)+ return {+ chat: t.chat,+ claude: { ...buildClaudeApi(client, stubApi.claude), readTranscript: t.claudeReadTranscript }+ }+ })(),// Web replacement for the Electron native dialog: an in-app server-directory browser over// fs.list (the stub's E_UNSUPPORTED reject is dropped in favor of this real picker).dialog: (() => {diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex c5b44a1ed..9d86b9738 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -4,6 +4,7 @@ import { useAgentStatus } from '../state/agentStatus'import { useSession } from '../session/session'import type { ChatMessage } from '@shared/types'import { hintLabel } from '@shared/platform-utils'+import { E_UNSUPPORTED } from '@shared/rpc'// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.@@ -20,6 +21,35 @@ interface ChatPanelProps {accountId?: string}+/**+ * Why the transcript isn't on screen. Every one of these used to render as "No conversation+ * yet.": a rejected read (this surface has no transcript reader at all) left `messages` at its+ * initial `[]` because nothing caught the rejection, and a failed resolution was indistinguishable+ * from a session nobody has spoken to. They need different words — and two of them are retryable.+ */+type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'error'++const isUnsupported = (e: unknown): boolean =>+ !!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED++/** One line each, in the user's terms: what is on screen and whether waiting will fix it.+ * `missing` names the two causes that actually produce it — a transcript Claude has cleaned up+ * (30 days by default), and a remote session whose host hasn't been reached yet — because the+ * second one heals by itself the moment the session speaks, and the first one never will. */+const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {+ loading: { title: 'Loading conversation…' },+ ok: { title: 'No conversation yet.' },+ missing: {+ title: 'No transcript found for this session.',+ detail: "It may have been cleaned up, or the agent's host isn't reachable yet."+ },+ unsupported: {+ title: "Transcripts can't be read on this surface.",+ detail: 'Open this session on the desktop app to read its conversation.'+ },+ error: { title: "Couldn't read the transcript." }+}+/*** Chat view for a chat-capable agent node (Cmd+M). Renders the session transcript as* markdown bubbles with collapsible tool calls, and sends new prompts into the running tmux@@ -31,6 +61,7 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)// both live on the core this panel's project belongs to).const { api } = useSession()const [messages, setMessages] = useState<ChatMessage[]>([])+ const [loadState, setLoadState] = useState<LoadState>('loading')const [input, setInput] = useState('')const [readonly, setReadonly] = useState(false)const state = useAgentStatus((s) => s.byId[nodeId]?.state)@@ -38,8 +69,18 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)const prevState = useRef(state)const load = useCallback(() => {- void api.chat.readTranscript(sessionId, cwd, accountId).then(setMessages)- }, [api, sessionId, cwd, accountId])+ setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread+ // `nodeId` is what lets an SSH-project node resolve on its host; the rejection branch is what+ // keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently+ // presenting itself as an empty conversation.+ void api.chat.readTranscript(sessionId, cwd, accountId, nodeId).then(+ (res) => {+ setMessages(res.messages)+ setLoadState(res.found ? 'ok' : 'missing')+ },+ (e: unknown) => setLoadState(isUnsupported(e) ? 'unsupported' : 'error')+ )+ }, [api, sessionId, cwd, accountId, nodeId])// Initial load.useEffect(() => {@@ -87,7 +128,19 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)<span className="term-chat__hint">{hintLabel('⌘M to exit')}</span></div><div className="term-chat__msgs" ref={msgsRef}>- {messages.length === 0 && <div className="term-chat__empty">No conversation yet.</div>}+ {messages.length === 0 && loadState !== 'loading' && (+ <div className="term-chat__empty">+ <div>{EMPTY_TEXT[loadState].title}</div>+ {EMPTY_TEXT[loadState].detail && (+ <div className="term-chat__empty-detail">{EMPTY_TEXT[loadState].detail}</div>+ )}+ {loadState !== 'unsupported' && loadState !== 'ok' && (+ <button className="term-chat__retry" onClick={load}>+ Retry+ </button>+ )}+ </div>+ )}{messages.map((m, i) => (<div key={i} className={`term-chat__msg term-chat__msg--${m.role}`}>{m.parts.map((p, j) =>diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 1bde65c12..324db585e 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -1823,6 +1823,31 @@ body,margin: auto;font-size: 12px;color: var(--label-secondary, rgba(255, 255, 255, 0.4));+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ text-align: center;+ padding: 0 16px;+}+.term-chat__empty-detail {+ font-size: 11px;+ color: var(--label-tertiary, rgba(255, 255, 255, 0.28));+ max-width: 34ch;+ line-height: 1.4;+}+.term-chat__retry {+ margin-top: 2px;+ padding: 3px 10px;+ font-size: 11px;+ color: var(--label-secondary, rgba(255, 255, 255, 0.55));+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid rgba(255, 255, 255, 0.1);+ border-radius: 6px;+ cursor: pointer;+}+.term-chat__retry:hover {+ background: rgba(255, 255, 255, 0.12);}.term-chat__msg {max-width: 92%;diff --git a/src/renderer/terminal/useTerminalSearch.ts b/src/renderer/terminal/useTerminalSearch.tsindex b21646ce8..8316a56d8 100644--- a/src/renderer/terminal/useTerminalSearch.ts+++ b/src/renderer/terminal/useTerminalSearch.ts@@ -71,10 +71,14 @@ export function useTerminalSearch({// else by cwd (durable) — so it works even when no live hook event set the sessionId.if (searchTranscript) {try {+ // `nodeId` is what lets an SSH-project node's transcript be located on its HOST when no+ // hook event has registered it in this app run — otherwise the search silently indexes+ // the terminal buffer alone there, which reads as "the transcript isn't searchable".const tr: TranscriptLine[] = await window.nodeTerminal.claude.readTranscript(sessionId,cwd,- accountId+ accountId,+ nodeId)for (const l of tr) {for (const t of l.text.split('\n')) lines.push({ source: 'claude', role: l.role, text: t })diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex 4ddd7d8c3..970cd11bd 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -40,8 +40,14 @@ export interface WireAgentStatusOptions {* the real `hookServer` singleton and real tails.** Does NOT call `hookServer.start()` — the boot step owns starting the server.+ *+ * Returns its context tail so the boot step can give the transcript read channels the same+ * hook-fed path authority the desktop gives them (`registerTranscriptIpc`).*/-export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusOptions = {}): void {+export function wireAgentStatus(+ platform: ServerPlatform,+ opts: WireAgentStatusOptions = {}+): { contextTail: ContextTail } {const hooks = opts.hooks ?? hookServer// nodeId → claude sessionIdconst nodeContextSession = new Map<string, string>()@@ -200,4 +206,6 @@ export function wireAgentStatus(platform: ServerPlatform, opts: WireAgentStatusO}platform.on(IPC.ptyDestroy, (nodeId: string) => releaseNodeTails(nodeId))platform.on(IPC.ptyRecycle, (nodeId: string) => releaseNodeTails(nodeId))++ return { contextTail }}diff --git a/src/server/index.ts b/src/server/index.tsindex 4b515c861..1b4e5f6bb 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -53,6 +53,7 @@ import { claudeConfigDirFor } from '../core/claude-config-dir'import { presenceHub } from '../core/presence/hub'import { initCanvasSync } from '../core/canvas-sync'import { wireAgentStatus } from './agent-status'+import { registerTranscriptIpc } from '../core/transcript-ipc'import { IPC } from '@shared/ipc'import { WhisperModelStore } from '../core/speech/whisper-models'import { SpeechService } from '../core/speech/speech-service'@@ -273,7 +274,12 @@ export async function startServer(// missing/corrupt file simply yields no block.const installMeta = readInstallMeta(config.dataDir)setMirrorServerProvider(() => installMeta)- wireAgentStatus(platform)+ const { contextTail } = wireAgentStatus(platform)+ // The ⌘M chat view + the find-bar's transcript index. Registered HERE rather than with the rest+ // of the handlers because the hook-fed path authority is the tail created just above. No remote+ // leg: the Server Edition runs ON the host whose transcripts it reads, so local resolution is+ // the complete answer (an SSH-project node is a desktop-only concept here).+ registerTranscriptIpc({ pathFor: (sessionId) => contextTail.pathFor(sessionId) })// Deterministic hook-reply approvals (docs/hook-reply-approvals.md): the browser canvas answers a// held Claude permission hook here. The Server Edition runs ON the host, so a local project's// answer file is written right there (under os.homedir(), which the hook uses as $HOME). SSHdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 57949ef17..0ad9e5d9f 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1460,17 +1460,31 @@ export interface ChatToolSummary {removed?: number}+/**+ * Result of a chat transcript read. `found` is the whole point of the wrapper: an empty+ * `messages` means two very different things — the session exists and nobody has said anything+ * yet (`found: true`), or no transcript could be resolved at all (`found: false`, e.g. Claude's+ * 30-day cleanup removed it, or the id belongs to another machine). The ⌘M panel rendered both+ * as "No conversation yet.", which is what made a resolution failure look like an empty session.+ */+export interface ChatTranscriptResult {+ messages: ChatMessage[]+ found: boolean+}+export interface ChatApi {/**- * Reads a Claude session transcript as structured chat messages ([] if unavailable).+ * Reads a Claude session transcript as structured chat messages.* Resolves the transcript like `ClaudeApi.readTranscript` (sessionId → cwd), then- * reconstructs ordered bubbles + tool calls.+ * reconstructs ordered bubbles + tool calls. `nodeId` lets an SSH-project node be resolved+ * on its HOST even when no hook event has registered its transcript in this app run.*/readTranscript(sessionId: string | undefined,cwd: string | undefined,- accountId?: string- ): Promise<ChatMessage[]>+ accountId?: string,+ nodeId?: string+ ): Promise<ChatTranscriptResult>}/** Optional SSH context for account ops. When `projectId` names a connected SSH project, the@@ -1535,11 +1549,14 @@ export interface ClaudeApi {* Resolves by `sessionId` when known (exact); otherwise falls back to `cwd` (durable —* the newest transcript under that project dir, no live hook event required).* `accountId` scopes resolution to a managed Claude account's transcript root (default `~/.claude`).+ * `nodeId` (optional) lets an SSH-project node's transcript be located on its HOST when no hook+ * event has registered it in this app run — without it the search silently reads nothing there.*/readTranscript(sessionId: string | undefined,cwd: string | undefined,- accountId?: string+ accountId?: string,+ nodeId?: string): Promise<TranscriptLine[]>}