Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 5 additions & 1 deletion src/main/pi/agent-status-extension-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
'// Orca receiver from building an unbounded queue of obsolete snapshots.',
'const HOOK_POST_TIMEOUT_MS = 1000',
'let activePost = false',
...(kind === 'pi' ? ['let piUiPromptActive = false'] : []),
'let pendingPost: { hookEventName: string; extra: Record<string, unknown>; metadata: Record<string, unknown>; ompRuntime: boolean } | null = null',
...sessionMetadataSourceLines,
'',
Expand Down Expand Up @@ -164,7 +165,10 @@ export function getPiAgentStatusExtensionSource(kind: PiAgentKind = 'pi'): strin
' const ompRuntime = isOmpRuntime()',
' pendingPost = {',
' hookEventName,',
' extra,',
// Why: every coalesced snapshot must retain an open modal, not just its start event.
kind === 'pi'
? ' extra: { ...extra, ...(!ompRuntime && piUiPromptActive ? { ui_prompt_active: true } : {}) },'
: ' extra,',
' metadata: getPostSessionMetadata(ompRuntime),',
' ompRuntime,',
' }',
Expand Down
2 changes: 2 additions & 0 deletions src/main/pi/agent-status-handler-source.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { PiAgentKind } from '../../shared/pi-agent-kind'
import { getPiAgentStatusUiPromptHandlerSourceLines } from './agent-status-ui-prompt-source'

// Why: keep the generated handler registrations separate from hook transport;
// both are independently sizeable and the installed extension concatenates them.
Expand Down Expand Up @@ -131,6 +132,7 @@ export function getPiAgentStatusHandlerSourceLines(kind: PiAgentKind): string[]
' })',
'',
...approvalHandlers,
...getPiAgentStatusUiPromptHandlerSourceLines(kind),
" // Why: capture the assistant's final text on each completed message",
' // so the dashboard preview reflects the most recent reply even before',
' // agent_end fires. message_end is the right hook because pi guarantees',
Expand Down
23 changes: 23 additions & 0 deletions src/main/pi/agent-status-ui-prompt-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import type { PiAgentKind } from '../../shared/pi-agent-kind'

/** Pi owns nested prompt depth and emits one pair around select/confirm/input/editor/custom. */
export function getPiAgentStatusUiPromptHandlerSourceLines(kind: PiAgentKind): string[] {
if (kind !== 'pi') {
return []
}

return [
" pi.on('ui_prompt_start', () => {",
' if (isOmpRuntime()) return',
' piUiPromptActive = true',
" post('ui_prompt_start')",
' })',
'',
" pi.on('ui_prompt_end', (_event, ctx) => {",
' if (isOmpRuntime() || !piUiPromptActive) return',
' piUiPromptActive = false',
" post('ui_prompt_end', { is_idle: ctx?.isIdle?.() === true })",
' })',
''
]
}
197 changes: 197 additions & 0 deletions src/main/pi/agent-status-ui-prompt.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,197 @@
import { describe, expect, it } from 'vitest'
import { normalizeHookPayload } from '../../shared/agent-hook-listener'
import { PANE_KEY } from '../../shared/agent-hook-listener-test-harness'
import { createHookListenerState } from '../../shared/agent-hook-listener/listener-state'
import { createAgentStatusExtensionHarness } from './agent-status-extension-test-harness'

const HOOK_ENV = { ORCA_PANE_KEY: PANE_KEY, ORCA_AGENT_HOOK_ENV: 'production' }

function createHarness() {
const state = createHookListenerState()
const statuses: ReturnType<typeof normalizeHookPayload>[] = []
const harness = createAgentStatusExtensionHarness({
kind: 'pi',
env: HOOK_ENV,
fetchImpl: async (_url, init) => {
statuses.push(normalizeHookPayload(state, 'pi', JSON.parse(String(init?.body)), 'production'))
return { ok: true }
}
})
return { ...harness, statuses }
}

async function flushPosts(): Promise<void> {
// Each delivery has a bounded promise chain; no wall-clock sleeps in the harness.
for (let i = 0; i < 20; i++) {
await Promise.resolve()
}
}

async function post(harness: ReturnType<typeof createHarness>, name: string, event = {}) {
await harness.callHook(name, event)
await flushPosts()
}

describe('Pi UI prompt status', () => {
it.each(['select', 'confirm', 'input', 'editor', 'custom'])(
'blocks for %s without exposing modal contents and resumes work on close',
async (kind) => {
const harness = createHarness()
await post(harness, 'agent_start')
await post(harness, 'ui_prompt_start', { kind, title: 'Private title' })
expect(harness.statuses.at(-1)?.payload.state).toBe('waiting')
const body = JSON.parse(String(harness.fetchMock.mock.calls.at(-1)?.[1]?.body))
expect(body.payload).toEqual({ hook_event_name: 'ui_prompt_start', ui_prompt_active: true })

await harness.callHook('ui_prompt_end', { kind }, { isIdle: () => false })
await flushPosts()
expect(harness.statuses.at(-1)?.payload.state).toBe('working')
}
)

it.each([
'tool_call',
'tool_execution_start',
'tool_execution_end',
'message_end',
'agent_settled'
])('%s cannot clear an open modal', async (name) => {
const harness = createHarness()
await post(harness, 'ui_prompt_start')
await post(harness, name, {
toolName: 'ask_user_question',
input: { questions: [{ question: 'Stale question' }] },
message: { role: 'assistant', content: [{ type: 'text', text: 'Still here' }] }
})
expect(harness.statuses.at(-1)?.payload).toMatchObject({ state: 'waiting', agentType: 'pi' })
expect(harness.statuses.at(-1)?.payload.toolName).toBeUndefined()
expect(harness.statuses.at(-1)?.payload.interactivePrompt).toBeUndefined()
await harness.callHook('ui_prompt_end', {}, { isIdle: () => true })
await flushPosts()
expect(harness.statuses.at(-1)?.payload.state).toBe('done')
})

it('clears stale question cards when a generic modal opens', async () => {
const harness = createHarness()
await post(harness, 'tool_call', {
toolName: 'ask_user_question',
input: { questions: [{ question: 'Pick one' }] }
})
expect(harness.statuses.at(-1)?.payload.interactivePrompt).toBeDefined()
await post(harness, 'ui_prompt_start')
expect(harness.statuses.at(-1)?.payload.toolName).toBeUndefined()
expect(harness.statuses.at(-1)?.payload.toolInput).toBeUndefined()
expect(harness.statuses.at(-1)?.payload.interactivePrompt).toBeUndefined()
})

it('returns an idle session to done after its modal closes', async () => {
const harness = createHarness()
await post(harness, 'ui_prompt_start')
await harness.callHook('ui_prompt_end', {}, { isIdle: () => true })
await flushPosts()
expect(harness.statuses.map((status) => status?.payload.state)).toEqual(['waiting', 'done'])
})

it('does not infer done when the context cannot establish idleness', async () => {
const harness = createHarness()
await post(harness, 'ui_prompt_start')
await post(harness, 'ui_prompt_end')
expect(harness.statuses.at(-1)?.payload.state).toBe('working')
})

it('lets the normal settlement hook finish work after a modal closes', async () => {
const harness = createHarness()
await post(harness, 'agent_start')
await post(harness, 'ui_prompt_start')
await harness.callHook('ui_prompt_end', {}, { isIdle: () => false })
await flushPosts()
await post(harness, 'agent_settled')
expect(harness.statuses.map((status) => status?.payload.state)).toEqual([
'working',
'waiting',
'working',
'done'
])
})

it('retains modal state across an in-process registration reload', async () => {
const harness = createHarness()
await post(harness, 'ui_prompt_start')
harness.reload()
await post(harness, 'session_start', { reason: 'reload' })
await post(harness, 'tool_execution_end', { toolName: 'bash' })
expect(harness.statuses.at(-1)?.payload.state).toBe('waiting')
})

it('keeps a session-switching modal blocked until it actually closes', async () => {
const harness = createHarness()
await post(harness, 'before_agent_start', { prompt: 'Old session prompt' })
await post(harness, 'ui_prompt_start')
await post(harness, 'session_start', { reason: 'switch' })
expect(harness.statuses.at(-1)?.payload.state).toBe('waiting')
expect(harness.statuses.at(-1)?.payload.prompt).toBe('')
await harness.callHook('ui_prompt_end', {}, { isIdle: () => true })
await flushPosts()
expect(harness.statuses.at(-1)?.payload.state).toBe('done')
})

it('ignores an unmatched prompt end', async () => {
const harness = createHarness()
await post(harness, 'ui_prompt_end')
expect(harness.fetchMock).not.toHaveBeenCalled()
})

it('isolates prompt state between Pi processes', async () => {
const first = createHarness()
const second = createHarness()
await post(first, 'ui_prompt_start')
await post(second, 'agent_start')
expect(first.statuses.at(-1)?.payload.state).toBe('waiting')
expect(second.statuses.at(-1)?.payload.state).toBe('working')
})

it('preserves blocked when a stalled sender coalesces away the start event', async () => {
let finish: (() => void) | undefined
const harness = createAgentStatusExtensionHarness({
kind: 'pi',
env: HOOK_ENV,
fetchImpl: () =>
new Promise<void>((resolve) => {
finish = resolve
})
})
await harness.callHook('agent_start')
await harness.callHook('ui_prompt_start')
await harness.callHook('tool_execution_end', { toolName: 'bash' })
expect(harness.fetchMock).toHaveBeenCalledTimes(1)
finish?.()
await flushPosts()
const state = createHookListenerState()
const latest = JSON.parse(String(harness.fetchMock.mock.calls.at(-1)?.[1]?.body))
expect(latest.payload.hook_event_name).toBe('tool_execution_end')
expect(normalizeHookPayload(state, 'pi', latest, 'production')?.payload.state).toBe('waiting')

await harness.callHook('ui_prompt_end', {}, { isIdle: () => false })
await harness.callHook('tool_execution_start', { toolName: 'bash', args: { command: 'pwd' } })
finish?.()
await flushPosts()
const resumed = JSON.parse(String(harness.fetchMock.mock.calls.at(-1)?.[1]?.body))
expect(normalizeHookPayload(state, 'pi', resumed, 'production')?.payload.state).toBe('working')
finish?.()
await flushPosts()
})

it.each([
{ kind: 'omp' as const },
{ kind: 'prime-agent' as const },
{ kind: 'pi' as const, title: 'omp' }
])('does not add Pi prompt status to $kind ($title)', async (args) => {
const harness = createAgentStatusExtensionHarness(args)
await harness.callHook('ui_prompt_start')
await harness.callHook('ui_prompt_end', {}, { isIdle: () => true })
expect(harness.fetchMock).not.toHaveBeenCalled()
await harness.callHook('tool_call', { toolName: 'bash', input: { command: 'pwd' } })
const body = JSON.parse(String(harness.fetchMock.mock.calls[0]?.[1]?.body))
expect(body.payload.ui_prompt_active).toBeUndefined()
})
})
17 changes: 15 additions & 2 deletions src/shared/agent-hook-listener/providers/pi-family-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ export function normalizePiCompatibleEvent(
if (agentType !== 'omp' && eventName === 'session_start') {
// Why: Pi's session_start fires on TUI open/resume; discard stale turn details, no working row before user activity.
clearPaneTurnCacheState(state, paneKey)
return null
// Why: a custom modal can switch sessions before its promise resolves.
if (agentType !== 'pi' || hookPayload.ui_prompt_active !== true) {
return null
}
}

// Why: gate on the event's own tool_name so a stale cached question can't re-enter blocked.
Expand All @@ -30,8 +33,11 @@ export function normalizePiCompatibleEvent(
(eventName === 'tool_call' || eventName === 'tool_execution_start')
const isOmpApprovalRequest = agentType === 'omp' && eventName === 'tool_approval_requested'
const isOmpApprovalResolution = agentType === 'omp' && eventName === 'tool_approval_resolved'
const isPiUiPrompt =
agentType === 'pi' && (eventName === 'ui_prompt_start' || hookPayload.ui_prompt_active === true)
const isPiUiPromptEnd = agentType === 'pi' && eventName === 'ui_prompt_end'

const stateName =
let stateName =
isPiCompatibleAsk || isOmpApprovalRequest
? 'blocked'
: isOmpApprovalResolution ||
Expand All @@ -46,6 +52,13 @@ export function normalizePiCompatibleEvent(
? 'done'
: null

if (isPiUiPrompt) {
// Why: waiting uses the same orange question icon as Claude/Codex input prompts.
stateName = 'waiting'
} else if (isPiUiPromptEnd) {
stateName = hookPayload.is_idle === true ? 'done' : 'working'
}

if (!stateName) {
return null
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ToolSnapshot } from '../listener-event'
import { isAskUserQuestionTool } from '../../agent-question-answered-intent'
import { deriveToolInputPreview, hasOwnField, readString, toolUpdate } from '../tool-input-preview'
import { deriveInteractivePrompt } from '../interactive-tool'
import { clearActiveToolFieldsUpdate, deriveInteractivePrompt } from '../interactive-tool'

/** OMP's `ask` carries the same questions/options payload as Pi's question tool. */
function serializeQuestionPrompt(toolInput: unknown): string | undefined {
Expand Down Expand Up @@ -29,6 +29,15 @@ export function extractPiToolFields(
hookPayload: Record<string, unknown>,
agentKind: 'pi' | 'omp' | 'prime-agent'
): ToolSnapshot {
// Why: arbitrary modals are not tool approvals or structured question cards.
if (
agentKind === 'pi' &&
(hookPayload.ui_prompt_active === true ||
eventName === 'ui_prompt_start' ||
eventName === 'ui_prompt_end')
) {
return clearActiveToolFieldsUpdate()
}
if (
eventName === 'tool_call' ||
eventName === 'tool_execution_start' ||
Expand Down
63 changes: 63 additions & 0 deletions tests/e2e/pi-ui-prompt-status.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import { test, expect } from './helpers/orca-app'
import { readHookEndpoint } from './helpers/agent-hook-endpoint'
import { ensureTerminalVisible, waitForActiveWorktree, waitForSessionReady } from './helpers/store'
import {
sendToTerminal,
waitForActivePaneHookDescriptor,
waitForActivePanePtyId,
waitForActiveTerminalManager,
waitForTerminalOutput
} from './helpers/terminal'

test('Pi modal hooks show the existing waiting-for-input indicator', async ({
orcaPage,
electronApp
}, testInfo) => {
await waitForSessionReady(orcaPage)
await waitForActiveWorktree(orcaPage)
await ensureTerminalVisible(orcaPage)
await waitForActiveTerminalManager(orcaPage, 30_000)
const endpoint = await readHookEndpoint(electronApp)
const ptyId = await waitForActivePanePtyId(orcaPage)
const marker = '__PI_MODAL_STATUS_READY__'
await sendToTerminal(orcaPage, ptyId, `printf '${marker}\\n'\r`)
await waitForTerminalOutput(orcaPage, marker)
const { paneKey, worktreeId } = await waitForActivePaneHookDescriptor(orcaPage)

async function emit(payload: Record<string, unknown>): Promise<void> {
const response = await fetch(`http://127.0.0.1:${endpoint.port}/hook/pi`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Orca-Agent-Hook-Token': endpoint.token
},
body: JSON.stringify({
paneKey,
tabId: paneKey.split(':')[0],
worktreeId,
env: endpoint.env,
version: endpoint.version,
payload
})
})
expect(response.status).toBe(204)
}

const waiting = orcaPage.locator('[aria-label="Waiting for input"]')
await emit({ hook_event_name: 'before_agent_start', prompt: 'Pi modal status check' })
await expect(orcaPage.locator('[aria-label="Working"]').first()).toBeVisible()
await orcaPage.screenshot({ path: testInfo.outputPath('before-working.png') })

await emit({ hook_event_name: 'ui_prompt_start', ui_prompt_active: true })
await expect(waiting.first()).toBeVisible()
await orcaPage.screenshot({ path: testInfo.outputPath('after-waiting.png') })
await emit({ hook_event_name: 'tool_execution_end', tool_name: 'bash', ui_prompt_active: true })
await expect(waiting.first()).toBeVisible()

await emit({ hook_event_name: 'ui_prompt_end', is_idle: false })
await expect(waiting).toHaveCount(0)
await expect(orcaPage.locator('[aria-label="Working"]').first()).toBeVisible()
await emit({ hook_event_name: 'agent_end' })
await expect(orcaPage.locator('[aria-label="Working"]')).toHaveCount(0)
await expect(waiting).toHaveCount(0)
})
Loading
Loading