diff --git a/src/renderer/src/hooks/useIpcEvents.test.ts b/src/renderer/src/hooks/useIpcEvents.test.ts index cf1a370ab..e32043a8d 100644 --- a/src/renderer/src/hooks/useIpcEvents.test.ts +++ b/src/renderer/src/hooks/useIpcEvents.test.ts @@ -6746,6 +6746,290 @@ describe('useIpcEvents agent status snapshot integration', () => { ) }) + it('queues replayed startup snapshots until the pane hydrates', async () => { + const setAgentStatus = vi.fn() + const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null } + let resolveSnapshot!: (entries: AgentStatusSetData[]) => void + const getSnapshot = vi.fn( + () => + new Promise((resolve) => { + resolveSnapshot = resolve + }) + ) + + const storeState: StoreLike = buildStoreState({ + setAgentStatus, + workspaceSessionReady: true, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + repos: [], + worktreesByRepo: {} + }) + + stubReactSyncEffect() + vi.doMock('../store', () => ({ + useAppStore: { + subscribe: vi.fn((listener: StoreSubscribeListener) => { + subscribeListenerRef.current = listener + return () => { + subscribeListenerRef.current = null + } + }), + getState: () => storeState + } + })) + stubAuxiliaryModules() + vi.stubGlobal( + 'window', + buildWindowApi({ + getSnapshot, + onSet: () => () => {} + }) + ) + + const { useIpcEvents } = await import('./useIpcEvents') + + useIpcEvents() + await Promise.resolve() + + resolveSnapshot([ + { + paneKey: FUTURE_PANE_KEY, + tabId: 'tab-future', + worktreeId: 'wt-1', + connectionId: 'ssh-1', + state: 'working', + prompt: 'PreToolUse: Bash', + agentType: 'codex', + toolName: 'Bash', + toolInput: 'pnpm test', + terminalHandle: 'term-future', + receivedAt: 1_700_000_000_000, + stateStartedAt: 1_699_999_999_000 + } + ]) + await Promise.resolve() + await Promise.resolve() + + expect(setAgentStatus).not.toHaveBeenCalled() + + Object.assign(storeState, { + tabsByWorktree: { + 'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'SSH Tab' }] + }, + terminalLayoutsByTabId: { + 'tab-future': { + root: { type: 'leaf', leafId: FUTURE_LEAF_ID }, + activeLeafId: FUTURE_LEAF_ID, + expandedLeafId: null + } + } + }) + subscribeListenerRef.current?.(storeState, storeState) + + expect(setAgentStatus).toHaveBeenCalledTimes(1) + expect(setAgentStatus).toHaveBeenCalledWith( + FUTURE_PANE_KEY, + expect.objectContaining({ + state: 'working', + prompt: 'PreToolUse: Bash', + agentType: 'codex', + toolName: 'Bash', + toolInput: 'pnpm test' + }), + 'SSH Tab', + { updatedAt: 1_700_000_000_000, stateStartedAt: 1_699_999_999_000 }, + expectWorktreeRouting('wt-1'), + undefined + ) + }) + + it('suppresses notifications for replayed done snapshots after pane hydration', async () => { + const setAgentStatus = vi.fn() + const observeAgentHookCompletionForNotification = vi.fn() + const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null } + let resolveSnapshot!: (entries: AgentStatusSetData[]) => void + const getSnapshot = vi.fn( + () => + new Promise((resolve) => { + resolveSnapshot = resolve + }) + ) + + const storeState: StoreLike = buildStoreState({ + setAgentStatus, + workspaceSessionReady: true, + settings: { terminalFontSize: 13, notifications: { enabled: true, agentTaskComplete: true } }, + tabsByWorktree: {}, + terminalLayoutsByTabId: {}, + repos: [], + worktreesByRepo: {} + }) + + stubReactSyncEffect() + vi.doMock('../store', () => ({ + useAppStore: { + subscribe: vi.fn((listener: StoreSubscribeListener) => { + subscribeListenerRef.current = listener + return () => { + subscribeListenerRef.current = null + } + }), + getState: () => storeState + } + })) + vi.doMock('./agent-hook-completion-notifications', () => ({ + observeAgentHookCompletionForNotification, + resetAgentHookCompletionNotificationCoordinators: vi.fn(), + syncAgentHookCompletionNotificationSettings: vi.fn(), + syncAgentHookCompletionNotificationsForStoreUpdate: vi.fn() + })) + stubAuxiliaryModules() + vi.stubGlobal( + 'window', + buildWindowApi({ + getSnapshot, + onSet: () => () => {} + }) + ) + + const { useIpcEvents } = await import('./useIpcEvents') + + useIpcEvents() + await Promise.resolve() + + resolveSnapshot([ + { + paneKey: FUTURE_PANE_KEY, + tabId: 'tab-future', + worktreeId: 'wt-1', + connectionId: 'ssh-1', + state: 'done', + prompt: 'remote completion', + agentType: 'codex', + lastAssistantMessage: 'queued completion', + terminalHandle: 'term-future', + receivedAt: 1_700_000_000_000, + stateStartedAt: 1_699_999_999_000 + } + ]) + await Promise.resolve() + await Promise.resolve() + + expect(setAgentStatus).not.toHaveBeenCalled() + + Object.assign(storeState, { + tabsByWorktree: { + 'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'SSH Tab' }] + }, + terminalLayoutsByTabId: { + 'tab-future': { + root: { type: 'leaf', leafId: FUTURE_LEAF_ID }, + activeLeafId: FUTURE_LEAF_ID, + expandedLeafId: null + } + } + }) + subscribeListenerRef.current?.(storeState, storeState) + + expect(setAgentStatus).toHaveBeenCalledWith( + FUTURE_PANE_KEY, + expect.objectContaining({ + state: 'done', + prompt: 'remote completion', + agentType: 'codex', + lastAssistantMessage: 'queued completion' + }), + 'SSH Tab', + { updatedAt: 1_700_000_000_000, stateStartedAt: 1_699_999_999_000 }, + expectWorktreeRouting('wt-1'), + undefined + ) + expect(observeAgentHookCompletionForNotification).not.toHaveBeenCalled() + }) + + it('drops replayed startup snapshots after hydration when connection ownership mismatches', async () => { + const setAgentStatus = vi.fn() + const subscribeListenerRef: { current: StoreSubscribeListener | null } = { current: null } + let resolveSnapshot!: (entries: AgentStatusSetData[]) => void + const getSnapshot = vi.fn( + () => + new Promise((resolve) => { + resolveSnapshot = resolve + }) + ) + + const storeState: StoreLike = buildStoreState({ + setAgentStatus, + workspaceSessionReady: true, + repos: [{ id: 'repo-1', connectionId: 'conn-actual' }], + worktreesByRepo: { 'repo-1': [{ id: 'wt-1', repoId: 'repo-1' }] }, + tabsByWorktree: {}, + terminalLayoutsByTabId: {} + }) + + stubReactSyncEffect() + vi.doMock('../store', () => ({ + useAppStore: { + subscribe: vi.fn((listener: StoreSubscribeListener) => { + subscribeListenerRef.current = listener + return () => { + subscribeListenerRef.current = null + } + }), + getState: () => storeState + } + })) + stubAuxiliaryModules() + vi.stubGlobal( + 'window', + buildWindowApi({ + getSnapshot, + onSet: () => () => {} + }) + ) + + const { useIpcEvents } = await import('./useIpcEvents') + + useIpcEvents() + await Promise.resolve() + + resolveSnapshot([ + { + paneKey: FUTURE_PANE_KEY, + tabId: 'tab-future', + worktreeId: 'wt-1', + connectionId: 'ssh-stale', + state: 'done', + prompt: 'remote completion', + agentType: 'codex', + terminalHandle: 'term-future', + receivedAt: 1_700_000_000_000, + stateStartedAt: 1_699_999_999_000 + } + ]) + await Promise.resolve() + await Promise.resolve() + + expect(setAgentStatus).not.toHaveBeenCalled() + + Object.assign(storeState, { + tabsByWorktree: { + 'wt-1': [{ id: 'tab-future', ptyId: 'pty-1', worktreeId: 'wt-1', title: 'SSH Tab' }] + }, + terminalLayoutsByTabId: { + 'tab-future': { + root: { type: 'leaf', leafId: FUTURE_LEAF_ID }, + activeLeafId: FUTURE_LEAF_ID, + expandedLeafId: null + } + } + }) + subscribeListenerRef.current?.(storeState, storeState) + + expect(setAgentStatus).not.toHaveBeenCalled() + }) + it('accepts WSL-relayed status events for a local repo (wsl:* is transport provenance, not ownership)', async () => { const setAgentStatus = vi.fn() const onSetListenerRef: { current: ((data: AgentStatusSetData) => void) | null } = { diff --git a/src/renderer/src/hooks/useIpcEvents.ts b/src/renderer/src/hooks/useIpcEvents.ts index b31d4068e..9b6439e59 100644 --- a/src/renderer/src/hooks/useIpcEvents.ts +++ b/src/renderer/src/hooks/useIpcEvents.ts @@ -844,6 +844,7 @@ export function useIpcEvents(): void { type PendingAgentStatusEvent = { data: AgentStatusIpcPayload firstSeenAt: number + replay: boolean } type AgentStatusApplyResult = 'applied' | 'pending' | 'dropped' const pendingAgentStatusEvents: PendingAgentStatusEvent[] = [] @@ -2921,8 +2922,15 @@ export function useIpcEvents(): void { }, PENDING_AGENT_STATUS_RETRY_MS) } - function enqueuePendingAgentStatus(data: AgentStatusIpcPayload): void { - pendingAgentStatusEvents.push({ data, firstSeenAt: Date.now() }) + function enqueuePendingAgentStatus( + data: AgentStatusIpcPayload, + options?: { replay?: boolean } + ): void { + pendingAgentStatusEvents.push({ + data, + firstSeenAt: Date.now(), + replay: options?.replay === true + }) while (pendingAgentStatusEvents.length > MAX_PENDING_AGENT_STATUS_EVENTS) { pendingAgentStatusEvents.shift() } @@ -2945,7 +2953,7 @@ export function useIpcEvents(): void { if (now - event.firstSeenAt > PENDING_AGENT_STATUS_TTL_MS) { continue } - const result = applyAgentStatus(event.data, { retry: true }) + const result = applyAgentStatus(event.data, { retry: true, replay: event.replay }) if (result === 'pending') { remaining.push(event) } @@ -3012,17 +3020,27 @@ export function useIpcEvents(): void { } } if (!exists) { - // Why: a non-empty paneKey with no matching tab is a routing failure to track. - // Skip during replay — main's durable cache legitimately holds closed-tab entries. - if (options?.replay !== true) { - if (options?.retry !== true) { - track('agent_hook_unattributed', { reason: 'unknown_tab_id' }) - // Why: live hook IPC can beat tab/layout hydration; retry so a transient pane-key miss doesn't drop completion state. - enqueuePendingAgentStatus(data) + // Why: startup snapshot replay can beat tab/layout hydration too. + // Reuse the same bounded retry queue when the row still carries + // runtime-backed worktree provenance so the cached status can adopt + // once the pane becomes visible. + if (options?.replay === true) { + if (data.worktreeId && hasRuntimeBackedWorktreeAttribution(data)) { + if (options?.retry !== true) { + enqueuePendingAgentStatus(data, { replay: true }) + } + return 'pending' } - return 'pending' + return 'dropped' } - return 'dropped' + if (options?.retry !== true) { + // Why: empty paneKeys are dropped in main before IPC fanout. Reaching + // this branch means a non-empty paneKey escaped without a matching + // renderer tab, so track the adoption/routing failure separately. + track('agent_hook_unattributed', { reason: 'unknown_tab_id' }) + enqueuePendingAgentStatus(data) + } + return 'pending' } if (options?.replay !== true && options?.retry !== true) { for (let index = pendingAgentStatusEvents.length - 1; index >= 0; index -= 1) {