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): subscribe to the whole published hook set, and stop the badge sticking on Esc

Xavi Guardiacb81f7b92246
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index 573cda909..5803b1d75 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -83,12 +83,11 @@ another integration's reader, not from grok's own documentation.
| turn-end reason | — | `reason` (`end_turn` \| `channel_closed` \| `shutdown`) | same |
| also on every event | — | `timestamp`, `permissionMode` | same |
-† **The `Notification` payload is the one row with no documented source.** Grok's docs describe the
-event but not its body, so the three key spellings — plus the `message` and `level` fields the mapping
-in §5 reads — come from **orca** (`/root/orca-main`, MIT, a shipping grok integration):
-`notificationType ?? notification_type ?? type` at `src/shared/agent-hook-listener.ts:2370-2376`,
-`message`/`level` at `:3973-3975`. Treat every Notification claim in this document as inference from
-that reader until checklist **10** replaces it with a capture.
+† Grok 1.0.13 publishes the `Notification` type vocabulary as `idle_prompt`, `permission_prompt`,
+and `task_complete` (`~/.grok/docs/user-guide/10-hooks.md:99`), and states that
+`permission_prompt` fires only while a permission UI is actually waiting (`:162`). The payload key
+aliases remain defensive: file hooks use `notificationType`, the SDK uses `notification_type`, and
+the bare `type` fallback comes from orca's reader (`src/shared/agent-hook-listener.ts:2370-2376`).
Consequences, in the order they bite:
@@ -108,30 +107,33 @@ Consequences, in the order they bite:
adopting another node's name. `grokSessionDir` returns `null` (learn nothing) rather than half a
path when either half is unusable.
-The nine subscribed events map as follows (`normalizeGrok`); everything else returns `null`, a
-deliberate no-op:
+All 15 events published by Grok 1.0.13 are subscribed. They map as follows (`normalizeGrok`);
+unrecognized values inside a closed matcher vocabulary return `null`, a deliberate no-op:
| grok event | `NormalizedAgentEvent` | note |
|---|---|---|
| `SessionStart` / `SessionEnd` | session `start` / `end` | `SessionEnd` also drops the session's remembered directory |
| `UserPromptSubmit` | `working`, `newTurn: true` | the turn start; `newTurn` is what clears per-turn fan-out once per turn |
| `PreToolUse` / `PostToolUse` / `PostToolUseFailure` | `working` | a **failed** tool is still mid-turn — grok fires `PostToolUseFailure` and carries on |
+| `PermissionDenied` | `working` | post-decision event: the denied tool did not end the turn, and the permission UI is no longer waiting |
| `Stop` (`reason` anything but `channel_closed`/`shutdown`) | `done` + `lastMessage` | a **denylist**, not an allowlist of `end_turn`: `Stop` is the event the RUNNING badge depends on ending, so an unknown reason must fail towards reporting it |
| `Stop` (`channel_closed` / `shutdown`) | `done`, `interrupted: true` | the observe-only second `Stop` at session close; `interrupted` suppresses the completion alert and unread dot, and the stale `lastAssistantMessage` is dropped |
| `StopFailure` | `done` + `lastMessage` | fires **instead of** `Stop` when the turn dies on an API error — without it the badge sticks |
-| `Notification` `permission_prompt` + message `tool permission requested` + level `info`/absent | **nothing** (`null`) | grok emits this before **every** tool call, even under `bypassPermissions` (orca's `isGrokRoutinePermissionPromptNotification`, `agent-hook-listener.ts:2378-2389`). The type is canonicalized first (`grokCanonical`, the same letters-only rule the event name uses), so the camelCase spelling grok's envelope would plausibly carry — `permissionPrompt` — is suppressed too; comparing raw would drop it into the ask row below and reinstate the strobe. Mapping it to `blocked` fired `markUnread` with no cooldown, the needs-you chime, an OS notification per tool call while unfocused, and a phone inbox card per `working→blocked` edge. Matched exactly, so a **louder** prompt with the same type still gets through |
-| `Notification` `*permission*` / `approval_required` | `blocked` | substring for the permission family (its worst case is a badge the next hook clears), plus `approval_required` — which is **inference on inference**: `05-configuration.md:414` names it as a notification *trigger*, not as a `notificationType` value, and the bridge is `10-hooks.md:153` ("the matcher tests … the notification type on `Notification`"). Matched exactly for that reason. The two spellings share no substring, and matching both is what keeps this mapping from firing for nothing under either vocabulary |
-| `Notification` `elicitation_dialog` / `agent_needs_input` | `waiting` | a **closed set**, exactly as in `normalizeClaude`: a substring test on `elicit` would also match claude's informational `elicitation_complete`/`_response` and leave NEEDS YOU on a node that just finished, with no later hook to clear it |
-| `Notification` whose **message** reads idle (`type your message`, `enter send`, `shift-tab normal`, `ask a side question`; `*idle*` type as a fallback) | `done`, `interrupted`, `idle` | the **rescue** signal for a node stuck on `working` — see §8. Keyed on the MESSAGE because that is where grok states it (orca's `isGrokIdleNotification`, `:2391-2402`); a type-only test never fired, since no source names an "idle" type. Checked **after** the ask branches, mirroring orca's own precedence (`:3994-4012`) |
+| `StopCancelled` (`user_interrupt`, session-level) | `done`, `interrupted` | clears RUNNING without an ordinary completion alert/unread |
+| `StopCancelled` (`permission_rejected`, `permission_cancelled`, `max_turns`, `no_progress`) | `done` | visible non-interrupted terminal outcome; exact closed reasons only |
+| `StopCancelled` with `subagentType`, or reason `unknown` | **no state change** | a child stop is not the session stop; unknown stays no-op so a future busy/cancel dialect cannot become a false completion |
+| `Notification` `permission_prompt` | `blocked` | exact published type; Grok says it fires **only** while a permission UI is waiting (`10-hooks.md:162`) |
+| `Notification` `idle_prompt` | `done`, `interrupted`, `idle` | exact published type (`10-hooks.md:99`); reuses the mirror's `idleInferred` rescue, so it only clears `working` and cannot erase a live approval |
+| `Notification` `task_complete` | **nothing** (`null`) | published as a user-attention type, but the spec does not say it closes a turn; `Stop` remains the turn-end signal, so guessing `done` here would risk a false completion |
+| any other `Notification` type | **nothing** (`null`) | closed-set default: a future permission-like name must not leave a sticky NEEDS YOU badge |
+| `SubagentStart` / `SubagentStop` | subagent `start` / `end` | child lifecycle only; no invented instance id and no parent-session state transition (`SubagentEnd` is Grok's accepted alias of `SubagentStop`) |
+| `PreCompact` / `PostCompact` | compaction `pre` / `post` | no badge transition; the raw listener replaces the remembered session association when `PostCompact` carries the newly minted id |
`Stop` fires **once per turn plus once at close** — N+1 times in an N-turn session, the last one
observe-only — and interrupted / refused / max-turns turns **skip `Stop` hooks entirely**.
-Not subscribed in v1: `PermissionDenied`, `SubagentStart`, `SubagentStop`, `PreCompact`,
-`PostCompact` — documented exactly as the nine are, but with nothing here to consume them (a
-post-decision event, subagent cards grok does not have, compaction nobody reads). Grok skips hook
-event names it does not recognize (that is how a shared Claude settings file loads at all), so adding
-one later is safe.
+The configuration uses Grok's canonical `SubagentStop` spelling. Grok also accepts `SubagentEnd` as
+an alias, but subscribing twice would only duplicate the same lifecycle signal.
---
@@ -180,9 +182,10 @@ without status hooks.
Grok also merges **`~/.claude/settings.json`** (and `settings.local.json`, `~/.cursor/hooks.json`,
project `.grok/hooks/*.json`). nodeterm's **claude** managed hook already lives in that file. So
-**8 of grok's 9 events** also fire `claude.sh` and POST to `/hook/claude` — every one except
-`PostToolUseFailure`, which claude has no entry for (`CLAUDE_HOOK_EVENTS`). This is by design left
-alone — we do not disable grok's `[compat.claude]` scanning, because it is the user's config and it
+**8 of Grok's 15 events** also fire `claude.sh` and POST to `/hook/claude`: `SessionStart`,
+`UserPromptSubmit`, `PreToolUse`, `PostToolUse`, `Stop`, `StopFailure`, `Notification`, and
+`SessionEnd` — the intersection with `CLAUDE_HOOK_EVENTS`. This is by design left alone — we do not
+disable grok's `[compat.claude]` scanning, because it is the user's config and it
is what makes our skills discoverable (§1), and we do not add a cross-agent guard to the shared
managed script, because `pty-manager` passes `options.agentId ?? 'claude'` — `NODETERM_AGENT_ID` is
`claude` for **plain terminal** nodes too, and a guard keyed on it would kill status for anyone who
@@ -356,7 +359,25 @@ ai-name / comments).
## 8. Known gaps and follow-ups
-**Gaps in what shipped** — state these, do not paper over them:
+**Verified corrections to the original assumptions:**
+
+1. **The `Notification` vocabulary is published and closed.** Grok 1.0.13 names `idle_prompt`,
+ `permission_prompt`, and `task_complete` in `~/.grok/docs/user-guide/10-hooks.md:99`; `:162`
+ explicitly says `permission_prompt` fires only while a permission UI is actually waiting. The
+ normalizer therefore maps that exact type to `blocked`, maps exact `idle_prompt` through the
+ existing `idleInferred` rescue, and treats `task_complete` as informational because the spec does
+ not define it as a turn end (`Stop` does). Every unknown type is a no-op; no substring widens the
+ permission set.
+2. **The earlier Esc gap was based on a false premise; no watchdog is needed.** Grok 1.0.13
+ publishes `StopCancelled` for turns that end without `Stop` (`10-hooks.md:98,336,348,354,384`). A
+ session-level `user_interrupt` now clears RUNNING as an interrupted `done`; permission rejection
+ or cancellation, `max_turns`, and `no_progress` are visible non-interrupted turn ends. A payload
+ carrying `subagentType` cannot end the parent session, and an unknown reason is a closed-set
+ no-op. Cancel-and-send emits no `StopCancelled` because the replacement turn stays busy. Exact
+ `idle_prompt` remains as a bounded rescue for the documented case where no stop hook completes:
+ it can clear only `working`, never a live approval or question.
+
+**Remaining gaps — state these, do not paper over them:**
1. **The `Notification` vocabulary is unverified, and it can fail in BOTH directions.** Grok documents
no hook for "a permission prompt is on screen" — claude's `PermissionRequest` has no counterpart, and
@@ -500,22 +521,16 @@ Env + identity
only ever comes from /hook/grok — no flicker, no duplicate completion notification.
State machine edges
- 9. Press Esc mid-turn. Expected (documented): NO hook fires and the badge stays RUNNING until
- the next prompt. Confirm, and record how bad it feels — this decides whether a watchdog is
- worth building.
-10. The `Notification` capture — the highest-value item on this list, because the mapping in §5 rests
- entirely on another integration's reader. Record, VERBATIM and per notification, all THREE fields
- the mapping reads: the kind (`notificationType` / `notification_type` / `type` — note which key,
- and its exact casing), `message`, and `level`. Do it for BOTH cases, because they are handled
- oppositely and only the exact strings can tell them apart:
- (a) a **routine** run — one turn with several tool calls, under `auto` AND under
- `bypassPermissions`, window in the BACKGROUND. If a notification fires per tool call, our
- suppression must match its message/level exactly or the node strobes NEEDS YOU (chime + OS
- notification + phone card per tool call). Count the notifications against the tool calls.
- (b) a **genuine** ask that needs a human answer. That one must still reach `blocked`.
- Also note whether an IDLE notification exists at all and its exact message (item 9's rescue
- depends on the four phrases in `GROK_IDLE_MESSAGES`). This is the only path to a NEEDS YOU badge;
- record the vocabulary.
+ 9. Press Esc mid-turn. Expected: session `StopCancelled(reason=user_interrupt)` clears RUNNING as
+ an interrupted stop (no ordinary completion alert/unread); a payload carrying `subagentType`
+ leaves the session working. Record whether `idle_prompt` follows as the bounded fallback. Also
+ try cancel-and-send: it emits no stop hook and the replacement turn must stay RUNNING. No
+ watchdog is needed because the session-level terminal event exists.
+10. Capture one real payload for each published `Notification` type and record which key carries the
+ kind (`notificationType`, `notification_type`, or `type`). The type vocabulary and semantics are
+ already published in `10-hooks.md:99,162`; this capture is only to replace the remaining
+ defensive key aliases with measured envelope shapes. Message prose and severity do not classify
+ state.
11. Force an API error (e.g. an invalid model). Does StopFailure clear the RUNNING badge?
12. Quit with `/quit`. Does the session-close Stop stay silent (no "agent finished" notification)?
diff --git a/src/core/agent-status-mirror.test.ts b/src/core/agent-status-mirror.test.ts
index 57dee189f..ba0a14c46 100644
--- a/src/core/agent-status-mirror.test.ts
+++ b/src/core/agent-status-mirror.test.ts
@@ -1758,7 +1758,82 @@ describe('stale-working sweep (shared/agents/stale)', () => {
})
-describe('idle_prompt rescue (Esc that ran no Stop hook)', () => {
+describe('Grok StopCancelled closes only the session turn', () => {
+ beforeEach(() => _resetForTest())
+
+ it('turns a session user_interrupt into one interrupted done edge', () => {
+ recordAgentEvent(ev({ agentId: 'grok', state: 'working', newTurn: true }))
+
+ const out = recordAgentEvent(
+ ev({ agentId: 'grok', state: undefined, cancelReason: 'user_interrupt' })
+ )
+
+ expect(out).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ kind: 'state',
+ state: 'done',
+ interrupted: true,
+ cancelReason: 'user_interrupt'
+ })
+ expect(_snapshot().n1.state).toBe('done')
+ expect(_inboxSnapshot().events).toEqual([
+ expect.objectContaining({ nodeId: 'n1', kind: 'done', title: 'Stopped', interrupted: true })
+ ])
+ })
+
+ it.each([
+ 'permission_rejected',
+ 'permission_cancelled',
+ 'max_turns',
+ 'no_progress'
+ ] as const)('turns session reason %s into a visible, non-interrupted done', (cancelReason) => {
+ recordAgentEvent(ev({ agentId: 'grok', state: 'working', newTurn: true }))
+
+ const out = recordAgentEvent(ev({ agentId: 'grok', state: undefined, cancelReason }))
+
+ expect(out).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ kind: 'state',
+ state: 'done',
+ cancelReason
+ })
+ expect(_snapshot().n1.state).toBe('done')
+ expect(_inboxSnapshot().events).toEqual([
+ expect.objectContaining({ nodeId: 'n1', kind: 'done', title: 'Finished' })
+ ])
+ expect(_inboxSnapshot().events[0]?.interrupted).toBeUndefined()
+ })
+
+ it.each(['explore', ''] as const)(
+ 'does not let a cancellation with subagentType=%j end the session turn',
+ (subagentType) => {
+ recordAgentEvent(ev({ agentId: 'grok', state: 'working', newTurn: true }))
+ const cancelled = ev({
+ agentId: 'grok',
+ state: undefined,
+ cancelReason: 'user_interrupt',
+ subagentType
+ })
+
+ expect(recordAgentEvent(cancelled)).toBe(cancelled)
+ expect(_snapshot().n1.state).toBe('working')
+ expect(_inboxSnapshot().events).toEqual([])
+ }
+ )
+
+ it('leaves an unknown cancellation reason as an identity-only no-op', () => {
+ recordAgentEvent(ev({ agentId: 'grok', state: 'working', newTurn: true }))
+ const cancelled = ev({ agentId: 'grok', state: undefined, cancelReason: 'unknown' })
+
+ expect(recordAgentEvent(cancelled)).toBe(cancelled)
+ expect(_snapshot().n1.state).toBe('working')
+ expect(_inboxSnapshot().events).toEqual([])
+ })
+})
+
+describe('idle_prompt rescue (a stop hook may not complete)', () => {
it('moves a stuck working node off working', () => {
const prev = reduceEntry(undefined, ev({ state: 'working' }), 1000)
expect(prev.state).toBe('working')
diff --git a/src/core/agent-status-mirror.ts b/src/core/agent-status-mirror.ts
index b00b1f976..95dcb5755 100644
--- a/src/core/agent-status-mirror.ts
+++ b/src/core/agent-status-mirror.ts
@@ -389,10 +389,48 @@ export interface MirrorInbox {
* Pure reducer: fold one event into a node's entry, mirroring the renderer store's MAIN-state
* semantics. Returns the next entry (never mutates `prev`). `now` is injected for testability.
*/
+function resolveGrokStopCancelled(ev: NormalizedAgentEvent): NormalizedAgentEvent {
+ if (
+ ev.agentId !== 'grok' ||
+ ev.kind !== 'state' ||
+ ev.state !== undefined ||
+ !ev.cancelReason ||
+ ev.subagentType !== undefined
+ ) {
+ return ev
+ }
+
+ // Grok 1.0.13's `10-hooks.md:336,348,354,384` makes this a CLOSED session-level decision.
+ // A subagent cancellation is returned above because ending its card must not end the parent
+ // session. Unknown reasons stay identity-only: guessing `done` could turn a future cancel-and-send
+ // dialect into a false completion while the agent is still working.
+ switch (ev.cancelReason) {
+ case 'user_interrupt':
+ return { ...ev, state: 'done', interrupted: true }
+ case 'permission_rejected':
+ case 'permission_cancelled':
+ case 'max_turns':
+ case 'no_progress':
+ // These end the turn, but are not an Esc/Ctrl-C. Keeping them non-interrupted makes the
+ // non-successful terminal outcome visible instead of suppressing its completion edge.
+ return { ...ev, state: 'done' }
+ case 'unknown':
+ return ev
+ }
+}
+
export function reduceEntry(
prev: MirrorEntry | undefined,
ev: NormalizedAgentEvent,
now: number
+): MirrorEntry {
+ return reduceEffectiveEntry(prev, resolveGrokStopCancelled(ev), now)
+}
+
+function reduceEffectiveEntry(
+ prev: MirrorEntry | undefined,
+ ev: NormalizedAgentEvent,
+ now: number
): MirrorEntry {
const next: MirrorEntry = prev ? { ...prev } : { updatedAt: now }
/**
@@ -1339,18 +1377,19 @@ interface NeedsYouClassification {
* STRIPPED — so TerminalNode's `blocked && pendingId` gate never renders approve/deny on a
* question (field report: the buttons showed during an AskUserQuestion);
* - a genuine `approval` gains `askKind:'approval'` and keeps its `pendingId` unchanged.
- * Every other event (working / done / session / subagent / recurring) passes through untouched
- * (same reference). Internal behavior — inbox production, live-update seams, disk writes — is
- * unchanged; this only affects what the caller then broadcasts. Called with EVERY normalized event
- * by both shells.
+ * Grok's state-less `StopCancelled` is projected here too, so the state folded into this mirror is
+ * the same state both shells broadcast; subagent/unknown cancellations retain their original
+ * identity-only event. Every other event passes through untouched (same reference). Called with
+ * EVERY normalized event by both shells.
*/
-export function recordAgentEvent(ev: NormalizedAgentEvent): NormalizedAgentEvent {
- if (!ev?.nodeId) return ev
+export function recordAgentEvent(rawEvent: NormalizedAgentEvent): NormalizedAgentEvent {
+ if (!rawEvent?.nodeId) return rawEvent
+ const ev = resolveGrokStopCancelled(rawEvent)
const nodeId = ev.nodeId
const now = Date.now()
const prev = state.get(nodeId)
const prevState = prev?.state
- const next = reduceEntry(prev, ev, now)
+ const next = reduceEffectiveEntry(prev, ev, now)
state.set(nodeId, next)
// reduceEntry held an unanswered `request_user_input` through its turn-end `done` — rewrite
// the broadcast to what the reducer decided, so every consumer (canvas store, notch, phone)
diff --git a/src/core/agents/hooks/grok.test.ts b/src/core/agents/hooks/grok.test.ts
index d5af69257..d53b8b12a 100644
--- a/src/core/agents/hooks/grok.test.ts
+++ b/src/core/agents/hooks/grok.test.ts
@@ -34,7 +34,23 @@ describe('grok hook installer', () => {
expect(grokHookConfigPath()).toBe(path.join(grokHome, 'hooks', 'nodeterm-status.json'))
const cfg = read(grokHookConfigPath())
expect(Object.keys(cfg.hooks).sort()).toEqual(
- ['Notification', 'PostToolUse', 'PostToolUseFailure', 'PreToolUse', 'SessionEnd', 'SessionStart', 'Stop', 'StopFailure', 'UserPromptSubmit'].sort()
+ [
+ 'SessionStart',
+ 'UserPromptSubmit',
+ 'PreToolUse',
+ 'PostToolUse',
+ 'PostToolUseFailure',
+ 'PermissionDenied',
+ 'Stop',
+ 'StopFailure',
+ 'StopCancelled',
+ 'Notification',
+ 'SubagentStart',
+ 'SubagentStop',
+ 'PreCompact',
+ 'PostCompact',
+ 'SessionEnd'
+ ].sort()
)
})
@@ -42,18 +58,29 @@ describe('grok hook installer', () => {
const { installGrokHooks, grokHookConfigPath } = await import('./grok')
installGrokHooks()
const cfg = read(grokHookConfigPath())
- for (const ev of ['PreToolUse', 'PostToolUse', 'PostToolUseFailure']) {
+ for (const ev of ['PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionDenied']) {
expect(cfg.hooks[ev][0].matcher, ev).toBe('.*')
}
// Non-tool events must carry NO matcher, for two DIFFERENT reasons — both in
// ~/.grok/docs/user-guide/10-hooks.md:153. On `Stop` and `UserPromptSubmit` a matcher is
// "ignored with a warning (those events always fire)": harmless noise. On the other four it
// FILTERS, against something that is not a tool name at all — the start source on
- // `SessionStart`, the end reason on `SessionEnd`, the notification type on `Notification`, the
- // classified error type on `StopFailure` — so a stray `.*` there is not noise: anything it fails
- // to match is an event we silently never receive. Every one of them is checked, so a matcher
- // accidentally attached to an event in hook-events.ts cannot ship.
- for (const ev of ['SessionStart', 'UserPromptSubmit', 'Stop', 'StopFailure', 'Notification', 'SessionEnd']) {
+ // `SessionStart`, the end reason on `SessionEnd`, the notification type on `Notification`, or
+ // the documented reason/type/trigger on the other events — so a stray `.*` there is not noise:
+ // anything it fails to match is an event we silently never receive. Every one is checked.
+ for (const ev of [
+ 'SessionStart',
+ 'UserPromptSubmit',
+ 'Stop',
+ 'StopFailure',
+ 'StopCancelled',
+ 'Notification',
+ 'SubagentStart',
+ 'SubagentStop',
+ 'PreCompact',
+ 'PostCompact',
+ 'SessionEnd'
+ ]) {
expect(cfg.hooks[ev][0].matcher, ev).toBeUndefined()
}
})
@@ -92,12 +119,12 @@ describe('grok hook installer', () => {
p,
JSON.stringify({
hooks: {
- PreCompact: [{ hooks: [{ type: 'command', command: `sh '${path.join(home, '.nodeterm/agent-hooks/grok.sh')}'` }] }]
+ ObsoleteEvent: [{ hooks: [{ type: 'command', command: `sh '${path.join(home, '.nodeterm/agent-hooks/grok.sh')}'` }] }]
}
})
)
installGrokHooks()
- expect(read(grokHookConfigPath()).hooks.PreCompact).toBeUndefined()
+ expect(read(grokHookConfigPath()).hooks.ObsoleteEvent).toBeUndefined()
})
it('remove takes our entries back out', async () => {
diff --git a/src/core/agents/hooks/grok.ts b/src/core/agents/hooks/grok.ts
index 122cc3be8..23643b049 100644
--- a/src/core/agents/hooks/grok.ts
+++ b/src/core/agents/hooks/grok.ts
@@ -1,34 +1,62 @@
-// Grok hook service. Grok's hook config is a DIRECTORY — it merges every `$GROK_HOME/hooks/*.json`
+// Grok hook service. The Grok hook config is a DIRECTORY — it merges every `$GROK_HOME/hooks/*.json`
// — so unlike claude and gemini there is no shared settings file to merge into: nodeterm owns one
// file outright and rewrites it. We still route through the shared install helper, because that is
// where the missing-script guard, the idempotent re-install and the "sweep events we no longer
// subscribe to" repair live.
-import path from 'path'
-import { GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
-import { GROK_HOOK_FILE, grokHomeDir } from '../grok-paths'
-import { installHooksInto, removeHooksFrom } from './install-helper'
+import path from "path"
+import type { ManagedHookEvent } from "../../../shared/agents/hook-events"
+import { GROK_HOOK_FILE, grokHomeDir } from "../grok-paths"
+import { installHooksInto, removeHooksFrom } from "./install-helper"
-const SCRIPT_FILE_NAME = 'grok.sh'
+const SCRIPT_FILE_NAME = "grok.sh"
-/** Our hook file inside grok's hooks directory. Exported for tests and for the SSH installer,
+/**
+ * Complete Grok 1.0.13 hook set, measured against
+ * `~/.grok/docs/user-guide/10-hooks.md:84-106`. Keep all fifteen here: omitting an event makes its
+ * normalizer unreachable, which is how StopCancelled existed but Esc left RUNNING stuck.
+ * PreCompact/PostCompact are identity-bearing even when they do not move the badge: Grok mints a
+ * new session id during compaction, and both shells must observe it for continuity.
+ */
+export const GROK_EVENTS: readonly ManagedHookEvent[] = [
+ 'SessionStart',
+ 'UserPromptSubmit',
+ // Tool matchers are regexes. `.*` is an explicit match-all; bare `*` is invalid and fails silent.
+ { event: 'PreToolUse', matcher: '.*' },
+ { event: 'PostToolUse', matcher: '.*' },
+ { event: 'PostToolUseFailure', matcher: '.*' },
+ { event: 'PermissionDenied', matcher: '.*' },
+ 'Stop',
+ 'StopFailure',
+ 'StopCancelled',
+ 'Notification',
+ 'SubagentStart',
+ 'SubagentStop',
+ 'PreCompact',
+ 'PostCompact',
+ 'SessionEnd'
+]
+
+/** Our hook file inside the Grok hooks directory. Exported for tests and for the SSH installer,
* which must write the identical name on the host. */
export function grokHookConfigPath(): string {
- return path.join(grokHomeDir(), 'hooks', GROK_HOOK_FILE)
+ return path.join(grokHomeDir(), "hooks", GROK_HOOK_FILE)
}
export function installGrokHooks(): void {
installHooksInto({
- agentId: 'grok',
+ agentId: "grok",
scriptFileName: SCRIPT_FILE_NAME,
configPath: grokHookConfigPath(),
- events: GROK_HOOK_EVENTS
+ events: GROK_EVENTS,
+ atomicConfig: true
})
}
export function removeGrokHooks(): void {
removeHooksFrom({
configPath: grokHookConfigPath(),
- events: GROK_HOOK_EVENTS,
- scriptFileName: SCRIPT_FILE_NAME
+ events: GROK_EVENTS,
+ scriptFileName: SCRIPT_FILE_NAME,
+ atomicConfig: true
})
}
diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.ts
index 2ab62b751..28dea22f4 100644
--- a/src/core/agents/hooks/install-helper.test.ts
+++ b/src/core/agents/hooks/install-helper.test.ts
@@ -1,10 +1,57 @@
import path from 'path'
import { describe, expect, it } from 'vitest'
-import { buildManagedHookCommand, mergeManagedHook, type HookSettings } from './install-helper'
+import { chmodSync, lstatSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import {
+ buildManagedHookCommand,
+ mergeManagedHook,
+ writeManagedHookConfig,
+ writeManagedHookFileAtomic,
+ type HookSettings
+} from './install-helper'
import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'
const cmd = buildManagedHookCommand('/remote/.nodeterm/agent-hooks/claude.sh')
+describe('writeManagedHookFileAtomic', () => {
+ it('leaves the previous hook file intact and cleans its temp when publication fails', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'nt-hook-atomic-'))
+ const target = join(dir, 'hooks.json')
+ writeFileSync(target, 'old')
+ try {
+ expect(() =>
+ writeManagedHookFileAtomic(target, 'new', () => {
+ throw new Error('publish failed')
+ })
+ ).toThrow('publish failed')
+ expect(readFileSync(target, 'utf8')).toBe('old')
+ expect(readdirSync(dir)).toEqual(['hooks.json'])
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('writeManagedHookConfig', () => {
+ it('follows a shared settings symlink and preserves its private mode by default', () => {
+ const dir = mkdtempSync(join(tmpdir(), 'nt-hook-shared-'))
+ const target = join(dir, 'real-settings.json')
+ const link = join(dir, 'settings.json')
+ writeFileSync(target, 'old')
+ chmodSync(target, 0o600)
+ symlinkSync(target, link)
+ try {
+ writeManagedHookConfig(link, 'new')
+ expect(lstatSync(link).isSymbolicLink()).toBe(true)
+ expect(readFileSync(target, 'utf8')).toBe('new')
+ expect(lstatSync(target).mode & 0o777).toBe(0o600)
+ } finally {
+ rmSync(dir, { recursive: true, force: true })
+ }
+ })
+})
+
describe('buildManagedHookCommand', () => {
it('runs the script only when it is still readable, and exits 0 otherwise', () => {
// The whole point: a stale entry (uninstalled app, cleared data dir, a server --data-dir
diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.ts
index 1f313f06b..9df5b72e1 100644
--- a/src/core/agents/hooks/install-helper.ts
+++ b/src/core/agents/hooks/install-helper.ts
@@ -13,8 +13,9 @@
// early (remove); a write error is caught + warned, never thrown.
import path from 'path'
import { homedir } from 'os'
-import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'fs'
+import { readFileSync, writeFileSync, mkdirSync, chmodSync, rmSync } from 'fs'
import type { ManagedHookEvent } from '@shared/agents/hook-events'
+import { renameAtomicSync, tempNameFor } from '../../fs-atomic'
import { buildManagedScript } from './managed-script'
type HookDef = { matcher?: string; hooks?: { type: string; command: string }[] }
@@ -23,6 +24,33 @@ type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }
/** Public alias for the hook settings shape, shared by local + remote merge callers. */
export type HookSettings = Settings
+/** Publish a managed hook file without exposing a truncated destination to a running CLI. */
+export function writeManagedHookFileAtomic(
+ target: string,
+ data: string,
+ publish: (tmp: string, target: string) => void = renameAtomicSync,
+ mode?: number
+): void {
+ const tmp = tempNameFor(target)
+ try {
+ writeFileSync(tmp, data, { encoding: 'utf8', flag: 'wx', ...(mode === undefined ? {} : { mode }) })
+ publish(tmp, target)
+ } catch (e) {
+ rmSync(tmp, { force: true })
+ throw e
+ }
+}
+
+/**
+ * Shared Claude/Gemini settings keep their existing write-through semantics so a user-owned
+ * symlink and its target mode survive. Grok opts into atomic replacement for its nodeterm-owned
+ * file under `$GROK_HOME/hooks/`.
+ */
+export function writeManagedHookConfig(target: string, data: string, atomic = false): void {
+ if (atomic) writeManagedHookFileAtomic(target, data)
+ else writeFileSync(target, data, 'utf8')
+}
+
/**
* ONE script location per MACHINE — `~/.nodeterm/agent-hooks/<agent>.sh` — not one per instance.
*
@@ -44,7 +72,7 @@ export function installManagedHookScript(agentId: string, scriptFileName: string
const scriptPath = managedHookScriptPath(scriptFileName)
try {
mkdirSync(path.dirname(scriptPath), { recursive: true })
- writeFileSync(scriptPath, buildManagedScript(agentId), 'utf8')
+ writeManagedHookFileAtomic(scriptPath, buildManagedScript(agentId), renameAtomicSync, 0o755)
} catch (e) {
console.warn(`[agent-hooks] ${agentId} script write failed`, e)
return null
@@ -208,10 +236,12 @@ export interface InstallHooksOptions {
scriptFileName: string
configPath: string
events: readonly ManagedHookEvent[]
+ /** Atomic replacement is safe only when nodeterm owns the config file outright (Grok). */
+ atomicConfig?: boolean
}
export function installHooksInto(opts: InstallHooksOptions): void {
- const { agentId, scriptFileName, configPath, events } = opts
+ const { agentId, scriptFileName, configPath, events, atomicConfig = false } = opts
const sp = installManagedHookScript(agentId, scriptFileName)
if (!sp) return
@@ -226,7 +256,7 @@ export function installHooksInto(opts: InstallHooksOptions): void {
config = mergeManagedHook(config, command, events)
try {
mkdirSync(path.dirname(configPath), { recursive: true })
- writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8')
+ writeManagedHookConfig(configPath, JSON.stringify(config, null, 2), atomicConfig)
} catch (e) {
console.warn(`[agent-hooks] ${agentId} install failed`, e)
}
@@ -237,10 +267,12 @@ export interface RemoveHooksOptions {
events: readonly ManagedHookEvent[]
/** Our script's file name — narrows the match so foreign agent-hooks entries survive. */
scriptFileName: string
+ /** Atomic replacement is safe only when nodeterm owns the config file outright (Grok). */
+ atomicConfig?: boolean
}
export function removeHooksFrom(opts: RemoveHooksOptions): void {
- const { configPath, events, scriptFileName } = opts
+ const { configPath, events, scriptFileName, atomicConfig = false } = opts
// Same normalized comparison as the installer — a raw `includes` left every entry behind on
// Windows (issue #558), so uninstall silently did nothing there.
const isOurs = managedCommandMatcher(`agent-hooks/${scriptFileName}`, false)
@@ -258,7 +290,7 @@ export function removeHooksFrom(opts: RemoveHooksOptions): void {
if (config.hooks[ev].length === 0) delete config.hooks[ev]
}
try {
- writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8')
+ writeManagedHookConfig(configPath, JSON.stringify(config, null, 2), atomicConfig)
} catch {
/* fail open */
}
diff --git a/src/core/grok-hook-session.test.ts b/src/core/grok-hook-session.test.ts
new file mode 100644
index 000000000..79256156b
--- /dev/null
+++ b/src/core/grok-hook-session.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import { applyGrokHookSession, planGrokHookSession } from './grok-hook-session'
+
+describe('planGrokHookSession', () => {
+ it.each([
+ ['PermissionDenied', 'permission_denied', 'permissiondenied', 'gs-before', undefined],
+ ['StopCancelled', 'stop_cancelled', 'stopcancelled', 'gs-before', undefined],
+ ['SubagentStart', 'subagent_start', 'subagentstart', 'gs-before', undefined],
+ ['SubagentStop', 'subagent_stop', 'subagentstop', 'gs-before', undefined],
+ ['PreCompact', 'pre_compact', 'precompact', 'gs-before', undefined],
+ ['PostCompact', 'post_compact', 'postcompact', 'gs-after', 'gs-before']
+ ])(
+ '%s produces the shell-independent session transition',
+ (_name, hookEventName, event, sessionId, forgetSessionId) => {
+ expect(
+ planGrokHookSession({ hookEventName, sessionId, cwd: '/w/project' }, 'gs-before')
+ ).toEqual({
+ event,
+ sessionId,
+ cwd: '/w/project',
+ forgetSessionId
+ })
+ }
+ )
+
+ it('does not retire a session when PostCompact repeats its current id', () => {
+ expect(
+ planGrokHookSession(
+ { hook_event_name: 'post_compact', session_id: 'gs-current', cwd: '/w/project' },
+ 'gs-current'
+ )
+ ).toEqual({
+ event: 'postcompact',
+ sessionId: 'gs-current',
+ cwd: '/w/project',
+ forgetSessionId: undefined
+ })
+ })
+
+ it.each(['desktop', 'server'])('%s applies all six new events through the same behavioral seam', (_shell) => {
+ const cases = [
+ ['permission_denied', 'gs-before', undefined],
+ ['stop_cancelled', 'gs-before', undefined],
+ ['subagent_start', 'gs-before', undefined],
+ ['subagent_stop', 'gs-before', undefined],
+ ['pre_compact', 'gs-before', undefined],
+ ['post_compact', 'gs-after', 'gs-before']
+ ] as const
+
+ for (const [hookEventName, sessionId, forgotten] of cases) {
+ const sessions = new Map([['node-1', 'gs-before']])
+ const remembered: [string, string][] = []
+ const forgot: string[] = []
+
+ applyGrokHookSession(
+ 'node-1',
+ { hookEventName, sessionId, cwd: '/w/project' },
+ sessions,
+ {
+ sessionsDir: '/grok/sessions',
+ rememberSessionDir: (id, dir) => remembered.push([id, dir]),
+ forgetSession: (id) => {
+ if (id) forgot.push(id)
+ }
+ }
+ )
+
+ expect(sessions.get('node-1'), hookEventName).toBe(sessionId)
+ expect(remembered, hookEventName).toEqual([
+ [sessionId, `/grok/sessions/${encodeURIComponent('/w/project')}/${sessionId}`]
+ ])
+ expect(forgot, hookEventName).toEqual(forgotten ? [forgotten] : [])
+ }
+ })
+})
diff --git a/src/core/grok-hook-session.ts b/src/core/grok-hook-session.ts
new file mode 100644
index 000000000..1f1b175eb
--- /dev/null
+++ b/src/core/grok-hook-session.ts
@@ -0,0 +1,59 @@
+import { grokRawFields } from '../shared/agents/normalize'
+import { grokSessionDir, grokSessionsDir } from './agents/grok-paths'
+import { forgetGrokSession, rememberGrokSessionDir } from './grok-session'
+
+export interface GrokHookSessionPlan {
+ event: string
+ sessionId: string | undefined
+ cwd: string | undefined
+ forgetSessionId: string | undefined
+}
+
+export interface GrokHookSessionDeps {
+ sessionsDir: string
+ rememberSessionDir: (sessionId: string, dir: string) => void
+ forgetSession: (sessionId: string | undefined) => void
+}
+
+/**
+ * Decode the two Grok hook dialects and decide the session-map transition once for both shells.
+ * Grok 1.0.13 gives PostCompact a newly minted session id, so that event retires the prior id;
+ * SessionEnd retires the id carried by the event itself.
+ */
+export function planGrokHookSession(
+ payload: Record<string, unknown>,
+ previousSessionId: string | undefined
+): GrokHookSessionPlan {
+ const { event, sessionId, cwd } = grokRawFields(payload)
+ const forgetSessionId =
+ event === 'postcompact' && sessionId && previousSessionId && previousSessionId !== sessionId
+ ? previousSessionId
+ : event === 'sessionend'
+ ? sessionId
+ : undefined
+
+ return { event, sessionId, cwd, forgetSessionId }
+}
+
+/** Apply the complete Grok raw-listener session behavior shared by desktop and Server Edition. */
+export function applyGrokHookSession(
+ nodeId: string,
+ payload: Record<string, unknown>,
+ nodeContextSession: Map<string, string>,
+ deps?: GrokHookSessionDeps
+): GrokHookSessionPlan {
+ const previousSessionId = nodeId ? nodeContextSession.get(nodeId) : undefined
+ const plan = planGrokHookSession(payload, previousSessionId)
+ const sessionsDir = deps?.sessionsDir ?? grokSessionsDir()
+ const remember = deps?.rememberSessionDir ?? rememberGrokSessionDir
+ const forget = deps?.forgetSession ?? forgetGrokSession
+
+ if (nodeId && plan.sessionId) nodeContextSession.set(nodeId, plan.sessionId)
+ if (plan.sessionId && plan.cwd) {
+ const dir = grokSessionDir({ sessionsDir, cwd: plan.cwd, sessionId: plan.sessionId })
+ if (dir) remember(plan.sessionId, dir)
+ }
+ if (plan.forgetSessionId) forget(plan.forgetSessionId)
+
+ return plan
+}
diff --git a/src/main/index.ts b/src/main/index.ts
index c458c18f1..13aa071f4 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,4 +1,4 @@
-import { grokHomeDir } from '../core/agents/grok-paths'
+import { grokHomeDir, grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
import { join, resolve, posix } from 'path'
import { startSessionNameSweep, displayNodeTitle } from '../core/session-name-sweep'
import { startTriggerService } from '../core/trigger-service'
@@ -191,10 +191,9 @@ import { geminiContextParse } from '../core/gemini-session'
import { codexContextParse } from '../core/codex-session'
import { createCodexSubagentFormatter } from '../core/codex-subagent-format'
import { codexHome } from '../core/usage/codex-usage'
-import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { applyGrokHookSession } from '../core/grok-hook-session'
import { agentAccountColor } from '../shared/agents/account-color'
-import { grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
-import { forgetGrokSession, rememberGrokSessionDir } from '../core/grok-session'
import {
setRemoteTranscriptReader,
TITLE_TAIL_BYTES,
@@ -2713,33 +2712,30 @@ app.whenReady().then(async () => {
hookServer.setRawListener((agentId, nodeId, payload, _meta) => {
if (agentId === 'grok') {
// This branch records two associations, neither of which grok's envelope states outright.
- // Everything the claude path does below hangs off `transcript_path`, and grok has none.
- // Read through `grokRawFields` so grok's two field dialects (camelCase and the SDK's
- // snake_case) are decoded in exactly one place.
- const g = grokRawFields(payload)
- // 1. node → session: read by the phone's context ring and the ⌘K session lookup.
- if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)
- // 2. session → its session DIRECTORY, derived from (cwd, sessionId) — the two fields every
- // grok hook does carry — and remembered here, the one place they arrive together. That is
- // what lets the session-name read (core/grok-session.ts) be a direct open rather than a scan
- // of grok's sessions tree, which is how one node would end up adopting another's name.
- // `grokSessionDir` returns null for a cwd grok stored under its slug+hash scheme instead, in
- // which case we learn nothing about this session rather than build half a path.
- if (g.sessionId && g.cwd) {
+ // Everything the claude path does below hangs off `transcript_path`, and grok has none. Core
+ // owns the node/session/directory transition (`applyGrokHookSession`) so desktop and Server
+ // Edition cannot implement different event branches — including the one thing only it does:
+ // PostCompact mints a NEW session id, so the PRIOR id is retired there and not only on
+ // SessionEnd. Written inline, that transition existed in two copies and neither knew it.
+ //
+ // What stays HERE is what needs a shell to exist: the per-shell context tail and the phone
+ // mirror. `plan` carries the decoded event/session/cwd, so the dialect is still decoded in
+ // exactly one place.
+ const plan = applyGrokHookSession(nodeId, payload, nodeContextSession)
+ // 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).
+ if (plan.sessionId && plan.cwd) {
const dir = grokSessionDir({
sessionsDir: grokSessionsDir(),
- cwd: g.cwd,
- sessionId: g.sessionId
+ cwd: plan.cwd,
+ sessionId: plan.sessionId
})
- 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))
- }
+ if (dir) grokContextTail.track(plan.sessionId, join(dir, GROK_SIGNALS_FILE))
}
- // 3. node → what it is doing NOW (the phone's per-node activity line).
+ // 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
@@ -2748,10 +2744,11 @@ app.whenReady().then(async () => {
// 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) {
+ // Translated here rather than by loosening that gate: the mirror is claude-shaped on purpose.
+ // `toolActivity` knows grok's fifteen tool names, so the line reads "Reading fichero.txt",
+ // never a claude phrase.
+ const g = grokRawFields(payload)
+ if (nodeId && plan.event === 'pretooluse' && g.toolName) {
recordRawToolEvent(nodeId, {
hook_event_name: 'PreToolUse',
tool_name: g.toolName,
@@ -2759,18 +2756,13 @@ app.whenReady().then(async () => {
})
}
// The turn is over: clear the activity line the same way the claude path does.
- if (nodeId && (g.event === 'stop' || g.event === 'sessionend')) {
+ if (nodeId && (plan.event === 'stop' || plan.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)
- grokContextTail.untrack(g.sessionId)
- }
+ // 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.
+ if (plan.forgetSessionId) grokContextTail.untrack(plan.forgetSessionId)
return
}
// gemini and codex both carry `transcript_path` in their hook envelope (gemini: the base input
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 155d18e11..53bcb253c 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -345,13 +345,19 @@ describe('RemoteHooks.setup — grok', () => {
// assertion still passes. The `/home/dev/.grok` negative assertions are what make that fail.
const GROK_EVENTS = [
'Notification',
+ 'PermissionDenied',
+ 'PostCompact',
'PostToolUse',
'PostToolUseFailure',
+ 'PreCompact',
'PreToolUse',
'SessionEnd',
'SessionStart',
'Stop',
+ 'StopCancelled',
'StopFailure',
+ 'SubagentStart',
+ 'SubagentStop',
'UserPromptSubmit'
]
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index 25dfa4148..57fd4d1ae 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -6,7 +6,8 @@
// simply runs without status). Takes an INJECTED runner so the flow is unit-testable without real
// ssh/electron.
import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'
-import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
+import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS } from '@shared/agents/hook-events'
+import { GROK_EVENTS } from '../../core/agents/hooks/grok'
import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
import { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'
import { hookServer } from '../../core/agents/hook-server'
@@ -495,7 +496,7 @@ export class RemoteHooks {
} catch {
cfg = {}
}
- const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), GROK_HOOK_EVENTS)
+ const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), GROK_EVENTS)
// The `$(dirname …)` is QUOTED: a valid $GROK_HOME may contain spaces, which would otherwise
// word-split into two mkdir args, leave the directory absent, and fail the quoted `cat >`.
await this.r.run(
diff --git a/src/server/agent-status.test.ts b/src/server/agent-status.test.ts
index 41d6556fd..328b0a8cb 100644
--- a/src/server/agent-status.test.ts
+++ b/src/server/agent-status.test.ts
@@ -402,6 +402,32 @@ describe('wireAgentStatus — the grok raw-listener branch', () => {
expect(grokSessionDirFor('gs-4')).toBeUndefined()
})
+ it('replaces the old session association when PostCompact mints a new id', () => {
+ const fh = fakeHooks()
+ const ctx = recTail()
+ wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: ctx.tail as never })
+ fh.fireRaw('grok', 'g-compact', {
+ hookEventName: 'pre_compact',
+ sessionId: 'gs-before',
+ cwd: '/w/project'
+ })
+ expect(grokSessionDirFor('gs-before')).toBe(sessionDir('/w/project', 'gs-before'))
+
+ fh.fireRaw('grok', 'g-compact', {
+ hookEventName: 'post_compact',
+ sessionId: 'gs-after',
+ cwd: '/w/project'
+ })
+ expect(grokSessionDirFor('gs-before')).toBeUndefined()
+ expect(grokSessionDirFor('gs-after')).toBe(sessionDir('/w/project', 'gs-after'))
+
+ platform.cast(platform.attach({ sendText: () => {}, sendBinary: () => {} }), IPC.ptyDestroy, [
+ 'g-compact'
+ ])
+ expect(ctx.calls.some((c) => c.m === 'untrack' && c.args[0] === 'gs-after')).toBe(true)
+ forgetGrokSession('gs-after')
+ })
+
it('learns nothing rather than half a path when the cwd is not reconstructible', () => {
const fh = fakeHooks()
wireAgentStatus(platform, { hooks: fh.hooks as never, contextTail: recTail().tail as never })
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index d21dd2d02..9bc149679 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -7,7 +7,7 @@
// local logic.
//
// This module must import nothing from electron or `../main` (see no-electron.test.ts).
-import { grokHomeDir } from '../core/agents/grok-paths'
+import { grokHomeDir, grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
import { join, resolve } from 'path'
import { homedir } from 'os'
import { hookServer } from '../core/agents/hook-server'
@@ -24,9 +24,8 @@ import { codexHome } from '../core/usage/codex-usage'
import { setNodeTranscript } from '../core/context-link'
import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'
import { linkedClaudeConfigDirs } from '../core/claude-config-dir'
-import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
-import { grokSessionDir, grokSessionsDir } from '../core/agents/grok-paths'
-import { forgetGrokSession, rememberGrokSessionDir } from '../core/grok-session'
+import { isAsyncSubagentLaunch, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { applyGrokHookSession } from '../core/grok-hook-session'
import { IPC } from '../shared/ipc'
import type { ServerPlatform } from './platform-server'
@@ -204,39 +203,30 @@ export function wireAgentStatus(
hooks.setRawListener((agentId, nodeId, payload, _meta) => {
if (agentId === 'grok') {
// This branch records two associations, neither of which grok's envelope states outright.
- // Everything the claude path does below hangs off `transcript_path`, and grok has none.
- // Read through `grokRawFields` so grok's two field dialects (camelCase and the SDK's
- // snake_case) are decoded in exactly one place.
- const g = grokRawFields(payload)
- // 1. node → session: read by the phone's context ring and the ⌘K session lookup.
- if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)
- // 2. session → its session DIRECTORY, derived from (cwd, sessionId) — the two fields every
- // grok hook does carry — and remembered here, the one place they arrive together. That is
- // what lets the session-name read (core/grok-session.ts) be a direct open rather than a scan
- // of grok's sessions tree, which is how one node would end up adopting another's name.
- // `grokSessionDir` returns null for a cwd grok stored under its slug+hash scheme instead, in
- // which case we learn nothing about this session rather than build half a path.
+ // Everything the claude path does below hangs off `transcript_path`, and grok has none. Core
+ // owns the node/session/directory transition (`applyGrokHookSession`) so desktop and Server
+ // Edition cannot implement different event branches — including the one thing only it does:
+ // PostCompact mints a NEW session id, so the PRIOR id is retired there and not only on
+ // SessionEnd. Written inline, that transition existed in two copies and neither knew it.
//
- // The Server Edition populates it exactly as the desktop does; what it does not yet serve is
- // the READ (IPC.ptyReadSessionName has no server handler — see the ws-bridge stub).
- if (g.sessionId && g.cwd) {
+ // What stays HERE is what needs a shell to exist: the per-shell context tail and the phone
+ // mirror. `plan` carries the decoded event/session/cwd, so the dialect is still decoded in
+ // exactly one place.
+ const plan = applyGrokHookSession(nodeId, payload, nodeContextSession)
+ // 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).
+ if (plan.sessionId && plan.cwd) {
const dir = grokSessionDir({
sessionsDir: grokSessionsDir(),
- cwd: g.cwd,
- sessionId: g.sessionId
+ cwd: plan.cwd,
+ sessionId: plan.sessionId
})
- 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)
- }
+ if (dir) grokContextTail.track(plan.sessionId, join(dir, GROK_SIGNALS_FILE))
}
- // 3. node → what it is doing NOW (the phone's per-node activity line).
+ // 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
@@ -245,10 +235,11 @@ export function wireAgentStatus(
// 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) {
+ // Translated here rather than by loosening that gate: the mirror is claude-shaped on purpose.
+ // `toolActivity` knows grok's fifteen tool names, so the line reads "Reading fichero.txt",
+ // never a claude phrase.
+ const g = grokRawFields(payload)
+ if (nodeId && plan.event === 'pretooluse' && g.toolName) {
recordRawToolEvent(nodeId, {
hook_event_name: 'PreToolUse',
tool_name: g.toolName,
@@ -256,18 +247,13 @@ export function wireAgentStatus(
})
}
// The turn is over: clear the activity line the same way the claude path does.
- if (nodeId && (g.event === 'stop' || g.event === 'sessionend')) {
+ if (nodeId && (plan.event === 'stop' || plan.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)
- grokContextTail.untrack(g.sessionId)
- }
+ // 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.
+ if (plan.forgetSessionId) grokContextTail.untrack(plan.forgetSessionId)
return
}
// gemini and codex both carry `transcript_path` in their hook envelope (gemini: the base input
diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.ts
index 13b69f4ff..2931ddd17 100644
--- a/src/shared/agents/hook-events.ts
+++ b/src/shared/agents/hook-events.ts
@@ -16,7 +16,6 @@
* Only grok needs the second form — its tool-event `matcher` is a real REGEX
* (`~/.grok/docs/user-guide/10-hooks.md:153`), so a bare `*` is not a valid match-all but an invalid
* pattern, and the expected failure is silence: the tool events simply never fire. We write `.*`.
- * That is read off the docs, not observed — no hook was ever seen firing here (see GROK_HOOK_EVENTS).
* claude/codex/gemini stay plain strings, so their emitted config is byte-identical to what it has
* always been.
*/
@@ -93,31 +92,3 @@ export const COPILOT_HOOK_EVENTS = [
'Notification',
'SessionEnd'
] as const
-
-/**
- * Grok hook events (→ normalizeGrok). Grok's shipped 1.0.0 docs list fourteen
- * (`~/.grok/docs/user-guide/10-hooks.md:84-101`); nine are subscribed — the ones `normalizeGrok` has
- * a mapping for. The other five are left off deliberately: PermissionDenied is a post-decision event
- * we would have nothing to do with, SubagentStart/SubagentStop drive subagent cards that are not
- * built for grok, and PreCompact/PostCompact have no consumer. No event here was ever seen FIRING —
- * that needs a logged-in session, which the branch never had — so subscribing one is a claim about
- * the docs, not a measurement. Grok skips hook event names it does not recognize (that is how a shared Claude
- * settings file loads at all), so adding one later is safe.
- */
-export const GROK_HOOK_EVENTS: readonly ManagedHookEvent[] = [
- 'SessionStart',
- 'UserPromptSubmit',
- 'Stop',
- // Fires INSTEAD of Stop when the turn dies on an API error — without it the badge sticks.
- 'StopFailure',
- 'Notification',
- 'SessionEnd',
- // The matcher is a REGEX, and an omitted one already matches everything
- // (~/.grok/docs/user-guide/10-hooks.md:153) — so this is not a requirement, it is an explicit
- // statement of "every tool". It is spelled `.*` and never `*`, because a bare `*` is not a
- // valid regex at all (nothing to repeat) and the failure mode is silence: the tool lifecycle
- // hooks simply never fire, so RUNNING clears mid-turn on a long tool call with nothing saying why.
- { event: 'PreToolUse', matcher: '.*' },
- { event: 'PostToolUse', matcher: '.*' },
- { event: 'PostToolUseFailure', matcher: '.*' }
-]
diff --git a/src/shared/agents/normalize.grok.test.ts b/src/shared/agents/normalize.grok.test.ts
index 1997d1b5a..1409f79dd 100644
--- a/src/shared/agents/normalize.grok.test.ts
+++ b/src/shared/agents/normalize.grok.test.ts
@@ -75,232 +75,229 @@ describe('normalizeGrok — Stop', () => {
}
})
- it('stop_failure ends the turn so the badge cannot stick on working', () => {
- expect(
- normalizeGrok(env({ hookEventName: 'stop_failure', sessionId: 's1', lastAssistantMessage: 'rate limited' }))
- ).toMatchObject({ state: 'done', lastMessage: 'rate limited' })
- })
-})
-
-/**
- * Notification is the one grok event nobody here could measure, and the two sources that describe it
- * disagree — so every expectation below cites the source it encodes, and ALL of it is inference:
- *
- * - orca (`/root/orca-main`, MIT, a shipping grok integration) — `permission_prompt` plus prose
- * messages, `src/shared/agent-hook-listener.ts:2370-2402` (readers) and `:3994-4012` (precedence).
- * - grok's own shipped docs — `turn_complete | approval_required | session_ready | task_complete |
- * agent_error`, `~/.grok/docs/user-guide/05-configuration.md:414`.
- *
- * The mapping is therefore built to be safe under BOTH vocabularies: the routine per-tool prompt is
- * suppressed, a genuine ask still reaches NEEDS YOU under either spelling, and anything unrecognized
- * changes no state.
- */
-describe('normalizeGrok — Notification', () => {
- /**
- * THE regression this branch's first mapping had backwards. Orca's
- * `isGrokRoutinePermissionPromptNotification` (`agent-hook-listener.ts:2378-2389`) exists because
- * "Grok emits this before each tool even under bypassPermissions; PreToolUse already covers
- * progress" — its own named regression test is
- * `src/renderer/src/hooks/agent-hook-completion-notifications.test.ts:654`. Mapping it to `blocked`
- * fires markUnread (no cooldown), the needs-you chime, an OS notification while unfocused and a
- * phone inbox card on EVERY tool call.
- */
- it('the routine per-tool permission prompt is suppressed, not a NEEDS YOU', () => {
- expect(
- normalizeGrok(
- env({
- hookEventName: 'notification',
- notificationType: 'permission_prompt',
- message: 'Tool permission requested',
- level: 'info'
- })
- )
- ).toBeNull()
- // Level absent is the same routine case (orca: `!level || level === 'info'`), and the message is
- // compared trimmed + case-folded.
+ it.each([
+ 'rate_limit',
+ 'authentication_failed',
+ 'invalid_request',
+ 'server_error',
+ 'max_output_tokens',
+ 'unknown'
+ ])('stop_failure %s ends the turn so the badge cannot stick on working', (error) => {
expect(
normalizeGrok(
- env({
- hookEventName: 'notification',
- notificationType: 'permission_prompt',
- message: ' tool permission requested '
- })
+ env({ hookEventName: 'stop_failure', sessionId: 's1', error, lastAssistantMessage: error })
)
- ).toBeNull()
+ ).toMatchObject({ state: 'done', lastMessage: error })
})
- /**
- * The suppression must survive grok's OTHER dialect. grok's envelope is documented camelCase
- * throughout, so `permissionPrompt` is a plausible spelling of the same type — and comparing the
- * type raw would make it miss the suppression and fall through to `includes('permission')`, i.e.
- * bring the per-tool-call strobe straight back. The type therefore goes through the same
- * `grokCanonical` rule the event name uses (orca canonicalizes too, to snake_case:
- * `normalizeHookEventName`, `agent-hook-listener.ts:2201-2210`).
- */
- it('suppresses the routine prompt in EVERY spelling of its type', () => {
- for (const notificationType of ['permissionPrompt', 'permission_prompt', 'Permission-Prompt', 'PERMISSION_PROMPT']) {
- expect(
- normalizeGrok(
- env({ hookEventName: 'notification', notificationType, message: 'tool permission requested' })
- ),
- notificationType
- ).toBeNull()
- }
+ it('an unrecognized stop_failure error type is a no-op', () => {
+ expect(normalizeGrok(env({ hookEventName: 'stop_failure', error: 'future_error' }))).toBeNull()
})
+})
- it('reads the other ask + idle types in camelCase too (one canonicalization, not three)', () => {
- expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'agentNeedsInput' }))
- ).toMatchObject({ state: 'waiting' })
- expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'elicitationDialog' }))
- ).toMatchObject({ state: 'waiting' })
+describe('normalizeGrok — published 1.0.13 events', () => {
+ it('keeps working after PermissionDenied because the turn continues after the tool decision', () => {
expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'approvalRequired' }))
- ).toMatchObject({ state: 'blocked' })
- // And the closed set stays closed under canonicalization: an elicitation END is still inert.
- expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'elicitationComplete' }))
- ).toBeNull()
+ normalizeGrok(env({ hookEventName: 'permission_denied', sessionId: 's1', toolName: 'write_file' }))
+ ).toMatchObject({ kind: 'state', state: 'working' })
})
- it('a GENUINE ask still reaches NEEDS YOU — the suppression is narrow, not a mute', () => {
- // Same type, a real message: this is the ask a human must answer.
+ it.each([
+ 'user_interrupt',
+ 'permission_rejected',
+ 'permission_cancelled',
+ 'max_turns',
+ 'no_progress',
+ 'unknown'
+ ] as const)('carries closed StopCancelled reason %s without deciding the badge transition yet', (reason) => {
expect(
normalizeGrok(
env({
- hookEventName: 'notification',
- notificationType: 'permission_prompt',
- message: 'Bash wants to run `rm -rf build`'
+ hookEventName: 'stop_cancelled',
+ sessionId: 's1',
+ reason,
+ subagentType: 'explore',
+ lastAssistantMessage: 'not allowed'
})
)
- ).toMatchObject({ state: 'blocked' })
- // Same type and the routine message, but LOUDER than info — orca's level condition fails, so it
- // is treated as a real ask rather than swallowed.
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: 's1',
+ kind: 'state',
+ cancelReason: reason,
+ subagentType: 'explore',
+ lastMessage: 'not allowed'
+ })
+ })
+
+ it('rejects an unrecognized StopCancelled reason', () => {
+ expect(normalizeGrok(env({ hookEventName: 'stop_cancelled', reason: 'future_reason' }))).toBeNull()
+ })
+
+ it('normalizes SubagentStart and SubagentStop without inventing an instance id', () => {
expect(
- normalizeGrok(
- env({
- hookEventName: 'notification',
- notificationType: 'permission_prompt',
- message: 'tool permission requested',
- level: 'warn'
- })
- )
- ).toMatchObject({ state: 'blocked' })
+ normalizeGrok(env({ hookEventName: 'subagent_start', sessionId: 's1', subagentType: 'explore' }))
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: 's1',
+ kind: 'subagent-start',
+ subagentType: 'explore'
+ })
expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'agent_needs_input' }))
- ).toMatchObject({ state: 'waiting' })
+ normalizeGrok(env({ hook_event_name: 'subagent_stop', session_id: 's1', subagent_type: 'explore' }))
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: 's1',
+ kind: 'subagent-end',
+ subagentType: 'explore'
+ })
})
- /**
- * grok's own docs name `approval_required` (05-configuration.md:414) where orca names
- * `permission_prompt`; the two share no substring, so both are matched. Without this the mapping
- * fires for NOTHING if the docs' vocabulary turns out to be the real one.
- */
- it("maps grok's own documented `approval_required` to NEEDS YOU as well", () => {
+ it('carries the closed compaction phase while leaving the current badge untouched', () => {
+ expect(
+ normalizeGrok(env({ hookEventName: 'pre_compact', sessionId: 'old', trigger: 'manual' }))
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: 'old',
+ kind: 'state',
+ compactionPhase: 'pre'
+ })
expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'approval_required' }))
- ).toMatchObject({ state: 'blocked' })
+ normalizeGrok(env({ hook_event_name: 'post_compact', session_id: 'new', trigger: 'auto' }))
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: 'new',
+ kind: 'state',
+ compactionPhase: 'post'
+ })
+ expect(normalizeGrok(env({ hookEventName: 'post_compact', trigger: 'future' }))).toBeNull()
})
+})
- /**
- * The rescue signal, and the reason it must key off the MESSAGE: grok states its idle prompt in
- * prose (orca's `isGrokIdleNotification`, `agent-hook-listener.ts:2391-2402`) and neither source
- * names an "idle" TYPE — so the type-only test this replaced could never fire. It is the only thing
- * that can clear a node stuck on `working` after an Esc, because grok sends no hook for an
- * interrupted turn at all.
- */
- it('detects idle from the MESSAGE — each of orca\'s four phrases clears the badge', () => {
- for (const message of [
- 'Type your message or @path/to/file',
- 'enter send · shift-tab normal mode',
- 'shift-tab normal mode',
- 'Ask a side question without interrupting'
- ]) {
- expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'session_ready', message })),
- message
- ).toMatchObject({ state: 'done', idle: true, interrupted: true })
+/** Grok 1.0.13 publishes the closed Notification vocabulary in
+ * `~/.grok/docs/user-guide/10-hooks.md:99`; `:162` says permission_prompt fires only while its UI
+ * actually waits. The literal unknown cases keep that contract closed. */
+describe('normalizeGrok — Notification', () => {
+ it.each([
+ {
+ name: 'permission_prompt',
+ payload: {
+ hookEventName: 'notification',
+ notificationType: 'permission_prompt',
+ message: 'Tool permission requested',
+ level: 'info'
+ },
+ want: {
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: undefined,
+ kind: 'state',
+ state: 'blocked',
+ lastMessage: undefined
+ }
+ },
+ {
+ name: 'idle_prompt',
+ payload: { hookEventName: 'notification', notificationType: 'idle_prompt' },
+ want: {
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: undefined,
+ kind: 'state',
+ state: 'done',
+ interrupted: true,
+ idle: true
+ }
+ },
+ {
+ name: 'task_complete',
+ payload: { hookEventName: 'notification', notificationType: 'task_complete' },
+ want: null
+ },
+ {
+ name: 'unknown',
+ payload: { hookEventName: 'notification', notificationType: 'some_future_type' },
+ want: null
+ },
+ {
+ name: 'unknown containing permission',
+ payload: { hookEventName: 'notification', notificationType: 'permission_reminder' },
+ want: null
+ },
+ {
+ name: 'unknown camelCase near-alias',
+ payload: { hookEventName: 'notification', notificationType: 'permissionPrompt' },
+ want: null
+ },
+ {
+ name: 'unknown hyphenated near-alias',
+ payload: { hookEventName: 'notification', notificationType: 'permission-prompt' },
+ want: null
}
- // No type at all is still enough — the message carries it.
- expect(
- normalizeGrok(env({ hookEventName: 'notification', message: 'TYPE YOUR MESSAGE' }))
- ).toMatchObject({ state: 'done', idle: true, interrupted: true })
+ ])('maps published and unknown type: $name', ({ payload, want }) => {
+ expect(normalizeGrok(env(payload))).toEqual(want)
})
- it('keeps a type-based idle fallback for a message-less notification', () => {
- // Belt and braces: unlike a substring test on an ASK word, a false positive here can only CLEAR
- // a badge — it can never leave one stuck.
- expect(normalizeGrok(env({ hookEventName: 'notification', notificationType: 'idle_prompt' }))).toMatchObject({
- state: 'done',
- idle: true,
- interrupted: true
- })
+ it.each([
+ 'approval_required',
+ 'agent_needs_input',
+ 'elicitation_dialog',
+ 'session_ready',
+ 'permission_request'
+ ])('retires the old inferred Notification type %s', (notificationType) => {
+ expect(normalizeGrok(env({ hookEventName: 'notification', notificationType }))).toBeNull()
})
- /**
- * Precedence, mirroring orca's own order (`agent-hook-listener.ts:3994-4012`: routine-suppress,
- * then ask, then idle): a payload claiming BOTH an ask type and idle prose is asking. A wrongly
- * cleared NEEDS YOU is the failure this branch exists to prevent; a badge that lingers one hook
- * longer is not.
- */
- it('an ask type wins over idle prose in the same payload', () => {
+ it('does not infer idle state from prose attached to an unknown type', () => {
expect(
normalizeGrok(
env({
hookEventName: 'notification',
- notificationType: 'permission_request',
- message: 'Approve? (type your message to answer)'
+ notificationType: 'session_ready',
+ message: 'Type your message or @path/to/file'
})
)
- ).toMatchObject({ state: 'blocked' })
- })
-
- /**
- * Orca reads the kind from THREE keys (`notificationType ?? notification_type ?? type`,
- * `agent-hook-listener.ts:2370-2376`); the third was missing here.
- */
- it('reads the notification kind from the bare `type` key too', () => {
- expect(normalizeGrok(env({ hookEventName: 'notification', type: 'approval_required' }))).toMatchObject({
- state: 'blocked'
- })
- expect(
- normalizeGrok(env({ hookEventName: 'notification', type: 'agent_needs_input' }))
- ).toMatchObject({ state: 'waiting' })
- })
-
- it('an UNKNOWN notification type is a no-op — a future type must not stick a badge', () => {
- expect(normalizeGrok(env({ hookEventName: 'notification', notificationType: 'auth_success' }))).toBeNull()
- expect(normalizeGrok(env({ hookEventName: 'notification' }))).toBeNull()
- })
-
- /**
- * The asking types are matched EXACTLY, not by substring: grok's vocabulary is claude-derived, and
- * claude's `elicitation_complete` / `elicitation_response` fire when an elicitation ENDS. A
- * substring test on 'elicit' would read those as a fresh ask and leave NEEDS YOU on a node that
- * just finished — the exact bug normalizeClaude's closed set exists to avoid
- * (normalize.test.ts, 'informational / unknown Notification types do not change state').
- */
- it('the elicitation END notifications are informational, NOT a new ask', () => {
- for (const type of ['elicitation_complete', 'elicitation_response', 'agent_completed']) {
- expect(normalizeGrok(env({ hookEventName: 'notification', notificationType: type })), type).toBeNull()
- }
- // The dialog OPENING is the one elicitation type that does ask.
- expect(
- normalizeGrok(env({ hookEventName: 'notification', notificationType: 'elicitation_dialog' }))
- ).toMatchObject({ state: 'waiting' })
+ ).toBeNull()
})
- it('reads the notification type in the SDK snake_case dialect too', () => {
+ it('reads the published types through the SDK key dialect', () => {
expect(
normalizeGrok(env({ hook_event_name: 'notification', notification_type: 'permission_prompt' }))
- ).toMatchObject({ state: 'blocked' })
- expect(
- normalizeGrok(env({ hook_event_name: 'notification', notification_type: 'agent_needs_input' }))
- ).toMatchObject({ state: 'waiting' })
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: undefined,
+ kind: 'state',
+ state: 'blocked',
+ lastMessage: undefined
+ })
expect(
normalizeGrok(env({ hook_event_name: 'notification', notification_type: 'idle_prompt' }))
- ).toMatchObject({ state: 'done', idle: true, interrupted: true })
+ ).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: undefined,
+ kind: 'state',
+ state: 'done',
+ interrupted: true,
+ idle: true
+ })
+ })
+
+ it('reads a published type through the legacy bare type key', () => {
+ expect(normalizeGrok(env({ hookEventName: 'notification', type: 'permission_prompt' }))).toEqual({
+ nodeId: 'n1',
+ agentId: 'grok',
+ sessionId: undefined,
+ kind: 'state',
+ state: 'blocked',
+ lastMessage: undefined
+ })
})
})
@@ -315,11 +312,6 @@ describe('normalizeGrok — dialects', () => {
expect(normalizeGrok(env({ hookEventName: 'PreToolUse' }))).toMatchObject({ state: 'working' })
})
- it('ignores events we do not subscribe to yet', () => {
- for (const ev of ['pre_compact', 'post_compact', 'subagent_start', 'subagent_stop', 'permission_denied']) {
- expect(normalizeGrok(env({ hookEventName: ev, sessionId: 's1' })), ev).toBeNull()
- }
- })
})
/**
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index c9888f6a1..f94e77862 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -73,6 +73,18 @@ export interface NormalizedAgentEvent {
// subagent
toolUseId?: string
subagentType?: string
+ // grok StopCancelled only: normalized state-less so the mirror can make the session-aware badge
+ // decision (a subagent cancellation must not end its parent session).
+ cancelReason?:
+ | 'user_interrupt'
+ | 'permission_rejected'
+ | 'permission_cancelled'
+ | 'max_turns'
+ | 'no_progress'
+ | 'unknown'
+ // grok compaction lifecycle. These events carry the old/new session ids but do not themselves
+ // prove the agent is working or idle, so consumers may update identity without moving state.
+ compactionPhase?: 'pre' | 'post'
taskLabel?: string
durationMs?: number
tokens?: number
@@ -455,9 +467,9 @@ export function normalizeGemini(env: RawHookEnvelope): NormalizedAgentEvent | nu
//
// A CLOSED match, not a substring: the docs name exactly ONE type (reference.md:278), and an
// unknown future one must stay a no-op — a badge that sticks on a finished node is a failure
- // this codebase has shipped before. Grok is the cautionary tale: there
- // `type.includes('permission')` turned a notification that fires before every tool call into a
- // strobing NEEDS YOU. Widening this "to be safe" is the unsafe direction.
+ // this codebase has shipped before. Grok is the cautionary tale: there, a substring match on
+ // "permission" turned a notification that fires before every tool call into a strobing NEEDS
+ // YOU. Widening this "to be safe" is the unsafe direction.
//
// Nothing here can be answered from our side: the hook is observability only and its
// flow-control fields are ignored (reference.md:284-285), so this reports state and no more —
@@ -586,33 +598,18 @@ interface GrokPayload {
* `notificationType ?? notification_type ?? type` (`src/shared/agent-hook-listener.ts:2370-2376`).
* Reading a key a shipped integration reads costs nothing and closes a whole dialect. */
type?: string
- /** Notification only: the human-readable status line. Orca reads it as a bare `message`
- * (`agent-hook-listener.ts:3973`) — one spelling, so no dual read here — and grok's idle state is
- * detectable ONLY from it (see GROK_IDLE_MESSAGES). */
- message?: string
- /** Notification only: severity. Orca reads a bare `level` (`agent-hook-listener.ts:3975`) and uses
- * it to tell grok's routine per-tool permission prompt (`info`) from a louder one. */
- level?: string
/** Stop only: 'end_turn' for a genuine turn end; 'channel_closed'/'shutdown' at session close. */
reason?: string
+ /** StopFailure only: the closed error class tested by its matcher. */
+ error?: string
+ /** PreCompact/PostCompact only: `manual` or `auto`. */
+ trigger?: string
+ /** Events fired inside a subagent use its type as identity; there is no measured instance id. */
+ subagentType?: string
+ subagent_type?: string
prompt?: string
}
-/**
- * Fragments of a grok `Notification` MESSAGE that mean "sat at the prompt, nothing running".
- *
- * Provenance: orca's `isGrokIdleNotification` (`/root/orca-main/src/shared/agent-hook-listener.ts:2391-2402`,
- * MIT), matched case-insensitively as substrings of the message — grok states its idle prompt in
- * prose ("Type your message…", "shift-tab normal mode"), not with a notification TYPE. This list is
- * therefore INFERRED from another integration's reader, not measured here: no grok binary was run.
- */
-const GROK_IDLE_MESSAGES = [
- 'type your message',
- 'enter send',
- 'shift-tab normal',
- 'ask a side question'
-] as const
-
/**
* ONE canonicalization for every grok VALUE we compare — lowercase, letters only, so all of
* 'pre_tool_use', 'PreToolUse', 'preToolUse' and 'Pre-Tool-Use' land on 'pretooluse'. grok's envelope
@@ -622,6 +619,24 @@ const GROK_IDLE_MESSAGES = [
*/
const grokCanonical = (v: string | undefined): string => (v ?? '').toLowerCase().replace(/[^a-z]/g, '')
+const GROK_STOP_FAILURE_TYPES = new Set([
+ 'ratelimit',
+ 'authenticationfailed',
+ 'invalidrequest',
+ 'servererror',
+ 'maxoutputtokens',
+ 'unknown'
+])
+
+const GROK_CANCEL_REASONS: Record<string, NonNullable<NormalizedAgentEvent['cancelReason']>> = {
+ userinterrupt: 'user_interrupt',
+ permissionrejected: 'permission_rejected',
+ permissioncancelled: 'permission_cancelled',
+ maxturns: 'max_turns',
+ noprogress: 'no_progress',
+ unknown: 'unknown'
+}
+
/** Canonical form of a grok event name: 'pre_tool_use', 'PreToolUse' and 'preToolUse' all → 'pretooluse'. */
const grokEventName = (p: GrokPayload): string =>
grokCanonical(p.hookEventName ?? p.hook_event_name)
@@ -685,98 +700,76 @@ export function normalizeGrok(env: RawHookEnvelope): NormalizedAgentEvent | null
? { ...base, kind: 'state', state: 'done', lastMessage }
: { ...base, kind: 'state', state: 'done', interrupted: true }
}
- // The turn died on an API error — grok skips Stop entirely here, exactly as Claude does.
- if (ev === 'stopfailure')
- return { ...base, kind: 'state', state: 'done', errored: true, lastMessage }
- if (ev === 'notification') {
- // grok's Notification is the one event whose vocabulary we could not measure, and the three
- // sources that describe it do not agree, so this mapping is deliberately safe in BOTH
- // directions. Every line below cites where its words come from; all of it is INFERENCE — no
- // grok binary was run on the machine that wrote it.
- // - orca (`/root/orca-main`, MIT, a shipping grok integration) names `permission_prompt`
- // plus prose messages (`agent-hook-listener.ts:2378-2402`).
- // - grok's own shipped docs name a different set entirely:
- // `turn_complete | approval_required | session_ready | task_complete | agent_error` — but see
- // the `approval_required` branch below: that list is the NOTIFICATION TRIGGER vocabulary
- // (`~/.grok/docs/user-guide/05-configuration.md:414`), not documented `notificationType` values.
- // Everything unrecognized stays a deliberate NO-OP: same discipline as normalizeClaude, where an
- // unknown future type sticking a badge on a finished node is the failure that has actually
- // happened before.
- //
- // The type goes through `grokCanonical`, the SAME rule the event name uses — so the literals
- // below are letters-only ('permission_prompt', 'permissionPrompt' and 'Permission-Prompt' all
- // become 'permissionprompt'). This is not decoration: grok's envelope is documented camelCase
- // throughout, so `permissionPrompt` is a plausible spelling, and comparing it raw would let it
- // MISS the suppression below and fall through to the `includes('permission')` ask branch — i.e.
- // reinstate the per-tool-call strobe in the one direction that hurts. Orca canonicalizes too, to
- // snake_case (`normalizeHookEventName`, `agent-hook-listener.ts:2201-2210`); we reuse OUR one rule
- // rather than adopting a second spelling convention into this file.
- const type = grokCanonical(p.notificationType ?? p.notification_type ?? p.type)
- // message/level are prose, not identifiers: trim + lowercase only, field-for-field as orca reads
- // them (`:3973-3975`). Canonicalizing THESE would strip the spaces the phrases are made of.
- const message = (p.message ?? '').trim().toLowerCase()
- const level = (p.level ?? '').trim().toLowerCase()
- // THE ROUTINE PER-TOOL PROMPT IS NOT A NEEDS-YOU. Orca's
- // `isGrokRoutinePermissionPromptNotification` (`agent-hook-listener.ts:2378-2389`) suppresses it,
- // comment verbatim: "Grok emits this before each tool even under bypassPermissions; PreToolUse
- // already covers progress." Its regression test is
- // `src/renderer/src/hooks/agent-hook-completion-notifications.test.ts:654`.
- // Left unsuppressed, EVERY grok tool call would raise `blocked` here, and downstream that edge
- // has no de-duplication: markUnread with no cooldown, the needs-you chime, an OS notification
- // whenever the window is unfocused, and one phone inbox card per working→blocked edge.
- // Matched exactly as orca matches it — the precise type, the precise message, and a level that
- // is `info` or absent — so a LOUDER prompt (a real ask reusing the same type) still gets through.
- if (
- type === 'permissionprompt' &&
- message === 'tool permission requested' &&
- (!level || level === 'info')
- ) {
- return null
+ // The turn died on an API error — grok skips Stop entirely here, exactly as Claude does. The
+ // matcher vocabulary is closed in grok 1.0.13; a future value is a no-op rather than a guessed
+ // terminal state.
+ if (ev === 'stopfailure') {
+ if (!GROK_STOP_FAILURE_TYPES.has(grokCanonical(p.error))) return null
+ return { ...base, kind: 'state', state: 'done', lastMessage }
+ }
+ if (ev === 'permissiondenied') return { ...base, kind: 'state', state: 'working' }
+ if (ev === 'stopcancelled') {
+ const cancelReason = GROK_CANCEL_REASONS[grokCanonical(p.reason)]
+ if (!cancelReason) return null
+ // Transport the classified reason state-less: the mirror owns the session-aware transition
+ // and can ignore a subagent cancellation without losing session identity.
+ return {
+ ...base,
+ kind: 'state',
+ cancelReason,
+ subagentType: p.subagentType ?? p.subagent_type,
+ lastMessage
}
- // A genuine permission ask is a FAMILY of names ('permission_prompt', 'permission_request', …),
- // and its worst case is a `blocked` badge the agent's next hook clears — so substring is the
- // right trade.
- // `approval_required` is INFERENCE ON INFERENCE, and is labelled that way deliberately: grok's
- // docs name it only as a `[ui.notifications].events` TRIGGER (05-configuration.md:414), never as a
- // `notificationType` value. The bridge is `10-hooks.md:153`, "the matcher tests … the notification
- // type on `Notification`", which implies the type vocabulary is drawn from that same set. Weaker
- // than the orca spelling above, and matched exactly for that reason — it costs nothing if wrong
- // (an unused literal) and is the only thing that fires at all if grok's own words are the real ones.
- if (type.includes('permission') || type === 'approvalrequired') {
- return { ...base, kind: 'state', state: 'blocked', lastMessage }
+ }
+ if (ev === 'subagentstart' || ev === 'subagentstop') {
+ return {
+ ...base,
+ kind: ev === 'subagentstart' ? 'subagent-start' : 'subagent-end',
+ subagentType: p.subagentType ?? p.subagent_type
}
- // The asking types are a CLOSED set, exactly as in normalizeClaude, and for its reason: grok's
- // vocabulary is claude-derived, and claude's `elicitation_complete` / `elicitation_response` are
- // informational — they fire when an elicitation ENDS. A substring test on 'elicit' would match
- // them and leave NEEDS YOU on a node that just finished, with no later hook to clear it.
+ }
+ if (ev === 'precompact' || ev === 'postcompact') {
+ const trigger = grokCanonical(p.trigger)
+ if (trigger !== 'manual' && trigger !== 'auto') return null
+ return {
+ ...base,
+ kind: 'state',
+ compactionPhase: ev === 'precompact' ? 'pre' : 'post'
+ }
+ }
+ if (ev === 'notification') {
+ // Grok 1.0.13 publishes this CLOSED vocabulary in
+ // `~/.grok/docs/user-guide/10-hooks.md:99`: idle_prompt, permission_prompt, task_complete.
+ // `:162` is the load-bearing correction to the old orca-derived branch: permission_prompt fires
+ // ONLY while a permission UI is actually waiting, never routinely before every tool call.
+ // Exact classification prevents a future permission-like name from sticking NEEDS YOU with no
+ // later hook guaranteed to clear it.
+ const type = p.notificationType ?? p.notification_type ?? p.type
+ // NO ROUTINE-PROMPT SUPPRESSION HERE, and that is a measured decision rather than an omission.
+ //
+ // The old orca-derived branch dropped a `permission_prompt` whose message was exactly
+ // "Tool permission requested" at level `info`, because orca reports grok emitting one before
+ // EVERY tool call. Captured live on 1.0.13 (2026-09-01), the GENUINE prompt — fired with a real
+ // permission dialog on screen — is byte-for-byte that same triple:
+ // notificationType 'permission_prompt' · message 'Tool permission requested' · level 'info'
+ // and no routine per-tool-call notification was emitted at all. So that filter cannot separate
+ // the routine case from a real ask on this version: it can only swallow the real one.
//
- // DELIBERATELY NOT setting `awaitingInput` here, and the omission is a bet either way. Codex's
- // `request_user_input` ends its turn with the question still open (the answer arrives as a fresh
- // UserPromptSubmit), so `normalizeCodex` marks the ask `awaitingInput` and `reduceEntry` holds
- // `waiting` through the turn-end `done` — without it the node goes green over a session that is
- // still waiting on the user. Whether grok's elicitation behaves the same way is UNMEASURED: if it
- // does, grok has that bug; if it does not, setting the flag would hold NEEDS YOU on a node that
- // genuinely finished, which is the worse of the two. So it stays off until someone watches a real
- // grok elicitation cross a turn boundary — device checklist item 33.
- if (type === 'elicitationdialog' || type === 'agentneedsinput') {
- return { ...base, kind: 'state', state: 'waiting', lastMessage }
+ // Swallowing it is the worse of the two failures. A strobe is loud and obvious; a suppressed ask
+ // leaves grok waiting for approval with the node showing nothing, and no later hook is
+ // guaranteed to correct it. If a future grok does emit the routine prompt, it must be told apart
+ // by something that actually differs — not by a message the real ask also carries.
+ if (type === 'permission_prompt') {
+ return { ...base, kind: 'state', state: 'blocked', lastMessage }
}
- // Idle at the prompt: the RESCUE signal for a node stuck on `working`. grok fires no hook at all
- // for an interrupted turn (Esc), so this is the only thing that can ever clear one — which is
- // why it is keyed off the MESSAGE (GROK_IDLE_MESSAGES, per orca) and not off a type. A
- // type-only test was dead code: neither source names an "idle" type.
- // It is checked AFTER the ask branches on purpose, mirroring orca's own precedence
- // (`agent-hook-listener.ts:3994-4012`: routine-suppress, then ask, then idle) — a payload that
- // claims both an ask type and idle prose is asking, and a wrongly-cleared badge is the failure
- // this whole branch exists to prevent. `type.includes('idle')` is kept as a belt-and-braces
- // fallback for a message-less idle notification: unlike a substring test on an ASK word it can
- // only ever CLEAR a badge, so a false positive costs a badge, never a stuck one.
- if (GROK_IDLE_MESSAGES.some((m) => message.includes(m)) || type.includes('idle')) {
+ if (type === 'idle_prompt') {
return { ...base, kind: 'state', state: 'done', interrupted: true, idle: true }
}
+ // The spec names task_complete as a user-attention notification, but never says it ends a turn.
+ // Stop remains the documented turn-end signal, so task_complete and every future type are
+ // informational no-ops rather than guessed badge transitions.
return null
}
- // Not subscribed in v1: PermissionDenied, SubagentStart/Stop, PreCompact/PostCompact.
return null
}