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.

fix(status): publish needs-you and image-paste receipts only on evidence

review64230e11368b
diff --git a/CLAUDE.md b/CLAUDE.md
index a81a8d718..e7e45f537 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1358,6 +1358,17 @@ session.
PTY write has no image receipt. Never synthesize that key or fall back between routes.
The macOS shortcuts reference explains both keys; its Server Edition copy explicitly
says Ctrl+V cannot transfer the viewer's clipboard to the host. SSH keeps remote uploads.
+ **The path paste has a receipt for claude, and only for claude** (`terminal/image-paste-confirm.ts`,
+ both surfaces through `pasteWithImageReceipt`). MEASURED on Claude Code 2.1.285 (bracketed paste,
+ captures in `terminal/__fixtures__/claude-image-paste.json`): a path to an existing
+ png/jpg/jpeg/gif/webp (any case) becomes `[Image #N]` in the composer within ~60 ms; bmp, svg,
+ heic, tiff and a missing file stay text; `N` keeps counting for the session and does NOT reset
+ when the composer is cleared. So the receipt reads OUR xterm buffer (the emulator, not tmux) for
+ placeholder numbers that were NOT on screen before the paste, up to 3 s: "Image attached", else
+ "Pasted the path — not confirmed as an image" (`.term-paste-pill`, top-right so it never covers
+ the copy pill or the agent's bottom-left input line). Only when a claude CLI is in the pane
+ (`agentProcessInPane`); every other agent was not measured and gets the paste with no receipt
+ either way — nothing is claimed on its behalf. A terminal disposed mid-wait reports nothing.
**Copying now says so**: the OSC 52 handler floats a transient `Copied N lines` pill over the
terminal's BOTTOM-RIGHT corner (`.term-copy-pill`, the same class on the canvas node and the
kanban card modal — one session seen twice must not speak in two voices; bottom-right because
@@ -1937,6 +1948,32 @@ else, and its context links must keep classifying across restarts).
harmful. The `auto` permission-mode **version gate is claude's alone** (it is fed by a `claude
--version` probe), and grok's mode flag must go **BEFORE** its `--` separator, which is
end-of-options. Full picture, dialect traps and the device checklist: **`docs/grok-agent.md`**.
+- **Grok NEEDS YOU is confirmed against grok's own event log** (`core/agents/grok-permission-gate.ts`,
+ inside the hook server, so both shells get it from one place). MEASURED on grok 1.0.13
+ (2026-09-30, interactive TUI against a local fake chat_completions model, fixture
+ `shared/agents/__fixtures__/grok/permission-events.json`): the `permission_prompt` notification is
+ genuine (fired 1–20 ms after grok writes `permission_requested` to `<session dir>/events.jsonl`),
+ but grok is silent about the ANSWER — approve fires no hook until the approved tool FINISHES (the
+ capture's 10 s command read NEEDS YOU for 10 s), a dismissed dialog (Ctrl+C) fires none at all
+ (the only later hook is `idle_prompt` 60 s on, which the mirror deliberately never lets clear a
+ `blocked` node — a stuck badge until the next prompt), and a rejection fires `permission_denied`
+ then cancels the turn with no Stop (RUNNING for 60 s). `events.jsonl` records all three:
+ `permission_resolved {decision: allow|deny|cancelled}` and `turn_ended {outcome: cancelled}`. The
+ gate ties each notification to ONE `permission_requested` written within 5 s before it and
+ publishes what the file says: still pending ⇒ `blocked` + a bounded 1 s watch (a `stat` per tick
+ while nothing changes); answered ⇒ `working` (unverified — a file read is not a hook POST); a
+ cancelled turn ⇒ `done` + `interrupted`. **The trap it is shaped around**: a SUBAGENT's prompt
+ fires with the PARENT's `sessionId` while its request is in the CHILD's `events.jsonl` — reading
+ the parent's file alone would find the parent's older, already-approved request and publish
+ "answered" over an open child dialog. So candidates are the sessions this node's hooks named
+ (children post their own ids), zero or several matches publish the hook unchanged, and every new
+ prompt ends the previous watch (the replay found that exact race: the parent's spawn approval
+ landed 90 ms before the child's prompt). Closed sets throughout; an unknown decision, unreadable
+ file or unparsable timestamp is today's behaviour, never a guess. Per-node ordering is kept (a
+ confirm read holds that node's later hooks, ≤ 500 ms; polls run off that chain and discard a read
+ that straddled a newer hook). A remote (SSH) grok node's file is on its host, so it reads "cannot
+ tell" and behaves exactly as before — a remote leg is a follow-up. Unmeasured: `events.jsonl`'s
+ shape on other grok versions (a changed shape degrades to today's behaviour).
- **Grok chat view (⌘M + phone `chat.page`)** — `parseGrokChat` (`core/grok-chat.ts`) reads
`chat_history.jsonl` into claude's `ChatMessage`/`ChatPart` shapes (no new wire field): typed
prompts, assistant text, tool calls (`arg` = the salient argument — `command`, `target_file`, …, in
diff --git a/docs/grok-agent.md b/docs/grok-agent.md
index c1c8ccf69..e62a9b5b2 100644
--- a/docs/grok-agent.md
+++ b/docs/grok-agent.md
@@ -404,6 +404,17 @@ ai-name / comments).
**Verified corrections to the original assumptions:**
+0. **The answer to a permission dialog is in `events.jsonl`, not in a hook** (measured 2026-09-30 on
+ 1.0.13 against a local fake model; fixture `src/shared/agents/__fixtures__/grok/permission-events.json`).
+ Approve: no hook until the approved tool finishes. Dismiss (Ctrl+C): no hook at all — the badge
+ stayed NEEDS YOU until the next prompt. Reject: `permission_denied`, then the turn is cancelled
+ with no Stop. `<session dir>/events.jsonl` records `permission_requested`, `permission_resolved`
+ (`decision`: `allow`/`deny`/`cancelled`) and `turn_ended` (`outcome: cancelled`), so the hook
+ server's grok permission gate (`core/agents/grok-permission-gate.ts`) publishes from it. A
+ subagent's prompt carries the PARENT's `sessionId` while its request is in the CHILD's file — see
+ the gate's header. Remote (SSH) nodes: not read yet (the file is on the host); they behave as
+ before.
+
1. **The `Notification` vocabulary is published and closed** — it was previously written up here as
UNVERIFIED and able to fail in BOTH directions: silence (NEEDS YOU never lighting, since grok
documents no counterpart to claude's `PermissionRequest`) or over-firing (orca reports a
diff --git a/src/core/agents/grok-permission-gate.test.ts b/src/core/agents/grok-permission-gate.test.ts
new file mode 100644
index 000000000..b628caf8d
--- /dev/null
+++ b/src/core/agents/grok-permission-gate.test.ts
@@ -0,0 +1,201 @@
+// Driven by REAL captures: `__fixtures__/grok/permission-events.json` holds the hook payloads and the
+// `events.jsonl` lines grok 1.0.13 wrote for four answered permission dialogs (allow, deny, cancel,
+// and a subagent's prompt). The file content each test serves is exactly what grok had written at
+// the moment in question — sliced by the record timestamps, never hand-written.
+import { describe, expect, it } from 'vitest'
+import path from 'path'
+import fixture from '../../shared/agents/__fixtures__/grok/permission-events.json'
+import { normalizeGrok, type NormalizedAgentEvent } from '../../shared/agents/normalize'
+import {
+ createGrokPermissionGate,
+ parseGrokEvents,
+ permissionVerdict,
+ requestNear,
+ type GrokPermissionGateDeps
+} from './grok-permission-gate'
+import { grokSessionDir } from './grok-paths'
+
+type Hook = Record<string, unknown> & { hookEventName: string; sessionId: string; timestamp?: string; cwd: string }
+type Scenario = { hooks: Hook[]; sessions: Record<string, string[]> }
+const S = fixture.scenarios as unknown as Record<'allow' | 'deny' | 'cancel' | 'subagent', Scenario>
+const SESSIONS_DIR = '/home/user/.grok/sessions'
+const tsOf = (line: string): number => Date.parse((JSON.parse(line) as { ts: string }).ts)
+const hookAt = (h: Hook): number => Date.parse(h.timestamp as string)
+/** The file as grok had written it at time `t`. */
+const fileAt = (lines: string[], t: number): string =>
+ lines.filter((l) => tsOf(l) <= t).map((l) => l + '\n').join('')
+
+function harness(sc: Scenario) {
+ let clock = 0
+ const timers: { at: number; fn: () => void; id: number }[] = []
+ let nextId = 1
+ const out: NormalizedAgentEvent[] = []
+ const fileFor = new Map<string, string>()
+ for (const id of Object.keys(sc.sessions)) {
+ const dir = grokSessionDir({ sessionsDir: SESSIONS_DIR, cwd: '/work/project', sessionId: id })
+ fileFor.set(path.join(dir as string, 'events.jsonl'), id)
+ }
+ const content = (file: string): string | null => {
+ const id = fileFor.get(file)
+ return id ? fileAt(sc.sessions[id], clock) : null
+ }
+ const deps: GrokPermissionGateDeps = {
+ sessionsDir: () => SESSIONS_DIR,
+ readFile: async (f) => content(f),
+ stat: async (f) => {
+ const c = content(f)
+ return c === null ? null : { size: c.length, mtimeMs: 0 }
+ },
+ now: () => clock,
+ setTimer: (fn, ms) => {
+ const id = nextId++
+ timers.push({ at: clock + ms, fn, id })
+ return id
+ },
+ clearTimer: (t) => {
+ const i = timers.findIndex((x) => x.id === t)
+ if (i >= 0) timers.splice(i, 1)
+ },
+ pollMs: 1000,
+ pendingMaxMs: 60 * 60 * 1000,
+ afterResolutionMaxMs: 60_000,
+ confirmTimeoutMs: 500
+ }
+ const gate = createGrokPermissionGate((e) => out.push(e), deps)
+ const flush = async (): Promise<void> => {
+ for (let i = 0; i < 20; i++) await Promise.resolve()
+ }
+ const advanceTo = async (t: number): Promise<void> => {
+ for (;;) {
+ await flush()
+ timers.sort((a, b) => a.at - b.at)
+ const next = timers[0]
+ if (!next || next.at > t) break
+ timers.shift()
+ clock = next.at
+ next.fn()
+ await flush()
+ }
+ clock = t
+ await flush()
+ }
+ const post = async (h: Hook): Promise<void> => {
+ await advanceTo(hookAt(h))
+ const e = normalizeGrok({ nodeId: 'n1', agentId: 'grok', payload: h })
+ gate.handle('n1', h, e ? { ...e, verified: true } : null)
+ await flush()
+ }
+ return { out, post, advanceTo, states: () => out.map((e) => e.state + (e.interrupted ? '*' : '')) }
+}
+
+const firstTs = (sc: Scenario, type: string): number => {
+ for (const lines of Object.values(sc.sessions))
+ for (const l of lines) if ((JSON.parse(l) as { type: string }).type === type) return tsOf(l)
+ throw new Error(type)
+}
+
+describe('parse + verdict over the captured files', () => {
+ it('reads the request, its resolution and the decision grok recorded', () => {
+ for (const [name, decision] of [
+ ['allow', 'allow'],
+ ['deny', 'deny'],
+ ['cancel', 'cancelled']
+ ] as const) {
+ const lines = Object.values(S[name].sessions)[0]
+ const recs = parseGrokEvents(lines.join('\n'))
+ const req = recs.find((r) => r.type === 'permission_requested')!
+ const v = permissionVerdict(recs, req.ts, 'run_terminal_command')
+ expect(v).toMatchObject({ phase: 'resolved', decision })
+ // Measured: deny and cancel both end the turn as cancelled; allow ends it normally.
+ expect(v).toMatchObject({ turnEnded: name === 'allow' ? 'other' : 'cancelled' })
+ }
+ })
+
+ it('is pending while only the request is on disk', () => {
+ const lines = Object.values(S.allow.sessions)[0]
+ const t = firstTs(S.allow, 'permission_requested')
+ const recs = parseGrokEvents(fileAt(lines, t))
+ expect(permissionVerdict(recs, t, 'run_terminal_command')).toEqual({ phase: 'pending' })
+ })
+
+ it('an unknown decision is unknown, never a resolution', () => {
+ const lines = Object.values(S.allow.sessions)[0].map((l) => l.replace('"decision":"allow"', '"decision":"later"'))
+ const recs = parseGrokEvents(lines.join('\n'))
+ const req = recs.find((r) => r.type === 'permission_requested')!
+ expect(permissionVerdict(recs, req.ts, req.type === 'permission_requested' ? req.toolName : '')).toEqual({ phase: 'unknown' })
+ })
+
+ it('the request window ties a notification only to a request written just before it', () => {
+ const lines = Object.values(S.allow.sessions)[0]
+ const recs = parseGrokEvents(lines.join('\n'))
+ const t = firstTs(S.allow, 'permission_requested')
+ expect(requestNear(recs, t + 5)).not.toBeNull()
+ expect(requestNear(recs, t + 30_000)).toBeNull()
+ })
+})
+
+describe('the gate, replaying each captured scenario', () => {
+ it('allow: NEEDS YOU while the dialog is open, working the moment grok records the approval', async () => {
+ const h = harness(S.allow)
+ const hooks = S.allow.hooks
+ const iNotif = hooks.findIndex((x) => x.hookEventName === 'notification')
+ for (const x of hooks.slice(0, iNotif + 1)) await h.post(x)
+ expect(h.states().at(-1)).toBe('blocked')
+ // Grok writes permission_resolved at the click; the next hook is PostToolUse 10 s later.
+ const resolvedAt = firstTs(S.allow, 'permission_resolved')
+ const post = hooks[iNotif + 1]
+ expect(hookAt(post) - resolvedAt).toBeGreaterThan(9_000)
+ await h.advanceTo(resolvedAt + 1500)
+ expect(h.out.at(-1)).toMatchObject({ state: 'working', verified: false, sessionId: post.sessionId })
+ for (const x of hooks.slice(iNotif + 1)) await h.post(x)
+ expect(h.states().at(-1)).toBe('done')
+ })
+
+ it('cancel (Ctrl+C): the badge clears to an interrupted done — grok sends no hook at all', async () => {
+ const h = harness(S.cancel)
+ for (const x of S.cancel.hooks) await h.post(x)
+ expect(h.states().at(-1)).toBe('blocked')
+ await h.advanceTo(firstTs(S.cancel, 'turn_ended') + 1500)
+ expect(h.states().at(-1)).toBe('done*')
+ })
+
+ it('deny: the permission_denied hook reads working, then the cancelled turn ends it', async () => {
+ const h = harness(S.deny)
+ for (const x of S.deny.hooks) await h.post(x)
+ await h.advanceTo(firstTs(S.deny, 'turn_ended') + 3000)
+ expect(h.states()).toContain('blocked')
+ expect(h.states().at(-1)).toBe('done*')
+ })
+
+ it("subagent: the child's prompt (parent sessionId) is tied to the CHILD's file, never the parent's old answer", async () => {
+ const h = harness(S.subagent)
+ const hooks = S.subagent.hooks
+ const notifs = hooks.filter((x) => x.hookEventName === 'notification')
+ expect(notifs).toHaveLength(2)
+ // Both notifications name the parent session — the trap.
+ expect(new Set(notifs.map((n) => n.sessionId)).size).toBe(1)
+ const second = hooks.indexOf(notifs[1])
+ for (const x of hooks.slice(0, second + 1)) await h.post(x)
+ // The parent's own request was resolved 90 ms before the child's notification. A parent-only
+ // read would have published that resolution over the child's open dialog.
+ expect(h.states().at(-1)).toBe('blocked')
+ })
+
+ it("subagent, child never seen: the parent's old, resolved request is NOT taken for the child's prompt", async () => {
+ const h = harness(S.subagent)
+ const parent = S.subagent.hooks.find((x) => x.hookEventName === 'session_start')!.sessionId
+ const hooks = S.subagent.hooks.filter((x) => x.sessionId === parent)
+ const second = hooks.filter((x) => x.hookEventName === 'notification')[1]
+ for (const x of hooks.slice(0, hooks.indexOf(second) + 1)) await h.post(x)
+ expect(h.states().at(-1)).toBe('blocked')
+ await h.advanceTo(hookAt(second) + 5_000)
+ expect(h.states().at(-1)).toBe('blocked')
+ })
+
+ it('a notification no request can be tied to is published exactly as before, and not watched', async () => {
+ const h = harness({ hooks: S.cancel.hooks, sessions: {} })
+ for (const x of S.cancel.hooks) await h.post(x)
+ await h.advanceTo(hookAt(S.cancel.hooks.at(-1)!) + 120_000)
+ expect(h.states().at(-1)).toBe('blocked')
+ })
+})
diff --git a/src/core/agents/grok-permission-gate.ts b/src/core/agents/grok-permission-gate.ts
new file mode 100644
index 000000000..d9e39f774
--- /dev/null
+++ b/src/core/agents/grok-permission-gate.ts
@@ -0,0 +1,514 @@
+// Grok's NEEDS YOU, confirmed against grok's own session event log before it is published and
+// cleared by that log when the dialog is answered.
+//
+// WHY. Grok's only "a permission dialog is open" signal is a `notification` hook with
+// `notificationType: 'permission_prompt'`, which `normalizeGrok` maps to `blocked`. MEASURED on grok
+// 1.0.13 (2026-09-30, interactive TUI against a local fake chat_completions model — fixture
+// `src/shared/agents/__fixtures__/grok/permission-events.json`), that hook is honest about the
+// OPENING and silent about everything after it:
+//
+// - approved in the pane: NO hook until the approved tool FINISHES. The fixture's command slept
+// 10 s, so the node sat on NEEDS YOU for 10 s while the agent was working.
+// - dismissed (Ctrl+C): NO hook at all. The turn is cancelled, and the only later hook is
+// `idle_prompt` 60 s afterwards, which the status mirror deliberately does NOT let clear a
+// `blocked` node (a node that is blocked is also idle at its prompt). So the node kept NEEDS YOU
+// until the next prompt: a stuck badge.
+// - rejected ("No, reject"): a `permission_denied` hook (→ `working`), then the turn is cancelled
+// with no Stop hook, so the node read RUNNING until the idle rescue 60 s later.
+//
+// Grok DOES record all of it, in `<session dir>/events.jsonl` (a sibling of `chat_history.jsonl`,
+// not in its shipped docs' layout list):
+//
+// {"type":"permission_requested","tool_name":"run_terminal_command","ts":"…Z"}
+// {"type":"permission_resolved","tool_name":"…","decision":"allow"|"deny"|"cancelled","wait_ms":N}
+// {"type":"turn_ended","outcome":"cancelled","cancellation_category":"permission_cancelled"|…}
+//
+// `permission_requested` is written ~5 ms BEFORE the notification hook fires (1–20 ms across the
+// captures), so at the moment the hook arrives the file already says whether the dialog is open.
+//
+// THE TRAP this module is shaped around: a SUBAGENT's permission prompt fires its notification with
+// the PARENT's `sessionId`, while its `permission_requested` is written to the CHILD's own
+// `events.jsonl`. Reading the parent's file alone would find the parent's EARLIER, already resolved
+// request and publish "resolved" over a real, open child dialog — suppressing an ask, which is the
+// worse of the two failures. So a notification is tied to exactly ONE request: the latest
+// `permission_requested` written within a few seconds of the notification's own timestamp, across
+// the sessions this node's hooks have named (parent and children — a child's own hooks carry the
+// child's id). Zero candidates or more than one means "we cannot tell", and the hook is published
+// exactly as before.
+//
+// RULES (each is a refusal; every "cannot tell" is today's behaviour, never a guess):
+// - Closed sets: the four record types above, the three decisions. An unknown decision, an
+// unreadable or missing file, an unparsable timestamp: the notification is published unchanged
+// and nothing watches it.
+// - Only a POSITIVE resolution record changes what is shown. Absence of a record is never evidence.
+// - Events derived from the file are published UNVERIFIED (a file read is not a hook POST), the
+// same rule the claude turn-interrupt marker follows.
+// - The watch is bounded (`pendingMaxMs` while the dialog is open, `afterResolutionMaxMs` after),
+// and it costs one `stat` per poll while nothing changes.
+// - Hook ordering is preserved per node: while a confirm read is in flight, that node's later
+// hook events wait behind it, so a stale `blocked` can never land after a newer event.
+//
+// A REMOTE (SSH) grok node's session lives on its host; the local file does not exist, so the
+// read answers "cannot tell" and the node behaves exactly as before. Lives in the hook server, so
+// Desktop and Server Edition get it from one place.
+import path from 'path'
+import { promises as fsp } from 'fs'
+import { grokRawFields, type NormalizedAgentEvent } from '../../shared/agents/normalize'
+import { grokSessionDir, grokSessionsDir } from './grok-paths'
+
+export const GROK_EVENTS_FILE = 'events.jsonl'
+
+/** The decisions grok 1.0.13 writes on `permission_resolved`. Closed: anything else is unknown. */
+export const GROK_PERMISSION_DECISIONS = ['allow', 'deny', 'cancelled'] as const
+export type GrokPermissionDecision = (typeof GROK_PERMISSION_DECISIONS)[number]
+
+export type GrokEventRecord =
+ | { type: 'turn_started'; ts: number }
+ | { type: 'turn_ended'; ts: number; outcome: string | undefined }
+ | { type: 'permission_requested'; ts: number; toolName: string | undefined }
+ | { type: 'permission_resolved'; ts: number; toolName: string | undefined; decision: string | undefined }
+
+const TRACKED = new Set(['turn_started', 'turn_ended', 'permission_requested', 'permission_resolved'])
+
+/** Parse the records this module reads. Other types and malformed lines are skipped. */
+export function parseGrokEvents(text: string): GrokEventRecord[] {
+ const out: GrokEventRecord[] = []
+ for (const line of text.split('\n')) {
+ if (!line.includes('"type"')) continue
+ let r: Record<string, unknown>
+ try {
+ r = JSON.parse(line) as Record<string, unknown>
+ } catch {
+ continue
+ }
+ if (!r || typeof r !== 'object' || typeof r.type !== 'string' || !TRACKED.has(r.type)) continue
+ const ts = typeof r.ts === 'string' ? Date.parse(r.ts) : NaN
+ if (!Number.isFinite(ts)) continue
+ const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
+ if (r.type === 'turn_started') out.push({ type: 'turn_started', ts })
+ else if (r.type === 'turn_ended') out.push({ type: 'turn_ended', ts, outcome: str(r.outcome) })
+ else if (r.type === 'permission_requested')
+ out.push({ type: 'permission_requested', ts, toolName: str(r.tool_name) })
+ else
+ out.push({
+ type: 'permission_resolved',
+ ts,
+ toolName: str(r.tool_name),
+ decision: str(r.decision)
+ })
+ }
+ return out
+}
+
+/** How far BEFORE the notification its request may have been written, and how far after. */
+export const GROK_REQUEST_WINDOW_BEFORE_MS = 5_000
+export const GROK_REQUEST_WINDOW_AFTER_MS = 500
+
+/** Index of the latest `permission_requested` written within the window around `notifiedAt`, or
+ * null. "Latest" because two prompts in one burst are answered newest-first on screen too. */
+export function requestNear(records: GrokEventRecord[], notifiedAt: number): number | null {
+ for (let i = records.length - 1; i >= 0; i--) {
+ const r = records[i]
+ if (r.type !== 'permission_requested') continue
+ const lead = notifiedAt - r.ts
+ if (lead <= GROK_REQUEST_WINDOW_BEFORE_MS && lead >= -GROK_REQUEST_WINDOW_AFTER_MS) return i
+ // Older requests only get older; stop at the first one outside the window.
+ if (lead > GROK_REQUEST_WINDOW_BEFORE_MS) return null
+ }
+ return null
+}
+
+export type GrokPermissionVerdict =
+ | { phase: 'pending' }
+ | {
+ phase: 'resolved'
+ decision: GrokPermissionDecision
+ /** Present once the turn has ended after the resolution. */
+ turnEnded?: 'cancelled' | 'other'
+ }
+ /** A newer turn began: whatever happened to this dialog, it is no longer what the node is doing. */
+ | { phase: 'superseded' }
+ | { phase: 'unknown' }
+
+/**
+ * What became of the request with timestamp `reqTs` and tool `toolName`. Requests inside one turn
+ * are answered one at a time, so the pairing is by ORDER within the turn: the k-th request since
+ * the turn started is answered by the k-th resolution. A resolution naming a different tool than
+ * its request means the pairing is not what we think it is: unknown.
+ */
+export function permissionVerdict(
+ records: GrokEventRecord[],
+ reqTs: number,
+ toolName: string | undefined
+): GrokPermissionVerdict {
+ const at = records.findIndex(
+ (r) => r.type === 'permission_requested' && r.ts === reqTs && r.toolName === toolName
+ )
+ if (at < 0) return { phase: 'unknown' }
+ let start = 0
+ for (let i = at; i >= 0; i--) {
+ if (records[i].type === 'turn_started') {
+ start = i
+ break
+ }
+ }
+ let ordinal = 0
+ for (let i = start; i <= at; i++) if (records[i].type === 'permission_requested') ordinal++
+ let seen = 0
+ let resolvedAt = -1
+ let decision: string | undefined
+ for (let i = start; i < records.length; i++) {
+ const r = records[i]
+ if (i > at && r.type === 'turn_started') return { phase: 'superseded' }
+ if (r.type !== 'permission_resolved') continue
+ seen++
+ if (seen === ordinal) {
+ if (i < at || r.toolName !== toolName) return { phase: 'unknown' }
+ resolvedAt = i
+ decision = r.decision
+ break
+ }
+ }
+ if (resolvedAt < 0) return { phase: 'pending' }
+ if (!(GROK_PERMISSION_DECISIONS as readonly string[]).includes(decision ?? '')) return { phase: 'unknown' }
+ for (let i = resolvedAt + 1; i < records.length; i++) {
+ const r = records[i]
+ if (r.type === 'turn_started') return { phase: 'superseded' }
+ if (r.type === 'turn_ended') {
+ return {
+ phase: 'resolved',
+ decision: decision as GrokPermissionDecision,
+ turnEnded: r.outcome === 'cancelled' ? 'cancelled' : 'other'
+ }
+ }
+ }
+ return { phase: 'resolved', decision: decision as GrokPermissionDecision }
+}
+
+/** True for the normalized event a grok `permission_prompt` notification produces. */
+export function isGrokPermissionPrompt(payload: Record<string, unknown>, e: NormalizedAgentEvent | null): boolean {
+ if (!e || e.kind !== 'state' || e.state !== 'blocked') return false
+ if (grokRawFields(payload).event !== 'notification') return false
+ const p = payload as { notificationType?: unknown; notification_type?: unknown; type?: unknown }
+ return (p.notificationType ?? p.notification_type ?? p.type) === 'permission_prompt'
+}
+
+export interface GrokPermissionGateDeps {
+ sessionsDir: () => string
+ /** The file's text, or null when it cannot be read. */
+ readFile: (file: string) => Promise<string | null>
+ /** size + mtime, or null when it cannot be stat'ed. */
+ stat: (file: string) => Promise<{ size: number; mtimeMs: number } | null>
+ now: () => number
+ setTimer: (fn: () => void, ms: number) => unknown
+ clearTimer: (t: unknown) => void
+ pollMs: number
+ /** How long an OPEN dialog is watched before the gate gives up (the badge then stays as is). */
+ pendingMaxMs: number
+ /** After a deny/cancel resolution, how long to wait for the turn to end. */
+ afterResolutionMaxMs: number
+ /** A confirm read slower than this publishes the hook unchanged. */
+ confirmTimeoutMs: number
+}
+
+/** Past this size only the file's tail is read; a turn's records are always near the end. */
+export const GROK_EVENTS_READ_MAX_BYTES = 4 * 1024 * 1024
+
+async function readTail(file: string): Promise<string | null> {
+ let fh: Awaited<ReturnType<typeof fsp.open>> | undefined
+ try {
+ fh = await fsp.open(file, 'r')
+ const { size } = await fh.stat()
+ const len = Math.min(size, GROK_EVENTS_READ_MAX_BYTES)
+ const buf = Buffer.alloc(len)
+ await fh.read(buf, 0, len, size - len)
+ let text = buf.toString('utf8')
+ // A cut first line is half a record; drop it.
+ if (len < size) text = text.slice(text.indexOf('\n') + 1)
+ return text
+ } catch {
+ return null
+ } finally {
+ await fh?.close().catch(() => {})
+ }
+}
+
+export const defaultGrokPermissionGateDeps = (): GrokPermissionGateDeps => ({
+ sessionsDir: () => grokSessionsDir(),
+ readFile: readTail,
+ stat: async (file) => {
+ try {
+ const s = await fsp.stat(file)
+ return { size: s.size, mtimeMs: s.mtimeMs }
+ } catch {
+ return null
+ }
+ },
+ now: () => Date.now(),
+ setTimer: (fn, ms) => {
+ const t = setTimeout(fn, ms)
+ ;(t as { unref?: () => void }).unref?.()
+ return t
+ },
+ clearTimer: (t) => clearTimeout(t as ReturnType<typeof setTimeout>),
+ pollMs: 1_000,
+ pendingMaxMs: 6 * 60 * 60 * 1000,
+ afterResolutionMaxMs: 60_000,
+ confirmTimeoutMs: 500
+})
+
+/** Sessions remembered per node (the parent and its recent children). */
+const SESSIONS_PER_NODE = 16
+
+interface Episode {
+ file: string
+ reqTs: number
+ toolName: string | undefined
+ /** The session id the hook named (the PARENT for a child's prompt): what synthetic events carry. */
+ hookSessionId: string | undefined
+ resolved: boolean
+ startedAt: number
+ resolvedAt: number
+ timer: unknown
+ lastStat: string
+}
+
+interface NodeState {
+ sessions: Map<string, string> // sessionId → cwd, insertion order = recency
+ chain: Promise<void>
+ episode: Episode | null
+ /** Bumped on every hook event delivered for the node. A poll whose read straddled one discards
+ * its answer and asks again next tick, so a file read can never land AFTER a newer hook. */
+ gen: number
+}
+
+export interface GrokPermissionGate {
+ /** Every grok hook event goes through here; `deliver` is the hook server's listener. */
+ handle(nodeId: string, payload: Record<string, unknown>, e: NormalizedAgentEvent | null): void
+ dispose(): void
+}
+
+export function createGrokPermissionGate(
+ deliver: (e: NormalizedAgentEvent) => void,
+ deps: GrokPermissionGateDeps = defaultGrokPermissionGateDeps()
+): GrokPermissionGate {
+ const nodes = new Map<string, NodeState>()
+ let disposed = false
+
+ const stateOf = (nodeId: string): NodeState => {
+ let s = nodes.get(nodeId)
+ if (!s) {
+ s = { sessions: new Map(), chain: Promise.resolve(), episode: null, gen: 0 }
+ nodes.set(nodeId, s)
+ }
+ return s
+ }
+
+ const remember = (s: NodeState, sessionId: string | undefined, cwd: string | undefined): void => {
+ if (!sessionId || !cwd) return
+ s.sessions.delete(sessionId)
+ s.sessions.set(sessionId, cwd)
+ while (s.sessions.size > SESSIONS_PER_NODE) s.sessions.delete(s.sessions.keys().next().value as string)
+ }
+
+ const endEpisode = (s: NodeState): void => {
+ if (s.episode?.timer) deps.clearTimer(s.episode.timer)
+ s.episode = null
+ }
+
+ const synthetic = (nodeId: string, ep: Episode, patch: Partial<NormalizedAgentEvent>): void => {
+ deliver({
+ nodeId,
+ agentId: 'grok',
+ kind: 'state',
+ ...(ep.hookSessionId ? { sessionId: ep.hookSessionId } : {}),
+ verified: false,
+ ...patch
+ })
+ }
+
+ /** Apply a verdict to an open episode. Returns true when the episode is over. */
+ const applyVerdict = (nodeId: string, ep: Episode, v: GrokPermissionVerdict): boolean => {
+ if (v.phase === 'unknown' || v.phase === 'superseded') return true
+ if (v.phase === 'pending') return deps.now() - ep.startedAt > deps.pendingMaxMs
+ if (v.turnEnded === 'cancelled') {
+ synthetic(nodeId, ep, { state: 'done', interrupted: true })
+ return true
+ }
+ if (!ep.resolved) {
+ ep.resolved = true
+ ep.resolvedAt = deps.now()
+ synthetic(nodeId, ep, { state: 'working' })
+ }
+ // Approved: the tool runs and grok's own PostToolUse/Stop hooks take over from here.
+ if (v.decision === 'allow' || v.turnEnded === 'other') return true
+ return deps.now() - ep.resolvedAt > deps.afterResolutionMaxMs
+ }
+
+ // Polls run OFF the node's delivery chain: a slow or hung read must never hold hook events back.
+ const poll = (nodeId: string, s: NodeState, ep: Episode): void => {
+ ep.timer = deps.setTimer(() => {
+ ep.timer = null
+ if (disposed || s.episode !== ep) return
+ void (async () => {
+ const gen = s.gen
+ const expired = (): boolean =>
+ ep.resolved
+ ? deps.now() - ep.resolvedAt > deps.afterResolutionMaxMs
+ : deps.now() - ep.startedAt > deps.pendingMaxMs
+ let done: boolean
+ try {
+ const st = await deps.stat(ep.file)
+ const key = st ? `${st.size}:${st.mtimeMs}` : ''
+ if (s.episode !== ep || disposed) return
+ if (!st) done = true
+ else if (key === ep.lastStat) done = expired()
+ else {
+ const text = await deps.readFile(ep.file)
+ if (s.episode !== ep || disposed) return
+ if (s.gen !== gen) done = expired()
+ else {
+ ep.lastStat = key
+ done =
+ text === null
+ ? true
+ : applyVerdict(nodeId, ep, permissionVerdict(parseGrokEvents(text), ep.reqTs, ep.toolName))
+ }
+ }
+ } catch {
+ done = true
+ }
+ if (s.episode !== ep) return
+ if (done) endEpisode(s)
+ else poll(nodeId, s, ep)
+ })()
+ }, deps.pollMs)
+ }
+
+ const confirm = async (
+ nodeId: string,
+ s: NodeState,
+ payload: Record<string, unknown>,
+ e: NormalizedAgentEvent,
+ out: (e: NormalizedAgentEvent) => void
+ ): Promise<void> => {
+ // A new prompt is what the node now shows, whether or not it can be tied to a request: the
+ // previous watch must not go on to publish ITS dialog's answer over this one. (Found by the
+ // subagent replay: the parent's spawn approval landed 90 ms before the child's prompt.)
+ endEpisode(s)
+ const raw = payload as { timestamp?: unknown }
+ const notifiedAt = typeof raw.timestamp === 'string' ? Date.parse(raw.timestamp) : NaN
+ if (!Number.isFinite(notifiedAt)) return out(e)
+ const matches: { file: string; records: GrokEventRecord[]; index: number }[] = []
+ for (const [sessionId, cwd] of s.sessions) {
+ const dir = grokSessionDir({ sessionsDir: deps.sessionsDir(), cwd, sessionId })
+ if (!dir) continue
+ const file = path.join(dir, GROK_EVENTS_FILE)
+ const text = await deps.readFile(file)
+ if (text === null) continue
+ const records = parseGrokEvents(text)
+ const index = requestNear(records, notifiedAt)
+ if (index !== null) matches.push({ file, records, index })
+ }
+ // Zero: nothing ties this notification to a request. Two or more: we cannot say which one it
+ // is about. Either way the hook is published exactly as it always was.
+ if (matches.length !== 1) return out(e)
+ const m = matches[0]
+ const req = m.records[m.index] as Extract<GrokEventRecord, { type: 'permission_requested' }>
+ const verdict = permissionVerdict(m.records, req.ts, req.toolName)
+ if (verdict.phase !== 'pending' && verdict.phase !== 'resolved') return out(e)
+ const ep: Episode = {
+ file: m.file,
+ reqTs: req.ts,
+ toolName: req.toolName,
+ hookSessionId: e.sessionId,
+ resolved: false,
+ startedAt: deps.now(),
+ resolvedAt: 0,
+ timer: null,
+ lastStat: ''
+ }
+ endEpisode(s)
+ if (verdict.phase === 'pending') {
+ out(e)
+ } else {
+ // Already answered by the time the hook arrived: publish what the file says instead of a
+ // dialog that is no longer on screen. The hook's own identity label is kept — it is the same
+ // POST, reclassified — while everything the watch derives later is unverified.
+ ep.resolved = true
+ ep.resolvedAt = deps.now()
+ if (verdict.turnEnded === 'cancelled') return out({ ...e, state: 'done', interrupted: true, lastMessage: undefined })
+ out({ ...e, state: 'working', lastMessage: undefined })
+ if (verdict.decision === 'allow' || verdict.turnEnded === 'other') return
+ }
+ s.episode = ep
+ poll(nodeId, s, ep)
+ }
+
+ const withTimeout = (p: Promise<void>, fallback: () => void): Promise<void> =>
+ new Promise<void>((resolve) => {
+ let settled = false
+ const t = deps.setTimer(() => {
+ if (settled) return
+ settled = true
+ fallback()
+ resolve()
+ }, deps.confirmTimeoutMs)
+ p.then(
+ () => {
+ if (settled) return
+ settled = true
+ deps.clearTimer(t)
+ resolve()
+ },
+ () => {
+ if (settled) return
+ settled = true
+ deps.clearTimer(t)
+ fallback()
+ resolve()
+ }
+ )
+ })
+
+ return {
+ handle(nodeId, payload, e) {
+ if (disposed) {
+ if (e) deliver(e)
+ return
+ }
+ const s = stateOf(nodeId)
+ const g = grokRawFields(payload)
+ remember(s, g.sessionId, g.cwd)
+ if (g.subagentId) remember(s, g.subagentId, g.cwd)
+ if (e && isGrokPermissionPrompt(payload, e)) {
+ s.chain = s.chain.then(() => {
+ let published = false
+ const once = (ev: NormalizedAgentEvent): void => {
+ if (published) return
+ published = true
+ s.gen++
+ deliver(ev)
+ }
+ const guarded = confirm(nodeId, s, payload, e, once).catch(() => once(e))
+ return withTimeout(guarded, () => once(e))
+ })
+ return
+ }
+ s.chain = s.chain.then(() => {
+ s.gen++
+ if (e) deliver(e)
+ const ep = s.episode
+ if (!ep || !e) return
+ // A new turn or a session boundary on the episode's session ends the watch: the dialog it
+ // was about belongs to a turn that is over.
+ if ((e.newTurn || e.kind === 'session') && e.sessionId === ep.hookSessionId) endEpisode(s)
+ })
+ },
+ dispose() {
+ disposed = true
+ for (const s of nodes.values()) endEpisode(s)
+ nodes.clear()
+ }
+ }
+}
diff --git a/src/core/agents/hook-server.grok-permission.test.ts b/src/core/agents/hook-server.grok-permission.test.ts
new file mode 100644
index 000000000..2f43efdb6
--- /dev/null
+++ b/src/core/agents/hook-server.grok-permission.test.ts
@@ -0,0 +1,81 @@
+// End to end through the REAL hook server: a grok `permission_prompt` POST, the gate reading a real
+// `events.jsonl` on disk, and the listener both shells install. The records are the captured ones
+// (`__fixtures__/grok/permission-events.json`, "cancel"), re-stamped to now so the request window
+// applies; nothing else about them is changed.
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import fs from 'node:fs'
+import path from 'node:path'
+import { request } from 'node:http'
+import { hookServer } from './hook-server'
+import { initPlatform, resetPlatformForTests } from '../platform'
+import { fakePlatform } from '../platform-fake'
+import { testTmpDir } from '../test-tmp'
+import type { NormalizedAgentEvent } from '../../shared/agents/normalize'
+import { defaultGrokPermissionGateDeps } from './grok-permission-gate'
+import { grokSessionDir } from './grok-paths'
+import fixture from '../../shared/agents/__fixtures__/grok/permission-events.json'
+
+const cancel = (fixture.scenarios as unknown as Record<string, { hooks: Record<string, unknown>[]; sessions: Record<string, string[]> }>).cancel
+const SID = Object.keys(cancel.sessions)[0]
+const lines = cancel.sessions[SID].map((l) => JSON.parse(l) as { ts: string; type: string })
+const events: NormalizedAgentEvent[] = []
+let sessionsDir = ''
+let eventsFile = ''
+
+beforeAll(async () => {
+ const dir = testTmpDir('nodeterm-grokgate-')
+ sessionsDir = path.join(dir, 'grok', 'sessions')
+ eventsFile = path.join(grokSessionDir({ sessionsDir, cwd: '/work/project', sessionId: SID }) as string, 'events.jsonl')
+ fs.mkdirSync(path.dirname(eventsFile), { recursive: true })
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: path.join(dir, 'ud') }))
+ await hookServer.start()
+ hookServer.setListener((e) => events.push(e))
+ hookServer.setGrokPermissionGateDeps({ ...defaultGrokPermissionGateDeps(), sessionsDir: () => sessionsDir, pollMs: 40 })
+})
+afterAll(() => hookServer.stop())
+
+function post(payload: Record<string, unknown>): Promise<number> {
+ const body = new URLSearchParams({ nodeId: 'g1', version: '2', payload: JSON.stringify(payload) }).toString()
+ return new Promise((resolve, reject) => {
+ const req = request(
+ {
+ host: '127.0.0.1',
+ port: hookServer.getPort(),
+ path: '/hook/grok',
+ method: 'POST',
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Nodeterm-Hook-Token': hookServer.getToken() }
+ },
+ (res) => {
+ res.resume()
+ res.on('end', () => resolve(res.statusCode ?? 0))
+ }
+ )
+ req.on('error', reject)
+ req.end(body)
+ })
+}
+
+const until = async (ok: () => boolean): Promise<void> => {
+ for (let i = 0; i < 100 && !ok(); i++) await new Promise((r) => setTimeout(r, 20))
+}
+
+describe('hook server + grok permission gate', () => {
+ it('a dismissed dialog clears NEEDS YOU from the event log, with no hook from grok', async () => {
+ const shift = Date.now() - Date.parse(lines.find((l) => l.type === 'permission_requested')!.ts)
+ const at = (l: { ts: string }): string => new Date(Date.parse(l.ts) + shift).toISOString()
+ const upToRequest = lines.slice(0, lines.findIndex((l) => l.type === 'permission_requested') + 1)
+ fs.writeFileSync(eventsFile, upToRequest.map((l) => JSON.stringify({ ...l, ts: at(l) }) + '\n').join(''))
+ for (const h of cancel.hooks) {
+ const t = Date.parse(h.timestamp as string) + shift
+ expect(await post({ ...h, timestamp: new Date(t).toISOString() })).toBe(204)
+ }
+ await until(() => events.some((e) => e.state === 'blocked'))
+ expect(events.at(-1)).toMatchObject({ state: 'blocked', agentId: 'grok' })
+ // The user presses Ctrl+C: grok appends the resolution and the cancelled turn end.
+ const rest = lines.slice(upToRequest.length)
+ fs.appendFileSync(eventsFile, rest.map((l) => JSON.stringify({ ...l, ts: at(l) }) + '\n').join(''))
+ await until(() => events.at(-1)?.state === 'done')
+ expect(events.at(-1)).toMatchObject({ state: 'done', interrupted: true, verified: false, sessionId: SID })
+ })
+})
diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.ts
index 26d9a1729..30d256536 100644
--- a/src/core/agents/hook-server.ts
+++ b/src/core/agents/hook-server.ts
@@ -13,6 +13,12 @@ import { parseEndpointEnv } from './hook-endpoint-parse'
import { hookSockPath } from './hook-sock-path'
import { canControlCanvas, type AgentId } from '../../shared/agents/config'
import { normalizeFor, type NormalizedAgentEvent } from '../../shared/agents/normalize'
+import {
+ createGrokPermissionGate,
+ defaultGrokPermissionGateDeps,
+ type GrokPermissionGate,
+ type GrokPermissionGateDeps
+} from './grok-permission-gate'
import { classifyClaudeConfigDir, configDirFromTranscriptPath } from '../claude-accounts-core'
import { claudeAccountsSnapshot } from '../claude-config-dir'
import type { CodexIdentityEvent, ObservedClaudeAccount } from '../../shared/types'
@@ -460,6 +466,24 @@ export class HookServer {
this.listener = cb
}
+ private grokPermissionGate: GrokPermissionGate | null = null
+ private grokGateDeps: GrokPermissionGateDeps | undefined
+ /** Test seam: the grok permission gate's file/timer deps. */
+ setGrokPermissionGateDeps(deps: GrokPermissionGateDeps): void {
+ this.grokPermissionGate?.dispose()
+ this.grokPermissionGate = null
+ this.grokGateDeps = deps
+ }
+ private grokGate(): GrokPermissionGate {
+ if (!this.grokPermissionGate) {
+ this.grokPermissionGate = createGrokPermissionGate(
+ (e) => this.listener?.(e),
+ this.grokGateDeps ?? defaultGrokPermissionGateDeps()
+ )
+ }
+ return this.grokPermissionGate
+ }
+
// Raw payload listener: receives the parsed (un-normalized) hook JSON. Drives the
// contextTail/subagentTail features, which need transcript_path (not in NormalizedAgentEvent).
// `meta` carries what the transport knows about the caller (see HookEventMeta).
@@ -1029,8 +1053,14 @@ export class HookServer {
// structured answer (core/agents/permission-decision.ts, MIN_STRUCTURED_ANSWER_REVISION).
const raw = normalizeFor(agentId, { nodeId, agentId, payload })
const normalized = raw ? labelHeldForRevision(raw, clientRevision) : raw
- if (normalized && this.listener)
- this.listener({ ...normalized, verified, clientRevision, ...(account ? { account } : {}) })
+ const labelled = normalized
+ ? { ...normalized, verified, clientRevision, ...(account ? { account } : {}) }
+ : null
+ // Grok's permission prompt is confirmed against grok's own event log before it is
+ // published, and cleared from it once answered (core/agents/grok-permission-gate.ts).
+ // Every grok event goes through the gate so their order is kept per node.
+ if (agentId === 'grok') this.grokGate().handle(nodeId, payload, labelled)
+ else if (labelled && this.listener) this.listener(labelled)
}
res.writeHead(204)
res.end()
@@ -1468,6 +1498,8 @@ export class HookServer {
// Write what the ledger learned before the process can go: an awaited write races exit.
this.requestLedgerFile?.dispose()
this.requestLedgerFile = null
+ this.grokPermissionGate?.dispose()
+ this.grokPermissionGate = null
this.server?.close()
this.server = null
// The file must not advertise a listener that no longer exists (issue #445): a stopped server
diff --git a/src/core/agents/hook-verified-parity.test.ts b/src/core/agents/hook-verified-parity.test.ts
index 0a5bcead8..fc1a53480 100644
--- a/src/core/agents/hook-verified-parity.test.ts
+++ b/src/core/agents/hook-verified-parity.test.ts
@@ -259,7 +259,11 @@ describe('both shells register a 4-arg raw listener', () => {
// gate reading a field nothing writes — silently, and identically on both shells, which is
// exactly the failure the parity assertion above cannot see.
const hs = readFileSync(join(root, 'src/core/agents/hook-server.ts'), 'utf8')
- expect(hs).toMatch(/this\.listener\(\{\s*\.\.\.normalized,\s*verified/)
+ expect(hs).toMatch(/const labelled = normalized\s*\?\s*\{\s*\.\.\.normalized,\s*verified/)
+ // Grok events reach the same listener through the permission gate, which receives the
+ // LABELLED event — so `verified` rides a gated grok event exactly as it rides every other.
+ expect(hs).toMatch(/this\.grokGate\(\)\.handle\(nodeId, payload, labelled\)/)
+ expect(hs).toMatch(/this\.listener\(labelled\)/)
})
it('the src/core mirror is the consumer, on both shells', () => {
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 93b193afa..13fe7a2c0 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -38,6 +38,9 @@ import { parseOsc52 } from '../../terminal/osc52'
import { createOsc52Notice, dispatchOsc52Toast, handleOsc52Write } from '../../terminal/osc52-policy'
import { activateUnicode11 } from '../../terminal/unicode-width'
import { useCopyFeedback } from '../../terminal/useCopyFeedback'
+import { pasteWithImageReceipt } from '../../terminal/image-paste-confirm'
+import { usePasteReceipt } from '../../terminal/usePasteReceipt'
+import { agentProcessInPane } from '../../terminal/live-work'
import {
attachReplay,
cursorPlacementSeq,
@@ -151,6 +154,7 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
glassRef.current = glass
const [dropping, setDropping] = useState(false)
const [uploading, setUploading] = useState(false)
+ const pasteReceipt = usePasteReceipt()
// Same copy feedback as the canvas node — a copy here is the same act as a copy there, including
// the agent gate: a claude card stays silent because claude prints its own copy line.
const copy = useCopyFeedback({
@@ -524,7 +528,17 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
// A paste came from this window, which already has focus.
if (opts.raiseWindow) window.nodeTerminal.focusWindow()
term.focus()
- term.paste(paths.join(' ') + ' ')
+ // Same receipt as the canvas node (TerminalNode.insertFiles): attached only once the pane
+ // shows it.
+ const st = useAgentStatus.getState().byId[nodeId]
+ const paneAgent = spawn.agentId ?? st?.agentId
+ pasteWithImageReceipt(
+ term,
+ paths.join(' ') + ' ',
+ paths,
+ agentProcessInPane(paneAgent, st) ? paneAgent : undefined,
+ pasteReceipt.report
+ )
}
const onDrop = async (e: React.DragEvent) => {
@@ -572,6 +586,11 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
{copy.feedback.label}
</div>
)}
+ {pasteReceipt.receipt && (
+ <div className={`term-paste-pill${pasteReceipt.receipt.ok ? '' : ' term-paste-pill--warn'}`}>
+ {pasteReceipt.receipt.text}
+ </div>
+ )}
{searchOpen && (
<FindBar
query={search.query}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 93b63a57f..f9354b84d 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -222,6 +222,8 @@ import { mdViewHint } from '../lib/mdViewHint'
import { Tooltip } from '../components/Tooltip'
import { useTerminalSearch } from '../terminal/useTerminalSearch'
import { useCopyFeedback } from '../terminal/useCopyFeedback'
+import { pasteWithImageReceipt } from '../terminal/image-paste-confirm'
+import { usePasteReceipt } from '../terminal/usePasteReceipt'
import { ContextMeter } from '../components/ContextMeter'
import { isZoomModifierHeld } from '../lib/zoomModifier'
import { isHidden } from '../lib/ui-visibility'
@@ -1494,6 +1496,7 @@ export function TerminalNode({
// Overlay while dropped files upload to an SSH host (scp is seconds-long with zero feedback);
// doubles as a brief "Upload failed" flash when nothing made it.
const [uploadNote, setUploadNote] = useState<{ text: string; failed?: boolean } | null>(null)
+ const pasteReceipt = usePasteReceipt()
const uploadNoteTimer = useRef<ReturnType<typeof setTimeout> | null>(null)
useEffect(() => () => {
if (uploadNoteTimer.current) clearTimeout(uploadNoteTimer.current)
@@ -5565,7 +5568,17 @@ export function TerminalNode({
if (opts.raiseWindow) window.nodeTerminal.focusWindow()
term.focus()
useTerminalFocus.getState().remember(id)
- term.paste(paths.join(' ') + ' ')
+ // A pasted image is only reported as attached once the agent's own pane shows it (claude's
+ // `[Image #N]`); otherwise the receipt says the path went in, unconfirmed.
+ const st = agentStatusStore.getState().byId[id]
+ const paneAgent = agentId ?? st?.agentId
+ pasteWithImageReceipt(
+ term,
+ paths.join(' ') + ' ',
+ paths,
+ agentProcessInPane(paneAgent, st) ? paneAgent : undefined,
+ pasteReceipt.report
+ )
useAgentStatus.getState().setActive(id, true)
presence.reportFocus(id)
}
@@ -6354,6 +6367,11 @@ export function TerminalNode({
{copy.feedback.label}
</div>
)}
+ {pasteReceipt.receipt && (
+ <div className={`term-paste-pill${pasteReceipt.receipt.ok ? '' : ' term-paste-pill--warn'}`}>
+ {pasteReceipt.receipt.text}
+ </div>
+ )}
{/* Downloads started from a link's right-click menu, reported on the terminal they were
clicked in (the same corner as the copy receipt) — not in a drawer that may be shut. */}
<DownloadStrip
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 3a38df8ad..88b0ab1f6 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2664,6 +2664,30 @@ body,
animation: nt-copy-pill-in 120ms ease-out;
}
+/* Image-paste receipt (terminal/image-paste-confirm.ts): "Image attached" once the agent's pane
+ shows the image, or a warning that only the path went in. Same chrome as the copy receipt, in the
+ TOP-right corner so the two can never cover each other or the agent's bottom-left input line. */
+.term-paste-pill {
+ position: absolute;
+ right: 10px;
+ top: 8px;
+ z-index: 5;
+ pointer-events: none;
+ font-size: 11px;
+ font-weight: 600;
+ line-height: 1;
+ padding: 5px 9px;
+ border-radius: 7px;
+ color: var(--success);
+ background: color-mix(in srgb, var(--bg) 82%, transparent);
+ border: 1px solid color-mix(in srgb, var(--success) 35%, transparent);
+ animation: nt-copy-pill-in 120ms ease-out;
+}
+.term-paste-pill--warn {
+ color: var(--caution);
+ border-color: color-mix(in srgb, var(--caution) 35%, transparent);
+}
+
/* The hint is instruction, not status: quieter border, neutral text. */
.term-copy-pill--hint {
color: var(--text);
diff --git a/src/renderer/terminal/__fixtures__/claude-image-paste.json b/src/renderer/terminal/__fixtures__/claude-image-paste.json
new file mode 100644
index 000000000..0636bb7d1
--- /dev/null
+++ b/src/renderer/terminal/__fixtures__/claude-image-paste.json
@@ -0,0 +1,15 @@
+{
+ "_provenance": "captured live from Claude Code 2.1.285 on 2026-09-30: `tmux capture-pane -p` of a private tmux pane after bracketed pastes (`paste-buffer -p`, what xterm term.paste sends when the app asked for bracketed paste). Paths redacted; screens otherwise unchanged. Placeholder numbers #1..#11 were used by earlier pastes in the same session, which is why the first here is #12.",
+ "before": {
+ "pasted": "/work/project/pasted-1.png ",
+ "screen": " ▐▛███▛█ Claude Code v2.1.285\n▝▜██████▀ Opus 5.5 · API Usage Billing\n ▝▝ ▝▝ /work/project\n\n▎ Auto mode is now Claude Code's default permission mode.\n▎ Auto mode lets Claude handle permission prompts automatically. Claude checks each tool call for risky actions and prompt injection before executing,\n▎ runs the ones it assesses as lower-risk, and blocks the rest.\n▎ https://code.claude.com/docs/en/permission-modes\n\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n❯ [Image #12]\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n ⏵⏵ auto mode on (shift+tab to cycle) Ctrl+Y to paste deleted text\n"
+ },
+ "pngAndBmp": {
+ "pasted": "/work/project/pasted-1.png /work/project/x.bmp ",
+ "screen": " ▐▛███▛█ Claude Code v2.1.285\n▝▜██████▀ Opus 5.5 · API Usage Billing\n ▝▝ ▝▝ /work/project\n\n▎ Auto mode is now Claude Code's default permission mode.\n▎ Auto mode lets Claude handle permission prompts automatically. Claude checks each tool call for risky actions and prompt injection before executing,\n▎ runs the ones it assesses as lower-risk, and blocks the rest.\n▎ https://code.claude.com/docs/en/permission-modes\n\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n❯ [Image #12] [Image #13]/work/project/x.bmp\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n ⏵⏵ auto mode on (shift+tab to cycle) Ctrl+Y to paste deleted text\n"
+ },
+ "missingPng": {
+ "pasted": "/work/project/nope.png ",
+ "screen": " ▐▛███▛█ Claude Code v2.1.285\n▝▜██████▀ Opus 5.5 · API Usage Billing\n ▝▝ ▝▝ /work/project\n\n▎ Auto mode is now Claude Code's default permission mode.\n▎ Auto mode lets Claude handle permission prompts automatically. Claude checks each tool call for risky actions and prompt injection before executing,\n▎ runs the ones it assesses as lower-risk, and blocks the rest.\n▎ https://code.claude.com/docs/en/permission-modes\n\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n❯ [Image #12] [Image #13]/work/project/x.bmp /work/project/nope.png\n──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────\n ⏵⏵ auto mode on (shift+tab to cycle)\n"
+ }
+}
diff --git a/src/renderer/terminal/image-paste-confirm.test.ts b/src/renderer/terminal/image-paste-confirm.test.ts
new file mode 100644
index 000000000..fb13cb861
--- /dev/null
+++ b/src/renderer/terminal/image-paste-confirm.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it } from 'vitest'
+import fixture from './__fixtures__/claude-image-paste.json'
+import {
+ confirmImagePaste,
+ expectedImagePlaceholders,
+ imagePasteNotice,
+ imagePlaceholderNumbers,
+ pasteWithImageReceipt,
+ xtermScreenText
+} from './image-paste-confirm'
+import { escapeDroppedPath } from './file-drop'
+
+// Screens captured from Claude Code 2.1.285 (see the fixture's provenance). `before` is the pane
+// after one earlier paste (#12 on screen); `pngAndBmp` after pasting a png and a bmp together;
+// `missingPng` after pasting a .png path that does not exist.
+const F = fixture
+
+describe('expectation: only claude, only the extensions claude turned into [Image #N]', () => {
+ it('counts png/jpg/jpeg/gif/webp in any case, not bmp/svg/heic/tiff', () => {
+ const paths = ['/a/x.png', '/a/x.JPG', '/a/x.jpeg', '/a/x.gif', '/a/x.webp', '/a/x.bmp', '/a/x.svg', '/a/x.heic', '/a/x.tiff']
+ expect(expectedImagePlaceholders('claude', paths)).toBe(5)
+ })
+ it('an escaped space still ends in the extension', () => {
+ expect(expectedImagePlaceholders('claude', [escapeDroppedPath('/a/pasted 2.png')])).toBe(1)
+ })
+ it('other agents and no agent get no expectation (nothing is claimed for them)', () => {
+ for (const a of ['codex', 'gemini', 'grok', 'copilot', 'opencode', undefined])
+ expect(expectedImagePlaceholders(a, ['/a/x.png'])).toBe(0)
+ })
+})
+
+describe('confirmation over the captured screens', () => {
+ const read = (seq: string[]) => {
+ let i = 0
+ return () => seq[Math.min(i++, seq.length - 1)]
+ }
+ const fast = { sleep: async () => {}, timeoutMs: 100, pollMs: 1 }
+
+ it('a new placeholder number confirms, even though it is not #1', async () => {
+ const before = imagePlaceholderNumbers(F.before.screen)
+ expect([...before]).toEqual([12])
+ const n = expectedImagePlaceholders('claude', F.pngAndBmp.pasted.trim().split(' '))
+ expect(n).toBe(1)
+ let t = 0
+ expect(
+ await confirmImagePaste({ before, expected: n, read: read([F.before.screen, F.pngAndBmp.screen]), now: () => t++, ...fast })
+ ).toBe('confirmed')
+ })
+
+ it('a placeholder already on screen before the paste never confirms it', async () => {
+ const before = imagePlaceholderNumbers(F.pngAndBmp.screen)
+ let t = 0
+ expect(
+ await confirmImagePaste({ before, expected: 1, read: read([F.missingPng.screen]), now: () => t++, ...fast })
+ ).toBe('unconfirmed')
+ })
+
+ it('a path claude kept as text is reported as not confirmed', () => {
+ expect(imagePasteNotice('unconfirmed', 1)).toEqual({ text: 'Pasted the path — not confirmed as an image', ok: false })
+ expect(imagePasteNotice('confirmed', 2)).toEqual({ text: '2 images attached', ok: true })
+ })
+})
+
+// A minimal xterm stand-in: rows of text, with soft-wrap flags.
+function fakeTerm(rows: { text: string; wrapped?: boolean }[]) {
+ const pasted: string[] = []
+ const term = {
+ rows: rows.length,
+ buffer: {
+ active: {
+ viewportY: 0,
+ getLine: (y: number) =>
+ rows[y] ? { isWrapped: !!rows[y].wrapped, translateToString: () => rows[y].text } : undefined
+ }
+ },
+ paste: (t: string) => pasted.push(t)
+ }
+ return { term: term as unknown as Parameters<typeof xtermScreenText>[0] & { paste: (t: string) => void }, rows, pasted }
+}
+
+describe('reading the emulator', () => {
+ it('joins a soft-wrapped placeholder back into one token', () => {
+ const { term } = fakeTerm([{ text: '❯ [Imag' }, { text: 'e #7]', wrapped: true }])
+ expect([...imagePlaceholderNumbers(xtermScreenText(term))]).toEqual([7])
+ })
+
+ it('pasteWithImageReceipt: pastes exactly the text, then reports what the pane showed', async () => {
+ const f = fakeTerm(F.before.screen.split('\n').map((text) => ({ text })))
+ const reports: { text: string; ok: boolean }[] = []
+ pasteWithImageReceipt(f.term, '/work/project/pasted-1.png ', ['/work/project/pasted-1.png'], 'claude', (r) =>
+ reports.push(r)
+ )
+ expect(f.pasted).toEqual(['/work/project/pasted-1.png '])
+ // The pane repaints with the new placeholder.
+ f.rows.splice(0, f.rows.length, ...F.pngAndBmp.screen.split('\n').map((text) => ({ text })))
+ for (let i = 0; i < 50 && !reports.length; i++) await new Promise((r) => setTimeout(r, 10))
+ expect(reports).toEqual([{ text: 'Image attached', ok: true }])
+ })
+
+ it('an agent we did not measure gets the paste and no receipt at all', async () => {
+ const f = fakeTerm([{ text: '❯' }])
+ const reports: unknown[] = []
+ pasteWithImageReceipt(f.term, '/a/x.png ', ['/a/x.png'], 'codex', (r) => reports.push(r))
+ await new Promise((r) => setTimeout(r, 30))
+ expect(f.pasted).toEqual(['/a/x.png '])
+ expect(reports).toEqual([])
+ })
+})
+
+describe('both terminal surfaces paste files through the receipt', () => {
+ it('TerminalNode and ModalTerminal never paste a file path with a bare term.paste', async () => {
+ const { readFileSync } = await import('node:fs')
+ const { join } = await import('node:path')
+ for (const rel of ['src/renderer/nodes/TerminalNode.tsx', 'src/renderer/components/kanban/ModalTerminal.tsx']) {
+ const src = readFileSync(join(process.cwd(), rel), 'utf8').replace(/\r\n/g, '\n')
+ expect(src, rel).toMatch(/pasteWithImageReceipt\(\s*term,\s*paths\.join\(' '\) \+ ' ',/)
+ expect(src, rel).not.toMatch(/term\.paste\(paths\.join/)
+ expect(src, rel).toMatch(/term-paste-pill/)
+ }
+ })
+})
diff --git a/src/renderer/terminal/image-paste-confirm.ts b/src/renderer/terminal/image-paste-confirm.ts
new file mode 100644
index 000000000..b437dfb33
--- /dev/null
+++ b/src/renderer/terminal/image-paste-confirm.ts
@@ -0,0 +1,138 @@
+// Did the agent actually take the image we pasted into its pane?
+//
+// A dropped or pasted screenshot becomes a FILE PATH typed into the terminal (file-drop.ts). What
+// happens next is the pane app's business, and until now nothing looked: the upload overlay went
+// away and the paste was presented as done, whether the agent attached an image or just received a
+// line of text.
+//
+// MEASURED on Claude Code 2.1.285 (2026-09-30, a private tmux, bracketed paste exactly as
+// `term.paste` sends it — fixture lines in `image-paste-confirm.test.ts`):
+// - a path to an existing .png/.jpg/.jpeg/.gif/.webp (any case) is replaced in the composer by
+// `[Image #N]` within ~60 ms; two paths in one paste become two placeholders;
+// - .bmp, .svg, .heic, .tiff and a path that does not exist stay as plain text;
+// - N counts up for the life of the session and does NOT restart when the composer is cleared
+// (`[Image #4]` after four earlier pastes), so "new" means a number the screen did not show
+// before the paste — never a fixed `#1`;
+// - a backslash-escaped space (`pasted\ 2.png`, what `escapeDroppedPath` writes) still attaches.
+//
+// So for claude the pane itself says whether the image was taken, and we read it from OUR emulator
+// (the xterm buffer), not from tmux — the pane app's output already arrives here. Other agents
+// were not measured: they get no receipt either way, exactly as before, and nothing claims success
+// on their behalf.
+import type { Terminal } from '@xterm/xterm'
+import { capabilityAgentId } from '@shared/agents/config'
+
+/** Extensions claude 2.1.285 turned into `[Image #N]` (compared lower-cased). Closed set. */
+export const CLAUDE_IMAGE_EXTENSIONS = ['png', 'jpg', 'jpeg', 'gif', 'webp'] as const
+
+/** How many `[Image #N]` placeholders a paste of `paths` should produce in this pane, or 0 when we
+ * have no measured expectation (another agent, no agent, or no image among the paths). */
+export function expectedImagePlaceholders(agentId: string | undefined, paths: string[]): number {
+ if (!agentId || capabilityAgentId(agentId) !== 'claude') return 0
+ let n = 0
+ for (const p of paths) {
+ const m = /\.([A-Za-z0-9]+)$/.exec(p)
+ if (m && (CLAUDE_IMAGE_EXTENSIONS as readonly string[]).includes(m[1].toLowerCase())) n++
+ }
+ return n
+}
+
+const PLACEHOLDER = /\[Image #(\d+)\]/g
+
+/** The placeholder numbers visible in `screen`. */
+export function imagePlaceholderNumbers(screen: string): Set<number> {
+ const out = new Set<number>()
+ for (const m of screen.matchAll(PLACEHOLDER)) out.add(Number(m[1]))
+ return out
+}
+
+/** The visible screen of an xterm, soft-wrapped rows joined so a placeholder split by the wrap is
+ * still one token. */
+export function xtermScreenText(term: Pick<Terminal, 'buffer' | 'rows'>): string {
+ const buf = term.buffer.active
+ const top = buf.viewportY
+ let out = ''
+ for (let y = top; y < top + term.rows; y++) {
+ const line = buf.getLine(y)
+ if (!line) continue
+ if (y > top && !line.isWrapped) out += '\n'
+ out += line.translateToString(true)
+ }
+ return out
+}
+
+export type ImagePasteOutcome = 'confirmed' | 'unconfirmed'
+
+/** Long enough for an SSH round trip; a local claude answered in ~60 ms. */
+export const IMAGE_PASTE_CONFIRM_MS = 3000
+export const IMAGE_PASTE_POLL_MS = 50
+
+/**
+ * Wait until the screen shows `expected` placeholder numbers that were not on it before the paste.
+ * `before` must be read BEFORE the paste is sent.
+ */
+export async function confirmImagePaste(opts: {
+ before: Set<number>
+ expected: number
+ read: () => string
+ now?: () => number
+ sleep?: (ms: number) => Promise<void>
+ timeoutMs?: number
+ pollMs?: number
+}): Promise<ImagePasteOutcome> {
+ const now = opts.now ?? (() => Date.now())
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)))
+ const deadline = now() + (opts.timeoutMs ?? IMAGE_PASTE_CONFIRM_MS)
+ for (;;) {
+ let fresh = 0
+ for (const n of imagePlaceholderNumbers(opts.read())) if (!opts.before.has(n)) fresh++
+ if (fresh >= opts.expected) return 'confirmed'
+ if (now() >= deadline) return 'unconfirmed'
+ await sleep(opts.pollMs ?? IMAGE_PASTE_POLL_MS)
+ }
+}
+
+/** The receipt shown on the terminal. The unconfirmed one says what we KNOW: the path went in. */
+export function imagePasteNotice(outcome: ImagePasteOutcome, expected: number): { text: string; ok: boolean } {
+ if (outcome === 'confirmed')
+ return { text: expected === 1 ? 'Image attached' : `${expected} images attached`, ok: true }
+ return {
+ text:
+ expected === 1
+ ? 'Pasted the path — not confirmed as an image'
+ : 'Pasted the paths — not confirmed as images',
+ ok: false
+ }
+}
+
+export const IMAGE_PASTE_NOTICE_MS = { ok: 1600, warn: 5000 } as const
+
+/**
+ * Paste `text` (the escaped path list) into `term`, and — when the pane's agent is one whose image
+ * handling we measured — report whether it attached the images. `before` is taken from the screen
+ * BEFORE the paste leaves, so a placeholder already on screen can never confirm this paste.
+ * A terminal disposed mid-wait (parked, released) reports nothing: there is no screen to read.
+ */
+export function pasteWithImageReceipt(
+ term: Pick<Terminal, 'buffer' | 'rows' | 'paste'>,
+ text: string,
+ paths: string[],
+ agentId: string | undefined,
+ report: (notice: { text: string; ok: boolean }) => void
+): void {
+ const expected = expectedImagePlaceholders(agentId, paths)
+ let before: Set<number> | null = null
+ if (expected) {
+ try {
+ before = imagePlaceholderNumbers(xtermScreenText(term))
+ } catch {
+ before = null
+ }
+ }
+ term.paste(text)
+ if (!expected || !before) return
+ void confirmImagePaste({ before, expected, read: () => xtermScreenText(term) }).then(
+ (outcome) => report(imagePasteNotice(outcome, expected)),
+ () => {}
+ )
+}
diff --git a/src/renderer/terminal/usePasteReceipt.ts b/src/renderer/terminal/usePasteReceipt.ts
new file mode 100644
index 000000000..d2a6e0183
--- /dev/null
+++ b/src/renderer/terminal/usePasteReceipt.ts
@@ -0,0 +1,28 @@
+// The image-paste receipt shown on a terminal (see image-paste-confirm.ts). One small piece of
+// state + its dwell timer, shared by the canvas node and the kanban card modal so the two surfaces
+// of one session speak in one voice.
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { IMAGE_PASTE_NOTICE_MS } from './image-paste-confirm'
+
+export function usePasteReceipt(): {
+ receipt: { text: string; ok: boolean } | null
+ report: (r: { text: string; ok: boolean }) => void
+} {
+ const [receipt, setReceipt] = useState<{ text: string; ok: boolean } | null>(null)
+ const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const alive = useRef(true)
+ useEffect(
+ () => () => {
+ alive.current = false
+ if (timer.current) clearTimeout(timer.current)
+ },
+ []
+ )
+ const report = useCallback((r: { text: string; ok: boolean }) => {
+ if (!alive.current) return
+ if (timer.current) clearTimeout(timer.current)
+ setReceipt(r)
+ timer.current = setTimeout(() => setReceipt(null), r.ok ? IMAGE_PASTE_NOTICE_MS.ok : IMAGE_PASTE_NOTICE_MS.warn)
+ }, [])
+ return { receipt, report }
+}
diff --git a/src/shared/agents/__fixtures__/grok/permission-events.json b/src/shared/agents/__fixtures__/grok/permission-events.json
new file mode 100644
index 000000000..b176af6bc
--- /dev/null
+++ b/src/shared/agents/__fixtures__/grok/permission-events.json
@@ -0,0 +1,715 @@
+{
+ "_provenance": "captured live from grok 1.0.13 (5e9a58528b76) on 2026-09-30, interactive TUI in a private tmux, pointed at a local fake chat_completions model (only the model is fake: every file and hook payload below was written by grok itself); paths redacted, KEYS, SHAPES, ORDER AND TIMESTAMPS UNCHANGED. Each scenario: a real permission dialog for run_terminal_command (or spawn_subagent), then answered in the pane.",
+ "scenarios": {
+ "allow": {
+ "answeredWith": "\"2 Yes, proceed\" then Enter; the approved command sleeps 10 s",
+ "hooks": [
+ {
+ "hookEventName": "session_start",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:14.083058151+00:00",
+ "permissionMode": "default",
+ "source": "new",
+ "hook_event_name": "SessionStart",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "user_prompt_submit",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:14.182167441+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "promptId": "3f38713d-d15f-4872-85ba-3a26a202356d",
+ "permissionMode": "default",
+ "prompt": "run the command",
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "pre_tool_use",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:14.233662047+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_2",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "toolInputTruncated": false,
+ "hook_event_name": "PreToolUse",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "tool_use_id": "call_2"
+ },
+ {
+ "hookEventName": "notification",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:14.253791821+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permissionMode": "default",
+ "notificationType": "permission_prompt",
+ "message": "Tool permission requested",
+ "level": "info",
+ "hook_event_name": "Notification",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "post_tool_use",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:34.637661178+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_2",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "toolResult": {
+ "type": "Bash",
+ "output": [
+ 115,
+ 108,
+ 101,
+ 112,
+ 116,
+ 10
+ ],
+ "output_for_prompt": "exit: 0\nslept\n",
+ "exit_code": 0,
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "truncated": false,
+ "signal": null,
+ "timed_out": false,
+ "description": "sleep then echo",
+ "current_dir": "/work/project",
+ "output_file": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/terminal/call_2.log",
+ "total_bytes": 6
+ },
+ "toolInputTruncated": false,
+ "toolResultTruncated": false,
+ "durationMs": 10022,
+ "isBackgrounded": false,
+ "hook_event_name": "PostToolUse",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "tool_response": {
+ "type": "Bash",
+ "output": [
+ 115,
+ 108,
+ 101,
+ 112,
+ 116,
+ 10
+ ],
+ "output_for_prompt": "exit: 0\nslept\n",
+ "exit_code": 0,
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "truncated": false,
+ "signal": null,
+ "timed_out": false,
+ "description": "sleep then echo",
+ "current_dir": "/work/project",
+ "output_file": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/terminal/call_2.log",
+ "total_bytes": 6
+ },
+ "tool_use_id": "call_2",
+ "duration_ms": 10022
+ },
+ {
+ "hookEventName": "stop",
+ "sessionId": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:34.713896700+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "promptId": "3f38713d-d15f-4872-85ba-3a26a202356d",
+ "permissionMode": "default",
+ "reason": "end_turn",
+ "stopHookActive": false,
+ "lastAssistantMessage": "All done.",
+ "backgroundTasks": [],
+ "sessionCrons": [],
+ "hook_event_name": "Stop",
+ "session_id": "01a0f22e-e1fa-7f03-9eac-be5716664af7",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22e-e1fa-7f03-9eac-be5716664af7/updates.jsonl",
+ "permission_mode": "default"
+ }
+ ],
+ "sessions": {
+ "01a0f22e-e1fa-7f03-9eac-be5716664af7": [
+ "{\"ts\":\"2026-09-30T11:59:14.182Z\",\"type\":\"turn_started\",\"session_id\":\"01a0f22e-e1fa-7f03-9eac-be5716664af7\",\"turn_number\":0,\"model_id\":\"fake\",\"yolo_mode\":false,\"conversation_message_count\":3,\"session_relationship\":\"primary\",\"schema_version\":\"1.0\"}",
+ "{\"ts\":\"2026-09-30T11:59:14.223Z\",\"type\":\"loop_started\",\"loop_index\":0}",
+ "{\"ts\":\"2026-09-30T11:59:14.226Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T11:59:14.233Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T11:59:14.233Z\",\"type\":\"tool_started\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T11:59:14.248Z\",\"type\":\"phase_changed\",\"phase\":\"permission_prompt\"}",
+ "{\"ts\":\"2026-09-30T11:59:14.248Z\",\"type\":\"permission_requested\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T11:59:24.614Z\",\"type\":\"permission_resolved\",\"tool_name\":\"run_terminal_command\",\"decision\":\"allow\",\"wait_ms\":10365}",
+ "{\"ts\":\"2026-09-30T11:59:24.614Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T11:59:34.693Z\",\"type\":\"tool_completed\",\"tool_name\":\"run_terminal_command\",\"duration_ms\":10022,\"outcome\":\"success\",\"tool_call_id\":\"call_2\"}",
+ "{\"ts\":\"2026-09-30T11:59:34.693Z\",\"type\":\"loop_started\",\"loop_index\":1}",
+ "{\"ts\":\"2026-09-30T11:59:34.694Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T11:59:34.707Z\",\"type\":\"first_token\"}",
+ "{\"ts\":\"2026-09-30T11:59:34.707Z\",\"type\":\"phase_changed\",\"phase\":\"streaming_text\"}",
+ "{\"ts\":\"2026-09-30T11:59:34.735Z\",\"type\":\"turn_ended\",\"outcome\":\"completed\"}"
+ ]
+ }
+ },
+ "deny": {
+ "answeredWith": "\"3 No, reject\" then Enter",
+ "hooks": [
+ {
+ "hookEventName": "session_start",
+ "sessionId": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:55.434419195+00:00",
+ "permissionMode": "default",
+ "source": "new",
+ "hook_event_name": "SessionStart",
+ "session_id": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "user_prompt_submit",
+ "sessionId": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:55.509578387+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "promptId": "28765f9a-260a-4ea5-b24d-2a76d2f020ac",
+ "permissionMode": "default",
+ "prompt": "run the command",
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "pre_tool_use",
+ "sessionId": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:55.574344639+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_6",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "toolInputTruncated": false,
+ "hook_event_name": "PreToolUse",
+ "session_id": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "tool_use_id": "call_6"
+ },
+ {
+ "hookEventName": "notification",
+ "sessionId": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:55.604339620+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permissionMode": "default",
+ "notificationType": "permission_prompt",
+ "message": "Tool permission requested",
+ "level": "info",
+ "hook_event_name": "Notification",
+ "session_id": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "permission_denied",
+ "sessionId": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T11:59:58.687401962+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_6",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "toolInputTruncated": false,
+ "hook_event_name": "PermissionDenied",
+ "session_id": "01a0f22f-839b-7481-a12b-cb87869b8ae0",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f22f-839b-7481-a12b-cb87869b8ae0/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "tool_use_id": "call_6"
+ }
+ ],
+ "sessions": {
+ "01a0f22f-839b-7481-a12b-cb87869b8ae0": [
+ "{\"ts\":\"2026-09-30T11:59:55.509Z\",\"type\":\"turn_started\",\"session_id\":\"01a0f22f-839b-7481-a12b-cb87869b8ae0\",\"turn_number\":0,\"model_id\":\"fake\",\"yolo_mode\":false,\"conversation_message_count\":3,\"session_relationship\":\"primary\",\"schema_version\":\"1.0\"}",
+ "{\"ts\":\"2026-09-30T11:59:55.555Z\",\"type\":\"loop_started\",\"loop_index\":0}",
+ "{\"ts\":\"2026-09-30T11:59:55.564Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T11:59:55.572Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T11:59:55.572Z\",\"type\":\"tool_started\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T11:59:55.598Z\",\"type\":\"phase_changed\",\"phase\":\"permission_prompt\"}",
+ "{\"ts\":\"2026-09-30T11:59:55.598Z\",\"type\":\"permission_requested\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T11:59:58.687Z\",\"type\":\"permission_resolved\",\"tool_name\":\"run_terminal_command\",\"decision\":\"deny\",\"wait_ms\":3088}",
+ "{\"ts\":\"2026-09-30T11:59:58.687Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T11:59:58.710Z\",\"type\":\"turn_ended\",\"outcome\":\"cancelled\",\"cancellation_category\":\"permission_rejected\",\"cancellation_context\":{\"tool_name\":\"run_terminal_command\",\"reason\":\"User rejected the execution\"}}"
+ ]
+ }
+ },
+ "cancel": {
+ "answeredWith": "Ctrl+C on the open dialog",
+ "hooks": [
+ {
+ "hookEventName": "session_start",
+ "sessionId": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:00:28.060258672+00:00",
+ "permissionMode": "default",
+ "source": "new",
+ "hook_event_name": "SessionStart",
+ "session_id": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "user_prompt_submit",
+ "sessionId": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:00:28.120724814+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "promptId": "b3bf1cfc-b230-4350-b898-8181f71b0caf",
+ "permissionMode": "default",
+ "prompt": "run the command",
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "pre_tool_use",
+ "sessionId": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:00:28.181202308+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_8",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "toolInputTruncated": false,
+ "hook_event_name": "PreToolUse",
+ "session_id": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && sleep 10 && echo slept",
+ "description": "sleep then echo"
+ },
+ "tool_use_id": "call_8"
+ },
+ {
+ "hookEventName": "notification",
+ "sessionId": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:00:28.203048440+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "permissionMode": "default",
+ "notificationType": "permission_prompt",
+ "message": "Tool permission requested",
+ "level": "info",
+ "hook_event_name": "Notification",
+ "session_id": "01a0f230-031d-78c1-8e26-5b13fb9d266d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f230-031d-78c1-8e26-5b13fb9d266d/updates.jsonl",
+ "permission_mode": "default"
+ }
+ ],
+ "sessions": {
+ "01a0f230-031d-78c1-8e26-5b13fb9d266d": [
+ "{\"ts\":\"2026-09-30T12:00:28.120Z\",\"type\":\"turn_started\",\"session_id\":\"01a0f230-031d-78c1-8e26-5b13fb9d266d\",\"turn_number\":0,\"model_id\":\"fake\",\"yolo_mode\":false,\"conversation_message_count\":3,\"session_relationship\":\"primary\",\"schema_version\":\"1.0\"}",
+ "{\"ts\":\"2026-09-30T12:00:28.172Z\",\"type\":\"loop_started\",\"loop_index\":0}",
+ "{\"ts\":\"2026-09-30T12:00:28.174Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T12:00:28.180Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:00:28.180Z\",\"type\":\"tool_started\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T12:00:28.200Z\",\"type\":\"phase_changed\",\"phase\":\"permission_prompt\"}",
+ "{\"ts\":\"2026-09-30T12:00:28.200Z\",\"type\":\"permission_requested\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T12:00:31.414Z\",\"type\":\"permission_resolved\",\"tool_name\":\"run_terminal_command\",\"decision\":\"cancelled\",\"wait_ms\":3213}",
+ "{\"ts\":\"2026-09-30T12:00:31.414Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:00:31.418Z\",\"type\":\"turn_ended\",\"outcome\":\"cancelled\",\"cancellation_category\":\"permission_cancelled\"}"
+ ]
+ }
+ },
+ "subagent": {
+ "answeredWith": "parent prompt for spawn_subagent approved with \"2\"; the CHILD then asked for run_terminal_command and that dialog was approved at once. The child's notification carries the PARENT sessionId, while its permission_requested is in the CHILD's events.jsonl.",
+ "hooks": [
+ {
+ "hookEventName": "session_start",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:15.218974522+00:00",
+ "permissionMode": "default",
+ "source": "new",
+ "hook_event_name": "SessionStart",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "user_prompt_submit",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:15.265831116+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "promptId": "e69ebc16-d47b-4f74-a7b3-6eeac7b70770",
+ "permissionMode": "default",
+ "prompt": "spawn it",
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "pre_tool_use",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:15.313846223+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "spawn_subagent",
+ "toolUseId": "call_2",
+ "toolInput": {
+ "prompt": "run the command",
+ "description": "run a command",
+ "background": false
+ },
+ "toolInputTruncated": false,
+ "hook_event_name": "PreToolUse",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "spawn_subagent",
+ "tool_input": {
+ "prompt": "run the command",
+ "description": "run a command",
+ "background": false
+ },
+ "tool_use_id": "call_2"
+ },
+ {
+ "hookEventName": "notification",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:15.347617151+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permissionMode": "default",
+ "notificationType": "permission_prompt",
+ "message": "Tool permission requested",
+ "level": "info",
+ "hook_event_name": "Notification",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "user_prompt_submit",
+ "sessionId": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.234516154+00:00",
+ "promptId": "01a0f232-c74f-7d93-8854-a732b0e19842",
+ "permissionMode": "default",
+ "prompt": "run the command",
+ "subagentType": "general-purpose",
+ "hook_event_name": "UserPromptSubmit",
+ "session_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "pre_tool_use",
+ "sessionId": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.267870106+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_4",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "description": "sleep then echo"
+ },
+ "toolInputTruncated": false,
+ "subagentType": "general-purpose",
+ "hook_event_name": "PreToolUse",
+ "session_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "description": "sleep then echo"
+ },
+ "tool_use_id": "call_4"
+ },
+ {
+ "hookEventName": "notification",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.291282873+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permissionMode": "default",
+ "notificationType": "permission_prompt",
+ "message": "Tool permission requested",
+ "level": "info",
+ "hook_event_name": "Notification",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "post_tool_use",
+ "sessionId": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.529761346+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "run_terminal_command",
+ "toolUseId": "call_4",
+ "toolInput": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "description": "sleep then echo"
+ },
+ "toolResult": {
+ "type": "Bash",
+ "output": [
+ 111,
+ 107,
+ 10
+ ],
+ "output_for_prompt": "exit: 0\nok\n",
+ "exit_code": 0,
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "truncated": false,
+ "signal": null,
+ "timed_out": false,
+ "description": "sleep then echo",
+ "current_dir": "/work/project",
+ "output_file": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/terminal/call_4.log",
+ "total_bytes": 3
+ },
+ "toolInputTruncated": false,
+ "toolResultTruncated": false,
+ "durationMs": 22,
+ "isBackgrounded": false,
+ "subagentType": "general-purpose",
+ "hook_event_name": "PostToolUse",
+ "session_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "run_terminal_command",
+ "tool_input": {
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "description": "sleep then echo"
+ },
+ "tool_response": {
+ "type": "Bash",
+ "output": [
+ 111,
+ 107,
+ 10
+ ],
+ "output_for_prompt": "exit: 0\nok\n",
+ "exit_code": 0,
+ "command": "mkdir -p /work/project/d && rm -rf /work/project/d && echo ok",
+ "truncated": false,
+ "signal": null,
+ "timed_out": false,
+ "description": "sleep then echo",
+ "current_dir": "/work/project",
+ "output_file": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/terminal/call_4.log",
+ "total_bytes": 3
+ },
+ "tool_use_id": "call_4",
+ "duration_ms": 22
+ },
+ {
+ "hookEventName": "session_end",
+ "sessionId": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.579889373+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permissionMode": "default",
+ "reason": "shutdown",
+ "subagentType": "general-purpose",
+ "hook_event_name": "SessionEnd",
+ "session_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-c731-7832-ae61-e1884d465d79/updates.jsonl",
+ "permission_mode": "default"
+ },
+ {
+ "hookEventName": "post_tool_use",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.604808729+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permissionMode": "default",
+ "toolName": "spawn_subagent",
+ "toolUseId": "call_2",
+ "toolInput": {
+ "prompt": "run the command",
+ "description": "run a command",
+ "background": false
+ },
+ "toolResult": {
+ "type": "SubagentCompleted",
+ "output": "All done.",
+ "subagent_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "subagent_type": "general-purpose",
+ "tool_calls": 1,
+ "turns": 1,
+ "duration_ms": 373,
+ "worktree_path": null,
+ "resume_from_hint": "01a0f232-c731-7832-ae61-e1884d465d79"
+ },
+ "toolInputTruncated": false,
+ "toolResultTruncated": false,
+ "durationMs": 403,
+ "isBackgrounded": false,
+ "hook_event_name": "PostToolUse",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default",
+ "tool_name": "spawn_subagent",
+ "tool_input": {
+ "prompt": "run the command",
+ "description": "run a command",
+ "background": false
+ },
+ "tool_response": {
+ "type": "SubagentCompleted",
+ "output": "All done.",
+ "subagent_id": "01a0f232-c731-7832-ae61-e1884d465d79",
+ "subagent_type": "general-purpose",
+ "tool_calls": 1,
+ "turns": 1,
+ "duration_ms": 373,
+ "worktree_path": null,
+ "resume_from_hint": "01a0f232-c731-7832-ae61-e1884d465d79"
+ },
+ "tool_use_id": "call_2",
+ "duration_ms": 403
+ },
+ {
+ "hookEventName": "stop",
+ "sessionId": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "cwd": "/work/project",
+ "workspaceRoot": "/work/project",
+ "timestamp": "2026-09-30T12:03:29.634196380+00:00",
+ "transcriptPath": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "promptId": "e69ebc16-d47b-4f74-a7b3-6eeac7b70770",
+ "permissionMode": "default",
+ "reason": "end_turn",
+ "stopHookActive": false,
+ "lastAssistantMessage": "All done.",
+ "backgroundTasks": [],
+ "sessionCrons": [],
+ "hook_event_name": "Stop",
+ "session_id": "01a0f232-900f-7a63-81ad-2b9bf2b32f8d",
+ "transcript_path": "/home/user/.grok/sessions/%2Fwork%2Fproject/01a0f232-900f-7a63-81ad-2b9bf2b32f8d/updates.jsonl",
+ "permission_mode": "default"
+ }
+ ],
+ "sessions": {
+ "01a0f232-900f-7a63-81ad-2b9bf2b32f8d": [
+ "{\"ts\":\"2026-09-30T12:03:15.265Z\",\"type\":\"turn_started\",\"session_id\":\"01a0f232-900f-7a63-81ad-2b9bf2b32f8d\",\"turn_number\":0,\"model_id\":\"fake\",\"yolo_mode\":false,\"conversation_message_count\":3,\"session_relationship\":\"primary\",\"schema_version\":\"1.0\"}",
+ "{\"ts\":\"2026-09-30T12:03:15.298Z\",\"type\":\"loop_started\",\"loop_index\":0}",
+ "{\"ts\":\"2026-09-30T12:03:15.304Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T12:03:15.313Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:03:15.313Z\",\"type\":\"tool_started\",\"tool_name\":\"spawn_subagent\"}",
+ "{\"ts\":\"2026-09-30T12:03:15.347Z\",\"type\":\"phase_changed\",\"phase\":\"permission_prompt\"}",
+ "{\"ts\":\"2026-09-30T12:03:15.347Z\",\"type\":\"permission_requested\",\"tool_name\":\"spawn_subagent\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.200Z\",\"type\":\"permission_resolved\",\"tool_name\":\"spawn_subagent\",\"decision\":\"allow\",\"wait_ms\":13853}",
+ "{\"ts\":\"2026-09-30T12:03:29.200Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.621Z\",\"type\":\"tool_completed\",\"tool_name\":\"spawn_subagent\",\"duration_ms\":403,\"outcome\":\"success\",\"tool_call_id\":\"call_2\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.622Z\",\"type\":\"loop_started\",\"loop_index\":1}",
+ "{\"ts\":\"2026-09-30T12:03:29.622Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.632Z\",\"type\":\"first_token\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.632Z\",\"type\":\"phase_changed\",\"phase\":\"streaming_text\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.662Z\",\"type\":\"turn_ended\",\"outcome\":\"completed\"}"
+ ],
+ "01a0f232-c731-7832-ae61-e1884d465d79": [
+ "{\"ts\":\"2026-09-30T12:03:29.234Z\",\"type\":\"turn_started\",\"session_id\":\"01a0f232-c731-7832-ae61-e1884d465d79\",\"turn_number\":0,\"model_id\":\"fake\",\"yolo_mode\":false,\"conversation_message_count\":1,\"session_relationship\":\"primary\",\"schema_version\":\"1.0\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.256Z\",\"type\":\"loop_started\",\"loop_index\":0}",
+ "{\"ts\":\"2026-09-30T12:03:29.261Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.267Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.267Z\",\"type\":\"tool_started\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.290Z\",\"type\":\"phase_changed\",\"phase\":\"permission_prompt\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.290Z\",\"type\":\"permission_requested\",\"tool_name\":\"run_terminal_command\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.506Z\",\"type\":\"permission_resolved\",\"tool_name\":\"run_terminal_command\",\"decision\":\"allow\",\"wait_ms\":216}",
+ "{\"ts\":\"2026-09-30T12:03:29.506Z\",\"type\":\"phase_changed\",\"phase\":\"tool_execution\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.546Z\",\"type\":\"tool_completed\",\"tool_name\":\"run_terminal_command\",\"duration_ms\":22,\"outcome\":\"success\",\"tool_call_id\":\"call_4\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.546Z\",\"type\":\"loop_started\",\"loop_index\":1}",
+ "{\"ts\":\"2026-09-30T12:03:29.547Z\",\"type\":\"phase_changed\",\"phase\":\"waiting_for_model\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.554Z\",\"type\":\"first_token\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.554Z\",\"type\":\"phase_changed\",\"phase\":\"streaming_text\"}",
+ "{\"ts\":\"2026-09-30T12:03:29.562Z\",\"type\":\"turn_ended\",\"outcome\":\"completed\"}"
+ ]
+ }
+ }
+ }
+}
diff --git a/src/shared/agents/normalize.ts b/src/shared/agents/normalize.ts
index fb5b3001d..d4baf7897 100644
--- a/src/shared/agents/normalize.ts
+++ b/src/shared/agents/normalize.ts
@@ -969,6 +969,10 @@ export function normalizeGrok(env: RawHookEnvelope): NormalizedAgentEvent | null
// 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.
+ // What this cannot see is the ANSWER: grok fires no hook when the dialog is approved (until the
+ // tool finishes) or dismissed (never). The hook server's grok permission gate
+ // (core/agents/grok-permission-gate.ts) confirms this `blocked` against grok's events.jsonl and
+ // clears it from there — this function stays a pure mapping of the hook.
if (type === 'permission_prompt') {
return { ...base, kind: 'state', state: 'blocked', lastMessage }
}