diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx index 89cb1f1a74..f562f1b265 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.history-restore.test.tsx @@ -14,20 +14,25 @@ const fixture = vi.hoisted(() => ({ restore: vi.fn(), restoreTail: vi.fn(), loadTurnWindow: vi.fn(), + synchronize: vi.fn(), + extend: vi.fn(), present: null as ((sessionId: string, presentation: SessionHistoryPresentation) => void) | null, })); vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: { getState: () => ({ activeSessionId: fixture.session?.sessionId, sessions: new Map(fixture.session ? [[fixture.session.sessionId, fixture.session]] : []) }), retainSessionHistory: () => () => {}, subscribeSelector: () => () => {}, - getSessionHistoryViewState: () => undefined, + getSessionHistoryViewState: () => ({ + catalog: fixture.session?.turnCatalog ?? null, loadedRanges: [], activeRange: fixture.cached?.range ?? null, + }), + synchronizeSessionHistory: (...args: unknown[]) => fixture.synchronize(...args), reactivateSessionHistoryWindow: () => fixture.cached, restoreSessionHistoryWindow: (...args: unknown[]) => fixture.restore(...args), restoreSessionTailPresentation: (...args: unknown[]) => fixture.restoreTail(...args), hasPendingSessionHistoryCompletion: () => false, hasDeferredSessionHistoryProjection: () => false, releaseSessionHistoryCompletionAfterInitialPaint: () => false, - extendSessionHistoryWindow: () => null, + extendSessionHistoryWindow: (...args: unknown[]) => fixture.extend(...args), loadSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args), loadPreviousSessionTurnWindow: (...args: unknown[]) => fixture.loadTurnWindow(...args), activateSessionHistoryWindow: () => fixture.cached, @@ -45,6 +50,7 @@ vi.mock('./VirtualMessageList', () => ({ VirtualMessageList: React.forwardRef((p fixture.listProps = props; React.useImperativeHandle(ref, () => ({ scrollToTurnEnd: () => true, + scrollToLatestEndPosition: () => {}, captureViewportSnapshot: () => null, clearSearchMatch: () => {}, prepareTurnNavigation: () => 'pending', @@ -103,6 +109,14 @@ function session(totalTurnCount = 8, historyState: Session['historyState'] = 're }], } as Session; } +function sessionWithCatalog(count: number, revision: string): Session { + return { ...session(count), turnCatalog: { + schemaVersion: 1, sessionId: 'session-a', revision, totalTurnCount: count, + complete: true, entries: Array.from({ length: count }, (_, ordinal) => ({ + ordinal, storageTurnIndex: ordinal, turnId: `turn-${ordinal}`, previewTruncated: false, + })), + } }; +} function presentation(startOrdinal = 4, endOrdinalExclusive = 8): SessionHistoryPresentation { return { range: { startOrdinal, endOrdinalExclusive, targetTurnId: `turn-${startOrdinal}`, mode: 'history-window' }, @@ -151,6 +165,8 @@ describe('FlowChat reader restoration across history rewrites', () => { fixture.session = session(); fixture.cached = presentation(); fixture.restore.mockResolvedValue(null); + fixture.extend.mockReturnValue(null); + fixture.synchronize.mockResolvedValue(undefined); fixture.listProps = null; fixture.viewportSettled = true; fixture.present = null; @@ -223,6 +239,109 @@ describe('FlowChat reader restoration across history rewrites', () => { expect(host.querySelector('[data-turn-id="turn-2"]')).not.toBeNull(); }); + it.each([['local', 8], ['local', 9], ['ssh', 8], ['ssh', 9], ['peer-device', 8], ['peer-device', 9]] as const)( + 'reacquires the reader window when the %s catalog changes after a turn (total: %d)', async (location, count) => { + if (location === 'peer-device') activateSurface('peer-device'); + const withCatalog = (total: number, revision: string): Session => ({ + ...sessionWithCatalog(total, revision), + ...(location === 'ssh' ? { remoteConnectionId: 'ssh-target', remoteSshHost: 'build-host' } : {}), + }); + fixture.session = withCatalog(8, 'before-turn'); + const window = presentation(3, 7); + fixture.cached = window; + stageBookmark(window); + await render(); + expectPresented(); + // Authoritative completion changes the catalog and invalidates the + // store's cached windows, without changing Session id or ready status. + fixture.cached = null; + const first = deferred(); + fixture.restore.mockReturnValueOnce(first.promise); + fixture.session = withCatalog(count, 'after-turn'); + await render(); + expect(fixture.restore).toHaveBeenCalledWith('session-a', window.range, expect.any(Function)); + const firstOwner = fixture.restore.mock.calls[0][2] as () => boolean; + const second = deferred(); + fixture.restore.mockReturnValueOnce(second.promise); + fixture.session = withCatalog(count, 'corrected-turn'); + await render(); + expect(fixture.restore).toHaveBeenCalledTimes(2); + expect(firstOwner()).toBe(false); + await act(async () => first.reject(new Error('Retired history read failed'))); + await act(async () => second.resolve(window)); + expectPresented(); + expect(messages().dataset.presentationMode).toBe('history-window'); + expect(host.querySelector('[data-turn-id="turn-3"]')).not.toBeNull(); + }, + ); + + it('drops a retained live-tail history projection when its catalog changes', async () => { + fixture.session = sessionWithCatalog(8, 'before-turn'); + fixture.cached = presentation(0, 8); + stageBookmark(fixture.cached); + await render(); + await act(async () => { fixture.listProps!.onRequestJumpToLatest!(); }); + expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull(); + fixture.cached = null; + fixture.session = sessionWithCatalog(8, 'after-turn'); + await render(); + expectPresented(); + expect(messages().dataset.presentationMode).toBe('tail'); + expect(host.querySelector('[data-turn-id="turn-0"]')).toBeNull(); + expect(fixture.restore).not.toHaveBeenCalled(); + }); + + it.each([false, true])('retries an orphaned reader after a failed read (explicit sync: %s)', async synchronizeHistory => { + const window = presentation(3, 7); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.cached = null; + fixture.restore.mockImplementation(async () => { + fixture.cached = window; + return window; + }); + fixture.restore.mockRejectedValueOnce(new Error('History read timed out')); + fixture.loadTurnWindow.mockResolvedValue({ status: 'ready', isCurrent: true }); + fixture.extend.mockImplementation(() => fixture.cached ? presentation(0, 7) : null); + let failed: unknown; + await act(async () => { + failed = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { synchronizeHistory }); + }); + expect(failed).toBe('not-ready'); + expect(fixture.loadTurnWindow).not.toHaveBeenCalled(); + expect(host.querySelector('[data-turn-id="turn-3"]')).not.toBeNull(); + let outcome: unknown; + await act(async () => { + outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { synchronizeHistory }); + }); + expect(outcome).toBe('applied'); + expect(fixture.restore).toHaveBeenCalledWith('session-a', window.range, expect.any(Function)); + expect(fixture.restore).toHaveBeenCalledTimes(2); + expect(fixture.synchronize).toHaveBeenCalledTimes(synchronizeHistory ? 2 : 0); + expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull(); + }); + + it('rejects a late orphan recovery after changing devices', async () => { + const window = presentation(3, 7); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.cached = null; + const read = deferred(); + fixture.restore.mockReturnValueOnce(read.promise); + let outcome!: Promise; + await act(async () => { + outcome = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { synchronizeHistory: true }); + }); + expect(fixture.restore).toHaveBeenCalledTimes(1); + activateSurface('peer-device'); + await act(async () => { read.resolve(window); await outcome; }); + expect(await outcome).toBe('cancelled'); + expect(fixture.loadTurnWindow).not.toHaveBeenCalled(); + expect(fixture.extend).not.toHaveBeenCalled(); + }); + it('cancels a pending cold range when a ready history rewrite removes it', async () => { fixture.cached = null; stageBookmark(); diff --git a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx index 0a8fe7d40c..4032e08f98 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx @@ -777,7 +777,8 @@ export const ModernFlowChatContainer: React.FC = ( useLayoutEffect(() => { const sessionId = activeSession?.sessionId; const previousSessionId = activeSessionIdRef.current; - if (previousSessionId && previousSessionId !== sessionId) { + if (previousSessionId && (previousSessionId !== sessionId + || historyPresentationRef.current?.sessionId === previousSessionId)) { rememberSessionViewportState(previousSessionId, { historyPresentation: historyPresentationRef.current?.sessionId === previousSessionId ? historyPresentationRef.current @@ -851,6 +852,28 @@ export const ModernFlowChatContainer: React.FC = ( } }, [activeSession?.sessionId, activeSession?.historyState, isRememberedHistoryRangeInvalid, invalidateHistoryPresentationOwner, rememberSessionViewportState, updateViewportIntent, restoreRevision, historyRestoreRetry, surfaceScope]); + const readerCatalogRef = useRef<{ sessionId: string | undefined; revision: string | undefined } | null>(null); + useEffect(() => { + const sessionId = activeSession?.sessionId; + const revision = activeSession?.turnCatalog?.revision; + const previous = readerCatalogRef.current; + readerCatalogRef.current = { sessionId, revision }; + if (!sessionId || previous?.sessionId !== sessionId || previous.revision === revision) return; + const intent = viewportIntentRef.current; + if (intent?.kind !== 'turn' || intent.sessionId !== sessionId || intent.source !== 'history-range') { + if (historyPresentationRef.current?.sessionId === sessionId) { + switchToLiveTailForSession(sessionId, { discardRecentHistory: true }); + } + return; + } + // The store invalidates cached ranges when the authoritative catalog + // changes. Retire the view's matching owner too, then reload its bookmark + // through the normal history path. Keeping only the rendered copy leaves + // every later extend/synchronize pointed at a window the store no longer owns. + invalidateHistoryPresentationOwner(); + setHistoryRestoreRetry(retry => retry + 1); + }, [activeSession?.sessionId, activeSession?.turnCatalog?.revision, invalidateHistoryPresentationOwner, switchToLiveTailForSession]); + useEffect(() => { const retainedSessionId = continuousProjectionSessionId; if (!retainedSessionId) { @@ -1991,6 +2014,27 @@ export const ModernFlowChatContainer: React.FC = ( return 'not-ready'; } } + // A catalog refresh or cache eviction can retire the store's window + // while the reader still displays its copy. Reacquire that exact range + // before extending it; repeatedly fetching the adjacent page cannot + // restore a missing active window, even after an explicit source sync. + const activeRange = flowChatStore.getSessionHistoryViewState(sessionId)?.activeRange; + if (presentation && (!activeRange + || activeRange.startOrdinal !== presentation.range.startOrdinal + || activeRange.endOrdinalExclusive !== presentation.range.endOrdinalExclusive)) { + setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' })); + try { + const restored = await flowChatStore.restoreSessionHistoryWindow(sessionId, presentation.range, isCurrent); + if (!isCurrent()) return 'cancelled'; + if (!restored) throw new Error('The reader history range is no longer available'); + } catch (error) { + if (!isCurrent() || isSurfaceChangedError(error)) return 'cancelled'; + recordHistoryPagingEvent(sessionId, 'outcome_not_ready', { direction, reason: 'reader-range-restore-failed' }); + log.warn('Failed to reacquire reader history range', { sessionId, direction, error }); + setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'error' })); + return 'not-ready'; + } + } const session = flowChatStore.getState().sessions.get(sessionId); if (scope.surfaceId !== 'local' && !presentation) { if (direction === 'after' || session?.isPartial === false) { @@ -2197,6 +2241,10 @@ export const ModernFlowChatContainer: React.FC = ( direction, reason: `load-${result.status}`, targetOrdinal, + surfaceId: scope.surfaceId, + remoteWorkspace: Boolean(session?.remoteConnectionId || session?.remoteSshHost), + requestedCatalogRevision: session?.turnCatalog?.revision ?? null, + currentCatalogRevision: flowChatStore.getSessionHistoryViewState(sessionId)?.catalog?.revision ?? null, }); setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'error' })); return 'not-ready'; @@ -2247,6 +2295,7 @@ export const ModernFlowChatContainer: React.FC = ( ? flowChatStore.extendSessionHistoryWindow(sessionId, direction) : flowChatStore.activateSessionHistoryWindowFromTail(sessionId, targetOrdinal); if (!nextPresentation) { + const currentHistoryView = flowChatStore.getSessionHistoryViewState(sessionId); if (viewportPreparationStarted) { options?.cancelViewportPresentationCommit?.(); } @@ -2254,6 +2303,13 @@ export const ModernFlowChatContainer: React.FC = ( direction, reason: 'no-next-presentation', targetOrdinal, + surfaceId: scope.surfaceId, + remoteWorkspace: Boolean(session?.remoteConnectionId || session?.remoteSshHost), + currentCatalogRevision: currentHistoryView?.catalog?.revision ?? null, + renderedStartOrdinal: renderedRange.startOrdinal, + renderedEndOrdinalExclusive: renderedRange.endOrdinalExclusive, + activeStartOrdinal: currentHistoryView?.activeRange?.startOrdinal ?? null, + activeEndOrdinalExclusive: currentHistoryView?.activeRange?.endOrdinalExclusive ?? null, }); setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'error' })); return 'not-ready'; diff --git a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx index 46a4f2181e..5ef2dbf106 100644 --- a/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/UserMessageItem.test.tsx @@ -150,6 +150,7 @@ const flowChatStoreMock = vi.hoisted(() => ({ activeSessionId: null, })), loadSessionHistory: vi.fn(async () => undefined), + subscribeSelector: vi.fn(() => () => {}), })); vi.mock('../../store/FlowChatStore', () => ({ diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts index 945f2b386a..72f63a6499 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.test.ts @@ -123,6 +123,37 @@ describe('external BTW turn projection', () => { }); }); +describe('late dialog start events', () => { + beforeEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); + afterEach(() => { resetFlowChatStore(); stateMachineManager.clear(); }); + + it.each(['completed', 'cancelled', 'error'] as const)( + 'does not restart a turn already projected as %s', status => { + createSessionWithTurn({ ...createFinishingTurn(), status }); + stateMachineManager.getOrCreate('session-1'); + __test_only__.handleDialogTurnStarted(createFlowChatContext(), { + sessionId: 'session-1', turnId: 'turn-1', turnIndex: 0, userInput: 'Delayed start', + }); + expect(stateMachineManager.getCurrentState('session-1')).toBe(SessionExecutionState.IDLE); + expect(FlowChatStore.getInstance().getState().sessions.get('session-1')?.dialogTurns[0].status).toBe(status); + }, + ); + + it('does not let an older admitted turn take ownership from the current turn', async () => { + createSessionWithTurn({ ...createFinishingTurn(), status: 'processing', backendTurnIndex: 1 }); + FlowChatStore.getInstance().addDialogTurn('session-1', { + ...createFinishingTurn(), id: 'turn-2', status: 'processing', backendTurnIndex: 2, + }); + await stateMachineManager.transition('session-1', SessionExecutionEvent.START, { + taskId: 'session-1', dialogTurnId: 'turn-2', + }); + __test_only__.handleDialogTurnStarted(createFlowChatContext(), { + sessionId: 'session-1', turnId: 'turn-1', turnIndex: 1, userInput: 'Delayed start', + }); + expect(stateMachineManager.get('session-1')?.getContext().currentDialogTurnId).toBe('turn-2'); + }); +}); + describe('Claw bootstrap cancellation', () => { beforeEach(() => { resetFlowChatStore(); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts index a36d602621..bc93cedfd1 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/EventHandlerModule.ts @@ -1896,12 +1896,25 @@ function handleDialogTurnStarted(context: FlowChatContext, event: any): void { return; } + // Canonical history and direct control events travel independently. A delayed + // start must not resurrect a settled turn or supersede a newer admitted turn. + // Optimistic queued turns have no backend index and do not block admission. + const store = FlowChatStore.getInstance(); + const knownTurns = store.getState().sessions.get(sessionId)?.dialogTurns ?? []; + const knownTurn = knownTurns.find(turn => turn.id === turnId); + const admittedIndex = typeof turnIndex === 'number' + ? turnIndex : knownTurn?.backendTurnIndex ?? knownTurn?.storageTurnIndex; + if (knownTurn && ['completed', 'cancelled', 'error'].includes(knownTurn.status) + || admittedIndex !== undefined && knownTurns.some(turn => + (turn.backendTurnIndex ?? turn.storageTurnIndex ?? -1) > admittedIndex)) { + log.debug('Dropped stale DialogTurnStarted', { sessionId, turnId, admittedIndex }); + return; + } + clearPromptSuggestion(sessionId); finalizePendingTurnCompletionNow(context, sessionId); clearPendingTurnCompletion(context, sessionId, turnId); - const store = FlowChatStore.getInstance(); - // Clean up temp image analysis turn if one exists for this session const tempTurnId = pendingImageAnalysisTurns.get(sessionId); const hadTempTurn = !!tempTurnId; diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts index 0dfd780189..c7c0486623 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.test.ts @@ -24,7 +24,7 @@ import { activateSurface, } from '@/infrastructure/peer-device/deviceSurface'; -import { beginRuntimeSessionAttachment } from '@/infrastructure/peer-device/runtimeSessionEventGate'; +import { beginRuntimeSessionAttachment, markRuntimeSessionProjectionStale } from '@/infrastructure/peer-device/runtimeSessionEventGate'; const mockSubscribeGlobal = vi.fn(); const mockTransition = vi.fn(); @@ -142,10 +142,13 @@ vi.mock('./SessionModule', () => ({ vi.mock('./PendingQueueModule', () => ({ pendingQueueManager: { list: (...args: unknown[]) => mockPendingList(...args), + subscribe: vi.fn(() => () => {}), enqueue: (...args: unknown[]) => mockPendingEnqueue(...args), enqueueForSurface: (...args: unknown[]) => mockPendingEnqueueForSurface(...args), setStatus: (...args: unknown[]) => mockPendingSetStatus(...args), remove: (...args: unknown[]) => mockPendingRemove(...args), + removeForSurface: (_surface: string, ...args: unknown[]) => mockPendingRemove(...args), + setStatusForSurface: (_surface: string, ...args: unknown[]) => mockPendingSetStatus(...args), }, })); @@ -250,6 +253,33 @@ describe('MessageModule session writer conflict', () => { .mockReturnValue('notification-3'); }); + it('drains an older peer queue from canonical completion even when direct events have a gap', async () => { + mockEnsureBackendSession.mockResolvedValue(undefined); + activateSurface('peer-queue-recovery'); + const { session, context } = conflictContext('peer-queue-recovery-session'); + Object.assign(session, { historyState: 'ready' }); + session.dialogTurns.push({ id: 'finished', status: 'cancelled', modelRounds: [], userMessage: { content: 'Previous' } }); + context.userCancelledSessionIds = new Set([session.sessionId]); + mockPendingList.mockReturnValue([{ id: 'next', sessionId: session.sessionId, content: 'Continue', status: 'queued', retryCount: 0 }]); + markRuntimeSessionProjectionStale('peer-queue-recovery', session.sessionId); + try { + await drainPendingQueue(context, session.sessionId); + expect(mockStartDialogTurn).toHaveBeenCalledTimes(1); + expect(context.userCancelledSessionIds.has(session.sessionId)).toBe(false); + } finally { activateSurface(LOCAL_SURFACE_ID); } + }); + + it('does not start a second queued message while the head is still being submitted', async () => { + const { session, context } = conflictContext('queue-submitting'); + context.userCancelledSessionIds = new Set(); + mockPendingList.mockReturnValue([ + { id: 'first', sessionId: session.sessionId, content: 'First', status: 'sending', retryCount: 0 }, + { id: 'next', sessionId: session.sessionId, content: 'Next', status: 'queued', retryCount: 0 }, + ]); + await drainPendingQueue(context, session.sessionId); + expect(mockStartDialogTurn).not.toHaveBeenCalled(); + }); + it.each([false, true])('preserves the plan build turn ID while busy, host queue=%s', async hostQueue => { const { context, session } = conflictContext('plan-build'); mockGetCurrentState.mockReturnValue('processing'); @@ -805,6 +835,7 @@ describe('MessageModule cancellation', () => { mockPendingSetStatus.mockImplementation((_session, _id, status) => { pending.status = status; }); const context: any = { flowChatStore: { + subscribeSelector: vi.fn(), getSurfaceGeneration: () => 0, getState: () => ({ sessions: new Map([[session.sessionId, session]]) }), addDialogTurn: vi.fn((_sessionId: string, turn: any) => session.dialogTurns.push(turn)), @@ -844,6 +875,25 @@ describe('MessageModule cancellation', () => { activateSurface('peer-other'); await Promise.resolve(); expect(mockStartDialogTurn).toHaveBeenCalledTimes(1); + activateSurface('peer-history-recovery'); + session.dialogTurns = []; + session.historyState = 'failed'; + onIdle(session.sessionId, { currentState: 'idle' }); + await Promise.resolve(); + expect(mockStartDialogTurn).toHaveBeenCalledTimes(1); + const [selectReady, onReady] = context.flowChatStore.subscribeSelector.mock.calls[0]; + expect(selectReady(context.flowChatStore.getState())).toEqual([]); + session.historyState = 'ready'; + onReady(selectReady(context.flowChatStore.getState())); + await vi.waitFor(() => expect(mockStartDialogTurn).toHaveBeenCalledTimes(2)); + + // Clearing a failed predecessor while already idle must also wake FIFO. + pending.status = 'queued'; + session.dialogTurns = []; + const { pendingQueueManager } = await import('./PendingQueueModule'); + const onQueueChange = vi.mocked(pendingQueueManager.subscribe).mock.calls.at(-1)![0]; + onQueueChange(session.sessionId, []); + await vi.waitFor(() => expect(mockStartDialogTurn).toHaveBeenCalledTimes(3)); activateSurface(LOCAL_SURFACE_ID); }); @@ -1574,7 +1624,7 @@ describe('MessageModule device surface switch', () => { expect(mockNotificationError).not.toHaveBeenCalled(); }); - it('does not re-queue when startDialogTurn was sent and the invoke then fails after a switch', async () => { + it('preserves an uncertain legacy submission for manual recovery after a device switch', async () => { const { context, switchSurface } = switchingContext('session-accepted'); mockStartDialogTurn.mockImplementation(async () => { switchSurface(); @@ -1584,11 +1634,32 @@ describe('MessageModule device surface switch', () => { await sendMessage(context, 'already running', 'session-accepted'); expect(mockStartDialogTurn).toHaveBeenCalledTimes(1); - expect(mockPendingEnqueueForSurface).not.toHaveBeenCalled(); + expect(mockPendingEnqueueForSurface).toHaveBeenCalledWith('local', expect.objectContaining({ + sessionId: 'session-accepted', content: 'already running', initialStatus: 'failed', retryCount: 1, + turnId: expect.any(String), + })); expect(context.flowChatStore.abandonOptimisticDialogTurn).not.toHaveBeenCalled(); expect(mockNotificationError).not.toHaveBeenCalled(); }); + it.each([false, true])('retains the original queue item and order after switching, submitted=%s', async submitted => { + const { context, switchSurface } = switchingContext('session-queue-switch', { switchAfterTransition: !submitted }); + context.userCancelledSessionIds = new Set(); + if (submitted) mockStartDialogTurn.mockImplementation(async () => { + switchSurface(); + throw new Error('Reply lost after submission'); + }); + const pending = { id: 'original-item', turnId: 'original-turn', sessionId: 'session-queue-switch', + content: 'Keep order', status: 'queued', retryCount: 0 }; + mockPendingList.mockReturnValue([pending]); + mockPendingSetStatus.mockImplementation((_session, _id, status) => { pending.status = status; }); + await drainPendingQueue(context, pending.sessionId); + expect(pending.status).toBe(submitted ? 'failed' : 'queued'); + expect(mockPendingRemove).not.toHaveBeenCalled(); + expect(mockPendingEnqueueForSurface).not.toHaveBeenCalled(); + expect(mockNotificationError).not.toHaveBeenCalled(); + }); + it('still reports ordinary failures when the surface did not change', async () => { const { context } = switchingContext('session-normal'); mockStartDialogTurn.mockRejectedValue(new Error('backend exploded')); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts index d49e856f2b..ef89a83d9c 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/MessageModule.ts @@ -14,6 +14,7 @@ import { createLogger } from '@/shared/utils/logger'; import { getActiveSurfaceId, getActiveSurfaceScope, + isLocalSurface, isSurfaceChangedError, type DeviceSurfaceId, } from '@/infrastructure/peer-device/deviceSurface'; @@ -122,6 +123,13 @@ export function inFlightSubmissionCount(): number { return inFlightSubmissions; } +/** The retained queue item owns recovery after its device stops being rendered. */ +class RetiredQueueSubmission extends Error { + constructor(readonly outcomeUnknown: boolean) { + super('Queued submission outlived its device surface'); + } +} + /** * Salvage a submission that lost the race against a device-surface switch. * @@ -142,15 +150,18 @@ function recoverSubmissionAfterSurfaceSwitch( options?: SendMessageOptions; }, ): void { - const hostHasTurn = - turnTracker.hostAcceptedTurn || turnTracker.hostSubmitStarted === true; - if (hostHasTurn) { + if (turnTracker.hostAcceptedTurn) { log.info('Device surface switched after the host accepted the turn; it keeps running there', { sessionId, }); return; } - if (turnTracker.createdLocalTurnId) { + const outcomeUnknown = turnTracker.hostSubmitStarted === true; + // Host-queue submissions have their own durable outbox and no frontend + // optimistic turn. Leave recovery with that owner. Legacy submissions need + // a retained draft, but an ambiguous receipt must never auto-resubmit it. + if (outcomeUnknown && !turnTracker.createdLocalTurnId) return; + if (turnTracker.createdLocalTurnId && !outcomeUnknown) { context.flowChatStore.abandonOptimisticDialogTurn( surfaceId, sessionId, @@ -159,9 +170,15 @@ function recoverSubmissionAfterSurfaceSwitch( stateMachineManager.resetForSurface(surfaceId, sessionId); context.processingManager.clearSessionStatusForSurface(surfaceId, sessionId); } + // A drain still owns its original item and FIFO position. Do not create a + // second entry and then remove the first one after returning to its caller. + if (draft.options?.bypassPendingQueue) return; try { pendingQueueManager.enqueueForSurface(surfaceId, { sessionId, + turnId: turnTracker.createdLocalTurnId ?? draft.options?.turnId, + initialStatus: outcomeUnknown ? 'failed' : 'queued', + retryCount: outcomeUnknown ? 1 : 0, content: draft.message, displayMessage: draft.displayMessage, agentType: draft.agentType, @@ -170,8 +187,8 @@ function recoverSubmissionAfterSurfaceSwitch( composerDraft: draft.options?.pendingQueueDraft, userMessageMetadata: draft.options?.userMessageMetadata, }); - log.info('Device surface switched before submit reached the host; message re-queued', { - sessionId, + log.info('Retained a message after its device surface changed', { + sessionId, outcomeUnknown, }); } catch (error) { // A full queue is the only expected failure, and dropping the message @@ -603,6 +620,9 @@ async function sendMessageInternal( if (latestSendBySession.get(sendCoordinationKey) === sendAttempt) { latestSendBySession.delete(sendCoordinationKey); } + if (options?.bypassPendingQueue && !turnTracker.hostAcceptedTurn) { + throw new RetiredQueueSubmission(turnTracker.hostSubmitStarted === true); + } return; } @@ -735,8 +755,15 @@ export async function drainPendingQueue( ): Promise { if (isBtwSessionClosing(sessionId)) return; if (hostQueueSupported(sessionId) && !options?.allowInterruptedRecoveryAbandon) return; - if (isRuntimeSessionAttachmentInFlight(getActiveSurfaceId(), sessionId) || - isRuntimeSessionProjectionStale(getActiveSurfaceId(), sessionId)) { + const scope = getActiveSurfaceScope(); + const session = context.flowChatStore.getState().sessions.get(sessionId); + // Peer content/terminal facts are owned by the canonical subscriber, not + // the independent direct-event cursor repaired by local Runtime attach. + const peerReady = !isLocalSurface(scope.surfaceId) && session?.historyState === 'ready'; + if (isLocalSurface(scope.surfaceId) + ? isRuntimeSessionAttachmentInFlight(scope.surfaceId, sessionId) + || isRuntimeSessionProjectionStale(scope.surfaceId, sessionId) + : !peerReady) { return; } const machineState = stateMachineManager.getCurrentState(sessionId); @@ -750,10 +777,14 @@ export async function drainPendingQueue( return; } if (context.userCancelledSessionIds.has(sessionId)) { - log.debug('Pending queue held until cancellation outcome is authoritative', { sessionId }); - return; + const latest = session?.dialogTurns.at(-1); + if (peerReady && latest && ['completed', 'cancelled', 'error'].includes(latest.status)) { + context.userCancelledSessionIds.delete(sessionId); + } else { + log.debug('Pending queue held until cancellation outcome is authoritative', { sessionId }); + return; + } } - const session = context.flowChatStore.getState().sessions.get(sessionId); if ( hasInterruptedTurnHoldingQueue(session) && !options?.allowInterruptedRecoveryAbandon @@ -766,6 +797,7 @@ export async function drainPendingQueue( // skipped here — the user must explicitly act on them to avoid re-entering // the same failure mode automatically. const allItems = pendingQueueManager.list(sessionId); + if (allItems.some(item => item.status === 'sending' || item.status === 'sending_now')) return; const next = allItems.find( (item) => (item.retryCount ?? 0) === 0 && item.status === 'queued', ); @@ -816,12 +848,17 @@ export async function drainPendingQueue( // Only remove the item AFTER sendMessage completes successfully so we keep // the original id / timestamp / retryCount on failure (no UI flicker, no // reset of the retry counter, and FIFO order is preserved). - pendingQueueManager.remove(sessionId, next.id); + pendingQueueManager.removeForSurface(scope.surfaceId, sessionId, next.id); } catch (error) { + if (error instanceof RetiredQueueSubmission) { + pendingQueueManager.setStatusForSurface(scope.surfaceId, sessionId, next.id, + error.outcomeUnknown ? 'failed' : 'queued'); + return; + } log.error('Failed to drain pending queue item', { sessionId, itemId: next.id, error }); // Mark in place. The auto-drain listener skips `failed` items so the user // can edit / send-now / delete without entering a tight retry loop. - pendingQueueManager.setStatus(sessionId, next.id, 'failed'); + pendingQueueManager.setStatusForSurface(scope.surfaceId, sessionId, next.id, 'failed'); } } @@ -857,4 +894,14 @@ export function installPendingQueueDrainListener(context: FlowChatContext): void subscribeRuntimeSessionAttachmentFinished((surfaceId, sessionId) => { if (surfaceId === getActiveSurfaceId()) schedulePendingQueueDrain(sessionId); }); + pendingQueueManager.subscribe(sessionId => schedulePendingQueueDrain(sessionId)); + // Recovery can confirm an already-idle session without another state-machine + // transition. Wake its queue when history becomes trustworthy again. + context.flowChatStore.subscribeSelector( + state => isLocalSurface(getActiveSurfaceId()) ? [] : [...state.sessions.values()] + .filter(session => session.historyState === 'ready' && pendingQueueManager.list(session.sessionId).length > 0) + .map(session => session.sessionId), + sessionIds => sessionIds.forEach(schedulePendingQueueDrain), + { isEqual: (a, b) => a.length === b.length && a.every((id, index) => id === b[index]) }, + ); } diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts index 2c303d5178..9125944fde 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.test.ts @@ -202,3 +202,23 @@ it('persists reordered payloads and refuses to move a queue during an active sen pendingQueueManager.setStatus(sessionId, second.id, 'sending'); expect(pendingQueueManager.reorder(sessionId, first.id, second.id)).toBe(false); }); + + +it('settles a pending send on its original device after the controller switches', () => { + const sessionId = testSession(); + const item = pendingQueueManager.enqueue({ sessionId, content: 'Original device' }); + pendingQueueManager.setStatus(sessionId, item.id, 'sending'); + activateSurface('peer-queue-other'); + const other = pendingQueueManager.enqueue({ sessionId, content: 'Other device' }); + const listener = vi.fn(); + const unsubscribe = pendingQueueManager.subscribe(listener); + try { + pendingQueueManager.setStatusForSurface(LOCAL_SURFACE_ID, sessionId, item.id, 'failed'); + expect(pendingQueueManager.list(sessionId)).toEqual([other]); + expect(pendingQueueManager.listForSurface(LOCAL_SURFACE_ID, sessionId)[0].status).toBe('failed'); + expect(listener).not.toHaveBeenCalled(); + expect(pendingQueueManager.removeForSurface(LOCAL_SURFACE_ID, sessionId, item.id)).toBe(true); + expect(pendingQueueManager.listForSurface(LOCAL_SURFACE_ID, sessionId)).toEqual([]); + expect(pendingQueueManager.list(sessionId)).toEqual([other]); + } finally { unsubscribe(); pendingQueueManager.clear(sessionId); } +}); diff --git a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts index 78033ee480..609fda125c 100644 --- a/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts +++ b/src/web-ui/src/flow_chat/services/flow-chat-manager/PendingQueueModule.ts @@ -276,7 +276,10 @@ class PendingQueueManager { } remove(sessionId: string, id: string): boolean { - const surfaceId = getActiveSurfaceId(); + return this.removeForSurface(getActiveSurfaceId(), sessionId, id); + } + + removeForSurface(surfaceId: DeviceSurfaceId, sessionId: string, id: string): boolean { const key = this.queueKey(sessionId, surfaceId); const items = this.queues.get(key); if (!items) return false; @@ -287,8 +290,8 @@ class PendingQueueManager { } else { this.queues.set(key, next); } - this.persist(sessionId); - this.notify(sessionId); + this.persist(sessionId, surfaceId); + this.notifySurface(surfaceId, sessionId); return true; } @@ -326,13 +329,17 @@ class PendingQueueManager { } setStatus(sessionId: string, id: string, status: QueuedMessage['status']): void { - const items = this.queues.get(this.queueKey(sessionId)); + this.setStatusForSurface(getActiveSurfaceId(), sessionId, id, status); + } + + setStatusForSurface(surfaceId: DeviceSurfaceId, sessionId: string, id: string, status: QueuedMessage['status']): void { + const items = this.queues.get(this.queueKey(sessionId, surfaceId)); if (!items) return; const idx = items.findIndex(item => item.id === id); if (idx === -1) return; items[idx] = { ...items[idx], status }; - this.persist(sessionId); - this.notify(sessionId); + this.persist(sessionId, surfaceId); + this.notifySurface(surfaceId, sessionId); } /** Update a still-pending payload atomically without changing FIFO identity or attachments. */ diff --git a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts index 43640f3843..fd5fca3cd2 100644 --- a/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts +++ b/src/web-ui/src/flow_chat/session-drivers/local/LocalSessionDriver.ts @@ -318,6 +318,8 @@ export const localSessionDriver: SessionDriver = { }, async cancel(context: FlowChatContext, sessionId: string): Promise { + const scope = getActiveSurfaceScope(); + const originalTurnId = stateMachineManager.get(sessionId)?.getContext().currentDialogTurnId; const currentState = stateMachineManager.getCurrentState(sessionId); if (currentState !== SessionExecutionState.PROCESSING) { return false; @@ -329,6 +331,9 @@ export const localSessionDriver: SessionDriver = { sessionId, SessionExecutionEvent.USER_CANCEL, ); + scope.assertCurrent('apply cancellation outcome'); + const currentTurnId = stateMachineManager.get(sessionId)?.getContext().currentDialogTurnId; + if (currentTurnId && currentTurnId !== originalTurnId) return false; const settledInFinishing = success && stateMachineManager.getCurrentState(sessionId) === SessionExecutionState.FINISHING; if (!settledInFinishing) { diff --git a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.test.ts b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.test.ts index 222389c3d5..7f5e2df802 100644 --- a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.test.ts +++ b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.test.ts @@ -1,6 +1,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { SessionStateMachineImpl } from './SessionStateMachine'; -import { SessionExecutionEvent } from './types'; +import { SessionExecutionEvent, SessionExecutionState } from './types'; + +import { activateSurface } from '@/infrastructure/peer-device/deviceSurface'; const cancelSessionTask = vi.fn(); const interruptDialogTurn = vi.fn(); @@ -32,6 +34,7 @@ vi.mock('@/infrastructure/peer-device/peerModeFlag', () => ({ describe('SessionStateMachine recoverable interruption', () => { beforeEach(() => { + activateSurface('local'); cancelSessionTask.mockReset(); interruptDialogTurn.mockReset(); interruptDialogTurn.mockResolvedValue(undefined); @@ -50,3 +53,57 @@ describe('SessionStateMachine recoverable interruption', () => { expect(cancelSessionTask).not.toHaveBeenCalled(); }); }); + +describe('cancellation ownership', () => { + beforeEach(() => { activateSurface('local'); interruptDialogTurn.mockReset(); }); + + it('does not issue a cancel through the newly selected device after an async import', async () => { + const machine = new SessionStateMachineImpl('session-1'); + await machine.transition(SessionExecutionEvent.START, { taskId: 'session-1', dialogTurnId: 'turn-1' }); + const pending = machine.transition(SessionExecutionEvent.USER_CANCEL); + activateSurface('peer-other'); + await pending; + expect(interruptDialogTurn).not.toHaveBeenCalled(); + activateSurface('local'); + }); + + it('still sends the requested stop if a running snapshot arrives during preparation', async () => { + interruptDialogTurn.mockResolvedValue(undefined); + const machine = new SessionStateMachineImpl('session-1'); + await machine.transition(SessionExecutionEvent.START, { taskId: 'session-1', dialogTurnId: 'turn-1' }); + const pending = machine.transition(SessionExecutionEvent.USER_CANCEL); + machine.acceptRuntimeStatus({ state: SessionExecutionState.PROCESSING, turnId: 'turn-1', + roundId: null, phase: null, pendingTools: [], error: null }); + await pending; + expect(interruptDialogTurn).toHaveBeenCalledWith('session-1', 'turn-1'); + }); + + it('restores processing after cancellation fails even if text arrived while waiting', async () => { + let reject!: (error: Error) => void; + interruptDialogTurn.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; })); + const machine = new SessionStateMachineImpl('session-1'); + await machine.transition(SessionExecutionEvent.START, { taskId: 'session-1', dialogTurnId: 'turn-1' }); + const pending = machine.transition(SessionExecutionEvent.USER_CANCEL); + await vi.waitFor(() => expect(interruptDialogTurn).toHaveBeenCalled()); + await machine.transition(SessionExecutionEvent.TEXT_CHUNK_RECEIVED, { text: 'Still running' }); + reject(new Error('Stop request failed')); + await pending; + expect(machine.getCurrentState()).toBe(SessionExecutionState.PROCESSING); + expect(machine.getContext().currentDialogTurnId).toBe('turn-1'); + }); + + it('does not move a newer finishing turn back to processing after an old cancellation fails', async () => { + let reject!: (error: Error) => void; + interruptDialogTurn.mockImplementationOnce(() => new Promise((_, fail) => { reject = fail; })); + const machine = new SessionStateMachineImpl('session-1'); + await machine.transition(SessionExecutionEvent.START, { taskId: 'session-1', dialogTurnId: 'turn-1' }); + const pending = machine.transition(SessionExecutionEvent.USER_CANCEL); + await vi.waitFor(() => expect(interruptDialogTurn).toHaveBeenCalled()); + machine.acceptRuntimeStatus({ state: SessionExecutionState.FINISHING, turnId: 'turn-2', + roundId: null, phase: null, pendingTools: [], error: null }); + reject(new Error('Relay connection closed before the reply arrived')); + await pending; + expect(machine.getCurrentState()).toBe(SessionExecutionState.FINISHING); + expect(machine.getContext().currentDialogTurnId).toBe('turn-2'); + }); +}); diff --git a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts index f8d5878031..ec2a753c74 100644 --- a/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts +++ b/src/web-ui/src/flow_chat/state-machine/SessionStateMachine.ts @@ -12,6 +12,7 @@ import { } from './types'; import { getNextState, PHASE_TRANSITIONS } from './transitions'; import { createLogger } from '@/shared/utils/logger'; +import { getActiveSurfaceScope, isSurfaceChangedError } from '@/infrastructure/peer-device/deviceSurface'; const log = createLogger('SessionStateMachine'); @@ -51,6 +52,7 @@ export class SessionStateMachineImpl { private context: SessionStateMachineContext; private transitionHistory: StateTransition[] = []; private listeners: Set<(machine: SessionStateMachine) => void> = new Set(); + private cancellationGeneration = 0; constructor(sessionId: string) { this.sessionId = sessionId; @@ -97,6 +99,7 @@ export class SessionStateMachineImpl { && this.context.errorMessage === status.error && pendingTools.size === this.context.pendingToolConfirmations.size && [...pendingTools].every(id => this.context.pendingToolConfirmations.has(id))) return; + this.cancellationGeneration += 1; this.currentState = status.state; this.context = { ...this.context, taskId: this.sessionId, currentDialogTurnId: status.turnId, currentModelRoundId: status.roundId, @@ -132,6 +135,13 @@ export class SessionStateMachineImpl { return false; } + if ([SessionExecutionEvent.START, SessionExecutionEvent.USER_CANCEL, + SessionExecutionEvent.FINISHING_SETTLED, SessionExecutionEvent.RESET, + SessionExecutionEvent.BACKEND_STREAM_COMPLETED, SessionExecutionEvent.ERROR_OCCURRED, + SessionExecutionEvent.TOOL_REJECTED].includes(event)) { + this.cancellationGeneration += 1; + } + const toolRelatedEvents = [ SessionExecutionEvent.TOOL_DETECTED, SessionExecutionEvent.TOOL_STARTED, @@ -286,18 +296,27 @@ export class SessionStateMachineImpl { const state = this.currentState; if (event === SessionExecutionEvent.USER_CANCEL && this.context.taskId && this.context.currentDialogTurnId) { - const { flowChatStore } = await import('@/flow_chat/store/FlowChatStore'); + const scope = getActiveSurfaceScope(); const sessionId = this.context.taskId; const dialogTurnId = this.context.currentDialogTurnId; - const { acpClientIdFromAgentType } = await import('@/flow_chat/utils/acpSession'); - const session = flowChatStore.getState().sessions.get(sessionId); - const acpClientId = - acpClientIdFromAgentType(session?.config?.agentType) || - acpClientIdFromAgentType(session?.mode); - + const generation = this.cancellationGeneration; + const stillOwnsCancellation = () => this.cancellationGeneration === generation + && this.context.currentDialogTurnId === dialogTurnId + && this.currentState === SessionExecutionState.FINISHING; + let acpClientId: string | undefined; + try { + const { flowChatStore } = await import('@/flow_chat/store/FlowChatStore'); + const { acpClientIdFromAgentType } = await import('@/flow_chat/utils/acpSession'); + scope.assertCurrent('resolve cancellation target'); + const session = flowChatStore.getState().sessions.get(sessionId); + acpClientId = acpClientIdFromAgentType(session?.config?.agentType) + || acpClientIdFromAgentType(session?.mode) || undefined; if (acpClientId) { const { ACPClientAPI } = await import('@/infrastructure/api/service-api/ACPClientAPI'); + scope.assertCurrent('cancel ACP turn'); + if (this.context.currentDialogTurnId !== dialogTurnId + || this.currentState === SessionExecutionState.IDLE) return; await ACPClientAPI.cancelDialogTurn({ sessionId, clientId: acpClientId, @@ -311,6 +330,9 @@ export class SessionStateMachineImpl { const { isPeerDeviceModeActive } = await import( '@/infrastructure/peer-device/peerModeFlag' ); + scope.assertCurrent('cancel dialog turn'); + if (this.context.currentDialogTurnId !== dialogTurnId + || this.currentState === SessionExecutionState.IDLE) return; const goalStatus = session?.threadGoal?.status?.toLowerCase(); const supportsRecoverableInterruption = session?.sessionKind === 'normal' @@ -331,7 +353,12 @@ export class SessionStateMachineImpl { } log.debug('Backend interruption completed', { sessionId, dialogTurnId, acpClientId }); } catch (error) { - log.error('Backend cancellation failed', { sessionId, dialogTurnId, acpClientId, error }); + if (!isSurfaceChangedError(error)) { + log.error('Backend cancellation failed', { sessionId, dialogTurnId, acpClientId, error }); + } + // A newer host fact or cancellation owns its own outcome. Never roll + // it back on behalf of a request that was issued for an older turn. + if (!stillOwnsCancellation()) return; await this.transition(SessionExecutionEvent.USER_CANCEL_FAILED).catch(transitionError => { log.error('Failed to restore processing state after cancellation failure', { sessionId, diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts index fe491ac25e..c31f13b1bb 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -902,6 +902,29 @@ describe('FlowChatStore session removal active selection', () => { sessionComposerStore.setState({ drafts: {} }); }); + it.each(['absent', 'present', 'offline'] as const)('reads back an uncertain peer deletion with host state=%s', async hostState => { + activateSurface('peer-deletion'); + const session = createSession(); + flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]), activeSessionId: session.sessionId })); + sessionComposerStore.getState().setValue(session.sessionId, 'Unsent message'); + const failure = new Error('outcome_unknown: Relay connection closed before the reply arrived'); + apiMocks.deleteSession.mockRejectedValueOnce(failure); + apiMocks.loadSessionMetadata.mockReset(); + if (hostState === 'offline') apiMocks.loadSessionMetadata.mockRejectedValueOnce(new Error('offline')); + else apiMocks.loadSessionMetadata.mockResolvedValueOnce(hostState === 'absent' ? null : { sessionId: session.sessionId }); + const deletion = flowChatStore.deleteSession(session.sessionId); + if (hostState === 'absent') { + await expect(deletion).resolves.toBeUndefined(); + expect(flowChatStore.getState().sessions.has(session.sessionId)).toBe(false); + } else { + await expect(deletion).rejects.toBe(failure); + expect(flowChatStore.getState().sessions.get(session.sessionId)).toBe(session); + expect(sessionComposerStore.getState().getDraft(session.sessionId).value).toBe('Unsent message'); + } + expect(apiMocks.deleteSession).toHaveBeenCalledTimes(1); + expect(apiMocks.loadSessionMetadata).toHaveBeenCalledWith(session.sessionId, session.workspaceId); + }); + it('keeps a failed deletion selected with its history, state machine and draft, then permits retry', async () => { const session = createSession(); flowChatStore.setState(() => ({ sessions: new Map([[session.sessionId, session]]), activeSessionId: session.sessionId })); @@ -6774,6 +6797,20 @@ describe('FlowChatStore historical session hydration state', () => { && range.endOrdinalExclusive > 3 && range.turns.some(turn => turn.id === 'turn-23') )).toBe(false); + + // Live output already owns this Turn, while the persisted catalog still + // ends at ordinal 22. Reading forwards must use that same canonical tail. + const newest = await flowChatStore.loadSessionTurnWindow('history-1', 23, { source: 'prefetch' }); + expect(newest).toMatchObject({ status: 'ready', cacheHit: true, targetTurnId: 'turn-23' }); + flowChatStore.setState(prev => { + const sessions = new Map(prev.sessions); + const current = sessions.get('history-1')!; + sessions.set('history-1', { ...current, dialogTurns: current.dialogTurns.filter(turn => turn.id !== 'turn-23') }); + return { ...prev, sessions }; + }); + await expect(flowChatStore.loadSessionTurnWindow('history-1', 23, { source: 'prefetch' })) + .resolves.toMatchObject({ status: 'not-found', cacheHit: false }); + expect(apiMocks.loadSessionTurnWindow).not.toHaveBeenCalled(); }); it('adopts an optimistic partial-tail turn in place without incrementing projected history twice', async () => { @@ -7352,6 +7389,43 @@ describe('FlowChatStore historical session hydration state', () => { ); }); + it.each(['ready', 'stale', 'not-found'] as const)( + 'retires old cached bodies and ignores a late %s page after a catalog refresh', async lateStatus => { + const catalog = createTurnCatalog(8, 'before-refresh'); + const refreshed = createTurnCatalog(8, 'after-refresh'); + flowChatStore.setState(() => ({ + sessions: new Map([['history-1', createSession({ + sessionId: 'history-1', historyState: 'ready', isPartial: true, + totalTurnCount: 8, turnCatalog: catalog, + })]]), activeSessionId: 'history-1', + })); + const ready = (revision: string, start: number, end: number) => ({ + status: 'ready' as const, catalogRevision: revision, totalTurnCount: 8, + startOrdinal: start, endOrdinalExclusive: end, targetTurnId: `turn-${start}`, + turns: Array.from({ length: end - start }, (_, i) => createPersistedTurn(start + i)), + }); + apiMocks.loadSessionTurnWindow.mockResolvedValueOnce(ready(catalog.revision, 0, 2)); + await flowChatStore.loadSessionTurnWindow('history-1', 0, { source: 'prefetch' }); + const oldPage = createDeferred(); + apiMocks.loadSessionTurnWindow.mockReturnValueOnce(oldPage.promise) + .mockResolvedValueOnce({ status: 'stale', catalog: refreshed }) + .mockResolvedValueOnce(ready(refreshed.revision, 4, 5)); + const oldRead = flowChatStore.loadSessionTurnWindow('history-1', 6, { source: 'prefetch' }); + const freshRead = await flowChatStore.loadSessionTurnWindow('history-1', 4, { source: 'prefetch' }); + expect(freshRead).toMatchObject({ status: 'ready', isCurrent: true }); + expect(flowChatStore.reactivateSessionHistoryWindow('history-1', { + startOrdinal: 0, endOrdinalExclusive: 2, targetTurnId: 'turn-0', mode: 'history-window', + })).toBeNull(); + oldPage.resolve(lateStatus === 'ready' ? ready(catalog.revision, 6, 7) + : { status: lateStatus, catalog: createTurnCatalog(8, 'late-intermediate-revision') }); + await expect(oldRead).resolves.toMatchObject({ isCurrent: false }); + expect(flowChatStore.getState().sessions.get('history-1')?.turnCatalog?.revision).toBe(refreshed.revision); + expect(flowChatStore.getSessionHistoryViewState('history-1')?.loadedRanges) + .toMatchObject([{ startOrdinal: 4, endOrdinalExclusive: 5 }]); + expect(apiMocks.loadSessionTurnWindow).toHaveBeenCalledTimes(4); + }, + ); + it('marks an unsupported window command per host and requests full-history fallback', async () => { const catalog = createTurnCatalog(5); flowChatStore.setState(() => ({ diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 634bc3ee9f..a4ee64f870 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -1,4 +1,5 @@ import { workspaceManager } from '@/infrastructure/services/business/workspaceManager'; +import { isOutcomeUnknownError } from '@/infrastructure/api/errors/TauriCommandError'; import { forgetAgentCanvasSession, removeBtwSessionFromAgentCanvas } from '@/app/components/panels/content-canvas/stores/canvasStore'; import { resolveLegacySessionWorkspace } from '@/infrastructure/api/service-api/legacyWorkspaceCompatibility'; import { projectUserQuestionTiming } from '../utils/userQuestionTiming'; @@ -3231,7 +3232,17 @@ export class FlowChatStore { if (catalog.sessionId !== sessionId) { return; } - this.ensureSessionHistoryView(sessionId, catalog).catalog = catalog; + const view = this.ensureSessionHistoryView(sessionId, catalog); + if (view.catalog?.revision !== catalog.revision) { + // Catalog revisions also version the cached bodies and in-flight reads. + // A stale page can discover a rewrite before the next Session snapshot. + view.navigationGeneration += 1; + view.pendingTargetOrdinal = null; + view.activeRange = null; + view.loadedRanges = []; + this.sessionHistoryTurnAccessTimes.delete(sessionId); + } + view.catalog = catalog; this.setState(prev => { const session = prev.sessions.get(sessionId); if (!session) { @@ -3751,22 +3762,21 @@ export class FlowChatStore { const entry = catalog?.entries.find( candidate => candidate.ordinal === normalizedTargetOrdinal, ); - if (!session || !catalog || !entry) { - return { - status: 'not-found', + const notFound = (): SessionTurnWindowLoadResult => ({ + status: 'not-found', + sessionId, + targetOrdinal: normalizedTargetOrdinal, + navigationGeneration: generation, + isCurrent: this.isSessionTurnWindowRequestCurrent( sessionId, - targetOrdinal: normalizedTargetOrdinal, - navigationGeneration: generation, - isCurrent: this.isSessionTurnWindowRequestCurrent( - sessionId, - generation, - normalizedTargetOrdinal, - source, - ), - cacheHit: false, - ...(catalog ? { catalog } : {}), - }; - } + generation, + normalizedTargetOrdinal, + source, + ), + cacheHit: false, + ...(catalog ? { catalog } : {}), + }); + if (!session || !catalog) return notFound(); const cachedRange = view.loadedRanges.find(range => range.startOrdinal <= normalizedTargetOrdinal @@ -3774,7 +3784,18 @@ export class FlowChatStore { ); if (cachedRange) { const cachedTarget = cachedRange.turns[normalizedTargetOrdinal - cachedRange.startOrdinal]; - if (!entry.turnId || cachedTarget?.id === entry.turnId) { + // A live/optimistic Turn can be rendered before the next persisted + // catalog includes it. Only the current canonical tail can vouch for + // that ordinal; an unrelated stale cache entry cannot fill a catalog gap. + const canonicalTarget = !entry && cachedTarget + ? session.dialogTurns.find(turn => turn.id === cachedTarget.id) + : undefined; + const canonicalOrdinal = canonicalTarget + ? resolveDialogTurnIdentity(session, canonicalTarget)?.ordinal + : undefined; + if (cachedTarget && (entry + ? !entry.turnId || cachedTarget.id === entry.turnId + : canonicalOrdinal === normalizedTargetOrdinal)) { const selected = selectTargetHistoryPresentationRange( cachedRange, normalizedTargetOrdinal, @@ -3804,6 +3825,8 @@ export class FlowChatStore { } } + if (!entry) return notFound(); + if (getActiveSurfaceId() !== 'local') { // Turn navigation reads the same canonical log replica. It never starts // a second transcript restore/RPC path after a cache eviction. @@ -4042,18 +4065,15 @@ export class FlowChatStore { }; } - const isCurrent = this.isSessionTurnWindowRequestCurrent( + const currentCatalog = this.sessionHistoryViews.get(request.sessionId)?.catalog; + const catalogIsCurrent = !currentCatalog || currentCatalog.revision === request.catalog.revision; + const isCurrent = catalogIsCurrent && this.isSessionTurnWindowRequestCurrent( request.sessionId, request.generation, request.targetOrdinal, request.source, ); - const currentCatalog = this.sessionHistoryViews.get(request.sessionId)?.catalog; - if ( - isCurrent - || !currentCatalog - || currentCatalog.revision === request.catalog.revision - ) { + if (catalogIsCurrent) { this.updateAuthoritativeSessionTurnCatalog(request.sessionId, response.catalog); } if (response.status === 'stale' && request.staleRetryCount === 0 && isCurrent) { @@ -4064,7 +4084,7 @@ export class FlowChatStore { ); if (relocatedEntry) { const view = this.sessionHistoryViews.get(request.sessionId); - if (request.source === 'target' && view?.navigationGeneration === request.generation) { + if (request.source === 'target' && view) { view.pendingTargetOrdinal = relocatedEntry.ordinal; } return this.loadSessionTurnWindowAttempt({ @@ -4073,6 +4093,7 @@ export class FlowChatStore { targetStorageTurnIndex: relocatedEntry.storageTurnIndex, originalTargetTurnId: relocatedEntry.turnId ?? request.originalTargetTurnId, catalog: response.catalog, + generation: view?.navigationGeneration ?? request.generation, staleRetryCount: 1, }); } @@ -5805,7 +5826,28 @@ export class FlowChatStore { // Session storage is resolved by workspace ID, so a session whose // workspace directory is gone must still reach the backend. Pre-ID // sessions fail loudly in sessionHistoryWorkspaceId. - await agentAPI.deleteSession(id, this.sessionHistoryWorkspaceId(id)); + const workspaceId = this.sessionHistoryWorkspaceId(id); + try { + await agentAPI.deleteSession(id, workspaceId); + } catch (error) { + scope.assertCurrent('verify session deletion'); + // A host deletion event may have confirmed the result before its + // RPC acknowledgement was lost. Otherwise only an authoritative + // read can settle an unknown outcome; never replay the mutation. + if (this.state.sessions.has(id)) { + if (scope.surfaceId === 'local' || !isOutcomeUnknownError(error)) throw error; + let confirmed = false; + try { + const { sessionAPI } = await import('@/infrastructure/api/service-api/SessionAPI'); + scope.assertCurrent('read session deletion outcome'); + confirmed = await sessionAPI.loadSessionMetadata(id, workspaceId) === null; + } catch (readError) { + log.warn('Could not verify peer session deletion', { sessionId: id, error: readError }); + } + scope.assertCurrent('apply verified session deletion'); + if (!confirmed) throw error; + } + } scope.assertCurrent('complete session deletion'); } stateMachineManager.delete(id); diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts index 07cffb7681..f8e816bba8 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.test.ts @@ -1,3 +1,4 @@ +import { isOutcomeUnknownError } from '../errors/TauriCommandError'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { PEER_BROWSER_CONTROL_SETUP_TIMEOUT_MS, @@ -1183,3 +1184,25 @@ describe('Magpie discovery capability', () => { expect(rpc).toHaveBeenCalledTimes(1); }); }); + + +describe('peer mutation outcomes', () => { + it('marks a lost mutation reply as unknown without resubmitting it', async () => { + const rpc = vi.fn().mockRejectedValue(new Error('Relay connection closed before the reply arrived')); + const adapter = new PeerDeviceTransportAdapter('peer-1', rpc); + const error = await adapter.request('delete_session', { request: { sessionId: 's' } }).catch(error => error); + expect(isOutcomeUnknownError(error)).toBe(true); + expect(rpc).toHaveBeenCalledTimes(1); + }); + + it.each([ + ['unsent', null, 'Relay is disconnected; request was not submitted'], + ['refused', { resp: 'host_invoke_result', ok: false, error: 'session_in_use: busy' }, null], + ])('preserves a known %s mutation failure', async (_kind, reply, message) => { + const rpc = reply ? vi.fn().mockResolvedValue(JSON.stringify(reply)) : vi.fn().mockRejectedValue(new Error(message!)); + const error = await new PeerDeviceTransportAdapter('peer-1', rpc) + .request('delete_session', { request: { sessionId: 's' } }).catch(error => error); + expect(isOutcomeUnknownError(error)).toBe(false); + expect(rpc).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts index 04e55188e1..40cda9c3d9 100644 --- a/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts +++ b/src/web-ui/src/infrastructure/api/adapters/peer-device-adapter.ts @@ -1042,6 +1042,15 @@ export class PeerDeviceTransportAdapter implements ITransportAdapter { } log.error('Peer HostInvoke transport failed', { action, error }); this.hooks.onHostInvokeTransportFailure?.(error, { action, priority }); + // A lost acknowledgement says nothing about whether a mutation ran. + // Keep the stable outcome code used by product readback flows, without + // making non-idempotent operations eligible for automatic replay. + const message = error instanceof Error ? error.message : String(error); + if (rpcPolicy.retryKind !== 'read' + && !message.includes('Relay is disconnected; request was not submitted') + && !message.startsWith('outcome_unknown:')) { + throw Object.assign(new Error(`outcome_unknown: ${message}`), { cause: error }); + } throw error; } } diff --git a/src/web-ui/src/infrastructure/peer-device/README.md b/src/web-ui/src/infrastructure/peer-device/README.md index 5664e6a7a1..1d683e5635 100644 --- a/src/web-ui/src/infrastructure/peer-device/README.md +++ b/src/web-ui/src/infrastructure/peer-device/README.md @@ -215,6 +215,18 @@ notification metadata. records; it does not reconstruct a running turn from a second full snapshot. Lifecycle and approval events may update controls, but raw token/tool-body events cannot overwrite the canonical content owner. + A delayed start cannot reactivate a terminal turn or replace a newer admitted + turn. Stop requests capture their device activation and turn before awaiting + preparation; a late response cannot settle another turn or device's buffers. + + Legacy frontend queues wait for canonical peer history to be ready; local + Runtime replay fences do not gate peer queues. An authoritative terminal + record releases a pending cancellation gate. Interrupted-turn recovery and + failed-message ordering still require their explicit user decisions. Queue + acknowledgements settle on the device where the send began. A device switch + preserves the original pending item and FIFO order when it was not submitted. + An uncertain legacy submission retains its draft and Turn id for explicit + recovery instead of being silently dropped or automatically resubmitted. `get_session_interaction_mailbox` returns the Runtime's revisioned pending questions and permissions on attach/reconnect. Apply it with a captured @@ -238,6 +250,10 @@ notification metadata. Request admission and byte budgets belong to the shared transport owner. Avoid independent UI slot limits or polling loops that compete with recovery. Mutations are not automatically replayed without an idempotency contract. + Lost mutation replies carry `outcome_unknown:`; confirmed unsent requests and + product refusals retain their known failure. Deletion may settle from the + host deletion event or an authoritative missing metadata record. A failed + readback or a still-present record keeps the session and unsent drafts. Dialog submissions reuse `(sessionId, turnId)` so an ambiguous acknowledgement does not create another turn. A failed session list must leave loading state and offer an explicit retry.