Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions src/main/claude/__fixtures__/claude-hook-event-enums.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"2.0.45": "2.0.44",
"2.0.56": "2.0.55",
"2.1.33": "2.1.32",
"2.1.63": "2.1.62",
"2.1.76": "2.1.75",
"2.1.78": "2.1.77"
},
Expand Down Expand Up @@ -687,6 +688,48 @@
"TeammateIdle",
"TaskCompleted"
],
"2.1.62": [
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"Notification",
"UserPromptSubmit",
"SessionStart",
"SessionEnd",
"Stop",
"SubagentStart",
"SubagentStop",
"PreCompact",
"PermissionRequest",
"Setup",
"TeammateIdle",
"TaskCompleted",
"ConfigChange",
"WorktreeCreate",
"WorktreeRemove"
],
"2.1.63": [
"PreToolUse",
"PostToolUse",
"PostToolUseFailure",
"Notification",
"UserPromptSubmit",
"SessionStart",
"SessionEnd",
"Stop",
"SubagentStart",
"SubagentStop",
"PreCompact",
"PermissionRequest",
"Setup",
"TeammateIdle",
"TaskCompleted",
"Elicitation",
"ElicitationResult",
"ConfigChange",
"WorktreeCreate",
"WorktreeRemove"
],
"2.1.75": [
"PreToolUse",
"PostToolUse",
Expand Down
9 changes: 8 additions & 1 deletion src/main/claude/claude-hook-event-install.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,14 @@ describe('Claude managed hook events by resolved version', () => {

const downgraded = install(current, '2.1.32')

for (const event of ['StopFailure', 'PostCompact', 'TeammateIdle', 'SessionEnd']) {
for (const event of [
'StopFailure',
'PostCompact',
'TeammateIdle',
'SessionEnd',
'Elicitation',
'ElicitationResult'
]) {
expect(downgraded.hooks?.[event], event).toBeUndefined()
}
})
Expand Down
2 changes: 2 additions & 0 deletions src/main/claude/claude-hook-event-versions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ export const CLAUDE_HOOK_EVENT_FIRST_VERSIONS = {
PermissionRequest: '2.0.45',
PostToolUseFailure: '2.0.56',
TeammateIdle: '2.1.33',
Elicitation: '2.1.63',
ElicitationResult: '2.1.63',
PostCompact: '2.1.76',
StopFailure: '2.1.78'
} as const
Expand Down
18 changes: 17 additions & 1 deletion src/main/claude/claude-managed-hook-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,23 @@ const CLAUDE_SESSION_END_EVENT = {
definition: { hooks: [{ type: 'command', command: '' }] }
} as const

export const CLAUDE_MANAGED_EVENTS = [...CLAUDE_EVENTS, CLAUDE_SESSION_END_EVENT] as const
// MCP elicitation dialogs block on the person (#25020); matcher is the MCP server name.
const CLAUDE_ELICITATION_EVENTS = [
{
eventName: 'Elicitation',
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
},
{
eventName: 'ElicitationResult',
definition: { matcher: '*', hooks: [{ type: 'command', command: '' }] }
}
] as const

export const CLAUDE_MANAGED_EVENTS = [
...CLAUDE_EVENTS,
...CLAUDE_ELICITATION_EVENTS,
CLAUDE_SESSION_END_EVENT
] as const

export type ManagedHookEvent = {
eventName: string
Expand Down
99 changes: 99 additions & 0 deletions src/shared/agent-hook-listener-claude-elicitation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { beforeEach, describe, expect, it } from 'vitest'
import { normalizeHookPayload } from './agent-hook-listener'
import {
createHookListenerState,
type HookListenerState
} from './agent-hook-listener/listener-state'
import { makePaneKey } from './stable-pane-id'

const PANE_KEY = makePaneKey('claude-elicitation', '11111111-1111-4111-8111-111111111111')

describe('Claude MCP elicitation', () => {
let state: HookListenerState

beforeEach(() => {
state = createHookListenerState()
})

function claude(payload: Record<string, unknown>) {
return normalizeHookPayload(state, 'claude', { paneKey: PANE_KEY, payload }, 'production')
?.payload
}

it('shows Needs You while an MCP elicitation is open, then returns to working', () => {
expect(
claude({ hook_event_name: 'UserPromptSubmit', prompt: 'approve the server' })?.state
).toBe('working')
const tool = claude({
hook_event_name: 'PreToolUse',
tool_name: 'mcp__server__tool',
tool_use_id: 'toolu_1',
tool_input: { query: 'x' }
})
expect(tool).toMatchObject({ state: 'working', toolName: 'mcp__server__tool' })

const waiting = claude({
hook_event_name: 'Elicitation',
session_id: 'session-a',
mcp_server_name: 'server',
message: 'Allow this?',
mode: 'form'
})
expect(waiting).toMatchObject({
state: 'waiting',
mainAgent: { state: 'waiting' },
toolName: 'mcp__server__tool'
})
expect(waiting?.interactivePrompt).toBeUndefined()

const resumed = claude({
hook_event_name: 'ElicitationResult',
session_id: 'session-a',
action: 'accept',
mode: 'form',
elicitation_id: 'elicit_1'
})
expect(resumed).toMatchObject({
state: 'working',
mainAgent: { state: 'working' },
toolName: 'mcp__server__tool'
})
})

it('settles back to done when a server elicits while the session is idle', () => {
claude({ hook_event_name: 'UserPromptSubmit', prompt: 'go' })
claude({ hook_event_name: 'Stop' })
expect(
claude({ hook_event_name: 'Elicitation', mcp_server_name: 'server', mode: 'url' })?.state
).toBe('waiting')
expect(
claude({ hook_event_name: 'ElicitationResult', mcp_server_name: 'server', action: 'cancel' })
).toMatchObject({ state: 'done', mainAgent: { state: 'done' } })
})

it('settles to done when the listener has no record of the session', () => {
claude({ hook_event_name: 'Elicitation', mcp_server_name: 'server', mode: 'url' })
expect(
claude({ hook_event_name: 'ElicitationResult', mcp_server_name: 'server', action: 'accept' })
).toMatchObject({ state: 'done', mainAgent: { state: 'done' } })
})

it('voids the previous session when an elicitation arrives for a replacement', () => {
claude({
hook_event_name: 'Stop',
session_id: 'session-a',
session_crons: [{ id: 'cron-1' }]
})
expect(state.claudeActiveSessionCronPaneKeys.has(PANE_KEY)).toBe(true)

claude({
hook_event_name: 'Elicitation',
session_id: 'session-b',
mcp_server_name: 'server',
message: 'Allow this?'
})

expect(state.claudeActiveSessionCronPaneKeys.has(PANE_KEY)).toBe(false)
expect(state.claudeSessionOwnerByPaneKey.get(PANE_KEY)).toBe('session-b')
})
})
50 changes: 34 additions & 16 deletions src/shared/agent-hook-listener/providers/claude-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,28 @@ export function normalizeClaudeEvent(
const isAskUserQuestion = eventName === 'PreToolUse' && isAskUserQuestionWait
// Manual PostCompact ends at idle without Stop; auto compaction stays in-turn, and PreCompact alone can be aborted (STA-2915).
const isManualCompactCompletion = eventName === 'PostCompact' && hookPayload.trigger === 'manual'
// An answered MCP dialog restores the displaced state; a server can elicit outside any turn.
if (eventName === 'ElicitationResult') {
if (previousLead?.state !== 'waiting' || previousLead.waitingAgentId !== eventAgentId) {
return null
}
const restored = setClaudeMainAgentTurnState(
state,
paneKey,
previousLead.stateBeforeWait ?? { state: 'working' }
)
return buildClaudeStatusPayload(state, eventName, promptText, paneKey, hookPayload, {
...resolveClaudePaneStatus(state, paneKey, restored),
updateToolSnapshot: true
})
}
const reportedStateName =
eventName === 'UserPromptSubmit' ||
eventName === 'PostToolUse' ||
eventName === 'PostToolUseFailure' ||
(eventName === 'PreToolUse' && !isAskUserQuestion)
? 'working'
: eventName === 'PermissionRequest' || isAskUserQuestion
: eventName === 'PermissionRequest' || eventName === 'Elicitation' || isAskUserQuestion
? 'waiting'
: isTurnBoundary || isManualCompactCompletion
? 'done'
Expand Down Expand Up @@ -224,21 +239,24 @@ export function normalizeClaudeEvent(
}
// Preserve the original lead stash through multiple child waits.
const stateBeforeWait =
isWaitingInducing && eventAgentId && previousLead
? previousLead.state === 'waiting'
? previousLead.stateBeforeWait
: {
state: previousLead.state,
// Child waits must retain the lead's verdict and clock.
...(previousLead.outcome ? { outcome: previousLead.outcome } : {}),
stateStartedAt: previousLead.stateStartedAt,
...(previousLead.taskWakeupTurn ? { taskWakeupTurn: true as const } : {}),
// Keep the displaced lead end time so later child drain belongs to the same turn.
...(previousLead.turnCompletedAt !== undefined
? { turnCompletedAt: previousLead.turnCompletedAt }
: {})
}
: undefined
// Without a lead record there is no turn to resume; an answered dialog must not invent work.
eventName === 'Elicitation' && !previousLead
? { state: 'done' as const, stateStartedAt: Date.now() }
: isWaitingInducing && (eventAgentId || eventName === 'Elicitation') && previousLead
? previousLead.state === 'waiting'
? previousLead.stateBeforeWait
: {
state: previousLead.state,
Comment on lines +245 to +249

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major · Functional Correctness · Quick win

Do not restore a lead state from a replaced session.

If session-a owns a working lead and session-b first appears through Elicitation, voidClaimsOfReplacedClaudeSession changes the owner but leaves that lead record in place. This branch saves session-a's working state and clock. When session-b sends ElicitationResult, the listener restores that old working state, even if session-b had no turn to resume. Compare session ownership before saving previousLead; use the no-prior-lead fallback when ownership changed. (raw.githubusercontent.com)

// Child waits must retain the lead's verdict and clock.
...(previousLead.outcome ? { outcome: previousLead.outcome } : {}),
stateStartedAt: previousLead.stateStartedAt,
...(previousLead.taskWakeupTurn ? { taskWakeupTurn: true as const } : {}),
// Keep the displaced lead end time so later child drain belongs to the same turn.
...(previousLead.turnCompletedAt !== undefined
? { turnCompletedAt: previousLead.turnCompletedAt }
: {})
}
: undefined
const waitingToolUseId = eventToolUseId ?? previousLead?.waitingToolUseId

if (isManualCompactCompletion) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,9 @@ const CLAUDE_SESSION_OWNER_EVENTS: ReadonlySet<string> = new Set([
'PreToolUse',
'PostToolUse',
'PostToolUseFailure',
'PermissionRequest'
'PermissionRequest',
'Elicitation',
'ElicitationResult'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor · Functional Correctness · Quick win

🔎 Supported by static analysis

Script executed:

# Locate the changed symbols and their consumers within the reviewed tree.
rg -n -F -e 'voidClaimsOfReplacedClaudeSession' -e 'CLAUDE_SESSION_OWNER_EVENTS' -e 'ElicitationResult' -e 'Elicitation' -- src/ || test "$?" -eq 1

# Print the complete changed file with line numbers.
wc -l src/shared/agent-hook-listener/providers/claude-roster-state.ts
cat -n src/shared/agent-hook-listener/providers/claude-roster-state.ts

Repository: stablyai/orca

Length of output: 20819


Script executed:

# Print the call site and the ElicitationResult/Elicitation branches with line numbers.
cat -n src/shared/agent-hook-listener/providers/claude-events.ts | sed -n '1,160p'
echo '-----'
cat -n src/shared/agent-hook-listener/providers/claude-events.ts | sed -n '225,270p'

Repository: stablyai/orca

Length of output: 10647


Script executed:

cat -n src/shared/agent-hook-listener/providers/claude-events.ts | sed -n '160,224p'

Repository: stablyai/orca

Length of output: 3649


Script executed:

cat -n src/shared/agent-hook-listener/providers/claude-events.ts | sed -n '270,400p'

Repository: stablyai/orca

Length of output: 3133


Reject stale ElicitationResult events before they change session ownership.

A delayed ElicitationResult from a replaced session can reclaim pane ownership. It can then restore the lead state that the newer session's open dialog displaced. The pane can show working while the newer session's dialog is still open. The same stale result also clears the newer session's replacement-owned cron and unconfirmed roster state.

Main-agent ElicitationResult events have no agent_id. The restore check therefore matches a main-agent Elicitation wait. Reject a main-agent ElicitationResult whose session_id differs from the current pane owner before the owner is reassigned:

🐛 Suggested fix
   }
+  // A stale result must not reclaim ownership or restore the lead after a session replacement.
+  const resultSessionId = readString(hookPayload, 'session_id')
+  const currentOwner = state.claudeSessionOwnerByPaneKey.get(paneKey)
+  if (
+    eventName === 'ElicitationResult' &&
+    eventAgentId === undefined &&
+    resultSessionId !== undefined &&
+    currentOwner !== undefined &&
+    resultSessionId !== currentOwner
+  ) {
+    return null
+  }
   voidClaimsOfReplacedClaudeSession(state, eventName, eventAgentId, paneKey, hookPayload)

Add a regression test that sends an Elicitation from session B, then an ElicitationResult from session A. Assert that the lead remains waiting and that pane ownership remains B.

])

/** Session replacement voids prior conversation claims even without SessionEnd. Preserve live shells until fresh inventory/certified death, confirmed in-process teammates, and the lead record the caller overwrites. */
Expand Down
Loading