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 99781ac431..9aa9880d4e 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 @@ -641,9 +641,17 @@ first, then restores that row-and-offset relationship through `viewportOwner.shift` and opens the ordinary anchor settle window so later measurements keep it stable. -The saved `scrollTop` is only a materialization hint when the anchor Turn has -not entered the rendered virtual window yet. It is never the final answer: once -the Turn exists in the DOM, its semantic offset is authoritative. A snapshot +When the exact row has not entered the rendered window, restoration measures +the mounted rows, resolves the saved key in the current virtualizer, and uses +its current bounds plus the saved intra-row offset to materialize it. That first +placement stays within the estimated row when the saved offset exceeds the +estimate; otherwise a long answer could remain outside the mounted window. It then +publishes the actual offset back to window selection without waiting for a +native scroll event. Repeatedly using the old absolute `scrollTop` can select a +different Turn indefinitely because a remount starts with a new measurement +cache. The saved absolute offset remains a compatibility fallback when the key +cannot be resolved. Once the row exists in the DOM, its semantic offset is +authoritative. A snapshot whose reader was away from the tail also suppresses the session-open tail follow, including when the reader was using the ordinary tail projection rather than an explicit history window. Snapshot publication remains gated until that 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 43d3deb783..bf45388ff2 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 @@ -49,6 +49,7 @@ each missing what the other had. | `flowChatLiveTailWindow.test.ts` | "does the transcript still reach the newest Turn" | | `flowChatViewportAnchor.test.ts` | anchor geometry and the DOM contract | | `useFlowChatViewportAnchor.test.tsx` | capture, restore, carry, the settle window | +| `useFlowChatLeadingExtent.test.tsx` | shared event geometry without repeated rectangle reads; fresh layout reads after resize and collection | | `VirtualMessageList.session-boundary.test.tsx` | prepend compensation, consecutive paging with/without queued input, passive scroll suppression, navigation-target current Turn with gesture/follow/session handoff, search placement only outside the readable viewport, and real viewport-register acknowledgement before trajectory details/highlights commit for user/search/model/folded-tool/history targets | | `flowChatScrollbarMask.test.ts`, `VirtualMessageList.session-boundary.test.tsx` | idle gutter masking with symmetric, one-sided and overlay scrollbars; overflow restoration and content/viewport resizing without scroll writes; supplied DOM geometry, not native rendering or live remote evidence | | `FlowChatOpeningBoundary.test.tsx` | opening-only activation/scroll isolation, bidirectional focus skipping, programmatic focus return, and reveal cleanup; DOM contracts only | @@ -57,7 +58,7 @@ each missing what the other had. | `useFlowChatVirtualizer.test.ts` | the offsets-and-positions boundary | | `useFlowChatVirtualizer.measurement.test.tsx` | `measureRenderedItems` against a real virtualizer | | `useFlowChatVirtualizer.cascade.test.tsx` | bounded synchronous measurement notifications, cross-frame convergence, ordinary synchronous opening, reader takeover and StrictMode/session cleanup; real hooks with supplied geometry, not native paint evidence | -| `useFlowChatVirtualizer.initial-window.test.tsx` | tail-first window, empty hydration, head default, one-time seed, user-scroll takeover, opening readbacks before native events, suspended viewport, measured-window reconciliation with delayed scroll/scroll-end delivery; supplied DOM geometry, not performance validation | +| `useFlowChatVirtualizer.initial-window.test.tsx` | tail-first window, empty hydration, head default, one-time seed, user-scroll takeover, newly attached rows measured during gestures before observer delivery, smooth-aim target stability and immediate measurement on reader takeover, opening readbacks before native events, suspended viewport, measured-window reconciliation with delayed scroll/scroll-end delivery; supplied DOM geometry, not performance validation | | `useFlowChatVirtualizer.aim.test.tsx` | the re-aim, and giving it up on takeover | | `VirtualMessageList.layout.test.ts` | the item-height estimate and the spacer | | `FlowChatTurnRail.test.tsx` | single-marker emphasis, neighboring hover fan, independent keyboard focus, reduced motion, and rail navigation | @@ -74,6 +75,34 @@ each missing what the other had. | `SessionTreePopover.test.tsx` | Agent selection/cancellation/deletion menus, type-only metadata, active branch filtering with ancestor retention, restoring all agents, and the active empty state | | `../../services/deleteSessionTreeBranch.test.ts` | Unloaded descendant deletion in child-first order, remote location forwarding, failure retention, and device surface guards | +## Native history-scroll fixture + +When UI verification is authorized, build Desktop and current frontend assets, +then run the focused command documented in `tests/e2e/AGENTS.md`: + +```bash +pnpm --dir tests/e2e exec wdio run ./config/wdio.flowchat-scroll-native.ts +``` + +The isolated packaged-app fixture opens an 80-Turn transcript, drives slow and +fast wheel actions in both directions, and records per-frame continuity, +rectangle reads, DOM scans and mounted rows. Reversals over 4px, empty frames, +post-gesture drift, lost session reading position, lost draft text and failed +search navigation are assertions. Frame intervals are diagnostic measurements, +not hard timing gates on shared machines. JSON evidence and a screenshot remain +in the printed temporary directory. `OPENBITFUN_SCROLL_DIAGNOSTICS=1` additionally +captures per-frame row geometry and scroll-write stacks; use it for attribution, +not timing comparisons. + +The embedded driver dispatches wheel input and updates the native WebView's +scroll offset. It does not reproduce OS trackpad inertia. This fixture does not +establish physical input comfort, live streaming/model transport, remote +workspace, remote control, Peer Device, or detached-dispatch behavior. Existing +follow-output, navigation, owner and session-boundary unit tests cover those +local state-machine contracts separately. The session-boundary suite also +covers measurement-shift credit and restoration when a saved key is unmounted +and its former absolute pixel position is obsolete. + ## Manual For content-width resizing, check both edge hit areas, subtle hover/focus paint, diff --git a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md index 8776843644..6548b84ae5 100644 --- a/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md +++ b/src/web-ui/src/flow_chat/components/modern/FLOWCHAT_VIRTUALIZATION.md @@ -1,5 +1,51 @@ # FlowChat Virtualization +## Historical scrolling and measurement + +Manual scrolling keeps the host's native wheel/touch behavior. Perceived +smoothness depends on stable content coordinates as well as frame time; adding +an easing loop to a height correction would expose the correction as motion. +The implementation follows the read-before-write guidance in +[rendering performance](https://web.dev/articles/rendering-performance) and +[layout thrashing](https://web.dev/articles/avoid-large-complex-layouts-and-layout-thrashing). +No new motion is introduced, so the existing reduced-motion policy and follow +targets remain unchanged. + +Newly attached rows are measured as one batch in the layout phase, including +while the reader is scrolling. The library's `measureElement` still registers +observation, but it skips its inline size update during a gesture; the adapter +therefore supplies the already-read height through `resizeItem` in that commit. +In this flow layout the real row heights affect following content immediately. +Waiting for ResizeObserver lets the old virtual padding and real rows disagree +for a visible frame. + +Explicit item/offset aims retain the library's own attachment-measurement policy. +A smooth aim intentionally leaves distant rows estimated: forcing their sizes +can move its target and make the library replace the animation with an `auto` +jump. Reader intent cancels the aim before scrolling, so newly attached rows +resume synchronous measurement in the first reader-controlled commit. + +Above-viewport measurement shifts pass through the viewport register and credit +the DOM anchor with the **actual applied** displacement. Otherwise the anchor +counts that repair as reader travel and applies it again. The anchor remains +independent of the virtualizer; the list joins these two owners. + +The native scroll handler shares one `flowChatViewportGeometry` sample among +leading-extent, anchor and session-snapshot readers. It is local to that event, +and discarded if a follow write changes the offset. Layout commits, resize and +navigation read fresh geometry; this is not a cross-frame cache. + +The packaged macOS WebView fixture (80 Turns with Markdown, code, tables and +collapsed tool groups) reproduced 17 reverse frames during 72 fast upward wheel +actions, with a maximum 499.45px reversal. After these changes the same five +slow/fast bidirectional phases had zero reversals over 4px and zero blank frames; +row/scroller rectangle reads fell from 37,331 to 28,489 across those phases. +Fast-up frame intervals still reached 26ms at p95 and 53ms at maximum in the +final run; continuity is established here, not a constant 60fps guarantee. +These are instrumented native-WebView samples, not physical trackpad or +cross-platform latency measurements. See `FLOWCHAT_VERIFICATION.md` for the +repeatable fixture and its limits. + ## Accepted steering display The host queue's optional `steeringDisplay` receipt projects an accepted message diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx index 03e7ddb1b5..83b281b1a2 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.session-boundary.test.tsx @@ -52,6 +52,8 @@ const mocks = vi.hoisted(() => ({ estimateWidth: undefined as number | undefined, estimateRevision: '', reconcileOpeningMeasurement: null as null | (() => boolean), + shiftMeasurement: null as null | ((delta: number) => boolean), + virtualizerKeys: [] as string[], placeSubmittedMessage: null as null | ((intent: SubmittedMessageScrollIntent) => number | null), readLayoutTarget: null as null | (() => number), /** @@ -149,6 +151,7 @@ vi.mock('./useFlowChatVirtualizer', async () => { scrollerRef: { current: HTMLElement | null }; startAtTailOnMount?: boolean; reconcileOpeningMeasurement?: () => boolean; + shiftViewport?: (delta: number) => boolean; estimateContext?: { availableWidthPx?: number }; estimateContextRevision?: string; }) => { @@ -156,12 +159,14 @@ vi.mock('./useFlowChatVirtualizer', async () => { mocks.estimateWidth = options.estimateContext?.availableWidthPx; mocks.estimateRevision = options.estimateContextRevision ?? ''; mocks.reconcileOpeningMeasurement = options.reconcileOpeningMeasurement ?? null; + mocks.shiftMeasurement = options.shiftViewport ?? null; const rows = options.items.map((item, index) => ({ index, key: options.getItemKey(item), startPx: index * 40, endPx: index * 40 + 40, })); + mocks.virtualizerKeys = rows.map(row => row.key); return { rows, paddingTopPx: 0, @@ -468,6 +473,35 @@ describe('VirtualMessageList natural scroll contract', () => { expect(mocks.reconcileOpeningMeasurement?.()).toBe(false); }); + it('does not compensate an above-viewport measurement twice before its scroll event arrives', async () => { + const restore = fakeLayout({ clientHeight: 800, scrollHeight: 4000, turnTopFromScrollerTop: 100 }); + try { + act(() => root.render()); + await settleOpenReveal(); + const scroller = container.querySelector('[data-flowchat-scroller]')!; + const rows = [...scroller.querySelectorAll('.virtual-item-wrapper')]; + let contentTop = 1100; + rows.forEach((row, index) => { + row.getBoundingClientRect = () => ({ top: contentTop + index * 80 - scroller.scrollTop, + bottom: contentTop + index * 80 + 60 - scroller.scrollTop, height: 60, + left: 0, right: 800, width: 800 }) as DOMRect; + }); + act(() => { + scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -100, bubbles: true })); + scroller.scrollTop = 1000; + scroller.dispatchEvent(new Event('scroll')); + }); + // Resize and its registered compensation precede native scroll delivery. + contentTop -= 120; + act(() => { expect(mocks.shiftMeasurement!(-120)).toBe(true); }); + expect(scroller.scrollTop).toBe(880); + act(() => { resizeObservers.forEach(observer => observer.notify()); }); + await settleOpenReveal(); + expect(scroller.scrollTop).toBe(880); + expect(rows[0].getBoundingClientRect().top).toBe(100); + } finally { restore(); } + }); + it('crops only idle gutter paint across content and viewport resizing without moving the reader', () => { const layout = { clientWidth: 986, clientHeight: 800, scrollHeight: 800, turnTopFromScrollerTop: 0 }; const restoreLayout = fakeLayout({ ...layout, scrollHeight: () => layout.scrollHeight }); @@ -2157,6 +2191,46 @@ describe('VirtualMessageList natural scroll contract', () => { } }); + it.each([-80, -800])('materializes a saved row at offset %s even when its new estimate is shorter', offset => { + mocks.items = [ + userMessage('turn-1', 'message-1', 'Question'), + modelRound('turn-1', 'round-1', 'Long answer'), + ]; + const listRef = React.createRef(); + const restoreLayout = fakeLayout({ clientHeight: 600, scrollHeight: 2000, turnTopFromScrollerTop: 0 }); + try { + act(() => root.render()); + const scroller = container.querySelector('[data-flowchat-scroller]')!; + const row = container.querySelector('.virtual-item-wrapper[data-item-type="model-round"]')!; + const index = Number(row.dataset.virtualIndex); + // This mock renderer normally keeps legacy keys. Match the production + // renderer's timeline key for the unmounted-item lookup under test. + row.dataset.virtualItemKey = mocks.virtualizerKeys[index]; + const parent = row.parentElement!; + const next = row.nextSibling; + const snapshot = { + sessionId: 'session-1', presentationMode: 'tail' as const, viewportMode: 'live-tail' as const, + historyWindow: null, anchorTurnId: 'turn-1', anchorItemKey: row.dataset.virtualItemKey!, + anchorOffsetPx: offset, scrollTopPx: 1400, isAtTail: false, capturedAtMs: 1, + }; + row.remove(); + try { + act(() => { expect(listRef.current?.restoreViewportSnapshot(snapshot)).toBe(false); }); + // Materialize inside the current 40px estimate, even when the saved + // reading position was hundreds of pixels into this same answer. + expect(scroller.scrollTop).toBe(index * 40 + 39); + } finally { + parent.insertBefore(row, next); + } + scroller.getBoundingClientRect = () => new DOMRect(0, 0, 1000, 600); + row.getBoundingClientRect = () => new DOMRect(0, index * 40 - scroller.scrollTop, 1000, 900); + act(() => { expect(listRef.current?.restoreViewportSnapshot(snapshot)).toBe(true); }); + expect(scroller.scrollTop).toBe(index * 40 - offset); + } finally { + restoreLayout(); + } + }); + it('materializes and restores a saved reading position without starting tail follow', async () => { const listRef = React.createRef(); const initialViewportSnapshot = { diff --git a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx index f66861fb56..3b9b608f35 100644 --- a/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx +++ b/src/web-ui/src/flow_chat/components/modern/VirtualMessageList.tsx @@ -56,6 +56,7 @@ import { useFlowChatFollowOutput } from './useFlowChatFollowOutput'; import { FlowChatScrollIntent, FlowChatTouchIntent, flowChatKeyScrollDirection, isFlowChatScrollbarPress } from './flowChatScrollIntent'; import { findRenderedTurnAnchorElement } from './flowChatViewportAnchor'; import { useFlowChatViewportAnchor } from './useFlowChatViewportAnchor'; +import { readFlowChatViewportGeometry, type FlowChatViewportGeometry } from './flowChatViewportGeometry'; import { useFlowChatLeadingExtent } from './useFlowChatLeadingExtent'; import { syncFlowChatScrollbarMask } from './flowChatScrollbarMask'; import { @@ -535,6 +536,18 @@ const VirtualMessageListSession = forwardRef boolean>(() => false); + const absorbMeasurementShiftRef = useRef<(byPx: number) => void>(() => {}); + const shiftMeasuredViewport = useCallback((byPx: number) => { + const scroller = scrollerElementRef.current; + if (!scroller) return false; + const before = scroller.scrollTop; + const applied = viewportOwner.shift(byPx); + // A measured row above the reader already moved both the content and the + // viewport. Credit that repair before the anchor's next settle, otherwise + // it mistakes the registered shift for reader travel and repairs it twice. + if (applied) absorbMeasurementShiftRef.current(scroller.scrollTop - before); + return applied; + }, [viewportOwner]); const isExpandingSearchSourceRef = useRef(false); const readerInteractionRef = useRef<(kind: TimelineReaderInteraction) => void>(() => {}); const interactionKeys = useTimelineInteraction(scrollerElementRef, reader, () => viewportOwner.currentOwner() === 'follow-output', undefined, kind => readerInteractionRef.current(kind)); @@ -573,7 +586,7 @@ const VirtualMessageListSession = forwardRef virtualItems @@ -798,6 +811,7 @@ const VirtualMessageListSession = forwardRef { + const captureViewportSnapshot = useCallback((sample?: FlowChatViewportGeometry): FlowChatViewportSnapshot | null => { const scroller = scrollerElementRef.current; if (!scroller || !activeSessionId || !isUsableFlowChatViewportRect({ width: scroller.clientWidth, @@ -1085,50 +1099,39 @@ const VirtualMessageListSession = forwardRef('.virtual-item-wrapper[data-turn-id]'), - ).map(element => { - const rect = element.getBoundingClientRect(); - return { - element, - turnId: element.dataset.turnId ?? null, - itemType: element.dataset.itemType ?? null, - itemKey: element.dataset.virtualItemKey ?? null, - top: rect.top, - bottom: rect.bottom, - }; - }); - const anchorEntry = entries.find(entry => ( - entry.bottom > scrollerRect.top && entry.top < scrollerRect.bottom + const geometry = sample ?? readFlowChatViewportGeometry(scroller); + const anchorEntry = geometry.rows.find(entry => ( + entry.turnId !== null && entry.bottom > geometry.top && entry.top < geometry.bottom )); const anchorTurnId = anchorEntry?.turnId ?? null; - const anchorElement = anchorEntry?.element; - const anchorRect = anchorElement?.getBoundingClientRect(); return { sessionId: activeSessionId, presentationMode, viewportMode, historyWindow, - anchorItemKey: anchorEntry?.itemKey ?? null, + anchorItemKey: anchorEntry?.key ?? null, anchorItemType: anchorEntry?.itemType ?? null, anchorTurnId, - anchorOffsetPx: anchorRect - ? Math.round((anchorRect.top - scrollerRect.top) * 10) / 10 + anchorOffsetPx: anchorEntry + ? Math.round((anchorEntry.top - geometry.top) * 10) / 10 : null, - scrollTopPx: Math.round(scroller.scrollTop * 10) / 10, + scrollTopPx: Math.round(geometry.scrollTop * 10) / 10, isAtTail: isAtTailRef.current, capturedAtMs: Math.round(performance.now()), }; }, [activeSessionId, historyWindow, presentationMode, viewportMode]); + const snapshotVirtualizerRef = useRef(virtualizer); + snapshotVirtualizerRef.current = virtualizer; const restoreViewportSnapshot = useCallback((snapshot: FlowChatViewportSnapshot): boolean => { if (snapshot.sessionId !== activeSessionId) return false; const scroller = scrollerElementRef.current; if (!scroller || snapshot.anchorTurnId === null || snapshot.anchorOffsetPx === null) { return false; } + const currentVirtualizer = snapshotVirtualizerRef.current; + currentVirtualizer.measureRenderedItems(); const exactAnchor = snapshot.anchorItemKey ? Array.from( scroller.querySelectorAll('.virtual-item-wrapper[data-virtual-item-key]'), @@ -1146,10 +1149,21 @@ const VirtualMessageListSession = forwardRef= 0 ? currentVirtualizer.getItemBounds(exactAnchorIndex) : null; + // A long answer's saved intra-row offset can exceed its new estimate. + // Keep the first placement inside that estimate so the row actually + // mounts; its measured geometry supplies the full offset on the retry. + const targetPx = bounds + ? Math.min(bounds.startPx - snapshot.anchorOffsetPx, Math.max(bounds.startPx, bounds.endPx - 1)) + : snapshot.scrollTopPx; + const materializeByPx = targetPx - scroller.scrollTop; if (Math.abs(materializeByPx) > 0.5) { viewportOwner.shift(materializeByPx); } + currentVirtualizer.syncViewportOffset(scroller.scrollTop); return false; } const currentOffsetPx = anchor.getBoundingClientRect().top - scroller.getBoundingClientRect().top; @@ -1165,8 +1179,8 @@ const VirtualMessageListSession = forwardRef { - const snapshot = captureViewportSnapshot(); + const publishViewportSnapshot = useCallback((sample?: FlowChatViewportGeometry) => { + const snapshot = captureViewportSnapshot(sample); if (snapshot) onViewportSnapshotRef.current?.(snapshot); }, [captureViewportSnapshot]); @@ -1440,6 +1454,9 @@ const VirtualMessageListSession = forwardRef { if (isViewportSuspendedRef.current) return; + // Share this event's read phase. It cannot outlive the event: commits, + // ResizeObserver and explicit navigation must measure their own layout. + const geometry = readFlowChatViewportGeometry(scrollerElement); const position = viewportOwner.readReaderScrollPosition(); const previous = readerScrollPositionRef.current; readerScrollPositionRef.current = position; @@ -1449,10 +1466,10 @@ const VirtualMessageListSession = forwardRef; +} + +/** Do not retain across events/commits: rows can reflow without a scroll. */ +export function readFlowChatViewportGeometry(scroller: HTMLElement): FlowChatViewportGeometry { + const rect = scroller.getBoundingClientRect(); + return { + scroller, top: rect.top, bottom: rect.bottom, + scrollTop: scroller.scrollTop, height: scroller.clientHeight, + rows: Array.from(scroller.querySelectorAll('.virtual-item-wrapper')).map(element => { + const bounds = element.getBoundingClientRect(); + return { element, key: element.dataset.virtualItemKey, turnId: element.dataset.turnId ?? null, + itemType: element.dataset.itemType ?? null, top: bounds.top, bottom: bounds.bottom }; + }), + }; +} diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.test.tsx b/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.test.tsx index 45ef874957..df427cd1f5 100644 --- a/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.test.tsx @@ -6,6 +6,7 @@ import type { VirtualItem } from '../../store/modernFlowChatStore'; import { useFlowChatLeadingExtent } from './useFlowChatLeadingExtent'; import { getVirtualItemStableKey } from './virtualItemIdentity'; import { readingLinePxForViewport } from './flowChatTailFollow'; +import { readFlowChatViewportGeometry } from './flowChatViewportGeometry'; globalThis.IS_REACT_ACT_ENVIRONMENT = true; @@ -49,6 +50,25 @@ function setup() { } describe('desktop leading extent lifecycle', () => { + it('reuses the current scroll read phase without measuring rows again', () => { + const view = setup(); + const row = document.createElement('div'); + row.className = 'virtual-item-wrapper'; row.dataset.virtualItemKey = 'block:member'; + let top = 2040; + const read = vi.fn(() => ({ top: top - view.scroller.scrollTop, + bottom: top + 1200 - view.scroller.scrollTop, height: 1200 }) as DOMRect); + row.getBoundingClientRect = read; view.extent.append(row); + view.scroller.scrollTop = 2200; + const sample = readFlowChatViewportGeometry(view.scroller); + view.api.capture(2200, true, sample); + expect(read).toHaveBeenCalledTimes(1); + expect(view.api.snapshot()).toEqual({ key: 'block:member', offset: -160 }); + // Another layout transaction must read the new geometry, not that sample. + top += 80; + view.api.refresh(1000); + expect(read).toHaveBeenCalledTimes(2); + expect(view.extent.style.minHeight).toBe('3080px'); + }); it.each([-2, -0.25, 0.25, 2])('does not turn a stable %s px cache/DOM difference into repeated travel', difference => { const view = setup(); view.layout([item('header', 'group-header'), item('after')], diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.ts b/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.ts index 5fa41c7144..e8df02b5e7 100644 --- a/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.ts +++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatLeadingExtent.ts @@ -4,6 +4,7 @@ import type { FlowChatVirtualizer } from './useFlowChatVirtualizer'; import { getVirtualItemStableKey } from './virtualItemIdentity'; import { leadingExtentFloor } from './flowChatLeadingExtent'; import { FLOWCHAT_TURN_TOP_GAP_PX } from './flowChatTailFollow'; +import { readFlowChatViewportGeometry, type FlowChatViewportGeometry } from './flowChatViewportGeometry'; type Virtualizer = Pick; type Bounds = { startPx: number; endPx: number }; @@ -53,21 +54,21 @@ export function useFlowChatLeadingExtent(options: { const value = floor === null ? '' : `${floor + scroller.clientHeight}px`; if (extent.style.minHeight !== value) extent.style.minHeight = value; }, [extentRef, scrollerRef]); - const measureLayout = useCallback(() => { + const measureLayout = useCallback((sample?: FlowChatViewportGeometry) => { const scroller = scrollerRef.current; if (!scroller) return; const measured = new Map(); - const origin = scroller.scrollTop - scroller.getBoundingClientRect().top; - for (const row of scroller.querySelectorAll('.virtual-item-wrapper[data-virtual-item-key]')) { + const geometry = sample ?? readFlowChatViewportGeometry(scroller); + const origin = geometry.scrollTop - geometry.top; + for (const { element: row, key, top, bottom } of geometry.rows) { + if (!key) continue; const viewport = row.closest('[data-flowchat-virtual-viewport], [data-flowchat-scroller]'); if (viewport && viewport !== scroller) continue; - const key = row.dataset.virtualItemKey!; const index = indexes.get(key); const cached = index === undefined ? null : virtualizer.getItemBounds(index); if (!cached) continue; - const rect = row.getBoundingClientRect(); - const startPx = origin + rect.top; - measured.set(key, { cached, mounted: { startPx, endPx: startPx + rect.height } }); + const startPx = origin + top; + measured.set(key, { cached, mounted: { startPx, endPx: origin + bottom } }); } // Bounded by mounted rows; keep only scalars, never DOM/content instances. current().measured = measured; @@ -86,11 +87,11 @@ export function useFlowChatLeadingExtent(options: { ? { key: getVirtualItemStableKey(items[groupIndex]), measurement } : undefined; }, [groupHeaders, items, measurementAt]); - const capture = useCallback((offset: number, exact = false) => { + const capture = useCallback((offset: number, exact = false, sample?: FlowChatViewportGeometry) => { const scroller = scrollerRef.current; if (!scroller?.clientHeight || !items.length) return; const s = current(); - if (exact) measureLayout(); + if (exact) measureLayout(sample); // Frames reuse the layout snapshot: no DOM traversal or row remeasure. let low = 0, high = items.length; while (low < high) { diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatViewportAnchor.ts b/src/web-ui/src/flow_chat/components/modern/useFlowChatViewportAnchor.ts index 240b76ae94..391f46ec9a 100644 --- a/src/web-ui/src/flow_chat/components/modern/useFlowChatViewportAnchor.ts +++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatViewportAnchor.ts @@ -27,6 +27,7 @@ */ import { useCallback, useEffect, useMemo, useRef, type RefObject } from 'react'; +import type { FlowChatViewportGeometry } from './flowChatViewportGeometry'; import { ANCHOR_CORRECTION_EPSILON_PX, ANCHOR_MISSING_TURN_ATTEMPTS, @@ -140,7 +141,7 @@ export interface FlowChatViewportAnchorApi { * movement is theirs and crediting it to the reader would drag the anchor * along with every follow and aim. */ - captureAnchorForScroll: () => void; + captureAnchorForScroll: (sample?: FlowChatViewportGeometry) => void; /** The user did something that scrolls, by their own hand. */ markUserScrollIntent: () => void; /** @@ -231,13 +232,17 @@ export function useFlowChatViewportAnchor({ missingTurnAttemptsRef.current = 0; }, []); - const captureAnchorAt = useCallback(() => { + const captureAnchorAt = useCallback((sample?: FlowChatViewportGeometry) => { const scroller = scrollerRef.current; if (!scroller) return; blockedGeometryRef.current = null; lastResizeGeometryRef.current = null; const next = selectViewportAnchor( - readViewportAnchorCandidates(scroller), + sample ? sample.rows.filter(row => row.key !== undefined || row.itemType === 'user-message').map(row => ({ + turnId: row.turnId, itemKey: row.key, + offsetFromScrollerTop: row.top - sample.top, + bottomOffsetFromScrollerTop: row.bottom - sample.top, + })) : readViewportAnchorCandidates(scroller), scroller.clientHeight, ); anchorRef.current = next; @@ -307,7 +312,7 @@ export function useFlowChatViewportAnchor({ }; }, []); - const captureAnchorForScroll = useCallback(() => { + const captureAnchorForScroll = useCallback((sample?: FlowChatViewportGeometry) => { const scroller = scrollerRef.current; if (!scroller) return; if (missingTurnAttemptsRef.current > 0) { @@ -316,7 +321,7 @@ export function useFlowChatViewportAnchor({ } const msSinceUserScrollIntent = performance.now() - lastUserScrollIntentAtRef.current; if (shouldCaptureViewportAnchorOnScroll(anchorRef.current !== null, msSinceUserScrollIntent)) { - captureAnchorAt(); + captureAnchorAt(sample); return; } /* diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx index 19b5d8af98..3830e62dbd 100644 --- a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx +++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.initial-window.test.tsx @@ -7,6 +7,7 @@ import { useFlowChatVirtualizer, type FlowChatVirtualizer } from './useFlowChatV globalThis.IS_REACT_ACT_ENVIRONMENT = true; const windows: number[][] = []; +const viewportWrites: Array<{ topPx: number; behavior?: ScrollBehavior }> = []; let latestApi: FlowChatVirtualizer; let reconcileEnabled = false; let shortOverscan = false; @@ -37,7 +38,8 @@ function Harness({ count, tail }: { count: number; tail: boolean }) { return true; }, scrollPaddingStartPx: 0, - writeViewport: ({ topPx }) => { + writeViewport: ({ topPx, behavior }) => { + viewportWrites.push({ topPx, behavior }); const element = scrollerRef.current; if (!element) return false; // Model a browser clamping a write while no rows have mounted yet. @@ -60,6 +62,7 @@ describe('initial virtual window with the real virtualizer', () => { let root: Root; beforeEach(() => { windows.length = 0; + viewportWrites.length = 0; reconcileEnabled = false; shortOverscan = false; viewportSuspended = false; @@ -122,6 +125,84 @@ describe('initial virtual window with the real virtualizer', () => { expect(first.at(-1)).toBe(33); }); + it('measures newly mounted rows during a gesture before ResizeObserver delivers', () => { + render(100, false); + const firstWindow = new Set(windows.at(-1)); + const scroller = host.querySelector('[data-scroller]')!; + act(() => { + scroller.scrollTop = 4000; + scroller.dispatchEvent(new Event('scroll')); + }); + const arrived = windows.at(-1)!.filter(index => !firstWindow.has(index)); + expect(arrived.length).toBeGreaterThan(0); + // No observer delivery or animation frame: the first scrolling commit + // must already agree with the rows' actual heights, not their estimates. + for (const index of arrived) { + const bounds = latestApi.getItemBounds(index)!; + expect(bounds.endPx - bounds.startPx).toBe(80); + } + }); + + it('keeps a smooth aim stable and resumes immediate measurement on reader takeover', () => { + // A short Turn header precedes an answer taller than the viewport. While + // returning to that mounted header, earlier overscan rows enter the window. + vi.spyOn(HTMLElement.prototype, 'offsetHeight', 'get').mockImplementation(function () { + if (this.hasAttribute('data-scroller')) return 500; + if (!this.hasAttribute('data-virtual-index')) return 0; + return Number(this.getAttribute('data-virtual-index')) === 40 ? 3000 : 80; + }); + render(100, false); + const scroller = host.querySelector('[data-scroller]')!; + act(() => { + scroller.scrollTop = 4000; + scroller.dispatchEvent(new Event('scroll')); + }); + act(() => latestApi.measureRenderedItems()); + act(() => { + scroller.scrollTop = 5200; + scroller.dispatchEvent(new Event('scroll')); + }); + const target = 39; + expect(host.querySelector(`[data-virtual-index="${target}"]`)).not.toBeNull(); + const targetStart = latestApi.getItemBounds(target)!.startPx; + const beforeAim = new Set(windows.at(-1)); + const pendingFrames: FrameRequestCallback[] = []; + vi.mocked(requestAnimationFrame).mockImplementation(callback => { + pendingFrames.push(callback); + return pendingFrames.length + 100; + }); + viewportWrites.length = 0; + act(() => latestApi.scrollItemIntoView(target, { + align: 'start', behavior: 'smooth', owner: 'one-shot-navigation', + })); + // Deliver an in-flight native animation offset, without a reader gesture + // or ResizeObserver delivery. The adapter must preserve the library's + // smooth-scroll measurement policy for newly mounted overscan rows. + act(() => { + scroller.scrollTop = targetStart + 20; + scroller.dispatchEvent(new Event('scroll')); + }); + expect(windows.at(-1)!.some(index => index < target && !beforeAim.has(index))).toBe(true); + for (const callback of pendingFrames.splice(0)) act(() => callback(16)); + expect(latestApi.getItemBounds(target)!.startPx).toBe(targetStart); + expect(viewportWrites).toEqual([{ topPx: targetStart, behavior: 'smooth' }]); + + // The ordinary intent handler cancels the aim before reader scrolling. + // New rows must still be measured synchronously in that first commit. + const beforeTakeover = new Set(windows.at(-1)); + act(() => { + latestApi.cancelAim(); + scroller.scrollTop = 8000; + scroller.dispatchEvent(new Event('scroll')); + }); + const arrived = windows.at(-1)!.filter(index => !beforeTakeover.has(index)); + expect(arrived.length).toBeGreaterThan(0); + for (const index of arrived) { + const bounds = latestApi.getItemBounds(index)!; + expect(bounds.endPx - bounds.startPx).toBe(80); + } + }); + it('preserves the default head window for history and reading restoration', () => { render(34, false); expect(windows.find(window => window.length)?.[0]).toBe(0); diff --git a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts index f8f8754c86..7c53c5191e 100644 --- a/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts +++ b/src/web-ui/src/flow_chat/components/modern/useFlowChatVirtualizer.ts @@ -752,7 +752,24 @@ export function useFlowChatVirtualizer({ if (!attached.length || isViewportSuspendedRef.current()) return; // Read before any viewport shift or size-cache notification can write. measurementBatchRef.current = new Map(attached.map(element => [element, element.offsetHeight])); - try { for (const element of attached) virtualizer.measureElement(element); } + try { + for (const element of attached) { + virtualizer.measureElement(element); + // Explicit aims keep the library's measurement policy. During smooth + // navigation it skips rows far from the target; forcing their sizes + // changes that target and makes the re-aim jump with 'auto' behavior. + // Reader takeover clears the aim before the next scrolling commit. + if (aimStartedAtMsRef.current !== null) continue; + // The library observes newly attached rows but skips their inline + // measurement during scrolling. In our flow layout their real heights + // already displace the following rows in this commit. Reconcile before + // paint, rather than showing the displacement until ResizeObserver. + const index = Number(element.getAttribute('data-virtual-index')); + if (Number.isInteger(index) && index >= 0 && index < itemsRef.current.length) { + virtualizer.resizeItem(index, measurementBatchRef.current.get(element)!); + } + } + } finally { measurementBatchRef.current = null; } }); diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md index fcf764ac48..4ccf46a486 100644 --- a/tests/e2e/AGENTS.md +++ b/tests/e2e/AGENTS.md @@ -38,6 +38,23 @@ pnpm --dir tests/e2e exec wdio run ./config/wdio.conf.ts --spec "./specs/. Prefer the narrowest relevant spec first, then broaden only if needed. +For historical FlowChat scroll continuity, build Desktop and current frontend +assets, then run: + +```bash +pnpm --dir tests/e2e exec wdio run ./config/wdio.flowchat-scroll-native.ts +``` + +This creates an isolated 80-Turn session, copies the completed packaged frontend, +and checks slow/fast bidirectional scrolling, reading-position restoration, +draft preservation and search navigation. The printed temporary directory keeps +`result.json`, per-phase frame data and screenshots. Set +`OPENBITFUN_E2E_FRONTEND_DIR` to a completed build with `frontend-revision.json`, +or `OPENBITFUN_E2E_WEBDRIVER_PORT` for a free driver port. Optional +`OPENBITFUN_SCROLL_DIAGNOSTICS=1` records row geometry and write stacks with +additional overhead. Wheel actions exercise the real WebView layout, not OS +trackpad inertia; local results do not establish remote or other-platform behavior. + For embedded WebDriver reveal/focus and shell scroll geometry, build Desktop and current frontend assets, then run: diff --git a/tests/e2e/config/wdio.flowchat-scroll-native.ts b/tests/e2e/config/wdio.flowchat-scroll-native.ts new file mode 100644 index 0000000000..e3a96dfd31 --- /dev/null +++ b/tests/e2e/config/wdio.flowchat-scroll-native.ts @@ -0,0 +1,37 @@ +import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import { join, resolve, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createEmbeddedConfig } from './embedded-driver'; + +const repo = resolve(dirname(fileURLToPath(import.meta.url)), '../../..'); +const root = process.env.OPENBITFUN_FLOWCHAT_SCROLL_EVIDENCE || realpathSync(mkdtempSync(join(tmpdir(), 'openbitfun-flowchat-scroll-'))); +const workspace = join(root, 'workspace'); +const home = join(root, 'home'); +const user = join(root, 'user'); +if (!existsSync(join(root, 'frontend'))) { + const source = resolve(process.env.OPENBITFUN_E2E_FRONTEND_DIR || join(repo, 'dist')); + const revision = readFileSync(join(source, 'frontend-revision.json'), 'utf8'); + cpSync(source, join(root, 'frontend'), { recursive: true }); + if (revision !== readFileSync(join(source, 'frontend-revision.json'), 'utf8')) throw new Error('Frontend changed during snapshot'); + mkdirSync(workspace, { recursive: true }); + writeFileSync(join(workspace, 'README.md'), '# FlowChat scroll fixture\n'); + const fixture = spawnSync(process.execPath, [join(repo, 'tests/e2e/scripts/generate-long-session-fixture.mjs'), + '--workspace', workspace, '--openbitfun-home', home, '--openbitfun-user-root', user, + '--session-prefix', 'scroll-history', '--session-count', '2', '--long-turns', '80', + '--assistant-chars', '4000', '--tool-items', '3', '--tool-result-chars', '6000', + ], { cwd: repo, windowsHide: true, encoding: 'utf8' }); + if (fixture.status !== 0) throw new Error(fixture.stderr || fixture.stdout); +} +Object.assign(process.env, { + OPENBITFUN_FLOWCHAT_SCROLL_EVIDENCE: root, + OPENBITFUN_E2E_STORAGE_ROOT: root, OPENBITFUN_E2E_HOME: home, OPENBITFUN_HOME: home, + OPENBITFUN_E2E_USER_ROOT: user, OPENBITFUN_USER_ROOT: user, + OPENBITFUN_E2E_LOG_DIR: join(root, 'logs'), OPENBITFUN_E2E_STORAGE_GUARD: '1', + OPENBITFUN_E2E_PACKAGED_FRONTEND: '1', OPENBITFUN_E2E_FRONTEND_DIR: join(root, 'frontend'), + E2E_TEST_WORKSPACE: workspace, + NO_PROXY: [process.env.NO_PROXY, '127.0.0.1', 'localhost', '::1'].filter(Boolean).join(','), +}); +console.log(`FlowChat scroll evidence: ${root}`); +export const config = createEmbeddedConfig(['../specs/flowchat-scroll-native.spec.ts'], 'FlowChat scroll'); diff --git a/tests/e2e/page-objects/FlowChatScrollPage.ts b/tests/e2e/page-objects/FlowChatScrollPage.ts new file mode 100644 index 0000000000..672ee789d5 --- /dev/null +++ b/tests/e2e/page-objects/FlowChatScrollPage.ts @@ -0,0 +1,159 @@ +import { $, browser } from '@wdio/globals'; + +export interface ScrollFrame { + time: number; + top: number; + height: number; + rows: number; + reverse: number; + blank: boolean; + anchor?: Array<{ key: string | undefined; top: number; height: number }>; +} +export interface ScrollProbe { + frames: ScrollFrame[]; + rectReads: number; + scans: number; + wheelEvents: number; + writes: Array<{ time: number; before: number; after: number; value: number; stack: string | undefined }>; +} + +/** Production transcript, driven through the embedded driver's wheel actions. */ +export class FlowChatScrollPage { + async openSession(id: string) { + const row = $(`[data-testid="nav-session-item"][data-session-id="${id}"]`); + await row.waitForExist({ timeout: 30000 }); + await row.click(); + await browser.waitUntil(async () => (await $('[data-testid="flowchat-message-list"]').getAttribute('data-open-viewport-settled')) === 'true', { timeout: 30000 }); + } + + async settle() { + await browser.executeAsync((done: () => void) => { + let frames = 24; + const tick = () => --frames ? requestAnimationFrame(tick) : done(); + requestAnimationFrame(tick); + }); + } + + async startProbe(direction: number) { + await browser.execute((direction: number, diagnostics: boolean) => { + const scroller = document.querySelector('[data-flowchat-scroller]')!; + const probe: ScrollProbe = { frames: [], rectReads: 0, scans: 0, wheelEvents: 0, writes: [] }; + const rect = Element.prototype.getBoundingClientRect; + const query = Element.prototype.querySelectorAll; + let sampling = false, frame = 0, previous: HTMLElement | undefined, previousTop = 0; + let prototype: object | null = scroller; + let scrollDescriptor: PropertyDescriptor | undefined; + while (prototype && !scrollDescriptor) { scrollDescriptor = Object.getOwnPropertyDescriptor(prototype, 'scrollTop'); prototype = Object.getPrototypeOf(prototype); } + if (diagnostics && scrollDescriptor?.get && scrollDescriptor?.set) Object.defineProperty(scroller, 'scrollTop', { + configurable: true, get() { return scrollDescriptor!.get!.call(this); }, + set(value: number) { + const before = scrollDescriptor!.get!.call(this); + scrollDescriptor!.set!.call(this, value); + const after = scrollDescriptor!.get!.call(this); + if (Math.abs(after - before) > 1) probe.writes.push({ time: performance.now(), before, after, value, stack: new Error().stack }); + }, + }); + Element.prototype.getBoundingClientRect = function () { + if (!sampling && (this === scroller || this.classList.contains('virtual-item-wrapper'))) probe.rectReads++; + return rect.call(this); + }; + Element.prototype.querySelectorAll = function (this: Element, selector: string) { + if (!sampling && this === scroller) probe.scans++; + return query.call(this, selector); + } as typeof query; + const onWheel = () => probe.wheelEvents++; + scroller.addEventListener('wheel', onWheel, { passive: true }); + const tick = (time: number) => { + sampling = true; + const bounds = rect.call(scroller); + const rows = [...query.call(scroller, '.virtual-item-wrapper')] as HTMLElement[]; + const visible = rows.filter(row => { const r = rect.call(row); return r.bottom > bounds.top && r.top < bounds.bottom && r.height > 0; }); + const reverse = previous?.isConnected ? Math.max(0, (rect.call(previous).top - previousTop) * direction) : 0; + previous = visible[0]; + previousTop = previous ? rect.call(previous).top : 0; + probe.frames.push({ time, top: scroller.scrollTop, height: scroller.scrollHeight, rows: rows.length, reverse, blank: visible.length === 0, + anchor: diagnostics ? rows.map(row => ({ key: row.dataset.virtualItemKey, top: rect.call(row).top - bounds.top, height: rect.call(row).height })) : undefined }); + sampling = false; + frame = requestAnimationFrame(tick); + }; + frame = requestAnimationFrame(tick); + (window as any).__flowchatScrollProbe = () => { + cancelAnimationFrame(frame); + Element.prototype.getBoundingClientRect = rect; + Element.prototype.querySelectorAll = query; + scroller.removeEventListener('wheel', onWheel); + if (diagnostics) delete (scroller as any).scrollTop; + return probe; + }; + }, direction, process.env.OPENBITFUN_SCROLL_DIAGNOSTICS === '1'); + } + + async wheel(delta: number, count = 72) { + const position = await browser.execute(() => { + const r = document.querySelector('[data-flowchat-scroller]')!.getBoundingClientRect(); + return { x: Math.round(r.left + r.width / 2), y: Math.round(r.top + r.height / 3) }; + }); + await browser.performActions([{ type: 'wheel', id: 'history-wheel', actions: Array.from({ length: count }, () => ({ + type: 'scroll', origin: 'viewport', ...position, deltaX: 0, deltaY: delta, duration: 24, + })) }]); + await browser.releaseActions(); + } + + async stopProbe(): Promise { + return browser.execute(() => { + const probe = (window as any).__flowchatScrollProbe(); + delete (window as any).__flowchatScrollProbe; + return probe; + }); + } + + async disposeProbe() { + await browser.execute(() => { + (window as any).__flowchatScrollProbe?.(); + delete (window as any).__flowchatScrollProbe; + }); + } + + async enterDraft(text: string) { + const editor = $('[data-testid="chat-input-container"] .rich-text-input[contenteditable="true"]'); + await editor.waitForExist(); + await editor.click(); + await browser.keys(text); + } + + async draftText() { + return $('[data-testid="chat-input-container"] .rich-text-input[contenteditable="true"]').getText(); + } + + async findFirstResult(query: string) { + await $('[data-testid="flowchat-header-search"]').click(); + await $('[data-testid="flowchat-header-search-bar"] input').setValue(query); + // Trajectory search is debounced. Wait for results before navigating them. + await browser.waitUntil(async () => /\/\s*[1-9]\d*/.test( + await $('.flowchat-header__search-status').getText(), + ), { timeout: 15000 }); + await browser.keys('Enter'); + await browser.waitUntil(() => browser.execute(() => { + const line = document.querySelector('.flowchat-search-line:not([hidden])'); + const scroller = document.querySelector('[data-flowchat-scroller]'); + if (!line || !scroller) return false; + const a = line.getBoundingClientRect(), b = scroller.getBoundingClientRect(); + return a.bottom > b.top && a.top < b.bottom; + }), { timeout: 15000 }); + } + + async closeSearch() { + await browser.keys('Escape'); + } + + async anchor() { + return browser.execute(() => { + const scroller = document.querySelector('[data-flowchat-scroller]')!; + const top = scroller.getBoundingClientRect().top; + const row = [...scroller.querySelectorAll('.virtual-item-wrapper')].find(row => { + const rect = row.getBoundingClientRect(); return rect.bottom > top && rect.top < top + scroller.clientHeight && rect.height > 0; + }); + return { key: row?.dataset.virtualItemKey, offset: row ? row.getBoundingClientRect().top - top : 0, top: scroller.scrollTop }; + }); + } +} diff --git a/tests/e2e/specs/flowchat-scroll-native.spec.ts b/tests/e2e/specs/flowchat-scroll-native.spec.ts new file mode 100644 index 0000000000..23bfd183ef --- /dev/null +++ b/tests/e2e/specs/flowchat-scroll-native.spec.ts @@ -0,0 +1,81 @@ +import { writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { browser, expect } from '@wdio/globals'; +import { openWorkspace } from '../helpers/workspace-helper'; +import { FlowChatScrollPage, type ScrollProbe } from '../page-objects/FlowChatScrollPage'; + +const page = new FlowChatScrollPage(); +const evidence = process.env.OPENBITFUN_FLOWCHAT_SCROLL_EVIDENCE!; +const results: Record = {}; +const percentile = (values: number[], p: number) => [...values].sort((a, b) => a - b)[Math.floor((values.length - 1) * p)] ?? 0; +function summarize(probe: ScrollProbe) { + const intervals = probe.frames.slice(1).map((frame, index) => frame.time - probe.frames[index].time); + const median = percentile(intervals, 0.5); + return { + frames: probe.frames.length, frameP50Ms: median, frameP95Ms: percentile(intervals, 0.95), maxFrameMs: Math.max(0, ...intervals), + delayedFrames: intervals.filter(value => value > Math.max(25, median * 1.5)).length, + reverseFrames: probe.frames.filter(frame => frame.reverse > 4).length, + maxReversePx: Math.max(0, ...probe.frames.map(frame => frame.reverse)), + blankFrames: probe.frames.filter(frame => frame.blank).length, + rectReads: probe.rectReads, scans: probe.scans, wheelEvents: probe.wheelEvents, + maxRows: Math.max(0, ...probe.frames.map(frame => frame.rows)), + }; +} + +describe('FlowChat historical scrolling in the packaged desktop', () => { + before(async () => { expect(await openWorkspace(process.env.E2E_TEST_WORKSPACE!, { requireWorkspaceLabel: false })).toBe(true); }); + after(() => { writeFileSync(join(evidence, 'result.json'), JSON.stringify(results, null, 2)); }); + afterEach(async function () { + await page.disposeProbe(); + await browser.saveScreenshot(join(evidence, `${this.currentTest?.state === 'failed' ? 'fail' : 'pass'}-${this.currentTest?.title.replace(/[^a-z0-9]+/gi, '-')}.png`)); + }); + + it('keeps history scrolling continuous and preserves reading position, drafts and search', async () => { + await page.openSession('scroll-history-000'); + await page.settle(); + results.opened = await page.anchor(); + for (const [label, delta] of [['paging-up', -85], ['reading-down', 65], ['reading-up', -65], ['fast-up', -420], ['fast-down', 280]] as const) { + await page.startProbe(Math.sign(delta)); + await page.wheel(delta); + await page.settle(); + const probe = await page.stopProbe(); + const summary = summarize(probe); + results[label] = summary; + writeFileSync(join(evidence, `${label}.json`), JSON.stringify(probe)); + console.log(label, summary); + expect(summary.wheelEvents).toBe(72); + expect(summary.frames).toBeGreaterThan(20); + expect(summary.maxRows).toBeLessThan(90); + expect(summary.reverseFrames).toBe(0); + expect(summary.blankFrames).toBe(0); + } + const stopped = await page.anchor(); + await page.settle(); + const stable = await page.anchor(); + results.stopped = { stopped, stable }; + expect(stable.key).toBe(stopped.key); + expect(Math.abs(stable.offset - stopped.offset)).toBeLessThan(2); + await page.enterDraft('Scroll continuity draft'); + const before = await page.anchor(); + await page.openSession('scroll-history-001'); + await page.openSession('scroll-history-000'); + await page.settle(); + const restored = await page.anchor(); + results.restoration = { before, restored }; + expect(restored.key).toBe(before.key); + expect(Math.abs(restored.offset - before.offset)).toBeLessThan(8); + expect(await page.draftText()).toContain('Scroll continuity draft'); + await page.findFirstResult('fixture'); + await page.closeSearch(); + const located = await page.anchor(); + await page.wheel(60, 8); + await page.settle(); + const released = await page.anchor(); + expect(released.key !== located.key || Math.abs(released.offset - located.offset) > 20).toBe(true); + await page.settle(); + const stableAfterSearch = await page.anchor(); + expect(stableAfterSearch.key).toBe(released.key); + expect(Math.abs(stableAfterSearch.offset - released.offset)).toBeLessThan(2); + results.interactions = { draftPreserved: true, searchLocated: true, readerTakeoverStable: true }; + }); +});