diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md index d6ce6fc922..b3bd5b0f37 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_HISTORY_PAGING.md @@ -242,6 +242,25 @@ no pending ticket; errors/cancellation require a new reader action rather than a render-driven retry loop. Exhaustion is forgotten when its window/boundary changes. Session instances isolate the controller across session switches. +Explicit source synchronization reserves the pager's presentation commit before +reading the host: publishing the snapshot can move the rendered boundary, and +must not cancel its own retry ticket. A cancelled request clears only its own +loading state, fenced by the request slot, surface, Session and presentation +owner. Errors remain retryable. Recovery accepts a changed host catalog revision +even when its previews are incomplete; a cached complete catalog from an older +revision cannot override that response. Same-revision complete previews and the +ordinary Peer snapshot merge policy remain intact. + +An adjacent read can adopt a newer catalog and retire the store's active range +even when its stale-response retry returns ready. The container reacquires the +displayed reader range and confirms the adjacent page again before preparing +the viewport. This uses the existing window reader and cache, not a full-history +reload. Catalog, navigation-generation or range changes during preparation +cancel the old commit and leave the boundary available for fresh reader demand. +Repeated invalidation does not start a recursive retry. Actual read failures +retain the displayed content and expose explicit synchronization; the error +sentinel restores pointer interaction so its recovery button can be clicked. + Opening and follow-output guards remain synchronous (`isFollowingOutputNow`), so the gesture that releases follow is evaluated against the new owner. Geometry with no visible range remains a diagnostic refusal. Request/refusal diagnostics diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md index 22540c5e6e..fe31b632bc 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VERIFICATION.md @@ -57,6 +57,7 @@ each missing what the other had. | `flowChatViewportGeometry.test.ts` | actual gutter centring, symmetric/omitted leading gutter and origin handoff without accumulated horizontal offset | | `../../services/RelaySessionHistory.test.ts`, `../../store/FlowChatStore.test.ts`, `../../services/flow-chat-manager/SessionModule.test.ts` | local/SSH one-Turn restore, paint-gated adjacent prefetch without tail replacement, partial reopen without full-history drain, replay staging, live updates during older reads, failed-read retention and retry; transport fixtures, not live remote evidence | | `flowChatHistoryPager.test.ts` | request/layout ordering, coalesced demand, prefetch without physical arrival, stale tickets, exhaustion and retry eligibility | +| `../../store/FlowChatStore.test.ts`, `ModernFlowChatContainer.history-restore.test.tsx` | explicit retry reserves the commit before a host snapshot moves the boundary; cancelled synchronization success/failure releases its loading state; changed host revisions replace stale complete catalogs while same-revision complete previews survive; controlled IO/pager fixtures, not live remote evidence | | `useFlowChatViewportOwner.test.tsx` | top/native coordinate conversion, older-range growth creates no reader demand, synchronous write/shift accounting preserves reader travel and actual clamping | | `flowChatLiveTailWindow.test.ts` | "does the transcript still reach the newest Turn" | | `flowChatViewportAnchor.test.ts` | anchor geometry and the DOM contract | @@ -72,7 +73,8 @@ each missing what the other had. | `FlowChatOpeningBoundary.test.tsx` | opening-only activation/scroll isolation, bidirectional focus skipping, programmatic focus return, and reveal cleanup; DOM contracts only | | `HistorySessionLoadingBoundary.test.tsx` | shared 200 ms indicator delay, immediate settled cold/warm opens, off-screen user-message independence, settled-viewport gating, atomic text/tools/code presentation, interaction blocking, session/device cancellation, failure/inactive/resume/reduced-motion handling and no streaming/remount replay; DOM/animation fixtures, not native paint or live remote evidence | | `ModernFlowChatContainer.history-state.test.tsx` | history presentation and the submission event | -| `ModernFlowChatContainer.history-restore.test.tsx` | production container/loading boundary with controlled history IO: rollback with/without an intermediate hydration commit, empty history, retired legacy snapshots/bookmarks, cold host transfer, pending-read cancellation, navigation takeover, late success/failure, retry, deliberately empty internal projections with accessible earlier history, and Session switching on local/simulated Peer surfaces; no native layout or live transport claim | +| `ModernFlowChatContainer.history-restore.test.tsx` | production container/loading boundary with controlled history IO: rollback with/without an intermediate hydration commit, empty history, retired legacy snapshots/bookmarks, cold host transfer, pending-read cancellation, navigation takeover, late success/failure, retry, deliberately empty internal projections with accessible earlier history, and Session switching; catalog retirement during before/after paging and explicit synchronization on local/simulated SSH/Peer surfaces, preparation invalidation and late/repeated recovery cancellation; no native layout or live transport claim | +| `VirtualMessageList.history-paging.test.ts` | compiled status CSS keeps idle/loading sentinels passive and exposes pointer interaction for visible error recovery; DOM/CSS fixture, not native hit testing | | `flowChatViewportOwnership.test.ts` | the priority order, preemption, expiry | | `useFlowChatVirtualizer.test.ts` | the offsets-and-positions boundary | | `useFlowChatVirtualizer.measurement.test.tsx` | `measureRenderedItems` against a real virtualizer, fractional normal-flow sizes and offscreen size reservations across reflow | 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 6c48284609..b66e0bf0c1 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 @@ -18,6 +18,7 @@ const fixture = vi.hoisted(() => ({ extend: vi.fn(), present: null as ((sessionId: string, presentation: SessionHistoryPresentation) => void) | null, loadedRanges: [] as SessionHistoryViewState['loadedRanges'], + navigationGeneration: 1, })); vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: { getState: () => ({ activeSessionId: fixture.session?.sessionId, sessions: new Map(fixture.session ? [[fixture.session.sessionId, fixture.session]] : []) }), @@ -25,6 +26,7 @@ vi.mock('../../store/FlowChatStore', () => ({ flowChatStore: { subscribeSelector: () => () => {}, getSessionHistoryViewState: () => ({ catalog: fixture.session?.turnCatalog ?? null, loadedRanges: fixture.loadedRanges, activeRange: fixture.cached?.range ?? null, + navigationGeneration: fixture.navigationGeneration, }), synchronizeSessionHistory: (...args: unknown[]) => fixture.synchronize(...args), reactivateSessionHistoryWindow: () => fixture.cached, @@ -95,6 +97,7 @@ vi.mock('@/infrastructure/api/service-api/AgentAPI', () => ({ agentAPI: { } })); import { ModernFlowChatContainer } from './ModernFlowChatContainer'; +import { FlowChatHistoryPager } from './flowChatHistoryPager'; import { registerConversationReader, stageConversationViewTransfer } from './flowChatViewHandoff'; import { activateSurface, getActiveSurfaceScope, LOCAL_SURFACE_ID } from '@/infrastructure/peer-device/deviceSurface'; @@ -165,13 +168,15 @@ describe('FlowChat reader restoration across history rewrites', () => { activateSurface(LOCAL_SURFACE_ID); fixture.session = session(); fixture.cached = presentation(); - fixture.restore.mockResolvedValue(null); - fixture.extend.mockReturnValue(null); + fixture.restore.mockReset().mockResolvedValue(null); + fixture.extend.mockReset().mockReturnValue(null); + fixture.loadTurnWindow.mockReset(); fixture.synchronize.mockResolvedValue(undefined); fixture.listProps = null; fixture.viewportSettled = true; fixture.present = null; fixture.loadedRanges = []; + fixture.navigationGeneration = 1; vi.stubGlobal('matchMedia', () => ({ matches: false, addEventListener() {}, removeEventListener() {} })); host = document.createElement('div'); document.body.append(host); @@ -293,6 +298,87 @@ describe('FlowChat reader restoration across history rewrites', () => { expect(fixture.restore).not.toHaveBeenCalled(); }); + it('keeps the retry ticket when the host snapshot moves the rendered boundary', async () => { + stageBookmark(); + await render(); + const pager = new FlowChatHistoryPager(); + pager.commitLayout('4:8', { before: 'turn-4', after: 'turn-7' }); + const ticket = pager.begin('before')!; + const read = deferred(); + fixture.synchronize.mockReturnValueOnce(read.promise); + fixture.loadTurnWindow.mockResolvedValue({ status: 'ready', isCurrent: true }); + fixture.extend.mockReturnValue(presentation(0, 8)); + let request!: Promise; + await act(async () => { + request = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + synchronizeHistory: true, isCurrent: () => pager.isCurrent(ticket), + prepareViewportForPresentationCommit: () => pager.prepareCommit(ticket), + }); + }); + pager.commitLayout('3:8', { before: 'turn-3', after: 'turn-7' }); + await act(async () => { + read.resolve(); + expect(await request).toBe('applied'); + }); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle'); + expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull(); + }); + + it.each(['resolve', 'reject'] as const)('settles loading when a synchronization ticket is cancelled before %s', async settlement => { + stageBookmark(); + await render(); + const read = deferred(); + fixture.synchronize.mockReturnValueOnce(read.promise); + let current = true; + let request!: Promise; + await act(async () => { + request = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + synchronizeHistory: true, isCurrent: () => current, + }); + }); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('loading'); + current = false; + await act(async () => { + if (settlement === 'reject') read.reject(new Error('Read failed after cancellation')); + else read.resolve(); + expect(await request).toBe('cancelled'); + }); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle'); + }); + + it('does not clear a newer retry when a cancelled synchronization fails late', async () => { + stageBookmark(); + await render(); + const first = deferred(); + const second = deferred(); + fixture.synchronize.mockReturnValueOnce(first.promise).mockReturnValueOnce(second.promise); + let firstCurrent = true; + let older!: Promise; + let newer!: Promise; + await act(async () => { + older = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + synchronizeHistory: true, isCurrent: () => firstCurrent, + }); + }); + firstCurrent = false; + await act(async () => { + newer = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + synchronizeHistory: true, isCurrent: () => true, + }); + }); + await act(async () => { + first.reject(new Error('Superseded source read failed')); + expect(await older).toBe('cancelled'); + }); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('loading'); + await act(async () => { + second.reject(new Error('Owning host unavailable')); + expect(await newer).toBe('not-ready'); + }); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('error'); + expect(host.querySelector('[data-turn-id="turn-4"]')).not.toBeNull(); + }); + 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; @@ -324,6 +410,165 @@ describe('FlowChat reader restoration across history rewrites', () => { expect(host.querySelector('[data-turn-id="turn-0"]')).not.toBeNull(); }); + it.each((['local', 'ssh', 'peer-device'] as const).flatMap(location => + (['before', 'after'] as const).flatMap(direction => + [false, true].map(synchronizeHistory => ({ location, direction, synchronizeHistory })), + ), + ))( + 'recovers a catalog retired during $direction paging on $location (explicit sync: $synchronizeHistory)', async ({ location, direction, synchronizeHistory }) => { + if (location === 'peer-device') activateSurface('peer-device'); + const withCatalog = (revision: string): Session => ({ + ...sessionWithCatalog(42, revision), + ...(location === 'ssh' ? { remoteConnectionId: 'ssh-target', remoteSshHost: 'build-host' } : {}), + }); + fixture.session = withCatalog('before-live-turn'); + const window = presentation(38, 40); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.restore.mockImplementation(async () => { + fixture.cached = window; + fixture.navigationGeneration += 1; + return window; + }); + fixture.loadTurnWindow.mockImplementationOnce(async () => { + // Stale-response retry succeeds under a new catalog, but the old + // reader window was retired while this request was in flight. + fixture.cached = null; + fixture.navigationGeneration += 1; + fixture.session = withCatalog('after-live-turn'); + return { status: 'ready', isCurrent: true }; + }).mockResolvedValueOnce({ status: 'ready', isCurrent: true }); + const extended = direction === 'before' ? presentation(34, 40) : presentation(38, 42); + fixture.extend.mockImplementation(() => { + if (!fixture.cached) return null; + fixture.cached = extended; + return extended; + }); + const prepare = vi.fn(() => true); + let outcome: unknown; + await act(async () => { + outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!(direction, { + synchronizeHistory, prepareViewportForPresentationCommit: prepare, + }); + }); + expect(outcome).toBe('applied'); + expect(prepare).toHaveBeenCalledTimes(1); + expect(host.querySelector(`[data-turn-id="turn-${extended.range.startOrdinal}"]`)).not.toBeNull(); + expect(fixture.restore).toHaveBeenCalledTimes(1); + expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(2); + expect(fixture.synchronize).toHaveBeenCalledTimes(synchronizeHistory ? 1 : 0); + }, + ); + + it.each(['catalog', 'navigation', 'range'] as const)( + 'cancels a page superseded by a %s change during viewport preparation', async change => { + fixture.session = sessionWithCatalog(42, 'before-preparation'); + const window = presentation(38, 40); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.loadTurnWindow.mockResolvedValue({ status: 'ready', isCurrent: true }); + const cancel = vi.fn(); + let outcome: unknown; + await act(async () => { + outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + prepareViewportForPresentationCommit: async () => { + if (change === 'catalog') fixture.session = sessionWithCatalog(42, 'after-preparation'); + if (change === 'navigation') fixture.navigationGeneration += 1; + if (change === 'range') fixture.cached = null; + return true; + }, + cancelViewportPresentationCommit: cancel, + }); + }); + expect(outcome).toBe('cancelled'); + expect(cancel).toHaveBeenCalledTimes(1); + expect(fixture.extend).not.toHaveBeenCalled(); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle'); + expect(host.querySelector('[data-turn-id="turn-38"]')).not.toBeNull(); + }, + ); + + it('leaves a failed post-read recovery retryable without replacing the reader', async () => { + fixture.session = sessionWithCatalog(42, 'before-live-turn'); + const window = presentation(38, 40); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.loadTurnWindow.mockImplementationOnce(async () => { + fixture.cached = null; + return { status: 'ready', isCurrent: true }; + }).mockResolvedValue({ status: 'ready', isCurrent: true }); + fixture.restore.mockRejectedValueOnce(new Error('History read timed out')); + let outcome: unknown; + await act(async () => { outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before'); }); + expect(outcome).toBe('not-ready'); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('error'); + expect(host.querySelector('[data-turn-id="turn-38"]')).not.toBeNull(); + fixture.restore.mockImplementation(async () => { fixture.cached = window; return window; }); + fixture.extend.mockReturnValue(presentation(34, 40)); + await act(async () => { + outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { synchronizeHistory: true }); + }); + expect(outcome).toBe('applied'); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle'); + expect(host.querySelector('[data-turn-id="turn-34"]')).not.toBeNull(); + }); + + it.each(['resolve', 'reject'] as const)('ignores a late post-read recovery %s after changing devices', async settlement => { + const window = presentation(38, 40); + fixture.session = sessionWithCatalog(42, 'before-live-turn'); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.loadTurnWindow.mockImplementationOnce(async () => { + fixture.cached = null; + return { status: 'ready', isCurrent: true }; + }); + const read = deferred(); + fixture.restore.mockReturnValueOnce(read.promise); + const prepare = vi.fn(() => true); + let outcome!: Promise; + await act(async () => { + outcome = fixture.listProps!.onHistoryWindowBoundaryIntent!('before', { + prepareViewportForPresentationCommit: prepare, + }); + }); + expect(fixture.restore).toHaveBeenCalledTimes(1); + activateSurface('peer-device'); + await act(async () => { + if (settlement === 'resolve') read.resolve(window); + else read.reject(new Error('Retired recovery failed')); + await outcome; + }); + expect(await outcome).toBe('cancelled'); + expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(1); + expect(fixture.extend).not.toHaveBeenCalled(); + expect(prepare).not.toHaveBeenCalled(); + }); + + it('cancels repeated catalog retirement instead of recursively retrying the page', async () => { + const window = presentation(38, 40); + fixture.session = sessionWithCatalog(42, 'before-live-turn'); + fixture.cached = window; + stageBookmark(window); + await render(); + fixture.loadTurnWindow.mockImplementation(async () => { + fixture.cached = null; + fixture.navigationGeneration += 1; + return { status: 'ready', isCurrent: true }; + }); + fixture.restore.mockImplementation(async () => { fixture.cached = window; return window; }); + let outcome: unknown; + await act(async () => { outcome = await fixture.listProps!.onHistoryWindowBoundaryIntent!('before'); }); + expect(outcome).toBe('cancelled'); + expect(fixture.loadTurnWindow).toHaveBeenCalledTimes(2); + expect(fixture.restore).toHaveBeenCalledTimes(1); + expect(fixture.extend).not.toHaveBeenCalled(); + expect(fixture.listProps!.historyBoundaryState?.before).toBe('idle'); + }); + it('rejects a late orphan recovery after changing devices', async () => { const window = presentation(3, 7); fixture.cached = window; 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 67d857fd1e..318651f548 100644 --- a/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx +++ b/src/web-ui/src/flow_chat/components/modern/ModernFlowChatContainer.tsx @@ -2047,6 +2047,7 @@ export const ModernFlowChatContainer: React.FC = ( return existingRequest; } + let ownsBoundaryStatus = () => false; const request = (async () => { const currentViewportIntent = viewportIntentRef.current; const presentation = currentViewportIntent?.kind === 'turn' @@ -2060,13 +2061,20 @@ export const ModernFlowChatContainer: React.FC = ( } const scope = getActiveSurfaceScope(); - const isCurrent = () => scope.isCurrent() + ownsBoundaryStatus = () => scope.isCurrent() && activeSessionIdRef.current === sessionId - && historyPresentationOwnerGenerationRef.current === presentationOwnerGeneration - && options?.isCurrent?.() !== false; + && historyPresentationOwnerGenerationRef.current === presentationOwnerGeneration; + const isCurrent = () => ownsBoundaryStatus() && options?.isCurrent?.() !== false; + let synchronizationPrepared = false; if (options?.synchronizeHistory) { setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' })); try { + // The host snapshot can itself move the rendered boundary. Reserve + // its commit before publishing it, otherwise the pager cancels this + // recovery as if an unrelated navigation had replaced the reader. + const prepared = await options.prepareViewportForPresentationCommit?.(); + if (prepared === false || !isCurrent()) return 'cancelled'; + synchronizationPrepared = Boolean(options.prepareViewportForPresentationCommit); await flowChatStore.synchronizeSessionHistory(sessionId, isCurrent); if (!isCurrent()) return 'cancelled'; } catch (error) { @@ -2081,10 +2089,12 @@ export const ModernFlowChatContainer: React.FC = ( // 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)) { + const readerWindowIsCurrent = () => { + const activeRange = flowChatStore.getSessionHistoryViewState(sessionId)?.activeRange; + return !presentation || (activeRange?.startOrdinal === presentation.range.startOrdinal + && activeRange.endOrdinalExclusive === presentation.range.endOrdinalExclusive); + }; + if (presentation && !readerWindowIsCurrent()) { setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' })); try { const restored = await flowChatStore.restoreSessionHistoryWindow(sessionId, presentation.range, isCurrent); @@ -2250,13 +2260,23 @@ export const ModernFlowChatContainer: React.FC = ( setHistoryBoundaryState(previous => ({ ...previous, [direction]: 'loading' })); let viewportPreparationStarted = false; try { - const result = direction === 'before' - ? await flowChatStore.loadPreviousSessionTurnWindow(sessionId, targetOrdinal) - : await flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, { + const loadAdjacentWindow = () => direction === 'before' + ? flowChatStore.loadPreviousSessionTurnWindow(sessionId, targetOrdinal) + : flowChatStore.loadSessionTurnWindow(sessionId, targetOrdinal, { source: 'prefetch', before: 4, after: 12, }); + let result = await loadAdjacentWindow(); + if (presentation && result.status === 'ready' && result.isCurrent && isCurrent() && !readerWindowIsCurrent()) { + // The adjacent read can itself adopt a new catalog and retire the + // active window. Restore the reader before extending, then confirm + // the adjacent page again: restoration may also replace cached bodies. + 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'); + result = await loadAdjacentWindow(); + } if (!result.isCurrent || !isCurrent()) { recordHistoryPagingEvent(sessionId, 'outcome_cancelled', { direction, @@ -2313,21 +2333,29 @@ export const ModernFlowChatContainer: React.FC = ( return 'not-ready'; } + const preparedHistoryView = flowChatStore.getSessionHistoryViewState(sessionId); viewportPreparationStarted = Boolean(options?.prepareViewportForPresentationCommit); - const preparationResult = await options?.prepareViewportForPresentationCommit?.(); + const preparationResult = synchronizationPrepared + ? true + : await options?.prepareViewportForPresentationCommit?.(); const activeSessionIsCurrent = activeSessionIdRef.current === sessionId; const presentationOwnerIsCurrent = ( historyPresentationOwnerGenerationRef.current === presentationOwnerGeneration ); + const currentHistoryView = flowChatStore.getSessionHistoryViewState(sessionId); + const historyWindowIsCurrent = readerWindowIsCurrent() + && currentHistoryView?.navigationGeneration === preparedHistoryView?.navigationGeneration + && currentHistoryView?.catalog?.revision === preparedHistoryView?.catalog?.revision; if ( preparationResult === false || !activeSessionIsCurrent || !presentationOwnerIsCurrent || !isCurrent() + || !historyWindowIsCurrent ) { recordHistoryPagingEvent(sessionId, 'outcome_cancelled', { direction, - reason: 'viewport-preparation', + reason: historyWindowIsCurrent ? 'viewport-preparation' : 'history-window-superseded', preparationResult: preparationResult ?? null, activeSessionIsCurrent, presentationOwnerIsCurrent, @@ -2416,6 +2444,11 @@ export const ModernFlowChatContainer: React.FC = ( // Only the request that owns the slot may release it. if (historyBoundaryRequestsRef.current[direction] === request) { historyBoundaryRequestsRef.current[direction] = null; + // A pager ticket may be cancelled without replacing the reader. The + // request still owns its loading indicator, but never a newer reader's. + setHistoryBoundaryState(previous => ownsBoundaryStatus() && previous[direction] === 'loading' + ? { ...previous, [direction]: 'idle' } + : previous); } }); historyBoundaryRequestsRef.current[direction] = request; diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.history-paging.test.ts b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.history-paging.test.ts new file mode 100644 index 0000000000..86f45d5b33 --- /dev/null +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.history-paging.test.ts @@ -0,0 +1,28 @@ +// @vitest-environment jsdom +import { resolve } from 'node:path'; +import { compile } from 'sass'; +import { describe, expect, it } from 'vitest'; + +const css = compile(resolve(__dirname, 'VirtualMessageList.scss')).css; + +describe('FlowChat history paging status interaction', () => { + it.each(['idle', 'loading', 'error'] as const)('exposes pointer interaction only for the %s recovery state', state => { + const style = document.createElement('style'); + style.textContent = css; + const boundary = document.createElement('div'); + boundary.className = 'virtual-message-list__history-paging-sentinel'; + boundary.dataset.historyPagingSentinel = state; + document.head.append(style); + document.body.append(boundary); + try { + const computed = getComputedStyle(boundary); + expect(computed.visibility).toBe(state === 'idle' ? 'hidden' : 'visible'); + // Programmatic button.click() bypasses pointer hit testing; the actual + // compiled stylesheet must make the recovery container reachable too. + expect(computed.pointerEvents).toBe(state === 'error' ? 'auto' : 'none'); + } finally { + boundary.remove(); + style.remove(); + } + }); +}); diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx index 63b3eefb60..361ae3379d 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.resize.test.tsx @@ -47,10 +47,17 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)' const heights = new Map(); const offsets = new WeakMap(); const px = (value: string) => Number.parseFloat(value || '0') || 0; - const reversed = (element: HTMLElement) => element.dataset.flowchatScrollOrigin === 'end'; - // Cache only within one synchronous geometry read. DOM/style and supplied - // row heights can change between any two reads, so no frame-level cache is safe. - function height(element: HTMLElement, measured = new WeakMap()): number { + const reversed = (element: HTMLElement) => element.getAttribute('data-flowchat-scroll-origin') === 'end'; + let geometryRead: WeakMap | null = null; + // Share measurements only within a read-only geometry snapshot. Each wheel, + // scroll, render and observer delivery must see fresh DOM/style/row heights. + function readGeometry(read: () => T): T { + if (geometryRead) return read(); + const previous = geometryRead; + geometryRead = new WeakMap(); + try { return read(); } finally { geometryRead = previous; } + } + function height(element: HTMLElement, measured = geometryRead ?? new WeakMap()): number { const cached = measured.get(element); if (cached !== undefined) return cached; const result = measureHeight(element, measured); @@ -59,8 +66,10 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)' } function measureHeight(element: HTMLElement, measured: WeakMap): number { if (element.hasAttribute('data-flowchat-scroller')) return viewportHeight; - if (element.dataset.virtualItemKey) return heights.get(element.dataset.virtualItemKey) ?? 100; - if (element.style.height) return px(element.style.height); + const itemKey = element.getAttribute('data-virtual-item-key'); + if (itemKey) return heights.get(itemKey) ?? 100; + const fixedHeight = element.style.height; + if (fixedHeight) return px(fixedHeight); const scroller = element.closest('[data-flowchat-scroller]'); if (scroller && reversed(scroller)) { const minimum = px(scroller.style.getPropertyValue('--_flow-chat-history-turn-min-height')); @@ -70,7 +79,7 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)' const natural = [...element.children].reduce((sum, child) => sum + height(child as HTMLElement, measured), 0); return Math.max(natural, minimum - preceding); } - if (element.dataset.historyTail === 'true') return Math.max(minimum, [...element.children].reduce((sum, child) => sum + height(child as HTMLElement, measured), 0)); + if (element.getAttribute('data-history-tail') === 'true') return Math.max(minimum, [...element.children].reduce((sum, child) => sum + height(child as HTMLElement, measured), 0)); } return Math.max(element.classList.contains('virtual-message-list__extent') && reversed(element.parentElement!) ? 600 : px(element.style.minHeight), px(element.style.paddingTop) + px(element.style.paddingBottom) + [...element.children].reduce((sum, child) => sum + height(child as HTMLElement, measured), 0)); @@ -148,18 +157,22 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)' return Math.round(this.hasAttribute('data-flowchat-scroller') ? height(this.firstElementChild as HTMLElement) : height(this)); }); vi.spyOn(HTMLElement.prototype, 'scrollTop', 'get').mockImplementation(function () { - const range = Math.max(0, this.scrollHeight - this.clientHeight); - return reversed(this) ? Math.max(-range, Math.min(0, offsets.get(this) ?? 0)) : Math.min(offsets.get(this) ?? 0, range); + return readGeometry(() => { + const range = Math.max(0, this.scrollHeight - this.clientHeight); + return reversed(this) ? Math.max(-range, Math.min(0, offsets.get(this) ?? 0)) : Math.min(offsets.get(this) ?? 0, range); + }); }); vi.spyOn(HTMLElement.prototype, 'scrollTop', 'set').mockImplementation(function (value) { const range = Math.max(0, this.scrollHeight - this.clientHeight); offsets.set(this, reversed(this) ? Math.max(-range, Math.min(0, value)) : Math.max(0, Math.min(value, range))); }); vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function () { - const measured = new WeakMap(); - const scroller = this.closest('[data-flowchat-scroller]'); - const top = this === scroller ? 0 : contentTop(this, measured) - (scroller?.scrollTop ?? 0); - return { x: 0, y: top, left: 0, right: 900, top, bottom: top + height(this, measured), height: height(this, measured), width: this.classList.contains('virtual-item-wrapper') ? columnWidth : 900, toJSON() {} }; + return readGeometry(() => { + const measured = geometryRead!; + const scroller = this.closest('[data-flowchat-scroller]'); + const top = this === scroller ? 0 : contentTop(this, measured) - (scroller?.scrollTop ?? 0); + return { x: 0, y: top, left: 0, right: 900, top, bottom: top + height(this, measured), height: height(this, measured), width: this.classList.contains('virtual-item-wrapper') ? columnWidth : 900, toJSON() {} }; + }); }); state.items = turn('latest', 180); state.session = { sessionId: 'history-session', config: {}, dialogTurns: [], isHistorical: false } as unknown as Session; @@ -220,9 +233,12 @@ describe('settled transcript resizing (real controllers, supplied DOM geometry)' render(); for (let frame = 0; frame < 30; frame++) { resize(); tick(); } const scroller = host.querySelector('[data-flowchat-scroller]')!; - const visibleRows = () => new Map([...host.querySelectorAll('.virtual-item-wrapper[data-virtual-item-key]')] - .map(row => [row.dataset.virtualItemKey!, row.getBoundingClientRect().top - scroller.getBoundingClientRect().top] as const) - .filter(([, top]) => top > -400 && top < viewportHeight)); + const visibleRows = () => readGeometry(() => { + const scrollerTop = scroller.getBoundingClientRect().top; + return new Map([...host.querySelectorAll('.virtual-item-wrapper[data-virtual-item-key]')] + .map(row => [row.getAttribute('data-virtual-item-key')!, row.getBoundingClientRect().top - scrollerTop] as const) + .filter(([, top]) => top > -400 && top < viewportHeight)); + }); const unexplained: string[] = []; for (const delta of [...Array(40).fill(-260), ...Array(40).fill(260)]) { const before = visibleRows(); diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss index 8358117d1f..b5308f1fff 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.scss @@ -198,6 +198,10 @@ visibility: visible; } + &[data-history-paging-sentinel='error'] { + pointer-events: auto; + } + // A page that arrives quickly never flashes its spinner. &[data-history-paging-sentinel='loading'] > * { animation: history-paging-reveal 160ms ease-out 200ms both; 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 5b8ee4ec06..9a7986f089 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.test.ts @@ -8285,6 +8285,47 @@ describe('FlowChatStore reconcile snapshot content safety', () => { expect(apiMocks.restoreSessionView).not.toHaveBeenCalled(); }); + it('resynchronizes an obsolete complete catalog from a fresh windowed host catalog', async () => { + await hydrateSessionWithContent(); + const obsolete = createTurnCatalog(1, 'obsolete'); + flowChatStore.setState(previous => ({ + ...previous, + sessions: new Map(previous.sessions).set('history-1', { + ...previous.sessions.get('history-1')!, turnCatalog: obsolete, + }), + })); + const fresh = { ...createTurnCatalog(80, 'restored'), complete: false }; + const snapshot = { + session: { ...hostSession(), turnCount: 80 }, + turns: [createPersistedTurn(79)], turnCatalog: fresh, contextRestoreState: 'ready', + }; + apiMocks.restoreSessionView.mockResolvedValueOnce(snapshot); + await flowChatStore.refreshPeerSessionSnapshot('history-1'); + expect(flowChatStore.getState().sessions.get('history-1')?.turnCatalog).toBe(obsolete); + apiMocks.restoreSessionView.mockResolvedValueOnce(snapshot); + const synchronized = await flowChatStore.synchronizeSessionHistory('history-1'); + expect(synchronized.applied).toBe(true); + expect(flowChatStore.getState().sessions.get('history-1')?.turnCatalog).toBe(fresh); + expect(flowChatStore.getSessionHistoryViewState('history-1')?.catalog).toBe(fresh); + }); + + it('retains complete previews when history synchronization confirms the same catalog revision', async () => { + await hydrateSessionWithContent(); + const complete = createTurnCatalog(1, 'unchanged'); + flowChatStore.setState(previous => ({ + ...previous, + sessions: new Map(previous.sessions).set('history-1', { + ...previous.sessions.get('history-1')!, turnCatalog: complete, + }), + })); + apiMocks.restoreSessionView.mockResolvedValueOnce({ + session: hostSession(), turns: [createPersistedTurn(0)], + turnCatalog: { ...complete, complete: false }, contextRestoreState: 'ready', + }); + await flowChatStore.synchronizeSessionHistory('history-1'); + expect(flowChatStore.getState().sessions.get('history-1')?.turnCatalog).toBe(complete); + }); + it('keeps a hydrated turn when a wholesale replace snapshot carries none of its work', async () => { // The reported failure: after switching device away and back, the rebuilt // projection has no state machines, so every turn reads as idle and every diff --git a/src/web-ui/src/flow_chat/store/FlowChatStore.ts b/src/web-ui/src/flow_chat/store/FlowChatStore.ts index 00035e0c34..58543d0022 100644 --- a/src/web-ui/src/flow_chat/store/FlowChatStore.ts +++ b/src/web-ui/src/flow_chat/store/FlowChatStore.ts @@ -9008,6 +9008,7 @@ export class FlowChatStore { requireActiveSession: true, shouldApply, shouldReplayRuntimeSnapshot: () => false, + synchronizeHistoryCatalog: true, }); if (!result.applied && shouldApply?.() !== false && this.state.sessions.get(sessionId) !== session) { throw new Error('Session history changed during source synchronization'); @@ -9029,6 +9030,8 @@ export class FlowChatStore { requireActiveSession?: boolean; shouldApply?: () => boolean; shouldReplayRuntimeSnapshot?: (snapshot: SessionRuntimeEventSnapshot) => boolean; + /** Explicit recovery accepts a new host revision even if its previews are incomplete. */ + synchronizeHistoryCatalog?: boolean; }, ): Promise { const scope = getActiveSurfaceScope(); @@ -9237,7 +9240,10 @@ export class FlowChatStore { } } const turnCatalog = restored.turnCatalog?.sessionId === sessionId - ? selectPreferredTurnCatalog(session.turnCatalog, restored.turnCatalog) + ? options?.synchronizeHistoryCatalog + && session.turnCatalog?.revision !== restored.turnCatalog.revision + ? restored.turnCatalog + : selectPreferredTurnCatalog(session.turnCatalog, restored.turnCatalog) : session.turnCatalog; const restoredAgentType = resolveRestoredAgentType( restored.session.agentType, session.mode, session.config.agentType,