From d8447530b902ab076ef9af22c1865dcbd64471e2 Mon Sep 17 00:00:00 2001 From: hsien wei Date: Sat, 3 Oct 2026 14:16:08 +0800 Subject: [PATCH 1/5] fix(hive): keep HITL notification classification type-aware - Share notification classification across WorkerWake and renderer paths. - Prefer known structured notification types and fall back to HITL-first message heuristics. - Pass notification types into WorkerWake and guard malformed runtime field values. --- src/core/hookServer.ts | 11 ++--- src/main/index.ts | 2 +- src/main/workerWake.ts | 29 +++---------- src/renderer/src/hooks/useHive.ts | 23 +++------- src/shared/hookClassify.ts | 44 +++++++++++++++++++ test/worker-wake.test.cjs | 71 +++++++++++++++++++++++++++++++ 6 files changed, 133 insertions(+), 47 deletions(-) create mode 100644 src/shared/hookClassify.ts diff --git a/src/core/hookServer.ts b/src/core/hookServer.ts index d6639a1998..0d283c6b02 100644 --- a/src/core/hookServer.ts +++ b/src/core/hookServer.ts @@ -196,10 +196,11 @@ export class HookServer { /** Standing goal text for an agent (from the durable roster). Optional so * tests can omit it; when set, injected at session start and when changed. */ private getStandingGoal?: (agentId: string) => string | null, - /** Optional observer of every hook boundary (agentId, event, message). The - * worker inbox-wake watchdog (workerWake.ts) feeds on this to learn when an - * agent is parked on a permission/HITL prompt so it never types into it. */ - private onEvent?: (agentId: string | undefined, event: string, message: string | undefined, tool?: string, source?: string) => void + /** Optional observer of every hook boundary (agentId, event, message, tool, + * source, notificationType). The worker inbox-wake watchdog (workerWake.ts) + * feeds on this to learn when an agent is parked on a permission/HITL + * prompt so it never types into it. */ + private onEvent?: (agentId: string | undefined, event: string, message: string | undefined, tool?: string, source?: string, notificationType?: unknown) => void ) {} /** Bind the hook socket. Asynchronous and safe to call repeatedly — a @@ -586,7 +587,7 @@ export class HookServer { if (LOGGED_HOOKS.has(event)) try { this.hive.appendLog({ kind: 'hook-seen', event, agentId: agentId ?? null, ...(event === 'UserPromptSubmit' && typeof p.prompt === 'string' ? { tailLen: promptTail(p.prompt).length } : {}) }); } catch { /* the log never affects the reply */ } - this.onEvent?.(agentId, event, p.message, p.tool_name, p.source); + this.onEvent?.(agentId, event, p.message, p.tool_name, p.source, p.notification_type); try { this.onFacts?.({ agentId, event, tool: p.tool_name, toolInput: p.tool_input, sessionId: p.session_id, agentType: p.agent_type, source: p.source }); } catch { /* an observer must never affect the hook reply */ } diff --git a/src/main/index.ts b/src/main/index.ts index f027cbd6f0..dea77cac56 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -875,7 +875,7 @@ const hookServer = new HookServer( // always true). // 0.5.6: the same stream tells wakeFiling when a turn ends (Stop), which is // when the mail that turn's wake printed is filed. - (agentId, event, message, tool, source) => { loginPastOnHook(agentId, event); if (agentId && event !== 'Status') agentDemand.touch(agentId); workerWake.noteHook(agentId, event, message, undefined, tool); wakeFiling.noteHook(agentId, event, source); } + (agentId, event, message, tool, source, notificationType) => { loginPastOnHook(agentId, event); if (agentId && event !== 'Status') agentDemand.touch(agentId); workerWake.noteHook(agentId, event, message, undefined, tool, notificationType); wakeFiling.noteHook(agentId, event, source); } ); // The toast itself is Electron's; the hook server decides when. hookServer.setNotifier((title, body) => { diff --git a/src/main/workerWake.ts b/src/main/workerWake.ts index 45b90ce99f..8f6ff879ad 100644 --- a/src/main/workerWake.ts +++ b/src/main/workerWake.ts @@ -42,6 +42,9 @@ import { OpenQuestionTracker } from '../shared/openQuestion'; import { TURN_EVENTS } from './hookProof'; +import { classifyHook } from '../shared/hookClassify'; + +export { classifyHook, type HookClass } from '../shared/hookClassify'; /** The exact nudge the renderer's inbox-wake loop would have typed. */ export const WORKER_WAKE_NUDGE = @@ -82,28 +85,6 @@ export const WORKER_WAKE_OPEN_TURN_MS = 15 * 60_000; /** Minimum age of pending mail before a held worker is reported in the log. */ export const WORKER_WAKE_REPORT_MS = 60_000; -/** A hook event message that means "the agent needs the human" — permission / - * approve / confirm prompts (mirrors the renderer's needsHuman detection in - * useHive.ts). Anything matching the idle-waiting shape is NOT a HITL hold. */ -export type HookClass = 'needsHuman' | 'idle' | null; - -export function classifyHook(event: string | undefined, message: string | undefined): HookClass { - if (event === 'Notification') { - const msg = (message ?? '').toLowerCase(); - const idleWaiting = !msg - || msg.includes('waiting for your input') - || msg.includes('is idle') - || msg.includes('waiting for input'); - const needsHuman = msg.includes('permission') - || msg.includes('approve') - || msg.includes('confirm') - || msg.includes('needs your'); - if (needsHuman && !idleWaiting) return 'needsHuman'; - return 'idle'; - } - return null; -} - /** A hook event that proves the CLI took a turn: the activity signal every * engine the harness shims produces, unlike telemetry, which only Claude Code * exports. SessionStart is the CLI coming up, not a turn: a worker whose boot @@ -239,7 +220,7 @@ export class WorkerWakeWatchdog { } /** Feed hook events (from HookServer) so a HITL prompt blocks nudges. */ - noteHook(agentId: string | undefined, event: string | undefined, message: string | undefined, at = Date.now(), tool?: string): void { + noteHook(agentId: string | undefined, event: string | undefined, message: string | undefined, at = Date.now(), tool?: string, notificationType?: unknown): void { if (!agentId) return; this.questions.note(agentId, event, tool); this.hookSeenAt.set(agentId, at); @@ -247,7 +228,7 @@ export class WorkerWakeWatchdog { this.lastTurnHookAt.set(agentId, at); this.lastTurnHookEvent.set(agentId, event as string); } - if (classifyHook(event, message) === 'needsHuman') this.lastHumanNeedsAt.set(agentId, at); + if (classifyHook(event, message, notificationType) === 'needsHuman') this.lastHumanNeedsAt.set(agentId, at); else if (event && TURN_EVENTS.has(event)) this.lastTurnAt.set(agentId, at); } diff --git a/src/renderer/src/hooks/useHive.ts b/src/renderer/src/hooks/useHive.ts index 27e178ed58..b860a51321 100644 --- a/src/renderer/src/hooks/useHive.ts +++ b/src/renderer/src/hooks/useHive.ts @@ -32,6 +32,7 @@ import { effectiveGodCommand } from '../../../shared/godCommand'; import { agentExitOf } from '../../../shared/agentExit'; import { godRunning, refusedBecauseAlive } from '../../../shared/godBoot'; import { resolveGodName } from '../../../shared/godIdentity'; +import { classifyHook } from '../../../shared/hookClassify'; import { resolveResponder } from '../../../shared/responder'; import { RESPONSE_STYLE_TAG, renderResponseStyle } from '../../../shared/responseStyle'; import { acquireTerminal, resetTerminal, isTerminalAutomationSafe, terminalAutomationBlockFor } from '@/components/terminalPool'; @@ -709,23 +710,11 @@ export function useHive(config: HarnessConfig | null): void { if (e.event === 'Stop' && codexSizeDue.current.has(e.agentId)) void queueCodexSizeClear(e.agentId); } } else if (e.event === 'Notification' && !breakerArmed) { - // Claude Code fires Notification for two very different situations: - // 1. it genuinely needs the human (a permission / approval prompt), or - // 2. the prompt has merely gone idle ("Claude is waiting for your - // input") — i.e. the agent answered and has nothing queued. - // Only (1) is a real "needs you". Treating (2) as blocked made Michael - // march to the door with a red "!" right after finishing, so detect the - // idle case and let him linger on the floor instead. - const msg = (e.message ?? '').toLowerCase(); - const idleWaiting = !msg - || msg.includes('waiting for your input') - || msg.includes('is idle') - || msg.includes('waiting for input'); - const needsHuman = msg.includes('permission') - || msg.includes('approve') - || msg.includes('confirm') - || msg.includes('needs your'); - if (needsHuman && !idleWaiting) { + // Known Claude notification types are authoritative. Legacy/unknown + // notifications use the shared text fallback so the watchdog and UI + // cannot disagree about HITL versus ordinary idle notifications. + const hookClass = classifyHook(e.event, e.message, e.notificationType); + if (hookClass === 'needsHuman') { // Only the god agent escalates to the human; sub-agents are autonomous // and read as "waiting" (parked on god, not on you). updateAgent(e.agentId, { status: self.isGod ? 'blocked' : 'waiting' }); diff --git a/src/shared/hookClassify.ts b/src/shared/hookClassify.ts new file mode 100644 index 0000000000..61d2e853a0 --- /dev/null +++ b/src/shared/hookClassify.ts @@ -0,0 +1,44 @@ +export type HookClass = 'needsHuman' | 'idle' | null; + +const CLAUDE_BLOCKING_NOTIFICATION_TYPES: ReadonlySet = new Set([ + 'permission_prompt', + 'elicitation_dialog', + 'elicitation_url_dialog', + 'agent_needs_input' +]); + +const CLAUDE_IDLE_NOTIFICATION_TYPES: ReadonlySet = new Set([ + 'idle_prompt' +]); + +const HITL_MESSAGE_MARKERS: readonly string[] = [ + 'permission', + 'approve', + 'confirm', + 'needs your' +]; + +function normalizeString(value: unknown): string { + return typeof value === 'string' ? value.trim().toLowerCase() : ''; +} + +/** Classify Notification hooks consistently across main and renderer. + * Known Claude notification types are authoritative. Legacy and unknown + * types fall back to message markers, where a HITL signal wins over generic + * idle wording. Untrusted runtime field shapes safely normalize to empty. */ +export function classifyHook( + event: unknown, + message?: unknown, + notificationType?: unknown +): HookClass { + if (event !== 'Notification') return null; + + const type = normalizeString(notificationType); + if (CLAUDE_BLOCKING_NOTIFICATION_TYPES.has(type)) return 'needsHuman'; + if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type)) return 'idle'; + + const msg = normalizeString(message); + return HITL_MESSAGE_MARKERS.some((marker) => msg.includes(marker)) + ? 'needsHuman' + : 'idle'; +} diff --git a/test/worker-wake.test.cjs b/test/worker-wake.test.cjs index 5c4df34cf4..42c11efb6e 100644 --- a/test/worker-wake.test.cjs +++ b/test/worker-wake.test.cjs @@ -111,6 +111,36 @@ test('an idle-waiting notification does NOT count as a HITL hold', () => { assert.deepEqual(w.decide([fact()], now), ['alice']); }); +test('a mixed permission and idle-waiting notification blocks nudges', () => { + const w = new WorkerWakeWatchdog(); + w.noteSpawn('pty-alice', 0); + const now = 200_000; + w.noteHook( + 'alice', + 'Notification', + 'Permission required — waiting for your input', + now - 1_000 + ); + assert.equal(w.explain(fact(), now), 'hitl'); + assert.deepEqual(w.decide([fact()], now), []); +}); + +test('a structured blocking notification arms the HITL hold despite idle wording', () => { + const w = new WorkerWakeWatchdog(); + w.noteSpawn('pty-alice', 0); + const now = 200_000; + w.noteHook( + 'alice', + 'Notification', + 'waiting for your input', + now - 1_000, + undefined, + 'permission_prompt' + ); + assert.equal(w.explain(fact(), now), 'hitl'); + assert.deepEqual(w.decide([fact()], now), []); +}); + test('the same inbox mail is not re-announced after the cooldown', () => { const w = new WorkerWakeWatchdog(); w.noteSpawn('pty-alice', 0); @@ -179,6 +209,47 @@ test('classifyHook: permission/approve/confirm shapes are needsHuman', () => { assert.equal(classifyHook('Notification', 'Claude needs your permission to use Bash.'), 'needsHuman'); assert.equal(classifyHook('Notification', 'Approve tool use?'), 'needsHuman'); assert.equal(classifyHook('Notification', 'confirm the change?'), 'needsHuman'); + assert.equal( + classifyHook('Notification', 'Permission required — waiting for your input'), + 'needsHuman' + ); +}); + +test('classifyHook: known structured notification types are authoritative', () => { + for (const notificationType of [ + 'permission_prompt', + 'elicitation_dialog', + 'elicitation_url_dialog', + 'agent_needs_input' + ]) { + assert.equal( + classifyHook('Notification', 'waiting for your input', notificationType), + 'needsHuman', + notificationType + ); + } + + assert.equal( + classifyHook( + 'Notification', + 'Permission required — waiting for your input', + 'idle_prompt' + ), + 'idle' + ); +}); + +test('classifyHook: unknown notification types fall back to message markers', () => { + assert.equal(classifyHook('Notification', 'permission required', 'future_type'), 'needsHuman'); + assert.equal(classifyHook('Notification', 'waiting for your input', 'future_type'), 'idle'); + assert.equal(classifyHook('Notification', '', 'future_type'), 'idle'); +}); + +test('classifyHook: malformed runtime field values never throw', () => { + assert.doesNotThrow(() => classifyHook('Notification', 123)); + assert.equal(classifyHook('Notification', null, 'permission_prompt'), 'needsHuman'); + assert.equal(classifyHook('Notification', {}, 'idle_prompt'), 'idle'); + assert.equal(classifyHook('Notification', 'permission required', {}), 'needsHuman'); }); test('classifyHook: idle-waiting shapes are idle, other events are null', () => { From 891a2db271d0767fc10939bbe29c81a64b09be3c Mon Sep 17 00:00:00 2001 From: hsien wei Date: Sun, 29 Nov 2026 22:41:23 +0800 Subject: [PATCH 2/5] test(hive): cover Notification wiring through HookServer.handle - Drive real Notification payloads through HookServer.handle and assert each field reaches onEvent in its own slot. - Wire a real WorkerWakeWatchdog the way index.ts does so permission_prompt arms the HITL hold and idle_prompt does not. - Catches a notificationType or tool slot slip that typecheck cannot, since the trailing parameters are loosely typed. --- test/hook-server-notification.test.cjs | 92 ++++++++++++++++++++++++++ 1 file changed, 92 insertions(+) create mode 100644 test/hook-server-notification.test.cjs diff --git a/test/hook-server-notification.test.cjs b/test/hook-server-notification.test.cjs new file mode 100644 index 0000000000..ad72680a04 --- /dev/null +++ b/test/hook-server-notification.test.cjs @@ -0,0 +1,92 @@ +// HookServer.handle → onEvent wiring for Notification hooks. +// +// Every argument after `event` is loosely typed (`unknown` / optional string), +// so a slot slip such as passing notification_type where `tool` belongs still +// typechecks. These tests drive a real payload through HookServer.handle and +// assert what the observer actually receives, then feed it to a real +// WorkerWakeWatchdog the same way src/main/index.ts does. + +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const loadTs = require('./load-ts.cjs'); + +const { HookServer } = loadTs('src/core/hookServer.ts'); +const { WorkerWakeWatchdog } = loadTs('src/main/workerWake.ts'); + +/** The smallest HookServer that can run handle(): no socket, no renderer, + * no toasts. `onEvent` is the 7th constructor argument. */ +function serverWith(onEvent) { + const hive = { appendLog() {} }; + return new HookServer( + hive, + () => null, + () => ({ notifications: false }), + undefined, + undefined, + undefined, + onEvent + ); +} + +/** Wire a watchdog exactly like src/main/index.ts does. */ +function watchdogServer() { + const w = new WorkerWakeWatchdog(); + const server = serverWith((agentId, event, message, tool, _source, notificationType) => + w.noteHook(agentId, event, message, undefined, tool, notificationType) + ); + return { w, server }; +} + +function fact() { + return { + agentId: 'alice', + ptyId: 'pty-alice', + lastOutputAt: 100_000, + inboxIds: ['mail-1'], + autoDeliveryPaused: false, + paused: false, + halted: false + }; +} + +test('HookServer.handle hands onEvent each field in its own slot', () => { + const calls = []; + const server = serverWith((...args) => calls.push(args)); + server.handle({ + hook_event_name: 'Notification', + agent_id: 'alice', + message: 'msg-value', + tool_name: 'tool-value', + source: 'source-value', + notification_type: 'type-value' + }); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0], ['alice', 'Notification', 'msg-value', 'tool-value', 'source-value', 'type-value']); +}); + +test('a permission_prompt through HookServer.handle arms the HITL hold despite idle wording', () => { + const { w, server } = watchdogServer(); + w.noteSpawn('pty-alice', 0); + server.handle({ + hook_event_name: 'Notification', + agent_id: 'alice', + message: 'Claude is waiting for your input', + notification_type: 'permission_prompt' + }); + const now = Date.now() + 1_000; + assert.equal(w.explain(fact(), now), 'hitl'); + assert.deepEqual(w.decide([fact()], now), []); +}); + +test('an idle_prompt through HookServer.handle does not arm the HITL hold despite HITL wording', () => { + const { w, server } = watchdogServer(); + w.noteSpawn('pty-alice', 0); + server.handle({ + hook_event_name: 'Notification', + agent_id: 'alice', + message: 'Permission required — waiting for your input', + notification_type: 'idle_prompt' + }); + const now = Date.now() + 1_000; + assert.notEqual(w.explain(fact(), now), 'hitl'); +}); From cd3a3e1c64ba979b4b273f61ec393f85bcfafd8e Mon Sep 17 00:00:00 2001 From: hsien wei Date: Sun, 29 Nov 2026 22:45:21 +0800 Subject: [PATCH 3/5] fix(hive): toast idle prompts by Claude's idle_prompt type - Replace the dead notification_type === 'idle' check: Claude Code sends idle_prompt, so the toast only ever fired through the message wording. - Add isIdleWaitNotification to hookClassify so the toast shares the watchdog's type rules: idle_prompt notifies, blocking types never do. - Without a known type, toast only on idle wording that is not a HITL prompt, so auth_success, empty, and mixed permission messages stay quiet. - Cover the toast through HookServer.handle with a real notifier. --- src/core/hookServer.ts | 10 +++--- src/shared/hookClassify.ts | 21 ++++++++++++ test/hook-server-notification.test.cjs | 44 ++++++++++++++++++++++++++ 3 files changed, 69 insertions(+), 6 deletions(-) diff --git a/src/core/hookServer.ts b/src/core/hookServer.ts index 0d283c6b02..4701b9da40 100644 --- a/src/core/hookServer.ts +++ b/src/core/hookServer.ts @@ -30,6 +30,7 @@ import type { ControlRegistry } from '../main/control'; import type { CircuitBreaker } from '../main/breaker'; import { estimateCostUsd } from '../main/pricing'; import { validateHookEvent } from '../shared/hookEvents'; +import { isIdleWaitNotification } from '../shared/hookClassify'; import type { HookSink } from '../main/hookSink'; import { liveModelOf } from '../shared/liveModel'; @@ -861,12 +862,9 @@ export class HookServer { // A Notification hook that means "the agent is blocked waiting for the user" // (idle prompt) deserves a desktop toast too — distinct from a permission // request, which surfaces natively in the agent's own Claude Code session - // (approvable remotely via /remote-control). - if ( - event === 'Notification' && - (p.notification_type === 'idle' || - (p.message ?? '').toLowerCase().includes('waiting for your input')) - ) { + // (approvable remotely via /remote-control). Claude Code tags this one + // `idle_prompt`; isIdleWaitNotification shares the watchdog's type rules. + if (isIdleWaitNotification(event, p.message, p.notification_type)) { this.notify(agentId ?? 'Agent', p.message ?? 'needs your attention'); } diff --git a/src/shared/hookClassify.ts b/src/shared/hookClassify.ts index 61d2e853a0..e1bb984ba7 100644 --- a/src/shared/hookClassify.ts +++ b/src/shared/hookClassify.ts @@ -42,3 +42,24 @@ export function classifyHook( ? 'needsHuman' : 'idle'; } + +/** Whether a Notification is the "done, waiting for you" idle prompt that + * earns a desktop toast. Not every non-HITL notification qualifies: an + * auth_success or an empty message classifies as idle but is no reason to + * ping the person. A known Claude type decides; without one, the idle + * wording counts only when the message is not a HITL prompt, which surfaces + * natively in the agent's own session instead. */ +export function isIdleWaitNotification( + event: unknown, + message?: unknown, + notificationType?: unknown +): boolean { + if (event !== 'Notification') return false; + + const type = normalizeString(notificationType); + if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type)) return true; + if (CLAUDE_BLOCKING_NOTIFICATION_TYPES.has(type)) return false; + + return classifyHook(event, message, type) === 'idle' + && normalizeString(message).includes('waiting for your input'); +} diff --git a/test/hook-server-notification.test.cjs b/test/hook-server-notification.test.cjs index ad72680a04..035f28a37b 100644 --- a/test/hook-server-notification.test.cjs +++ b/test/hook-server-notification.test.cjs @@ -78,6 +78,50 @@ test('a permission_prompt through HookServer.handle arms the HITL hold despite i assert.deepEqual(w.decide([fact()], now), []); }); +/** Run one Notification through handle() with toasts on; return the toasts. */ +function toastsFor(fields) { + const toasts = []; + const server = new HookServer({ appendLog() {} }, () => null, () => ({ notifications: true })); + server.setNotifier((title, body) => toasts.push({ title, body })); + server.handle({ hook_event_name: 'Notification', agent_id: 'alice', ...fields }); + return toasts; +} + +test('toast: Claude idle_prompt notifies, whatever the wording', () => { + assert.deepEqual( + toastsFor({ message: 'Claude is waiting for your input', notification_type: 'idle_prompt' }), + [{ title: 'alice', body: 'Claude is waiting for your input' }] + ); + assert.equal(toastsFor({ message: 'Claude has finished', notification_type: 'idle_prompt' }).length, 1); +}); + +test('toast: a blocking type never notifies, even with idle wording', () => { + for (const notification_type of ['permission_prompt', 'elicitation_dialog']) { + assert.deepEqual( + toastsFor({ message: 'Claude is waiting for your input', notification_type }), + [], + notification_type + ); + } +}); + +test('toast: without a known type, only non-HITL idle wording notifies', () => { + assert.equal(toastsFor({ message: 'Claude is waiting for your input' }).length, 1); + assert.equal(toastsFor({ message: 'Claude is waiting for your input', notification_type: 'future_type' }).length, 1); + assert.deepEqual(toastsFor({ message: 'Permission required — waiting for your input' }), []); + assert.deepEqual(toastsFor({ message: 'Authentication succeeded', notification_type: 'auth_success' }), []); + assert.deepEqual(toastsFor({ message: '' }), []); +}); + +test('toast: the idle-prompt toast belongs to Notification only', () => { + const toasts = []; + const server = new HookServer({ appendLog() {} }, () => null, () => ({ notifications: true })); + server.setNotifier((title, body) => toasts.push({ title, body })); + server.handle({ hook_event_name: 'Stop', agent_id: 'alice', message: 'waiting for your input', notification_type: 'idle_prompt' }); + // Stop has its own "finished — idle" toast; the Notification body must not appear. + assert.ok(toasts.every((t) => t.body !== 'waiting for your input'), JSON.stringify(toasts)); +}); + test('an idle_prompt through HookServer.handle does not arm the HITL hold despite HITL wording', () => { const { w, server } = watchdogServer(); w.noteSpawn('pty-alice', 0); From b54ca6664f1eb35ce31c90f1a98156784924bc10 Mon Sep 17 00:00:00 2001 From: hsien wei Date: Fri, 4 Dec 2026 17:48:28 +0800 Subject: [PATCH 4/5] fix(hive): open the ptySubmit ask guard with the shared HITL classifier - HookProofRecord.note now takes notification_type and opens the ask when classifyHook says needsHuman, replacing its own ASKS_PERSON/QUIET copy - HookServer.handle passes notification_type to the proof record - Add 'approval' to the shared HITL message markers so no old match is lost - Cover the mixed permission/idle message and a permission_prompt with idle wording in test/hook-proof.test.cjs and through HookServer.handle - Assert isIdleWaitNotification is false for non-Notification events directly instead of inspecting toast bodies --- src/core/hookServer.ts | 2 +- src/main/hookProof.ts | 15 ++---- src/shared/hookClassify.ts | 3 +- test/hook-proof.test.cjs | 64 ++++++++++++++++++++++++++ test/hook-server-notification.test.cjs | 24 +++++++--- test/worker-wake.test.cjs | 1 + 6 files changed, 90 insertions(+), 19 deletions(-) create mode 100644 test/hook-proof.test.cjs diff --git a/src/core/hookServer.ts b/src/core/hookServer.ts index 4701b9da40..6b8037135f 100644 --- a/src/core/hookServer.ts +++ b/src/core/hookServer.ts @@ -581,7 +581,7 @@ export class HookServer { const agentId = p.agent_id ?? undefined; const event = p.hook_event_name ?? 'Unknown'; // Autosend proof first, before any other work here can delay it. - this.proof.note(agentId, event, p.prompt, { message: p.message, tool: p.tool_name }); + this.proof.note(agentId, event, p.prompt, { message: p.message, tool: p.tool_name, notificationType: p.notification_type }); // The session and turn events as they arrive, so a hook lost in the CLI can be told from one lost here. // Tool events are left out: they add nothing to delivery and come by the hundred. A prompt's tail // length only, never its text. diff --git a/src/main/hookProof.ts b/src/main/hookProof.ts index 0657fce9a8..94fcb1df90 100644 --- a/src/main/hookProof.ts +++ b/src/main/hookProof.ts @@ -8,6 +8,7 @@ * removed (promptTail): enough to recognise our own text, never the message. */ import { promptTail, tailMatches } from '../shared/providerAutomation'; +import { classifyHook } from '../shared/hookClassify'; /** Events that mean a prompt was taken or a turn is running. Only these are * proof of activity, and only these show the hook channel works (gate G1, @@ -35,19 +36,13 @@ interface AgentHooks { /** * A PROMPT THAT ASKS THE PERSON IS OPEN (trigger-prompt-058, god, 9 Nov 2026: a launch desk trigger's Enter approved a * subagent's permission prompt that had waited 3 hours, and its own text was lost). Opened by a Notification that needs - * the person (a permission, an approval, a confirm: agentState.ts stateAfter's rule) or by the AskUserQuestion tool. + * the person or by the AskUserQuestion tool. A known Claude notification_type decides; without one, the shared + * HITL-first message rule in hookClassify.ts decides. * Closed only by what answers it: the tool running or failing (PostToolUse, PostToolUseFailure), a prompt sent * (UserPromptSubmit) or a new session (SessionStart). Not by a Stop: a background subagent's prompt stays open after * its parent's turn ends. Not by the quiet "waiting for your input" Notification, which also comes while it is open. */ -const ASKS_PERSON = /permission|approve|approval|confirm|needs your/i; -const QUIET = /waiting for your input|is idle|waiting for input/i; const ASK_CLOSED: ReadonlySet = new Set(['PostToolUse', 'PostToolUseFailure', 'UserPromptSubmit', 'SessionStart']); -/** A Notification's words that ask the person, never the quiet one. */ -export function asksPerson(message: string | undefined): boolean { - const m = (message ?? '').trim(); - return !!m && ASKS_PERSON.test(m) && !QUIET.test(m); -} /** * A COMPACTION IS RUNNING. From PreCompact until one of these comes after it: the @@ -64,14 +59,14 @@ export class HookProofRecord { constructor(private now: () => number = Date.now) {} - note(agentId: string | undefined, event: string, prompt?: unknown, extra?: { message?: unknown; tool?: unknown }): void { + note(agentId: string | undefined, event: string, prompt?: unknown, extra?: { message?: unknown; tool?: unknown; notificationType?: unknown }): void { if (!agentId) return; const at = this.now(); let a = this.byAgent.get(agentId); if (!a) { a = { lastAt: new Map(), turnAt: 0, prompts: [], askOpenAt: 0 }; this.byAgent.set(agentId, a); } a.lastAt.set(event, at); if (TURN_EVENTS.has(event)) a.turnAt = at; - if (event === 'Notification' && asksPerson(typeof extra?.message === 'string' ? extra.message : undefined)) a.askOpenAt = at; + if (classifyHook(event, extra?.message, extra?.notificationType) === 'needsHuman') a.askOpenAt = at; else if (event === 'PreToolUse' && extra?.tool === 'AskUserQuestion') a.askOpenAt = at; else if (ASK_CLOSED.has(event)) a.askOpenAt = 0; if (event === 'UserPromptSubmit' && typeof prompt === 'string') { diff --git a/src/shared/hookClassify.ts b/src/shared/hookClassify.ts index e1bb984ba7..53d453aaa8 100644 --- a/src/shared/hookClassify.ts +++ b/src/shared/hookClassify.ts @@ -14,6 +14,7 @@ const CLAUDE_IDLE_NOTIFICATION_TYPES: ReadonlySet = new Set([ const HITL_MESSAGE_MARKERS: readonly string[] = [ 'permission', 'approve', + 'approval', 'confirm', 'needs your' ]; @@ -22,7 +23,7 @@ function normalizeString(value: unknown): string { return typeof value === 'string' ? value.trim().toLowerCase() : ''; } -/** Classify Notification hooks consistently across main and renderer. +/** Classify Notification hooks consistently for the renderer, WorkerWake and hookProof/ptySubmit. * Known Claude notification types are authoritative. Legacy and unknown * types fall back to message markers, where a HITL signal wins over generic * idle wording. Untrusted runtime field shapes safely normalize to empty. */ diff --git a/test/hook-proof.test.cjs b/test/hook-proof.test.cjs new file mode 100644 index 0000000000..04b497149c --- /dev/null +++ b/test/hook-proof.test.cjs @@ -0,0 +1,64 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const loadTs = require('./load-ts.cjs'); + +const { HookProofRecord } = loadTs('src/main/hookProof.ts'); + +test('a mixed permission and idle notification opens the ask without a type', () => { + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { message: 'Permission required — waiting for your input' }); + assert.equal(proof.askOpen('alice'), true); +}); + +test('a permission_prompt opens the ask despite idle wording', () => { + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { + message: 'Claude is waiting for your input', + notificationType: 'permission_prompt' + }); + assert.equal(proof.askOpen('alice'), true); +}); + +test('a quiet notification without a type does not open the ask', () => { + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { message: 'Claude is waiting for your input' }); + assert.equal(proof.askOpen('alice'), false); +}); + +test('an idle_prompt does not open the ask despite permission wording', () => { + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { + message: 'Permission required — waiting for your input', + notificationType: 'idle_prompt' + }); + assert.equal(proof.askOpen('alice'), false); +}); + +test('approval wording opens the ask without a type', () => { + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { message: 'Tool use needs approval' }); + assert.equal(proof.askOpen('alice'), true); +}); + +test('a quiet notification leaves an ask open until PostToolUse closes it', () => { + let now = 1_000; + const proof = new HookProofRecord(() => now); + proof.note('alice', 'Notification', undefined, { message: 'Permission required' }); + assert.equal(proof.askOpen('alice'), true); + now += 1_000; + proof.note('alice', 'Notification', undefined, { message: 'Claude is waiting for your input' }); + assert.equal(proof.askOpen('alice'), true); + now += 1_000; + proof.note('alice', 'PostToolUse'); + assert.equal(proof.askOpen('alice'), false); +}); + +test('non-string message and notificationType values never throw', () => { + for (const message of [123, {}, null]) { + for (const notificationType of [123, {}, null]) { + const proof = new HookProofRecord(() => 1_000); + assert.doesNotThrow(() => proof.note('alice', 'Notification', undefined, { message, notificationType })); + assert.equal(proof.askOpen('alice'), false); + } + } +}); diff --git a/test/hook-server-notification.test.cjs b/test/hook-server-notification.test.cjs index 035f28a37b..0060e6813b 100644 --- a/test/hook-server-notification.test.cjs +++ b/test/hook-server-notification.test.cjs @@ -12,6 +12,7 @@ const loadTs = require('./load-ts.cjs'); const { HookServer } = loadTs('src/core/hookServer.ts'); const { WorkerWakeWatchdog } = loadTs('src/main/workerWake.ts'); +const { isIdleWaitNotification } = loadTs('src/shared/hookClassify.ts'); /** The smallest HookServer that can run handle(): no socket, no renderer, * no toasts. `onEvent` is the 7th constructor argument. */ @@ -78,6 +79,17 @@ test('a permission_prompt through HookServer.handle arms the HITL hold despite i assert.deepEqual(w.decide([fact()], now), []); }); +test('a permission_prompt through HookServer.handle opens the proof ask despite idle wording', () => { + const server = serverWith(); + server.handle({ + hook_event_name: 'Notification', + agent_id: 'alice', + message: 'Claude is waiting for your input', + notification_type: 'permission_prompt' + }); + assert.equal(server.proof.askOpen('alice'), true); +}); + /** Run one Notification through handle() with toasts on; return the toasts. */ function toastsFor(fields) { const toasts = []; @@ -113,13 +125,11 @@ test('toast: without a known type, only non-HITL idle wording notifies', () => { assert.deepEqual(toastsFor({ message: '' }), []); }); -test('toast: the idle-prompt toast belongs to Notification only', () => { - const toasts = []; - const server = new HookServer({ appendLog() {} }, () => null, () => ({ notifications: true })); - server.setNotifier((title, body) => toasts.push({ title, body })); - server.handle({ hook_event_name: 'Stop', agent_id: 'alice', message: 'waiting for your input', notification_type: 'idle_prompt' }); - // Stop has its own "finished — idle" toast; the Notification body must not appear. - assert.ok(toasts.every((t) => t.body !== 'waiting for your input'), JSON.stringify(toasts)); +test('isIdleWaitNotification: the idle prompt belongs to Notification only', () => { + for (const event of ['Stop', 'SubagentStop', 'PreToolUse', undefined]) { + assert.equal(isIdleWaitNotification(event, 'waiting for your input', 'idle_prompt'), false, String(event)); + } + assert.equal(isIdleWaitNotification('Notification', 'waiting for your input', 'idle_prompt'), true); }); test('an idle_prompt through HookServer.handle does not arm the HITL hold despite HITL wording', () => { diff --git a/test/worker-wake.test.cjs b/test/worker-wake.test.cjs index 42c11efb6e..f62e5efd69 100644 --- a/test/worker-wake.test.cjs +++ b/test/worker-wake.test.cjs @@ -208,6 +208,7 @@ test('forget clears cooldown + boot grace + HITL state', () => { test('classifyHook: permission/approve/confirm shapes are needsHuman', () => { assert.equal(classifyHook('Notification', 'Claude needs your permission to use Bash.'), 'needsHuman'); assert.equal(classifyHook('Notification', 'Approve tool use?'), 'needsHuman'); + assert.equal(classifyHook('Notification', 'Tool use needs approval'), 'needsHuman'); assert.equal(classifyHook('Notification', 'confirm the change?'), 'needsHuman'); assert.equal( classifyHook('Notification', 'Permission required — waiting for your input'), From a4af093fcc33d502e6fd645f66a238f625da6167 Mon Sep 17 00:00:00 2001 From: hsien wei Date: Sat, 5 Dec 2026 13:16:40 +0800 Subject: [PATCH 5/5] fix(hive): match HITL markers by whole word and keep the legacy idle toast MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Match the HITL message markers as whole words, so an idle report such as "Changes approved — waiting for your input" no longer opens a ptySubmit ask that nothing closes on an idle agent - Keep "permissions" and "confirmation" as HITL wording - Toast on the legacy notification_type 'idle' again, as main did; the Grok hook shim passes its type through unchanged - Cover both cases in the classifier, HookProofRecord and HookServer toast tests --- src/shared/hookClassify.ts | 23 ++++++++++++----------- test/hook-proof.test.cjs | 7 +++++++ test/hook-server-notification.test.cjs | 5 +++++ test/worker-wake.test.cjs | 7 +++++++ 4 files changed, 31 insertions(+), 11 deletions(-) diff --git a/src/shared/hookClassify.ts b/src/shared/hookClassify.ts index 53d453aaa8..4e4d320772 100644 --- a/src/shared/hookClassify.ts +++ b/src/shared/hookClassify.ts @@ -11,13 +11,16 @@ const CLAUDE_IDLE_NOTIFICATION_TYPES: ReadonlySet = new Set([ 'idle_prompt' ]); -const HITL_MESSAGE_MARKERS: readonly string[] = [ - 'permission', - 'approve', - 'approval', - 'confirm', - 'needs your' -]; +/** A notification type from before Claude's typed notifications, still passed + * through unchanged by engine shims such as Grok's. It only means "toast"; + * classification falls back to the message as for any unknown type. */ +const LEGACY_IDLE_TOAST_TYPES: ReadonlySet = new Set([ + 'idle' +]); + +/** Whole words only: "approved" or "confirmed" in an idle report must not open + * an ask, because nothing closes one on an idle agent. */ +const HITL_MESSAGE_MARKERS = /\b(?:permissions?|approve|approval|confirm|confirmation|needs your)\b/; function normalizeString(value: unknown): string { return typeof value === 'string' ? value.trim().toLowerCase() : ''; @@ -39,9 +42,7 @@ export function classifyHook( if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type)) return 'idle'; const msg = normalizeString(message); - return HITL_MESSAGE_MARKERS.some((marker) => msg.includes(marker)) - ? 'needsHuman' - : 'idle'; + return HITL_MESSAGE_MARKERS.test(msg) ? 'needsHuman' : 'idle'; } /** Whether a Notification is the "done, waiting for you" idle prompt that @@ -58,7 +59,7 @@ export function isIdleWaitNotification( if (event !== 'Notification') return false; const type = normalizeString(notificationType); - if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type)) return true; + if (CLAUDE_IDLE_NOTIFICATION_TYPES.has(type) || LEGACY_IDLE_TOAST_TYPES.has(type)) return true; if (CLAUDE_BLOCKING_NOTIFICATION_TYPES.has(type)) return false; return classifyHook(event, message, type) === 'idle' diff --git a/test/hook-proof.test.cjs b/test/hook-proof.test.cjs index 04b497149c..5ec9315a4c 100644 --- a/test/hook-proof.test.cjs +++ b/test/hook-proof.test.cjs @@ -62,3 +62,10 @@ test('non-string message and notificationType values never throw', () => { } } }); + +test('a past-tense report with idle wording does not open the ask', () => { + // Nothing closes an ask on an idle agent, so a false open would hold every send while the screen is unreadable. + const proof = new HookProofRecord(() => 1_000); + proof.note('alice', 'Notification', undefined, { message: 'Changes approved — waiting for your input' }); + assert.equal(proof.askOpen('alice'), false); +}); diff --git a/test/hook-server-notification.test.cjs b/test/hook-server-notification.test.cjs index 0060e6813b..b2cc2f21aa 100644 --- a/test/hook-server-notification.test.cjs +++ b/test/hook-server-notification.test.cjs @@ -107,6 +107,11 @@ test('toast: Claude idle_prompt notifies, whatever the wording', () => { assert.equal(toastsFor({ message: 'Claude has finished', notification_type: 'idle_prompt' }).length, 1); }); +test('toast: the legacy idle type still notifies, whatever the wording', () => { + // main toasted on notification_type 'idle'; the Grok shim passes its type through unchanged. + assert.equal(toastsFor({ message: 'Grok finished', notification_type: 'idle' }).length, 1); +}); + test('toast: a blocking type never notifies, even with idle wording', () => { for (const notification_type of ['permission_prompt', 'elicitation_dialog']) { assert.deepEqual( diff --git a/test/worker-wake.test.cjs b/test/worker-wake.test.cjs index f62e5efd69..38322afabf 100644 --- a/test/worker-wake.test.cjs +++ b/test/worker-wake.test.cjs @@ -216,6 +216,13 @@ test('classifyHook: permission/approve/confirm shapes are needsHuman', () => { ); }); +test('classifyHook: HITL markers match whole words, not past-tense reports', () => { + assert.equal(classifyHook('Notification', 'Changes approved — waiting for your input'), 'idle'); + assert.equal(classifyHook('Notification', 'Order confirmed — waiting for your input'), 'idle'); + assert.equal(classifyHook('Notification', 'Claude needs your permissions to continue'), 'needsHuman'); + assert.equal(classifyHook('Notification', 'Awaiting confirmation'), 'needsHuman'); +}); + test('classifyHook: known structured notification types are authoritative', () => { for (const notificationType of [ 'permission_prompt',