iterate.com / ui

git clone https://git.iterate.com/repos/ui

VirtualLog: add ContextView day-line prepend scroll reproduction and tests

Jonas Templestein, 2026-11-28 01:02 UTC · 406137a34b21cd690022b47a8ac840ee95c8cc2e · parent 5b5842e

4 files changed

M scripts/check-virtual-log-scroll.ts
@@ -16,12 +16,14 @@
 export type ScenarioSpec = {
   name: string;
   query: string;
-  /** Duration of upward wheel scrolling in ms. */
+  /** Duration of upward scrolling in ms. */
   scrollMs: number;
-  /** Upward wheel speed in px/s (positive number; dispatched as negative deltaY). */
+  /** Upward scroll speed in px/s (positive number; dispatched as negative deltaY). */
   speedPxPerSec: number;
   /** Optional extra idle ms at scrollTop=0 waiting for older pages to land. */
   idleAtTopMs?: number;
+  /** "wheel" uses CDP mouseWheel events; "scrollTop" drives scroller.scrollTop per rAF like scrolltest.js. */
+  driver?: "wheel" | "scrollTop";
 };
 
 export type ScenarioResult = {
@@ -110,6 +112,28 @@
     scrollMs: 5_000,
     speedPxPerSec: 2_000,
   },
+  {
+    name: "context-day-lines-wheel",
+    query:
+      "totalRows=1200&initialRows=60&pageSizes=50,70,116,47,170,84&pageDelayMs=500&dayLines=1&parseBusyMs=50",
+    scrollMs: 5_000,
+    speedPxPerSec: 2_000,
+  },
+  {
+    name: "context-day-lines-raf",
+    query:
+      "totalRows=1200&initialRows=85&pageSizes=70,116,47,50,170,84&pageDelayMs=450&dayLines=1&parseBusyMs=50",
+    scrollMs: 5_000,
+    speedPxPerSec: 2_000,
+    driver: "scrollTop",
+  },
+  {
+    name: "context-day-lines-at-top",
+    query: "totalRows=600&initialRows=35&pageSizes=57,70,47&pageDelayMs=700&dayLines=1",
+    scrollMs: 1_000,
+    speedPxPerSec: 3_000,
+    idleAtTopMs: 1_500,
+  },
 ];
 
 const HARNESS_HTML = `<!doctype html>
@@ -363,9 +387,14 @@
   // Track exact wheel deltaY delivered to the scroller between frames.
   let pendingWheelDelta = 0;
   let totalWheelDelta = 0;
+  const driverMode = window.__DRIVER_MODE__ || 'wheel';
+  const driverSpeed = window.__DRIVER_SPEED__ || 2000;
+  let lastWheelDispatch = 0;
   scroller.addEventListener('wheel', (e) => {
-    pendingWheelDelta += e.deltaY;
-    totalWheelDelta += e.deltaY;
+    if (driverMode === 'wheel') {
+      pendingWheelDelta += e.deltaY;
+      totalWheelDelta += e.deltaY;
+    }
   }, { passive: true });
 
   const pickAnchor = () => {
@@ -474,6 +503,17 @@
     prevTop = anchor ? anchor.getBoundingClientRect().top : 0;
     prevS = S;
     prevH = H;
+    if (driverMode === 'scrollTop') {
+      if (now - lastWheelDispatch > 400) {
+        lastWheelDispatch = now;
+        scroller.dispatchEvent(new WheelEvent('wheel', { deltaY: -120, bubbles: true }));
+      }
+      const want = S - driverSpeed * Math.min(dt, 50) / 1000;
+      scroller.scrollTop = want;
+      const applied = scroller.scrollTop - S;
+      prevTop -= applied;
+      prevS = scroller.scrollTop;
+    }
     requestAnimationFrame(step);
   };
   requestAnimationFrame(step);
@@ -545,31 +585,41 @@
     await sleep(150);
 
     // Start frame measurer.
-    await cdp.send("Runtime.evaluate", { expression: INSTALL_MEASURER }, sessionId);
+    await cdp.send(
+      "Runtime.evaluate",
+      {
+        expression: `window.__DRIVER_MODE__ = ${JSON.stringify(spec.driver ?? "wheel")}; window.__DRIVER_SPEED__ = ${String(spec.speedPxPerSec)}; ${INSTALL_MEASURER}`,
+      },
+      sessionId,
+    );
     await sleep(50);
 
-    // Drive upward scrolling with real Chromium mouseWheel events at ~60 Hz, compensating for
-    // CDP round-trip so actual speed matches speedPxPerSec.
-    const tickMs = 16;
-    const stepPx = Math.round((spec.speedPxPerSec * tickMs) / 1000);
-    const deadline = performance.now() + spec.scrollMs;
-    let nextTick = performance.now();
-    while (performance.now() < deadline) {
-      await cdp.send(
-        "Input.dispatchMouseEvent",
-        {
-          type: "mouseWheel",
-          x: 600,
-          y: 350,
-          deltaX: 0,
-          deltaY: -stepPx,
-        },
-        sessionId,
-      );
-      nextTick += tickMs;
-      const wait = nextTick - performance.now();
-      if (wait > 1) await sleep(wait);
-      else nextTick = performance.now();
+    if (spec.driver === "scrollTop") {
+      await sleep(spec.scrollMs);
+    } else {
+      // Drive upward scrolling with real Chromium mouseWheel events at ~60 Hz, compensating for
+      // CDP round-trip so actual speed matches speedPxPerSec.
+      const tickMs = 16;
+      const stepPx = Math.round((spec.speedPxPerSec * tickMs) / 1000);
+      const deadline = performance.now() + spec.scrollMs;
+      let nextTick = performance.now();
+      while (performance.now() < deadline) {
+        await cdp.send(
+          "Input.dispatchMouseEvent",
+          {
+            type: "mouseWheel",
+            x: 600,
+            y: 350,
+            deltaX: 0,
+            deltaY: -stepPx,
+          },
+          sessionId,
+        );
+        nextTick += tickMs;
+        const wait = nextTick - performance.now();
+        if (wait > 1) await sleep(wait);
+        else nextTick = performance.now();
+      }
     }
 
     if (spec.idleAtTopMs) {
M scripts/virtual-log-scroll.test.ts
@@ -42,13 +42,28 @@
     scrollMs: 3_000,
     speedPxPerSec: 2_000,
   },
+  {
+    name: "context-day-lines-raf",
+    query:
+      "totalRows=1200&initialRows=85&pageSizes=70,116,47,50,170&pageDelayMs=400&dayLines=1&parseBusyMs=50",
+    scrollMs: 3_000,
+    speedPxPerSec: 2_000,
+    driver: "scrollTop",
+  },
+  {
+    name: "context-day-lines-at-top",
+    query: "totalRows=600&initialRows=35&pageSizes=57,70,47&pageDelayMs=700&dayLines=1",
+    scrollMs: 900,
+    speedPxPerSec: 3_000,
+    idleAtTopMs: 1_200,
+  },
 ];
 
 const hasChromium = findChromium() !== null;
 
 test.runIf(hasChromium)(
   "VirtualLog keeps visible rows still (0 jumps > 2 px) while scrolling up and prepending older pages",
-  { timeout: 45_000 },
+  { timeout: 60_000 },
   async () => {
     const results = await runScrollStabilityCheck(REPO_ROOT, THRESHOLD_SCENARIOS);
     for (const r of results) {
@@ -58,7 +73,10 @@
       expect(r.visualJumpAbsSum, `${detail}`).toBe(0);
       expect(r.anchorLost, `${r.name}: anchor lost`).toBe(0);
       expect(r.cls, `${r.name}: layout shift`).toBe(0);
-      expect(r.longTasks.length, `${r.name}: long tasks`).toBeLessThanOrEqual(2);
+      // `context-day-lines-raf` intentionally injects a 50 ms busy parse per page.
+      if (!r.name.includes("context-day-lines-raf")) {
+        expect(r.longTasks.length, `${r.name}: long tasks`).toBeLessThanOrEqual(2);
+      }
       expect(r.over33 / r.frames, `${r.name}: >33ms frame share`).toBeLessThanOrEqual(0.15);
     }
   },
M src/components/virtual-log/virtual-log-scroll.test.tsx
@@ -18,7 +18,7 @@
   }
 });
 
-type TestRow = { id: string; offset: number; estimate: number };
+type TestRow = { id: string; offset?: number; estimate: number };
 
 const ROW_INFO: VirtualLogRowInfo<TestRow> = {
   key: (row) => row.id,
@@ -141,4 +141,52 @@
     />,
   );
   expect(scroller.scrollTop).toBe(300);
+});
+
+test("same-day prepend at scrollTop 0 advances scrollTop even when a floating day header stays at index 0", () => {
+  const initial: TestRow[] = [
+    { id: "day:Thu", estimate: 32 },
+    ...Array.from({ length: 30 }, (_, i) => ({
+      id: `event:${100 + i}`,
+      offset: 100 + i,
+      estimate: 26,
+    })),
+  ];
+  using view = mount(
+    <VirtualLog
+      rows={initial}
+      rowInfo={ROW_INFO}
+      renderRow={(row) => <div data-row={row.id}>{row.id}</div>}
+      label="Day-header prepend test"
+    />,
+    26,
+  );
+  const scroller = view.container.querySelector<HTMLDivElement>('[data-slot="virtual-log"]')!;
+  Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 4_000 });
+  act(() => {
+    scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: -120, bubbles: true }));
+    scroller.scrollTop = 0;
+    scroller.dispatchEvent(new Event("scroll"));
+  });
+  expect(scroller.scrollTop).toBe(0);
+
+  // Prepend 50 same-day events under the same `"day:Thu"` header at index 0 (50 * 26 = 1,300 px).
+  const prepended: TestRow[] = [
+    { id: "day:Thu", estimate: 32 },
+    ...Array.from({ length: 50 }, (_, i) => ({
+      id: `event:${50 + i}`,
+      offset: 50 + i,
+      estimate: 26,
+    })),
+    ...initial.slice(1),
+  ];
+  view.rerender(
+    <VirtualLog
+      rows={prepended}
+      rowInfo={ROW_INFO}
+      renderRow={(row) => <div data-row={row.id}>{row.id}</div>}
+      label="Day-header prepend test"
+    />,
+  );
+  expect(scroller.scrollTop).toBe(1_300);
 });
M src/test-support/virtual-log-scroll-harness.tsx
@@ -7,13 +7,14 @@
 import type { OlderPages } from "#/components/virtual-log/older-pages.ts";
 import { VirtualLog, type VirtualLogRowInfo } from "#/components/virtual-log/virtual-log.tsx";
 
-type RowKind = "tiny4" | "compact24" | "user" | "assistant" | "widget";
+type RowKind = "tiny4" | "compact24" | "user" | "assistant" | "widget" | "event26" | "day32";
 
 type HarnessRow = {
   id: string;
-  offset: number;
+  offset?: number;
   kind: RowKind;
   height: number;
+  day?: string;
   /** Optional second height settled after mount to emulate late content/CSS reflow. */
   reflowHeight?: number;
   reflowDelayMs?: number;
@@ -35,6 +36,12 @@
   lateReflow: boolean;
   /** Optional override for uniform tiny4 rows (e.g. testing 4px overscan buffer). */
   tinyBurst?: boolean;
+  /** When true, render a ContextView-style event stream: 26 px event rows grouped under 32 px
+   *  floating day-separator headers (`day:<day>`, `offset: undefined`) that move to index 0 when
+   *  older events of the same calendar day prepend. */
+  dayLines?: boolean;
+  /** Optional busy-wait ms right before applying a prepend, emulating main-thread event parsing. */
+  parseBusyMs?: number;
 };
 
 const ESTIMATE: Record<RowKind, number> = {
@@ -43,6 +50,8 @@
   user: 96,
   assistant: 72,
   widget: 140,
+  event26: 26,
+  day32: 36,
 };
 
 const ROW_INFO: VirtualLogRowInfo<HarnessRow> = {
@@ -62,6 +71,23 @@
 }
 
 function buildRows(cfg: HarnessConfig): HarnessRow[] {
+  if (cfg.dayLines) {
+    // Emulate ContextView's event rows (26 px) spread across calendar days (~220 events/day so
+    // most 50-170-row older pages land on the SAME day and keep the day header key at index 0).
+    const rows: HarnessRow[] = [];
+    for (let i = 0; i < cfg.totalRows; i += 1) {
+      const offset = i + 1;
+      const dayNum = Math.floor(i / 220) + 1;
+      rows.push({
+        id: `event:${offset}`,
+        offset,
+        kind: "event26",
+        height: 26,
+        day: `Day-${dayNum}`,
+      });
+    }
+    return rows;
+  }
   const rand = mulberry32(20261127);
   const rows: HarnessRow[] = [];
   // Keep a few 2,000 px rows in the log (including right above a 24-row run of 4 px rows so
@@ -173,9 +199,27 @@
     mergeBoundary: params.get("mergeBoundary") === "1",
     lateReflow: params.get("lateReflow") === "1",
     tinyBurst: params.get("tinyBurst") === "1",
+    dayLines: params.get("dayLines") === "1",
+    parseBusyMs: Number(params.get("parseBusyMs") ?? 0),
   };
 }
 
+/** Inserts floating 32 px day-separator rows (`day:<day>`, `offset: undefined`) wherever the day
+ *  changes in `slice`, matching `ContextView`'s `foldEvents` / `refold` behavior. */
+function withDayLines(slice: readonly HarnessRow[]): HarnessRow[] {
+  const out: HarnessRow[] = [];
+  let lastDay = "";
+  for (const row of slice) {
+    const day = row.day ?? "";
+    if (day && day !== lastDay) {
+      out.push({ id: `day:${day}`, kind: "day32", height: 32, day });
+      lastDay = day;
+    }
+    out.push(row);
+  }
+  return out;
+}
+
 export function HarnessApp() {
   const cfg = useMemo(readConfig, []);
   const allRows = useMemo(() => buildRows(cfg), [cfg]);
@@ -190,12 +234,13 @@
 
   const rows = useMemo(() => {
     const slice = allRows.slice(windowStart);
+    if (cfg.dayLines) return withDayLines(slice);
     if (mergedIds.size === 0) return slice;
     return slice.map((row) => {
-      const merged = mergedIds.get(row.offset);
+      const merged = row.offset !== undefined ? mergedIds.get(row.offset) : undefined;
       return merged ? { ...row, id: merged } : row;
     });
-  }, [allRows, windowStart, mergedIds]);
+  }, [allRows, windowStart, mergedIds, cfg.dayLines]);
 
   const loadOlder = useCallback(() => {
     if (loading || windowStart <= 0) return;
@@ -205,22 +250,48 @@
     const size = cfg.pageSizes[pageIdx % cfg.pageSizes.length]!;
     timerRef.current = window.setTimeout(() => {
       timerRef.current = null;
-      const nextStart = Math.max(0, windowStart - size);
-      const added = windowStart - nextStart;
-      const shouldMerge = cfg.mergeBoundary && pageIdx % 2 === 0 && windowStart < allRows.length;
-      if (shouldMerge) {
-        const oldFirst = allRows[windowStart]!;
-        setMergedIds((prev) => {
-          const next = new Map(prev);
-          next.set(oldFirst.offset, `merged-${nextStart}-${oldFirst.offset}`);
-          return next;
-        });
+      if (cfg.parseBusyMs && cfg.parseBusyMs > 0) {
+        const until = performance.now() + cfg.parseBusyMs;
+        while (performance.now() < until) {
+          // Emulate DOMWebSocket.onmessage main-thread parsing cost BEFORE rAF flush.
+        }
       }
-      prependsRef.current.push({ t: performance.now(), added, mergedBoundary: shouldMerge });
-      setWindowStart(nextStart);
-      setLoading(false);
+      const publishPage = () => {
+        const nextStart = Math.max(0, windowStart - size);
+        const added = windowStart - nextStart;
+        const shouldMerge = cfg.mergeBoundary && pageIdx % 2 === 0 && windowStart < allRows.length;
+        if (shouldMerge) {
+          const oldFirst = allRows[windowStart]!;
+          if (oldFirst.offset !== undefined) {
+            const firstOffset = oldFirst.offset;
+            setMergedIds((prev) => {
+              const next = new Map(prev);
+              next.set(firstOffset, `merged-${nextStart}-${firstOffset}`);
+              return next;
+            });
+          }
+        }
+        prependsRef.current.push({ t: performance.now(), added, mergedBoundary: shouldMerge });
+        setWindowStart(nextStart);
+        setLoading(false);
+      };
+      // Match iterate SDK's connectEventLog (`event-log.mjs:70`): flush pages in a rAF.
+      if (cfg.dayLines) {
+        window.requestAnimationFrame(publishPage);
+      } else {
+        publishPage();
+      }
     }, cfg.pageDelayMs);
-  }, [loading, windowStart, cfg.pageSizes, cfg.pageDelayMs, cfg.mergeBoundary, allRows]);
+  }, [
+    loading,
+    windowStart,
+    cfg.pageSizes,
+    cfg.pageDelayMs,
+    cfg.mergeBoundary,
+    cfg.dayLines,
+    cfg.parseBusyMs,
+    allRows,
+  ]);
 
   useEffect(
     () => () => {