Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand All @@ -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 |
Expand All @@ -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,
Expand Down
Original file line number Diff line number Diff line change
@@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
/**
Expand Down Expand Up @@ -149,19 +151,22 @@ vi.mock('./useFlowChatVirtualizer', async () => {
scrollerRef: { current: HTMLElement | null };
startAtTailOnMount?: boolean;
reconcileOpeningMeasurement?: () => boolean;
shiftViewport?: (delta: number) => boolean;
estimateContext?: { availableWidthPx?: number };
estimateContextRevision?: string;
}) => {
mocks.virtualizerStartsAtTail = options.startAtTailOnMount === true;
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,
Expand Down Expand Up @@ -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(<VirtualMessageList />));
await settleOpenReveal();
const scroller = container.querySelector<HTMLElement>('[data-flowchat-scroller]')!;
const rows = [...scroller.querySelectorAll<HTMLElement>('.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 });
Expand Down Expand Up @@ -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<VirtualMessageListRef>();
const restoreLayout = fakeLayout({ clientHeight: 600, scrollHeight: 2000, turnTopFromScrollerTop: 0 });
try {
act(() => root.render(<VirtualMessageList ref={listRef} />));
const scroller = container.querySelector<HTMLElement>('[data-flowchat-scroller]')!;
const row = container.querySelector<HTMLElement>('.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<VirtualMessageListRef>();
const initialViewportSnapshot = {
Expand Down
Loading
Loading