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(grok): cross-agent transfer and the Cmd+M chat panel

Xavi Guardia8693f125b567
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index 6b6224a6d..7a9ee558f 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -44,8 +44,8 @@ is the cost of adding the next agent to the same list.
| `CONTEXT_LINK_CAPABLE` | **joined** | Two pieces, both pinned by fixtures cut from real sessions rather than written from the docs: `linesFromGrok` (`core/context-link-render.ts`) renders grok's log, and `locateGrok` (`core/handoff/locate.ts`) finds it. The file is **`chat_history.jsonl`, not the `updates.jsonl`** this row used to name and grok's own hook payloads advertise — routing through the advertised path fails **silently**, handing the reader an empty transcript with nothing logged, which is why the locator pins it. The directory comes from the hook-fed `sessionId → dir` map, never from a scan. The path jail was widened to `$GROK_HOME/sessions` — that subdirectory, not `$GROK_HOME`, because `auth.json` lives in the same tree. Grok is no longer outside this list; the list is now `claude, codex, gemini, opencode, grok`, and the one builtin still outside it is **copilot**. |
| `SUBAGENT_CAPABLE` | **not joined** | Needs the `spawn_subagent` `PreToolUse`/`PostToolUse` payload fields, including whatever marks a **background** launch. Task 11 stops at its capture step. |
| `BRANCH_CAPABLE` | not joined | Branch sends claude's `/branch` and resumes by claude's session id; grok has no counterpart. |
-| `CHAT_CAPABLE` | not joined | The ⌘M `ChatPanel` renders claude's transcript `.jsonl`. **The blocker named here is gone** — the parser exists (`linesFromGrok`, and the log is `chat_history.jsonl`, not `updates.jsonl`) — so what is left is a decision, not a missing piece: the panel has its own shape requirements beyond a list of lines, and nobody has measured them against grok's log. Do not read the omission as "impossible". |
-| `TRANSFER_SOURCE_CAPABLE` | not joined | Cross-agent transfer reads the source's native transcript. **Same correction as the row above:** the parser is no longer missing, so this is now an unmade decision rather than a blocked one. Grok is a valid transfer **target** (it is an agent node like any other); it just is not yet wired as the source. |
+| `CHAT_CAPABLE` | **joined**, and the list was SPLIT to do it safely | `chatMessagesFromGrok` (`core/grok-chat.ts`) builds the panel's bubbles from the same `grokParse` the context-link reader uses, so the two views of one file cannot drift. The channel is now routed by agent (`chat:read-transcript` takes an `agentId`), and that routing is the safety property, not a refinement: claude's `resolveTranscript` falls back to **the newest claude transcript for the node's cwd** whenever its sessionId leg misses, which a grok id always does — so an unrouted grok node is answered with a stranger's conversation rather than with nothing. **The list itself had to be split.** `CHAT_CAPABLE` carried two facts that coincided only while claude was its sole member: "we can render this agent's conversation" and "claude's resolver can locate and parse this agent's file". Grok is the first agent for which they differ, so the second now lives in `CLAUDE_TRANSCRIPT_READABLE` (claude only), which is what `renderer/lib/transcriptGates.ts` reads. Merging them back is a cross-session read of someone else's transcript, and it fails OPEN — it shows data. `config.capabilities.test.ts` pins the pair. |
+| `TRANSFER_SOURCE_CAPABLE` | **joined** | `renderGrokTranscript` (`main/handoff/render-grok.ts`) sits beside the claude/codex/gemini renderers and, like them, is registered in `RENDERERS` and `LOCATORS`. It renders through `linesFromGrok` rather than re-reading grok's line shapes, and it gives harness-injected text its own heading — `## Injected (system_reminder)`, never `## User`. That distinction matters more here than anywhere else in the codebase: the receiving agent reads a `## User` heading as an instruction from the person, so mislabelling a skill reminder would hand it someone's tooling as a command. The **destination** list is separate (`transferTargets` derives it from `BUILTIN_AGENT_IDS`) and is untouched: grok was already a valid target, and unifying the two would light a menu over an operation that does nothing. |
| `RECURRING_CAPABLE` | not joined | `/loop`, `/schedule`, `/cron` are detected from claude's `Skill` / `CronCreate` / `ScheduleWakeup` tool names; grok's tool vocabulary for these is unknown. |
**Grok billing usage ≠ the grok context meter.** These are two different features and the plan once
@@ -329,6 +329,8 @@ 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 |
+| 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 | **not implemented for grok** (§1) | the meter itself IS wired server-side (both shells create the per-agent tails — it is codex and gemini that use them, `docs/gemini-agent.md` §4); grok simply has no numbers to feed it on either surface | idem |
| Managed accounts | **deliberately N/A** — accounts are a claude config-dir mechanism. `createAgentNode` never stamps an `accountId` onto a non-claude node, and `CLAUDE_CONFIG_DIR` is irrelevant to `~/.grok/hooks`. A grok node in a managed-account project must still report status (checklist 7) | idem | idem |
| Brand logo | the **official** xAI mark, INLINED in `agentIcons.tsx` as `GrokMark` rather than shipped as an asset — it is a single monochrome path, so `fill="currentColor"` inherits the label colour and is correct in both themes. The other four marks are multi-colour and stay `<img src>` assets, where `currentColor` cannot inherit | same component, for free | the phone draws its own icons — **follow-up owed** |
diff --git a/src/core/context-link-render.ts b/src/core/context-link-render.ts
index 0e137d15c..57d7a0b45 100644
--- a/src/core/context-link-render.ts
+++ b/src/core/context-link-render.ts
@@ -224,7 +224,7 @@ export function linesFromOpencodeExport(raw: string): string[] | null {
* A malformed line is skipped but NOT in silence: `linesFromGrok.skipped(buf)` counts them, so a
* caller can say "3 lines were unreadable" instead of quietly rendering a shorter transcript.
*/
-interface GrokChatLine {
+export interface GrokChatLine {
type?: string
content?: unknown
tool_calls?: { id?: string; name?: string; arguments?: unknown }[]
@@ -233,7 +233,9 @@ interface GrokChatLine {
kind?: { tool_type?: string; action?: { type?: string; query?: string } }
}
-function grokParse(buf: string): { lines: GrokChatLine[]; skipped: number } {
+/** Exported so the ⌘M chat reader can build structured messages from the SAME shape knowledge
+ * instead of re-deriving grok's line vocabulary a second time and drifting from it. */
+export function grokParse(buf: string): { lines: GrokChatLine[]; skipped: number } {
const lines: GrokChatLine[] = []
let skipped = 0
for (const raw of buf.split('\n')) {
diff --git a/src/core/grok-chat.test.ts b/src/core/grok-chat.test.ts
new file mode 100644
index 000000000..3cf170c53
--- /dev/null
+++ b/src/core/grok-chat.test.ts
@@ -0,0 +1,74 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+import { chatMessagesFromGrok } from './grok-chat'
+
+const RAW = fs.readFileSync(path.join(__dirname, '__fixtures__/grok/chat_history.jsonl'), 'utf8')
+
+describe('chatMessagesFromGrok', () => {
+ it('builds bubbles from a real session', () => {
+ const msgs = chatMessagesFromGrok(RAW)
+ expect(msgs.length).toBeGreaterThan(0)
+ expect(msgs.some((m) => m.role === 'user')).toBe(true)
+ expect(msgs.some((m) => m.role === 'assistant')).toBe(true)
+ })
+
+ it('never gives harness-injected text the user role', () => {
+ // The panel has two roles and no third place to put tooling text. grok marks these only with
+ // `synthetic_reason` under the `user` type, so an unlabelled read shows a skill reminder in the
+ // same shape as a typed prompt. Every injected line is assistant-side and carries its reason.
+ const msgs = chatMessagesFromGrok(RAW)
+ for (const reason of [
+ 'system_reminder',
+ 'compaction_meta',
+ 'project_instructions',
+ 'task_completed'
+ ]) {
+ const hit = msgs.find((m) =>
+ m.parts.some((p) => p.kind === 'text' && p.text.startsWith(`[${reason}]`))
+ )
+ expect(hit, reason).toBeDefined()
+ expect(hit!.role).toBe('assistant')
+ }
+ // …and no user bubble carries one.
+ for (const m of msgs.filter((x) => x.role === 'user')) {
+ for (const p of m.parts) {
+ if (p.kind === 'text') expect(p.text.startsWith('[')).toBe(false)
+ }
+ }
+ })
+
+ it('correlates a tool result back onto the call it answers', () => {
+ const msgs = chatMessagesFromGrok(RAW)
+ const tools = msgs.flatMap((m) => m.parts).filter((p) => p.kind === 'tool')
+ expect(tools.length).toBeGreaterThan(0)
+ // The fixture's results reference ids that its assistant lines declare, so at least one lands.
+ expect(tools.some((t) => t.kind === 'tool' && typeof t.result === 'string')).toBe(true)
+ // A result is never a bubble of its own.
+ expect(msgs.some((m) => m.parts.some((p) => p.kind === 'text' && p.text.startsWith(' =')))).toBe(
+ false
+ )
+ })
+
+ it('emits no model reasoning', () => {
+ const msgs = chatMessagesFromGrok(RAW)
+ const all = JSON.stringify(msgs)
+ expect(all).not.toContain('encrypted_content')
+ })
+
+ it('is empty, not thrown, for junk and for nothing', () => {
+ expect(chatMessagesFromGrok('')).toEqual([])
+ expect(chatMessagesFromGrok('{broken\n')).toEqual([])
+ })
+
+ it('does not parse a CLAUDE transcript — the two readers are not interchangeable', () => {
+ // A claude line nests its content under `message.content`, which this reader does not read.
+ // The point is that pointing the wrong reader at a file yields NOTHING rather than a plausible
+ // half-transcript: silence is the failure we can see.
+ const claudeLine = JSON.stringify({
+ type: 'user',
+ message: { content: [{ type: 'text', text: 'hello from claude' }] }
+ })
+ expect(chatMessagesFromGrok(claudeLine)).toEqual([])
+ })
+})
diff --git a/src/core/grok-chat.ts b/src/core/grok-chat.ts
new file mode 100644
index 000000000..0d9d2929d
--- /dev/null
+++ b/src/core/grok-chat.ts
@@ -0,0 +1,103 @@
+// grok's `chat_history.jsonl` as the ⌘M panel's structured messages.
+//
+// Separate from `transcript-reader.ts`'s `parseChatMessages`, which parses CLAUDE's shape
+// (`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.
+import type { ChatMessage, ChatPart } from '../shared/types'
+import { grokParse } from './context-link-render'
+
+const TOOL_ARG_MAX = 200
+const TOOL_RESULT_MAX = 500
+
+function textOf(content: unknown): string {
+ if (typeof content === 'string') return content
+ if (Array.isArray(content)) {
+ return content
+ .map((c) => (typeof c === 'string' ? c : ((c as { text?: string })?.text ?? '')))
+ .filter(Boolean)
+ .join('\n')
+ }
+ return ''
+}
+
+/**
+ * Ordered bubbles for a grok conversation.
+ *
+ * Two rules carried over from `linesFromGrok`, because breaking either one here would be a
+ * behaviour difference between two views of the same file:
+ *
+ * - A `user` line with `synthetic_reason` was injected by the harness, not typed by a person. It is
+ * rendered as an ASSISTANT-side note prefixed with its reason rather than as a user bubble — the
+ * panel has only two roles, and the one thing that must never happen is tooling text appearing in
+ * the shape of something the human said.
+ * - `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[] {
+ const messages: ChatMessage[] = []
+ const toolById = new Map<string, Extract<ChatPart, { kind: 'tool' }>>()
+ for (const o of grokParse(buf).lines) {
+ switch (o.type) {
+ case 'user': {
+ const t = textOf(o.content)
+ if (!t) break
+ const injected = typeof o.synthetic_reason === 'string' ? o.synthetic_reason.trim() : ''
+ if (injected) {
+ messages.push({ role: 'assistant', parts: [{ kind: 'text', text: `[${injected}] ${t}` }] })
+ } else {
+ messages.push({ role: 'user', parts: [{ kind: 'text', text: t }] })
+ }
+ break
+ }
+ case 'system': {
+ const t = textOf(o.content)
+ if (t) messages.push({ role: 'assistant', parts: [{ kind: 'text', text: `[system] ${t}` }] })
+ break
+ }
+ case 'assistant': {
+ 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 ?? '')
+ const part: Extract<ChatPart, { kind: 'tool' }> = {
+ kind: 'tool',
+ name: c.name || 'tool',
+ arg: String(a).slice(0, TOOL_ARG_MAX)
+ }
+ parts.push(part)
+ if (c.id) toolById.set(c.id, part)
+ }
+ if (parts.length) messages.push({ role: 'assistant', parts })
+ break
+ }
+ 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
+ if (!tool) break
+ const s = textOf(o.content).slice(0, TOOL_RESULT_MAX)
+ if (s) tool.result = s
+ break
+ }
+ case 'backend_tool_call': {
+ const q = o.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) : ''
+ }
+ ]
+ })
+ break
+ }
+ default:
+ break
+ }
+ }
+ return messages
+}
diff --git a/src/core/transcript-ipc.test.ts b/src/core/transcript-ipc.test.ts
index d31a75fb8..aea958c51 100644
--- a/src/core/transcript-ipc.test.ts
+++ b/src/core/transcript-ipc.test.ts
@@ -9,6 +9,7 @@ import path from 'path'
import { fakePlatform } from './platform-fake'
import { initPlatform, resetPlatformForTests } from './platform'
import { registerTranscriptIpc } from './transcript-ipc'
+import { rememberGrokSessionDir } from './grok-session'
import { IPC } from '../shared/ipc'
import type { ChatTranscriptResult, TranscriptLine } from '../shared/types'
@@ -103,3 +104,71 @@ describe('registerTranscriptIpc — the injected remote leg', () => {
expect(await chat('nt-1')).toEqual({ messages: [], found: false })
})
})
+
+describe('registerTranscriptIpc — the chat channel is routed by AGENT', () => {
+ // The ⌘M panel serves more than claude since grok joined CHAT_CAPABLE. Routing is not a
+ // refinement here: claude's resolver has a cwd fallback that returns the newest CLAUDE transcript
+ // for the node's directory whenever its sessionId leg misses, and a grok id always misses. So an
+ // unrouted grok node is not answered with "nothing" — it is answered with SOMEONE ELSE'S
+ // conversation. These tests exist to make that failure loud.
+ const GROK_SID = '01a06126-b981-73f1-8b68-4547e4d7da84'
+
+ const grokChat = (agentId?: string) =>
+ f.handlers[IPC.chatReadTranscript](
+ GROK_SID,
+ CWD,
+ undefined,
+ undefined,
+ agentId
+ ) as Promise<ChatTranscriptResult>
+
+ const writeGrokHistory = (body: string): string => {
+ const dir = path.join(home, '.grok', 'sessions', 'proj', GROK_SID)
+ fs.mkdirSync(dir, { recursive: true })
+ const p = path.join(dir, 'chat_history.jsonl')
+ fs.writeFileSync(p, body)
+ rememberGrokSessionDir(GROK_SID, dir)
+ return p
+ }
+
+ it('reads grok from its OWN file, in grok\'s own shape', async () => {
+ writeGrokHistory(
+ lines(
+ { type: 'user', content: 'from the grok session' },
+ { type: 'assistant', content: 'answered by grok' }
+ )
+ )
+ registerTranscriptIpc()
+ const res = await grokChat('grok')
+ expect(res.found).toBe(true)
+ expect(res.messages.map((m) => m.role)).toEqual(['user', 'assistant'])
+ expect(JSON.stringify(res.messages)).toContain('from the grok session')
+ })
+
+ it('does NOT hand a grok node the claude transcript sitting in the same cwd', async () => {
+ // Both files exist and describe the same directory. This is the exact shape of the bug: the
+ // claude one is newer and is what the cwd fallback would return.
+ writeTranscript(lines(userLine('SOMEONE ELSE PRIVATE'), assistantLine('not yours')))
+ writeGrokHistory(lines({ type: 'user', content: 'mine' }))
+ registerTranscriptIpc()
+ const res = await grokChat('grok')
+ expect(JSON.stringify(res.messages)).not.toContain('SOMEONE ELSE PRIVATE')
+ expect(JSON.stringify(res.messages)).toContain('mine')
+ })
+
+ it('reports not-found for a grok session no hook has located, instead of falling back', async () => {
+ // No `rememberGrokSessionDir`, so the locator knows nothing. The claude transcript below is
+ // present and resolvable by cwd — reaching it would be the leak.
+ writeTranscript(lines(userLine('SOMEONE ELSE PRIVATE')))
+ registerTranscriptIpc()
+ expect(await grokChat('grok')).toEqual({ messages: [], found: false })
+ })
+
+ it('leaves the claude path exactly as it was when no agent is named', async () => {
+ writeTranscript(lines(userLine('merhaba')))
+ registerTranscriptIpc()
+ const res = await chat()
+ expect(res.found).toBe(true)
+ expect(res.messages.length).toBe(1)
+ })
+})
diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.ts
index 824f26482..38a7e4980 100644
--- a/src/core/transcript-ipc.ts
+++ b/src/core/transcript-ipc.ts
@@ -12,9 +12,12 @@
import { IPC } from '../shared/ipc'
import type { ChatTranscriptResult, TranscriptLine } from '../shared/types'
import { platform } from './platform'
+import { chatMessagesFromGrok } from './grok-chat'
+import { locateGrok } from './handoff/locate'
import {
parseChatMessages,
parseTranscriptLines,
+ readCappedTail,
readChatMessages,
readTranscriptLines,
resolveTranscriptPath,
@@ -84,8 +87,22 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {
sessionId: string | undefined,
cwd: string | undefined,
accountId: string | undefined,
- nodeId: string | undefined
+ nodeId: string | undefined,
+ agentId: string | undefined
): Promise<ChatTranscriptResult> => {
+ // 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') {
+ const gp = sessionId ? await locateGrok(sessionId) : undefined
+ if (!gp) return { messages: [], found: false }
+ const buf = await readCappedTail(gp)
+ return buf === undefined
+ ? { messages: [], found: false }
+ : { messages: chatMessagesFromGrok(buf), found: true }
+ }
const remote = await remoteText({ sessionId, cwd, accountId, nodeId })
// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read failed
// (master down, transcript gone), and the panel must be able to say so.
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index fb9bfd39c..f726dc738 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -77,7 +77,7 @@ function linesFrom(raw: string): TranscriptLine[] {
// Read the last ~READ_CAP_BYTES of the file as UTF-8 (dropping the partial leading line on a
// capped read), or the whole file when it's small. Returns undefined if it can't be read.
-async function readCappedTail(filePath: string): Promise<string | undefined> {
+export async function readCappedTail(filePath: string): Promise<string | undefined> {
try {
const stat = await fs.promises.stat(filePath)
if (stat.size > READ_CAP_BYTES) {
diff --git a/src/main/handoff/index.test.ts b/src/main/handoff/index.test.ts
index c05a838ca..155f411d1 100644
--- a/src/main/handoff/index.test.ts
+++ b/src/main/handoff/index.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { handoffFilename } from './index'
+import { buildHandoff, handoffFilename } from './index'
describe('handoffFilename', () => {
it('builds a filesystem-safe handoff filename', () => {
@@ -14,3 +14,31 @@ describe('handoffFilename', () => {
)
})
})
+
+describe('buildHandoff — grok as a transfer source', () => {
+ // `buildHandoff` refuses an agent that has no renderer, with a message naming the agent. That
+ // refusal is the only observable difference between "grok is wired" and "grok is not", so it is
+ // what these assert: removing grok from RENDERERS or LOCATORS turns the first case into the
+ // second, and typecheck stays happy either way.
+ const SESSION = '01a06126-b981-73f1-8b68-4547e4d7da84'
+
+ it('is not refused as an unsupported source', async () => {
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'grok',
+ sourceNodeId: 'term-1'
+ })
+ // It may still fail to find a transcript on THIS machine — that is a different, honest error.
+ // What must never come back is the capability refusal.
+ expect(res).not.toEqual({ error: 'Transfer is not supported from grok.' })
+ })
+
+ it('still refuses an agent whose renderer really is unwritten', async () => {
+ const res = await buildHandoff({
+ sessionId: SESSION,
+ agentId: 'opencode',
+ sourceNodeId: 'term-1'
+ })
+ expect(res).toEqual({ error: 'Transfer is not supported from opencode.' })
+ })
+})
diff --git a/src/main/handoff/index.ts b/src/main/handoff/index.ts
index 825ea0310..455c0dcad 100644
--- a/src/main/handoff/index.ts
+++ b/src/main/handoff/index.ts
@@ -16,8 +16,9 @@ import { SESSION_ID_RE } from '../../core/transcript-reader'
import { renderClaudeTranscript } from './render-claude'
import { renderCodexTranscript } from './render-codex'
import { renderGeminiTranscript } from './render-gemini'
+import { renderGrokTranscript } from './render-grok'
import { budgetHandoff } from './budget'
-import { locateClaude, locateCodex, locateGemini } from '../../core/handoff/locate'
+import { locateClaude, locateCodex, locateGemini, locateGrok } from '../../core/handoff/locate'
export type HandoffResult = { filePath: string } | { error: string }
@@ -27,13 +28,15 @@ type Locator = (sessionId: string, accountId?: string) => Promise<string | undef
const RENDERERS: Record<string, Renderer> = {
claude: renderClaudeTranscript,
codex: renderCodexTranscript,
- gemini: renderGeminiTranscript
+ gemini: renderGeminiTranscript,
+ grok: renderGrokTranscript
}
const LOCATORS: Record<string, Locator> = {
claude: locateClaude,
codex: locateCodex,
- gemini: locateGemini
+ gemini: locateGemini,
+ grok: locateGrok
}
/** Filesystem-safe handoff filename for a node + ISO-ish timestamp. Node ids are
diff --git a/src/main/handoff/render-grok.test.ts b/src/main/handoff/render-grok.test.ts
new file mode 100644
index 000000000..76b0fb7f7
--- /dev/null
+++ b/src/main/handoff/render-grok.test.ts
@@ -0,0 +1,55 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+import { renderGrokTranscript } from './render-grok'
+
+// The fixture is cut from a REAL grok session (see core/__fixtures__/grok/chat_history.jsonl):
+// every line shape grok emits, including a deliberately truncated one.
+const RAW = fs.readFileSync(
+ path.join(__dirname, '../../core/__fixtures__/grok/chat_history.jsonl'),
+ 'utf8'
+)
+
+describe('renderGrokTranscript', () => {
+ it('renders each turn under its own heading', () => {
+ const md = renderGrokTranscript(RAW)
+ expect(md).toContain('## User')
+ expect(md).toContain('## Assistant')
+ expect(md).toContain('## System')
+ })
+
+ it('never presents harness-injected text as something the human said', () => {
+ // This is the rule that matters most in a handoff: the receiving agent reads a `## User`
+ // heading as an instruction from the person. grok files skill reminders, compaction notes,
+ // project instructions and subagent completions under the `user` role, marked only by
+ // `synthetic_reason` — so each gets its own heading, spelled as itself.
+ const md = renderGrokTranscript(RAW)
+ for (const reason of [
+ 'system_reminder',
+ 'compaction_meta',
+ 'project_instructions',
+ 'task_completed'
+ ]) {
+ expect(md).toContain(`## Injected (${reason})`)
+ }
+ })
+
+ it('keeps tool calls attached to the message above, not as speakers of their own', () => {
+ const md = renderGrokTranscript(RAW)
+ // Tool lines keep their `$` marker and never gain a heading.
+ expect(md).toMatch(/\$ \w+/)
+ expect(md).not.toContain('## $')
+ })
+
+ it('omits model reasoning, which is unreadable and not ours to forward', () => {
+ // `reasoning` lines carry `encrypted_content`. Three of them sit in the fixture; none of their
+ // ciphertext may appear in a document handed to another agent.
+ expect(renderGrokTranscript(RAW)).not.toContain('encrypted_content')
+ expect(renderGrokTranscript(RAW)).not.toContain('## Reasoning')
+ })
+
+ it('returns an empty document rather than throwing on junk', () => {
+ expect(renderGrokTranscript('')).toBe('')
+ expect(renderGrokTranscript('{not json\n\n')).toBe('')
+ })
+})
diff --git a/src/main/handoff/render-grok.ts b/src/main/handoff/render-grok.ts
new file mode 100644
index 000000000..28606f77d
--- /dev/null
+++ b/src/main/handoff/render-grok.ts
@@ -0,0 +1,46 @@
+// Renders a grok chat history .jsonl (~/.grok/sessions/<cwd>/<id>/chat_history.jsonl) to full
+// Markdown. No size cap, no summarization.
+//
+// The file is `chat_history.jsonl`, NOT the `updates.jsonl` grok's hook payloads advertise: that
+// sibling holds no readable conversation, and rendering it produces an empty handoff rather than an
+// error. `core/handoff/locate.ts` is where that choice is made and pinned.
+//
+// Shape knowledge is NOT duplicated here. `linesFromGrok` (core/context-link-render.ts) already
+// parses every measured line type from a real session, including the `synthetic_reason` rule that
+// keeps harness-injected text from being attributed to the human — a distinction that matters more
+// in a handoff than anywhere else, because the receiving agent reads "the user said X" as an
+// instruction. This module only turns those lines into Markdown headings.
+import { linesFromGrok } from '../../core/context-link-render'
+
+/** `role: text` (and the ` $ `/` = ` tool lines) as `linesFromGrok` emits them. */
+const ROLE_RE = /^(\w+): ([\s\S]*)$/
+
+const HEADINGS: Record<string, string> = {
+ user: 'User',
+ assistant: 'Assistant',
+ system: 'System'
+}
+
+export function renderGrokTranscript(raw: string): string {
+ const out: string[] = []
+ for (const line of linesFromGrok(raw)) {
+ // Tool lines are indented continuations of the message above them, never messages of their own,
+ // so they keep their `$`/`=` prefix and get no heading.
+ if (line.startsWith(' ')) {
+ out.push(line.trim())
+ continue
+ }
+ const m = ROLE_RE.exec(line)
+ if (!m) {
+ out.push(line)
+ continue
+ }
+ const [, role, text] = m
+ // A `synthetic_reason` role (`system_reminder`, `compaction_meta`, …) is not a speaker. It gets
+ // its own heading, spelled as itself, so the receiving agent can tell injected context from a
+ // human turn instead of inheriting someone's tooling as an instruction. One heading per message,
+ // like every sibling renderer — merging consecutive same-role turns would erase where one ended.
+ out.push(`## ${HEADINGS[role] ?? `Injected (${role})`}\n\n${text}`)
+ }
+ return out.join('\n\n')
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b6e285dc4..b2809c4ea 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -523,8 +523,8 @@ const api: NodeTerminalApi = {
clearGatewayCredential: () => ipcRenderer.invoke(IPC.agentGatewayCredentialClear)
},
chat: {
- readTranscript: (sessionId, cwd, accountId, nodeId) =>
- ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId)
+ readTranscript: (sessionId, cwd, accountId, nodeId, agentId) =>
+ ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId)
},
claudeAccounts: {
add: (ctx) => ipcRenderer.invoke(IPC.claudeAccountsAdd, ctx),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 695c6e14c..eaf35b4fb 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -827,13 +827,14 @@ export function buildTranscriptApi(
): Pick<NodeTerminalApi, 'chat'> & { claudeReadTranscript: ClaudeApi['readTranscript'] } {
return {
chat: {
- readTranscript: (sessionId, cwd, accountId, nodeId) =>
+ readTranscript: (sessionId, cwd, accountId, nodeId, agentId) =>
client.request(
IPC.chatReadTranscript,
sessionId,
cwd,
accountId,
- nodeId
+ nodeId,
+ agentId
) as Promise<ChatTranscriptResult>
},
claudeReadTranscript: (sessionId, cwd, accountId, nodeId) =>
diff --git a/src/renderer/lib/transcriptGates.ts b/src/renderer/lib/transcriptGates.ts
index 3a0d08aab..c31db1922 100644
--- a/src/renderer/lib/transcriptGates.ts
+++ b/src/renderer/lib/transcriptGates.ts
@@ -1,4 +1,4 @@
-import { canChat, type AgentId } from '@shared/agents/config'
+import { readsClaudeShapedTranscript, type AgentId } from '@shared/agents/config'
/**
* Does this node's conversation live in a file **claude's** transcript readers can locate and parse?
@@ -18,9 +18,13 @@ import { canChat, type AgentId } from '@shared/agents/config'
* session's messages as its own hits. Even wired to the right file the reader would be wrong: it
* parses claude's JSONL shape, which a codex rollout is not.
*
- * `CHAT_CAPABLE` already states exactly the fact being asked for — "we can read and render this
- * agent's transcript ourselves" — so it is reused here rather than adding a fourth capability list
- * that would mean the same thing.
+ * This used to read `CHAT_CAPABLE`, on the reasoning that it "already states exactly the fact being
+ * asked for" and a separate list "would mean the same thing". That was true only while claude was
+ * CHAT_CAPABLE's only member. Grok joined it in 2026-09 — we render grok's conversation ourselves
+ * with `linesFromGrok` — while grok's file is neither shaped like claude's nor under claude's tree,
+ * so the two facts came apart and the shared list became the very bug described above, pointed at a
+ * new agent. The gate now reads `CLAUDE_TRANSCRIPT_READABLE`, which asks the narrower question this
+ * function's name has always asked.
*
* The meter itself stays on `hasUsage` and spans three agents: it is fed by the per-agent context
* tails in the shells (`geminiContextParse` / `codexContextParse`), which need no resolver because
@@ -33,5 +37,5 @@ import { canChat, type AgentId } from '@shared/agents/config'
* `locateGemini` by sessionId) and to route to the matching tail — a real feature, not a gate.
*/
export function readsClaudeTranscript(agentId: AgentId | undefined): boolean {
- return !!agentId && canChat(agentId)
+ return !!agentId && readsClaudeShapedTranscript(agentId)
}
diff --git a/src/renderer/lib/transferItems.test.tsx b/src/renderer/lib/transferItems.test.tsx
index 0a1b804ba..33e354748 100644
--- a/src/renderer/lib/transferItems.test.tsx
+++ b/src/renderer/lib/transferItems.test.tsx
@@ -73,15 +73,33 @@ describe('transferConversationItems', () => {
})
it('returns [] when the agent is not transfer-capable', () => {
+ // opencode, not grok: grok joined TRANSFER_SOURCE_CAPABLE once `renderGrokTranscript` existed.
+ // The list is the gate, so this case needs an agent whose renderer is genuinely unwritten —
+ // otherwise it asserts nothing the moment that agent gains one.
const items = transferConversationItems(
'node-1',
undefined,
- args({ sourceAgentId: 'grok' as AgentId, customAgents: [] }),
+ args({ sourceAgentId: 'opencode' as AgentId, customAgents: [] }),
handler
)
expect(items).toEqual([])
})
+ it('offers targets for a grok source, now that its transcript can be rendered', () => {
+ const items = transferConversationItems(
+ 'node-1',
+ undefined,
+ args({ sourceAgentId: 'grok' as AgentId, customAgents: [] }),
+ handler
+ )
+ expect(items.length).toBeGreaterThan(1)
+ expect(items[0]).toEqual({ type: 'label', label: 'Transfer conversation to' })
+ // grok is never offered as a destination for itself; every other builtin still is.
+ const labels = items.slice(1).map((i) => ('label' in i ? i.label : ''))
+ expect(labels).not.toContain('Grok')
+ expect(labels).toContain('Claude Code')
+ })
+
it('returns [] when there is no session id yet', () => {
const items = transferConversationItems(
'node-1',
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 8f1232da7..bed30018e 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -19,6 +19,10 @@ interface ChatPanelProps {
cwd?: string
/** Managed Claude account this node runs under; resolves the transcript in the right root. */
accountId?: string
+ /** Which agent's reader to use. Omitted means claude, the historical behaviour. Passing it is not
+ * cosmetic: claude's resolver falls back to the newest transcript for the cwd, so a non-claude
+ * node that arrives unlabelled is answered with another session's conversation. */
+ agentId?: string
}
/**
@@ -56,7 +60,7 @@ const EMPTY_TEXT: Record<LoadState, { title: string; detail?: string }> = {
* session via pty.sendText. Phase 1 reloads the transcript whenever a turn finishes
* (working -> idle); live streaming is a later phase. Replaces the markdown-of-output overlay.
*/
-export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps) {
+export function ChatPanel({ nodeId, sessionId, cwd, accountId, agentId }: ChatPanelProps) {
// This node's core api (stable for the session — the chat transcript and the tmux session
// both live on the core this panel's project belongs to).
const { api } = useSession()
@@ -73,14 +77,14 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)
// `nodeId` is what lets an SSH-project node resolve on its host; the rejection branch is what
// keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently
// presenting itself as an empty conversation.
- void api.chat.readTranscript(sessionId, cwd, accountId, nodeId).then(
+ void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId).then(
(res) => {
setMessages(res.messages)
setLoadState(res.found ? 'ok' : 'missing')
},
(e: unknown) => setLoadState(isUnsupported(e) ? 'unsupported' : 'error')
)
- }, [api, sessionId, cwd, accountId, nodeId])
+ }, [api, sessionId, cwd, accountId, nodeId, agentId])
// Initial load.
useEffect(() => {
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 4318c8a5d..ee1f4e736 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -4937,6 +4937,7 @@ export function TerminalNode({
sessionId={status?.sessionId}
cwd={data.cwd as string | undefined}
accountId={data.accountId}
+ agentId={agentId}
/>
</Suspense>
) : (
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index 8a1038d5f..4f0e61511 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -4,6 +4,7 @@ import {
BUILTIN_AGENT_IDS,
canBranch,
canChat,
+ readsClaudeShapedTranscript,
canContextLink,
canControlCanvas,
canReadTitle,
@@ -186,6 +187,31 @@ describe('grok capabilities', () => {
expect(canContextLink('grok')).toBe(true)
})
+ it('hands its conversation to another agent, and shows it in the chat panel', () => {
+ // Both ride the reader task06 wrote. Transfer adds `renderGrokTranscript` beside the other
+ // three renderers; the panel adds `chatMessagesFromGrok`. Neither re-derives grok's line
+ // vocabulary — they build on the same `grokParse`, so the two views cannot drift apart.
+ expect(canTransferFrom('grok')).toBe(true)
+ expect(canChat('grok')).toBe(true)
+ })
+
+ it('is CHAT_CAPABLE and yet NOT readable by claude\'s resolver — the pair is the invariant', () => {
+ // These two must never collapse back into one list. `canChat` means "we can render this
+ // conversation ourselves"; `readsClaudeShapedTranscript` means "claude's resolver can locate and
+ // parse this file". Grok is the first agent for which they differ, and the cost of merging them
+ // is not cosmetic: `resolveTranscript` falls back to the newest CLAUDE transcript for the node's
+ // cwd whenever its sessionId leg misses, which a grok id always does. A merged list would show a
+ // grok node someone else's conversation in the find bar and meter it from that session.
+ //
+ // If a future change "simplifies" CLAUDE_TRANSCRIPT_READABLE away, this line fails first.
+ expect(canChat('grok')).toBe(true)
+ expect(readsClaudeShapedTranscript('grok')).toBe(false)
+ // claude is the one agent where both hold — which is exactly why the shared list looked correct
+ // for as long as it was claude-only.
+ expect(canChat('claude')).toBe(true)
+ expect(readsClaudeShapedTranscript('claude')).toBe(true)
+ })
+
it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {
expect(hasUsage('grok')).toBe(false)
expect(canBranch('grok')).toBe(false)
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index bffbf9574..aee818a99 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -154,9 +154,29 @@ export const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'g
// used count to divide.
export const USAGE_CAPABLE = ['claude', 'codex', 'gemini'] as const
// Agents whose structured transcript we can render as a chat panel (Cmd+M chat mode).
-export const CHAT_CAPABLE = ['claude'] as const
+//
+// SPLIT from CLAUDE_TRANSCRIPT_READABLE below on 2026-09-02, when grok joined. Until then this one
+// list carried TWO facts that happened to coincide while claude was its only member: "we can render
+// this agent's conversation ourselves" and "CLAUDE's transcript resolver can locate and parse this
+// agent's file". Grok satisfies the first (`linesFromGrok`, core/context-link-render.ts) and NOT the
+// second, and merging them is not a cosmetic error: `resolveTranscript` (core/transcript-ipc.ts:58)
+// falls back to `transcriptPathForCwd` when the sessionId leg misses — which it ALWAYS does for a
+// non-claude id, since no `<that id>.jsonl` exists under `~/.claude/projects` — and hands back the
+// newest CLAUDE transcript for that cwd. A grok node in this list would therefore show a stranger's
+// conversation in its find bar and rehydrate its meter from it. That exact bug already happened once
+// with codex and gemini; transcriptGates.ts documents it.
+export const CHAT_CAPABLE = ['claude', 'grok'] as const
+// Agents whose transcript CLAUDE's own resolver can locate and parse — the gate for everything that
+// goes through `resolveTranscript` (the find bar's index, the meter's mount-time rehydration).
+//
+// This is deliberately NOT a superset of CHAT_CAPABLE and must not be "simplified" back into it: the
+// question here is not "can we read this agent" but "does this agent's conversation live in a file
+// shaped like claude's, under claude's tree". Only claude answers yes, and the failure mode of a
+// wrong answer is a read of SOMEONE ELSE'S session (see the comment above), which fails OPEN — it
+// shows data rather than hiding it. `config.capabilities.test.ts` pins that grok is absent.
+export const CLAUDE_TRANSCRIPT_READABLE = ['claude'] as const
// Agents whose native transcript we can read + render for cross-agent transfer.
-export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini'] as const
+export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const
// Agents that accept a node title being PUSHED back into the session — the write leg only. The
// write is the same literal `/rename <name>` for both, which grok also accepts as `/title`.
// The READ leg is TITLE_READ_CAPABLE below, which is a superset: an agent can name its own session
@@ -301,6 +321,10 @@ export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)
export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CAPABLE, id)
export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)
export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)
+/** Can CLAUDE's transcript resolver locate and parse this agent's conversation? Never widen this
+ * to mean "can we read this agent" — see CLAUDE_TRANSCRIPT_READABLE. */
+export const readsClaudeShapedTranscript = (id: AgentId): boolean =>
+ includes(CLAUDE_TRANSCRIPT_READABLE, id)
export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)
export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)
export const canReadTitle = (id: AgentId): boolean => includes(TITLE_READ_CAPABLE, id)
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 24e8c5f6f..a4de0c10a 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2310,16 +2310,22 @@ export interface ChatTranscriptResult {
export interface ChatApi {
/**
- * Reads a Claude session transcript as structured chat messages.
+ * Reads an agent session transcript as structured chat messages.
* Resolves the transcript like `ClaudeApi.readTranscript` (sessionId → cwd), then
* reconstructs ordered bubbles + tool calls. `nodeId` lets an SSH-project node be resolved
* on its HOST even when no hook event has registered its transcript in this app run.
+ *
+ * `agentId` picks the reader. Omitted (or `claude`) keeps the historical claude path exactly as
+ * it was. It is NOT optional in spirit: without it a grok node falls into claude's resolver, whose
+ * cwd fallback returns the newest CLAUDE transcript for that directory — someone else's
+ * conversation. `CHAT_CAPABLE` decides who may ask; this decides who answers.
*/
readTranscript(
sessionId: string | undefined,
cwd: string | undefined,
accountId?: string,
- nodeId?: string
+ nodeId?: string,
+ agentId?: string
): Promise<ChatTranscriptResult>
}