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): grok remote read honours page.maxBytes, shares the installer's GROK_HOME rule, names ambiguity
review8cb4b406ec38
diff --git a/src/core/agents/grok-paths.ts b/src/core/agents/grok-paths.tsindex 39a892ece..e77de9072 100644--- a/src/core/agents/grok-paths.ts+++ b/src/core/agents/grok-paths.ts@@ -193,3 +193,18 @@ export function isSafeRemoteGrokHome(p: string | undefined): boolean {// interpolated into the same kind of remote command line) — see `isSafeRemoteHome`.return isSafeRemoteHome(p)}++/** The host-side probe for `$GROK_HOME`, over a plain exec channel. ONE spelling for the hook+ * installer and the remote chat reader, so both ask the same question. */+export const REMOTE_GROK_HOME_PROBE = 'printf %s "${GROK_HOME:-}"'++/** The grok home a host's answer to `REMOTE_GROK_HOME_PROBE` names, or null when it names none+ * usable — the caller then uses `$HOME/.grok`. Trimmed at this READ site (see+ * `isSafeRemoteGrokHome`), trailing slashes stripped (`/` stays `/`). Shared by+ * `RemoteHooks.installGrokRemote` and `core/remote-grok-chat.ts`, so the hook grok fires and the+ * reader of its history always agree on the root. */+export function resolveReportedGrokHome(raw: string): string | null {+ const reported = raw.trim()+ if (!isSafeRemoteGrokHome(reported)) return null+ return reported.replace(/\/+$/, '') || '/'+}diff --git a/src/core/remote-grok-chat.test.ts b/src/core/remote-grok-chat.test.tsindex 1a1269492..cf1debbb7 100644--- a/src/core/remote-grok-chat.test.ts+++ b/src/core/remote-grok-chat.test.ts@@ -14,6 +14,8 @@ import {parseRemoteGrokChat,remoteGrokChatCommand} from './remote-grok-chat'+import { REMOTE_GROK_HOME_PROBE, resolveReportedGrokHome } from './agents/grok-paths'+import { CHAT_PAGE_MAX_BYTES } from '../shared/chat-page'const SID = '01a06126-b981-73f1-8b68-4547e4d7da84'const OTHER = '01a06126-b981-73f1-8b68-000000000000'@@ -57,15 +59,16 @@ describe('remoteGrokChatCommand under a real /bin/sh', () => {expect(got).toEqual({ text: jl({ type: 'user', content: 'mine' }) })})- it('honours an absolute $GROK_HOME, and ignores a relative one (the installer\'s rule)', () => {+ it('reads under the grok home it is GIVEN, and never consults $GROK_HOME itself', () => {const home = freshHome('b')const custom = path.join(host, 'b-grokhome')writeSession(custom, 'g', SID, jl({ type: 'user', content: 'from GROK_HOME' }))writeSession(path.join(home, '.grok'), 'g', SID, jl({ type: 'user', content: 'from ~/.grok' }))- const abs = parseRemoteGrokChat(runOn(remoteGrokChatCommand(SID)!, { HOME: home, GROK_HOME: custom }).stdout)- expect(abs).toEqual({ text: jl({ type: 'user', content: 'from GROK_HOME' }) })- const rel = parseRemoteGrokChat(runOn(remoteGrokChatCommand(SID)!, { HOME: home, GROK_HOME: 'relative/dir' }).stdout)- expect(rel).toEqual({ text: jl({ type: 'user', content: 'from ~/.grok' }) })+ const given = parseRemoteGrokChat(runOn(remoteGrokChatCommand(SID, undefined, custom)!, { HOME: home }).stdout)+ expect(given).toEqual({ text: jl({ type: 'user', content: 'from GROK_HOME' }) })+ // No validated home = $HOME/.grok, whatever the env says: the root was decided in TypeScript.+ const fallback = parseRemoteGrokChat(runOn(remoteGrokChatCommand(SID)!, { HOME: home, GROK_HOME: custom }).stdout)+ expect(fallback).toEqual({ text: jl({ type: 'user', content: 'from ~/.grok' }) })})it('answers a clean miss with status 0 — "no transcript" is an ANSWER, not a failed ssh', () => {@@ -141,7 +144,7 @@ describe('remoteGrokChatCommand under a real /bin/sh', () => {const home = freshHome('i')const odd = path.join(host, 'i-[star]*')writeSession(odd, 'g', SID, jl({ type: 'user', content: 'odd home' }))- const r = runOn(remoteGrokChatCommand(SID)!, { HOME: home, GROK_HOME: odd })+ const r = runOn(remoteGrokChatCommand(SID, undefined, odd)!, { HOME: home })expect(parseRemoteGrokChat(r.stdout)).toEqual({ text: jl({ type: 'user', content: 'odd home' }) })})})@@ -161,7 +164,11 @@ describe('createReadRemoteGrokChat — the tri-state', () => {t?: typeof target | undefinedrun?: (t: typeof target, cmd: string) => Promise<{ code: number; stdout: string }>}) => {- const run = vi.fn(o.run ?? (async () => ({ code: 0, stdout: 'NODETERM_ABSENT\n' })))+ const run = vi.fn(+ o.run ??+ (async (_t: typeof target, cmd: string) =>+ cmd === REMOTE_GROK_HOME_PROBE ? { code: 0, stdout: '' } : { code: 0, stdout: 'NODETERM_ABSENT\n' })+ )const read = createReadRemoteGrokChat({isRemote: () => o.remote ?? false,target: () => o.t,@@ -182,7 +189,7 @@ describe('createReadRemoteGrokChat — the tri-state', () => {run: async () => ({ code: 0, stdout: 'NODETERM_ABSENT\n' })})expect(await read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false, absent: true })- expect(run).toHaveBeenCalledOnce()+ expect(run).toHaveBeenCalled()})it('remote with no master = could not ask (unreadable), and nothing ran', async () => {@@ -205,8 +212,10 @@ describe('createReadRemoteGrokChat — the tri-state', () => {throw new Error('master down')},async () => ({ code: 255, stdout: '' }),- async () => ({ code: 3, stdout: '' }),- async () => ({ code: 0, stdout: 'half a reply' })+ async () => ({ code: 0, stdout: 'half a reply' }),+ // The $GROK_HOME probe itself failed: the root is unknown, so nothing is read.+ async (_t: typeof target, cmd: string) =>+ cmd === REMOTE_GROK_HOME_PROBE ? { code: 255, stdout: '' } : { code: 0, stdout: 'NODETERM_ABSENT\n' }]) {expect(await make({ remote: true, t: target, run }).read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false })}@@ -222,7 +231,54 @@ describe('createReadRemoteGrokChat — the tri-state', () => {})expect(await read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: true, text: jl({ type: 'user', content: 'over ssh' }) })expect(run.mock.calls[0][0]).toBe(target)- expect(run.mock.calls[0][1]).toContain(SID)+ expect(run.mock.calls.at(-1)![1]).toContain(SID)+ })++ it('two sessions with the id is its own answer — AMBIGUOUS, not unreadable (a retry cannot fix it)', async () => {+ const home = freshHome('amb')+ writeSession(path.join(home, '.grok'), 'g1', SID, jl({ type: 'user', content: 'one' }))+ writeSession(path.join(home, '.grok'), 'g2', SID, jl({ type: 'user', content: 'two' }))+ const { read } = make({ remote: true, t: target, run: async (_t, cmd) => runOn(cmd, { HOME: home }) })+ expect(await read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false, ambiguous: true })+ })++ it('resolves the root with the INSTALLER\'s rule: an unsafe $GROK_HOME falls back to $HOME/.grok', async () => {+ const home = freshHome('root')+ writeSession(path.join(home, '.grok'), 'g', SID, jl({ type: 'user', content: 'from ~/.grok' }))+ const good = path.join(host, 'root-good')+ writeSession(good, 'g', SID, jl({ type: 'user', content: 'from GROK_HOME' }))+ // Absolute, but carries `$` — isSafeRemoteGrokHome refuses it, so the hook installer writes+ // under ~/.grok and the reader must look there too.+ const unsafe = path.join(host, 'root-$bad')+ writeSession(unsafe, 'g', SID, jl({ type: 'user', content: 'UNSAFE ROOT' }))+ const readWith = async (env: Record<string, string>) =>+ make({ remote: true, t: target, run: async (_t, cmd) => runOn(cmd, { HOME: home, ...env }) }).read({+ sessionId: SID,+ nodeId: 'n'+ })+ expect(await readWith({ GROK_HOME: good })).toEqual({ ok: true, text: jl({ type: 'user', content: 'from GROK_HOME' }) })+ expect(await readWith({ GROK_HOME: `${good}/` })).toEqual({ ok: true, text: jl({ type: 'user', content: 'from GROK_HOME' }) })+ expect(await readWith({ GROK_HOME: unsafe })).toEqual({ ok: true, text: jl({ type: 'user', content: 'from ~/.grok' }) })+ expect(await readWith({ GROK_HOME: 'relative/dir' })).toEqual({ ok: true, text: jl({ type: 'user', content: 'from ~/.grok' }) })+ expect(resolveReportedGrokHome(unsafe)).toBeNull()+ })++ it('honours a smaller per-call maxBytes: a TAIL window, newest messages kept, partial line dropped', async () => {+ const home = freshHome('win')+ const rows = Array.from({ length: 300 }, (_, i) => ({ type: 'user', content: `row ${i} ${'y'.repeat(40)}` }))+ const body = jl(...rows)+ writeSession(path.join(home, '.grok'), 'g', SID, body)+ const { read, run } = make({ remote: true, t: target, run: async (_t, cmd) => runOn(cmd, { HOME: home }) })+ const got = await read({ sessionId: SID, nodeId: 'n' }, { maxBytes: 4096 })+ if (!got || !got.ok) throw new Error('expected text')+ expect(Buffer.byteLength(got.text)).toBeLessThanOrEqual(4096)+ const kept = got.text.trimEnd().split('\n')+ expect(kept.at(-1)).toBe(JSON.stringify(rows.at(-1)))+ for (const l of kept) expect(() => JSON.parse(l)).not.toThrow()+ expect(kept.length).toBeLessThan(rows.length)+ // …and never MORE than the cap, whatever the caller asks.+ await read({ sessionId: SID, nodeId: 'n' }, { maxBytes: 64 * 1024 * 1024 })+ expect(run.mock.calls.at(-1)![1]).toBe(remoteGrokChatCommand(SID, CHAT_PAGE_MAX_BYTES, null))})})diff --git a/src/core/remote-grok-chat.ts b/src/core/remote-grok-chat.tsindex 81e8f1588..acc202606 100644--- a/src/core/remote-grok-chat.ts+++ b/src/core/remote-grok-chat.ts@@ -10,45 +10,62 @@//// One round trip, one generated `sh` line, built from the session id alone://-// - The ROOT is `$GROK_HOME` when the host sets it to an absolute path, else `$HOME/.grok` — the-// same rule `RemoteHooks.installGrokRemote` applies before it writes the hook grok fires, and-// read over the same plain exec channel, so the hook and the reader agree on where grok lives.+// - The ROOT is decided BEFORE that line, in TypeScript: the factory asks the host+// `REMOTE_GROK_HOME_PROBE` and resolves the answer with `resolveReportedGrokHome` — the very+// function `RemoteHooks.installGrokRemote` uses before it writes the hook grok fires — falling+// back to `$HOME/.grok`. One probe, one validator, so the hook and the reader cannot disagree+// on where grok lives (a `$` in `$GROK_HOME`, say, sends BOTH to `~/.grok`). That costs a+// second exec over the same ControlMaster.// - The FILE is found by the session id, which is the one key no other session shares:// `<root>/sessions/*/<id>/chat_history.jsonl`. No cwd is needed, which also covers grok's// slug+hash group for a cwd longer than 255 encoded bytes (`grokEncodedCwdDirName` cannot name// it). Two matches are REFUSED (exit 3), never resolved by picking one.// - The READ is the paged transcript command (`transcriptPageCommand`: size + a byte window, dd-// status framed inside the base64) at a `CHAT_PAGE_MAX_BYTES` window — exactly the cap the local-// leg's `readCappedTail` applies. grok does not page (its file is rewritten in place, see-// `grok-chat.ts`), so this is its whole read.+// status framed inside the base64): the newest `maxBytes` of the file — the caller's page size+// when it is smaller (the ⌘M panel asks for a small tail, the phone for 256 KB), never more than+// `CHAT_PAGE_MAX_BYTES`, the cap the local leg's `readCappedTail` applies. grok does not page+// (its file is rewritten in place, see `grok-chat.ts`), so this TAIL window is its whole read:+// the newest messages show, the partial first line is dropped, and `olderCursor` stays null.//// The path the file is read from never crosses the machine boundary as an input: the glob and the// read run in the same script, and the only interpolated values are app-built constants and the// session id, validated by `isSafeGrokSessionId` (no `/`, `.`, quote or space can pass).import { posixQuote } from '../shared/ssh'import { CHAT_PAGE_MAX_BYTES } from '../shared/chat-page'-import { GROK_CHAT_HISTORY_FILE, isSafeGrokSessionId } from './agents/grok-paths'+import {+ GROK_CHAT_HISTORY_FILE,+ REMOTE_GROK_HOME_PROBE,+ isSafeGrokSessionId,+ resolveReportedGrokHome+} from './agents/grok-paths'import { parseTranscriptPage, transcriptPageCommand } from './remote-ssh/transcript-window'/** What the host answered for a clean miss (status 0) — the same word the page commands use. */const ABSENT = 'NODETERM_ABSENT'-/** Exit status for "the id names more than one session": a refusal to guess, read as a failure. */+/** Exit status for "the id names more than one session": a refusal to guess, its own answer+ * (`ambiguous`) — neither a miss nor a failure a retry could heal. */const AMBIGUOUS_EXIT = 3/**- * The host-side read for `sessionId`, or null when no transcript file can carry that id.+ * The host-side read for `sessionId` under `grokHome` (already resolved by+ * `resolveReportedGrokHome`; null = `$HOME/.grok`), or null when no transcript file can carry that+ * id. The script never reads `$GROK_HOME` itself — the root is the validated one or the fallback.** Wrapped in `sh -c` because the ssh exec channel runs the USER's login shell: under zsh a glob* that matches nothing is an error ("no matches found") rather than a literal, which would turn* every clean miss into a failed read. The inner script is POSIX sh either way.*/-export function remoteGrokChatCommand(sessionId: string, maxBytes: number = CHAT_PAGE_MAX_BYTES): string | null {+export function remoteGrokChatCommand(+ sessionId: string,+ maxBytes: number = CHAT_PAGE_MAX_BYTES,+ grokHome: string | null = null+): string | null {if (!isSafeGrokSessionId(sessionId)) return nullconst id = posixQuote(sessionId)const file = posixQuote(GROK_CHAT_HISTORY_FILE)const script = [- 'case "${GROK_HOME:-}" in /*) r=$GROK_HOME ;; *) r=$HOME/.grok ;; esac',+ grokHome ? `r=${posixQuote(grokHome.replace(/\/$/, ''))}` : 'r=$HOME/.grok','n=0; d=',// `*` outside the quotes (it must glob); the root is quoted, so a `[` or `*` in it is a path.`for p in "$r"/sessions/*/${id}; do if [ -f "$p"/${file} ]; then n=$((n + 1)); d=$p; fi; done`,@@ -81,8 +98,9 @@ export function parseRemoteGrokChat(return { text: data.toString('utf8') }}-/** A remote grok read: the host's text, a clean miss (`absent`), or could-not-read. */-export type RemoteGrokChat = { ok: true; text: string } | { ok: false; absent?: true }+/** A remote grok read: the host's text, a clean miss (`absent`), an id naming two sessions+ * (`ambiguous` — no retry fixes it), or could-not-read. */+export type RemoteGrokChat = { ok: true; text: string } | { ok: false; absent?: true; ambiguous?: true }/*** The desktop's remote grok leg, injected into `readChatTranscript` as `readRemoteGrok`. `null` =@@ -97,20 +115,31 @@ export function createReadRemoteGrokChat<T>(deps: {/** The master to ask over (live pty, else the node's SSH project), or undefined when none. */target(nodeId: string): T | undefinedrun(target: T, cmd: string): Promise<{ code: number; stdout: string }>- /** Test seam; defaults to the local leg's cap. */+ /** The ceiling; defaults to the local leg's cap. A caller's smaller `maxBytes` narrows it. */maxBytes?: number-}): (q: { sessionId?: string; nodeId?: string }) => Promise<RemoteGrokChat | null> {- const maxBytes = deps.maxBytes ?? CHAT_PAGE_MAX_BYTES- return async (q) => {+}): (+ q: { sessionId?: string; nodeId?: string },+ opts?: { maxBytes?: number }+) => Promise<RemoteGrokChat | null> {+ const cap = Math.min(deps.maxBytes ?? CHAT_PAGE_MAX_BYTES, CHAT_PAGE_MAX_BYTES)+ return async (q, opts) => {+ const asked = opts?.maxBytes+ const maxBytes =+ typeof asked === 'number' && Number.isFinite(asked) && asked > 0 ? Math.min(cap, Math.floor(asked)) : capif (!q.nodeId) return nullconst t = deps.target(q.nodeId)if (!t && !deps.isRemote(q.nodeId)) return null// No id, or one no transcript file can carry: nothing to find — an answer, not a failure.- const cmd = q.sessionId ? remoteGrokChatCommand(q.sessionId, maxBytes) : null- if (!cmd) return { ok: false, absent: true }+ if (!q.sessionId || !remoteGrokChatCommand(q.sessionId, maxBytes)) return { ok: false, absent: true }if (!t) return { ok: false }try {+ // The root first, by the installer's own probe + validator (see the header).+ const probe = await deps.run(t, REMOTE_GROK_HOME_PROBE)+ if (probe.code !== 0) return { ok: false }+ const cmd = remoteGrokChatCommand(q.sessionId, maxBytes, resolveReportedGrokHome(probe.stdout))+ if (!cmd) return { ok: false, absent: true }const r = await deps.run(t, cmd)+ if (r.code === AMBIGUOUS_EXIT) return { ok: false, ambiguous: true }if (r.code !== 0) return { ok: false }const got = parseRemoteGrokChat(r.stdout, maxBytes)return 'absent' in got ? { ok: false, absent: true } : { ok: true, text: got.text }diff --git a/src/core/transcript-ipc.grok.test.ts b/src/core/transcript-ipc.grok.test.tsindex 8e86447af..dc0adcd7c 100644--- a/src/core/transcript-ipc.grok.test.ts+++ b/src/core/transcript-ipc.grok.test.ts@@ -12,6 +12,7 @@ import { initPlatform, resetPlatformForTests } from './platform'import { readChatTranscript, type TranscriptIpcDeps } from './transcript-ipc'import { _resetGrokSessionDirsForTests, rememberGrokSessionDir } from './grok-session'import { setCustomAgentBaseResolver } from '../shared/agents/config'+import { GROK_AMBIGUOUS_SESSION_MESSAGE } from '../shared/chat-page'const GROK_SID = '01a06126-b981-73f1-8b68-4547e4d7da84'const CWD = '/srv/app'@@ -84,6 +85,26 @@ describe('readChatTranscript — grok, local', () => {expect(res).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })})+ it('a paged local read is the newest page.maxBytes too — the same TAIL window the remote leg serves', async () => {+ const rows = Array.from({ length: 2000 }, (_, i) => ({ type: 'user', content: `row ${i} ${'z'.repeat(60)}` }))+ writeLocalGrok(jl(...rows))+ const res = await readChatTranscript(+ { sessionId: GROK_SID, cwd: CWD, nodeId: 'n1', agentId: 'grok' },+ { maxBytes: 65536 },+ {}+ )+ expect(res.found).toBe(true)+ expect(res.olderCursor).toBeNull()+ expect(res.messages.length).toBeGreaterThan(0)+ expect(res.messages.length).toBeLessThan(rows.length)+ expect(JSON.stringify(res.messages.at(-1))).toContain('row 1999 ')+ // The partial first line was dropped, not parsed as a mangled message.+ for (const m of res.messages) expect(JSON.stringify(m)).toMatch(/row \d+ z{60}/)+ // …and the legacy unpaged read keeps the whole (5 MiB-capped) file.+ const legacy = await readChatTranscript({ sessionId: GROK_SID, cwd: CWD, nodeId: 'n1', agentId: 'grok' }, undefined, {})+ expect(legacy.messages.length).toBe(rows.length)+ })+it('a local node (remote leg says null) still reads locally', async () => {writeLocalGrok(jl({ type: 'user', content: 'local grok' }))const readRemoteGrok = vi.fn(async () => null)@@ -148,6 +169,22 @@ describe('readChatTranscript — grok, remote (SSH project)', () => {expect(bad).toEqual({ messages: [], found: false })})+ it('an id matching two host sessions REJECTS with its own sentence — never unreadable, never not-found', async () => {+ const readRemoteGrok = async () => ({ ok: false as const, ambiguous: true as const })+ await expect(readChatTranscript(remoteQ, { maxBytes: 65536 }, { readRemoteGrok })).rejects.toThrow(+ GROK_AMBIGUOUS_SESSION_MESSAGE+ )+ await expect(readChatTranscript(remoteQ, undefined, { readRemoteGrok })).rejects.toThrow(GROK_AMBIGUOUS_SESSION_MESSAGE)+ })++ it('hands the page\'s maxBytes to the remote leg (the legacy read asks for no window)', async () => {+ const readRemoteGrok = vi.fn(async (_q: unknown, _o?: { maxBytes?: number }) => ({ ok: true as const, text: jl({ type: 'user', content: 'h' }) }))+ await readChatTranscript(remoteQ, { maxBytes: 262144 }, { readRemoteGrok })+ expect(readRemoteGrok.mock.calls[0][1]).toEqual({ maxBytes: 262144 })+ await readChatTranscript(remoteQ, undefined, { readRemoteGrok })+ expect(readRemoteGrok.mock.calls[1][1]).toBeUndefined()+ })+it('never asks the claude remote legs for a grok node', async () => {const readRemotePage = vi.fn(async () => ({ ok: true as const, data: Buffer.from(''), start: 0 }))const readRemote = vi.fn(async () => 'x')diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.tsindex 55163eaff..c88bb59d7 100644--- a/src/core/transcript-ipc.ts+++ b/src/core/transcript-ipc.ts@@ -12,7 +12,12 @@import fsp from 'node:fs/promises'import { IPC } from '../shared/ipc'import type { ChatTranscriptResult, TranscriptLine, TranscriptPresence } from '../shared/types'-import { CHAT_PAGE_MAX_BYTES, normalizeChatPage, type ChatTranscriptPage } from '../shared/chat-page'+import {+ CHAT_PAGE_MAX_BYTES,+ GROK_AMBIGUOUS_SESSION_MESSAGE,+ normalizeChatPage,+ type ChatTranscriptPage+} from '../shared/chat-page'import { platform } from './platform'import { parseGrokChat } from './grok-chat'import type { RemoteGrokChat } from './remote-grok-chat'@@ -87,7 +92,7 @@ export interface TranscriptIpcDeps {* claude's `readRemotePage` tails a claude file and must never answer for a grok node.* Electron-only, like the other remote legs.*/- readRemoteGrok?(q: TranscriptQuery): Promise<RemoteGrokChat | null>+ readRemoteGrok?(q: TranscriptQuery, opts?: { maxBytes?: number }): Promise<RemoteGrokChat | null>}export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false; absent?: true }@@ -233,8 +238,13 @@ async function readGrokChat(}}if (deps.readRemoteGrok) {- const remote = await deps.readRemoteGrok(q)+ // A paged read asks for the newest `page.maxBytes` only (the phone asks for 256 KB): still one+ // whole capped read, just a smaller tail window. The legacy read keeps the full cap.+ const remote = await deps.readRemoteGrok(q, page ? { maxBytes: page.maxBytes } : undefined)if (remote !== null) {+ // Two host sessions carry this id: its own sentence, as a rejection (the result shape is a+ // locked wire format) — never `unreadable`, whose copy promises a retry that cannot help.+ if (!remote.ok && remote.ambiguous) throw new Error(GROK_AMBIGUOUS_SESSION_MESSAGE)if (!remote.ok) return remote.absent ? notFound() : unreadable()return served(remote.text)}@@ -244,7 +254,8 @@ async function readGrokChat(if (q.remoteOnly) return unreadable()const gp = q.sessionId ? await locateGrok(q.sessionId) : undefinedif (!gp) return notFound()- const buf = await readCappedTail(gp)+ // Same window as the remote leg: a paged read's newest `page.maxBytes`, the legacy read the cap.+ const buf = await readCappedTail(gp, page ? page.maxBytes : undefined)return buf === undefined ? notFound() : served(buf)}diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex d806ff26a..7ff050d4e 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -196,23 +196,27 @@ function linesFrom(raw: string): TranscriptLine[] {return out}-// Read the last ~READ_CAP_BYTES of the file as UTF-8 (dropping the partial leading line on a-// capped read), or the whole file when it's small. Returns undefined if it can't be read.-export async function readCappedTail(filePath: string): Promise<string | undefined> {+// Read the last `cap` bytes (default and ceiling READ_CAP_BYTES) of the file as UTF-8 (dropping the+// partial leading line on a capped read), or the whole file when it's small. Returns undefined if+// it can't be read.+export async function readCappedTail(filePath: string, cap: number = READ_CAP_BYTES): Promise<string | undefined> {+ const limit = Math.min(READ_CAP_BYTES, Math.max(1, Math.floor(cap)))try {const stat = await fs.promises.stat(filePath)- if (stat.size > READ_CAP_BYTES) {+ if (stat.size > limit) {const fd = await fs.promises.open(filePath, 'r')try {- const start = stat.size - READ_CAP_BYTES- const { buffer } = await fd.read({+ // One LOOKBEHIND byte before the window: when it is a `\n`, the window's first line is+ // whole and survives the drop below (the remote page reader's rule).+ const start = stat.size - limit - 1+ const { buffer, bytesRead } = await fd.read({position: start,- length: READ_CAP_BYTES,- buffer: Buffer.alloc(READ_CAP_BYTES)+ length: limit + 1,+ buffer: Buffer.alloc(limit + 1)})- const s = buffer.toString('utf8')- const nl = s.indexOf('\n') // drop the first (partial) line- return nl >= 0 ? s.slice(nl + 1) : s+ const data = buffer.subarray(0, bytesRead)+ const nl = data.indexOf(0x0a) // drop the first (partial) line+ return nl >= 0 ? data.subarray(nl + 1).toString('utf8') : ''} finally {await fd.close()}diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex d737aca37..f87b44a7f 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -11,7 +11,7 @@ import { legacyEndpointMigration } from './legacy-hook-endpoint'import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, type ManagedHookEvent } from '@shared/agents/hook-events'import { GROK_EVENTS } from '../../core/agents/hooks/grok'-import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'+import { GROK_HOOK_FILE, REMOTE_GROK_HOME_PROBE, resolveReportedGrokHome } from '../../core/agents/grok-paths'import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'import { hookServer } from '../../core/agents/hook-server'import { updateRemoteSettingsFile } from '../../core/agents/hooks/remote-settings-file'@@ -557,15 +557,11 @@ export class RemoteHooks {): Promise<void> {try {const { stdout: rawHome } = await this.r.run(- childArgs(conn, controlPath, 'printf %s "${GROK_HOME:-}"')+ childArgs(conn, controlPath, REMOTE_GROK_HOME_PROBE))- // Trim at the READ site: isSafeRemoteGrokHome judges the exact string we would go on to- // interpolate into a remote command line, so it (correctly) refuses an untrimmed value.- const reported = rawHome.trim()- // `|| '/'`: a host that genuinely reports `/` means `/`, and letting the strip leave `''`- // would make `grokHome` a value no host ever said.- const stripped = reported.replace(/\/+$/, '') || '/'- const grokHome = isSafeRemoteGrokHome(reported) ? stripped : `${home}/.grok`+ // The ONE rule (trim at the read site, isSafeRemoteGrokHome, strip trailing slashes) the+ // remote chat reader applies too, so the hook and the reader agree on grok's root.+ const grokHome = resolveReportedGrokHome(rawHome) ?? `${home}/.grok`// Joined so the separator is never doubled (`//hooks` is implementation-defined in POSIX).const config = `${grokHome.replace(/\/$/, '')}/hooks/${GROK_HOOK_FILE}`const script = `${remoteDir}/agent-hooks/grok.sh`diff --git a/src/main/remote/host-service.chat.test.ts b/src/main/remote/host-service.chat.test.tsindex b36333802..b50c0a110 100644--- a/src/main/remote/host-service.chat.test.ts+++ b/src/main/remote/host-service.chat.test.ts@@ -10,6 +10,7 @@// - Happy paths answer `{page}` / `{status}` / `{result}` / `{ok}`.import { describe, expect, it, vi } from 'vitest'import { REF_MAX_LEN } from '../../shared/presence'+import { GROK_AMBIGUOUS_SESSION_MESSAGE } from '../../shared/chat-page'import { CHAT_SEND_TEXT_MAX, type ChatPage, type ChatStatus } from '../../shared/mobile-chat'import {createHostHandlers,@@ -126,6 +127,14 @@ describe('chat.page', () => {body: { message: 'Chat is not available for this agent.' }})})+ it('an ambiguous grok session id reaches the phone as its own sentence, not "Could not read"', async () => {+ const { call } = make({ page: vi.fn(async () => { throw new Error(GROK_AMBIGUOUS_SESSION_MESSAGE) }) })+ expect(await call('chat.page', { nodeId: 'n1' })).toEqual({+ id: 'r1',+ ok: false,+ body: { message: GROK_AMBIGUOUS_SESSION_MESSAGE }+ })+ })it('a failed read is an error, never an empty page', async () => {const { call } = make({ page: vi.fn(async () => { throw new Error('boom') }) })expect(await call('chat.page', { nodeId: 'n1' })).toEqual({diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 2b1f76443..d1bef8eb5 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -35,7 +35,7 @@ import * as fsOps from '../../core/fs-ops'import { TITLE_MAX, type RemoteNodeInput } from '../../core/project-node-append'import { parseCardLabelEdit, type CardLabelEdit } from '../../core/project-kanban-write'import { isValidPendingId } from '../../core/agents/pending-approvals'-import { normalizeChatPage } from '../../shared/chat-page'+import { GROK_AMBIGUOUS_SESSION_MESSAGE, isGrokAmbiguousSessionError, normalizeChatPage } from '../../shared/chat-page'import {CHAT_SEND_TEXT_MAX,sanitizeChatText,@@ -857,7 +857,11 @@ export function createHostHandlers(? socket.respond(req.id, true, { page }): fail('Unknown node.'))- .catch(() => fail('Could not read the transcript.'))+ // An id naming two host grok sessions is its own sentence: "could not read" would+ // promise a retry that can never help. Every other failure stays generic.+ .catch((e: unknown) =>+ fail(isGrokAmbiguousSessionError(e) ? GROK_AMBIGUOUS_SESSION_MESSAGE : 'Could not read the transcript.')+ )return}case 'chat.status':diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 9bba1d683..65e41f857 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -19,6 +19,7 @@ import {type ChatThread} from '../lib/chatPaging'import { E_UNSUPPORTED } from '@shared/rpc'+import { GROK_AMBIGUOUS_SESSION_MESSAGE, isGrokAmbiguousSessionError } from '@shared/chat-page'import { Spinner } from '../components/Spinner'import { CHAT_LIVE_RELOAD_MIN_MS, CHAT_OPTIMISTIC_WORKING_MS, chatActivity, planLiveReload } from '../lib/chatLive'import { sentCommand } from '@shared/chat-command'@@ -84,7 +85,7 @@ interface ChatPanelProps {* 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'+type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'ambiguous' | 'error'const isUnsupported = (e: unknown): boolean =>!!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED@@ -105,6 +106,12 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {title: "Transcripts can't be read on this surface.",detail: 'Open this session on the desktop app to read its conversation.'},+ // A remote grok id that names two sessions on the host: a fixed fact, like `unsupported` — so,+ // like it, no Retry (waiting cannot change which file is this node's).+ ambiguous: {+ title: GROK_AMBIGUOUS_SESSION_MESSAGE,+ detail: 'nodeterm will not guess which one belongs to this node.'+ },error: {title: "Couldn't read the transcript.",detail: "The agent's host may not be reachable — Retry once it is."@@ -356,7 +363,7 @@ export function ChatPanel({// …and, as there, a thread of ANOTHER transcript (the session changed under the panel) is// cleared: the error message must not sit under the previous session's conversation.if (t.identity !== identity) setThread(emptyThread(identity))- setLoadState(isUnsupported(e) ? 'unsupported' : 'error')+ setLoadState(isUnsupported(e) ? 'unsupported' : isGrokAmbiguousSessionError(e) ? 'ambiguous' : 'error')settleHeldReload(threadHeldForRef.current)})@@ -757,7 +764,7 @@ export function ChatPanel({{EMPTY_TEXT[loadState].detail && (<div className="term-chat__empty-detail">{EMPTY_TEXT[loadState].detail}</div>)}- {loadState !== 'unsupported' && loadState !== 'ok' && (+ {loadState !== 'unsupported' && loadState !== 'ambiguous' && loadState !== 'ok' && (<button className="term-chat__retry" onClick={() => load()}>Retry</button>diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsxindex 36bb3bfeb..08c70582a 100644--- a/src/renderer/nodes/ChatPanel.ux.test.tsx+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx@@ -16,6 +16,7 @@ import { useAgentStatus } from '../state/agentStatus'interface Pending {sessionId: string | undefinedresolve: (r: ChatTranscriptResult) => void+ reject: (e: unknown) => void}// ONE stable api object: `load` depends on `api`, so a fresh object per `useSession()` call would@@ -25,7 +26,7 @@ const { sendText, readTranscript, pending, session } = vi.hoisted(() => {const sendText = vi.fn(async (_id: string, _text: string) => true as const)const readTranscript = vi.fn((sessionId: string | undefined) =>- new Promise<ChatTranscriptResult>((resolve) => pending.push({ sessionId, resolve }))+ new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ sessionId, resolve, reject })))const session = { api: { chat: { readTranscript }, pty: { sendText } } }return { sendText, readTranscript, pending, session }@@ -33,6 +34,7 @@ const { sendText, readTranscript, pending, session } = vi.hoisted(() => {vi.mock('../session/session', () => ({ useSession: () => session }))import { ChatPanel } from './ChatPanel'+import { GROK_AMBIGUOUS_SESSION_MESSAGE } from '@shared/chat-page'const NODE = 'n-chat-ux'let host: HTMLDivElement@@ -252,6 +254,21 @@ describe('ChatPanel empty states', () => {expect(host.querySelector('.term-chat__retry')).not.toBeNull()})+ it('a grok session id that matches two host sessions says so, with NO Retry (a retry cannot fix it)', async () => {+ await render({ agentId: 'grok' })+ // Over Electron IPC only the message survives a rejection (the `code` is dropped), wrapped in+ // Electron's own prefix — the panel must recognise it from the message alone.+ await act(async () => {+ pending[0].reject(+ new Error(`Error invoking remote method 'chat:read-transcript': Error: ${GROK_AMBIGUOUS_SESSION_MESSAGE}`)+ )+ })+ expect(msgs().textContent).toContain(GROK_AMBIGUOUS_SESSION_MESSAGE)+ expect(msgs().textContent).not.toContain('may not be reachable')+ expect(msgs().textContent).not.toContain("can't be read on this surface")+ expect(host.querySelector('.term-chat__retry')).toBeNull()+ })+it('a clean miss still says no transcript was found', async () => {await render()await act(async () => {diff --git a/src/shared/chat-fixtures/grok/README.md b/src/shared/chat-fixtures/grok/README.mdindex 8f9e92918..e62e010c5 100644--- a/src/shared/chat-fixtures/grok/README.md+++ b/src/shared/chat-fixtures/grok/README.md@@ -40,8 +40,10 @@ host's text through `readRemoteGrok`) serve the identical page, and that `page.m(duplicate and dangling tool results) rewrite the history in place. A byte offset is therefore not astable identity for a line, so:-- The desktop reads the **whole file**, capped at its last 5 MiB (`CHAT_PAGE_MAX_BYTES`); when capped,- the partial first line is dropped.+- The desktop reads the file's **tail window**: the newest `page.maxBytes` of it (the phone asks for+ 262144), never more than 5 MiB (`CHAT_PAGE_MAX_BYTES`); the legacy unpaged read takes the full+ 5 MiB. Local and remote (SSH host) legs read the same window. When capped, the partial first line is+ dropped (a line starting exactly on the window edge is kept).- A paged request is answered with ONE page: `olderCursor: null`, `unmatchedResults: []`, and **no`key` and no `at`** on any message (grok records carry no timestamp).- The phone must treat a grok page as the **whole thread**: replace, never merge by key, and never ask@@ -52,6 +54,10 @@ stable identity for a line, so:## Record rules (the Swift port must replicate these exactly)+**Changed in `feat/chat-view-grok`:** a tool part's `arg` is now the SALIENT argument (rule 8) and its+`result` the first three lines of the output (rule 6) — earlier builds showed the raw `arguments` /+full result. The iOS port must follow these goldens, not the old formatting.+Lines are split on `\n`. A line that is blank after JS `trim` is ignored. Each remaining line is`JSON.parse`d (after trim):diff --git a/src/shared/chat-page.ts b/src/shared/chat-page.tsindex 73b82563f..66e210db3 100644--- a/src/shared/chat-page.ts+++ b/src/shared/chat-page.ts@@ -53,3 +53,18 @@ export function normalizeChatPage(page: unknown): ChatTranscriptPage | null {}return { before: b, maxBytes: m }}++/**+ * What a grok chat read says when its session id names MORE than one session on an SSH host+ * (`core/remote-grok-chat.ts` refuses to pick one). It travels as a REJECTION's message — the+ * result shape is a locked wire format, and over Electron IPC a rejection keeps only its message+ * (wrapped in Electron's own prefix, the `code` dropped) — so it is matched by substring. Retry can+ * never fix it, which is why it is not `unreadable`.+ */+export const GROK_AMBIGUOUS_SESSION_MESSAGE = 'This session id matches more than one grok session on the host.'++/** Is `e` the rejection carrying `GROK_AMBIGUOUS_SESSION_MESSAGE` (Electron-wrapped or not)? */+export function isGrokAmbiguousSessionError(e: unknown): boolean {+ const m = e && typeof e === 'object' ? (e as { message?: unknown }).message : undefined+ return typeof m === 'string' && m.includes(GROK_AMBIGUOUS_SESSION_MESSAGE)+}