Skip to content

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

feat(chat): grok chat view reads SSH-project nodes on the host, carries model/effort

review2085d5d4cf16
diff --git a/CLAUDE.md b/CLAUDE.md
index ccea29e57..ee63f4962 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1815,6 +1815,24 @@ else, and its context links must keep classifying across restarts).
harmful. The `auto` permission-mode **version gate is claude's alone** (it is fed by a `claude
--version` probe), and grok's mode flag must go **BEFORE** its `--` separator, which is
end-of-options. Full picture, dialect traps and the device checklist: **`docs/grok-agent.md`**.
+- **Grok chat view (⌘M + phone `chat.page`)** — `parseGrokChat` (`core/grok-chat.ts`) reads
+ `chat_history.jsonl` into claude's `ChatMessage`/`ChatPart` shapes (no new wire field): typed
+ prompts, assistant text, tool calls (`arg` = the salient argument — `command`, `target_file`, …, in
+ claude's `toolArg` order — else the raw JSON, 200 units) with results summarised like claude's,
+ `web_search` backend calls, harness-injected `synthetic_reason` lines as assistant-side `[reason]`
+ notes, and `model_id`/`reasoning_effort` of the NEWEST assistant record (never carried forward).
+ `reasoning` is hidden. It does NOT page: measured on 1.0.13, the file is rewritten via
+ `.sync.tmp` + rename and `/compact`/`/rewind`/history repair replace lines, so it is one capped
+ whole-file read with no keys and no `at`. Routing is by `capabilityAgentId`, so a custom agent built
+ on grok reaches grok's reader, never claude's cwd fallback. **A remote (SSH) grok node is read on its
+ host** (`core/remote-grok-chat.ts`, one `sh -c` round trip: `$GROK_HOME` if absolute else
+ `$HOME/.grok`, the session found by id across `sessions/*/<id>/`, two matches refused, the
+ paged-transcript window at 5 MiB) — its failures are terminal, never this machine's disk (the
+ hook-derived local map names a wrong-machine path for these nodes). The phone gets it for free:
+ `chat.page` reads through the same deps. Golden fixtures + exact rules for the Swift port:
+ `src/shared/chat-fixtures/grok/`. Not supported: the composer's model/effort labels (grok's `/model`
+ and `/effort` pickers are unmeasured — the TUI needed a login here), plan/question answer cards
+ (claude-only), pre-compaction history, and a local session whose map entry `SessionEnd` retired.
- **Antigravity** (`agy` 1.2.3 measured on Windows; the 1.2.12 Linux binary read; builtin since
2026-09 — Google's replacement for Gemini CLI on personal accounts) — in `AGENT_HOOK_TARGETS`
(badge, NEEDS YOU from `ask_question`, a closed set of one, `--after` and triggers) and
@@ -2553,8 +2571,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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. `transcriptExists` shares the same locate
(`remotePresenceFromLocate`: ref/absent/unreadable → present/absent/unknown, a malformed id
- `unknown`), so it also works for a node with no live pty. A remote grok node (no remote reader)
- shows "not supported yet", not the retryable error. (2) **The cwd fallback keeps `accountId`** in BOTH
+ `unknown`), so it also works for a node with no live pty. A remote grok node is read on its host
+ by its own leg (`readRemoteGrok`, see the grok chat bullet), with the same absent/unreadable split. (2) **The cwd fallback keeps `accountId`** in BOTH
`resolveTranscript` and `contextEnsure`; without it a managed-account node fell back to the
system root and could adopt an unrelated session's newest transcript. (3) **Relay tabs** stay
local-only (a transcript read over the relay would read the GUEST's disk) and reject with
@@ -2593,7 +2611,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
trip, dd status inside the base64 like the context-tail's window command) instead of pulling the
5 MB tail on every open and every turn-end reload; its `{ok:false}` is terminal (never the local
disk), and it is tested under a real `/bin/sh` (`transcript-page.realsh.test.ts`). **Grok does not
- page**: a paged request gets its whole capped read with `olderCursor: null` and no keys.
+ page** (its file is rewritten in place, so offsets are no identity): a paged request gets its whole
+ capped read with `olderCursor: null`, no keys, and the newest record's `model`/`effort`.
Server Edition passes `page` through ws-bridge to the same core handler; relay still refuses.
**ChatPanel consumes it progressively** (pure state in `renderer/lib/chatPaging.ts`): the first
read is a 256 KB tail (`CHAT_TAIL_PAGE_BYTES`, with a "Loading conversation…" row), older 512 KB
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index 670e788d3..c1c8ccf69 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -385,7 +385,7 @@ ai-name / comments).
| In-place restart + cold-restore resume | yes | yes | N/A |
| Canvas control | yes, via `~/.claude/skills` + the sh+curl shim. The discovery premise is no longer inferred: `grok inspect --json` on grok 1.0.13 lists `get-linked-context` with `vendor: claude` and `compatibilityStatus: enabled`, and `externalCompat.cells` reports `{surface: 'skills', enabled: true, source: 'default'}` — grok reads `~/.claude/skills` **by default**, without a config edit (§8.7) | **not wired at all** — `agent:control` has no server handler; pre-existing, unchanged by grok | N/A — no canvas |
| Context links | **yes** — `locateGrok` resolves the linked node's `chat_history.jsonl` and `linesFromGrok` renders it. The whole leaf is in core (`core/handoff/locate.ts`, `core/context-link.ts`, `core/grok-session.ts`, `core/claude-accounts-core.ts`); the renderer only asks the pure `canContextLink`, so **no `window.nodeTerminal` member was added** and nothing new crosses the preload bridge | **yes, for free** — the row's old claim that `initContextLink` is never called from `src/server` is stale: `src/server/context-link.ts` calls it, driven off the persisted `bridges[]` instead of the renderer's live edges. Both shells feed the same `sessionId → dir` map from their raw hook listeners (`src/main/index.ts`, `src/server/agent-status.ts`) and both pass `grokHomeDir()` into the path jail — invariant 11 | **N/A** — linking is a canvas gesture and the phone has no canvas (`~/projects/nodeterm-ios`). The transcript it would read is the same file, so this is a surface gap, not a capability one |
-| ⌘M chat panel | **yes** — `chatMessagesFromGrok`, reached through the agent-routed `chat:read-transcript`. The panel is the same component; what is new is that the channel asks WHICH agent before it picks a reader | **yes, for free** — the channel is registered through the CorePlatform seam, so both shells serve it and both route the same way | the phone has no ⌘M panel |
+| ⌘M chat panel | **yes** — `parseGrokChat`, reached through the agent-routed `chat:read-transcript` (by `capabilityAgentId`, so custom agents built on grok too). Paged requests also carry the newest record's `model`/`effort`; there is no paging (the file is rewritten in place). **SSH-project nodes are read on the host** (`core/remote-grok-chat.ts`); a failure there is terminal, never a local read. The composer's model/effort labels stay claude-only (grok's pickers are unmeasured) | **yes, for free** — the channel is registered through the CorePlatform seam, so both shells serve it and both route the same way (the server has no SSH projects, so no remote leg) | **yes** — the relay `chat.page` verb reads through the desktop's same deps, local and remote; golden fixtures for the Swift port in `src/shared/chat-fixtures/grok/` |
| Cross-agent transfer (grok as SOURCE) | **yes** — `renderGrokTranscript` | **N/A** — `buildHandoff` lives in `src/main`; the Server Edition has no transfer path at all, pre-existing and unchanged by grok | N/A |
| Context meter | **yes** — a third tail, on `signals.json` rather than on a transcript, tracked from the session directory the hooks let us derive (there is no hook field pointing at it) | **yes** — both shells create the same tail the same way, with the same `wholeFile` flag. Invariant 11: a tail added in one shell only is a meter the Server Edition silently lacks | the phone reads the mirror, which is agent-agnostic, so the numbers arrive with no phone-side work |
| Session-id minting | **yes** — probed at boot (`ensureGrokCliCaps`), minted at node creation, checked against the ids already on disk for that cwd | **yes** — `registerGrokCliIpc` runs in this shell too, so the browser gets the same answer over WS-RPC. A probe registered in one shell only is minting that silently works on the desktop and not in the browser | N/A — the phone launches nothing (see §8) |
diff --git a/docs/mobile-chat-view.md b/docs/mobile-chat-view.md
index c5fbfe969..b14522c78 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 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. For REMOTE nodes the desktop ⌘M panel follows the same remote-only rule and the same absent-vs-unreadable split (same deps): 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`); it shows `unreadable` as "Couldn't read the transcript." (a remote grok node, which has no remote reader, as "not supported yet"). LOCAL nodes on ⌘M are unchanged — the renderer still sends the cwd, so claude's cwd fallback still applies there; the cwd-only-when-remote rule below is the phone path's. 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. For REMOTE nodes the desktop ⌘M panel follows the same remote-only rule and the same absent-vs-unreadable split (same deps): 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`); it shows `unreadable` as "Couldn't read the transcript." (a remote grok node is read on its host too — `core/remote-grok-chat.ts`, whole-file and unpaged, with the same absent-vs-unreadable split). LOCAL nodes on ⌘M are unchanged — the renderer still sends the cwd, so claude's cwd fallback still applies there; the cwd-only-when-remote rule below is the phone path's. 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/grok-chat-fixtures.test.ts b/src/core/grok-chat-fixtures.test.ts
new file mode 100644
index 000000000..28297ae6c
--- /dev/null
+++ b/src/core/grok-chat-fixtures.test.ts
@@ -0,0 +1,285 @@
+// Golden fixtures for the GROK half of the mobile chat view's parser port
+// (`src/shared/chat-fixtures/grok/`, README section "Grok"). The TS implementation is the
+// REFERENCE: `nodeterm-ios` carries a byte-identical copy and its Swift port must reproduce every
+// `expected/*.json` from the same input. This file is both the drift test and the regenerator:
+//
+// UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/grok-chat-fixtures.test.ts
+//
+// Inputs are SYNTHETIC, built below from the record shapes MEASURED on grok 1.0.13 (the real-derived
+// `__fixtures__/grok/chat_history.jsonl` plus the record vocabulary compiled into the shipped
+// binary). None is a slice of a real session — those carry customer data.
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { parseGrokChat } from './grok-chat'
+import { readChatTranscript } from './transcript-ipc'
+import { _resetGrokSessionDirsForTests, rememberGrokSessionDir } from './grok-session'
+import { fakePlatform } from './platform-fake'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { CHAT_PAGE_DEFAULT_BYTES } from '../shared/chat-page'
+
+const DIR = path.join(__dirname, '..', 'shared', 'chat-fixtures', 'grok')
+const UPDATE = process.env.UPDATE_CHAT_FIXTURES === '1'
+// Regenerating in CI would turn the drift test into a no-op that always passes.
+if (UPDATE && process.env.CI) throw new Error('UPDATE_CHAT_FIXTURES must not be set in CI')
+
+const SID = '01a06126-b981-73f1-8b68-4547e4d7da84'
+/** The phone's first (and, for grok, only) request: the default tail. */
+const REQUEST = { maxBytes: CHAT_PAGE_DEFAULT_BYTES }
+
+// ── Synthetic records, in the measured shapes ────────────────────────────────────────────────────
+type Rec = Record<string, unknown>
+const system = (content: string): Rec => ({ type: 'system', content })
+const user = (text: string, extra: Rec = {}): Rec => ({ type: 'user', content: [{ type: 'text', text }], ...extra })
+const typed = (text: string, promptIndex: number): Rec => user(text, { prompt_index: promptIndex })
+const injected = (reason: string, text: string, extra: Rec = {}): Rec => user(text, { synthetic_reason: reason, ...extra })
+const assistant = (content: string, extra: Rec = {}): Rec => ({
+ type: 'assistant',
+ content,
+ model_id: 'grok-4.6-build',
+ model_fingerprint: 'fp_0000000000synthetic',
+ reasoning_effort: 'xhigh',
+ ...extra
+})
+const call = (id: string, name: string, args: unknown): Rec => ({
+ id,
+ name,
+ arguments: typeof args === 'string' ? args : JSON.stringify(args)
+})
+const result = (id: string, content: unknown): Rec => ({ type: 'tool_result', tool_call_id: id, content })
+const reasoning = (id: string, summary: string[]): Rec => ({
+ type: 'reasoning',
+ id,
+ summary: summary.map((text) => ({ type: 'summary_text', text })),
+ encrypted_content: 'gAAAAABsyntheticSyntheticSynthetic==',
+ status: 'completed'
+})
+const webSearch = (id: string, query: unknown): Rec => ({
+ type: 'backend_tool_call',
+ kind: {
+ tool_type: 'web_search',
+ action: {
+ type: 'search',
+ ...(query === undefined ? {} : { query }),
+ sources: [{ type: 'url', url: 'https://example.com/a' }, { type: 'url', url: 'https://example.com/b' }]
+ }
+ },
+ id,
+ status: 'completed'
+})
+const jl = (...rows: Array<Rec | string>): string =>
+ rows.map((r) => (typeof r === 'string' ? r : JSON.stringify(r))).join('\n') + '\n'
+
+function plainTurns(): string {
+ return jl(
+ system('You are a synthetic coding agent. Follow the rules.\n\n# Rules\n- be brief'),
+ typed('Explain the **plan**:\n\n1. read\n2. write', 0),
+ assistant('## Plan\n\n- Read `a.ts`\n- Then write\n\n```ts\nconst x = 1\n```\n\n> quoted'),
+ // Two text items in one user record are joined with a newline.
+ user('first half', { prompt_index: 1, content: [{ type: 'text', text: 'first half' }, { type: 'text', text: 'second half' }] }),
+ // A string content (the shape `system` and `assistant` use) is read the same way.
+ { type: 'user', content: 'a string-content prompt', prompt_index: 2 },
+ typed('Türkçe karakterler: ğüşiöç — 中文 — emoji 🧪', 3),
+ assistant('Tamam ✓ 🧪')
+ )
+}
+
+function tools(): string {
+ return jl(
+ typed('look around', 0),
+ assistant('Reading the project.', {
+ tool_calls: [
+ call('call-00000001', 'read_file', { target_file: '/srv/app/src/a.ts' }),
+ call('call-00000002', 'list_dir', { target_directory: '/srv/app/src' }),
+ call('call-00000003', 'run_terminal_cmd', { command: 'npm test -- --run', is_background: false }),
+ call('call-00000004', 'search_replace', { file_path: '/srv/app/b.ts', old_string: 'x', new_string: 'y' }),
+ call('call-00000005', 'grep', { pattern: 'TODO', path: '/srv/app' }),
+ // No salient key: the raw arguments text, capped at 200 UTF-16 units.
+ call('call-00000006', 'future_tool', { knob: 'k'.repeat(260) }),
+ // Arguments that are not JSON: shown as written.
+ call('call-00000007', 'odd_tool', 'not json at all')
+ ]
+ }),
+ result('call-00000001', 'line one\nline two\nline three\nline four'),
+ result('call-00000002', 'a.ts\nb.ts'),
+ result('call-00000003', 'r'.repeat(700)),
+ result('call-00000004', ''),
+ // An orphan result (no call declares this id) is dropped, never a speaker-less bubble.
+ result('call-99999999', 'orphan'),
+ assistant('Done: tests pass.')
+ )
+}
+
+function syntheticNotes(): string {
+ return jl(
+ injected('project_instructions', '# AGENTS.md\nUse tabs.'),
+ injected('system_reminder', 'Remember to update the todo list.'),
+ typed('real prompt', 0),
+ assistant('working on it'),
+ injected('task_completed', 'Background task t-1 finished.', { prompt_index: 1 }),
+ injected('subagent_completed', 'Subagent explore-1 returned.'),
+ injected('permission_rejected', 'The user rejected run_terminal_cmd.'),
+ injected('compaction_meta', 'Summary of the conversation so far: the user asked for a plan.'),
+ // A blank reason is no reason: the line is read as typed.
+ injected(' ', 'blank reason reads as the user')
+ )
+}
+
+function backendAndReasoning(): string {
+ return jl(
+ typed('search the web', 0),
+ reasoning('rs_00000001', ['Considering the query.']),
+ reasoning('rs_00000002', []),
+ webSearch('ws_00000001', 'nodeterm canvas terminal manager'),
+ webSearch('ws_00000002', undefined),
+ assistant('Found two sources.')
+ )
+}
+
+function modelEffort(): string {
+ return jl(
+ typed('go', 0),
+ assistant('first', { model_id: 'grok-4.6-build', reasoning_effort: 'medium' }),
+ typed('again', 1),
+ assistant('second', { model_id: 'grok-4.6', reasoning_effort: 'high' })
+ )
+}
+
+function modelEffortNoCarry(): string {
+ const { reasoning_effort: _dropped, ...noEffort } = assistant('newest states no effort', { model_id: 'grok-code-fast' })
+ return jl(typed('go', 0), assistant('older', { reasoning_effort: 'xhigh' }), noEffort)
+}
+
+function modelEffortCap(): string {
+ // 100 UTF-16 units is kept, 101 is not (JS `.length`; Swift `utf16.count`).
+ return jl(typed('go', 0), assistant('capped', { model_id: '\u{1F9EA}'.repeat(50), reasoning_effort: 'e'.repeat(101) }))
+}
+
+function skippedLines(): string {
+ return jl(
+ '{"type":"user","content":[{"type":"text","text":"truncat',
+ '42',
+ 'null',
+ '[1,2,3]',
+ ' ',
+ JSON.stringify({ type: 'some_future_record', content: 'never rendered' }),
+ typed('the one line that survives', 0)
+ )
+}
+
+function reasoningOnly(): string {
+ // A session whose history holds nothing renderable yet: FOUND, with no messages.
+ return jl(reasoning('rs_00000001', ['thinking']), reasoning('rs_00000002', []))
+}
+
+const INPUTS: Record<string, string> = {
+ 'plain-turns.jsonl': plainTurns(),
+ 'tools.jsonl': tools(),
+ 'synthetic-notes.jsonl': syntheticNotes(),
+ 'backend-and-reasoning.jsonl': backendAndReasoning(),
+ 'model-effort.jsonl': modelEffort(),
+ 'model-effort-no-carry.jsonl': modelEffortNoCarry(),
+ 'model-effort-cap.jsonl': modelEffortCap(),
+ 'skipped-lines.jsonl': skippedLines(),
+ 'reasoning-only.jsonl': reasoningOnly()
+}
+
+// ── Plumbing ─────────────────────────────────────────────────────────────────────────────────────
+const serialize = (x: unknown): string => JSON.stringify(x, null, 2) + '\n'
+const fixture = (rel: string): string => path.join(DIR, rel)
+
+function golden(rel: string, content: string): void {
+ const p = fixture(rel)
+ if (UPDATE) {
+ fs.mkdirSync(path.dirname(p), { recursive: true })
+ fs.writeFileSync(p, content)
+ return
+ }
+ expect(fs.existsSync(p), `grok/${rel} is missing — run UPDATE_CHAT_FIXTURES=1`).toBe(true)
+ expect(fs.readFileSync(p, 'utf8'), `grok/${rel}`).toBe(content)
+}
+
+let home: string
+let sessionDir: string
+beforeAll(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-grok-fixtures-'))
+ sessionDir = path.join(home, '.grok', 'sessions', '%2Fsrv%2Fapp', SID)
+ fs.mkdirSync(sessionDir, { recursive: true })
+})
+afterAll(() => fs.rmSync(home, { recursive: true, force: true }))
+beforeEach(() => {
+ vi.spyOn(os, 'homedir').mockReturnValue(home)
+ initPlatform(fakePlatform())
+ _resetGrokSessionDirsForTests()
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ _resetGrokSessionDirsForTests()
+})
+
+describe('grok chat golden fixtures', () => {
+ it('inputs are what the synthetic builders produce (checked in, never real sessions)', () => {
+ for (const [name, body] of Object.entries(INPUTS)) golden(`inputs/${name}`, body)
+ })
+
+ it('no orphan files: inputs/ and expected/ hold exactly the generated set', () => {
+ const listing = (dir: string): string[] => (fs.existsSync(fixture(dir)) ? fs.readdirSync(fixture(dir)).sort() : [])
+ const expected = Object.keys(INPUTS).map((n) => n.replace(/\.jsonl$/, '.page.json')).sort()
+ if (UPDATE) {
+ for (const f of listing('expected')) if (!expected.includes(f)) fs.rmSync(fixture(`expected/${f}`))
+ for (const f of listing('inputs')) if (!(f in INPUTS)) fs.rmSync(fixture(`inputs/${f}`))
+ return
+ }
+ expect(listing('inputs')).toEqual(Object.keys(INPUTS).sort())
+ expect(listing('expected')).toEqual(expected)
+ })
+
+ for (const [name, body] of Object.entries(INPUTS)) {
+ const base = name.replace(/\.jsonl$/, '')
+ it(`${base}: parse + served page match expected/${base}.page.json`, async () => {
+ // The page is what the REAL producer serves: the local leg over a real session directory…
+ fs.writeFileSync(path.join(sessionDir, 'chat_history.jsonl'), body)
+ rememberGrokSessionDir(SID, sessionDir)
+ const page = await readChatTranscript({ sessionId: SID, agentId: 'grok' }, REQUEST, {})
+ // …and the remote leg (the host's text through `readRemoteGrok`) serves the identical page.
+ const remote = await readChatTranscript(
+ { sessionId: SID, nodeId: 'n-remote', agentId: 'grok', remoteOnly: true },
+ REQUEST,
+ { readRemoteGrok: async () => ({ ok: true, text: body }) }
+ )
+ expect(remote).toStrictEqual(page)
+ const parse = parseGrokChat(body)
+ expect(page.messages).toStrictEqual(parse.messages)
+ golden(`expected/${base}.page.json`, serialize({ request: REQUEST, parse, page }))
+ })
+ }
+
+ it('tools: a salient argument names the call, the rest fall back to the raw text', () => {
+ const tools = parseGrokChat(INPUTS['tools.jsonl']).messages[1].parts
+ expect(tools.map((p) => (p.kind === 'tool' ? p.arg : null))).toEqual([
+ null,
+ '/srv/app/src/a.ts',
+ '/srv/app/src',
+ 'npm test -- --run',
+ '/srv/app/b.ts',
+ // claude's `toolArg` order: `path` outranks `pattern`.
+ '/srv/app',
+ JSON.stringify({ knob: 'k'.repeat(260) }).slice(0, 200),
+ 'not json at all'
+ ])
+ })
+
+ it('model-effort-no-carry: the newest record states no effort, so the key is ABSENT', () => {
+ const p = parseGrokChat(INPUTS['model-effort-no-carry.jsonl'])
+ expect(p.model).toBe('grok-code-fast')
+ expect('effort' in p).toBe(false)
+ })
+
+ it('skipped-lines: five lines could not be mapped, and only the typed prompt renders', () => {
+ const p = parseGrokChat(INPUTS['skipped-lines.jsonl'])
+ expect(p.skipped).toBe(5)
+ expect(p.messages).toHaveLength(1)
+ })
+})
diff --git a/src/core/grok-chat.test.ts b/src/core/grok-chat.test.ts
index 3cf170c53..8b57b2f34 100644
--- a/src/core/grok-chat.test.ts
+++ b/src/core/grok-chat.test.ts
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import fs from 'fs'
import path from 'path'
-import { chatMessagesFromGrok } from './grok-chat'
+import { chatMessagesFromGrok, parseGrokChat } from './grok-chat'
const RAW = fs.readFileSync(path.join(__dirname, '__fixtures__/grok/chat_history.jsonl'), 'utf8')
@@ -72,3 +72,129 @@ describe('chatMessagesFromGrok', () => {
expect(chatMessagesFromGrok(claudeLine)).toEqual([])
})
})
+
+// ── The structured reader behind the paged ⌘M read and the phone (`parseGrokChat`) ──────────────
+// Synthetic lines in the shapes MEASURED on grok 1.0.13 (the real-derived fixture above, plus the
+// record vocabulary in the shipped binary): `assistant` carries `model_id`, `model_fingerprint` and
+// `reasoning_effort` at top level; `tool_calls[].arguments` is a JSON STRING; `tool_result.content`
+// is a string. No record carries a timestamp.
+const jl = (...rows: object[]): string => rows.map((r) => JSON.stringify(r)).join('\n') + '\n'
+const asst = (content: string, extra: Record<string, unknown> = {}): object => ({
+ type: 'assistant',
+ content,
+ model_id: 'grok-4.6-build',
+ model_fingerprint: 'fp_synthetic',
+ reasoning_effort: 'high',
+ ...extra
+})
+
+describe('parseGrokChat', () => {
+ it('reports the newest assistant record\'s model and effort', () => {
+ const r = parseGrokChat(
+ jl(asst('one', { reasoning_effort: 'medium' }), { type: 'user', content: 'go on' }, asst('two', { model_id: 'grok-5', reasoning_effort: 'xhigh' }))
+ )
+ expect(r.model).toBe('grok-5')
+ expect(r.effort).toBe('xhigh')
+ })
+
+ it('never carries an effort forward from an older record', () => {
+ // The newest record states no effort: the key is ABSENT, same rule as claude's reader.
+ const r = parseGrokChat(jl(asst('old', { reasoning_effort: 'xhigh' }), asst('new', { reasoning_effort: undefined })))
+ expect(r.model).toBe('grok-4.6-build')
+ expect('effort' in r).toBe(false)
+ })
+
+ it('drops a model or effort longer than 100 UTF-16 units instead of reporting it', () => {
+ const r = parseGrokChat(jl(asst('x', { model_id: 'm'.repeat(101), reasoning_effort: 'e'.repeat(100) })))
+ expect('model' in r).toBe(false)
+ expect(r.effort).toBe('e'.repeat(100))
+ })
+
+ it('omits both keys when no assistant record exists', () => {
+ const r = parseGrokChat(jl({ type: 'user', content: 'hi' }))
+ expect('model' in r).toBe(false)
+ expect('effort' in r).toBe(false)
+ })
+
+ it('names a tool call by its salient argument, not its raw JSON', () => {
+ const r = parseGrokChat(
+ jl(
+ asst('', {
+ tool_calls: [
+ { id: 'call-1', name: 'read_file', arguments: JSON.stringify({ target_file: '/srv/app/a.ts' }) },
+ { id: 'call-2', name: 'list_dir', arguments: JSON.stringify({ target_directory: '/srv/app' }) },
+ { id: 'call-3', name: 'run_terminal_cmd', arguments: JSON.stringify({ command: 'ls -la', is_background: false }) }
+ ]
+ })
+ )
+ )
+ const tools = r.messages[0].parts
+ expect(tools).toEqual([
+ { kind: 'tool', name: 'read_file', arg: '/srv/app/a.ts' },
+ { kind: 'tool', name: 'list_dir', arg: '/srv/app' },
+ { kind: 'tool', name: 'run_terminal_cmd', arg: 'ls -la' }
+ ])
+ })
+
+ it('falls back to the raw arguments text, capped at 200 units, when no salient key exists', () => {
+ const odd = JSON.stringify({ something: 'x'.repeat(300) })
+ const r = parseGrokChat(
+ jl(asst('', { tool_calls: [{ id: 'c', name: 'weird', arguments: odd }, { id: 'd', name: 'broken', arguments: '{not json' }] }))
+ )
+ const [a, b] = r.messages[0].parts as Array<{ arg: string }>
+ expect(a.arg).toBe(odd.slice(0, 200))
+ expect(b.arg).toBe('{not json')
+ })
+
+ it('summarizes a result like claude: first three lines joined, capped at 500', () => {
+ const body = ['l1', 'l2', 'l3', 'l4'].join('\n')
+ const long = 'y'.repeat(900)
+ const r = parseGrokChat(
+ jl(
+ asst('', { tool_calls: [{ id: 'a', name: 'read_file', arguments: '{}' }, { id: 'b', name: 'read_file', arguments: '{}' }] }),
+ { type: 'tool_result', tool_call_id: 'a', content: body },
+ { type: 'tool_result', tool_call_id: 'b', content: long }
+ )
+ )
+ const [a, b] = r.messages[0].parts as Array<{ result?: string }>
+ expect(a.result).toBe('l1 l2 l3')
+ expect(b.result).toBe('y'.repeat(500))
+ })
+
+ it('counts every line it could not map, and nothing it deliberately hides', () => {
+ const r = parseGrokChat(
+ [
+ '{broken',
+ '42',
+ '[1,2]',
+ JSON.stringify({ type: 'some_future_record', content: 'x' }),
+ JSON.stringify({ type: 'reasoning', encrypted_content: 'zz', summary: [] }),
+ JSON.stringify({ type: 'user', content: 'kept' })
+ ].join('\n')
+ )
+ expect(r.skipped).toBe(4)
+ expect(r.messages).toEqual([{ role: 'user', parts: [{ kind: 'text', text: 'kept' }] }])
+ })
+
+ it('survives hostile shapes: one bad field costs that field, never the thread', () => {
+ const r = parseGrokChat(
+ jl(
+ { type: 'assistant', content: 'a', tool_calls: { not: 'an array' } },
+ { type: 'assistant', content: 'b', tool_calls: [null, 7, ['an', 'array'], { id: 'k', name: 42, arguments: null }] },
+ { type: 'tool_result', tool_call_id: 'k', content: { weird: true } },
+ { type: 'backend_tool_call', kind: ['web_search'] },
+ { type: 'user', content: 'still here' }
+ )
+ )
+ expect(r.messages.map((m) => m.role)).toEqual(['assistant', 'assistant', 'assistant', 'user'])
+ expect(r.messages[1].parts).toEqual([
+ { kind: 'text', text: 'b' },
+ { kind: 'tool', name: 'tool', arg: '' }
+ ])
+ expect(r.messages[2].parts).toEqual([{ kind: 'tool', name: 'backend_tool', arg: '' }])
+ })
+
+ it('agrees with chatMessagesFromGrok on the messages', () => {
+ expect(parseGrokChat(RAW).messages).toEqual(chatMessagesFromGrok(RAW))
+ })
+})
diff --git a/src/core/grok-chat.ts b/src/core/grok-chat.ts
index 0d9d2929d..e387169b5 100644
--- a/src/core/grok-chat.ts
+++ b/src/core/grok-chat.ts
@@ -4,11 +4,28 @@
// (`o.message.content`, `tool_use`/`tool_result` blocks) and would return an empty thread for every
// grok line. Sharing that function was never an option; sharing the SHAPE knowledge is, so this
// builds on `grokParse` rather than re-deriving grok's line vocabulary and drifting from it.
+//
+// MEASURED shapes (grok 1.0.13 — the real-derived `__fixtures__/grok/chat_history.jsonl`, plus the
+// record vocabulary compiled into the shipped binary's `xai-chat-state` crate). One record per line,
+// discriminated by `type`, with NO timestamp on any of them:
+// system {content: string} — the system prompt
+// user {content: [{type:'text', text}], prompt_index?, synthetic_reason?, images?,
+// cwd_generation?, prior_turn_interrupt?}
+// assistant {content: string, tool_calls?: [{id, name, arguments: <JSON string>}],
+// model_id, model_fingerprint, reasoning_effort}
+// tool_result {tool_call_id, content: string}
+// backend_tool_call {kind: {tool_type: 'web_search', action: {type, query, sources}}, id, status}
+// reasoning {id, summary: [...], encrypted_content, status}
+// `reasoning_effort` ∈ minimal | low | medium | high | xhigh | max (the binary's enum).
+//
+// The file is NOT an append-only log: grok persists it through `chat_history.jsonl.sync.tmp` +
+// rename, and `/compact`, `/rewind` and its own history repair (duplicate / dangling tool results)
+// rewrite the history in place. A byte offset is therefore not a stable identity for a line, which
+// is why this reader does not page (see `readChatTranscript`).
import type { ChatMessage, ChatPart } from '../shared/types'
+import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
import { grokParse } from './context-link-render'
-
-const TOOL_ARG_MAX = 200
-const TOOL_RESULT_MAX = 500
+import { metaString, summarizeResult } from './transcript-reader'
function textOf(content: unknown): string {
if (typeof content === 'string') return content
@@ -21,6 +38,60 @@ function textOf(content: unknown): string {
return ''
}
+/**
+ * The argument keys that NAME what a grok tool call acts on, in priority order. `target_file` and
+ * `target_directory` are measured (`read_file` / `list_dir`); the rest are the same salient keys
+ * claude's `toolArg` reads. A key a tool does not have is simply not picked, so an unmeasured name
+ * here can never produce a wrong value — only a value that really is in the call.
+ */
+const SALIENT_ARG_KEYS = [
+ 'command',
+ 'target_file',
+ 'file_path',
+ 'target_directory',
+ 'path',
+ 'pattern',
+ 'query',
+ 'url',
+ 'description',
+ 'prompt'
+] as const
+
+/** A tool call's `arg`: its salient string argument, else the raw arguments text — capped at
+ * `CHAT_TOOL_ARG_MAX` UTF-16 units either way. */
+function toolArg(args: unknown): string {
+ const raw = typeof args === 'string' ? args : args && typeof args === 'object' ? JSON.stringify(args) : ''
+ let o: unknown = args
+ if (typeof args === 'string') {
+ try {
+ o = JSON.parse(args)
+ } catch {
+ o = undefined
+ }
+ }
+ if (o && typeof o === 'object' && !Array.isArray(o)) {
+ for (const k of SALIENT_ARG_KEYS) {
+ const v = (o as Record<string, unknown>)[k]
+ if (typeof v === 'string' && v) return v.slice(0, CHAT_TOOL_ARG_MAX)
+ }
+ }
+ return String(raw).slice(0, CHAT_TOOL_ARG_MAX)
+}
+
+/** What a grok conversation reads as. `model` / `effort` are keys only when stated. */
+export interface GrokChatParse {
+ messages: ChatMessage[]
+ /** `model_id` of the NEWEST assistant record (one record answers both fields). */
+ model?: string
+ /** That same record's `reasoning_effort` — never carried forward from an older record. */
+ effort?: string
+ /** Lines that are not a record this reader knows: malformed JSON, a non-object, an unknown
+ * `type`. A record deliberately hidden (`reasoning`, an empty text) is NOT counted. */
+ skipped: number
+}
+
+const KNOWN_TYPES = new Set(['system', 'user', 'assistant', 'tool_result', 'backend_tool_call', 'reasoning'])
+
/**
* Ordered bubbles for a grok conversation.
*
@@ -34,10 +105,20 @@ function textOf(content: unknown): string {
* - `reasoning` is skipped. Its `encrypted_content` is unreadable, and its plaintext `summary` is
* omitted by the same product decision documented in `context-link-render.ts`.
*/
-export function chatMessagesFromGrok(buf: string): ChatMessage[] {
+export function parseGrokChat(buf: string): GrokChatParse {
const messages: ChatMessage[] = []
const toolById = new Map<string, Extract<ChatPart, { kind: 'tool' }>>()
- for (const o of grokParse(buf).lines) {
+ const parsed = grokParse(buf)
+ let skipped = parsed.skipped
+ let model: string | undefined
+ let effort: string | undefined
+ for (const o of parsed.lines) {
+ // `grokParse` admits any JSON value that is an object — an array or a record of a type this
+ // reader has never seen is a line it could not map, and says so in the count.
+ if (Array.isArray(o) || !KNOWN_TYPES.has(o.type as string)) {
+ skipped++
+ continue
+ }
switch (o.type) {
case 'user': {
const t = textOf(o.content)
@@ -56,18 +137,23 @@ export function chatMessagesFromGrok(buf: string): ChatMessage[] {
break
}
case 'assistant': {
+ // A snapshot of ONE record: the newest assistant record answers both fields, and a field it
+ // does not state is absent — the same rule claude's paged reader follows.
+ const rec = o as { model_id?: unknown; reasoning_effort?: unknown }
+ model = metaString(rec.model_id)
+ effort = metaString(rec.reasoning_effort)
const parts: ChatPart[] = []
const t = textOf(o.content)
if (t) parts.push({ kind: 'text', text: t })
- for (const c of o.tool_calls ?? []) {
- const a = typeof c.arguments === 'string' ? c.arguments : JSON.stringify(c.arguments ?? '')
+ for (const c of Array.isArray(o.tool_calls) ? o.tool_calls : []) {
+ if (!c || typeof c !== 'object' || Array.isArray(c)) continue
const part: Extract<ChatPart, { kind: 'tool' }> = {
kind: 'tool',
- name: c.name || 'tool',
- arg: String(a).slice(0, TOOL_ARG_MAX)
+ name: typeof c.name === 'string' && c.name ? c.name : 'tool',
+ arg: toolArg(c.arguments)
}
parts.push(part)
- if (c.id) toolById.set(c.id, part)
+ if (typeof c.id === 'string' && c.id) toolById.set(c.id, part)
}
if (parts.length) messages.push({ role: 'assistant', parts })
break
@@ -75,29 +161,39 @@ export function chatMessagesFromGrok(buf: string): ChatMessage[] {
case 'tool_result': {
// Attached to the call it answers, never rendered as its own bubble — same as claude's
// reader. An orphan result (no matching id) is dropped rather than shown speaker-less.
- const tool = o.tool_call_id ? toolById.get(o.tool_call_id) : undefined
+ const tool = typeof o.tool_call_id === 'string' ? toolById.get(o.tool_call_id) : undefined
if (!tool) break
- const s = textOf(o.content).slice(0, TOOL_RESULT_MAX)
+ const s = summarizeResult(textOf(o.content))
if (s) tool.result = s
break
}
case 'backend_tool_call': {
- const q = o.kind?.action?.query
+ const kind = o.kind && typeof o.kind === 'object' && !Array.isArray(o.kind) ? o.kind : undefined
+ const q = kind?.action?.query
messages.push({
role: 'assistant',
parts: [
{
kind: 'tool',
- name: o.kind?.tool_type || 'backend_tool',
- arg: typeof q === 'string' ? q.slice(0, TOOL_ARG_MAX) : ''
+ name: typeof kind?.tool_type === 'string' && kind.tool_type ? kind.tool_type : 'backend_tool',
+ arg: typeof q === 'string' ? q.slice(0, CHAT_TOOL_ARG_MAX) : ''
}
]
})
break
}
default:
+ // `reasoning`: known, deliberately hidden (see above).
break
}
}
- return messages
+ const out: GrokChatParse = { messages, skipped }
+ if (model !== undefined) out.model = model
+ if (effort !== undefined) out.effort = effort
+ return out
+}
+
+/** The messages alone — the legacy (unpaged) read and every caller that predates `parseGrokChat`. */
+export function chatMessagesFromGrok(buf: string): ChatMessage[] {
+ return parseGrokChat(buf).messages
}
diff --git a/src/core/remote-grok-chat.test.ts b/src/core/remote-grok-chat.test.ts
new file mode 100644
index 000000000..1a1269492
--- /dev/null
+++ b/src/core/remote-grok-chat.test.ts
@@ -0,0 +1,234 @@
+// The REMOTE (SSH-project) grok chat read: a generated `sh` line, executed here by a REAL /bin/sh
+// against a fake host tree, plus the tri-state factory the desktop injects into `readChatTranscript`.
+//
+// Generated shell is source no compiler checks — only running it proves the glob, the root choice,
+// the ambiguity refusal and the page framing agree with the parser (same discipline as
+// `remote-transcript-locate.test.ts` and `transcript-page.realsh.test.ts`).
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
+import { execFileSync, spawnSync } from 'child_process'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import {
+ createReadRemoteGrokChat,
+ parseRemoteGrokChat,
+ remoteGrokChatCommand
+} from './remote-grok-chat'
+
+const SID = '01a06126-b981-73f1-8b68-4547e4d7da84'
+const OTHER = '01a06126-b981-73f1-8b68-000000000000'
+const jl = (...rows: object[]): string => rows.map((r) => JSON.stringify(r)).join('\n') + '\n'
+
+let host: string
+beforeAll(() => {
+ host = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-grok-remote-'))
+})
+afterAll(() => fs.rmSync(host, { recursive: true, force: true }))
+
+/** A fresh fake $HOME for one case. */
+const freshHome = (name: string): string => {
+ const h = path.join(host, name)
+ fs.mkdirSync(h, { recursive: true })
+ return h
+}
+const writeSession = (grokHome: string, group: string, sid: string, body: string): void => {
+ const d = path.join(grokHome, 'sessions', group, sid)
+ fs.mkdirSync(d, { recursive: true })
+ fs.writeFileSync(path.join(d, 'chat_history.jsonl'), body)
+}
+/** Run the command the way ssh would: a shell with the host's env. */
+const runOn = (
+ cmd: string,
+ env: Record<string, string>,
+ shell = '/bin/sh'
+): { code: number; stdout: string } => {
+ const r = spawnSync(shell, ['-c', cmd], { encoding: 'utf8', env: { PATH: process.env.PATH ?? '', ...env } })
+ return { code: r.status ?? -1, stdout: r.stdout }
+}
+
+describe('remoteGrokChatCommand under a real /bin/sh', () => {
+ it('reads THIS session\'s chat_history.jsonl from $HOME/.grok, whatever cwd group it sits in', () => {
+ const home = freshHome('a')
+ writeSession(path.join(home, '.grok'), '%2Fsrv%2Fapp', SID, jl({ type: 'user', content: 'mine' }))
+ writeSession(path.join(home, '.grok'), '%2Fsrv%2Fapp', OTHER, jl({ type: 'user', content: 'SOMEONE ELSE' }))
+ const r = runOn(remoteGrokChatCommand(SID)!, { HOME: home })
+ expect(r.code).toBe(0)
+ const got = parseRemoteGrokChat(r.stdout)
+ expect(got).toEqual({ text: jl({ type: 'user', content: 'mine' }) })
+ })
+
+ it('honours an absolute $GROK_HOME, and ignores a relative one (the installer\'s rule)', () => {
+ 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' }) })
+ })
+
+ it('answers a clean miss with status 0 — "no transcript" is an ANSWER, not a failed ssh', () => {
+ const home = freshHome('c')
+ writeSession(path.join(home, '.grok'), 'g', OTHER, jl({ type: 'user', content: 'SOMEONE ELSE' }))
+ const r = runOn(remoteGrokChatCommand(SID)!, { HOME: home })
+ expect(r.code).toBe(0)
+ expect(parseRemoteGrokChat(r.stdout)).toEqual({ absent: true })
+ // No sessions tree at all is the same answer.
+ const bare = runOn(remoteGrokChatCommand(SID)!, { HOME: freshHome('c2') })
+ expect(bare.code).toBe(0)
+ expect(parseRemoteGrokChat(bare.stdout)).toEqual({ absent: true })
+ })
+
+ it('a session dir with no chat_history.jsonl yet is a clean miss, not a failure', () => {
+ const home = freshHome('d')
+ fs.mkdirSync(path.join(home, '.grok', 'sessions', 'g', SID), { recursive: true })
+ const r = runOn(remoteGrokChatCommand(SID)!, { HOME: home })
+ expect(r.code).toBe(0)
+ expect(parseRemoteGrokChat(r.stdout)).toEqual({ absent: true })
+ })
+
+ it('refuses to CHOOSE when the id matches two sessions (never a guess between two files)', () => {
+ const home = freshHome('e')
+ 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 r = runOn(remoteGrokChatCommand(SID)!, { HOME: home })
+ expect(r.code).not.toBe(0)
+ })
+
+ it('reads only the last maxBytes of a big history and drops the partial first line', () => {
+ const home = freshHome('f')
+ const rows = Array.from({ length: 400 }, (_, i) => ({ type: 'user', content: `satır ${i} — ğüşiöç ✓` }))
+ const body = jl(...rows)
+ writeSession(path.join(home, '.grok'), 'g', SID, body)
+ const cap = 4096
+ const r = runOn(remoteGrokChatCommand(SID, cap)!, { HOME: home })
+ expect(r.code).toBe(0)
+ const got = parseRemoteGrokChat(r.stdout, cap)
+ if (!('text' in got)) throw new Error('expected text')
+ // Every kept line is a whole record from the file's tail, and the tail's last line is present.
+ const kept = got.text.trimEnd().split('\n')
+ for (const l of kept) expect(body.includes(l + '\n')).toBe(true)
+ expect(kept.at(-1)).toBe(JSON.stringify(rows.at(-1)))
+ expect(Buffer.byteLength(got.text)).toBeLessThanOrEqual(cap)
+ expect(JSON.parse(kept[0])).toMatchObject({ type: 'user' })
+ })
+
+ it('keeps a line that begins exactly on the window edge (the lookbehind byte)', () => {
+ const home = freshHome('g')
+ const first = JSON.stringify({ type: 'user', content: 'x'.repeat(50) }) + '\n'
+ const second = JSON.stringify({ type: 'user', content: 'edge line' }) + '\n'
+ writeSession(path.join(home, '.grok'), 'g', SID, first + second)
+ const cap = Buffer.byteLength(second)
+ const got = parseRemoteGrokChat(runOn(remoteGrokChatCommand(SID, cap)!, { HOME: home }).stdout, cap)
+ expect(got).toEqual({ text: second })
+ })
+
+ it('works when the login shell is bash too', () => {
+ const home = freshHome('h')
+ writeSession(path.join(home, '.grok'), 'g', SID, jl({ type: 'user', content: 'bash' }))
+ const r = runOn(remoteGrokChatCommand(SID)!, { HOME: home }, '/bin/bash')
+ expect(parseRemoteGrokChat(r.stdout)).toEqual({ text: jl({ type: 'user', content: 'bash' }) })
+ })
+
+ it('emits no command for an id that could escape the sessions tree', () => {
+ for (const bad of ['', '../x', 'a/b', '*', "a'b", 'a b', 'x'.repeat(129), '$(id)']) {
+ expect(remoteGrokChatCommand(bad), bad).toBeNull()
+ }
+ })
+
+ it('a glob character in $GROK_HOME stays a path', () => {
+ 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 })
+ expect(parseRemoteGrokChat(r.stdout)).toEqual({ text: jl({ type: 'user', content: 'odd home' }) })
+ })
+})
+
+describe('parseRemoteGrokChat', () => {
+ it('throws on anything that is neither the absent marker nor a well-formed page', () => {
+ for (const bad of ['', 'garbage', 'NODETERM_ABSENTX\n', '0 5 5\n']) {
+ expect(() => parseRemoteGrokChat(bad), JSON.stringify(bad)).toThrow()
+ }
+ })
+})
+
+describe('createReadRemoteGrokChat — the tri-state', () => {
+ const target = { conn: 'c', controlPath: '/tmp/cp' }
+ const make = (o: {
+ remote?: boolean
+ t?: typeof target | undefined
+ run?: (t: typeof target, cmd: string) => Promise<{ code: number; stdout: string }>
+ }) => {
+ const run = vi.fn(o.run ?? (async () => ({ code: 0, stdout: 'NODETERM_ABSENT\n' })))
+ const read = createReadRemoteGrokChat({
+ isRemote: () => o.remote ?? false,
+ target: () => o.t,
+ run
+ })
+ return { read, run }
+ }
+
+ it('null = not a remote session (no node, or neither records nor a live master say remote)', async () => {
+ expect(await make({ remote: true, t: target }).read({ sessionId: SID })).toBeNull()
+ expect(await make({ remote: false, t: undefined }).read({ sessionId: SID, nodeId: 'n' })).toBeNull()
+ })
+
+ it('a live master makes the node remote whatever the records say', async () => {
+ const { read, run } = make({
+ remote: false,
+ t: target,
+ run: async () => ({ code: 0, stdout: 'NODETERM_ABSENT\n' })
+ })
+ expect(await read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false, absent: true })
+ expect(run).toHaveBeenCalledOnce()
+ })
+
+ it('remote with no master = could not ask (unreadable), and nothing ran', async () => {
+ const { read, run } = make({ remote: true, t: undefined })
+ expect(await read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false })
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ it('remote with no session id (or an unusable one) = a clean miss, and nothing ran', async () => {
+ for (const sessionId of [undefined, '../etc']) {
+ const { read, run } = make({ remote: true, t: target })
+ expect(await read({ sessionId, nodeId: 'n' })).toEqual({ ok: false, absent: true })
+ expect(run).not.toHaveBeenCalled()
+ }
+ })
+
+ it('a failed ssh, a non-zero status or a malformed reply is unreadable — never absent', async () => {
+ for (const run of [
+ async () => {
+ throw new Error('master down')
+ },
+ async () => ({ code: 255, stdout: '' }),
+ async () => ({ code: 3, stdout: '' }),
+ async () => ({ code: 0, stdout: 'half a reply' })
+ ]) {
+ expect(await make({ remote: true, t: target, run }).read({ sessionId: SID, nodeId: 'n' })).toEqual({ ok: false })
+ }
+ })
+
+ it('returns the host\'s text on success, and the command names only this session', async () => {
+ const home = freshHome('factory')
+ writeSession(path.join(home, '.grok'), 'g', SID, jl({ type: 'user', content: 'over ssh' }))
+ const { read, run } = make({
+ remote: true,
+ t: target,
+ run: async (_t, cmd) => runOn(cmd, { HOME: home })
+ })
+ 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)
+ })
+})
+
+// Guard against the test above silently passing because the command never touched the tree.
+describe('the fake host tree is really read', () => {
+ it('execFileSync /bin/sh is available', () => {
+ expect(execFileSync('/bin/sh', ['-c', 'printf ok'], { encoding: 'utf8' })).toBe('ok')
+ })
+})
diff --git a/src/core/remote-grok-chat.ts b/src/core/remote-grok-chat.ts
new file mode 100644
index 000000000..81e8f1588
--- /dev/null
+++ b/src/core/remote-grok-chat.ts
@@ -0,0 +1,121 @@
+// Reading a REMOTE (SSH-project) grok node's conversation ON ITS HOST.
+//
+// A remote grok session's `chat_history.jsonl` lives on the host, under the host's `$GROK_HOME`.
+// Nothing on this machine can stand in for it: the desktop's hook listener derives a session
+// directory from the LOCAL sessions root and the host's cwd (a path on the wrong machine), so every
+// local locator is wrong by construction for these nodes. This module is therefore the only way a
+// remote grok node's ⌘M panel — and the phone's Chat screen, which reads through the same deps — can
+// show anything, and its failures are TERMINAL in `readChatTranscript`: never a fall-through to this
+// machine's disk.
+//
+// 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 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.
+//
+// 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 { 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. */
+const AMBIGUOUS_EXIT = 3
+
+/**
+ * The host-side read for `sessionId`, or null when no transcript file can carry that id.
+ *
+ * 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 {
+ if (!isSafeGrokSessionId(sessionId)) return null
+ const id = posixQuote(sessionId)
+ const file = posixQuote(GROK_CHAT_HISTORY_FILE)
+ const script = [
+ 'case "${GROK_HOME:-}" in /*) r=$GROK_HOME ;; *) r=$HOME/.grok ;; esac',
+ '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`,
+ `if [ "$n" -eq 0 ]; then printf '%s\\n' ${ABSENT}; exit 0; fi`,
+ `if [ "$n" -gt 1 ]; then exit ${AMBIGUOUS_EXIT}; fi`,
+ 'cd "$d" || exit 1',
+ transcriptPageCommand(GROK_CHAT_HISTORY_FILE, null, maxBytes)
+ ].join('\n')
+ return `sh -c ${posixQuote(script)}`
+}
+
+/**
+ * The reply of `remoteGrokChatCommand` (status 0): `{absent}` for a clean miss, else the text of
+ * the tail window with its partial leading line dropped. STRICT: anything malformed throws, because
+ * the caller must tell "the host could not be read" from "an empty conversation".
+ */
+export function parseRemoteGrokChat(
+ stdout: string,
+ maxBytes: number = CHAT_PAGE_MAX_BYTES
+): { absent: true } | { text: string } {
+ if (stdout === `${ABSENT}\n`) return { absent: true }
+ const page = parseTranscriptPage(stdout, null, maxBytes)
+ let data = page.data
+ if (page.start > 0) {
+ // The window opened mid-file: everything through the first newline is the partial line (the
+ // lookbehind byte makes a line that begins exactly on the edge survive — its `\n` is byte 0).
+ const nl = data.indexOf(0x0a)
+ data = nl < 0 ? Buffer.alloc(0) : data.subarray(nl + 1)
+ }
+ 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 }
+
+/**
+ * The desktop's remote grok leg, injected into `readChatTranscript` as `readRemoteGrok`. `null` =
+ * not a remote session (take the local path); everything else is final.
+ *
+ * Remoteness is the shell's own records OR a live master for the node — the same two sources the
+ * claude leg uses (`locateRemoteTranscriptRef`) — and a remote node with no reachable master is
+ * `{ok:false}` (could not ask), never `null`, which would send it to this machine's disk.
+ */
+export function createReadRemoteGrokChat<T>(deps: {
+ isRemote(nodeId: string): boolean
+ /** The master to ask over (live pty, else the node's SSH project), or undefined when none. */
+ target(nodeId: string): T | undefined
+ run(target: T, cmd: string): Promise<{ code: number; stdout: string }>
+ /** Test seam; defaults to the local leg's cap. */
+ maxBytes?: number
+}): (q: { sessionId?: string; nodeId?: string }) => Promise<RemoteGrokChat | null> {
+ const maxBytes = deps.maxBytes ?? CHAT_PAGE_MAX_BYTES
+ return async (q) => {
+ if (!q.nodeId) return null
+ const 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 (!t) return { ok: false }
+ try {
+ const r = await deps.run(t, cmd)
+ 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 }
+ } catch {
+ return { ok: false }
+ }
+ }
+}
diff --git a/src/core/transcript-ipc.grok.test.ts b/src/core/transcript-ipc.grok.test.ts
new file mode 100644
index 000000000..8e86447af
--- /dev/null
+++ b/src/core/transcript-ipc.grok.test.ts
@@ -0,0 +1,159 @@
+// `readChatTranscript`'s grok leg: which machine answers, which file, and what rides a paged reply.
+//
+// The two failures these exist to make loud: a grok node answered with SOMEONE ELSE'S conversation
+// (claude's cwd-newest fallback, reached by any grok read that is not routed first — a custom agent
+// built on grok included), and a REMOTE grok node answered from THIS machine's disk.
+import { afterEach, beforeEach, describe, expect, it, 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 { readChatTranscript, type TranscriptIpcDeps } from './transcript-ipc'
+import { _resetGrokSessionDirsForTests, rememberGrokSessionDir } from './grok-session'
+import { setCustomAgentBaseResolver } from '../shared/agents/config'
+
+const GROK_SID = '01a06126-b981-73f1-8b68-4547e4d7da84'
+const CWD = '/srv/app'
+const jl = (...rows: object[]): string => rows.map((r) => JSON.stringify(r)).join('\n') + '\n'
+const grokAssistant = (content: string, model = 'grok-4.6-build', effort = 'xhigh') => ({
+ type: 'assistant',
+ content,
+ model_id: model,
+ model_fingerprint: 'fp',
+ reasoning_effort: effort
+})
+
+let home: string
+beforeEach(() => {
+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-grok-ipc-'))
+ vi.spyOn(os, 'homedir').mockReturnValue(home)
+ initPlatform(fakePlatform())
+ _resetGrokSessionDirsForTests()
+})
+afterEach(() => {
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ setCustomAgentBaseResolver(null)
+ _resetGrokSessionDirsForTests()
+ fs.rmSync(home, { recursive: true, force: true })
+})
+
+/** A claude transcript for the same cwd — what claude's cwd fallback would hand back. */
+const writeClaudeStranger = (): void => {
+ const dir = path.join(home, '.claude', 'projects', '-srv-app')
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(
+ path.join(dir, '11111111-2222-3333-4444-555555555555.jsonl'),
+ jl({ type: 'user', message: { content: 'SOMEONE ELSE PRIVATE' } })
+ )
+}
+const writeLocalGrok = (body: string): void => {
+ const dir = path.join(home, '.grok', 'sessions', '%2Fsrv%2Fapp', GROK_SID)
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(path.join(dir, 'chat_history.jsonl'), body)
+ rememberGrokSessionDir(GROK_SID, dir)
+}
+
+describe('readChatTranscript — grok, local', () => {
+ it('a paged read carries the newest assistant record\'s model and effort', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'hi' }, grokAssistant('hello', 'grok-5', 'high')))
+ const res = await readChatTranscript({ sessionId: GROK_SID, cwd: CWD, agentId: 'grok' }, { maxBytes: 65536 }, {})
+ expect(res).toMatchObject({ found: true, olderCursor: null, unmatchedResults: [], model: 'grok-5', effort: 'high' })
+ })
+
+ it('the legacy unpaged read stays exactly {messages, found}', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'hi' }, grokAssistant('hello')))
+ const res = await readChatTranscript({ sessionId: GROK_SID, cwd: CWD, agentId: 'grok' }, undefined, {})
+ expect(Object.keys(res).sort()).toEqual(['found', 'messages'])
+ })
+
+ it('a CUSTOM agent built on grok reads grok\'s file — never claude\'s cwd fallback', async () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:g1' ? 'grok' : undefined))
+ writeClaudeStranger()
+ writeLocalGrok(jl({ type: 'user', content: 'mine' }))
+ const res = await readChatTranscript({ sessionId: GROK_SID, cwd: CWD, agentId: 'custom:g1' }, { maxBytes: 65536 }, {})
+ expect(JSON.stringify(res.messages)).not.toContain('SOMEONE ELSE PRIVATE')
+ expect(JSON.stringify(res.messages)).toContain('mine')
+ })
+
+ it('a custom grok agent with no located session is not-found, not a stranger\'s transcript', async () => {
+ setCustomAgentBaseResolver((id) => (id === 'custom:g1' ? 'grok' : undefined))
+ writeClaudeStranger()
+ const res = await readChatTranscript({ sessionId: GROK_SID, cwd: CWD, agentId: 'custom:g1' }, { maxBytes: 65536 }, {})
+ expect(res).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })
+ })
+
+ 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)
+ const res = await readChatTranscript(
+ { sessionId: GROK_SID, cwd: CWD, nodeId: 'n1', agentId: 'grok' },
+ { maxBytes: 65536 },
+ { readRemoteGrok }
+ )
+ expect(readRemoteGrok).toHaveBeenCalledOnce()
+ expect(JSON.stringify(res.messages)).toContain('local grok')
+ })
+})
+
+describe('readChatTranscript — grok, remote (SSH project)', () => {
+ const remoteQ = { sessionId: GROK_SID, cwd: CWD, nodeId: 'n-remote', agentId: 'grok', remoteOnly: true }
+
+ it('answers from the HOST, parsed like the local file, with model and effort', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'THIS MACHINE' }))
+ const deps: TranscriptIpcDeps = {
+ readRemoteGrok: async () => ({ ok: true, text: jl({ type: 'user', content: 'the host' }, grokAssistant('ok', 'grok-h', 'low')) })
+ }
+ const res = await readChatTranscript(remoteQ, { maxBytes: 65536 }, deps)
+ expect(res.found).toBe(true)
+ expect(JSON.stringify(res.messages)).toContain('the host')
+ expect(JSON.stringify(res.messages)).not.toContain('THIS MACHINE')
+ expect(res).toMatchObject({ olderCursor: null, unmatchedResults: [], model: 'grok-h', effort: 'low' })
+ })
+
+ it('a host that could not be read is UNREADABLE — and this machine\'s file is never touched', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'THIS MACHINE' }))
+ const res = await readChatTranscript(remoteQ, { maxBytes: 65536 }, { readRemoteGrok: async () => ({ ok: false }) })
+ expect(res).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
+ })
+
+ it('a clean miss on the host is not-found WITHOUT unreadable', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'THIS MACHINE' }))
+ const res = await readChatTranscript(remoteQ, { maxBytes: 65536 }, { readRemoteGrok: async () => ({ ok: false, absent: true }) })
+ expect(res).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })
+ })
+
+ it('the remote verdict is final even without remoteOnly (a live master said remote)', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'THIS MACHINE' }))
+ const { remoteOnly: _r, ...q } = remoteQ
+ const res = await readChatTranscript(q, { maxBytes: 65536 }, { readRemoteGrok: async () => ({ ok: false }) })
+ expect(res.found).toBe(false)
+ expect(res.unreadable).toBe(true)
+ })
+
+ it('a known-remote node with no remote leg is unreadable, never a local read', async () => {
+ writeLocalGrok(jl({ type: 'user', content: 'THIS MACHINE' }))
+ for (const deps of [{}, { readRemoteGrok: async () => null }] as TranscriptIpcDeps[]) {
+ const res = await readChatTranscript(remoteQ, { maxBytes: 65536 }, deps)
+ expect(res).toMatchObject({ found: false, unreadable: true, messages: [] })
+ }
+ })
+
+ it('the legacy unpaged remote read keeps its two-key shape on success and failure', async () => {
+ const ok = await readChatTranscript(remoteQ, undefined, { readRemoteGrok: async () => ({ ok: true, text: jl({ type: 'user', content: 'h' }) }) })
+ expect(Object.keys(ok).sort()).toEqual(['found', 'messages'])
+ expect(ok.found).toBe(true)
+ const bad = await readChatTranscript(remoteQ, undefined, { readRemoteGrok: async () => ({ ok: false }) })
+ expect(bad).toEqual({ messages: [], found: false })
+ })
+
+ 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')
+ await readChatTranscript(remoteQ, { maxBytes: 65536 }, { readRemotePage, readRemote, readRemoteGrok: async () => ({ ok: false }) })
+ await readChatTranscript(remoteQ, undefined, { readRemotePage, readRemote, readRemoteGrok: async () => ({ ok: false }) })
+ expect(readRemotePage).not.toHaveBeenCalled()
+ expect(readRemote).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.ts
index a58b6a080..55163eaff 100644
--- a/src/core/transcript-ipc.ts
+++ b/src/core/transcript-ipc.ts
@@ -14,8 +14,10 @@ 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 { platform } from './platform'
-import { chatMessagesFromGrok } from './grok-chat'
+import { parseGrokChat } from './grok-chat'
+import type { RemoteGrokChat } from './remote-grok-chat'
import { locateGrok } from './handoff/locate'
+import { capabilityAgentId } from '../shared/agents/config'
import {
parseChatMessages,
parseChatWindow,
@@ -78,6 +80,14 @@ export interface TranscriptIpcDeps {
* (the Server Edition — it runs ON the host) = no node is remote, which is correct there.
*/
isRemoteNode?(nodeId: string): boolean
+ /**
+ * A REMOTE grok node's conversation, read ON the host (`createReadRemoteGrokChat`). `null` = not
+ * a remote session (take the local path); `{ok:false}` = it IS remote and the host could not be
+ * read; `{ok:false, absent:true}` = the host looked and has no such session. Grok's own leg —
+ * 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>
}
export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false; absent?: true }
@@ -192,6 +202,52 @@ export async function resolveTranscript(
return p
}
+/**
+ * A grok node's chat read. Grok does NOT page: its `chat_history.jsonl` is rewritten in place (a
+ * `.sync.tmp` + rename; `/compact`, `/rewind` and history repair replace lines), so a byte offset
+ * is no stable identity for a line. A paged request therefore gets the whole capped read with
+ * `olderCursor: null` ("nothing older to fetch"), no carried results and no keys — plus the newest
+ * assistant record's `model` / `effort`, as claude's paged reads carry theirs. The legacy unpaged
+ * read stays `{messages, found}` byte for byte.
+ *
+ * Remote first, and its answer is TERMINAL: a remote grok session lives on the host, and the local
+ * map can even hold a path derived for it on THIS machine (the hook listener builds it from the
+ * local sessions root and the host's cwd), so falling through would read the wrong machine.
+ */
+async function readGrokChat(
+ q: TranscriptQuery,
+ page: ChatTranscriptPage | null,
+ deps: TranscriptIpcDeps
+): Promise<ChatTranscriptResult> {
+ const paging = page ? { olderCursor: null, unmatchedResults: [] } : {}
+ const notFound = (): ChatTranscriptResult => ({ messages: [], found: false, ...paging })
+ const unreadable = (): ChatTranscriptResult => (page ? unreadablePage() : { messages: [], found: false })
+ const served = (buf: string): ChatTranscriptResult => {
+ const { messages, model, effort } = parseGrokChat(buf)
+ return {
+ messages,
+ found: true,
+ ...paging,
+ ...(page && model !== undefined ? { model } : {}),
+ ...(page && effort !== undefined ? { effort } : {})
+ }
+ }
+ if (deps.readRemoteGrok) {
+ const remote = await deps.readRemoteGrok(q)
+ if (remote !== null) {
+ if (!remote.ok) return remote.absent ? notFound() : unreadable()
+ return served(remote.text)
+ }
+ }
+ // A node its caller KNOWS is remote whose remote leg could not resolve it: a failed read, never
+ // this machine's disk.
+ if (q.remoteOnly) return unreadable()
+ const gp = q.sessionId ? await locateGrok(q.sessionId) : undefined
+ if (!gp) return notFound()
+ const buf = await readCappedTail(gp)
+ return buf === undefined ? notFound() : served(buf)
+}
+
/** What a chat read is asked for — the IPC channel's positional arguments, named. */
export interface ChatReadQuery {
sessionId?: string
@@ -200,7 +256,7 @@ export interface ChatReadQuery {
nodeId?: string
agentId?: string
/** See `TranscriptQuery.remoteOnly`. Honoured by every read: paged, legacy unpaged, and grok's
- * local-only reader. */
+ * reader (whose remote leg is `readRemoteGrok`). */
remoteOnly?: boolean
}
@@ -208,7 +264,8 @@ export interface ChatReadQuery {
* The `chat:read-transcript` read, callable without the IPC seam — the relay's `chat.page` verb
* serves the phone through it, so the phone and the ⌘M panel can never read a session differently.
* `rawPage` is untrusted (IPC / WS bridge / relay) and validated here; absent = the legacy unpaged
- * read, byte for byte. Paged claude results also carry `model` / `effort` (see `parseChatWindow`).
+ * read, byte for byte. Paged claude and grok results also carry `model` / `effort` (see
+ * `parseChatWindow` / `parseGrokChat`).
*/
export async function readChatTranscript(
q: ChatReadQuery,
@@ -222,21 +279,10 @@ export async function readChatTranscript(
// Routed by agent BEFORE anything claude-shaped runs. `resolveTranscript` below falls back to
// the newest claude transcript for the cwd when its sessionId leg misses, and a grok id always
// misses — so reaching that fallback with a grok node would answer with a stranger's
- // conversation. The remote leg is claude-only too (its reader tails claude's file), so a grok
- // node is served locally or not at all rather than being handed the wrong host's claude log.
- if (agentId === 'grok') {
- // Grok is read locally only — a remote grok node's history is on the host.
- if (remoteOnly) return page ? unreadablePage() : { messages: [], found: false }
- const gp = sessionId ? await locateGrok(sessionId) : undefined
- // Grok does NOT page: its history is small and its reader has no byte-offset keys, so a
- // paged request gets the whole (capped) read with `olderCursor: null` — "nothing older to
- // fetch" — and no carried results. Keys are absent; the panel falls back to its own.
- const paging = page ? { olderCursor: null, unmatchedResults: [] } : {}
- if (!gp) return { messages: [], found: false, ...paging }
- const buf = await readCappedTail(gp)
- return buf === undefined
- ? { messages: [], found: false, ...paging }
- : { messages: chatMessagesFromGrok(buf), found: true, ...paging }
+ // conversation. Resolved through the base harness, so a custom agent built on grok (which the
+ // panel and the phone admit via `canChat`) is routed here too instead of into that fallback.
+ if (agentId !== undefined && capabilityAgentId(agentId) === 'grok') {
+ return readGrokChat({ sessionId, cwd, accountId, nodeId, ...(remoteOnly ? { remoteOnly } : {}) }, page, deps)
}
if (page) return readChatPage({ sessionId, cwd, accountId, nodeId, ...(remoteOnly ? { remoteOnly } : {}) }, page, deps)
const remote = deps.readRemote ? await deps.readRemote({ sessionId, cwd, accountId, nodeId }) : null
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index dcdd50d22..d806ff26a 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -41,7 +41,7 @@ function textOf(content: unknown): string {
return ''
}
-function summarizeResult(content: unknown): string {
+export function summarizeResult(content: unknown): string {
return textOf(content).split('\n').slice(0, 3).join(' ').slice(0, 500)
}
@@ -262,7 +262,7 @@ const CHAT_META_MAX_CHARS = 100
const SYNTHETIC_MODEL = '<synthetic>'
/** A string field worth reporting as chat metadata, else undefined. */
-function metaString(v: unknown): string | undefined {
+export function metaString(v: unknown): string | undefined {
return typeof v === 'string' && v.length > 0 && v.length <= CHAT_META_MAX_CHARS ? v : undefined
}
/** A transcript line's ISO `timestamp` as epoch ms; undefined when absent or not a date string. */
diff --git a/src/main/grok-chat-remote-wiring.test.ts b/src/main/grok-chat-remote-wiring.test.ts
new file mode 100644
index 000000000..f634ac122
--- /dev/null
+++ b/src/main/grok-chat-remote-wiring.test.ts
@@ -0,0 +1,44 @@
+// The desktop shell must INJECT grok's remote chat leg — and no type can make it.
+//
+// `TranscriptIpcDeps.readRemoteGrok` is optional (the Server Edition has no SSH projects and passes
+// none), so a `transcriptIpcDeps` literal that forgets it is perfectly well-typed. The failure would
+// be silent in the one way that matters: every remote grok node's ⌘M panel AND the phone's Chat
+// screen (host-chat reads through the same deps object) would answer `unreadable` forever, with a
+// green suite behind it. Same class of hole `hook-verified-parity.test.ts` and
+// `codex-identity-record-wiring.test.ts` pin at source level; same remedy.
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'fs'
+import { join } from 'path'
+
+const source = readFileSync(join(__dirname, 'index.ts'), 'utf8')
+
+/** The `transcriptIpcDeps` object literal, from its declaration to the registration after it. */
+function depsLiteral(): string {
+ const start = source.indexOf('const transcriptIpcDeps: TranscriptIpcDeps = {')
+ expect(start, 'transcriptIpcDeps is not declared — this guard is looking at the wrong file').toBeGreaterThan(-1)
+ const end = source.indexOf('registerTranscriptIpc(transcriptIpcDeps)', start)
+ expect(end).toBeGreaterThan(start)
+ return source.slice(start, end)
+}
+
+describe('the desktop shell wires the remote grok chat read', () => {
+ it('injects readRemoteGrok into the deps both ⌘M and the phone read through', () => {
+ const deps = depsLiteral()
+ expect(deps).toMatch(/\n\s+readRemoteGrok:\s*createReadRemoteGrokChat\(/)
+ })
+
+ it('resolves remoteness from the shell\'s records and the project master, not a live pty alone', () => {
+ const deps = depsLiteral()
+ const at = deps.search(/\n\s+readRemoteGrok:/)
+ expect(at).toBeGreaterThan(-1)
+ const leg = deps.slice(at)
+ // An idle tab, or any node after a restart, has no attached pty: resolving through the pty
+ // alone would read such a node as "not remote" and send it to THIS machine's disk.
+ expect(leg).toMatch(/isRemote:\s*isRemoteTranscriptNode/)
+ expect(leg).toMatch(/target:\s*sshTargetForNode/)
+ })
+
+ it('the phone\'s chat.page reads through the SAME deps object', () => {
+ expect(source).toMatch(/readTranscript:\s*\(q, rawPage\) => readChatTranscript\(q, rawPage, transcriptIpcDeps\)/)
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index baa1cb1db..209e6f9d3 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -232,6 +232,7 @@ import {
remoteTranscriptRoots
} from '../core/remote-transcript-locate'
import { readChatTranscript, registerTranscriptIpc, resolveTranscript, type TranscriptIpcDeps } from '../core/transcript-ipc'
+import { createReadRemoteGrokChat } from '../core/remote-grok-chat'
import { createHostChat, mirrorChatSendRefusal } from './remote/host-chat'
import type { ChatSendOutcome, HostChatReply, RendererChatStatus } from '../shared/mobile-chat'
import {
@@ -2667,7 +2668,19 @@ app.whenReady().then(async () => {
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
+ isRemoteNode: isRemoteTranscriptNode,
+ // A remote GROK node's conversation, read on its host by session id (grok's file lives under the
+ // host's $GROK_HOME, and the hook-derived local map names a path on the wrong machine). Same
+ // remoteness and same master resolution as the claude legs above; the phone's `chat.page` reads
+ // through this object too.
+ readRemoteGrok: createReadRemoteGrokChat({
+ isRemote: isRemoteTranscriptNode,
+ target: sshTargetForNode,
+ run: (rt, cmd) =>
+ sshProjectManager
+ ? sshProjectManager.sshRun(childArgs(rt.conn, rt.controlPath, cmd))
+ : Promise.resolve({ code: 1, stdout: '' })
+ })
}
registerTranscriptIpc(transcriptIpcDeps)
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 2bc3a415b..9bba1d683 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -84,17 +84,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' | 'remoteUnsupported' | 'error'
-
-/**
- * An `unreadable` read of a GROK node can only be the remote case: core's grok leg is local-only
- * and answers a remote grok node (`remoteOnly`) with `unreadable` before touching anything, while
- * its local reader never sets the flag. So the agent alone names it — no renderer-side remoteness
- * guess, and no new field on the wire (the phone contract keeps `unreadable`). `=== 'grok'`
- * exactly, mirroring core's routing (`readChatTranscript` routes only the builtin id to grok's
- * reader). Retry cannot heal it, so it must not read as a transient failure.
- */
-const remoteGrokUnreadable = (agentId: string | undefined): boolean => agentId === 'grok'
+type LoadState = 'loading' | 'ok' | 'missing' | 'unsupported' | 'error'
const isUnsupported = (e: unknown): boolean =>
!!e && typeof e === 'object' && (e as { code?: string }).code === E_UNSUPPORTED
@@ -103,7 +93,7 @@ const isUnsupported = (e: unknown): boolean =>
* `missing` is a CLEAN miss — the (local or remote) host looked and there is no file: a transcript
* Claude has cleaned up (30 days by default), or a session that has not written one yet (the
* second heals the moment it speaks). A host that could not be ASKED is `error`, which Retry can
- * fix; `remoteUnsupported` is a remote node whose agent has no remote reader, which it never can. */
+ * fix — a remote grok node included, whose host is read by `core/remote-grok-chat.ts`. */
const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
loading: { title: 'Loading conversation…' },
ok: { title: 'No conversation yet.' },
@@ -115,7 +105,6 @@ 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.'
},
- remoteUnsupported: { title: "Reading a remote Grok session's transcript isn't supported yet." },
error: {
title: "Couldn't read the transcript.",
detail: "The agent's host may not be reachable — Retry once it is."
@@ -338,7 +327,7 @@ export function ChatPanel({
setThread(emptyThread(identity))
// 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 ? 'missing' : remoteGrokUnreadable(agentId) ? 'remoteUnsupported' : 'error')
+ setLoadState(res.unreadable ? 'error' : 'missing')
setHeldRead({ identity, pendingId: heldAtStart })
settleHeldReload(heldAtStart)
return
@@ -480,7 +469,7 @@ export function ChatPanel({
attemptLiveRef.current = () => {
if (!livePendingRef.current) return
// This surface cannot read transcripts at all (relay tab): every live read would be refused.
- if (loadStateRef.current === 'unsupported' || loadStateRef.current === 'remoteUnsupported') {
+ if (loadStateRef.current === 'unsupported') {
livePendingRef.current = false
return
}
@@ -768,7 +757,7 @@ export function ChatPanel({
{EMPTY_TEXT[loadState].detail && (
<div className="term-chat__empty-detail">{EMPTY_TEXT[loadState].detail}</div>
)}
- {loadState !== 'unsupported' && loadState !== 'remoteUnsupported' && loadState !== 'ok' && (
+ {loadState !== 'unsupported' && 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.tsx
index 34aad4a52..36bb3bfeb 100644
--- a/src/renderer/nodes/ChatPanel.ux.test.tsx
+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx
@@ -240,14 +240,16 @@ describe('ChatPanel empty states', () => {
expect(host.querySelector('.term-chat__retry')).not.toBeNull()
})
- it('an unreadable REMOTE grok read says it is unsupported, with no Retry (Retry can never fix it)', async () => {
+ it('an unreadable REMOTE grok read is a host failure like any other: it says so and offers Retry', async () => {
+ // Grok has a remote reader now (core/remote-grok-chat.ts): `unreadable` means the HOST did not
+ // answer, which a retry can heal — not "remote grok is unsupported", which it never could.
await render({ agentId: 'grok' })
await act(async () => {
pending[0].resolve({ messages: [], found: false, olderCursor: null, unmatchedResults: [], unreadable: true })
})
- expect(msgs().textContent).toContain("Reading a remote Grok session's transcript isn't supported yet.")
- expect(msgs().textContent).not.toContain("Couldn't read")
- expect(host.querySelector('.term-chat__retry')).toBeNull()
+ expect(msgs().textContent).toContain("Couldn't read the transcript.")
+ expect(msgs().textContent).not.toContain("isn't supported yet")
+ expect(host.querySelector('.term-chat__retry')).not.toBeNull()
})
it('a clean miss still says no transcript was found', async () => {
diff --git a/src/shared/chat-fixtures/grok/README.md b/src/shared/chat-fixtures/grok/README.md
new file mode 100644
index 000000000..8f9e92918
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/README.md
@@ -0,0 +1,111 @@
+# Grok chat golden fixtures
+
+The grok half of the chat parser port (`docs/mobile-chat-view.md`). The TypeScript implementation is
+the reference: `parseGrokChat` (`src/core/grok-chat.ts`) for the parse, `readChatTranscript`'s grok
+leg (`src/core/transcript-ipc.ts`) for the page the phone receives. `nodeterm-ios` keeps a
+byte-identical copy of this directory, and its Swift port must reproduce every `expected/*.json` from
+the same input.
+
+Every input is **synthetic**, built by `src/core/grok-chat-fixtures.test.ts` from record shapes
+measured on grok 1.0.13 (a real-derived session fixture plus the record vocabulary compiled into the
+shipped binary). None of them is a slice of a real session. Do not add one.
+
+## Regenerate
+
+```sh
+UPDATE_CHAT_FIXTURES=1 npx vitest run src/core/grok-chat-fixtures.test.ts
+```
+
+Without the variable, the test requires every file to equal what the code produces, and requires
+`inputs/` and `expected/` to hold exactly the generated set. Regenerating is refused when `CI` is set.
+After regenerating, refresh the iOS copy in the same change.
+
+## Layout
+
+| path | what it is |
+|---|---|
+| `inputs/<name>.jsonl` | A synthetic `chat_history.jsonl`. |
+| `expected/<name>.page.json` | `{ request, parse, page }`: the phone's request (`{maxBytes: 262144}`), `parseGrokChat(input)` verbatim, and the page `readChatTranscript` serves for that request. |
+
+Every expected file is `JSON.stringify(value, null, 2) + "\n"`, keys in the order the TS code builds
+them. Optional keys (`model`, `effort`, a tool part's `result`) are **absent** when unset, never
+`null`. The test also checks that the LOCAL leg (a real session directory) and the REMOTE leg (the
+host's text through `readRemoteGrok`) serve the identical page, and that `page.messages` equals
+`parse.messages`.
+
+## Paging: grok does not page
+
+`chat_history.jsonl` is NOT an append-only log. grok 1.0.13 persists it through
+`chat_history.jsonl.sync.tmp` + rename, and `/compact`, `/rewind` and its own history repair
+(duplicate and dangling tool results) rewrite the history in place. A byte offset is therefore not a
+stable 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.
+- 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
+ for an older page. There is no "beginning of conversation" marker, because a capped read cannot
+ know it reached the start.
+- `model` / `effort` ride a paged reply exactly as they do for claude. The legacy unpaged read stays
+ `{messages, found}`.
+
+## Record rules (the Swift port must replicate these exactly)
+
+Lines are split on `\n`. A line that is blank after JS `trim` is ignored. Each remaining line is
+`JSON.parse`d (after trim):
+
+1. **Skipped and counted** (`parse.skipped`): a line that does not parse, parses to a non-object
+ (`42`, `null`, a string), parses to an array, or is an object whose `type` is not one of `system`,
+ `user`, `assistant`, `tool_result`, `backend_tool_call`, `reasoning`. The count is not on the wire.
+2. **Text of a `content` field** (`textOf`): a string is itself; an array maps each item to itself if
+ it is a string, else to its `text` field (else `""`), drops empty strings, and joins with `\n`;
+ anything else is `""`.
+3. `system` → if its text is non-empty, an assistant message with one text part `"[system] " + text`.
+4. `user` → if its text is empty, nothing. If `synthetic_reason` is a string whose JS-`trim` is
+ non-empty, an **assistant** message `"[" + trimmedReason + "] " + text` (harness-injected text is
+ never shown as something the human typed). Otherwise a user message with the text.
+5. `assistant`:
+ - **model / effort**: every assistant record REPLACES both values — `model_id` and
+ `reasoning_effort`, each kept only when it is a non-empty string of at most 100 UTF-16 units
+ (JS `.length`, Swift `utf16.count`). A record that does not state one clears it: the newest
+ assistant record answers both fields, and nothing is carried forward from an older record.
+ - parts: a text part with `textOf(content)` when non-empty, then one tool part per entry of
+ `tool_calls` (only when `tool_calls` is an array; an entry that is not a JSON object — `null`, a
+ number, a string, an array — is ignored):
+ `name` = the entry's `name` when it is a non-empty string, else `"tool"`; `arg` = see rule 8.
+ - An entry with a non-empty string `id` is remembered for rule 6. A message is pushed only when it
+ has at least one part.
+6. `tool_result` → when `tool_call_id` is a string naming a remembered call, that call's tool part
+ gets `result` = `textOf(content)` split on `\n`, the first three pieces joined with a space, then
+ its first 500 UTF-16 units — set only when non-empty. A later result for the same id overwrites.
+ An orphan result is dropped (never its own message).
+7. `backend_tool_call` → an assistant message with one tool part (a `kind` that is not a JSON object
+ counts as absent): `name` = `kind.tool_type` when it is a non-empty string, else `"backend_tool"`;
+ `arg` = `kind.action.query` when it is a string
+ (first 200 UTF-16 units), else `""`. No `result`.
+8. **A tool call's `arg`**: when `arguments` is a string, it is `JSON.parse`d (a failure leaves no
+ object); when it is an object it is used as is. If that yields a non-array object, the first of
+ these keys whose value is a non-empty string wins, in this order: `command`, `target_file`,
+ `file_path`, `target_directory`, `path`, `pattern`, `query`, `url`, `description`, `prompt` (claude's
+ `toolArg` order with grok's measured `target_file` / `target_directory` added). Otherwise the arg is
+ the raw text: the `arguments` string itself, `JSON.stringify` of an object/array, or `""` for any
+ other value. Either way, the first 200 UTF-16 units (`String.prototype.slice(0, 200)`).
+9. `reasoning` → nothing (its `encrypted_content` is unreadable and its `summary` is omitted by
+ product decision), and it is NOT counted as skipped.
+
+No new role, part kind or field: a v1 decoder reads all of this as ordinary text and tool parts.
+
+## What each fixture pins
+
+| fixture | pins |
+|---|---|
+| `plain-turns` | The `system` prompt note, typed prompts with `prompt_index`, markdown, two text items joined with `\n`, a string-content user record, non-ASCII text. |
+| `tools` | Salient args (`target_file`, `target_directory`, `command`, `file_path`, `path` over `pattern`), the raw-text fallback capped at 200, a non-JSON `arguments` string, results summarised to three lines / 500 units, an empty result (no `result` key), an orphan result dropped. |
+| `synthetic-notes` | Every injected reason becomes an assistant-side `[reason]` note (`project_instructions`, `system_reminder`, `task_completed`, `subagent_completed`, `permission_rejected`, `compaction_meta`); a blank reason reads as the user. |
+| `backend-and-reasoning` | `reasoning` records (with and without a summary) render nothing; a `web_search` backend call with a query, and one without. |
+| `model-effort` | The newest assistant record's model and effort win. |
+| `model-effort-no-carry` | The newest record states no effort: `effort` is absent, never an older record's value. |
+| `model-effort-cap` | A model of 50 × U+1F9EA (100 UTF-16 units) is kept; an effort of 101 units is absent. |
+| `skipped-lines` | A truncated line, `42`, `null`, an array and an unknown `type` are skipped and counted (5); a blank line is ignored without counting. |
+| `reasoning-only` | A history with nothing renderable is still FOUND, with no messages. |
diff --git a/src/shared/chat-fixtures/grok/expected/backend-and-reasoning.page.json b/src/shared/chat-fixtures/grok/expected/backend-and-reasoning.page.json
new file mode 100644
index 000000000..1ef254b0b
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/backend-and-reasoning.page.json
@@ -0,0 +1,97 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "search the web"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "web_search",
+ "arg": "nodeterm canvas terminal manager"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "web_search",
+ "arg": ""
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Found two sources."
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "search the web"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "web_search",
+ "arg": "nodeterm canvas terminal manager"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "tool",
+ "name": "web_search",
+ "arg": ""
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Found two sources."
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/model-effort-cap.page.json b/src/shared/chat-fixtures/grok/expected/model-effort-cap.page.json
new file mode 100644
index 000000000..cc37548c4
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/model-effort-cap.page.json
@@ -0,0 +1,55 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "capped"
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "capped"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/model-effort-no-carry.page.json b/src/shared/chat-fixtures/grok/expected/model-effort-no-carry.page.json
new file mode 100644
index 000000000..3d831e018
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/model-effort-no-carry.page.json
@@ -0,0 +1,73 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "older"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "newest states no effort"
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-code-fast"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "older"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "newest states no effort"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-code-fast"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/model-effort.page.json b/src/shared/chat-fixtures/grok/expected/model-effort.page.json
new file mode 100644
index 000000000..6b8283d1e
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/model-effort.page.json
@@ -0,0 +1,93 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "again"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "second"
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-4.6",
+ "effort": "high"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "go"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "again"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "second"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-4.6",
+ "effort": "high"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/plain-turns.page.json b/src/shared/chat-fixtures/grok/expected/plain-turns.page.json
new file mode 100644
index 000000000..470340cba
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/plain-turns.page.json
@@ -0,0 +1,147 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[system] You are a synthetic coding agent. Follow the rules.\n\n# Rules\n- be brief"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Explain the **plan**:\n\n1. read\n2. write"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Plan\n\n- Read `a.ts`\n- Then write\n\n```ts\nconst x = 1\n```\n\n> quoted"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first half\nsecond half"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "a string-content prompt"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Türkçe karakterler: ğüşiöç — 中文 — emoji 🧪"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Tamam ✓ 🧪"
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[system] You are a synthetic coding agent. Follow the rules.\n\n# Rules\n- be brief"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Explain the **plan**:\n\n1. read\n2. write"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "## Plan\n\n- Read `a.ts`\n- Then write\n\n```ts\nconst x = 1\n```\n\n> quoted"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "first half\nsecond half"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "a string-content prompt"
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Türkçe karakterler: ğüşiöç — 中文 — emoji 🧪"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Tamam ✓ 🧪"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/reasoning-only.page.json b/src/shared/chat-fixtures/grok/expected/reasoning-only.page.json
new file mode 100644
index 000000000..0ec790489
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/reasoning-only.page.json
@@ -0,0 +1,15 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [],
+ "skipped": 0
+ },
+ "page": {
+ "messages": [],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": []
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/skipped-lines.page.json b/src/shared/chat-fixtures/grok/expected/skipped-lines.page.json
new file mode 100644
index 000000000..6eff82915
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/skipped-lines.page.json
@@ -0,0 +1,35 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "the one line that survives"
+ }
+ ]
+ }
+ ],
+ "skipped": 5
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "the one line that survives"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": []
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/synthetic-notes.page.json b/src/shared/chat-fixtures/grok/expected/synthetic-notes.page.json
new file mode 100644
index 000000000..32ee5c27e
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/synthetic-notes.page.json
@@ -0,0 +1,183 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[project_instructions] # AGENTS.md\nUse tabs."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[system_reminder] Remember to update the todo list."
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "real prompt"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "working on it"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[task_completed] Background task t-1 finished."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[subagent_completed] Subagent explore-1 returned."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[permission_rejected] The user rejected run_terminal_cmd."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[compaction_meta] Summary of the conversation so far: the user asked for a plan."
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "blank reason reads as the user"
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[project_instructions] # AGENTS.md\nUse tabs."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[system_reminder] Remember to update the todo list."
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "real prompt"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "working on it"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[task_completed] Background task t-1 finished."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[subagent_completed] Subagent explore-1 returned."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[permission_rejected] The user rejected run_terminal_cmd."
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "[compaction_meta] Summary of the conversation so far: the user asked for a plan."
+ }
+ ]
+ },
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "blank reason reads as the user"
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/expected/tools.page.json b/src/shared/chat-fixtures/grok/expected/tools.page.json
new file mode 100644
index 000000000..7ad26140b
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/expected/tools.page.json
@@ -0,0 +1,151 @@
+{
+ "request": {
+ "maxBytes": 262144
+ },
+ "parse": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "look around"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Reading the project."
+ },
+ {
+ "kind": "tool",
+ "name": "read_file",
+ "arg": "/srv/app/src/a.ts",
+ "result": "line one line two line three"
+ },
+ {
+ "kind": "tool",
+ "name": "list_dir",
+ "arg": "/srv/app/src",
+ "result": "a.ts b.ts"
+ },
+ {
+ "kind": "tool",
+ "name": "run_terminal_cmd",
+ "arg": "npm test -- --run",
+ "result": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ },
+ {
+ "kind": "tool",
+ "name": "search_replace",
+ "arg": "/srv/app/b.ts"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "/srv/app"
+ },
+ {
+ "kind": "tool",
+ "name": "future_tool",
+ "arg": "{\"knob\":\"kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
+ },
+ {
+ "kind": "tool",
+ "name": "odd_tool",
+ "arg": "not json at all"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Done: tests pass."
+ }
+ ]
+ }
+ ],
+ "skipped": 0,
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ },
+ "page": {
+ "messages": [
+ {
+ "role": "user",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "look around"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Reading the project."
+ },
+ {
+ "kind": "tool",
+ "name": "read_file",
+ "arg": "/srv/app/src/a.ts",
+ "result": "line one line two line three"
+ },
+ {
+ "kind": "tool",
+ "name": "list_dir",
+ "arg": "/srv/app/src",
+ "result": "a.ts b.ts"
+ },
+ {
+ "kind": "tool",
+ "name": "run_terminal_cmd",
+ "arg": "npm test -- --run",
+ "result": "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"
+ },
+ {
+ "kind": "tool",
+ "name": "search_replace",
+ "arg": "/srv/app/b.ts"
+ },
+ {
+ "kind": "tool",
+ "name": "grep",
+ "arg": "/srv/app"
+ },
+ {
+ "kind": "tool",
+ "name": "future_tool",
+ "arg": "{\"knob\":\"kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"
+ },
+ {
+ "kind": "tool",
+ "name": "odd_tool",
+ "arg": "not json at all"
+ }
+ ]
+ },
+ {
+ "role": "assistant",
+ "parts": [
+ {
+ "kind": "text",
+ "text": "Done: tests pass."
+ }
+ ]
+ }
+ ],
+ "found": true,
+ "olderCursor": null,
+ "unmatchedResults": [],
+ "model": "grok-4.6-build",
+ "effort": "xhigh"
+ }
+}
diff --git a/src/shared/chat-fixtures/grok/inputs/backend-and-reasoning.jsonl b/src/shared/chat-fixtures/grok/inputs/backend-and-reasoning.jsonl
new file mode 100644
index 000000000..db336bcb8
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/backend-and-reasoning.jsonl
@@ -0,0 +1,6 @@
+{"type":"user","content":[{"type":"text","text":"search the web"}],"prompt_index":0}
+{"type":"reasoning","id":"rs_00000001","summary":[{"type":"summary_text","text":"Considering the query."}],"encrypted_content":"gAAAAABsyntheticSyntheticSynthetic==","status":"completed"}
+{"type":"reasoning","id":"rs_00000002","summary":[],"encrypted_content":"gAAAAABsyntheticSyntheticSynthetic==","status":"completed"}
+{"type":"backend_tool_call","kind":{"tool_type":"web_search","action":{"type":"search","query":"nodeterm canvas terminal manager","sources":[{"type":"url","url":"https://example.com/a"},{"type":"url","url":"https://example.com/b"}]}},"id":"ws_00000001","status":"completed"}
+{"type":"backend_tool_call","kind":{"tool_type":"web_search","action":{"type":"search","sources":[{"type":"url","url":"https://example.com/a"},{"type":"url","url":"https://example.com/b"}]}},"id":"ws_00000002","status":"completed"}
+{"type":"assistant","content":"Found two sources.","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
diff --git a/src/shared/chat-fixtures/grok/inputs/model-effort-cap.jsonl b/src/shared/chat-fixtures/grok/inputs/model-effort-cap.jsonl
new file mode 100644
index 000000000..3d51dac9f
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/model-effort-cap.jsonl
@@ -0,0 +1,2 @@
+{"type":"user","content":[{"type":"text","text":"go"}],"prompt_index":0}
+{"type":"assistant","content":"capped","model_id":"🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪🧪","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"}
diff --git a/src/shared/chat-fixtures/grok/inputs/model-effort-no-carry.jsonl b/src/shared/chat-fixtures/grok/inputs/model-effort-no-carry.jsonl
new file mode 100644
index 000000000..2a6e1a4aa
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/model-effort-no-carry.jsonl
@@ -0,0 +1,3 @@
+{"type":"user","content":[{"type":"text","text":"go"}],"prompt_index":0}
+{"type":"assistant","content":"older","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
+{"type":"assistant","content":"newest states no effort","model_id":"grok-code-fast","model_fingerprint":"fp_0000000000synthetic"}
diff --git a/src/shared/chat-fixtures/grok/inputs/model-effort.jsonl b/src/shared/chat-fixtures/grok/inputs/model-effort.jsonl
new file mode 100644
index 000000000..b4dbe316a
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/model-effort.jsonl
@@ -0,0 +1,4 @@
+{"type":"user","content":[{"type":"text","text":"go"}],"prompt_index":0}
+{"type":"assistant","content":"first","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"medium"}
+{"type":"user","content":[{"type":"text","text":"again"}],"prompt_index":1}
+{"type":"assistant","content":"second","model_id":"grok-4.6","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"high"}
diff --git a/src/shared/chat-fixtures/grok/inputs/plain-turns.jsonl b/src/shared/chat-fixtures/grok/inputs/plain-turns.jsonl
new file mode 100644
index 000000000..67f29ef63
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/plain-turns.jsonl
@@ -0,0 +1,7 @@
+{"type":"system","content":"You are a synthetic coding agent. Follow the rules.\n\n# Rules\n- be brief"}
+{"type":"user","content":[{"type":"text","text":"Explain the **plan**:\n\n1. read\n2. write"}],"prompt_index":0}
+{"type":"assistant","content":"## Plan\n\n- Read `a.ts`\n- Then write\n\n```ts\nconst x = 1\n```\n\n> quoted","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
+{"type":"user","content":[{"type":"text","text":"first half"},{"type":"text","text":"second half"}],"prompt_index":1}
+{"type":"user","content":"a string-content prompt","prompt_index":2}
+{"type":"user","content":[{"type":"text","text":"Türkçe karakterler: ğüşiöç — 中文 — emoji 🧪"}],"prompt_index":3}
+{"type":"assistant","content":"Tamam ✓ 🧪","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
diff --git a/src/shared/chat-fixtures/grok/inputs/reasoning-only.jsonl b/src/shared/chat-fixtures/grok/inputs/reasoning-only.jsonl
new file mode 100644
index 000000000..1fd643424
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/reasoning-only.jsonl
@@ -0,0 +1,2 @@
+{"type":"reasoning","id":"rs_00000001","summary":[{"type":"summary_text","text":"thinking"}],"encrypted_content":"gAAAAABsyntheticSyntheticSynthetic==","status":"completed"}
+{"type":"reasoning","id":"rs_00000002","summary":[],"encrypted_content":"gAAAAABsyntheticSyntheticSynthetic==","status":"completed"}
diff --git a/src/shared/chat-fixtures/grok/inputs/skipped-lines.jsonl b/src/shared/chat-fixtures/grok/inputs/skipped-lines.jsonl
new file mode 100644
index 000000000..681df1ccd
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/skipped-lines.jsonl
@@ -0,0 +1,7 @@
+{"type":"user","content":[{"type":"text","text":"truncat
+42
+null
+[1,2,3]
+
+{"type":"some_future_record","content":"never rendered"}
+{"type":"user","content":[{"type":"text","text":"the one line that survives"}],"prompt_index":0}
diff --git a/src/shared/chat-fixtures/grok/inputs/synthetic-notes.jsonl b/src/shared/chat-fixtures/grok/inputs/synthetic-notes.jsonl
new file mode 100644
index 000000000..255f7b9fb
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/synthetic-notes.jsonl
@@ -0,0 +1,9 @@
+{"type":"user","content":[{"type":"text","text":"# AGENTS.md\nUse tabs."}],"synthetic_reason":"project_instructions"}
+{"type":"user","content":[{"type":"text","text":"Remember to update the todo list."}],"synthetic_reason":"system_reminder"}
+{"type":"user","content":[{"type":"text","text":"real prompt"}],"prompt_index":0}
+{"type":"assistant","content":"working on it","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
+{"type":"user","content":[{"type":"text","text":"Background task t-1 finished."}],"synthetic_reason":"task_completed","prompt_index":1}
+{"type":"user","content":[{"type":"text","text":"Subagent explore-1 returned."}],"synthetic_reason":"subagent_completed"}
+{"type":"user","content":[{"type":"text","text":"The user rejected run_terminal_cmd."}],"synthetic_reason":"permission_rejected"}
+{"type":"user","content":[{"type":"text","text":"Summary of the conversation so far: the user asked for a plan."}],"synthetic_reason":"compaction_meta"}
+{"type":"user","content":[{"type":"text","text":"blank reason reads as the user"}],"synthetic_reason":" "}
diff --git a/src/shared/chat-fixtures/grok/inputs/tools.jsonl b/src/shared/chat-fixtures/grok/inputs/tools.jsonl
new file mode 100644
index 000000000..548de0e1c
--- /dev/null
+++ b/src/shared/chat-fixtures/grok/inputs/tools.jsonl
@@ -0,0 +1,8 @@
+{"type":"user","content":[{"type":"text","text":"look around"}],"prompt_index":0}
+{"type":"assistant","content":"Reading the project.","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh","tool_calls":[{"id":"call-00000001","name":"read_file","arguments":"{\"target_file\":\"/srv/app/src/a.ts\"}"},{"id":"call-00000002","name":"list_dir","arguments":"{\"target_directory\":\"/srv/app/src\"}"},{"id":"call-00000003","name":"run_terminal_cmd","arguments":"{\"command\":\"npm test -- --run\",\"is_background\":false}"},{"id":"call-00000004","name":"search_replace","arguments":"{\"file_path\":\"/srv/app/b.ts\",\"old_string\":\"x\",\"new_string\":\"y\"}"},{"id":"call-00000005","name":"grep","arguments":"{\"pattern\":\"TODO\",\"path\":\"/srv/app\"}"},{"id":"call-00000006","name":"future_tool","arguments":"{\"knob\":\"kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk\"}"},{"id":"call-00000007","name":"odd_tool","arguments":"not json at all"}]}
+{"type":"tool_result","tool_call_id":"call-00000001","content":"line one\nline two\nline three\nline four"}
+{"type":"tool_result","tool_call_id":"call-00000002","content":"a.ts\nb.ts"}
+{"type":"tool_result","tool_call_id":"call-00000003","content":"rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr"}
+{"type":"tool_result","tool_call_id":"call-00000004","content":""}
+{"type":"tool_result","tool_call_id":"call-99999999","content":"orphan"}
+{"type":"assistant","content":"Done: tests pass.","model_id":"grok-4.6-build","model_fingerprint":"fp_0000000000synthetic","reasoning_effort":"xhigh"}
diff --git a/src/shared/types.ts b/src/shared/types.ts
index fcd8467f4..c02e31939 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2882,11 +2882,13 @@ export interface ChatTranscriptResult {
*/
unmatchedResults?: ChatCarriedToolResult[]
/**
- * PAGED claude reads only: the newest assistant record's `message.model` in the returned window
- * (`<synthetic>` error lines skipped). Absent when the window has none, and on the legacy read.
+ * PAGED reads only: the newest assistant record's model in the returned window — claude's
+ * `message.model` (`<synthetic>` error lines skipped), grok's `model_id`. Absent when the window
+ * has none, and on the legacy read.
*/
model?: string
- /** PAGED claude reads only: the newest assistant record's top-level `effort` in the window. */
+ /** PAGED reads only: that same record's effort — claude's top-level `effort`, grok's
+ * `reasoning_effort`. Never carried forward from an older record. */
effort?: string
/** PAGED reads only, with `found: false`: the transcript could not be READ (a remote host that did
* not answer, a growth re-read that failed, a remote node with no reachable master) — as opposed