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): subagent visualization via native SubagentStart/SubagentStop hooks

Xavi Guardia29409aa0550f
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index 94e99e916..5c23776ef 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -44,7 +44,7 @@ is the cost of adding the next agent to the same list.
| `USAGE_CAPABLE` (the per-node context meter) | **joined** | `signals.json` yields both numbers AND the answer: `contextTokensUsed`, `contextWindowTokens` and `contextWindowUsage` — the percentage grok has already computed. Measured on 22 real sessions (1.0.13, 2026-09-02): all three present in all 22, and the stated percentage agrees with used/window in all 22, which is a free oracle and is pinned as a test. The window is READ, never inferred from the model id, putting grok with codex rather than with gemini. The reader (`core/grok-signals.ts`) takes three of the file's 66 keys and returns null unless both numbers are there — no denominator, no meter. Its tail is created with `wholeFile`, because signals.json is rewritten in place rather than appended to; an offset read would hand the parser a JSON fragment and the meter would freeze after its first fill with nothing to say so. The rule this row used to state still holds for everyone: a percentage against a guessed denominator is a wrong number presented as a fact, so no total ⇒ no meter. (The list is now `claude, codex, gemini, grok`; **opencode** is the one builtin outside it. Codex states its own denominator in its rollout; gemini's comes from its model id through `geminiWindowFor`, mirroring the CLI's own `tokenLimit`. See `docs/gemini-agent.md` §4.) **The trap this row used to warn about was real and is now disarmed:** joining this list also switched on two features that read CLAUDE's transcript, because `readsClaudeTranscript` shared a list with them — a codex node once metered and searched a stranger's claude session that way. That gate now reads `CLAUDE_TRANSCRIPT_READABLE` (claude only), pinned in `config.capabilities.test.ts`, so grok joins the meter without joining those. Do not confuse this with grok *billing* usage — see the note below. |
| `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**. |
| `MODEL_SWITCH_CAPABLE` | **joined** | The whole capability is the leaf in `shared/agents/model-gateway.ts`; no frontend spells a grok model id or the string `grok`. **Discovery has no allowlist:** `grok models` lists the CLI's own catalogue (`grok-4.6`, `grok-4.5` on 1.0.13), parsed by `grokModelsFrom` from a captured fixture, so a model shipped tomorrow appears with no code change. Only the indented bullets are read — the `Default model:` line is prose that repeats an id, and treating prose as data is how a banner becomes a fake model. Unparseable output ⇒ EMPTY list ⇒ no model switching, the pre-feature behaviour. **grok is offered its OWN models, never the gateway's,** and that is correctness rather than taste: grok cannot be routed through the gateway at all, so the gateway catalogue would put ids on the menu that grok rejects at launch — a picker that looks like it worked and kills the node. **It needs no new environment,** which is the part worth stating rather than omitting: grok's custom models are declared in `~/.grok/config.toml` with their own `base_url`/`api_key`, and `11-custom-models.md` says explicitly that `model`/`base_url`/`api_key` CANNOT be defaulted from the environment. So `modelGatewayEnv` returns `{}` for grok on purpose. Writing into the user's `config.toml` to route grok through the gateway is a real feature and a separate decision. The flag is `-m/--model`, emitted **before** the `--` separator — after it, grok swallows it into the prompt and the node launches on the default model while the agent reads the flag as its first instruction. `--reasoning-effort` exists and is deliberately NOT part of this. |
-| `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. |
+| `SUBAGENT_CAPABLE` | **joined** | grok fires native `SubagentStart`/`SubagentStop`, and the design turns entirely on three things that had to be MEASURED — two `explore` children launched in parallel, 1.0.13, 2026-09-02. **(1) There is an instance id.** `subagentId` differs between two children of the SAME type, so grok keys like codex's `agent_id`; the assumption that it exposes only a TYPE, forcing an aggregated card, was wrong. **(2) `sessionId` means different things in the two events** — the PARENT's on the start (the hook runs in the parent), the CHILD's own on the stop, where it equals `subagentId`. Keying on it would file the start and the stop under different cards and the started one would never close: a badge lit forever, with no error. `subagentId` is the only id both events share. **(3) codex's leg does not port.** `subagent-tail.ts` says of codex that *"SubagentStart hands us the child rollout's path directly"*; grok's start carries the PARENT's `transcriptPath`, so copying it paints the parent's conversation inside the child's card — full, plausible, somebody else's. The child's directory is derived from `subagentId` instead and read as `chat_history.jsonl`, never as the advertised `updates.jsonl` (the stop's path is finally the child's, and still names the wrong file). `description` is captured on the start because the stop does not carry it. And a `session_end` bearing `subagentType` returns early: without that guard a child finishing tears down the PARENT's session state and the node goes quiet mid-turn. |
| `BRANCH_CAPABLE` | not joined | Branch sends claude's `/branch` and resumes by claude's session id; grok has no counterpart. |
| `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. |
@@ -378,6 +378,7 @@ ai-name / comments).
| 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) |
| Model switch | **yes** — discovered from `grok models` through the same memoized CLI probe the session-id flag rides | **yes** — `registerGrokCliIpc` runs in this shell too, so the browser gets the same catalogue over WS-RPC | N/A — the phone launches nothing |
+| Subagent cards | **yes** — one card per `subagentId`, live from the child's own `chat_history.jsonl` | **yes** — the same branch in `src/server/agent-status.ts`; `hook-verified-parity.test.ts` fails if either shell loses it | the phone reads the mirror, so cards arrive with no phone-side work |
| 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** |
| Working indicator | the **brand mark, breathing** — no critter. Since 2026-08-09 this is a THREE-agent mechanism (grok, gemini, opencode) driven by one pure decision, `brandPulsePlan` in `lib/brandPulse.ts`, with a thin renderer per surface: `BrandPulse` for the React badge (`AgentMascot` no longer imports `GrokMark`) and `workingMascot` for the notch strip. Grok is the only `kind: 'inline'` case — its mark is a single monochrome path from `lib/grokMark.ts` (`createGrokMarkSvg` in the HUD) pulsing with a `currentColor` drop-shadow bloom; the other marks are multi-colour assets whose bloom takes the label colour instead of their own ink. One decision, so an agent is never two things on two surfaces. See docs/mascot-sprites.md | **N/A** — no notch there; the canvas badge indicator works | the phone has its own SwiftUI renderer |
diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.ts
index 8fc296d2a..d83b6a052 100644
--- a/src/core/agents/hook-verified-parity.test.ts
+++ b/src/core/agents/hook-verified-parity.test.ts
@@ -162,6 +162,27 @@ describe('both shells register a 4-arg raw listener', () => {
// (b) skip the context-meter track for agent_id-tagged child events — a shell missing (a)
// silently has no live activity, and one missing (b) re-points the parent's meter at the
// child's rollout (SubagentStart carries the parent session_id with the CHILD's path).
+ // Same rule, grok's instance. Three things must be in BOTH shells or the feature is silently
+ // half-present: (a) the card is keyed by `subagentId` — the only id the start and the stop share,
+ // since the start's `sessionId` is the PARENT's; (b) the child's transcript is DERIVED from that
+ // id, never taken from the payload's path, which on the start belongs to the parent; and (c) a
+ // `session_end` carrying `subagentType` returns early, or a child finishing tears down the
+ // PARENT's session state and the node goes quiet mid-turn.
+ it('both raw listeners carry the grok subagent branch (subagentId + derived path + child-end guard)', () => {
+ for (const rel of ['src/main/index.ts', 'src/server/agent-status.ts']) {
+ const src = code(rel)
+ expect(src, `${rel} misses the grok subagent trackFile branch`).toMatch(
+ /subagentTail\.trackFile\(\s*g\.subagentId/
+ )
+ expect(src, `${rel} derives the child path from the payload instead of the subagentId`).toMatch(
+ /sessionId: g\.subagentId/
+ )
+ expect(src, `${rel} misses the child session_end guard`).toMatch(
+ /g\.event === 'sessionend' && g\.subagentType/
+ )
+ }
+ })
+
it('both raw listeners carry the codex subagent branch (trackFile + agent_id gate)', () => {
for (const rel of ['src/main/index.ts', 'src/server/agent-status.ts']) {
const src = code(rel)
diff --git a/src/core/grok-subagent-format.test.ts b/src/core/grok-subagent-format.test.ts
new file mode 100644
index 000000000..9befda415
--- /dev/null
+++ b/src/core/grok-subagent-format.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
+import { createGrokSubagentFormatter } from './grok-subagent-format'
+
+// A real child session's lines. The card is a live view of the SAME file context links and the ⌘M
+// panel read, so this delegates to `linesFromGrok` rather than parsing again — a card that disagreed
+// with the transcript the user can open beside it would be worse than no card.
+const RAW = fs.readFileSync(path.join(__dirname, '__fixtures__/grok/chat_history.jsonl'), 'utf8')
+
+describe('createGrokSubagentFormatter', () => {
+ it('renders a chunk of the child conversation', () => {
+ const out = createGrokSubagentFormatter()(RAW)
+ expect(out.length).toBeGreaterThan(0)
+ expect(out).toMatch(/^(user|assistant|system|system_reminder|compaction_meta):/m)
+ })
+
+ it('emits nothing for a chunk with no renderable line', () => {
+ // The tail feeds partial reads. A chunk that lands mid-line, or between messages, must produce
+ // an empty string rather than a stray fragment on the card.
+ const fmt = createGrokSubagentFormatter()
+ expect(fmt('')).toBe('')
+ expect(fmt('{"type":"reasoning"')).toBe('')
+ expect(fmt('\n\n')).toBe('')
+ })
+
+ it('never shows model reasoning on the card', () => {
+ // `reasoning` lines carry `encrypted_content`; the fixture has three. None of that ciphertext
+ // may reach a card the user reads.
+ expect(createGrokSubagentFormatter()(RAW)).not.toContain('encrypted_content')
+ })
+
+ it('does not attribute harness-injected text to the child', () => {
+ // Same rule the transcript reader follows: a `user` line carrying `synthetic_reason` was
+ // injected by tooling, and on a card labelled with a subagent's name it would read as something
+ // that subagent said.
+ const out = createGrokSubagentFormatter()(RAW)
+ expect(out).toMatch(/^system_reminder:/m)
+ })
+
+ it('gives each card its own formatter instance', () => {
+ // Two children run in parallel and each gets its own. They must not share state — today there
+ // is none, and this pins that a future state stays per-card.
+ expect(createGrokSubagentFormatter()).not.toBe(createGrokSubagentFormatter())
+ })
+})
diff --git a/src/core/grok-subagent-format.ts b/src/core/grok-subagent-format.ts
new file mode 100644
index 000000000..93955e138
--- /dev/null
+++ b/src/core/grok-subagent-format.ts
@@ -0,0 +1,29 @@
+// One chunk of a grok SUBAGENT's `chat_history.jsonl`, as card text.
+//
+// The card is a live view of a child session, so this is fed incremental chunks by
+// `subagent-tail.ts` rather than a whole file. It delegates every shape decision to `linesFromGrok`
+// (core/context-link-render.ts) — the same reader context links, the ⌘M panel and cross-agent
+// transfer use — so a card can never disagree with the transcript the user can open next to it.
+//
+// WHICH FILE: `chat_history.jsonl`, derived from the child's `subagentId`. NOT the `transcriptPath`
+// grok's own subagent payloads carry. On `SubagentStart` that path is the PARENT'S session (measured
+// on 1.0.13 across two parallel children), so following it would paint the parent's conversation
+// inside the child's card — full, plausible, and somebody else's. On `SubagentStop` the directory is
+// finally the child's, but the file is still `updates.jsonl`, which parses to nothing here. Both
+// spellings of the trap are documented at `handoff/locate.ts`.
+import { linesFromGrok } from './context-link-render'
+
+/**
+ * A fresh formatter per card. Stateless today — grok's child transcript has no replay prefix to
+ * skip, unlike codex's fork-replay — but built with the same factory shape as
+ * `createCodexSubagentFormatter` so the tail has ONE contract, and so a future state (a
+ * compaction marker, a nested spawn) has somewhere to live.
+ */
+export function createGrokSubagentFormatter(): (text: string) => string {
+ return (text: string): string => {
+ // `linesFromGrok` skips model reasoning and labels harness-injected text with its own reason,
+ // so neither can appear in the card as something the child said.
+ const lines = linesFromGrok(text)
+ return lines.length ? lines.join('\n') : ''
+ }
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index d2c1f4202..e7041ab76 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -187,6 +187,8 @@ import { installManagedAgentHooks } from '../core/agents/hooks'
import { createSubagentTail } from '../core/subagent-tail'
import { createContextTail, type TaskNotification } from '../core/context-tail'
import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'
+import { GROK_CHAT_HISTORY_FILE } from '../core/agents/grok-paths'
+import { createGrokSubagentFormatter } from '../core/grok-subagent-format'
import { geminiContextParse } from '../core/gemini-session'
import { codexContextParse } from '../core/codex-session'
import { createCodexSubagentFormatter } from '../core/codex-subagent-format'
@@ -2764,6 +2766,45 @@ app.whenReady().then(async () => {
if (nodeId && (plan.event === 'stop' || plan.event === 'sessionend')) {
recordRawToolEvent(nodeId, { hook_event_name: 'Stop' })
}
+ // 3. SUBAGENT CARDS. Keyed by `subagentId` — the per-instance id, and the ONLY id both
+ // events share. On SubagentStart `sessionId` is the PARENT's; on SubagentStop it is the
+ // CHILD's own. Keying on it would file the start and the stop under different cards, and the
+ // started one would never close: a badge lit forever, with no error to show for it.
+ //
+ // The child's transcript is DERIVED from `subagentId`, never taken from the payload's
+ // `transcriptPath`. On the start that path is the PARENT's session — following it paints the
+ // parent's conversation inside the child's card, full and plausible and somebody else's — and
+ // on the stop the directory is finally the child's but the file is still `updates.jsonl`,
+ // which parses to nothing. Both spellings of that trap are documented at `handoff/locate.ts`.
+ if (g.subagentId && g.cwd) {
+ if (g.event === 'subagentstart') {
+ const childDir = grokSessionDir({
+ sessionsDir: grokSessionsDir(),
+ cwd: g.cwd,
+ sessionId: g.subagentId
+ })
+ if (childDir) {
+ subagentTail.trackFile(
+ g.subagentId,
+ join(childDir, GROK_CHAT_HISTORY_FILE),
+ createGrokSubagentFormatter
+ )
+ if (nodeId) {
+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()
+ set.add(g.subagentId)
+ nodeSubagents.set(nodeId, set)
+ }
+ }
+ } else if (g.event === 'subagentstop') {
+ subagentTail.finish(g.subagentId)
+ if (nodeId) nodeSubagents.get(nodeId)?.delete(g.subagentId)
+ }
+ }
+ // A CHILD's teardown is not this node's. `session_end` carries `subagentType` only in a
+ // subagent session (measured: 2 of the 4 captured ends had it, and those two were the
+ // children). Without this guard a subagent finishing would forget the PARENT's session
+ // directory and clear its context tail — the node would go quiet mid-turn.
+ if (g.event === 'sessionend' && g.subagentType) return
// Forgetting the MAP entry and untracking the TAIL are two different things and neither
// substitutes for the other: `applyGrokHookSession` did the first (and does it for PostCompact
// too, which this call site cannot see). The tail is this shell's, so it is released here.
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 75d767dd6..0fdf1b211 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -19,6 +19,8 @@ import { createContextTail, type ContextTail, type TaskNotification } from '../c
import { geminiContextParse } from '../core/gemini-session'
import { codexContextParse } from '../core/codex-session'
import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'
+import { GROK_CHAT_HISTORY_FILE } from '../core/agents/grok-paths'
+import { createGrokSubagentFormatter } from '../core/grok-subagent-format'
import { createCodexSubagentFormatter } from '../core/codex-subagent-format'
import { codexHome } from '../core/usage/codex-usage'
import { setNodeTranscript } from '../core/context-link'
@@ -255,6 +257,45 @@ export function wireAgentStatus(
if (nodeId && (plan.event === 'stop' || plan.event === 'sessionend')) {
recordRawToolEvent(nodeId, { hook_event_name: 'Stop' })
}
+ // 3. SUBAGENT CARDS. Keyed by `subagentId` — the per-instance id, and the ONLY id both
+ // events share. On SubagentStart `sessionId` is the PARENT's; on SubagentStop it is the
+ // CHILD's own. Keying on it would file the start and the stop under different cards, and the
+ // started one would never close: a badge lit forever, with no error to show for it.
+ //
+ // The child's transcript is DERIVED from `subagentId`, never taken from the payload's
+ // `transcriptPath`. On the start that path is the PARENT's session — following it paints the
+ // parent's conversation inside the child's card, full and plausible and somebody else's — and
+ // on the stop the directory is finally the child's but the file is still `updates.jsonl`,
+ // which parses to nothing. Both spellings of that trap are documented at `handoff/locate.ts`.
+ if (g.subagentId && g.cwd) {
+ if (g.event === 'subagentstart') {
+ const childDir = grokSessionDir({
+ sessionsDir: grokSessionsDir(),
+ cwd: g.cwd,
+ sessionId: g.subagentId
+ })
+ if (childDir) {
+ subagentTail.trackFile(
+ g.subagentId,
+ join(childDir, GROK_CHAT_HISTORY_FILE),
+ createGrokSubagentFormatter
+ )
+ if (nodeId) {
+ const set = nodeSubagents.get(nodeId) ?? new Set<string>()
+ set.add(g.subagentId)
+ nodeSubagents.set(nodeId, set)
+ }
+ }
+ } else if (g.event === 'subagentstop') {
+ subagentTail.finish(g.subagentId)
+ if (nodeId) nodeSubagents.get(nodeId)?.delete(g.subagentId)
+ }
+ }
+ // A CHILD's teardown is not this node's. `session_end` carries `subagentType` only in a
+ // subagent session (measured: 2 of the 4 captured ends had it, and those two were the
+ // children). Without this guard a subagent finishing would forget the PARENT's session
+ // directory and clear its context tail — the node would go quiet mid-turn.
+ if (g.event === 'sessionend' && g.subagentType) return
// Forgetting the MAP entry and untracking the TAIL are two different things and neither
// substitutes for the other: `applyGrokHookSession` did the first (and does it for PostCompact
// too, which this call site cannot see). The tail is this shell's, so it is released here.
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index b40b8c405..b22189c23 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -258,9 +258,16 @@ describe('grok capabilities', () => {
expect(canSwitchModel('grok')).toBe(true)
})
+ it('shows one card per subagent INSTANCE, not one per type', () => {
+ // Keyed by `subagentId`, measured by running two `explore` children in parallel: same type,
+ // different ids. The premise this task started from — that grok only exposes a TYPE, so two
+ // children of one type would have to share an aggregated card — was wrong, and running the two
+ // is the only thing that could have told us.
+ expect(canSubagent('grok')).toBe(true)
+ })
+
it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {
expect(canBranch('grok')).toBe(false)
- expect(canSubagent('grok')).toBe(false)
})
})
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 40f921a76..995bcd4cf 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -136,7 +136,12 @@ export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok'] as const
export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const
// claude: Task/Agent tool via hooks (tool_use_id-keyed). codex: spawn_agent collaboration via its
// native SubagentStart/SubagentStop hooks (agent_id-keyed), measured on codex-cli 0.146.0.
-export const SUBAGENT_CAPABLE = ['claude', 'codex'] as const
+// grok: its own native SubagentStart/SubagentStop, keyed by `subagentId` — measured on 1.0.13 by
+// running two subagents of the SAME type in parallel, which is the only way to tell an instance
+// id from a type. It was assumed to key by `subagentType` (a type, so two children of one type
+// would collide); the payloads say otherwise, and `subagentId` is also the ONLY id the start and
+// the stop share — on the start `sessionId` is the PARENT's.
+export const SUBAGENT_CAPABLE = ['claude', 'codex', 'grok'] as const
export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
export const BRANCH_CAPABLE = ['claude'] as const
// grok joins with NO installer of its own: it scans `~/.claude/skills` for Claude Code
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index 6137717f0..faf7c6325 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -591,6 +591,16 @@ interface GrokPayload {
tool_use_id?: string
toolInput?: Record<string, unknown>
tool_input?: Record<string, unknown>
+ /** SubagentStart/SubagentStop only. MEASURED (1.0.13, two parallel `explore` children): a
+ * per-INSTANCE id, and the only id both events share — see `grokRawFields`. The snake spelling is
+ * read alongside the camel one for the same reason every other field here is: grok emits both
+ * dialects in the same payload, and the SDK path may present only one. */
+ subagentId?: string
+ subagent_id?: string
+ subagentType?: string
+ subagent_type?: string
+ /** SubagentStart only: the human task text ("Read a.txt contents"). Absent on the stop. */
+ description?: string
lastAssistantMessage?: string
last_assistant_message?: string
notificationType?: string
@@ -653,6 +663,9 @@ export function grokRawFields(payload: Record<string, unknown>): {
toolName?: string
toolUseId?: string
toolInput?: Record<string, unknown>
+ subagentId?: string
+ subagentType?: string
+ description?: string
} {
const p = payload as GrokPayload
return {
@@ -661,7 +674,21 @@ export function grokRawFields(payload: Record<string, unknown>): {
cwd: p.cwd,
toolName: p.toolName ?? p.tool_name,
toolUseId: p.toolUseId ?? p.tool_use_id,
- toolInput: p.toolInput ?? p.tool_input
+ toolInput: p.toolInput ?? p.tool_input,
+ // MEASURED on 1.0.13 (2026-09-02) by running two `explore` subagents in parallel:
+ //
+ // - `subagentId` is a per-INSTANCE id. The two children of the same TYPE came back with
+ // different ids, so grok keys like codex's `agent_id` and not, as was assumed, by type
+ // alone — nothing has to be aggregated.
+ // - It is also the ONLY id common to both events. On `SubagentStart` the `sessionId` is the
+ // PARENT's (the hook runs in the parent); on `SubagentStop` it is the CHILD's own, equal to
+ // `subagentId`. Keying on `sessionId` would file the start and the stop under different
+ // cards, and the started one would never close: a badge lit forever, with no error.
+ // - `description` arrives ONLY on the start ("Read a.txt contents"); on the stop it is
+ // absent, so a title resolved at close time has nothing to read.
+ subagentId: p.subagentId ?? p.subagent_id,
+ subagentType: p.subagentType ?? p.subagent_type,
+ description: p.description
}
}