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 d48f509c9..6a4c8b197 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 @@ -40,6 +40,7 @@ function createRejectableDeferred(): { } const HOOK_DONE_QUIET_MS = 1_500 +const CODEX_ATTENTION_QUIET_MS = 1_500 describe('agent completion coordinator', () => { beforeEach(() => { @@ -1638,6 +1639,283 @@ describe('agent completion coordinator', () => { expect(dispatchCompletion).toHaveBeenCalledTimes(1) }) + it('cancels the debounced Codex attention notification when work resumes in the quiet window', () => { + // Why: Codex fires PermissionRequest at the human-input boundary *before* the + // approval decision. Under "Approve for me" the review agent approves and + // Codex resumes within the quiet window, so the OS notification must be + // debounced and canceled — no false "approval required" banner (issue #8387). + const dispatchAttention = vi.fn() + const dispatchHookLifecycle = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + dispatchHookLifecycle, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ + state: 'waiting', + ...turn, + toolName: 'exec_command', + toolInput: 'git status' + }) + + // Visual status still updates immediately even though the notification waits. + expect(dispatchHookLifecycle).toHaveBeenCalledWith( + expect.objectContaining({ state: 'waiting', agentType: 'codex' }) + ) + expect(dispatchAttention).not.toHaveBeenCalled() + + coordinator.observeHookStatus({ + state: 'working', + ...turn, + toolName: 'exec_command', + toolInput: 'git status' + }) + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + + expect(dispatchAttention).not.toHaveBeenCalled() + }) + + it('dispatches the debounced Codex attention notification after the quiet window elapses', () => { + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ + state: 'waiting', + ...turn, + toolName: 'exec_command', + toolInput: 'apply patch' + }) + expect(dispatchAttention).not.toHaveBeenCalled() + + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + + expect(dispatchAttention).toHaveBeenCalledTimes(1) + expect(dispatchAttention).toHaveBeenCalledWith( + 'codex', + expect.objectContaining({ + source: 'hook', + agentStatus: expect.objectContaining({ + state: 'waiting', + agentType: 'codex', + toolInput: 'apply patch' + }) + }) + ) + }) + + it('dispatches a non-Codex attention notification immediately without debounce', () => { + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'cursor' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ + state: 'waiting', + ...turn, + toolName: 'Shell', + toolInput: 'pnpm test' + }) + + expect(dispatchAttention).toHaveBeenCalledTimes(1) + // Non-Codex attention must not arm the debounce timer at all. + expect(vi.getTimerCount()).toBe(0) + }) + + it('debounces a blocked Codex pause like waiting and fires after the quiet window', () => { + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ state: 'blocked', ...turn, toolName: 'exec_command' }) + expect(dispatchAttention).not.toHaveBeenCalled() + + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + expect(dispatchAttention).toHaveBeenCalledTimes(1) + }) + + it('cancels the debounced Codex attention when a completion lands in the window (no double notify)', () => { + const dispatchAttention = vi.fn() + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion, + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ state: 'waiting', ...turn, toolName: 'exec_command' }) + // A 'done' completing the turn inside the window must cancel the pending + // attention so the pause never co-fires with the completion notification. + coordinator.observeHookStatus({ state: 'done', ...turn }) + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + + expect(dispatchAttention).not.toHaveBeenCalled() + expect(dispatchCompletion).toHaveBeenCalledTimes(1) + expect(vi.getTimerCount()).toBe(0) + }) + + it('clears the pending Codex attention timer on dispose (no leak, no late fire)', () => { + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ state: 'waiting', ...turn, toolName: 'exec_command' }) + expect(vi.getTimerCount()).toBe(1) + + coordinator.dispose() + expect(vi.getTimerCount()).toBe(0) + + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + expect(dispatchAttention).not.toHaveBeenCalled() + }) + + it('re-arms and fires a second distinct Codex pause after work resumed', () => { + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ state: 'waiting', ...turn, toolName: 'exec_command', toolInput: 'ls' }) + // First pause auto-resolves before the window elapses. + coordinator.observeHookStatus({ state: 'working', ...turn, toolName: 'exec_command', toolInput: 'ls' }) + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + expect(dispatchAttention).not.toHaveBeenCalled() + + // A later, genuinely-distinct pause must re-arm the debounce and fire. + coordinator.observeHookStatus({ state: 'waiting', ...turn, toolName: 'apply_patch', toolInput: 'diff' }) + expect(dispatchAttention).not.toHaveBeenCalled() + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + expect(dispatchAttention).toHaveBeenCalledTimes(1) + }) + + it('cancels the debounced Codex attention when a working-spinner title resumes', () => { + // Why: a Codex resume can surface as a working title before the resume + // 'working' hook lands; that title must also cancel the pending attention + // so the self-resolving pause never fires a false banner (issue #8387). + const dispatchAttention = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(), + dispatchCompletion: vi.fn(), + dispatchAttention, + isLive: () => true + }) + + const turn = { prompt: 'fix the bug', agentType: 'codex' as const } + coordinator.observeHookStatus({ state: 'working', ...turn }) + coordinator.observeHookStatus({ state: 'waiting', ...turn, toolName: 'exec_command' }) + expect(vi.getTimerCount()).toBe(1) + + coordinator.observeTitleWorking() + expect(vi.getTimerCount()).toBe(0) + + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + expect(dispatchAttention).not.toHaveBeenCalled() + }) + + it('does not let a null-foreground inspection blip drop the debounced Codex attention', async () => { + // Why: guard for #8387 fail-open. In the pty-connection coordinator (real + // process polling), a transient null/shell foreground blip — or a remote + // inspection that cannot resolve the foreground — must not convert a genuine + // Codex pause into a process-exit completion while the attention debounce is + // still pending. Mirrors the pendingHookDoneTimer evidence-teardown guard. + let foreground: string | null = 'codex' + const dispatchAttention = vi.fn() + const dispatchCompletion = vi.fn() + const coordinator = createAgentCompletionCoordinator({ + paneKey: 'tab-1:leaf-1', + getPtyId: () => 'pty-1', + getSettings: () => null, + inspectProcess: vi.fn(async () => processResult(foreground)), + dispatchCompletion, + dispatchAttention, + isLive: () => true + }) + + coordinator.startProcessTracking() + // First cadence poll recognizes Codex as the foreground agent (active tier). + await vi.advanceTimersByTimeAsync(2_000) + await flushAsyncTicks() + + // Codex pauses for a permission decision: the OS attention is debounced. + const turn = { prompt: 'apply patch', agentType: 'codex' as const } + coordinator.observeHookStatus({ + state: 'waiting', + ...turn, + toolName: 'exec_command', + toolInput: 'rm -rf build' + }) + expect(dispatchAttention).not.toHaveBeenCalled() + + // Foreground reads null for the whole window; without the guard this would + // land a false process-exit completion racing/duplicating the pause banner. + foreground = null + await vi.advanceTimersByTimeAsync(CODEX_ATTENTION_QUIET_MS + 100) + await flushAsyncTicks() + + expect(dispatchCompletion).not.toHaveBeenCalled() + expect(dispatchAttention).toHaveBeenCalledTimes(1) + }) + it('keeps a generic title completion pending long enough for the first remote inspection', 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 fe3e8208a..f71141e10 100644 --- a/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts +++ b/src/renderer/src/components/terminal-pane/agent-completion-coordinator.ts @@ -61,6 +61,12 @@ const PENDING_TITLE_TTL_MS = Math.max(2_000, INSPECTION_TIMEOUT_MS + 500) const PENDING_TITLE_MAX_TTL_MS = Math.max(30_000, PENDING_TITLE_TTL_MS) const COMPLETION_REPLAY_GUARD_MS = 1_000 const HOOK_DONE_QUIET_MS = 1_500 +// Why: Codex fires its PermissionRequest hook at the human-input boundary before +// the approval decision, so under "Approve for me" the review agent approves and +// Codex resumes almost immediately. Debounce the OS attention notification behind +// this quiet window so a self-resolving pause never raises a false "approval +// required" banner (issue #8387). The visual status still updates immediately. +const CODEX_ATTENTION_QUIET_MS = 1_500 const POLL_TIER_INTERVAL_MS: Record = { active: ACTIVE_POLL_INTERVAL_MS, @@ -106,6 +112,7 @@ export function createAgentCompletionCoordinator( let pendingHookDoneTimer: ReturnType | null = null let pendingHookDoneTitle: string | null = null let pendingHookDonePayload: AgentCompletionStatusSnapshot | null = null + let pendingCodexAttentionTimer: ReturnType | null = null let pendingProcessExitAgent: RecognizedAgentProcess | null = null let pendingTitleSequence = 0 let pendingTitle: { @@ -155,6 +162,13 @@ export function createAgentCompletionCoordinator( pendingHookDonePayload = null } + function clearPendingCodexAttention(): void { + if (pendingCodexAttentionTimer !== null) { + clearTimeout(pendingCodexAttentionTimer) + pendingCodexAttentionTimer = null + } + } + function establishAgentEvidence(): void { agentIdentityEstablished = true hasAgentRunEvidence = true @@ -304,6 +318,9 @@ export function createAgentCompletionCoordinator( lastCompletedTurn = currentTurn lastCompletionSource = source workingStatusObserved = false + // Why: any committed completion (hook/title/process-exit) ends the turn, so a + // debounced Codex attention from an earlier pause must never fire after it. + clearPendingCodexAttention() if (optionsOverride.completionIdentity) { lastCompletionIdentityByPaneKey.set(options.paneKey, optionsOverride.completionIdentity) } @@ -324,6 +341,13 @@ export function createAgentCompletionCoordinator( } } + function dispatchAttentionNotification(payload: AgentCompletionStatusSnapshot): void { + options.dispatchAttention?.(payload.agentType ?? options.paneKey, { + source: 'hook', + agentStatus: payload + }) + } + function dispatchAttention(payload: AgentCompletionStatusSnapshot): void { if (!options.dispatchAttention || !options.isLive() || !hasAgentRunEvidence) { return @@ -333,11 +357,25 @@ export function createAgentCompletionCoordinator( return } lastAttentionToken = token + // Why: the visual "needs input" status must update immediately for every + // agent; only the OS attention notification is debounced (Codex, below). options.dispatchHookLifecycle?.(payload) - options.dispatchAttention(payload.agentType ?? options.paneKey, { - source: 'hook', - agentStatus: payload - }) + if (payload.agentType === 'codex') { + // Why: a Codex PermissionRequest that "Approve for me" auto-resolves fires a + // working/completion hook inside this window, which cancels the pending + // notification (see CODEX_ATTENTION_QUIET_MS). Scoped to Codex so every other + // agent's genuine pause still notifies immediately. + clearPendingCodexAttention() + pendingCodexAttentionTimer = setTimeout(() => { + pendingCodexAttentionTimer = null + if (!options.isLive() || !hasAgentRunEvidence) { + return + } + dispatchAttentionNotification(payload) + }, CODEX_ATTENTION_QUIET_MS) + return + } + dispatchAttentionNotification(payload) } function scheduleHookDoneCompletion(title: string, payload: AgentCompletionStatusSnapshot): void { @@ -472,9 +510,12 @@ export function createAgentCompletionCoordinator( handleRecognizedProcess(recognized) return true } - if (pendingHookDoneTimer !== null) { - // Why: a pending quiet-window 'done' is the authoritative completion; - // tearing down agent evidence here would make the timer drop it. + if (pendingHookDoneTimer !== null || pendingCodexAttentionTimer !== null) { + // Why: a pending quiet-window 'done' or debounced Codex attention is the + // authoritative signal for this turn; tearing down agent evidence here (a + // transient null/shell foreground blip before the agent process is + // recognized) would make the timer's hasAgentRunEvidence guard silently + // drop it. Keep the fail-open contract for #8387 as for the done timer. scheduleNextPoll() return false } @@ -696,6 +737,12 @@ export function createAgentCompletionCoordinator( ) { return false } + // Why: a genuine Codex resume can surface as a working-spinner title before + // (or instead of) the resume 'working' hook, so cancel the debounced + // attention here or the self-resolving pause still fires a false banner + // (#8387). Placed after the replay guard so only an authoritative resume — + // not a stale post-completion title replay — drops a still-pending banner. + clearPendingCodexAttention() workingStatusObserved = true requiresFreshWorking = false lastCompletionIdentityByPaneKey.delete(options.paneKey) @@ -789,6 +836,7 @@ export function createAgentCompletionCoordinator( // so the quiet-window timer never fires a false completion notification. if (isAttentionHookState(payload.state)) { clearPendingHookDone() + clearPendingCodexAttention() } return } @@ -797,6 +845,9 @@ export function createAgentCompletionCoordinator( } if (payload.state === 'working') { clearPendingHookDone() + // Why: resumed work (e.g. Codex after "Approve for me") cancels the debounced + // attention notification so the self-resolving pause never notifies. + clearPendingCodexAttention() workingStatusObserved = true requiresFreshWorking = false lastCompletionIdentity = null @@ -814,6 +865,9 @@ export function createAgentCompletionCoordinator( return } if (isCompletionHookState(payload.state)) { + // Why: the turn is ending, so a debounced attention from an earlier pause in + // this turn must not fire after the completion notification. + clearPendingCodexAttention() if (isRecognizedAgentType(payload.agentType)) { establishAgentEvidence() } @@ -885,6 +939,7 @@ export function createAgentCompletionCoordinator( function resetCompletionState(options: { requireFreshWorking?: boolean } = {}): void { clearPendingHookDone() + clearPendingCodexAttention() dropPendingTitle() agentIdentityEstablished = false hasAgentRunEvidence = false @@ -905,6 +960,7 @@ export function createAgentCompletionCoordinator( disposed = true clearPollTimer() clearPendingHookDone() + clearPendingCodexAttention() dropPendingTitle() // Why: the dedup identity is module-scoped so it survives a live-stream remount // (dispose-then-recreate with the same paneKey while isLive() stays true). Only diff --git a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts index 75487c039..1801c78ba 100644 --- a/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts +++ b/src/renderer/src/hooks/agent-hook-completion-notifications.test.ts @@ -56,6 +56,9 @@ type MockStoreState = { let mockStoreState: MockStoreState const HOOK_DONE_QUIET_MS = 1_500 +// Why: Codex attention notifications are debounced (issue #8387), so a genuine +// permission pause only notifies once this quiet window elapses without resuming. +const CODEX_ATTENTION_QUIET_MS = 1_500 vi.mock('@/store', () => ({ useAppStore: { @@ -106,6 +109,31 @@ function seedCodexPaneLaunchConfig( describe('agent hook completion notifications', () => { const paneKey = 'tab-1:11111111-1111-4111-8111-111111111111' + // Why: the Codex permission-pause tests share a working→pause→quiet-window + // sequence; centralizing it keeps the debounce advance (issue #8387) in one spot. + async function observeCodexPermissionPause(state: 'waiting' | 'blocked'): Promise { + const { observeAgentHookCompletionForNotification } = await import( + './agent-hook-completion-notifications' + ) + observeAgentHookCompletionForNotification({ + paneKey, + worktreeId: 'wt-1', + payload: hookStatus('working') + }) + observeAgentHookCompletionForNotification({ + paneKey, + worktreeId: 'wt-1', + payload: { + state, + prompt: 'implement notifications', + agentType: 'codex', + toolName: 'exec_command', + toolInput: 'git status' + } + }) + vi.advanceTimersByTime(CODEX_ATTENTION_QUIET_MS) + } + beforeEach(() => { vi.resetModules() vi.useFakeTimers() @@ -560,50 +588,14 @@ describe('agent hook completion notifications', () => { it('fails open for Codex auto-approved permission requests without launch proof', async () => { seedCodexPaneLaunchConfig(paneKey, YOLO_TUI_AGENT_ARGS.codex ?? '') - const { observeAgentHookCompletionForNotification } = - await import('./agent-hook-completion-notifications') - - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: hookStatus('working') - }) - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: { - state: 'waiting', - prompt: 'implement notifications', - agentType: 'codex', - toolName: 'exec_command', - toolInput: 'git status' - } - }) + await observeCodexPermissionPause('waiting') expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) }) it('still notifies for manual Codex permission requests', async () => { seedCodexPaneLaunchConfig(paneKey, '') - const { observeAgentHookCompletionForNotification } = - await import('./agent-hook-completion-notifications') - - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: hookStatus('working') - }) - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: { - state: 'waiting', - prompt: 'implement notifications', - agentType: 'codex', - toolName: 'exec_command', - toolInput: 'git status' - } - }) + await observeCodexPermissionPause('waiting') expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) expect(dispatchTerminalNotification).toHaveBeenCalledWith( @@ -618,25 +610,7 @@ describe('agent hook completion notifications', () => { it('fails open for Codex auto-approved blocked permission requests without launch proof', async () => { seedCodexPaneLaunchConfig(paneKey, YOLO_TUI_AGENT_ARGS.codex ?? '') - const { observeAgentHookCompletionForNotification } = - await import('./agent-hook-completion-notifications') - - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: hookStatus('working') - }) - observeAgentHookCompletionForNotification({ - paneKey, - worktreeId: 'wt-1', - payload: { - state: 'blocked', - prompt: 'implement notifications', - agentType: 'codex', - toolName: 'exec_command', - toolInput: 'git status' - } - }) + await observeCodexPermissionPause('blocked') expect(dispatchTerminalNotification).toHaveBeenCalledTimes(1) })