diff --git a/src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts b/src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts index 5c701a862..204a356e8 100644 --- a/src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts +++ b/src/renderer/src/components/terminal-pane/agent-completion-coordinator.test.ts @@ -22,6 +22,17 @@ function createDeferred(): { promise: Promise; resolve: (value: T) => void return { promise, resolve: resolveDeferred } } +function createRejectableDeferred(): { + promise: Promise + reject: (reason?: unknown) => void +} { + let rejectDeferred!: (reason?: unknown) => void + const promise = new Promise((_resolve, reject) => { + rejectDeferred = reject + }) + return { promise, reject: rejectDeferred } +} + describe('agent completion coordinator', () => { beforeEach(() => { vi.useFakeTimers() @@ -111,6 +122,131 @@ describe('agent completion coordinator', () => { expect(dispatchCompletion).not.toHaveBeenCalled() }) + it('does not validate a pending cwd title with an already in-flight inspection', async () => { + const staleInspection = createDeferred() + const freshInspection = createDeferred() + const inspectProcess = vi + .fn() + .mockReturnValueOnce(staleInspection.promise) + .mockReturnValueOnce(freshInspection.promise) + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess, + dispatchCompletion, + isLive: () => true + }) + + coordinator.startProcessTracking() + vi.advanceTimersByTime(2_000) + await flushAsyncTicks() + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/orca-e2e-repo') + staleInspection.resolve(processResult('codex')) + await flushAsyncTicks() + + expect(inspectProcess).toHaveBeenCalledTimes(2) + expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/orca-e2e-repo') + + freshInspection.resolve(processResult('zsh')) + await flushAsyncTicks() + + expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/orca-e2e-repo') + }) + + it('does not validate a replaced pending title with an older pending-title inspection', async () => { + const titleAInspection = createDeferred() + const titleBInspection = createDeferred() + const inspectProcess = vi + .fn() + .mockReturnValueOnce(titleAInspection.promise) + .mockReturnValueOnce(titleBInspection.promise) + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess, + dispatchCompletion, + isLive: () => true + }) + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/title-a') + await flushAsyncTicks() + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/title-b') + titleAInspection.resolve(processResult('codex')) + await flushAsyncTicks() + + expect(inspectProcess).toHaveBeenCalledTimes(2) + expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b') + + titleBInspection.resolve(processResult('zsh')) + await flushAsyncTicks() + + expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b') + }) + + it('does not drop a replaced pending title from an older non-agent inspection', async () => { + const titleAInspection = createDeferred() + const titleBInspection = createDeferred() + const inspectProcess = vi + .fn() + .mockReturnValueOnce(titleAInspection.promise) + .mockReturnValueOnce(titleBInspection.promise) + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess, + dispatchCompletion, + isLive: () => true + }) + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/title-a') + await flushAsyncTicks() + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/title-b') + titleAInspection.resolve(processResult('zsh')) + await flushAsyncTicks() + + expect(inspectProcess).toHaveBeenCalledTimes(2) + expect(dispatchCompletion).not.toHaveBeenCalledWith('/tmp/title-b') + + titleBInspection.resolve(processResult('codex')) + await flushAsyncTicks() + + expect(dispatchCompletion).toHaveBeenCalledWith('/tmp/title-b') + }) + + it('does not dispatch a pending cwd title when process inspection fails', async () => { + const inspection = createRejectableDeferred() + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(() => inspection.promise), + dispatchCompletion, + isLive: () => true + }) + + coordinator.observeTitle('Codex working') + coordinator.observeTitle('/tmp/orca-e2e-repo') + inspection.reject(new Error('inspection failed')) + await flushAsyncTicks() + + expect(dispatchCompletion).not.toHaveBeenCalled() + }) + it('prefers a later explicit completion title over a pending cwd title', async () => { const inspection = createDeferred() const dispatchCompletion = vi.fn() diff --git a/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts b/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts index 7ec966e3e..a1c142a26 100644 --- a/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts +++ b/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts @@ -51,11 +51,14 @@ export function createAgentCompletionCoordinator( let requiresFreshWorking = false let pollTimer: ReturnType | null = null let pendingTitleTimer: ReturnType | null = null + let pendingTitleSequence = 0 let pendingTitle: { + id: number title: string expiresAt: number maxExpiresAt: number firstInspectionFinished: boolean + validatedByFreshInspection: boolean } | null = null let inspectionInFlight = false let inspectionGeneration = 0 @@ -125,7 +128,12 @@ export function createAgentCompletionCoordinator( } function dispatchPendingTitleIfEligible(): void { - if (!pendingTitle || !agentIdentityEstablished || !hasAgentRunEvidence) { + if ( + !pendingTitle || + !pendingTitle.validatedByFreshInspection || + !agentIdentityEstablished || + !hasAgentRunEvidence + ) { return } const title = pendingTitle.title @@ -165,10 +173,12 @@ export function createAgentCompletionCoordinator( // Why: generic spinner titles can be just "⠋ cwd"; hold the completion // only long enough for one foreground-process probe to prove an agent owns it. pendingTitle = { + id: ++pendingTitleSequence, title, expiresAt: Math.min(now + PENDING_TITLE_TTL_MS, now + PENDING_TITLE_MAX_TTL_MS), maxExpiresAt: now + PENDING_TITLE_MAX_TTL_MS, - firstInspectionFinished: false + firstInspectionFinished: false, + validatedByFreshInspection: false } schedulePendingTitleExpiry() requestInspection('pending-title') @@ -185,12 +195,14 @@ export function createAgentCompletionCoordinator( establishAgentEvidence() } - function handleProcessInspectionResult(result: RuntimeTerminalProcessInspection): void { + function handleProcessInspectionResult(result: RuntimeTerminalProcessInspection): boolean { consecutiveInspectionErrors = 0 const recognized = recognizeAgentProcess(result.foregroundProcess) if (recognized) { handleRecognizedProcess(recognized) - } else if (lastForegroundAgent && hasAgentRunEvidence) { + return true + } + if (lastForegroundAgent && hasAgentRunEvidence) { const exited = lastForegroundAgent dispatchCompletion('process-exit', exited.processName) lastForegroundAgent = null @@ -199,6 +211,7 @@ export function createAgentCompletionCoordinator( lastForegroundAgent = null clearAgentRunEvidence() } + return false } function requestInspection(priority: InspectionPriority): void { @@ -211,13 +224,22 @@ export function createAgentCompletionCoordinator( } inspectionInFlight = true const generationAtRequest = inspectionGeneration + const pendingTitleIdAtRequest = priority === 'pending-title' ? pendingTitle?.id : null enqueueAgentProcessInspection({ priority, run: async () => { + let inspectedRecognizedAgent = false + let inspectionSucceeded = false try { const result = await options.inspectProcess(options.getSettings(), ptyId) if (!disposed && generationAtRequest === inspectionGeneration) { - handleProcessInspectionResult(result) + const appliesToCurrentPendingTitle = + !pendingTitle || + (priority === 'pending-title' && pendingTitle.id === pendingTitleIdAtRequest) + if (appliesToCurrentPendingTitle) { + inspectedRecognizedAgent = handleProcessInspectionResult(result) + } + inspectionSucceeded = true } } catch { consecutiveInspectionErrors += 1 @@ -231,9 +253,21 @@ export function createAgentCompletionCoordinator( } } else { if (pendingTitle) { - pendingTitle.firstInspectionFinished = true - dispatchPendingTitleIfEligible() - schedulePendingTitleExpiry() + if (priority === 'pending-title' && pendingTitle.id === pendingTitleIdAtRequest) { + pendingTitle.firstInspectionFinished = true + if (inspectionSucceeded && inspectedRecognizedAgent) { + pendingTitle.validatedByFreshInspection = true + dispatchPendingTitleIfEligible() + } else if (!inspectionSucceeded) { + dropPendingTitle() + } + schedulePendingTitleExpiry() + } else { + // Why: only the probe requested for this exact pending title + // can prove it belongs to an agent; older in-flight probes are + // stale even when they were also pending-title inspections. + requestInspection('pending-title') + } } scheduleNextPoll() } diff --git a/tests/e2e/droid-notification.spec.ts b/tests/e2e/droid-notification.spec.ts index 783745527..cfc8c41e0 100644 --- a/tests/e2e/droid-notification.spec.ts +++ b/tests/e2e/droid-notification.spec.ts @@ -52,8 +52,8 @@ async function getNotificationDispatches( }) } -async function createAndSwitchToOtherWorktree(page: Page): Promise { - return page.evaluate(async () => { +async function switchToOtherExistingWorktree(page: Page): Promise { + return page.evaluate(() => { const store = window.__store if (!store) { throw new Error('Store unavailable') @@ -69,13 +69,26 @@ async function createAndSwitchToOtherWorktree(page: Page): Promise { if (!activeWorktree) { throw new Error(`Active worktree ${activeWorktreeId} not found`) } - const result = await state.createWorktree( - activeWorktree.repoId, - `codex-hook-notify-${Date.now()}` - ) - await state.fetchWorktrees(activeWorktree.repoId) - state.setActiveWorktree(result.worktree.id) - return result.worktree.id + const otherWorktree = + Object.values(state.worktreesByRepo) + .flat() + .find( + (worktree) => + worktree.repoId === activeWorktree.repoId && + worktree.id !== activeWorktreeId && + worktree.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary' + ) ?? + Object.values(state.worktreesByRepo) + .flat() + .find( + (worktree) => + worktree.repoId === activeWorktree.repoId && worktree.id !== activeWorktreeId + ) + if (!otherWorktree) { + throw new Error(`No inactive worktree found for repo ${activeWorktree.repoId}`) + } + state.setActiveWorktree(otherWorktree.id) + return otherWorktree.id }) } @@ -164,7 +177,7 @@ test.describe('Droid notifications', () => { ) .toBe(true) - await createAndSwitchToOtherWorktree(orcaPage) + await switchToOtherExistingWorktree(orcaPage) const finalMessage = `Codex hook completed ${Date.now()}` await emitCodexHookStatus(endpoint, { diff --git a/tests/e2e/source-control-create-pr.spec.ts b/tests/e2e/source-control-create-pr.spec.ts index 5a0c5ba09..40bef7076 100644 --- a/tests/e2e/source-control-create-pr.spec.ts +++ b/tests/e2e/source-control-create-pr.spec.ts @@ -80,18 +80,12 @@ async function seedCreatePREligibleBranch( throw new Error('window.__store is not available') } const state = store.getState() - const worktreeId = state.activeWorktreeId const worktrees = Object.values(state.worktreesByRepo).flat() - const activeWorktree = worktrees.find((entry) => entry.id === worktreeId) - const worktree = - worktrees.find((entry) => entry.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary') ?? - worktrees.find((entry) => { - const branchName = entry.branch.replace(/^refs\/heads\//, '') - return branchName !== 'main' && !entry.isMainWorktree - }) ?? - activeWorktree + const worktree = worktrees.find( + (entry) => entry.branch.replace(/^refs\/heads\//, '') === 'e2e-secondary' + ) if (!worktree) { - throw new Error('active worktree not found') + throw new Error('seeded e2e-secondary worktree not found') } // Why: the worker-scoped test repo can accumulate extra non-main // worktrees; use the seeded secondary worktree as the stable PR target.