diff --git a/config/reliability-gates.jsonc b/config/reliability-gates.jsonc index 30fbf9336e7b..42103e9d352a 100644 --- a/config/reliability-gates.jsonc +++ b/config/reliability-gates.jsonc @@ -20870,6 +20870,124 @@ "Reproduce and fix the native trigger; collect cross-platform and soak evidence." ], "demotionRule": "Keep experimental until the initial trigger and cross-platform behavior are understood." + }, + { + "id": "agent-status.nested-provider-roster", + "title": "Nested review CLIs cannot replace the active pane status", + "maturity": "experimental", + "protection": "partial", + "owner": "agent-session", + "layer": "cross-boundary", + "surfaces": [ + "agent hook normalization", + "sidebar child rows", + "mobile status snapshots" + ], + "platforms": [ + "macos", + "linux", + "windows" + ], + "providers": [ + "local", + "daemon", + "ssh", + "wsl", + "remote-runtime" + ], + "coveredPlatforms": [ + "macos" + ], + "coveredProviders": [], + "coverageNotes": "Contract tests exercise local HTTP hooks, loopback SSH/WSL relay forwarding and legacy relay snapshots. No live SSH, WSL, Linux or Windows execution is claimed. Daemon PTYs use the same hook ingress; folder workspace routing is covered. Hidden macOS Electron validation used the real WorktreeCardAgents component and store in a temporary harness, receiving real hook IPC: 60 nested Codex updates produced zero row mutations, retained 32 children and kept height at 1170px. Screenshots inspected; synthetic hooks, no new model-backed turn.", + "motivatingLinks": [ + "User report (2026-10-15): Claude status in nwparker/SSH alternates between a 32-child roster and an empty roster when nested Codex reviews report on the inherited terminal pane.", + "https://github.com/stablyai/orca/pull/8211", + "https://github.com/stablyai/orca/pull/3990" + ], + "invariant": "A different provider inheriting an active pane key cannot replace its child roster, main turn, prompt, resume identity, model or freshness, nor mutate the owning provider caches. Same-provider children still update; finished or stale owners and distinct execution hosts/workspaces permit provider replacement. WSL local and relay transports retain the same owner.", + "oracle": "Send a full Claude child roster, interleave Codex review lifecycle/tool/approval/completion hooks, and require identical snapshots plus zero publications. A later Claude child event must retain the original prompt and roster, and a real child completion must shrink it.", + "commands": [ + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-nested-agent-boundaries.test.ts src/main/agent-hooks/server-nested-agent-consumers.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/main/agent-hooks/server-turn-started-at.test.ts src/main/agent-hooks/server-status-listener-fanout.test.ts src/main/agent-hooks/terminal-handle-row-identity.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts src/renderer/src/store/slices/agent-status-provider-session.test.ts src/renderer/src/store/slices/agent-status-nested-resume.test.ts src/wsl-guest/agent-hook-provider-normalization.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-agent-presence.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/wsl-guest/agent-hook-server.test.ts --maxWorkers=2", + "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/main/agent-hooks/server-turn-started-at.test.ts src/main/agent-hooks/server-status-listener-fanout.test.ts src/main/agent-hooks/terminal-handle-row-identity.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts --maxWorkers=2" + ], + "testFiles": [ + "src/main/agent-hooks/server-status-listener-fanout.test.ts", + "src/main/agent-hooks/terminal-handle-row-identity.test.ts", + "src/wsl-guest/agent-hook-provider-normalization.test.ts", + "src/main/agent-hooks/server-nested-agent-boundaries.test.ts", + "src/main/agent-hooks/server-nested-agent-consumers.test.ts", + "src/renderer/src/store/slices/agent-status-nested-resume.test.ts", + "src/main/agent-hooks/server-nested-agent-roster.test.ts", + "src/main/agent-hooks/server-nested-agent-model.test.ts", + "src/main/agent-hooks/server-ingest-remote.test.ts", + "src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts" + ], + "assertionRefs": [ + { + "file": "src/main/agent-hooks/server-nested-agent-roster.test.ts", + "assertions": [ + "keeps Claude children, prompt and turn stable through Codex review hooks", + "rejects a nested working snapshot from an older relay without renewing the parent" + ] + } + ], + "evidenceRuns": [ + { + "date": "2026-10-15", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-nested-agent-boundaries.test.ts src/main/agent-hooks/server-nested-agent-consumers.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/main/agent-hooks/server-turn-started-at.test.ts src/main/agent-hooks/server-status-listener-fanout.test.ts src/main/agent-hooks/terminal-handle-row-identity.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts src/renderer/src/store/slices/agent-status-provider-session.test.ts src/renderer/src/store/slices/agent-status-nested-resume.test.ts src/wsl-guest/agent-hook-provider-normalization.test.ts --maxWorkers=2", + "result": "passed", + "durationSeconds": 8.75, + "summary": "132 tests across 13 files passed after review and CI boundary fixes, including actual mobile transcript selection, renderer Claude resume argv, host/workspace collision replacement, WSL transport equivalence, legacy unstamped local renderer entries, Pi identity-only boundaries, clock rollback and provider-isolated relay HTTP/spool/reconnect/teardown." + }, + { + "date": "2026-10-15", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-agent-presence.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/wsl-guest/agent-hook-server.test.ts --maxWorkers=2", + "result": "passed", + "durationSeconds": 91.45, + "summary": "97 tests across seven files passed, including full 32-child local and relay HTTP flows, legacy remote snapshots, model isolation, owner process contracts and renderer ownership. Finished/stale replacement controls added afterward are validated separately." + }, + { + "date": "2026-10-15", + "runner": "local", + "platform": "macos", + "command": "ORCA_BACKGROUND_LAUNCH=1 pnpm exec vitest run --config config/vitest.config.ts src/main/agent-hooks/server-nested-agent-roster.test.ts src/main/agent-hooks/server-ingest-remote.test.ts src/main/agent-hooks/server-nested-agent-model.test.ts src/main/agent-hooks/server-hook-http-ingest.test.ts src/main/agent-hooks/server-turn-started-at.test.ts src/main/agent-hooks/server-status-listener-fanout.test.ts src/main/agent-hooks/terminal-handle-row-identity.test.ts src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts --maxWorkers=2", + "result": "passed", + "durationSeconds": 180.43, + "summary": "Final implementation passes 64 tests in six files, including local/relay finished-provider replacement, stale-provider replacement, 32-child ownership, legacy remote snapshots, turn clocks and renderer identity." + } + ], + "runtimeBudget": { + "p95Seconds": 30, + "scope": "Focused local HTTP, relay, legacy snapshot and renderer contracts; excludes package build and machine contention." + }, + "flakeHistory": { + "status": "not-started", + "evidence": "New gate; no CI soak history." + }, + "redGreenEvidence": { + "status": "partial", + "evidence": "Live incident records alternate between a Claude 32-child roster and a Codex empty roster. Executing the original HEAD identity function accepts a nested working status; the patched function rejects it. Local and relay HTTP roster tests pass and hidden Electron real-component proof preserves all 32 rendered children through 60 nested hooks. No archived CI red/green run yet." + }, + "performanceBudget": { + "required": true, + "evidence": "Main reuses the constant-time provider identity decision and publishes no rejected updates. Legacy relays retain provider-specific prompt/tool/previous-status caches, bounded by MAX_CACHED_PANES for each finite provider and cleared on pane teardown or stop; no polling, timers or subprocesses added." + }, + "promotionCriteria": [ + "Save red/green evidence and CI soak before promotion." + ], + "knownGaps": [ + "A nested CLI started before any owner is observed may still establish the initial pane identity.", + "Same-provider nested sessions remain governed by the existing process/session ownership rules.", + "Live SSH/WSL, Linux, Windows and physical mobile validation are not included." + ], + "demotionRule": "Keep experimental until CI soak; investigate any roster loss or blocked genuine provider replacement without weakening the snapshot and publication assertions." } ] } diff --git a/src/main/agent-hooks/server-ingest-remote.test.ts b/src/main/agent-hooks/server-ingest-remote.test.ts index 67f11a51a2bd..2cf1310b0051 100644 --- a/src/main/agent-hooks/server-ingest-remote.test.ts +++ b/src/main/agent-hooks/server-ingest-remote.test.ts @@ -194,7 +194,7 @@ describe('AgentHookServer ingestRemote', () => { ) }) - it('preserves active pane identity when a nested remote hook reports another agent', () => { + it('preserves active pane status when a nested remote hook reports another agent', () => { vi.useFakeTimers() vi.setSystemTime(1_000) try { @@ -234,17 +234,15 @@ describe('AgentHookServer ingestRemote', () => { expect.objectContaining({ paneKey: PANE, state: 'working', - prompt: 'nested claude', + prompt: 'parent codex', agentType: 'codex', - toolName: 'Read', - toolInput: '00-review-context.md', - receivedAt: 1_100 + receivedAt: 1_000 }) ]) expect(listener).toHaveBeenLastCalledWith( expect.objectContaining({ payload: expect.objectContaining({ - prompt: 'nested claude', + prompt: 'parent codex', agentType: 'codex' }) }) diff --git a/src/main/agent-hooks/server-nested-agent-boundaries.test.ts b/src/main/agent-hooks/server-nested-agent-boundaries.test.ts new file mode 100644 index 000000000000..154da625a09f --- /dev/null +++ b/src/main/agent-hooks/server-nested-agent-boundaries.test.ts @@ -0,0 +1,157 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { AgentHookServer } from './server' +import { AGENT_STATUS_STALE_AFTER_MS } from '../../shared/agent-status-types' +import { buildBody, PANE, postHookEvent } from './server.test-fixtures' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) +})) + +class ClockedHookServer extends AgentHookServer { + advanceConnectionClock(at: number): void { + this.connectionTimestampWatermarkById.set('conn-1', at) + } +} + +const route = { paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1' } + +afterEach(() => { + vi.useRealTimers() + vi.restoreAllMocks() +}) + +describe('nested provider ownership boundaries', () => { + it.each([ + ['ssh-b', 'wt-1', 'codex'], + ['conn-1', 'wt-2', 'codex'], + ['conn-1', 'wt-1', 'claude'] + ] as const)( + 'scopes ownership to host %s and workspace %s', + (connectionId, worktreeId, agentType) => { + const server = new AgentHookServer() + server.ingestRemote( + { ...route, payload: { state: 'working', prompt: 'Parent', agentType: 'claude' } }, + 'conn-1' + ) + server.ingestRemote( + { + ...route, + worktreeId, + payload: { state: 'working', prompt: 'Other', agentType: 'codex' } + }, + connectionId + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ agentType, connectionId, worktreeId }) + } + ) + + it.each([ + [null, 'wsl:Ubuntu'], + ['wsl:Ubuntu', null] + ] as const)('retains WSL ownership across %s to %s transport', (before, after) => { + const server = new AgentHookServer() + const worktreeId = 'repo:://wsl.localhost/Ubuntu/home/user/project' + server.ingestRemote( + { + ...route, + worktreeId, + payload: { state: 'working', prompt: 'Parent', agentType: 'claude' } + }, + before + ) + server.ingestRemote( + { ...route, worktreeId, payload: { state: 'working', prompt: 'Nested', agentType: 'codex' } }, + after + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ agentType: 'claude', prompt: 'Parent' }) + }) + + it('admits a local HTTP owner despite a remote pane-key collision', async () => { + const server = new AgentHookServer() + await server.start({ env: 'production' }) + try { + server.ingestRemote( + { ...route, payload: { state: 'working', prompt: 'Remote', agentType: 'claude' } }, + 'ssh-a' + ) + const response = await postHookEvent( + server, + buildBody({ + hook_event_name: 'UserPromptSubmit', + session_id: 'local-codex', + prompt: 'Local' + }), + '/hook/codex' + ) + expect(response.status).toBe(204) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + connectionId: null, + agentType: 'codex', + prompt: 'Local', + providerSession: { id: 'local-codex' } + }) + } finally { + server.stop() + } + }) + + it('uses the retained connection clock to allow a stale provider replacement after rollback', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const server = new ClockedHookServer() + server.ingestRemote( + { ...route, payload: { state: 'working', prompt: 'Old work', agentType: 'claude' } }, + 'conn-1' + ) + const future = 1_000 + AGENT_STATUS_STALE_AFTER_MS + 100 + server.advanceConnectionClock(future) + vi.setSystemTime(500) + server.ingestRemote( + { ...route, payload: { state: 'working', prompt: 'New work', agentType: 'codex' } }, + 'conn-1' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'codex', + prompt: 'New work', + receivedAt: future + 1 + }) + }) + + it('keeps nested Pi identity-only metadata off an active owner and permits it after completion', () => { + vi.useFakeTimers() + vi.setSystemTime(1_000) + const server = new AgentHookServer() + server.ingestRemote( + { + ...route, + payload: { state: 'working', prompt: 'Parent work', agentType: 'claude' }, + providerSession: { key: 'session_id', id: 'claude-parent' } + }, + 'conn-1' + ) + const before = server.getStatusSnapshot() + const pi = { + ...route, + providerSessionOnly: true, + providerSession: { + key: 'session_id' as const, + id: 'pi-child', + transcriptPath: '/tmp/pi-child.jsonl' + }, + payload: { state: 'done' as const, prompt: '', agentType: 'pi' as const } + } + server.ingestRemote(pi, 'conn-1') + expect(server.getStatusSnapshot()).toEqual(before) + server.ingestRemote( + { ...route, payload: { state: 'done', prompt: 'Parent work', agentType: 'claude' } }, + 'conn-1' + ) + server.ingestRemote(pi, 'conn-1') + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'pi', + providerSessionOnly: true, + providerSession: { id: 'pi-child' } + }) + }) +}) diff --git a/src/main/agent-hooks/server-nested-agent-consumers.test.ts b/src/main/agent-hooks/server-nested-agent-consumers.test.ts new file mode 100644 index 000000000000..071d7953e8d1 --- /dev/null +++ b/src/main/agent-hooks/server-nested-agent-consumers.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { AgentHookServer } from './server' +import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { buildRuntimeMobileAgentStatus } from '../runtime/runtime-mobile-agent-status-builder' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) +})) + +afterEach(() => vi.restoreAllMocks()) + +describe('nested hooks retain the session used by mobile', () => { + it('keeps the Claude mobile transcript through a nested Codex review', async () => { + const server = new AgentHookServer() + await server.start({ env: 'production' }) + try { + await postHookEvent( + server, + buildBody({ + hook_event_name: 'UserPromptSubmit', + session_id: 'claude-parent', + prompt: 'Review my changes' + }) + ) + const checkConsumers = () => { + const mobile = buildRuntimeMobileAgentStatus( + null, + { + type: 'terminal', + id: 'tab-1::leaf', + parentTabId: 'tab-1', + leafId: 'leaf', + title: 'Claude', + launchAgent: 'claude', + isActive: true + }, + null, + null, + () => server.getStatusSnapshot(), + { + getPaneKey: () => PANE, + getLeaf: () => null, + getTrackedTitle: () => null + } + ) + expect(mobile).toMatchObject({ + agentStatus: { + agentType: 'claude', + prompt: 'Review my changes', + providerSession: { id: 'claude-parent' } + } + }) + } + checkConsumers() + for (const hook_event_name of [ + 'SessionStart', + 'UserPromptSubmit', + 'PreToolUse', + 'PostToolUse', + 'PermissionRequest', + 'Stop' + ]) { + const response = await postHookEvent( + server, + buildBody({ + hook_event_name, + session_id: 'nested-codex', + prompt: 'Nested review', + tool_name: 'shell', + model: 'gpt-6-astra' + }), + '/hook/codex' + ) + expect(response.status).toBe(204) + checkConsumers() + } + } finally { + server.stop() + } + }) +}) diff --git a/src/main/agent-hooks/server-nested-agent-model.test.ts b/src/main/agent-hooks/server-nested-agent-model.test.ts index 3fbdb435dcfa..7ee47a07aa8f 100644 --- a/src/main/agent-hooks/server-nested-agent-model.test.ts +++ b/src/main/agent-hooks/server-nested-agent-model.test.ts @@ -185,7 +185,7 @@ describe('AgentHookServer nested agent model fence', () => { server.stop() } - expect(pushed.length).toBeGreaterThanOrEqual(4) + expect(pushed).toHaveLength(2) expect(pushed.every((payload) => payload.agentType === 'claude')).toBe(true) expect(pushed.map((payload) => payload.model)).not.toContain('gpt-6-astra') }) diff --git a/src/main/agent-hooks/server-nested-agent-roster.test.ts b/src/main/agent-hooks/server-nested-agent-roster.test.ts new file mode 100644 index 000000000000..238108f17cd2 --- /dev/null +++ b/src/main/agent-hooks/server-nested-agent-roster.test.ts @@ -0,0 +1,209 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { AgentHookServer } from './server' +import { buildBody, PANE, postHookEvent } from './server.test-fixtures' +import { RelayAgentHookServer } from '../../wsl-guest/agent-hook-server' +import { + AGENT_STATUS_MAX_SUBAGENTS, + AGENT_STATUS_STALE_AFTER_MS +} from '../../shared/agent-status-types' +import type { AgentHookSource } from '../../shared/agent-hook-relay' + +vi.mock('../telemetry/client', () => ({ track: vi.fn() })) +vi.mock('../telemetry/cohort-classifier', () => ({ + getCohortAtEmit: vi.fn(() => ({ nth_repo_added: 2 })) +})) + +afterEach(() => vi.restoreAllMocks()) + +describe('nested agent hooks preserve the owning pane', () => { + it.each(['local', 'relay'] as const)( + 'keeps Claude children, prompt and turn stable through Codex review hooks over %s', + async (transport) => { + const server = new AgentHookServer() + const dir = mkdtempSync(join(tmpdir(), 'orca-nested-roster-')) + const relay = new RelayAgentHookServer({ + endpointDir: dir, + forward: (event) => server.ingestRemote(event, 'conn-1') + }) + const pushed = vi.fn() + server.setListener(pushed) + await server.start({ env: 'production' }) + try { + if (transport === 'relay') { + await relay.start() + } + const post = async (source: AgentHookSource, payload: Record) => { + const body = buildBody(payload) + const response = + transport === 'local' + ? await postHookEvent(server, body, `/hook/${source}`) + : await fetch(`http://127.0.0.1:${relay.getCoordinates().port}/hook/${source}`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'X-Orca-Agent-Hook-Token': relay.getCoordinates().token + }, + body: JSON.stringify(body) + }) + expect(response.status).toBe(204) + } + await post('claude', { + hook_event_name: 'UserPromptSubmit', + session_id: 'claude-parent', + prompt: 'Fix SSH' + }) + await post('claude', { + hook_event_name: 'Stop', + session_id: 'claude-parent', + background_tasks: Array.from({ length: AGENT_STATUS_MAX_SUBAGENTS }, (_, i) => ({ + id: `child${i}`, + type: 'subagent', + status: 'running', + description: `Fix issue ${i}` + })) + }) + const before = server.getStatusSnapshot() + expect(before[0]).toMatchObject({ + state: 'working', + prompt: 'Fix SSH', + mainAgent: { state: 'done' }, + providerSession: { id: 'claude-parent' } + }) + expect(before[0]?.subagents).toHaveLength(AGENT_STATUS_MAX_SUBAGENTS) + pushed.mockClear() + for (const hook_event_name of [ + 'SessionStart', + 'UserPromptSubmit', + 'PreToolUse', + 'PostToolUse', + 'PermissionRequest', + 'Stop' + ]) { + await post('codex', { + hook_event_name, + session_id: 'codex-review', + prompt: 'Review origin/main', + tool_name: 'shell', + tool_input: { command: 'git diff' }, + model: 'gpt-6-astra' + }) + expect(server.getStatusSnapshot()).toEqual(before) + } + expect(pushed).not.toHaveBeenCalled() + await post('claude', { + hook_event_name: 'PreToolUse', + session_id: 'claude-parent', + agent_id: 'child0', + tool_name: 'Read', + tool_input: { file_path: 'README.md' } + }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + prompt: 'Fix SSH', + mainAgent: { state: 'done' }, + providerSession: { id: 'claude-parent' }, + subagents: before[0]?.subagents + }) + await post('claude', { + hook_event_name: 'SubagentStop', + session_id: 'claude-parent', + agent_id: 'child0' + }) + expect(server.getStatusSnapshot()[0]?.subagents).toHaveLength( + AGENT_STATUS_MAX_SUBAGENTS - 1 + ) + await post('claude', { + hook_event_name: 'Stop', + session_id: 'claude-parent', + background_tasks: [] + }) + expect(server.getStatusSnapshot()[0]?.state).toBe('done') + await post('codex', { + hook_event_name: 'UserPromptSubmit', + session_id: 'new-codex', + prompt: 'New turn' + }) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'codex', + prompt: 'New turn', + providerSession: { id: 'new-codex' } + }) + } finally { + relay.stop() + server.stop() + rmSync(dir, { recursive: true, force: true }) + } + } + ) + + it('allows a different provider after the previous status becomes stale', async () => { + const now = vi.spyOn(Date, 'now').mockReturnValue(1_000) + const server = new AgentHookServer() + await server.start({ env: 'production' }) + try { + await postHookEvent( + server, + buildBody({ + hook_event_name: 'UserPromptSubmit', + session_id: 'old-claude', + prompt: 'Old turn' + }) + ) + now.mockReturnValue(1_000 + AGENT_STATUS_STALE_AFTER_MS + 1) + await postHookEvent( + server, + buildBody({ + hook_event_name: 'UserPromptSubmit', + session_id: 'new-codex', + prompt: 'New turn' + }), + '/hook/codex' + ) + expect(server.getStatusSnapshot()[0]).toMatchObject({ + agentType: 'codex', + prompt: 'New turn', + providerSession: { id: 'new-codex' } + }) + } finally { + server.stop() + } + }) + + it('rejects a nested working snapshot from an older relay without renewing the parent', () => { + const server = new AgentHookServer() + const route = { paneKey: PANE, tabId: 'tab-1', worktreeId: 'folder:workspace' } + server.ingestRemote( + { + ...route, + payload: { + state: 'working', + prompt: 'Fix SSH', + agentType: 'claude', + subagents: [{ id: 'child', state: 'working', startedAt: Date.now() }], + mainAgent: { state: 'done', stateStartedAt: Date.now() } + } + }, + 'conn-1' + ) + const before = server.getStatusSnapshot() + const pushed = vi.fn() + server.setListener(pushed) + pushed.mockClear() + server.ingestRemote( + { + ...route, + payload: { + state: 'working', + prompt: 'Review origin/main', + agentType: 'codex' + } + }, + 'conn-1' + ) + expect(server.getStatusSnapshot()).toEqual(before) + expect(pushed).not.toHaveBeenCalled() + server.stop() + }) +}) diff --git a/src/main/agent-hooks/server/server-row-ownership.ts b/src/main/agent-hooks/server/server-row-ownership.ts index e8540392075f..a1836e5777f5 100644 --- a/src/main/agent-hooks/server/server-row-ownership.ts +++ b/src/main/agent-hooks/server/server-row-ownership.ts @@ -1,9 +1,4 @@ -import { - isWslHookRelayConnectionId, - wslHookRelayConnectionId -} from '../../../shared/wsl-hook-relay-contract' -import { splitWorktreeIdForFilesystem, worktreeIdsEqual } from '../../../shared/worktree/id' -import { parseWslUncPath } from '../../../shared/wsl-paths' +import { sameAgentStatusTerminalOwner } from '../../../shared/agent-status-terminal-owner' import { structuralValuesEqualIgnoringUndefined } from '../../../shared/structural-value-equality' import type { AgentHookEventPayload } from '../../../shared/agent-hook-listener/listener-event' import type { @@ -55,13 +50,6 @@ function semanticRowsEqual( return structuralValuesEqualIgnoringUndefined(semanticRow(before), semanticRow(after)) } -function wslDistroForWorktree(worktreeId: string | undefined): string | null { - const worktreePath = worktreeId - ? splitWorktreeIdForFilesystem(worktreeId)?.worktreePath - : undefined - return worktreePath ? (parseWslUncPath(worktreePath)?.distro ?? null) : null -} - export abstract class AgentHookServerRowOwnership extends AgentHookServerListeners { _resetRowOwnershipForTests(): void { this.paneKeyByTerminalHandle.clear() @@ -82,34 +70,7 @@ export abstract class AgentHookServerRowOwnership extends AgentHookServerListene previous: Pick, incoming: Pick ): boolean { - if ( - previous.worktreeId && - incoming.worktreeId && - !worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) - ) { - return false - } - if (previous.connectionId === incoming.connectionId) { - return true - } - const relayConnection = isWslHookRelayConnectionId(previous.connectionId) - ? previous.connectionId - : isWslHookRelayConnectionId(incoming.connectionId) - ? incoming.connectionId - : null - const localConnection = previous.connectionId === null || incoming.connectionId === null - if (!relayConnection || !localConnection || !previous.worktreeId || !incoming.worktreeId) { - return false - } - const previousDistro = wslDistroForWorktree(previous.worktreeId) - const incomingDistro = wslDistroForWorktree(incoming.worktreeId) - return ( - previousDistro !== null && - incomingDistro !== null && - previousDistro === incomingDistro && - relayConnection === wslHookRelayConnectionId(previousDistro) && - worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) - ) + return sameAgentStatusTerminalOwner(previous, incoming) } protected retainedOwnerLaunchTokenHash( diff --git a/src/main/agent-hooks/server/server-status-update.ts b/src/main/agent-hooks/server/server-status-update.ts index e9d98098c059..85cd98cc0a3a 100644 --- a/src/main/agent-hooks/server/server-status-update.ts +++ b/src/main/agent-hooks/server/server-status-update.ts @@ -68,10 +68,6 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA }) return undefined } - if (payload.hookEventName === 'UserPromptSubmit') { - // Why: the prompt boundary is authoritative even when text is unchanged; its next OSC working row must not inherit the prior cron/background turn stamp. - this.activeHookTurnCompletedAtByPaneKey.delete(payload.paneKey) - } // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Main admits enriched legacy rows; the shared view declares their base event type. const previous = this.state.lastStatusByPaneKey.get(payload.paneKey) as | EnrichedAgentHookEventPayload @@ -92,13 +88,39 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA const connectionClearWatermark = terminalOwnedPayload.connectionId ? this.connectionTimestampWatermarkById.get(terminalOwnedPayload.connectionId) : undefined - // Why: renderer ordering rejects older rows; live evidence must sort after reconnect clears and restored rows across clock rollback. const restoredStatusWatermark = previous?.restoredUnconfirmed ? previous.receivedAt : undefined + // Delivery ordering and identity freshness must use the same clock across rollback. const now = Math.max( Date.now(), (connectionClearWatermark ?? -1) + 1, (restoredStatusWatermark ?? -1) + 1 ) + const identity = resolveAgentStatusIdentity({ + existing: + previous && this.sameTerminalOwner(previous, terminalOwnedPayload) + ? { + agentType: previous.payload.agentType, + state: previous.payload.state, + updatedAt: previous.receivedAt, + restoredUnconfirmed: previous.restoredUnconfirmed + } + : undefined, + incoming: terminalOwnedPayload.payload.agentType, + now + }) + if ( + previous && + shouldSuppressInheritedTerminalStatus({ + inheritedFromActivePane: identity.inheritedFromActivePane + }) + ) { + this.commitStatusRowMutation(rowBefore, previous) + return previous + } + if (payload.hookEventName === 'UserPromptSubmit') { + // Why: the prompt boundary is authoritative even when text is unchanged; its next OSC working row must not inherit the prior cron/background turn stamp. + this.activeHookTurnCompletedAtByPaneKey.delete(payload.paneKey) + } if (terminalOwnedPayload.connectionId) { this.connectionTimestampWatermarkById.set(terminalOwnedPayload.connectionId, now) } @@ -159,41 +181,8 @@ export abstract class AgentHookServerStatusUpdate extends AgentHookServerStatusA : stateReconciledPayload.payload } : stateReconciledPayload - const identity = resolveAgentStatusIdentity({ - existing: previous - ? { - agentType: previous.payload.agentType, - state: previous.payload.state, - updatedAt: previous.receivedAt, - restoredUnconfirmed: previous.restoredUnconfirmed - } - : undefined, - incoming: rootContextPreservingPayload.payload.agentType, - now - }) - if ( - previous && - shouldSuppressInheritedTerminalStatus({ - inheritedFromActivePane: identity.inheritedFromActivePane, - incomingState: rootContextPreservingPayload.payload.state - }) - ) { - this.commitStatusRowMutation(rowBefore, previous) - return previous - } - const { model: _nestedModel, ...modelFencedPayload } = rootContextPreservingPayload.payload - const parentModel = previous?.payload.model - const identityResolvedPayload = identity.inheritedFromActivePane - ? { - ...rootContextPreservingPayload, - // Why: a nested CLI's model must stay with the child whose identity was fenced out. - payload: { - ...modelFencedPayload, - agentType: identity.agentType, - ...(parentModel ? { model: parentModel } : {}) - } - } - : identity.agentType === rootContextPreservingPayload.payload.agentType + const identityResolvedPayload = + identity.agentType === rootContextPreservingPayload.payload.agentType ? rootContextPreservingPayload : { ...rootContextPreservingPayload, diff --git a/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts b/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts index 41957078f41a..9aa5657aeb67 100644 --- a/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts +++ b/src/renderer/src/hooks/ipc-events/agent-status-event-applicator.ts @@ -1,3 +1,4 @@ +import { sameAgentStatusTerminalOwner } from '../../../../shared/agent-status-terminal-owner' import { isWslHookRelayConnectionId } from '../../../../shared/wsl-hook-relay-contract' import type { AgentStatusIpcPayload } from '../../../../shared/agent-status-types' import { @@ -196,22 +197,30 @@ export function createAgentStatusEventApplicator(args: { ? { ...statusPayloadWithProvenance, observation: data.observation } : statusPayloadWithProvenance const identity = resolveAgentStatusIdentity({ - existing: existingStatus - ? { - agentType: existingStatus.agentType, - state: existingStatus.state, - updatedAt: existingStatus.updatedAt, - restoredUnconfirmed: existingStatus.restoredUnconfirmed + existing: + existingStatus && + sameAgentStatusTerminalOwner( + { + connectionId: existingStatus.connectionId ?? null, + worktreeId: existingStatus.worktreeId + }, + { + connectionId: + (ownershipConnectionId === undefined + ? existingStatus.connectionId + : ownershipConnectionId) ?? null, + worktreeId: data.worktreeId ?? owningWorktreeId ?? existingStatus.worktreeId } - : undefined, + ) + ? existingStatus + : undefined, incoming: statusPayload.agentType, now: data.receivedAt }) if ( existingStatus && shouldSuppressInheritedTerminalStatus({ - inheritedFromActivePane: identity.inheritedFromActivePane, - incomingState: statusPayload.state + inheritedFromActivePane: identity.inheritedFromActivePane }) ) { return 'dropped' diff --git a/src/renderer/src/store/slices/agent-status-live-entry-builder.ts b/src/renderer/src/store/slices/agent-status-live-entry-builder.ts index cd4c6da3d47f..b7d554a1ce4e 100644 --- a/src/renderer/src/store/slices/agent-status-live-entry-builder.ts +++ b/src/renderer/src/store/slices/agent-status-live-entry-builder.ts @@ -1,3 +1,4 @@ +import { sameAgentStatusTerminalOwner } from '../../../../shared/agent-status-terminal-owner' import type { AppState } from '../types' import { resolveAgentStatusLiveEntryMainAgent } from './agent-status-live-entry-main-agent' import { resolveAgentStatusLiveEntryStateHistory } from './agent-status-live-entry-state-history' @@ -81,14 +82,19 @@ export function buildAgentStatusLiveEntry( const { history, lastCompletedAssistantMessage, stateObservedAt } = resolveAgentStatusLiveEntryStateHistory(existing, payload, updatedAt) const identity = resolveAgentStatusIdentity({ - existing: existing - ? { - agentType: existing.agentType, - state: existing.state, - updatedAt: existing.updatedAt, - restoredUnconfirmed: existing.restoredUnconfirmed + existing: + existing && + sameAgentStatusTerminalOwner( + { connectionId: existing.connectionId ?? null, worktreeId: existing.worktreeId }, + { + connectionId: + (routing?.connectionId === undefined ? existing.connectionId : routing.connectionId) ?? + null, + worktreeId: routing?.worktreeId ?? existing.worktreeId } - : undefined, + ) + ? existing + : undefined, incoming: payload.agentType, now: updatedAt }) @@ -121,8 +127,7 @@ export function buildAgentStatusLiveEntry( if ( existing && shouldSuppressInheritedTerminalStatus({ - inheritedFromActivePane: identity.inheritedFromActivePane, - incomingState: payload.state + inheritedFromActivePane: identity.inheritedFromActivePane }) ) { return { entry: null, reason: 'suppressed-inherited-terminal' } diff --git a/src/renderer/src/store/slices/agent-status-nested-resume.test.ts b/src/renderer/src/store/slices/agent-status-nested-resume.test.ts new file mode 100644 index 000000000000..68481284b623 --- /dev/null +++ b/src/renderer/src/store/slices/agent-status-nested-resume.test.ts @@ -0,0 +1,108 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import { createTestStore } from './store-test-helpers' +import { sleepingRecordFromEntry } from './agent-status-sleeping-records' +import { getAgentResumeArgv } from '../../../../shared/agent-session-resume' + +const PANE = 'tab-1:11111111-1111-4111-8111-111111111111' + +afterEach(() => vi.useRealTimers()) + +describe('nested provider resume ownership', () => { + it.each([ + ['ssh-a', 'ssh-b', 'wt-1', 'wt-1', 'codex'], + [undefined, null, 'wt-1', 'wt-1', 'claude'], + [undefined, 'ssh-b', 'wt-1', 'wt-1', 'codex'], + ['ssh-a', 'ssh-a', 'wt-1', 'wt-2', 'codex'], + ['ssh-a', 'ssh-a', 'wt-1', 'wt-1', 'claude'], + [ + null, + 'wsl:Ubuntu', + 'repo:://wsl.localhost/Ubuntu/home/user/project', + 'repo:://wsl.localhost/Ubuntu/home/user/project', + 'claude' + ], + [ + 'wsl:Ubuntu', + null, + 'repo:://wsl.localhost/Ubuntu/home/user/project', + 'repo:://wsl.localhost/Ubuntu/home/user/project', + 'claude' + ] + ] as const)( + 'scopes resume ownership across %s to %s in %s to %s', + (before, after, oldWorkspace, newWorkspace, agent) => { + vi.useFakeTimers() + const store = createTestStore() + store + .getState() + .setAgentStatus( + PANE, + { state: 'working', prompt: 'Parent', agentType: 'claude' }, + undefined, + undefined, + { connectionId: before, worktreeId: oldWorkspace }, + { providerSession: { key: 'session_id', id: 'claude-parent' } } + ) + store + .getState() + .setAgentStatus( + PANE, + { state: 'working', prompt: 'Other', agentType: 'codex' }, + undefined, + undefined, + { connectionId: after, worktreeId: newWorkspace }, + { providerSession: { key: 'session_id', id: 'other-codex' } } + ) + expect(store.getState().agentStatusByPaneKey[PANE]).toMatchObject({ + agentType: agent, + providerSession: { id: agent === 'claude' ? 'claude-parent' : 'other-codex' } + }) + } + ) + + it('captures Claude resume after nested Codex status and session metadata arrive', () => { + vi.useFakeTimers() + const store = createTestStore() + store + .getState() + .setAgentStatus( + PANE, + { state: 'working', prompt: 'Parent work', agentType: 'claude' }, + 'Claude', + undefined, + { worktreeId: 'wt-1', tabId: 'tab-1' }, + { providerSession: { key: 'session_id', id: 'claude-parent' } } + ) + for (const state of ['working', 'waiting', 'done'] as const) { + store + .getState() + .setAgentStatus( + PANE, + { state, prompt: 'Nested review', agentType: 'codex' }, + 'Codex', + undefined, + { worktreeId: 'wt-1', tabId: 'tab-1' }, + { providerSession: { key: 'session_id', id: 'nested-codex' } } + ) + const record = sleepingRecordFromEntry({ + state: store.getState(), + entry: store.getState().agentStatusByPaneKey[PANE], + worktreeId: 'wt-1', + capturedAt: Date.now() + }) + expect(record).toMatchObject({ + agent: 'claude', + providerSession: { id: 'claude-parent' } + }) + if (!record) { + throw new Error('Expected Claude resume record') + } + expect(getAgentResumeArgv(record.agent, record.providerSession)).toEqual([ + 'claude', + '--resume', + 'claude-parent' + ]) + expect(store.getState().sleepingAgentSessionsByPaneKey[PANE]?.agent).not.toBe('codex') + } + }) +}) diff --git a/src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts b/src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts index 7a80fc0279ee..889db732cd10 100644 --- a/src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts +++ b/src/renderer/src/store/slices/agent-status-tool-assistant-fields.test.ts @@ -81,16 +81,17 @@ describe('agent status tool + assistant fields', () => { expect(store.getState().agentStatusByPaneKey['tab-1:1'].agentType).toBe('claude') }) - it('preserves active pane agentType when a nested hook sends a different known value', () => { + it('preserves the active pane row when a nested hook sends a different known value', () => { vi.useFakeTimers() const store = createTestStore() store .getState() .setAgentStatus('tab-1:1', { state: 'working', prompt: 'p1', agentType: 'codex' }) + const before = store.getState().agentStatusByPaneKey['tab-1:1'] store .getState() .setAgentStatus('tab-1:1', { state: 'working', prompt: 'p2', agentType: 'claude' }) - expect(store.getState().agentStatusByPaneKey['tab-1:1'].agentType).toBe('codex') + expect(store.getState().agentStatusByPaneKey['tab-1:1']).toBe(before) }) it('ignores nested done while the parent pane agent is still active', () => { diff --git a/src/shared/agent-hook-listener.ts b/src/shared/agent-hook-listener.ts index bd10cf8ab61e..9553d0698f67 100644 --- a/src/shared/agent-hook-listener.ts +++ b/src/shared/agent-hook-listener.ts @@ -1,4 +1,6 @@ import { readAgentProcessIdentity } from './agent-process-presence' +import { resolveAgentStatusIdentity } from './agent-status-identity' +import { sameAgentStatusTerminalOwner } from './agent-status-terminal-owner' import { normalizeAgentStatusPayload, type AgentMainAgentStatus } from './agent-status-types' import type { AgentHookSource } from './agent-hook-relay' import { extractAgentProviderSession } from './agent-session-resume' @@ -152,6 +154,33 @@ export function normalizeHookPayload( return null } const previousStatus = state.lastStatusByPaneKey.get(paneKey) + const previousReceivedAt = + previousStatus && + 'receivedAt' in previousStatus && + typeof previousStatus.receivedAt === 'number' + ? previousStatus.receivedAt + : previousStatus?.hostEvidenceObservedAt + // Reject before provider folds mutate the pane's prompt, tool and child caches. + if ( + previousStatus && + previousReceivedAt !== undefined && + sameAgentStatusTerminalOwner( + { connectionId: previousStatus.connectionId ?? null, worktreeId: previousStatus.worktreeId }, + { connectionId: null, worktreeId } + ) && + resolveAgentStatusIdentity({ + existing: { + agentType: previousStatus.payload.agentType, + state: previousStatus.payload.state, + updatedAt: previousReceivedAt, + restoredUnconfirmed: previousStatus.restoredUnconfirmed + }, + incoming: source, + now: Date.now() + }).inheritedFromActivePane + ) { + return null + } // Why: only a MANUAL completion claims anything, so only it may write compact-scoped state. An // auto compact runs inside a turn that resumes and emits its own Stop; running the ownership // guard for it would burn the pane's consumed-compact slot on an event that maps to nothing. diff --git a/src/shared/agent-status-identity.ts b/src/shared/agent-status-identity.ts index 9cb816253105..b618753131e0 100644 --- a/src/shared/agent-status-identity.ts +++ b/src/shared/agent-status-identity.ts @@ -21,11 +21,9 @@ type AgentIdentityResolution = { export function shouldSuppressInheritedTerminalStatus(args: { inheritedFromActivePane: boolean - incomingState: AgentStatusState }): boolean { - // Why: nested child hooks inherit the parent's ORCA_PANE_KEY. A child - // completion does not prove the active parent turn completed. - return args.inheritedFromActivePane && args.incomingState === 'done' + // Nested CLIs inherit the pane key, but own neither its turn nor its children. + return args.inheritedFromActivePane } function normalizedKnownAgentType(agentType: AgentType | null | undefined): AgentType | null { diff --git a/src/shared/agent-status-terminal-owner.ts b/src/shared/agent-status-terminal-owner.ts new file mode 100644 index 000000000000..5013d113e199 --- /dev/null +++ b/src/shared/agent-status-terminal-owner.ts @@ -0,0 +1,46 @@ +import { isWslHookRelayConnectionId, wslHookRelayConnectionId } from './wsl-hook-relay-contract' +import { splitWorktreeIdForFilesystem, worktreeIdsEqual } from './worktree/id' +import { parseWslUncPath } from './wsl-paths' + +type TerminalOwner = { connectionId?: string | null; worktreeId?: string } + +function wslDistroForWorktree(worktreeId: string | undefined): string | null { + const worktreePath = worktreeId + ? splitWorktreeIdForFilesystem(worktreeId)?.worktreePath + : undefined + return worktreePath ? (parseWslUncPath(worktreePath)?.distro ?? null) : null +} + +export function sameAgentStatusTerminalOwner( + previous: TerminalOwner, + incoming: TerminalOwner +): boolean { + if ( + previous.worktreeId && + incoming.worktreeId && + !worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) + ) { + return false + } + if (previous.connectionId === incoming.connectionId) { + return true + } + const relayConnection = isWslHookRelayConnectionId(previous.connectionId) + ? previous.connectionId + : isWslHookRelayConnectionId(incoming.connectionId) + ? incoming.connectionId + : null + const localConnection = previous.connectionId === null || incoming.connectionId === null + if (!relayConnection || !localConnection || !previous.worktreeId || !incoming.worktreeId) { + return false + } + const previousDistro = wslDistroForWorktree(previous.worktreeId) + const incomingDistro = wslDistroForWorktree(incoming.worktreeId) + return ( + previousDistro !== null && + incomingDistro !== null && + previousDistro === incomingDistro && + relayConnection === wslHookRelayConnectionId(previousDistro) && + worktreeIdsEqual(previous.worktreeId, incoming.worktreeId) + ) +} diff --git a/src/wsl-guest/agent-hook-provider-normalization.test.ts b/src/wsl-guest/agent-hook-provider-normalization.test.ts new file mode 100644 index 000000000000..0df9daec5d29 --- /dev/null +++ b/src/wsl-guest/agent-hook-provider-normalization.test.ts @@ -0,0 +1,115 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { RelayAgentHookServer } from './agent-hook-server' +import type { AgentHookRelayEnvelope, AgentHookSource } from '../shared/agent-hook-relay' +import { makePaneKey } from '../shared/stable-pane-id' + +const PANE = makePaneKey('tab-1', '11111111-1111-4111-8111-111111111111') + +describe('relay provider normalization', () => { + let dir: string + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), 'relay-provider-normalization-')) + }) + afterEach(() => rmSync(dir, { recursive: true, force: true })) + + it('forwards mixed-provider spool replay without losing the new prompt', async () => { + const spoolDir = join(dir, 'spool') + mkdirSync(spoolDir) + writeFileSync( + join(spoolDir, 'pane.jsonl'), + `${[ + ['codex', { hook_event_name: 'UserPromptSubmit', prompt: 'Old turn' }], + ['claude', { hook_event_name: 'UserPromptSubmit', prompt: 'New turn' }], + ['claude', { hook_event_name: 'PreToolUse', tool_name: 'Read' }] + ] + .map(([source, payload]) => + JSON.stringify({ + paneKey: PANE, + tabId: 'tab-1', + source, + payload, + receivedAt: Date.now() + }) + ) + .join('\n')}\n` + ) + const forward = vi.fn<(event: AgentHookRelayEnvelope) => void>() + const relay = new RelayAgentHookServer({ endpointDir: dir, forward }) + try { + await relay.start() + expect(forward).toHaveBeenCalledTimes(3) + expect(forward.mock.calls[2][0]).toMatchObject({ + isReplay: true, + payload: { agentType: 'claude', prompt: 'New turn', toolName: 'Read' } + }) + } finally { + relay.stop() + } + }) + + it('forwards a new provider despite the cached owner and replays its latest prompt', async () => { + const forward = vi.fn<(event: AgentHookRelayEnvelope) => void>() + const relay = new RelayAgentHookServer({ endpointDir: dir, forward }) + await relay.start() + const post = async (source: AgentHookSource, payload: Record) => { + const { port, token } = relay.getCoordinates() + const response = await fetch(`http://127.0.0.1:${port}/hook/${source}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'X-Orca-Agent-Hook-Token': token }, + body: JSON.stringify({ paneKey: PANE, tabId: 'tab-1', worktreeId: 'wt-1', payload }) + }) + expect(response.status).toBe(204) + } + try { + await post('codex', { + hook_event_name: 'UserPromptSubmit', + prompt: 'Old Codex turn', + session_id: 'codex-old' + }) + // A desktop interrupt can finish Codex without changing the relay's cached working row. + await post('claude', { + hook_event_name: 'UserPromptSubmit', + prompt: 'New Claude turn', + session_id: 'claude-new' + }) + await post('claude', { + hook_event_name: 'PreToolUse', + session_id: 'claude-new', + tool_name: 'Read', + tool_input: { file_path: 'README.md' } + }) + expect(forward).toHaveBeenCalledTimes(3) + expect(forward.mock.calls[2][0]).toMatchObject({ + providerSession: { id: 'claude-new' }, + payload: { agentType: 'claude', prompt: 'New Claude turn', toolName: 'Read' } + }) + forward.mockClear() + expect(relay.replayCachedPayloadsForPanes()).toBe(1) + expect(forward.mock.calls[0][0]).toMatchObject({ + isReplay: true, + providerSession: { id: 'claude-new' }, + payload: { agentType: 'claude', prompt: 'New Claude turn' } + }) + await post('codex', { + hook_event_name: 'PreToolUse', + session_id: 'codex-old', + tool_name: 'shell' + }) + expect(forward.mock.calls.at(-1)?.[0].payload.prompt).toBe('Old Codex turn') + await post('claude', { + hook_event_name: 'PostToolUse', + session_id: 'claude-new', + tool_name: 'Read' + }) + expect(forward.mock.calls.at(-1)?.[0].payload.prompt).toBe('New Claude turn') + relay.clearPaneState(PANE) + await post('claude', { hook_event_name: 'PreToolUse', tool_name: 'Read' }) + expect(forward.mock.calls.at(-1)?.[0].payload.prompt).toBe('') + } finally { + relay.stop() + } + }) +}) diff --git a/src/wsl-guest/agent-hook-provider-normalization.ts b/src/wsl-guest/agent-hook-provider-normalization.ts new file mode 100644 index 000000000000..fda4c9598b15 --- /dev/null +++ b/src/wsl-guest/agent-hook-provider-normalization.ts @@ -0,0 +1,66 @@ +import { normalizeHookPayload } from '../shared/agent-hook-listener' +import { + clearPaneCacheState, + createHookListenerState, + type HookListenerState +} from '../shared/agent-hook-listener/listener-state' +import type { AgentHookEventPayload } from '../shared/agent-hook-listener/listener-event' +import type { AgentHookSource } from '../shared/agent-hook-relay' +import { cacheRelayLegacyAgentStatus } from '../shared/agent-status-legacy-relay-cache' +import { MAX_CACHED_PANES } from './agent-hook-cached-pane-status' + +/** Forward every provider; only the client knows about desktop-only owner completion. */ +export class RelayProviderHookNormalization { + private readonly states = new Map() + + normalize( + canonical: HookListenerState, + source: AgentHookSource, + body: unknown, + env: string, + options: Parameters[4] = {} + ): AgentHookEventPayload | null { + let state = this.states.get(source) + if (!state) { + state = createHookListenerState() + this.states.set(source, state) + } + // Provider folds stay in the execution host; generic fields cannot leak between providers. + const view: HookListenerState = { + ...canonical, + lastPromptByPaneKey: state.lastPromptByPaneKey, + lastToolByPaneKey: state.lastToolByPaneKey, + lastStatusByPaneKey: state.lastStatusByPaneKey + } + const event = normalizeHookPayload(view, source, body, env, options) + if (event) { + const providerState = state + cacheRelayLegacyAgentStatus(state, event, MAX_CACHED_PANES, (paneKey) => + clearPaneCacheState(providerState, paneKey) + ) + const prompt = state.lastPromptByPaneKey.get(event.paneKey) + const tool = state.lastToolByPaneKey.get(event.paneKey) + if (prompt !== undefined) { + canonical.lastPromptByPaneKey.set(event.paneKey, prompt) + } else { + canonical.lastPromptByPaneKey.delete(event.paneKey) + } + if (tool !== undefined) { + canonical.lastToolByPaneKey.set(event.paneKey, tool) + } else { + canonical.lastToolByPaneKey.delete(event.paneKey) + } + } + return event + } + + clearPane(paneKey: string): void { + for (const state of this.states.values()) { + clearPaneCacheState(state, paneKey) + } + } + + clear(): void { + this.states.clear() + } +} diff --git a/src/wsl-guest/agent-hook-request.ts b/src/wsl-guest/agent-hook-request.ts index c95cdc9e3dd7..6a477d98e527 100644 --- a/src/wsl-guest/agent-hook-request.ts +++ b/src/wsl-guest/agent-hook-request.ts @@ -1,6 +1,5 @@ import type { IncomingMessage, ServerResponse } from 'node:http' import { HOOK_REQUEST_SLOWLORIS_MS } from '../shared/agent-hook-listener/listener-limits' -import { normalizeHookPayload } from '../shared/agent-hook-listener' import { mergeAgentHookRequestHeaders } from '../shared/agent-hook-listener/hook-envelope' import { readRequestBody } from '../shared/agent-hook-listener/request-body' import { resolveHookSource } from '../shared/agent-hook-listener/source-routing' @@ -12,6 +11,7 @@ import type { AgentHookSource } from '../shared/agent-hook-relay' import type { AgentHookResultRetryScheduler } from './agent-hook-result-retry-scheduler' import { hookBodyEnv, hookBodyVersion } from './agent-hook-envelope-build' import { bindOpenCodeTuiSession } from '../shared/agent-hook-listener/opencode-session-registry' +import type { RelayProviderHookNormalization } from './agent-hook-provider-normalization' export async function handleRelayHookRequest( req: IncomingMessage, @@ -20,6 +20,7 @@ export async function handleRelayHookRequest( token: string env: string state: HookListenerState + providerNormalization: RelayProviderHookNormalization isPaneSurfaceRetired: (paneKey: string) => boolean getAgentLaunchToken: (paneKey: string) => string | undefined applyEvent: ( @@ -65,14 +66,20 @@ export async function handleRelayHookRequest( return } let admittedOpenCodeTuiOwner = false - const event = normalizeHookPayload(options.state, source, hookBody, options.env, { - deferCompactOwnershipToClient: true, - admitOpenCodeTui: (identity) => { - const admission = admitRelayOpenCodeTui(options, identity) - admittedOpenCodeTuiOwner = admission === true - return admission + const event = options.providerNormalization.normalize( + options.state, + source, + hookBody, + options.env, + { + deferCompactOwnershipToClient: true, + admitOpenCodeTui: (identity) => { + const admission = admitRelayOpenCodeTui(options, identity) + admittedOpenCodeTuiOwner = admission === true + return admission + } } - }) + ) if (event) { // TODO: once normalizeHookPayload returns validated env/version, drop bodyEnv/bodyVersion and source them from the listener result. const env = hookBodyEnv(hookBody) diff --git a/src/wsl-guest/agent-hook-server.ts b/src/wsl-guest/agent-hook-server.ts index 0250f8a87b6c..9e96a88ecf7f 100644 --- a/src/wsl-guest/agent-hook-server.ts +++ b/src/wsl-guest/agent-hook-server.ts @@ -3,17 +3,13 @@ import { type RelayInterruptHost } from './agent-hook-interrupt-reconciliation' import { applyRelayHookEvent } from './agent-hook-event-admission' +import { RelayProviderHookNormalization } from './agent-hook-provider-normalization' import { RelayAgentHookCanonicalStatus } from './agent-hook-canonical-status' import type { RelayHookForward, RelayHookServerOptions, RelayHookServerStartOptions } from './agent-hook-server-contract' -export type { - RelayHookForward, - RelayHookServerOptions, - RelayHookServerStartOptions -} from './agent-hook-server-contract' import { handleRelayHookRequest } from './agent-hook-request' import { RelayAgentPresence } from './relay-agent-presence' import { createServer, type IncomingMessage, type ServerResponse } from 'node:http' @@ -27,8 +23,7 @@ import { import { clearAllListenerCaches, clearPaneCacheState, - createHookListenerState, - type HookListenerState + createHookListenerState } from '../shared/agent-hook-listener/listener-state' import { getEndpointFileName, @@ -59,7 +54,8 @@ export class RelayAgentHookServer extends RelayAgentHookCanonicalStatus { private endpointDir: string private endpointFilePath: string private endpointFileWritten = false - private state: HookListenerState = createHookListenerState() + private state = createHookListenerState() + private readonly providerNormalization = new RelayProviderHookNormalization() private transportInterference = createHookTransportInterferenceTracker((report) => { process.stderr.write(`${describeHookTransportInterference(report)}\n`) }) @@ -188,6 +184,7 @@ export class RelayAgentHookServer extends RelayAgentHookCanonicalStatus { this.stopCanonicalHooks() this.retryScheduler.clearAll() clearAllListenerCaches(this.state) + this.providerNormalization.clear() this.claudeTerminalInterrupts.clear() this.lastEnvelopeMetaByPaneKey.clear() } @@ -258,6 +255,7 @@ export class RelayAgentHookServer extends RelayAgentHookCanonicalStatus { this.retryScheduler.clearAssistantMessageRetry(paneKey) this.retryScheduler.clearTranscriptPoll(paneKey) clearPaneCacheState(this.state, paneKey) + this.providerNormalization.clearPane(paneKey) this.lastEnvelopeMetaByPaneKey.delete(paneKey) } @@ -284,6 +282,7 @@ export class RelayAgentHookServer extends RelayAgentHookCanonicalStatus { token: this.token, env: this.env, state: this.state, + providerNormalization: this.providerNormalization, isPaneSurfaceRetired: this.isPaneSurfaceRetired, getAgentLaunchToken: this.getAgentLaunchToken, applyEvent: (event, source, env, version) => this.applyEvent(event, source, env, version), @@ -322,6 +321,7 @@ export class RelayAgentHookServer extends RelayAgentHookCanonicalStatus { private ingestSpoolRecord(record: SpoolRecord): void { ingestRelayHookSpoolRecord(record, this.state, this.env, { + providerNormalization: this.providerNormalization, apply: (...args) => this.applyEvent(...args, { isReplay: true }), isPaneSurfaceRetired: this.isPaneSurfaceRetired, getAgentLaunchToken: this.getAgentLaunchToken diff --git a/src/wsl-guest/agent-hook-spool-ingest.ts b/src/wsl-guest/agent-hook-spool-ingest.ts index 4230729f2904..0d4dcc3c6e34 100644 --- a/src/wsl-guest/agent-hook-spool-ingest.ts +++ b/src/wsl-guest/agent-hook-spool-ingest.ts @@ -9,12 +9,14 @@ import { type SpoolRecord } from '../shared/agent-hook-spool' import { hookBodyEnv, hookBodyVersion } from './agent-hook-envelope-build' +import type { RelayProviderHookNormalization } from './agent-hook-provider-normalization' export function ingestRelayHookSpoolRecord( record: SpoolRecord, state: HookListenerState, env: string, host: { + providerNormalization?: RelayProviderHookNormalization apply: ( event: AgentHookEventPayload, source: AgentHookSource, @@ -29,10 +31,13 @@ export function ingestRelayHookSpoolRecord( return } const body = buildSpoolHookBody(record) - const event = normalizeHookPayload(state, record.source, body, env, { + const options: Parameters[4] = { admitOpenCodeTui: (identity) => admitRelayOpenCodeTui(host, identity), deferCompactOwnershipToClient: true - }) + } + const event = host.providerNormalization + ? host.providerNormalization.normalize(state, record.source, body, env, options) + : normalizeHookPayload(state, record.source, body, env, options) if (event) { host.apply(event, record.source, hookBodyEnv(body), hookBodyVersion(body)) }