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): never answer a grok prompt with a request resolved before it fired

review84a7477b6295
diff --git a/CLAUDE.md b/CLAUDE.md
index e7e45f537..de9ac6864 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1364,7 +1364,9 @@ session.
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
+ placeholder numbers ABOVE the highest one on screen before the paste (the counter only rises,
+ so an older placeholder scrolling into view cannot confirm it; with none on screen, two pastes
+ inside ~60 ms can still confirm each other), 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
@@ -1961,17 +1963,25 @@ else, and its context links must keep classifying across restarts).
`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
+ while nothing changes); answered ⇒ `working` (unverified — a file read is not a hook POST — including when the
+ answer is already on disk as the hook is read); 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
+ "answered" over an open child dialog. 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
+ landed 90 ms before the child's prompt). The candidate set CAN miss the real request — a child's
+ prompt may reach us before any of the child's own hooks, or a second request's line may not be
+ on disk yet — and the older request found instead is then already answered. **The load-bearing
+ rule is therefore: a request answered BEFORE the notification fired is never taken as its
+ answer** (`resolvedTs < notifiedAt` ⇒ the hook is published unchanged, nothing watched): a
+ notification cannot be about a dialog that closed before it. Every capture resolves after its
+ notification (fastest 216 ms). Review of #1065 found that hole; tests A/B pin it. 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
+ that straddled a newer hook). A listener that throws costs that ONE event (as it did inside the
+ hook server's try/catch before), never the node's delivery chain. 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
diff --git a/src/core/agents/grok-permission-gate.test.ts b/src/core/agents/grok-permission-gate.test.ts
index b628caf8d..c4f13ec19 100644
--- a/src/core/agents/grok-permission-gate.test.ts
+++ b/src/core/agents/grok-permission-gate.test.ts
@@ -199,3 +199,125 @@ describe('the gate, replaying each captured scenario', () => {
expect(h.states().at(-1)).toBe('blocked')
})
})
+
+// Review round (PR #1065): synthetic timelines in the captured record shapes, for orderings the
+// captures did not happen to contain.
+const T = Date.parse('2026-09-30T12:00:00.000Z')
+const iso = (ms: number): string => new Date(ms).toISOString()
+const rec = (ms: number, type: string, extra: Record<string, unknown> = {}): string =>
+ JSON.stringify({ ts: iso(ms), type, ...extra })
+const hook = (ms: number, sessionId: string, hookEventName: string, extra: Record<string, unknown> = {}): Hook => ({
+ hookEventName,
+ sessionId,
+ cwd: '/work/project',
+ timestamp: iso(ms),
+ ...extra
+})
+const prompt = (ms: number, sid: string): Hook =>
+ hook(ms, sid, 'notification', { notificationType: 'permission_prompt', message: 'Tool permission requested', level: 'info' })
+const P = '01a0f232-0000-7000-8000-00000000000a'
+const C = '01a0f232-0000-7000-8000-00000000000b'
+
+describe('review: a notification is never answered by a request resolved BEFORE it fired', () => {
+ it("A: the child's prompt arrives before the child's own hooks — the parent's earlier approval must not hide it", async () => {
+ const sc: Scenario = {
+ hooks: [
+ hook(T, P, 'session_start'),
+ hook(T + 10, P, 'user_prompt_submit'),
+ prompt(T + 105, P), // the spawn dialog
+ prompt(T + 2095, P) // the CHILD's dialog, carrying the parent's id
+ ],
+ sessions: {
+ [P]: [
+ rec(T + 5, 'turn_started'),
+ rec(T + 100, 'permission_requested', { tool_name: 'spawn_subagent' }),
+ rec(T + 2000, 'permission_resolved', { tool_name: 'spawn_subagent', decision: 'allow', wait_ms: 1900 })
+ ],
+ [C]: [rec(T + 2050, 'turn_started'), rec(T + 2090, 'permission_requested', { tool_name: 'run_terminal_command' })]
+ }
+ }
+ const h = harness(sc)
+ for (const x of sc.hooks) await h.post(x)
+ await h.advanceTo(T + 20_000)
+ expect(h.states().at(-1)).toBe('blocked')
+ // After the child's prompt, nothing claimed the node was working again.
+ const iBlocked = h.out.map((e) => e.state).lastIndexOf('blocked')
+ expect(h.out.slice(iBlocked + 1)).toEqual([])
+ })
+
+ it("B: a second request whose line is not on disk yet is not answered by the first one's approval", async () => {
+ const S1 = '01a0f232-0000-7000-8000-00000000000c'
+ const sc: Scenario = {
+ hooks: [hook(T, S1, 'session_start'), prompt(T + 105, S1), prompt(T + 2990, S1)],
+ sessions: {
+ [S1]: [
+ rec(T + 5, 'turn_started'),
+ rec(T + 100, 'permission_requested', { tool_name: 'run_terminal_command' }),
+ rec(T + 1000, 'permission_resolved', { tool_name: 'run_terminal_command', decision: 'allow', wait_ms: 900 })
+ // request 2's line has not reached the disk
+ ]
+ }
+ }
+ const h = harness(sc)
+ for (const x of sc.hooks) await h.post(x)
+ await h.advanceTo(T + 20_000)
+ expect(h.states().at(-1)).toBe('blocked')
+ })
+
+ it('two candidate requests inside the window: the hook is published unchanged and NOTHING is watched', async () => {
+ const sc: Scenario = {
+ hooks: [
+ hook(T, P, 'session_start'),
+ hook(T + 50, C, 'user_prompt_submit'), // the child is known
+ prompt(T + 1000, P)
+ ],
+ sessions: {
+ [P]: [
+ rec(T + 5, 'turn_started'),
+ rec(T + 990, 'permission_requested', { tool_name: 'spawn_subagent' }),
+ rec(T + 4000, 'permission_resolved', { tool_name: 'spawn_subagent', decision: 'allow', wait_ms: 3010 })
+ ],
+ [C]: [
+ rec(T + 60, 'turn_started'),
+ rec(T + 995, 'permission_requested', { tool_name: 'run_terminal_command' }),
+ rec(T + 5000, 'permission_resolved', { tool_name: 'run_terminal_command', decision: 'allow', wait_ms: 4005 })
+ ]
+ }
+ }
+ const h = harness(sc)
+ for (const x of sc.hooks) await h.post(x)
+ await h.advanceTo(T + 20_000)
+ // Ambiguous: we cannot say which dialog the prompt was, so we never publish either answer.
+ expect(h.states().at(-1)).toBe('blocked')
+ expect(h.out.filter((e) => e.verified === false)).toEqual([])
+ })
+})
+
+describe('review: a throwing listener costs one event, not the node', () => {
+ it('later events for the same node are still delivered', async () => {
+ const got: NormalizedAgentEvent[] = []
+ let first = true
+ const gate = createGrokPermissionGate((e) => {
+ if (first) {
+ first = false
+ throw new Error('listener boom')
+ }
+ got.push(e)
+ })
+ const warn = console.warn
+ console.warn = () => {}
+ try {
+ const x = hook(T, P, 'user_prompt_submit')
+ gate.handle('n9', x, normalizeGrok({ nodeId: 'n9', agentId: 'grok', payload: x }))
+ const y = hook(T + 10, P, 'pre_tool_use')
+ gate.handle('n9', y, normalizeGrok({ nodeId: 'n9', agentId: 'grok', payload: y }))
+ const z = prompt(T + 20, P) // no file anywhere → published unchanged
+ gate.handle('n9', z, normalizeGrok({ nodeId: 'n9', agentId: 'grok', payload: z }))
+ for (let i = 0; i < 50 && got.length < 2; i++) await new Promise((r) => setTimeout(r, 10))
+ } finally {
+ console.warn = warn
+ gate.dispose()
+ }
+ expect(got.map((e) => e.state)).toEqual(['working', 'blocked'])
+ })
+})
diff --git a/src/core/agents/grok-permission-gate.ts b/src/core/agents/grok-permission-gate.ts
index d9e39f774..690b1de69 100644
--- a/src/core/agents/grok-permission-gate.ts
+++ b/src/core/agents/grok-permission-gate.ts
@@ -123,6 +123,8 @@ export type GrokPermissionVerdict =
| {
phase: 'resolved'
decision: GrokPermissionDecision
+ /** When grok recorded the answer. */
+ resolvedTs: number
/** Present once the turn has ended after the resolution. */
turnEnded?: 'cancelled' | 'other'
}
@@ -157,6 +159,7 @@ export function permissionVerdict(
let seen = 0
let resolvedAt = -1
let decision: string | undefined
+ let resolvedTs = 0
for (let i = start; i < records.length; i++) {
const r = records[i]
if (i > at && r.type === 'turn_started') return { phase: 'superseded' }
@@ -166,6 +169,7 @@ export function permissionVerdict(
if (i < at || r.toolName !== toolName) return { phase: 'unknown' }
resolvedAt = i
decision = r.decision
+ resolvedTs = r.ts
break
}
}
@@ -178,11 +182,12 @@ export function permissionVerdict(
return {
phase: 'resolved',
decision: decision as GrokPermissionDecision,
+ resolvedTs,
turnEnded: r.outcome === 'cancelled' ? 'cancelled' : 'other'
}
}
}
- return { phase: 'resolved', decision: decision as GrokPermissionDecision }
+ return { phase: 'resolved', decision: decision as GrokPermissionDecision, resolvedTs }
}
/** True for the normalized event a grok `permission_prompt` notification produces. */
@@ -295,6 +300,20 @@ export function createGrokPermissionGate(
const nodes = new Map<string, NodeState>()
let disposed = false
+ // The listener fans out to several subsystems; one throw must cost that ONE event (as it did
+ // inside the hook server's try/catch before this gate existed), never the node's delivery chain.
+ let warned = false
+ const safeDeliver = (e: NormalizedAgentEvent): void => {
+ try {
+ deliver(e)
+ } catch (err) {
+ if (!warned) {
+ warned = true
+ console.warn('[grok-permission-gate] listener threw; event dropped', err)
+ }
+ }
+ }
+
const stateOf = (nodeId: string): NodeState => {
let s = nodes.get(nodeId)
if (!s) {
@@ -317,7 +336,7 @@ export function createGrokPermissionGate(
}
const synthetic = (nodeId: string, ep: Episode, patch: Partial<NormalizedAgentEvent>): void => {
- deliver({
+ safeDeliver({
nodeId,
agentId: 'grok',
kind: 'state',
@@ -400,7 +419,9 @@ export function createGrokPermissionGate(
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) {
+ // A SNAPSHOT: a hook arriving while a read is awaited re-inserts its session into the live Map,
+ // and iterating that Map would read the same file twice and count two matches.
+ 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)
@@ -417,6 +438,12 @@ export function createGrokPermissionGate(
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)
+ // A notification cannot be about a request that was answered BEFORE it fired. When the matched
+ // request's answer predates the notification, the real request is one we did not find (a
+ // child whose own hooks have not reached us yet, or a second request whose line is not on disk
+ // yet) — so the hook is published unchanged and nothing is watched. Every legitimate case in
+ // the captures resolves after its notification (the fastest, 216 ms after).
+ if (verdict.phase === 'resolved' && verdict.resolvedTs < notifiedAt) return out(e)
const ep: Episode = {
file: m.file,
reqTs: req.ts,
@@ -432,13 +459,14 @@ export function createGrokPermissionGate(
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.
+ // Answered between the notification and our read: publish what the file says instead of a
+ // dialog that is no longer on screen. The STATE now comes from a file read, so it is
+ // unverified like everything the watch derives.
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.turnEnded === 'cancelled')
+ return out({ ...e, state: 'done', interrupted: true, lastMessage: undefined, verified: false })
+ out({ ...e, state: 'working', lastMessage: undefined, verified: false })
if (verdict.decision === 'allow' || verdict.turnEnded === 'other') return
}
s.episode = ep
@@ -474,7 +502,7 @@ export function createGrokPermissionGate(
return {
handle(nodeId, payload, e) {
if (disposed) {
- if (e) deliver(e)
+ if (e) safeDeliver(e)
return
}
const s = stateOf(nodeId)
@@ -488,22 +516,22 @@ export function createGrokPermissionGate(
if (published) return
published = true
s.gen++
- deliver(ev)
+ safeDeliver(ev)
}
const guarded = confirm(nodeId, s, payload, e, once).catch(() => once(e))
return withTimeout(guarded, () => once(e))
- })
+ }).catch(() => {})
return
}
s.chain = s.chain.then(() => {
s.gen++
- if (e) deliver(e)
+ if (e) safeDeliver(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)
- })
+ }).catch(() => {})
},
dispose() {
disposed = true
diff --git a/src/renderer/terminal/image-paste-confirm.test.ts b/src/renderer/terminal/image-paste-confirm.test.ts
index fb13cb861..c885adcf3 100644
--- a/src/renderer/terminal/image-paste-confirm.test.ts
+++ b/src/renderer/terminal/image-paste-confirm.test.ts
@@ -119,3 +119,19 @@ describe('both terminal surfaces paste files through the receipt', () => {
}
})
})
+
+describe('review: only numbers ABOVE the highest one on screen confirm', () => {
+ it('an older placeholder scrolling into view does not confirm this paste', async () => {
+ let t = 0
+ const out = await confirmImagePaste({
+ before: new Set([12]),
+ expected: 1,
+ read: () => '❯ [Image #3] [Image #12]', // #3 was scrolled off before the paste
+ now: () => t++,
+ sleep: async () => {},
+ timeoutMs: 50,
+ pollMs: 1
+ })
+ expect(out).toBe('unconfirmed')
+ })
+})
diff --git a/src/renderer/terminal/image-paste-confirm.ts b/src/renderer/terminal/image-paste-confirm.ts
index b437dfb33..3fb161d36 100644
--- a/src/renderer/terminal/image-paste-confirm.ts
+++ b/src/renderer/terminal/image-paste-confirm.ts
@@ -68,7 +68,7 @@ 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.
+ * Wait until the screen shows `expected` placeholder numbers above every one on it before the paste.
* `before` must be read BEFORE the paste is sent.
*/
export async function confirmImagePaste(opts: {
@@ -83,9 +83,16 @@ export async function confirmImagePaste(opts: {
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)
+ // Claude's counter only goes up, so this paste's placeholders are numbered ABOVE every one
+ // already on screen. Counting "any number not seen before" would let an older placeholder that
+ // scrolls into view confirm this paste. Residual: with nothing on screen before the paste, the
+ // floor is 0, and two pastes within the ~60 ms claude takes to answer can still confirm each
+ // other — a receipt is per paste, not per image.
+ let floor = 0
+ for (const n of opts.before) floor = Math.max(floor, n)
for (;;) {
let fresh = 0
- for (const n of imagePlaceholderNumbers(opts.read())) if (!opts.before.has(n)) fresh++
+ for (const n of imagePlaceholderNumbers(opts.read())) if (n > floor) fresh++
if (fresh >= opts.expected) return 'confirmed'
if (now() >= deadline) return 'unconfirmed'
await sleep(opts.pollMs ?? IMAGE_PASTE_POLL_MS)