Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(grok): a context meter on the denominator grok states, and its own tool vocabulary
Xavi Guardia34a21b1b475e
diff --git a/docs/grok-agent.md b/docs/grok-agent.mdindex 7a9ee558f..9dadea399 100644--- a/docs/grok-agent.md+++ b/docs/grok-agent.md@@ -40,7 +40,7 @@ is the cost of adding the next agent to the same list.| `RENAME_CAPABLE` + `TITLE_READ_CAPABLE` | **joined both** | A **read** leg that resolves a session's own name *without searching* (`core/grok-session.ts`, keyed off the hook-fed `sessionId → session dir` map), a **write** leg byte-identical to claude's (`/rename <name>` typed into the pane via `pty.sendText`; grok also accepts `/title`), and one routing rule for the readers — `readAgentSessionName` in `core/agent-session-name.ts`, serving the desktop IPC handler *and* both shells' session-name sweeps. The list SPLIT in two after the grok branch (2026-08-09): `TITLE_READ_CAPABLE` is the read leg and `RENAME_CAPABLE` the write leg, because **gemini** names its own sessions but has no rename command. Grok is in both, so nothing about its behaviour changed — but a future agent must pick per leg, and every `RENAME_CAPABLE` member must also be `TITLE_READ_CAPABLE` (pinned in `config.capabilities.test.ts`). Routing is not cosmetic: claude's resolver scans `~/.claude/projects` on a cache miss, so an unrouted grok node paid that scan on every poll for a guaranteed null — a mounted node polls every **4 s** until the name first resolves and **15 s** after (`TerminalNode.tsx`), and the mirror's own `SESSION_NAME_SWEEP_MS` sweep adds one pass a minute. || `PERMISSION_MODE_CAPABLE` | **joined** | Grok shares claude's flag **spelling** and value vocabulary (`--permission-mode auto\|plan\|acceptEdits\|bypassPermissions`; our `manual` = no flag = grok's own `default`), which is why *its* membership needed no translation. Two things had to change around it: claude's `auto` **version gate** had to become agent-scoped (`activePermissionMode(agentId)`, `renderer/state/permissionMode.ts`), and the flag had to be emitted **before** grok's `--`. See §6. **Sharing the spelling is no longer what membership means:** the list is now `claude, grok, gemini, codex` (2026-08-09) and the last two spell it their own way (`--approval-mode`, `--ask-for-approval`), translated per agent in `src/shared/agents/approval-mode.ts` — which is also where `withPermissionMode` now lives, moved one layer up to break a `config ↔ approval-mode` cycle. || `CANVAS_CONTROL_CAPABLE` | **joined** | Nothing new to install: grok scans `~/.claude/skills` by default for Claude Code compatibility, which is exactly where `manage-nodeterm-canvas` is already written (locally, and on an SSH host by `RemoteHooks.installCanvasControl`). Membership is what sets `NODETERM_CANVAS_CONTROL=1` in the session env — `hook-server.buildPtyEnv` locally, `remoteHookEnvArgs` remotely, both through the single `canControlCanvas` predicate — i.e. what makes the sh+curl shim anything other than a no-op. **The discovery premise is MEASURED, not inferred** (grok 1.0.13, 2026-09-02): `grok inspect --json` lists `manage-nodeterm-canvas` and `get-linked-context` with `vendor: claude` and `compatibilityStatus: enabled`, and `externalCompat.cells` reports `{surface: 'skills', enabled: true, source: 'default'}`. `source: 'default'` is the part that matters: grok reads `~/.claude/skills` with **no** config edit by the user. Two per-user failure modes survive the measurement and cannot be exercised on a default-config machine — `[compat.claude] skills = false` in `~/.grok/config.toml`, and `GROK_CLAUDE_SKILLS_ENABLED=false`. In each, `NODETERM_CANVAS_CONTROL=1` is still set while the skill is undiscoverable: the shim is armed and mute. See §8.7 and checklist 21. |-| `USAGE_CAPABLE` (the per-node context meter) | **not joined** | Needs a real `signals.json` yielding **both** a used-token count **and** the window total. A percentage against a guessed denominator is a wrong number presented as a fact, so no total ⇒ no meter. Task 5 of the plan stops at its capture step. (For reference, the list is now `claude, codex, gemini`; grok and **opencode** are the two builtins 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 — and note that **joining this list also switches on two features that read CLAUDE's transcript**, which is a trap grok will hit too: `docs/gemini-agent.md` §1.) Do not confuse this with grok *billing* usage — see the note below. |+| `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**. || `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. |@@ -246,8 +246,9 @@ first so a real manual title wins the moment the key is confirmed; a wrong guessgenerated title (right name, just not overridable from grok's side) rather than to a wrong name.Confirming it is checklist item **14**.-**Not captured at all:** `signals.json` (blocks the context meter — the used-token key, the window-total, and whether a total exists anywhere). The transcript log is **no longer** in this list, and+**Not captured at all:** nothing, for the context meter. `signals.json` was the last entry here and+it has been captured (22 sessions): it states the used count, the window total AND the percentage.+The transcript log left this list earlier, andthe entry that used to sit here was wrong twice over: it named `updates.jsonl`, when the readableconversation is its sibling `chat_history.jsonl`, and it said the gap blocked context links, whichhave since shipped off a fixture cut from a real session. Recipes for both, and for the `spawn_subagent` payload, are@@ -331,7 +332,7 @@ ai-name / comments).| 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 |+| 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 || 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 |@@ -360,11 +361,21 @@ ai-name / comments).`Notification`, if grok emits one — detected from its **message** text (orca's four phrases), sincenothing in either source names an idle *type*. No watchdog was built; checklist **9** measures howbad it feels, which is the input to deciding whether one is worth it.-3. **The phone's per-node "what it's doing now" activity line does not work for grok.**- `recordRawToolEvent` gates on `payload.hook_event_name === 'PreToolUse'`, which grok's file hooks- never send, so calling it from the grok branch was a no-op and was deleted. Making it work needs a- grok **tool vocabulary** (`run_terminal_command`, `read_file`, `search_replace`, …) in- `agent-status-mirror.ts`'s `toolActivity`; feeding it claude's names would print nonsense.+3. ~~The phone's per-node "what it's doing now" activity line does not work for grok.~~ **CLOSED,+ and the stated cause was wrong.** This said grok's file hooks "never send `PreToolUse`", so the+ `recordRawToolEvent` call was a no-op and was deleted. Measured on 1.0.13 (2026-09-02): grok DOES+ publish the event — it spells it **`pre_tool_use`**, its own snake_case, in both field dialects —+ and `recordRawToolEvent` gates on the exact string `PreToolUse`. The blocker was a SPELLING, not+ an absence, which is exactly why deleting the call looked correct and closed the door on a working+ feature for good. The shells now translate at the boundary (where `grokRawFields` already decodes+ grok's dialect) rather than loosening a claude-shaped gate. The **tool vocabulary** it needed is+ in `toolActivity` and is measured, not derived from the docs: the fifteen names in+ `signals.json.toolsUsed` across 22 real sessions. Only two argument keys were ever seen in a+ captured payload (`read_file.target_file`, `run_terminal_command.command`), so those two lines+ carry a detail and the other thirteen name the action and stop — a phrase with no detail is+ honest; one built on a guessed key renders wrong forever. Note grok's names collide with claude's+ by CASE alone in two places (`grep`/`Grep`, `write`/`Write`), so that switch must stay+ case-sensitive.4. **A remote (SSH) grok node's session name never resolves.** The shells build the session directoryfrom the **local** `grokSessionsDir()` while the payload's `cwd` came from the host. It degradessafely — a wrong name is never produced, only no name — but it is a real asymmetry: claude's leg@@ -501,9 +512,12 @@ Session identity + restorean app restart the session NAME will not resolve until that session's next hook (§8.5).Fixtures the unbuilt features need, modes, restart-17. CAPTURE `signals.json` from a live session (Task 5 Step 1): note `/session-info`'s used and- total tokens first, then find the keys holding those two numbers. If NO total appears in- signals.json or summary.json, record that — no window means no context meter, ever.+17. ~~CAPTURE `signals.json` from a live session.~~ **DONE, 22 sessions (1.0.13, 2026-09-02).** The+ keys are `contextTokensUsed`, `contextWindowTokens` and `contextWindowUsage`; a total DOES+ appear, in all 22. Fixture at `core/__fixtures__/grok/signals.json`, survey in+ `evidence/grok-signals.txt`. What a NEW device should still check is the opposite case this item+ was written for: a session whose signals.json lacks `contextWindowTokens` (a future grok, an+ interrupted write). The meter must then vanish, not fall back to a guessed window.18. Settings → Agents → Auto: does the launched command carry `--permission-mode auto`, on amachine WITHOUT claude installed? (The claude gate must not touch grok.)19. Does `--permission-mode acceptEdits` launch cleanly, and what does grok actually do with it@@ -546,14 +560,17 @@ SSHtreatment `SshProjectManager.connect` uses for the remote `claude --version`.Surfaces-27. Server Edition in a browser: grok badges, unread dot, no context meter, notch N/A. Also- confirm the node title does NOT adopt grok's session name there (readSessionName is stubbed).-28. Phone: does a grok node appear in the inbox with the right state? Its "what it's doing now"- activity line will be absent (§8.3).+27. Server Edition in a browser: grok badges, unread dot, notch N/A — and now a context meter too+ (both shells create the signals.json tail). Also confirm the node title does NOT adopt grok's+ session name there (readSessionName is stubbed).+28. Phone: does a grok node appear in the inbox with the right state, AND does its "what it's doing+ now" line now read grok's own phrases ("Reading fichero.txt", "Searching the code")? That line+ was absent until the `pre_tool_use` spelling was translated at the shells (§8.3). A claude phrase+ or a bare tool name appearing there means the vocabulary was bypassed.29. macOS notch: does the grok mark pulse and bloom while it works, on the black capsule, next toclaude's walking critter without looking out of place?-30. Kanban board + card modal: badges and the 💬 comments panel on a grok card (the meter row has- nothing to show).+30. Kanban board + card modal: badges, the 💬 comments panel, and the meter row — which now HAS+ something to show on a grok card.Two traps with no code fix — appended so the numbering above stays stable31. `echo $GROK_HOME` in a nodeterm terminal, then check where the hook file actually went. The appdiff --git a/src/core/__fixtures__/grok/signals.json b/src/core/__fixtures__/grok/signals.jsonnew file mode 100644index 000000000..e93453309--- /dev/null+++ b/src/core/__fixtures__/grok/signals.json@@ -0,0 +1,79 @@+{+ "turnCount": 21,+ "userMessageCount": 21,+ "assistantMessageCount": 137,+ "errorCount": 2,+ "toolFailureCount": 2,+ "cancellationCount": 0,+ "consecutiveCancellations": 0,+ "regenerationCount": 0,+ "hasReverted": false,+ "compactionCount": 0,+ "totalTokensBeforeCompaction": 0,+ "contextWindowUsage": 76,+ "contextTokensUsed": 381615,+ "contextWindowTokens": 500000,+ "toolCallCount": 305,+ "toolsUsed": [+ "read_file",+ "list_dir",+ "web_search",+ "run_terminal_command",+ "todo_write",+ "write",+ "search_replace",+ "get_command_or_subagent_output",+ "kill_command_or_subagent",+ "web_fetch"+ ],+ "modelsUsed": [+ "grok-4.6"+ ],+ "primaryModelId": "grok-4.6",+ "editAndRetryCount": 0,+ "bashBareEchoCount": 0,+ "gitCommitCount": 0,+ "prCreatedCount": 0,+ "prMergedCount": 0,+ "inferenceIdleTimeouts": 0,+ "doomLoopRecoveryAttempts": 0,+ "doomLoopRecoveryAcceptedAfterBudget": 0,+ "doomLoopRecoveryTopTrigger": "",+ "doomLoopRecoveryAbortedChunks": 0,+ "inferenceIdleTimeoutConfiguredSecs": 3600,+ "gcsQueueEnqueued": 0,+ "gcsQueueUploaded": 0,+ "gcsQueueFailed": 0,+ "gcsQueueFallbacks": 0,+ "gcsQueueCircuitBreakerTrips": 0,+ "gcsQueuePending": 0,+ "gcsQueuePendingBytes": 0,+ "gcsQueueOrphansCleaned": 0,+ "positiveRatings": 0,+ "negativeRatings": 0,+ "longPausesCount": 17,+ "sessionDurationSeconds": 57514,+ "avgTimeToFirstTokenMs": 13556,+ "avgResponseTimeMs": 24840,+ "minTimeToFirstTokenMs": 941,+ "maxTimeToFirstTokenMs": 78813,+ "latencySampleCount": 45,+ "itlP50Ms": 0,+ "itlP99Ms": 125,+ "itlMaxMs": 263,+ "itlMeanMs": 17,+ "totalChunkCount": 6253,+ "itlSampleCount": 45,+ "agentLinesAdded": 0,+ "agentLinesRemoved": 0,+ "agentLinesAddedReverted": 0,+ "agentLinesRemovedReverted": 0,+ "humanLinesAdded": 0,+ "humanLinesRemoved": 0,+ "humanLinesAddedReverted": 0,+ "humanLinesRemovedReverted": 0,+ "agentFilesTouched": 0,+ "humanFilesTouched": 0,+ "totalFilesTouched": 0,+ "peakRssBytes": 145391616+}diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.tsindex 44f2f34bd..2cf7706bb 100644--- a/src/core/agent-status-mirror.test.ts+++ b/src/core/agent-status-mirror.test.ts@@ -846,6 +846,47 @@ describe('activity mapping (toolActivity + recordRawToolEvent)', () => {expect(toolActivity('CustomThing', {})).toBe('Using CustomThing')})+ it("maps grok's OWN tool names, which are measured and not claude's", () => {+ // The fifteen names come from `signals.json.toolsUsed` across 22 real sessions, not from the+ // docs. Only two argument keys were ever seen in a captured payload, so only two lines carry a+ // detail — the rest name the action and stop rather than read a key nobody has observed.+ expect(toolActivity('read_file', { target_file: 'src/app/fichero.txt' })).toBe('Reading fichero.txt')+ expect(toolActivity('run_terminal_command', { command: 'echo hola' })).toBe('Running echo hola')+ expect(toolActivity('search_replace', {})).toBe('Editing a file')+ expect(toolActivity('write', {})).toBe('Writing a file')+ expect(toolActivity('list_dir', {})).toBe('Listing a directory')+ expect(toolActivity('grep', {})).toBe('Searching the code')+ expect(toolActivity('web_search', {})).toBe('Searching the web')+ expect(toolActivity('web_fetch', {})).toBe('Fetching a page')+ expect(toolActivity('todo_write', {})).toBe('Updating its plan')+ expect(toolActivity('spawn_subagent', {})).toBe('Delegating to a subagent')+ expect(toolActivity('get_command_or_subagent_output', {})).toBe('Checking a background task')+ expect(toolActivity('kill_command_or_subagent', {})).toBe('Stopping a background task')+ expect(toolActivity('search_tool', {})).toBe('Looking up an MCP tool')+ expect(toolActivity('ask_user_question', {})).toBe('Asking you a question')+ expect(toolActivity('exit_plan_mode', {})).toBe('Presenting a plan')+ })++ it('never confuses the two vocabularies, which differ only by case in three places', () => {+ // `grep`/`Grep` and `write`/`Write` are the same word. If anyone adds case-folding to that+ // switch, these four expectations disagree — which is the point: folding them would read grok's+ // argument keys out of a claude payload and vice versa.+ expect(toolActivity('grep', { pattern: 'foo' })).toBe('Searching the code')+ expect(toolActivity('Grep', { pattern: 'foo' })).toBe('Searching foo')+ expect(toolActivity('write', { file_path: '/a/b.ts' })).toBe('Writing a file')+ expect(toolActivity('Write', { file_path: '/a/b.ts' })).toBe('Editing b.ts')+ })++ it('names an MCP call by its tool AND its server, from the string itself', () => {+ // grok resolves an MCP call to `server__tool` before the hook fires; its own dispatcher never+ // appears. Deriving this from the name means no vocabulary to keep in sync with any server.+ expect(toolActivity('linear__save_issue', {})).toBe('Using save_issue (linear)')+ expect(toolActivity('iria-corpus__search', {})).toBe('Using search (iria-corpus)')+ // Not an MCP shape: unchanged.+ expect(toolActivity('CustomThing', {})).toBe('Using CustomThing')+ expect(toolActivity('__weird', {})).toBe('Using __weird')+ })+it('truncates a long Bash command', () => {const long = 'echo ' + 'a'.repeat(200)const out = toolActivity('Bash', { command: long })@@ -854,6 +895,25 @@ describe('activity mapping (toolActivity + recordRawToolEvent)', () => {expect(out.endsWith('…')).toBe(true)})+ it("shows a grok node's activity, translated at the shell boundary", () => {+ // The shells translate grok's `pre_tool_use` into the string this gate wants. What this pins is+ // the OTHER half: given that translation, the line is grok's own phrase and grok's own tool+ // name, never a claude one. §8.3 of docs/grok-agent.md claimed grok never sends the event; it+ // does, spelled `pre_tool_use`, and the gate below wants `PreToolUse` — a spelling, not an+ // absence, which is why the original call looked like dead code and was deleted.+ recordRawToolEvent('n-grok', {+ hook_event_name: 'PreToolUse',+ tool_name: 'read_file',+ tool_input: { target_file: '/w/src/fichero.txt' }+ })+ expect(_inboxSnapshot().nodes['n-grok']).toMatchObject({+ activity: 'Reading fichero.txt',+ tool: 'read_file'+ })+ recordRawToolEvent('n-grok', { hook_event_name: 'Stop' })+ expect(_inboxSnapshot().nodes['n-grok']?.activity ?? '').toBe('')+ })+it('records activity on PreToolUse and clears it on Stop/SessionEnd', () => {recordRawToolEvent('n1', { hook_event_name: 'PreToolUse', tool_name: 'Bash', tool_input: { command: 'ls -la' } })expect(_inboxSnapshot().nodes.n1).toMatchObject({ activity: 'Running ls -la', tool: 'Bash' })diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.tsindex 4601a827e..12f6f0121 100644--- a/src/core/agent-status-mirror.ts+++ b/src/core/agent-status-mirror.ts@@ -538,12 +538,74 @@ function basename(p: string): string {/*** Map a raw hook tool invocation to a human "what it's doing now" line (spec: mobile-usage-inbox).* Pure; clipped to INBOX_ACTIVITY_MAX. Unknown tools fall back to "Using <tool>".+ *+ * TWO VOCABULARIES, one function. Claude's names are PascalCase (`Read`, `Bash`) and grok's are+ * snake_case (`read_file`, `run_terminal_command`), so they cannot collide and no agent id is needed+ * to tell them apart — but only while the match stays EXACT. Do not add case-folding here: `grep`+ * and `Grep`, `write` and `Write` differ by case alone, and folding them would silently read grok's+ * argument keys out of a claude payload.+ *+ * The grok names are MEASURED, not derived from the docs: `signals.json.toolsUsed` across 22 real+ * sessions (grok 1.0.13, 2026-09-02) yields exactly fifteen. Their ARGUMENT keys are a separate+ * question and only two were seen in captured hook payloads — `read_file.target_file` and+ * `run_terminal_command.command`. Every other grok case below therefore names the action and stops,+ * rather than reading a key nobody has observed: a phrase with no detail is honest, a phrase built+ * on a guessed key renders "Editing file" forever the day the guess is wrong.*/export function toolActivity(toolName: string, toolInput: Record<string, unknown> | undefined): string {const ti = toolInput ?? {}const str = (v: unknown): string => (typeof v === 'string' ? v : '')let out: stringswitch (toolName) {+ // ---- grok (snake_case). MEASURED argument keys only. ----+ case 'read_file':+ out = `Reading ${basename(str(ti.target_file)) || 'file'}`+ break+ case 'run_terminal_command': {+ const cmd = str(ti.command).replace(/\s+/g, ' ').trim()+ out = `Running ${cmd ? clip(cmd, 60) : 'command'}`+ break+ }+ case 'search_replace':+ out = 'Editing a file'+ break+ case 'write':+ out = 'Writing a file'+ break+ case 'list_dir':+ out = 'Listing a directory'+ break+ case 'grep':+ out = 'Searching the code'+ break+ case 'web_search':+ out = 'Searching the web'+ break+ case 'web_fetch':+ out = 'Fetching a page'+ break+ case 'todo_write':+ out = 'Updating its plan'+ break+ case 'spawn_subagent':+ out = 'Delegating to a subagent'+ break+ case 'get_command_or_subagent_output':+ out = 'Checking a background task'+ break+ case 'kill_command_or_subagent':+ out = 'Stopping a background task'+ break+ case 'search_tool':+ out = 'Looking up an MCP tool'+ break+ case 'ask_user_question':+ out = 'Asking you a question'+ break+ case 'exit_plan_mode':+ out = 'Presenting a plan'+ break+ // ---- claude (PascalCase) ----case 'Edit':case 'Write':case 'MultiEdit':@@ -582,7 +644,14 @@ export function toolActivity(toolName: string, toolInput: Record<string, unknownout = `Fetching ${str(ti.query) || '…'}`breakdefault:- out = `Using ${toolName}`+ // A qualified MCP name is `server__tool` — grok's own dispatcher (`use_tool`) never appears in+ // a payload, the resolved call does (10-hooks.md). Naming the tool and its server is more use+ // than either half alone, and it is derived from the string itself, so no vocabulary can go+ // stale. Everything else keeps the historical "Using <tool>".+ {+ const mcp = /^([A-Za-z0-9_.-]+)__([A-Za-z0-9_.-]+)$/.exec(toolName)+ out = mcp ? `Using ${mcp[2]} (${mcp[1]})` : `Using ${toolName}`+ }}return clip(out, INBOX_ACTIVITY_MAX)}diff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.tsindex d0e7bb8ec..2c298bfb7 100644--- a/src/core/context-tail.test.ts+++ b/src/core/context-tail.test.ts@@ -212,3 +212,47 @@ describe('hasToolResult (the declined-ask rescue)', () => {expect(hasToolResult('{"type":"user","message":{"content":[{"type":"tool_res')).toBe(false)})})++describe('createContextTail — `wholeFile` (grok: a document rewritten, not appended)', () => {+ // grok's numbers live in signals.json, which it REWRITES on every turn. The default offset read+ // hands the parser only the bytes past the previous read — a fragment of a JSON document, which+ // never parses. The meter would fill once and then freeze, with nothing anywhere saying why.+ const signals = (used: number): string =>+ JSON.stringify({ contextTokensUsed: used, contextWindowTokens: 500000, primaryModelId: 'grok-4.6' })++ /** grok's real parser shape: the WHOLE buffer must be valid JSON. */+ const parse = (text: string | string[]) => {+ try {+ const o = JSON.parse(Array.isArray(text) ? text.join('\n') : text)+ return { used: o.contextTokensUsed, window: o.contextWindowTokens, model: o.primaryModelId }+ } catch {+ return null+ }+ }++ async function pushesAfterRewrite(opts: { wholeFile?: boolean }): Promise<unknown[]> {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-whole-'))+ const file = path.join(dir, 'signals.json')+ // First document, then a LONGER one — longer matters: a shorter file trips the existing+ // truncation reset and would re-read from zero by accident, hiding the bug.+ fs.writeFileSync(file, signals(1000))+ const send = vi.fn()+ const tail = createContextTail(send, { parse, ...opts })+ tail.track('s1', file)+ await new Promise((r) => setTimeout(r, 300))+ fs.writeFileSync(file, signals(222222) + ' ')+ await new Promise((r) => setTimeout(r, 1300))+ tail.untrack('s1')+ return send.mock.calls.map((c) => c[0])+ }++ it('keeps reading the rewritten document', async () => {+ const pushes = await pushesAfterRewrite({ wholeFile: true })+ expect(JSON.stringify(pushes)).toContain('222222')+ }, 8000)++ it('WITHOUT it, the second read never parses — the silent freeze this flag exists for', async () => {+ const pushes = await pushesAfterRewrite({})+ expect(JSON.stringify(pushes)).not.toContain('222222')+ }, 8000)+})diff --git a/src/core/context-tail.ts b/src/core/context-tail.tsindex c933496ff..60990b42a 100644--- a/src/core/context-tail.ts+++ b/src/core/context-tail.ts@@ -157,6 +157,16 @@ export interface ContextTailOptions {parse?: (text: string | string[]) => { used: number; window?: number | null; model: string | null } | null+ /**+ * Re-read the tracked file from byte 0 on every tick instead of tailing an offset.+ *+ * For grok, whose numbers live in `signals.json` — a whole JSON document REWRITTEN in place, not a+ * JSONL appended to. An offset read hands the parser the bytes that happen to sit past the last+ * read, which is a fragment of JSON and never parses. The meter would fill on the first tick and+ * then freeze, with nothing anywhere to say why: exactly the silent-degrade shape this codebase+ * keeps paying for. The file is a few KB, so re-reading it whole costs nothing worth optimizing.+ */+ wholeFile?: boolean}interface Tracked {@@ -234,6 +244,8 @@ export function createContextTail(}if (size >= 0) {const before = t.offset+ // A rewritten-in-place document has no meaningful offset: only the whole file parses.+ if (opts?.wholeFile) t.offset = 0if (size < t.offset) t.offset = 0 // truncated/rotated → re-read from start// First read of a large transcript: skip to the last INITIAL_READ_CAP bytes.if (t.offset === 0 && size > INITIAL_READ_CAP) t.offset = size - INITIAL_READ_CAPdiff --git a/src/core/grok-signals.test.ts b/src/core/grok-signals.test.tsnew file mode 100644index 000000000..c1927ea72--- /dev/null+++ b/src/core/grok-signals.test.ts@@ -0,0 +1,89 @@+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import path from 'path'+import { grokSignalsParse, grokContextParse } from './grok-signals'++// Captured whole from a real session (grok 1.0.13). Kept entire rather than trimmed to the three+// keys we read: the point of the fixture is to prove the reader ignores the other 63.+const RAW = fs.readFileSync(path.join(__dirname, '__fixtures__/grok/signals.json'), 'utf8')++describe('grokSignalsParse', () => {+ it('reads the numerator and the denominator grok states', () => {+ const r = grokSignalsParse(RAW)+ expect(r).not.toBeNull()+ expect(r!.used).toBe(381615)+ expect(r!.window).toBe(500000)+ expect(r!.model).toBe('grok-4.6')+ })++ it("agrees with grok's OWN percentage — the oracle this agent gives us for free", () => {+ // grok is the only agent that states the answer as well as both operands. If our arithmetic+ // ever disagrees with its `contextWindowUsage`, one of the two changed: a rounding rule, a key+ // meaning, a new denominator. This test is what makes that a failure instead of a meter quietly+ // off by a percent.+ const r = grokSignalsParse(RAW)!+ expect(r.statedPercent).toBe(76)+ expect(Math.floor((r.used / r.window) * 100)).toBe(r.statedPercent)+ })++ it('returns null when the WINDOW is missing — no denominator, no meter', () => {+ // The degrade rule, and the mutation target: a meter drawn against a guessed window is a wrong+ // number presented as a fact. Nothing here may fall back to a window inferred from the model.+ const o = JSON.parse(RAW)+ delete o.contextWindowTokens+ expect(grokSignalsParse(JSON.stringify(o))).toBeNull()+ o.contextWindowTokens = 0+ expect(grokSignalsParse(JSON.stringify(o))).toBeNull()+ })++ it('returns null when the used count is missing or not a number', () => {+ const o = JSON.parse(RAW)+ delete o.contextTokensUsed+ expect(grokSignalsParse(JSON.stringify(o))).toBeNull()+ expect(grokSignalsParse(JSON.stringify({ ...JSON.parse(RAW), contextTokensUsed: '381615' }))).toBeNull()+ })++ it('survives junk without throwing', () => {+ expect(grokSignalsParse('')).toBeNull()+ expect(grokSignalsParse('{ truncated')).toBeNull()+ expect(grokSignalsParse('[]')).toBeNull()+ expect(grokSignalsParse('null')).toBeNull()+ })++ it('reads none of the other 63 keys', () => {+ // A metrics file grows keys. A reader that matched loosely would start reporting whatever gets+ // added next — so changing everything EXCEPT the three must change nothing.+ const o = JSON.parse(RAW)+ const before = grokSignalsParse(RAW)+ for (const k of Object.keys(o)) {+ if (k === 'contextTokensUsed' || k === 'contextWindowTokens' || k === 'contextWindowUsage')+ continue+ o[k] = typeof o[k] === 'number' ? 999999 : typeof o[k] === 'boolean' ? !o[k] : 'CHANGED'+ }+ o.somethingGrokAddsNextRelease = { nested: true }+ const after = grokSignalsParse(JSON.stringify(o))+ expect(after!.used).toBe(before!.used)+ expect(after!.window).toBe(before!.window)+ })+})++describe('grokContextParse — the shape the context tail expects', () => {+ it('matches the dep signature the other agents use', () => {+ expect(grokContextParse(RAW)).toEqual({ used: 381615, window: 500000, model: 'grok-4.6' })+ })++ it('rejoins a line array, because the tail may hand it either', () => {+ expect(grokContextParse(RAW.split('\n'))).toEqual({+ used: 381615,+ window: 500000,+ model: 'grok-4.6'+ })+ })++ it('returns null for a FRAGMENT — why the tail must read the whole file', () => {+ // signals.json is rewritten in place, not appended to. An offset read hands the parser the tail+ // end of a rewritten file, which is not valid JSON. Without `wholeFile`, the meter would fill+ // once and then freeze with nothing to say so.+ expect(grokContextParse(RAW.slice(RAW.length / 2))).toBeNull()+ })+})diff --git a/src/core/grok-signals.ts b/src/core/grok-signals.tsnew file mode 100644index 000000000..f00806a0e--- /dev/null+++ b/src/core/grok-signals.ts@@ -0,0 +1,100 @@+// grok's per-session context numbers, from `~/.grok/sessions/<cwd>/<id>/signals.json`.+//+// NOT to be confused with `core/usage/grok-usage.ts`, which is the account's weekly/monthly plan+// credit read from the billing endpoint. That is a BILLING figure for the whole account; this is the+// context window of ONE session. They are different numbers with similar names, and merging them+// would put a quota percentage on a per-node meter.+//+// The file is grok's metrics dump: 66 keys on the sessions measured (latencies, GCS queue counters,+// lines touched, peak RSS). Exactly three matter here, and nothing else is read — a metrics file is+// free to grow keys, and a reader that pattern-matches loosely would start reporting whatever gets+// added next.+import path from 'path'+import fs from 'fs'+import { grokSessionDirFor } from './grok-session'++/** grok's own name for the file. Sibling of `chat_history.jsonl` in the session directory. */+export const GROK_SIGNALS_FILE = 'signals.json'++export interface GrokContextNumbers {+ used: number+ window: number+ /** grok's OWN percentage, already computed and truncated to an integer. */+ statedPercent: number | null+ model: string | null+}++/**+ * Parse a whole `signals.json` buffer.+ *+ * MEASURED on 22 real sessions (grok 1.0.13, 2026-09-02): `contextTokensUsed` and+ * `contextWindowTokens` are present in all 22, and `contextWindowUsage` — the percentage grok has+ * already computed — matches `used/window` in all 22. That makes grok the only agent that states the+ * numerator, the denominator AND the answer.+ *+ * Returns null unless BOTH numbers are present and usable. That is the project's degrade rule and it+ * is not defensive noise: a meter drawn against a guessed window is a wrong number presented as a+ * fact, and the correct behaviour without a trustworthy denominator is NO METER. Do not add a+ * fallback window here from the model id — grok states its own, and inferring one would silently+ * replace a measured fact with a guess the day grok ships a different window.+ */+export function grokSignalsParse(buf: string): GrokContextNumbers | null {+ let o: Record<string, unknown>+ try {+ o = JSON.parse(buf) as Record<string, unknown>+ } catch {+ return null+ }+ if (!o || typeof o !== 'object') return null+ const used = o.contextTokensUsed+ const window = o.contextWindowTokens+ if (typeof used !== 'number' || !Number.isFinite(used) || used < 0) return null+ if (typeof window !== 'number' || !Number.isFinite(window) || window <= 0) return null+ const stated = o.contextWindowUsage+ const model = o.primaryModelId+ return {+ used,+ window,+ statedPercent: typeof stated === 'number' && Number.isFinite(stated) ? stated : null,+ model: typeof model === 'string' && model ? model : null+ }+}++/**+ * Shaped for `ContextTail`'s `parse` dep, which hands the reader whatever it just read.+ *+ * The tail must be created with `wholeFile: true` for grok: `signals.json` is REWRITTEN in place,+ * not appended to, so an offset read would hand this function a fragment of JSON and every parse+ * after the first would fail — silently, as a meter that filled once and then froze.+ */+export function grokContextParse(+ text: string | string[]+): { used: number; window: number | null; model: string | null } | null {+ const buf = Array.isArray(text) ? text.join('\n') : text+ const r = grokSignalsParse(buf)+ return r ? { used: r.used, window: r.window, model: r.model } : null+}++/** The signals file for a session a hook has located, or undefined. Derived, never searched — the+ * same rule `locateGrok` follows, and for the same reason: a scan keyed on anything weaker than the+ * session id can settle on another session's numbers. */+export function grokSignalsPathFor(sessionId: string | undefined): string | undefined {+ const dir = grokSessionDirFor(sessionId)+ return dir ? path.join(dir, GROK_SIGNALS_FILE) : undefined+}++/** Read and parse in one step. undefined when the session is unknown, the file is absent, or the+ * numbers are not both there. */+export async function readGrokContextNumbers(+ sessionId: string | undefined+): Promise<GrokContextNumbers | null> {+ const p = grokSignalsPathFor(sessionId)+ if (!p) return null+ let buf: string+ try {+ buf = await fs.promises.readFile(p, 'utf8')+ } catch {+ return null+ }+ return grokSignalsParse(buf)+}diff --git a/src/main/index.ts b/src/main/index.tsindex dc45cebdb..09d1f131b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -181,6 +181,7 @@ import { retainUntilDismissed } from './notifications'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 { geminiContextParse } from '../core/gemini-session'import { codexContextParse } from '../core/codex-session'import { createCodexSubagentFormatter } from '../core/codex-subagent-format'@@ -2122,6 +2123,14 @@ app.whenReady().then(async () => {// it, assigned here where the tail exists).geminiTranscriptPathFor = (sessionId) => geminiContextTail.pathFor(sessionId)const codexContextTail = createContextTail(pushContextUpdate, { parse: codexContextParse })+ // grok's third tail. `wholeFile` is not a tuning knob: signals.json is a whole JSON document+ // rewritten in place, so an offset read yields a fragment that never parses and the meter+ // would freeze after its first fill with nothing to say so. Invariant 11 — the Server+ // Edition creates the same tail the same way in src/server/agent-status.ts.+ const grokContextTail = createContextTail(pushContextUpdate, {+ parse: grokContextParse,+ wholeFile: true+ })// Remote (SSH-project) counterparts: a node whose pty runs on a remote host has its Claude// transcript on that host, so its meter / subagent transcript / search must read over the// project's ControlMaster. One RemoteFile bound to the SSH-project manager's own ssh runner@@ -2610,14 +2619,46 @@ app.whenReady().then(async () => {cwd: g.cwd,sessionId: g.sessionId})- if (dir) rememberGrokSessionDir(g.sessionId, dir)+ if (dir) {+ rememberGrokSessionDir(g.sessionId, dir)+ // Context meter: grok's numbers are NOT in the transcript, so there is nothing for+ // `transcript_path` to point at. They live in `signals.json`, the sibling of+ // `chat_history.jsonl`, so the tail is tracked from the DERIVED directory.+ grokContextTail.track(g.sessionId, join(dir, GROK_SIGNALS_FILE))+ }+ }+ // 3. node → what it is doing NOW (the phone's per-node activity line).+ //+ // §8.3 of docs/grok-agent.md said grok's file hooks "never send PreToolUse", so calling this+ // was a no-op and it was deleted. MEASURED on 1.0.13 (2026-09-02), that is wrong in wording+ // and right in effect: grok DOES publish the event, spelled `pre_tool_use` — its own+ // snake_case — and `recordRawToolEvent` gates on the exact string `PreToolUse`, so the gate+ // never matched. The blocker was a SPELLING, not an absence, which is why deleting the call+ // looked correct and closed the door on a working feature.+ //+ // Translated here rather than by loosening that gate: the mirror is claude-shaped on purpose,+ // and grok's dialect is decoded in exactly one place (`grokRawFields`). `toolActivity` knows+ // grok's fifteen tool names, so the line reads "Reading fichero.txt", never a claude phrase.+ if (nodeId && g.event === 'pretooluse' && g.toolName) {+ recordRawToolEvent(nodeId, {+ hook_event_name: 'PreToolUse',+ tool_name: g.toolName,+ tool_input: g.toolInput+ })+ }+ // The turn is over: clear the activity line the same way the claude path does.+ if (nodeId && (g.event === 'stop' || g.event === 'sessionend')) {+ recordRawToolEvent(nodeId, { hook_event_name: 'Stop' })}// The session is over, so nothing will read its directory again — and forgetting costs// nothing even though grok IS resumable and `grok --resume <id>` reuses BOTH the id and the// directory: a resumed session fires its own hooks, whose (cwd, sessionId) re-derive and// re-remember the very same path. The map is bounded, so dropping now beats waiting for// eviction to reach an entry nobody is asking about.- if (g.event === 'sessionend') forgetGrokSession(g.sessionId)+ if (g.event === 'sessionend') {+ forgetGrokSession(g.sessionId)+ grokContextTail.untrack(g.sessionId)+ }return}// gemini and codex both carry `transcript_path` in their hook envelope (gemini: the base input@@ -2802,6 +2843,7 @@ app.whenReady().then(async () => {contextTail.untrack(sessionId)geminiContextTail.untrack(sessionId)codexContextTail.untrack(sessionId)+ grokContextTail.untrack(sessionId)remoteContextTail.untrack(sessionId)remoteTranscriptBySession.delete(sessionId)locatedTranscriptSessions.delete(sessionId)diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex ad6f1c3cd..ef25359a5 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -8,7 +8,7 @@//// This module must import nothing from electron or `../main` (see no-electron.test.ts).import { grokHomeDir } from '../core/agents/grok-paths'-import { resolve } from 'path'+import { join, resolve } from 'path'import { homedir } from 'os'import { hookServer } from '../core/agents/hook-server'import { recordAgentEvent, recordRawToolEvent, recordContextUsage,@@ -18,6 +18,7 @@ import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'import { geminiContextParse } from '../core/gemini-session'import { codexContextParse } from '../core/codex-session'+import { grokContextParse, GROK_SIGNALS_FILE } from '../core/grok-signals'import { createCodexSubagentFormatter } from '../core/codex-subagent-format'import { codexHome } from '../core/usage/codex-usage'import { setNodeTranscript } from '../core/context-link'@@ -143,6 +144,13 @@ export function wireAgentStatus(// and the declined-ask rescue is claude-only too).const geminiContextTail = createContextTail(pushContextUpdate, { parse: geminiContextParse })const codexContextTail = createContextTail(pushContextUpdate, { parse: codexContextParse })+ // grok's third tail. `wholeFile` is not a tuning knob here: signals.json is a whole JSON+ // document rewritten in place, so an offset read yields a fragment that never parses and the+ // meter would freeze after its first fill with nothing to say so.+ const grokContextTail = createContextTail(pushContextUpdate, {+ parse: grokContextParse,+ wholeFile: true+ })hooks.setListener((e) => {// Record FIRST: recordAgentEvent computes the stash-priority classification and returns the@@ -202,14 +210,49 @@ export function wireAgentStatus(cwd: g.cwd,sessionId: g.sessionId})- if (dir) rememberGrokSessionDir(g.sessionId, dir)+ if (dir) {+ rememberGrokSessionDir(g.sessionId, dir)+ // Context meter: grok's numbers are NOT in the transcript, so there is nothing here for+ // `transcript_path` to point at even once grok starts sending one. They live in+ // `signals.json`, the sibling of `chat_history.jsonl`, which is why this tail is tracked+ // from the DERIVED directory rather than from a hook field — and why it is created with+ // `wholeFile` (that file is rewritten in place, not appended to).+ const signals = join(dir, GROK_SIGNALS_FILE)+ grokContextTail.track(g.sessionId, signals)+ }+ }+ // 3. node → what it is doing NOW (the phone's per-node activity line).+ //+ // §8.3 of docs/grok-agent.md said grok's file hooks "never send PreToolUse", so calling this+ // was a no-op and it was deleted. MEASURED on 1.0.13 (2026-09-02), that is wrong in wording+ // and right in effect: grok DOES publish the event, spelled `pre_tool_use` — its own+ // snake_case — and `recordRawToolEvent` gates on the exact string `PreToolUse`, so the gate+ // never matched. The blocker was a SPELLING, not an absence, which is why deleting the call+ // looked correct and closed the door on a working feature.+ //+ // Translated here rather than by loosening that gate: the mirror is claude-shaped on purpose,+ // and grok's dialect is decoded in exactly one place (`grokRawFields`). `toolActivity` knows+ // grok's fifteen tool names, so the line reads "Reading fichero.txt", never a claude phrase.+ if (nodeId && g.event === 'pretooluse' && g.toolName) {+ recordRawToolEvent(nodeId, {+ hook_event_name: 'PreToolUse',+ tool_name: g.toolName,+ tool_input: g.toolInput+ })+ }+ // The turn is over: clear the activity line the same way the claude path does.+ if (nodeId && (g.event === 'stop' || g.event === 'sessionend')) {+ recordRawToolEvent(nodeId, { hook_event_name: 'Stop' })}// The session is over, so nothing will read its directory again — and forgetting costs// nothing even though grok IS resumable and `grok --resume <id>` reuses BOTH the id and the// directory: a resumed session fires its own hooks, whose (cwd, sessionId) re-derive and// re-remember the very same path. The map is bounded, so dropping now beats waiting for// eviction to reach an entry nobody is asking about.- if (g.event === 'sessionend') forgetGrokSession(g.sessionId)+ if (g.event === 'sessionend') {+ forgetGrokSession(g.sessionId)+ grokContextTail.untrack(g.sessionId)+ }return}// gemini and codex both carry `transcript_path` in their hook envelope (gemini: the base input@@ -323,6 +366,7 @@ export function wireAgentStatus(contextTail.untrack(sessionId)geminiContextTail.untrack(sessionId)codexContextTail.untrack(sessionId)+ grokContextTail.untrack(sessionId)nodeContextSession.delete(nodeId)}const subs = nodeSubagents.get(nodeId)diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex 4f0e61511..5fa224c7f 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -212,8 +212,25 @@ describe('grok capabilities', () => {expect(readsClaudeShapedTranscript('claude')).toBe(true)})+ it('fills a context meter from the numbers it states itself', () => {+ // grok states the numerator, the denominator AND the percentage (signals.json). The window is+ // read, never inferred from the model id — which puts grok with codex, not with gemini.+ expect(hasUsage('grok')).toBe(true)+ })++ it('joins USAGE_CAPABLE without joining the claude-transcript readers', () => {+ // The regression this project already survived once: `hasUsage` gated THREE features, and+ // joining it for the meter also switched on `context.ensure` and the find bar's index, both of+ // which resolve through claude's `resolveTranscript` — whose cwd fallback then hands the node+ // the newest CLAUDE transcript for that directory. A codex node metered and searched a+ // stranger's session, and the preconditions were default-true, so it would have shipped.+ //+ // These two must therefore DISAGREE for grok, exactly as they do for codex and gemini.+ expect(hasUsage('grok')).toBe(true)+ expect(readsClaudeShapedTranscript('grok')).toBe(false)+ })+it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {- expect(hasUsage('grok')).toBe(false)expect(canBranch('grok')).toBe(false)expect(canSubagent('grok')).toBe(false)})diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex aee818a99..576190b9c 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -150,9 +150,25 @@ export const CONTEXT_LINK_CAPABLE = ['claude', 'codex', 'gemini', 'opencode', 'g// - gemini: states none, so the window comes from its model id through `geminiWindowFor`, which// mirrors the CLI's OWN `tokenLimit(model)` — a family rule with a 1M catch-all default, so a// model we have never heard of still gets the right answer rather than a stale guess.-// grok is absent: its `updates.jsonl` parser is unbuilt (see docs/grok-agent.md), so there is no-// used count to divide.-export const USAGE_CAPABLE = ['claude', 'codex', 'gemini'] as const+// - grok: states BOTH numbers and the answer. `contextTokensUsed` and `contextWindowTokens` sit in+// `~/.grok/sessions/<cwd>/<id>/signals.json`, alongside `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. So the window is read,+// never inferred from the model id, which puts grok with codex rather than with gemini.+//+// Until 2026-09 this comment explained grok's absence by pointing at a missing parser for the wrong+// file, and concluding there was no used count to divide. Both halves were false, and the first is+// the one worth remembering: the counters never lived in the file it named, so the blocker it+// declared was not the real blocker even on the day it was written. A comment that explains an+// absence with a false cause is worse than no comment — it sends the next reader to build a parser+// nobody needed. What let it survive is that nobody could check it: the integration was written with+// no grok binary on the machine.+//+// signals.json is a METRICS file (66 keys: latencies, GCS queue counters, lines touched, peak RSS).+// `core/grok-signals.ts` reads exactly three of them and nothing else. If a future grok drops+// `contextWindowTokens`, that reader returns null and the meter disappears — no inferred+// denominator, because a percentage over a guessed window is a wrong number presented as a fact.+export const USAGE_CAPABLE = ['claude', 'codex', 'gemini', 'grok'] as const// Agents whose structured transcript we can render as a chat panel (Cmd+M chat mode).//// SPLIT from CLAUDE_TRANSCRIPT_READABLE below on 2026-09-02, when grok joined. Until then this one