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): normalize grok's hook dialect into the shared agent event model
enes06906bd7c9a6
diff --git a/src/shared/agents/hook-events.ts b/src/shared/agents/hook-events.tsindex 01fee751e..635d3d4ce 100644--- a/src/shared/agents/hook-events.ts+++ b/src/shared/agents/hook-events.ts@@ -11,6 +11,15 @@// rewrites only the events IT knows, so a stale instance's command survived on every event the// other list lacked. Keeping the lists here is what makes an install a complete rewrite.+/**+ * One managed hook subscription: an event name, or an event name PLUS the matcher to write for it.+ * Only grok needs the second form — its tool-event `matcher` is a real REGEX, and a bare `*` is+ * invalid there and silently stops tool events from firing at all (measured on the shipped 1.0.0+ * binary). `.*` is the value that works. claude/codex/gemini stay plain strings, so their emitted+ * config is byte-identical to what it has always been.+ */+export type ManagedHookEvent = string | { event: string; matcher: string }+/** Claude Code hook events. Each maps to a `NormalizedAgentEvent` in shared/agents/normalize.ts. */export const CLAUDE_HOOK_EVENTS = ['SessionStart',@@ -29,3 +38,25 @@ export const CLAUDE_HOOK_EVENTS = [/** Gemini CLI hook events — its own names, NOT Claude's (see normalizeGemini). */export const GEMINI_HOOK_EVENTS = ['BeforeAgent', 'AfterAgent', 'AfterTool', 'BeforeTool'] as const++/**+ * Grok hook events (→ normalizeGrok). Only the nine events VERIFIED against the shipped 1.0.0+ * binary are subscribed. The docs additionally list PermissionDenied, SubagentStart, SubagentStop,+ * PreCompact and PostCompact; 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 — but it is not measured,+ * so it is not here.+ */+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',+ // Tool events need the regex matcher. `.*` matches every tool name; an omitted matcher is+ // documented as matching everything too, but `.*` is the form measured working here.+ { 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.tsnew file mode 100644index 000000000..70434fc82--- /dev/null+++ b/src/shared/agents/normalize.grok.test.ts@@ -0,0 +1,151 @@+import { describe, expect, it } from 'vitest'+import { grokRawFields, normalizeClaude, normalizeGrok } from './normalize'++/**+ * Grok's hook envelope is its own dialect: camelCase keys whose `hookEventName` VALUE is+ * snake_case ("pre_tool_use"), and the grok SDK path converts the top-level keys to snake_case.+ * Both spellings are therefore read, and the event name is canonicalized rather than matched+ * literally — measured against the shipped 1.0.0 docs, not inferred from claude's shape.+ */+const env = (payload: Record<string, unknown>) => ({ nodeId: 'n1', agentId: 'grok', payload })++describe('normalizeGrok — lifecycle', () => {+ it('maps session_start / session_end to the session phases', () => {+ expect(normalizeGrok(env({ hookEventName: 'session_start', sessionId: 's1' }))).toEqual({+ nodeId: 'n1',+ agentId: 'grok',+ sessionId: 's1',+ kind: 'session',+ sessionPhase: 'start'+ })+ expect(normalizeGrok(env({ hookEventName: 'session_end', sessionId: 's1' }))?.sessionPhase).toBe('end')+ })++ it('treats user_prompt_submit as the turn start (newTurn)', () => {+ const e = normalizeGrok(env({ hookEventName: 'user_prompt_submit', sessionId: 's1', prompt: 'ship it' }))+ expect(e).toMatchObject({ kind: 'state', state: 'working', newTurn: true, task: 'ship it' })+ })++ it('keeps the node working across every tool event, including a tool FAILURE', () => {+ for (const ev of ['pre_tool_use', 'post_tool_use', 'post_tool_use_failure']) {+ expect(normalizeGrok(env({ hookEventName: ev, sessionId: 's1' }))).toMatchObject({+ kind: 'state',+ state: 'working'+ })+ }+ })+})++describe('normalizeGrok — Stop', () => {+ it('a genuine turn end is done, carrying the last assistant message', () => {+ const e = normalizeGrok(+ env({ hookEventName: 'stop', sessionId: 's1', reason: 'end_turn', lastAssistantMessage: 'done' })+ )+ expect(e).toMatchObject({ state: 'done', lastMessage: 'done' })+ // Not interrupted — a genuine turn end DOES earn the completion alert. Asserted separately+ // (as normalize.test.ts does for claude's Stop) because toMatchObject demands the key exist.+ expect(e?.interrupted).toBeFalsy()+ })++ it('an ABSENT reason is still a real turn end (never swallow the badge event)', () => {+ expect(normalizeGrok(env({ hookEventName: 'stop', sessionId: 's1' }))).toMatchObject({ state: 'done' })+ })++ it('the observe-only session-close Stop is marked interrupted, so no completion alert fires', () => {+ for (const reason of ['channel_closed', 'shutdown']) {+ const e = normalizeGrok(env({ hookEventName: 'stop', sessionId: 's1', reason, lastAssistantMessage: 'x' }))+ expect(e).toMatchObject({ state: 'done', interrupted: true })+ expect(e?.lastMessage).toBeUndefined()+ }+ })++ 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' })+ })+})++describe('normalizeGrok — Notification', () => {+ it('a permission notification is blocked; an input request is waiting', () => {+ expect(+ normalizeGrok(env({ hookEventName: 'notification', notificationType: 'permission_prompt' }))+ ).toMatchObject({ state: 'blocked' })+ expect(+ normalizeGrok(env({ hookEventName: 'notification', notificationType: 'agent_needs_input' }))+ ).toMatchObject({ state: 'waiting' })+ })++ it('an idle notification is the rescue signal (done + idle), not a NEEDS YOU', () => {+ expect(normalizeGrok(env({ hookEventName: 'notification', notificationType: 'idle_prompt' }))).toMatchObject({+ state: 'done',+ idle: true,+ interrupted: true+ })+ })++ 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()+ })+})++describe('normalizeGrok — dialects', () => {+ it('reads the SDK snake_case key spelling too', () => {+ expect(+ normalizeGrok(env({ hook_event_name: 'stop', session_id: 's9', last_assistant_message: 'ok' }))+ ).toMatchObject({ sessionId: 's9', state: 'done', lastMessage: 'ok' })+ })++ it('accepts a PascalCase event name (canonicalized, not matched literally)', () => {+ 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()+ }+ })+})++/**+ * Grok also merges `~/.claude/settings.json`, where nodeterm's CLAUDE managed hook already lives —+ * so every grok event ALSO fires claude.sh and POSTs to /hook/claude. That leg must stay inert:+ * this is the test that keeps it a property instead of a coincidence.+ */+describe('the claude-compat cross-fire is inert', () => {+ it('normalizeClaude returns null for every grok payload', () => {+ for (const ev of ['session_start', 'user_prompt_submit', 'pre_tool_use', 'post_tool_use', 'stop', 'session_end']) {+ expect(+ normalizeClaude({ nodeId: 'n1', agentId: 'claude', payload: { hookEventName: ev, sessionId: 's1' } }),+ ev+ ).toBeNull()+ }+ })+})++describe('grokRawFields', () => {+ it('hands the shells ONE canonical field set from either dialect', () => {+ expect(+ grokRawFields({+ hookEventName: 'pre_tool_use',+ sessionId: 's1',+ cwd: '/w',+ toolName: 'spawn_subagent',+ toolUseId: 't1',+ toolInput: { subagent_type: 'explore' }+ })+ ).toEqual({+ event: 'pretooluse',+ sessionId: 's1',+ cwd: '/w',+ toolName: 'spawn_subagent',+ toolUseId: 't1',+ toolInput: { subagent_type: 'explore' }+ })+ expect(grokRawFields({ hook_event_name: 'session_end', session_id: 's2' })).toMatchObject({+ event: 'sessionend',+ sessionId: 's2'+ })+ })+})diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.tsindex 90cabdc76..47f9e9181 100644--- a/src/shared/agents/normalize.ts+++ b/src/shared/agents/normalize.ts@@ -338,10 +338,121 @@ export function normalizeOpencode(env: RawHookEnvelope): NormalizedAgentEvent |return null}+// grok hook payload. Its dialect differs from every other agent here in two ways, both measured+// against the shipped 1.0.0 CLI: the keys are camelCase, and `hookEventName`'s VALUE is+// snake_case ("pre_tool_use"). Hooks registered through the grok SDK convert the top-level keys to+// snake_case instead, so both spellings occur in the wild — hence every field is read twice and+// the event name is CANONICALIZED (lowercased, letters only) rather than compared literally.+// There is deliberately no `transcript_path` in this envelope: grok's transcript is DERIVED from+// (cwd, sessionId), which is why the shells' raw listeners need `grokRawFields` below.+interface GrokPayload {+ hookEventName?: string+ hook_event_name?: string+ sessionId?: string+ session_id?: string+ cwd?: string+ toolName?: string+ tool_name?: string+ toolUseId?: string+ tool_use_id?: string+ toolInput?: Record<string, unknown>+ tool_input?: Record<string, unknown>+ lastAssistantMessage?: string+ last_assistant_message?: string+ notificationType?: string+ notification_type?: string+ /** Stop only: 'end_turn' for a genuine turn end; 'channel_closed'/'shutdown' at session close. */+ reason?: string+ prompt?: string+}++/** Canonical form of a grok event name: 'pre_tool_use', 'PreToolUse' and 'preToolUse' all → 'pretooluse'. */+const grokEventName = (p: GrokPayload): string =>+ (p.hookEventName ?? p.hook_event_name ?? '').toLowerCase().replace(/[^a-z]/g, '')++/**+ * The fields the SHELLS need from a raw grok payload, in nodeterm's own names — one definition+ * shared by `src/main` and `src/server` so their raw listeners can never drift. Exported (and+ * unit-tested) rather than re-read at each call site, because the two-dialect reading is exactly+ * the kind of detail that gets half-copied.+ */+export function grokRawFields(payload: Record<string, unknown>): {+ event: string+ sessionId?: string+ cwd?: string+ toolName?: string+ toolUseId?: string+ toolInput?: Record<string, unknown>+} {+ const p = payload as GrokPayload+ return {+ event: grokEventName(p),+ sessionId: p.sessionId ?? p.session_id,+ cwd: p.cwd,+ toolName: p.toolName ?? p.tool_name,+ toolUseId: p.toolUseId ?? p.tool_use_id,+ toolInput: p.toolInput ?? p.tool_input+ }+}++export function normalizeGrok(env: RawHookEnvelope): NormalizedAgentEvent | null {+ const p = env.payload as GrokPayload+ const base = { nodeId: env.nodeId, agentId: env.agentId, sessionId: p.sessionId ?? p.session_id }+ const ev = grokEventName(p)+ const lastMessage = p.lastAssistantMessage ?? p.last_assistant_message++ if (ev === 'sessionstart') return { ...base, kind: 'session', sessionPhase: 'start' }+ if (ev === 'sessionend') return { ...base, kind: 'session', sessionPhase: 'end' }++ // grok's turn start. Flagged newTurn so per-turn fan-out clears once per turn, not per tool event.+ if (ev === 'userpromptsubmit') {+ return { ...base, kind: 'state', state: 'working', task: p.prompt, newTurn: true }+ }+ // A FAILED tool is still mid-turn: grok fires PostToolUseFailure and carries on, so mapping it+ // to anything but `working` would clear RUNNING while the agent is still going.+ if (ev === 'pretooluse' || ev === 'posttooluse' || ev === 'posttoolusefailure') {+ return { ...base, kind: 'state', state: 'working' }+ }+ if (ev === 'stop') {+ // grok fires a SECOND, observe-only Stop when the session itself closes (reason+ // 'channel_closed' / 'shutdown'). Reporting that as a finished turn would pop a "your agent is+ // done" notification every time a session ends, so it is marked `interrupted` — the flag the+ // renderer already reads as "skip the completion alert and the unread dot" — and its+ // lastAssistantMessage (an earlier turn's text) is dropped. A MISSING reason is treated as a+ // genuine turn end: this is the one event the RUNNING badge depends on ending, so an unknown+ // dialect must fail towards reporting it, not towards swallowing it.+ const genuineTurnEnd = p.reason === undefined || p.reason === 'end_turn'+ return genuineTurnEnd+ ? { ...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', lastMessage }+ if (ev === 'notification') {+ // grok's notification-type vocabulary is not documented as a closed set (its `matcher` tests+ // the type as a regex), so we classify by substring and default to a NO-OP. Same discipline as+ // normalizeClaude: an unrecognized future type must never stick a badge on a finished node.+ const type = (p.notificationType ?? p.notification_type ?? '').toLowerCase()+ if (type.includes('permission')) return { ...base, kind: 'state', state: 'blocked', lastMessage }+ if (type.includes('input') || type.includes('elicit')) {+ return { ...base, kind: 'state', state: 'waiting', lastMessage }+ }+ // Idle at the prompt: the RESCUE signal for a node stuck on `working`. grok fires no hook at+ // all for an interrupted turn, so this is the only thing that can clear one.+ if (type.includes('idle')) {+ return { ...base, kind: 'state', state: 'done', interrupted: true, idle: true }+ }+ return null+ }+ // Not subscribed in v1: PermissionDenied, SubagentStart/Stop, PreCompact/PostCompact.+ return null+}+export function normalizeFor(agentId: AgentId, env: RawHookEnvelope): NormalizedAgentEvent | null {if (agentId === 'claude') return normalizeClaude(env)if (agentId === 'codex') return normalizeCodex(env)if (agentId === 'gemini') return normalizeGemini(env)if (agentId === 'opencode') return normalizeOpencode(env)+ if (agentId === 'grok') return normalizeGrok(env)return null}