iterate.com / ui

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

VirtualLog: add headless Chromium scroll-stability reproduction and tests

Jonas Templestein, 2026-11-28 00:21 UTC · 31a71d9433f488b182ae65a4dc5594feaf457c6a · parent 9dadff7

4 files changed

A scripts/check-virtual-log-scroll.ts
@@ -0,0 +1,659 @@
+// Headless Chromium scroll-stability check for VirtualLog.
+// Bundles src/test-support/virtual-log-scroll-harness.tsx with tsdown, serves it locally, drives
+// Chromium with real wheel events (Input.dispatchMouseEvent mouseWheel) via CDP, and measures:
+// - visual row jumps (> 2 px beyond what wheel scroll explains) and layout-Y shifts
+// - frame timings (> 33 ms, > 50 ms, p95, max)
+// - long tasks, long animation frames, and layout shifts (CLS)
+//
+// Run directly: node scripts/check-virtual-log-scroll.ts
+import { spawn, type ChildProcess } from "node:child_process";
+import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { createServer, type Server } from "node:http";
+import { homedir } from "node:os";
+import { join, resolve } from "node:path";
+import { build } from "tsdown";
+
+export type ScenarioSpec = {
+  name: string;
+  query: string;
+  /** Duration of upward wheel scrolling in ms. */
+  scrollMs: number;
+  /** Upward wheel 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;
+};
+
+export type ScenarioResult = {
+  name: string;
+  frames: number;
+  over33: number;
+  over50: number;
+  p95: number;
+  maxFrameMs: number;
+  /** True visual jumps on screen (> 2 px beyond wheel scroll). */
+  visualJumps: number;
+  visualJumpAbsSum: number;
+  visualJumpSamples: Array<{
+    t: number;
+    jump: number;
+    dTop: number;
+    wheel: number;
+    dS: number;
+    dH: number;
+    S: number;
+    idx: string;
+    rowId: string;
+    reason: string;
+  }>;
+  /** scrolltest.js-style layout-Y changes (top - (prevTop - (S - prevS))). */
+  layoutShiftsDev: number;
+  layoutShiftsDevAbsSum: number;
+  anchorLost: number;
+  longTasks: number[];
+  cls: number;
+  shifts: number;
+  pagesLoaded: number;
+  loadedRows: number;
+  finalScrollTop: number;
+  finalScrollHeight: number;
+};
+
+export const SCENARIOS: ScenarioSpec[] = [
+  {
+    name: "small-pages-stable-keys",
+    query:
+      "totalRows=200&initialRows=22&pageSizes=4,7,3,12,17,5,9&pageDelayMs=450&mergeBoundary=0&lateReflow=0",
+    scrollMs: 6_500,
+    speedPxPerSec: 2_000,
+  },
+  {
+    name: "small-pages-boundary-merge",
+    query:
+      "totalRows=200&initialRows=22&pageSizes=4,7,3,12,17,5,9&pageDelayMs=450&mergeBoundary=1&lateReflow=0",
+    scrollMs: 6_500,
+    speedPxPerSec: 2_000,
+  },
+  {
+    name: "mid-list-mixed-and-reflow",
+    query:
+      "totalRows=240&initialRows=240&pageSizes=10&pageDelayMs=400&mergeBoundary=0&lateReflow=1",
+    scrollMs: 5_000,
+    speedPxPerSec: 2_500,
+  },
+  {
+    name: "idle-at-top-page-lands",
+    query:
+      "totalRows=120&initialRows=22&pageSizes=5,3,15,40&pageDelayMs=350&mergeBoundary=1&lateReflow=0",
+    scrollMs: 1_200,
+    speedPxPerSec: 3_000,
+    idleAtTopMs: 2_000,
+  },
+  {
+    name: "tiny4-run-above-2000px",
+    query:
+      "totalRows=200&initialRows=200&pageSizes=10&pageDelayMs=400&mergeBoundary=0&lateReflow=0",
+    scrollMs: 4_000,
+    speedPxPerSec: 6_000,
+  },
+  {
+    name: "tiny-4px-pages-at-top",
+    query:
+      "totalRows=180&initialRows=22&pageSizes=3,5,8,4&pageDelayMs=300&mergeBoundary=1&lateReflow=0&tinyBurst=1",
+    scrollMs: 4_500,
+    speedPxPerSec: 2_000,
+  },
+  {
+    name: "huge-2000px-and-large-pages",
+    query:
+      "totalRows=220&initialRows=22&pageSizes=1,3,50,17&pageDelayMs=350&mergeBoundary=1&lateReflow=1",
+    scrollMs: 5_000,
+    speedPxPerSec: 2_000,
+  },
+];
+
+const HARNESS_HTML = `<!doctype html>
+<html>
+<head>
+<meta charset="utf-8" />
+<style>
+  *, *::before, *::after { box-sizing: border-box; }
+  html, body, #root { margin: 0; padding: 0; height: 100%; overflow: hidden; font-family: system-ui, sans-serif; }
+  .flex { display: flex; }
+  .flex-1 { flex: 1 1 0%; }
+  .flex-col { flex-direction: column; }
+  .min-h-0 { min-height: 0; }
+  .shrink-0 { flex-shrink: 0; }
+  .grow { flex-grow: 1; }
+  .relative { position: relative; }
+  .absolute { position: absolute; }
+  .sticky { position: sticky; }
+  .top-0 { top: 0; }
+  .bottom-0 { bottom: 0; }
+  .left-0 { left: 0; }
+  .right-3 { right: 12px; }
+  .top-8 { top: 32px; }
+  .bottom-full { bottom: 100%; }
+  .z-10 { z-index: 10; }
+  .h-0 { height: 0; }
+  .h-6 { height: 24px; }
+  .h-8 { height: 32px; }
+  .min-w-8 { min-width: 32px; }
+  .w-full { width: 100%; }
+  .mb-1 { margin-bottom: 4px; }
+  .overflow-x-hidden { overflow-x: hidden; }
+  .overflow-y-auto { overflow-y: auto; }
+  .overscroll-contain { overscroll-behavior: contain; }
+  .outline-none { outline: none; }
+  .items-center { align-items: center; }
+  .justify-center { justify-content: center; }
+  .bg-background { background: #ffffff; }
+  .border { border: 1px solid #d1d5db; }
+  .rounded-full { border-radius: 9999px; }
+</style>
+</head>
+<body>
+  <div id="root"></div>
+  <script src="/harness.js"></script>
+</body>
+</html>`;
+
+export function findChromium(): string | null {
+  if (process.env.CHROMIUM_BIN && existsSync(process.env.CHROMIUM_BIN)) {
+    return process.env.CHROMIUM_BIN;
+  }
+  const pwDir = join(homedir(), ".cache", "ms-playwright");
+  if (existsSync(pwDir)) {
+    // Prefer chrome-headless-shell: Chromium 155 --headless=new can stall on rapid CDP wheel acks.
+    for (const prefix of ["chromium_headless_shell-", "chromium-"]) {
+      for (const entry of readdirSync(pwDir).sort().reverse()) {
+        if (!entry.startsWith(prefix)) continue;
+        for (const sub of [
+          "chrome-headless-shell-linux64/chrome-headless-shell",
+          "chrome-headless-shell-linux/chrome-headless-shell",
+          "chrome-linux64/chrome",
+          "chrome-linux/chrome",
+        ]) {
+          const full = join(pwDir, entry, sub);
+          if (existsSync(full)) return full;
+        }
+      }
+    }
+  }
+  for (const bin of ["/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome"]) {
+    if (existsSync(bin)) return bin;
+  }
+  return null;
+}
+
+class CdpClient {
+  private ws: WebSocket;
+  private nextId = 1;
+  private pending = new Map<
+    number,
+    { resolve: (v: unknown) => void; reject: (e: Error) => void }
+  >();
+
+  private constructor(ws: WebSocket) {
+    this.ws = ws;
+    ws.addEventListener("message", (event) => {
+      const msg = JSON.parse(String(event.data)) as {
+        id?: number;
+        result?: unknown;
+        error?: { message: string };
+      };
+      if (msg.id === undefined) return;
+      const p = this.pending.get(msg.id);
+      if (!p) return;
+      this.pending.delete(msg.id);
+      if (msg.error) p.reject(new Error(msg.error.message));
+      else p.resolve(msg.result);
+    });
+  }
+
+  static async connect(wsUrl: string): Promise<CdpClient> {
+    const ws = new WebSocket(wsUrl);
+    await new Promise<void>((res, rej) => {
+      ws.addEventListener("open", () => res(), { once: true });
+      ws.addEventListener("error", () => rej(new Error(`CDP connect failed: ${wsUrl}`)), {
+        once: true,
+      });
+    });
+    return new CdpClient(ws);
+  }
+
+  send<T = unknown>(
+    method: string,
+    params?: Record<string, unknown>,
+    sessionId?: string,
+  ): Promise<T> {
+    const id = this.nextId++;
+    return new Promise<T>((resolvePromise, rejectPromise) => {
+      const timer = setTimeout(() => {
+        this.pending.delete(id);
+        rejectPromise(new Error(`CDP timeout on ${method}`));
+      }, 15_000);
+      this.pending.set(id, {
+        resolve: (v) => {
+          clearTimeout(timer);
+          resolvePromise(v as T);
+        },
+        reject: (e) => {
+          clearTimeout(timer);
+          rejectPromise(e);
+        },
+      });
+      this.ws.send(JSON.stringify({ id, method, params, sessionId }));
+    });
+  }
+
+  close() {
+    this.ws.close();
+  }
+}
+
+async function bundleHarness(repoRoot: string): Promise<string> {
+  const outDir = join(repoRoot, "node_modules", ".cache", "virtual-log-scroll-harness");
+  mkdirSync(outDir, { recursive: true });
+  await build({
+    config: false,
+    cwd: repoRoot,
+    entry: { harness: "src/test-support/virtual-log-scroll-harness.tsx" },
+    format: "iife",
+    outDir,
+    clean: false,
+    platform: "browser",
+    target: "es2022",
+    hash: false,
+    minify: false,
+    dts: false,
+    define: {
+      "import.meta.env.SSR": "false",
+      "import.meta.env.DEV": "false",
+      "import.meta.env.BASE_URL": JSON.stringify("/"),
+      "process.env.NODE_ENV": JSON.stringify("production"),
+    },
+    deps: { alwaysBundle: [/./], onlyBundle: false },
+    inputOptions: {
+      onLog: (level, log, handler) => log.code === "MODULE_LEVEL_DIRECTIVE" || handler(level, log),
+    },
+    outputOptions: { entryFileNames: "harness.js" },
+  });
+  return readFileSync(join(outDir, "harness.js"), "utf8");
+}
+
+async function startServer(bundleJs: string): Promise<{ server: Server; baseUrl: string }> {
+  const server = createServer((req, res) => {
+    const url = req.url ?? "/";
+    if (url.startsWith("/harness.js")) {
+      res.writeHead(200, { "content-type": "application/javascript; charset=utf-8" });
+      res.end(bundleJs);
+      return;
+    }
+    res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
+    res.end(HARNESS_HTML);
+  });
+  await new Promise<void>((res) => server.listen(0, "127.0.0.1", () => res()));
+  const addr = server.address();
+  if (!addr || typeof addr === "string") throw new Error("Failed to bind server");
+  return { server, baseUrl: `http://127.0.0.1:${addr.port}` };
+}
+
+async function launchChromium(
+  bin: string,
+  cacheDir: string,
+): Promise<{ proc: ChildProcess; wsUrl: string; userDataDir: string }> {
+  const userDataDir = join(cacheDir, `profile-${process.pid}`);
+  mkdirSync(userDataDir, { recursive: true });
+  const isHeadlessShell = bin.includes("headless-shell") || bin.includes("headless_shell");
+  const proc = spawn(
+    bin,
+    [
+      ...(isHeadlessShell ? [] : ["--headless=new"]),
+      "--no-sandbox",
+      "--use-gl=angle",
+      "--use-angle=swiftshader",
+      "--disable-dev-shm-usage",
+      "--disable-smooth-scrolling",
+      `--user-data-dir=${userDataDir}`,
+      "--remote-debugging-port=0",
+      "--window-size=1200,762",
+      "about:blank",
+    ],
+    { stdio: ["ignore", "pipe", "pipe"] },
+  );
+  const wsUrl = await new Promise<string>((resolveUrl, rejectUrl) => {
+    let stderr = "";
+    const timeout = setTimeout(
+      () => rejectUrl(new Error(`Chromium did not emit DevTools URL:\n${stderr}`)),
+      15_000,
+    );
+    proc.stderr.on("data", (chunk: Buffer) => {
+      stderr += chunk.toString();
+      const match = /DevTools listening on (ws:\/\/\S+)/.exec(stderr);
+      if (match) {
+        clearTimeout(timeout);
+        resolveUrl(match[1]!);
+      }
+    });
+    proc.once("exit", (code) => {
+      clearTimeout(timeout);
+      rejectUrl(new Error(`Chromium exited early (${String(code)}):\n${stderr}`));
+    });
+  });
+  return { proc, wsUrl, userDataDir };
+}
+
+const INSTALL_MEASURER = `(() => {
+  const scroller = document.querySelector('[data-slot="virtual-log"]');
+  if (!scroller) throw new Error('missing virtual-log scroller');
+  const longTasks = [];
+  const shifts = [];
+  const obs = [];
+  const tryObs = (type, fn) => {
+    try {
+      const o = new PerformanceObserver((l) => l.getEntries().forEach(fn));
+      o.observe({ type, buffered: false });
+      obs.push(o);
+    } catch {}
+  };
+  tryObs('longtask', (e) => longTasks.push(Math.round(e.duration)));
+  tryObs('layout-shift', (e) => shifts.push({ v: +e.value.toFixed(4), t: Math.round(e.startTime) }));
+
+  // Track exact wheel deltaY delivered to the scroller between frames.
+  let pendingWheelDelta = 0;
+  let totalWheelDelta = 0;
+  scroller.addEventListener('wheel', (e) => {
+    pendingWheelDelta += e.deltaY;
+    totalWheelDelta += e.deltaY;
+  }, { passive: true });
+
+  const pickAnchor = () => {
+    const vr = scroller.getBoundingClientRect();
+    const mid = vr.top + vr.height / 2;
+    let best = null;
+    let bd = 1e9;
+    for (const r of scroller.querySelectorAll('[data-index]')) {
+      const b = r.getBoundingClientRect();
+      if (b.height < 4) continue;
+      if (b.bottom <= vr.top || b.top >= vr.bottom) continue;
+      const dist = Math.abs((b.top + b.bottom) / 2 - mid);
+      if (dist < bd) { bd = dist; best = r; }
+    }
+    return best;
+  };
+
+  let running = true;
+  const frames = [];
+  const visualJumps = [];
+  const layoutDevJumps = [];
+  let anchorLost = 0;
+  let anchor = null;
+  let prevTop = 0;
+  let prevS = scroller.scrollTop;
+  let prevH = scroller.scrollHeight;
+  let prevPrepends = window.__HARNESS_STATE__ ? window.__HARNESS_STATE__.prepends.length : 0;
+  // Unconsumed upward wheel pixels from the immediately previous frame (for 1-frame compositor lag).
+  let prevUnusedUp = 0;
+  let last = performance.now();
+  const start = last;
+
+  const step = () => {
+    if (!running) return;
+    const now = performance.now();
+    const dt = now - last;
+    last = now;
+    frames.push(dt);
+
+    const S = scroller.scrollTop;
+    const H = scroller.scrollHeight;
+    const rawWheel = pendingWheelDelta;
+    pendingWheelDelta = 0;
+    const curPrepends = window.__HARNESS_STATE__ ? window.__HARNESS_STATE__.prepends.length : 0;
+    const prependLanded = curPrepends > prevPrepends;
+    prevPrepends = curPrepends;
+
+    if (anchor && anchor.isConnected && anchor.getBoundingClientRect().height >= 4) {
+      const top = anchor.getBoundingClientRect().top;
+      const dTop = top - prevTop;
+      const dS = S - prevS;
+      const dH = H - prevH;
+
+      // scrolltest.js formula (layout-Y change)
+      const dev = top - (prevTop - dS);
+      if (Math.abs(dev) > 2) layoutDevJumps.push(Math.round(dev));
+
+      // True visual jump on screen while scrolling up (rawWheel <= 0) or idle:
+      // Upward wheel moves rows DOWN on screen (dTop >= 0) by up to the delivered wheel delta
+      // (clamped by prevS when not prepending). A 1-frame lag between the DOM wheel event and
+      // compositor scroll commit is allowed via prevUnusedUp, but expires after 1 frame so
+      // clobbered scrolls or hidden shrink jumps are still caught.
+      const curUp = Math.max(0, -rawWheel);
+      const maxOldUp = prependLanded ? prevUnusedUp : Math.min(prevUnusedUp, prevS);
+      const carryableCurUp = Math.min(curUp, Math.max(0, prevS - maxOldUp));
+      const maxCurUp = prependLanded ? curUp : carryableCurUp;
+      let jump = 0;
+      if (dTop < -2) {
+        jump = dTop;
+        prevUnusedUp = carryableCurUp;
+      } else {
+        const useOld = Math.min(Math.max(0, dTop), maxOldUp);
+        const remAfterOld = Math.max(0, dTop - useOld);
+        const useCur = Math.min(remAfterOld, maxCurUp);
+        const excessDown = remAfterOld - useCur;
+        const expiredOld = maxOldUp - useOld;
+        if (excessDown > 2) {
+          jump = excessDown;
+        } else if (expiredOld > 2 && prevS > 0 && S > 0) {
+          jump = -expiredOld;
+        }
+        prevUnusedUp = Math.max(0, carryableCurUp - useCur);
+      }
+
+      if (Math.abs(jump) > 2) {
+        const rowEl = anchor.querySelector('[data-row-id]');
+        visualJumps.push({
+          t: Math.round(now - start),
+          jump: Math.round(jump),
+          dTop: Math.round(dTop),
+          wheel: Math.round(rawWheel),
+          dS: Math.round(dS),
+          dH: Math.round(dH),
+          S: Math.round(S),
+          idx: String(anchor.dataset.index ?? ''),
+          rowId: rowEl ? String(rowEl.getAttribute('data-row-id')) : '',
+          reason: prependLanded ? 'prepend' : dH !== 0 ? 'resize' : 'scroll',
+        });
+      }
+    } else if (anchor) {
+      anchorLost += 1;
+      prevUnusedUp = 0;
+    }
+
+    anchor = pickAnchor();
+    prevTop = anchor ? anchor.getBoundingClientRect().top : 0;
+    prevS = S;
+    prevH = H;
+    requestAnimationFrame(step);
+  };
+  requestAnimationFrame(step);
+
+  window.__STOP_MEASURER__ = () => {
+    running = false;
+    obs.forEach((o) => o.disconnect());
+    const sorted = [...frames].sort((a, b) => a - b);
+    const q = (p) => Math.round(sorted[Math.floor(sorted.length * p)] || 0);
+    const st = window.__HARNESS_STATE__ || { pagesLoaded: 0, loadedCount: 0 };
+    return {
+      frames: frames.length,
+      over33: frames.filter((f) => f > 33).length,
+      over50: frames.filter((f) => f > 50).length,
+      p95: q(0.95),
+      maxFrameMs: Math.round(sorted.at(-1) || 0),
+      visualJumps: visualJumps.length,
+      visualJumpAbsSum: visualJumps.reduce((a, b) => a + Math.abs(b.jump), 0),
+      visualJumpSamples: visualJumps.slice(0, 15),
+      layoutShiftsDev: layoutDevJumps.length,
+      layoutShiftsDevAbsSum: layoutDevJumps.reduce((a, b) => a + Math.abs(b), 0),
+      anchorLost,
+      longTasks,
+      cls: +shifts.reduce((a, b) => a + b.v, 0).toFixed(4),
+      shifts: shifts.length,
+      pagesLoaded: st.pagesLoaded,
+      loadedRows: st.loadedCount,
+      finalScrollTop: Math.round(scroller.scrollTop),
+      finalScrollHeight: scroller.scrollHeight,
+    };
+  };
+})()`;
+
+async function sleep(ms: number) {
+  await new Promise((r) => setTimeout(r, ms));
+}
+
+async function runScenario(
+  cdp: CdpClient,
+  baseUrl: string,
+  spec: ScenarioSpec,
+): Promise<ScenarioResult> {
+  const { targetId } = await cdp.send<{ targetId: string }>("Target.createTarget", {
+    url: `${baseUrl}/?${spec.query}`,
+  });
+  await cdp.send("Target.activateTarget", { targetId });
+  const { sessionId } = await cdp.send<{ sessionId: string }>("Target.attachToTarget", {
+    targetId,
+    flatten: true,
+  });
+  try {
+    await cdp.send("Page.enable", {}, sessionId);
+    await cdp.send("Page.bringToFront", {}, sessionId);
+    await cdp.send("Runtime.enable", {}, sessionId);
+
+    // Wait for VirtualLog to render and settle at the bottom.
+    for (let attempt = 0; attempt < 100; attempt += 1) {
+      const check = await cdp.send<{ result: { value: boolean } }>(
+        "Runtime.evaluate",
+        {
+          expression: `Boolean(window.__HARNESS_STATE__?.ready && document.querySelectorAll('[data-index]').length > 0)`,
+          returnByValue: true,
+        },
+        sessionId,
+      );
+      if (check.result.value) break;
+      await sleep(30);
+    }
+    await sleep(150);
+
+    // Start frame measurer.
+    await cdp.send("Runtime.evaluate", { expression: 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.idleAtTopMs) {
+      await sleep(spec.idleAtTopMs);
+    }
+
+    const res = await cdp.send<{ result: { value: Omit<ScenarioResult, "name"> } }>(
+      "Runtime.evaluate",
+      { expression: `window.__STOP_MEASURER__()`, returnByValue: true },
+      sessionId,
+    );
+    return { name: spec.name, ...res.result.value };
+  } finally {
+    await cdp.send("Target.closeTarget", { targetId }).catch(() => {});
+  }
+}
+
+export async function runScrollStabilityCheck(
+  repoRoot: string,
+  scenarios: ScenarioSpec[] = SCENARIOS,
+): Promise<ScenarioResult[]> {
+  const chromiumBin = findChromium();
+  if (!chromiumBin) throw new Error("No Chromium binary found on this machine");
+  const cacheDir = join(repoRoot, "node_modules", ".cache", "virtual-log-scroll-harness");
+  const bundleJs = await bundleHarness(repoRoot);
+  const { server, baseUrl } = await startServer(bundleJs);
+  const { proc, wsUrl, userDataDir } = await launchChromium(chromiumBin, cacheDir);
+  const cdp = await CdpClient.connect(wsUrl);
+  try {
+    const results: ScenarioResult[] = [];
+    for (const spec of scenarios) {
+      results.push(await runScenario(cdp, baseUrl, spec));
+    }
+    return results;
+  } finally {
+    cdp.close();
+    proc.kill("SIGKILL");
+    server.closeAllConnections();
+    server.close();
+    rmSync(userDataDir, { recursive: true, force: true });
+  }
+}
+
+if (import.meta.main) {
+  const repoRoot = resolve(import.meta.dirname, "..");
+  const filter = process.argv[2];
+  const chosen = filter ? SCENARIOS.filter((s) => s.name.includes(filter)) : SCENARIOS;
+  const results = await runScrollStabilityCheck(repoRoot, chosen);
+  console.log(
+    "scenario".padEnd(30),
+    "frames".padStart(6),
+    ">33ms".padStart(6),
+    "p95".padStart(5),
+    "vJumps".padStart(7),
+    "vJumpPx".padStart(8),
+    "devJmp".padStart(7),
+    "lost".padStart(5),
+    "longT".padStart(6),
+    "cls".padStart(7),
+    "pages".padStart(6),
+    "scrollTop/H",
+  );
+  let failed = false;
+  for (const r of results) {
+    console.log(
+      r.name.padEnd(30),
+      String(r.frames).padStart(6),
+      String(r.over33).padStart(6),
+      String(r.p95).padStart(5),
+      String(r.visualJumps).padStart(7),
+      String(r.visualJumpAbsSum).padStart(8),
+      String(r.layoutShiftsDev).padStart(7),
+      String(r.anchorLost).padStart(5),
+      String(r.longTasks.length).padStart(6),
+      r.cls.toFixed(4).padStart(7),
+      String(r.pagesLoaded).padStart(6),
+      `${r.finalScrollTop}/${r.finalScrollHeight}`,
+    );
+    for (const sample of r.visualJumpSamples.slice(0, 6)) {
+      console.log(
+        `  jump t=${sample.t}ms jump=${sample.jump}px dTop=${sample.dTop} wheel=${sample.wheel} dS=${sample.dS} dH=${sample.dH} S=${sample.S} idx=${sample.idx} (${sample.rowId}) [${sample.reason}]`,
+      );
+    }
+    if (r.visualJumps > 0) failed = true;
+  }
+  process.exit(failed ? 1 : 0);
+}
A scripts/virtual-log-scroll.test.ts
@@ -0,0 +1,65 @@
+// Browser scroll-stability threshold test for VirtualLog (scripts/check-virtual-log-scroll.ts).
+// Runs in real headless Chromium with wheel events across the four failure modes:
+// boundary-merging prepends at scrollTop 0, late reflows during backward scroll, idle prepend at
+// top, all-4px pages, and mixed 4px/2,000px pages.
+import { resolve } from "node:path";
+import { expect, test } from "vitest";
+import {
+  findChromium,
+  runScrollStabilityCheck,
+  type ScenarioSpec,
+} from "./check-virtual-log-scroll.ts";
+
+const REPO_ROOT = resolve(import.meta.dirname, "..");
+
+const THRESHOLD_SCENARIOS: ScenarioSpec[] = [
+  {
+    name: "small-pages-boundary-merge",
+    query:
+      "totalRows=200&initialRows=22&pageSizes=4,7,3,12,17,5,9&pageDelayMs=400&mergeBoundary=1&lateReflow=0",
+    scrollMs: 3_500,
+    speedPxPerSec: 2_000,
+  },
+  {
+    name: "mid-list-mixed-and-reflow",
+    query:
+      "totalRows=240&initialRows=240&pageSizes=10&pageDelayMs=400&mergeBoundary=0&lateReflow=1",
+    scrollMs: 2_800,
+    speedPxPerSec: 2_500,
+  },
+  {
+    name: "idle-at-top-page-lands",
+    query:
+      "totalRows=120&initialRows=22&pageSizes=5,3,15,40&pageDelayMs=300&mergeBoundary=1&lateReflow=0",
+    scrollMs: 900,
+    speedPxPerSec: 3_000,
+    idleAtTopMs: 1_400,
+  },
+  {
+    name: "tiny-4px-and-2000px-pages",
+    query:
+      "totalRows=200&initialRows=22&pageSizes=3,1,30,8&pageDelayMs=300&mergeBoundary=1&lateReflow=1",
+    scrollMs: 3_000,
+    speedPxPerSec: 2_000,
+  },
+];
+
+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 },
+  async () => {
+    const results = await runScrollStabilityCheck(REPO_ROOT, THRESHOLD_SCENARIOS);
+    for (const r of results) {
+      const detail = `${r.name}: ${JSON.stringify(r.visualJumpSamples)}`;
+      expect(r.frames, `${r.name}: rendered frames`).toBeGreaterThan(30);
+      expect(r.visualJumps, `${detail}`).toBe(0);
+      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);
+      expect(r.over33 / r.frames, `${r.name}: >33ms frame share`).toBeLessThanOrEqual(0.15);
+    }
+  },
+);
A src/components/virtual-log/virtual-log-scroll.test.tsx
@@ -0,0 +1,144 @@
+// @vitest-environment jsdom
+// Unit checks for VirtualLog scroll stability: pixel-based overscan over runs of 4 px rows and
+// surviving-row fallback anchoring when a prepend re-keys the oldest row at scrollTop 0.
+import { act, type ReactElement } from "react";
+import { createRoot } from "react-dom/client";
+import { beforeAll, expect, test } from "vitest";
+import { VirtualLog, type VirtualLogRowInfo } from "./virtual-log.tsx";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+
+beforeAll(() => {
+  if (typeof globalThis.ResizeObserver === "undefined") {
+    globalThis.ResizeObserver = class {
+      observe() {}
+      unobserve() {}
+      disconnect() {}
+    } as unknown as typeof ResizeObserver;
+  }
+});
+
+type TestRow = { id: string; offset: number; estimate: number };
+
+const ROW_INFO: VirtualLogRowInfo<TestRow> = {
+  key: (row) => row.id,
+  estimateSize: (row) => row.estimate,
+  offset: (row) => row.offset,
+};
+
+function mount(element: ReactElement, rowHeight = 0) {
+  const ownClientHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "clientHeight");
+  const ownOffsetHeight = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "offsetHeight");
+  Object.defineProperty(HTMLElement.prototype, "clientHeight", {
+    configurable: true,
+    get: () => 600,
+  });
+  Object.defineProperty(HTMLElement.prototype, "offsetHeight", {
+    configurable: true,
+    get(this: HTMLElement) {
+      return this.hasAttribute("data-index") ? rowHeight : 0;
+    },
+  });
+  const container = document.createElement("div");
+  document.body.appendChild(container);
+  const root = createRoot(container);
+  act(() => {
+    root.render(element);
+  });
+  return {
+    container,
+    rerender(next: ReactElement) {
+      act(() => {
+        root.render(next);
+      });
+    },
+    [Symbol.dispose]() {
+      act(() => root.unmount());
+      container.remove();
+      document.body.replaceChildren();
+      if (ownClientHeight)
+        Object.defineProperty(HTMLElement.prototype, "clientHeight", ownClientHeight);
+      else delete (HTMLElement.prototype as unknown as Record<string, unknown>).clientHeight;
+      if (ownOffsetHeight)
+        Object.defineProperty(HTMLElement.prototype, "offsetHeight", ownOffsetHeight);
+      else delete (HTMLElement.prototype as unknown as Record<string, unknown>).offsetHeight;
+    },
+  };
+}
+
+test("pixel overscan mounts more than 16 tiny 4 px rows above the viewport", () => {
+  const rows: TestRow[] = Array.from({ length: 200 }, (_, i) => ({
+    id: `r-${i}`,
+    offset: i + 1,
+    estimate: 4,
+  }));
+  using view = mount(
+    <VirtualLog
+      rows={rows}
+      rowInfo={ROW_INFO}
+      renderRow={(row) => <div data-row={row.id}>{row.id}</div>}
+      label="Tiny rows"
+    />,
+  );
+  const scroller = view.container.querySelector<HTMLDivElement>('[data-slot="virtual-log"]')!;
+  // Scroll away from end into the middle of the 4px rows.
+  act(() => {
+    scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: -120, bubbles: true }));
+    scroller.scrollTop = 400;
+    scroller.dispatchEvent(new Event("scroll"));
+  });
+  const mounted = [...scroller.querySelectorAll<HTMLElement>("[data-index]")].map((el) =>
+    Number(el.dataset.index),
+  );
+  const minIndex = Math.min(...mounted);
+  // startIndex is around 100 (400px / 4px). Old overscan: 16 would only reach index 84;
+  // pixel overscan (1600px, capped at 120 rows) mounts all the way to index 0.
+  expect(minIndex).toBeLessThan(50);
+});
+
+test("prepend at scrollTop 0 advances scrollTop even when old row 0 is re-keyed", () => {
+  const initial: TestRow[] = Array.from({ length: 20 }, (_, i) => ({
+    id: `row-${100 + i}`,
+    offset: 100 + i,
+    estimate: 60,
+  }));
+  using view = mount(
+    <VirtualLog
+      rows={initial}
+      rowInfo={ROW_INFO}
+      renderRow={(row) => <div data-row={row.id}>{row.id}</div>}
+      label="Prepend test"
+    />,
+    60,
+  );
+  const scroller = view.container.querySelector<HTMLDivElement>('[data-slot="virtual-log"]')!;
+  Object.defineProperty(scroller, "scrollHeight", { configurable: true, get: () => 2_400 });
+  // Leave the end and stand at scrollTop 0.
+  act(() => {
+    scroller.dispatchEvent(new WheelEvent("wheel", { deltaY: -120, bubbles: true }));
+    scroller.scrollTop = 0;
+    scroller.dispatchEvent(new Event("scroll"));
+  });
+  expect(scroller.scrollTop).toBe(0);
+
+  // Prepend 5 rows (5 * 60 = 300 px) AND re-key old row 0 (row-100 -> merged-95-100), so
+  // virtual-core's single-key anchor misses while row-101..row-119 survive.
+  const prepended: TestRow[] = [
+    ...Array.from({ length: 5 }, (_, i) => ({
+      id: `row-${95 + i}`,
+      offset: 95 + i,
+      estimate: 60,
+    })),
+    { ...initial[0]!, id: "merged-95-100" },
+    ...initial.slice(1),
+  ];
+  view.rerender(
+    <VirtualLog
+      rows={prepended}
+      rowInfo={ROW_INFO}
+      renderRow={(row) => <div data-row={row.id}>{row.id}</div>}
+      label="Prepend test"
+    />,
+  );
+  expect(scroller.scrollTop).toBe(300);
+});
A src/test-support/virtual-log-scroll-harness.tsx
@@ -0,0 +1,283 @@
+// Browser harness for VirtualLog scroll stability checks (scripts/check-virtual-log-scroll.ts).
+// Renders VirtualLog directly with a deterministic mix of row heights (4 px, 24 px, 50-450 px,
+// 2,000 px), delayed older pages of varied sizes, optional page-boundary key replacement (as in
+// AgentChat's folded turns), and optional post-mount height reflow.
+import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { createRoot } from "react-dom/client";
+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 HarnessRow = {
+  id: string;
+  offset: number;
+  kind: RowKind;
+  height: number;
+  /** Optional second height settled after mount to emulate late content/CSS reflow. */
+  reflowHeight?: number;
+  reflowDelayMs?: number;
+};
+
+type HarnessConfig = {
+  /** Total rows in the synthetic log. */
+  totalRows: number;
+  /** Rows loaded initially at the bottom. */
+  initialRows: number;
+  /** Page sizes cycled when loading older pages (e.g. [4, 7, 3, 12, 17, 5]). */
+  pageSizes: number[];
+  /** Delay in ms before an older page lands. */
+  pageDelayMs: number;
+  /** When true, every other older page replaces the previous oldest row's key (emulating
+   *  AgentChat's folded activity/background turn merging across a page boundary). */
+  mergeBoundary: boolean;
+  /** When true, ~10% of rows settle to a different height 40 ms after mount. */
+  lateReflow: boolean;
+  /** Optional override for uniform tiny4 rows (e.g. testing 4px overscan buffer). */
+  tinyBurst?: boolean;
+};
+
+const ESTIMATE: Record<RowKind, number> = {
+  tiny4: 36,
+  compact24: 36,
+  user: 96,
+  assistant: 72,
+  widget: 140,
+};
+
+const ROW_INFO: VirtualLogRowInfo<HarnessRow> = {
+  key: (row) => row.id,
+  estimateSize: (row) => ESTIMATE[row.kind],
+  offset: (row) => row.offset,
+};
+
+function mulberry32(seed: number) {
+  let state = seed >>> 0;
+  return () => {
+    state = (state + 0x6d2b79f5) >>> 0;
+    let t = Math.imul(state ^ (state >>> 15), 1 | state);
+    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+  };
+}
+
+function buildRows(cfg: HarnessConfig): HarnessRow[] {
+  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
+  // row-count overscan of 16 rows = 64 px fails to pre-mount the 2,000 px row before it enters view).
+  const hugeOffsets = new Set([
+    Math.floor(cfg.totalRows * 0.15),
+    70 + 12, // immediately above the 24 consecutive 4px rows at i=82..105!
+    140 + 12, // immediately above the 24 consecutive 4px rows at i=152..175!
+  ]);
+  for (let i = 0; i < cfg.totalRows; i += 1) {
+    const offset = i + 1;
+    // Include runs of 24 consecutive 4px rows so row-count overscan (16 rows = 64px) is exhausted.
+    // Keep the initial bottom window non-tiny even in tinyBurst mode so the viewport starts overflowed.
+    if ((cfg.tinyBurst && i < cfg.totalRows - cfg.initialRows) || (i % 70 >= 12 && i % 70 < 36)) {
+      rows.push({ id: `row-${offset}`, offset, kind: "tiny4", height: 4 });
+      continue;
+    }
+    if (hugeOffsets.has(offset)) {
+      rows.push({ id: `row-${offset}`, offset, kind: "widget", height: 2_000 });
+      continue;
+    }
+    const r = rand();
+    let kind: RowKind;
+    let height: number;
+    if (r < 0.42) {
+      kind = "tiny4";
+      height = 4;
+    } else if (r < 0.64) {
+      kind = "compact24";
+      height = 24;
+    } else if (r < 0.84) {
+      kind = "user";
+      height = Math.round(50 + rand() * 350);
+    } else {
+      kind = "assistant";
+      height = Math.round(56 + rand() * 394);
+    }
+    const doReflow = cfg.lateReflow && kind !== "tiny4" && i % 9 === 0;
+    const reflowHeight = doReflow
+      ? kind === "compact24"
+        ? 4
+        : Math.max(24, height + (i % 18 === 0 ? 180 : -24))
+      : undefined;
+    rows.push({
+      id: `row-${offset}`,
+      offset,
+      kind,
+      height,
+      reflowHeight,
+      reflowDelayMs: doReflow ? 40 : undefined,
+    });
+  }
+  return rows;
+}
+
+const RowView = memo(function RowView({ row }: { row: HarnessRow }) {
+  const [height, setHeight] = useState(row.height);
+  useEffect(() => {
+    if (row.reflowHeight === undefined) return;
+    const timer = window.setTimeout(() => setHeight(row.reflowHeight!), row.reflowDelayMs ?? 40);
+    return () => window.clearTimeout(timer);
+  }, [row.reflowHeight, row.reflowDelayMs]);
+  return (
+    <div
+      data-row-id={row.id}
+      data-kind={row.kind}
+      style={{
+        height: `${height}px`,
+        boxSizing: "border-box",
+        borderBottom: "1px solid #e5e7eb",
+        padding: row.height <= 8 ? "0 8px" : "4px 8px",
+        fontSize: "12px",
+        overflow: "hidden",
+        background:
+          row.kind === "widget"
+            ? "#eef2ff"
+            : row.kind === "user"
+              ? "#f8fafc"
+              : row.kind === "tiny4"
+                ? "#f1f5f9"
+                : "#ffffff",
+      }}
+    >
+      {row.height > 8 ? `${row.id} (${row.kind}, ${height}px)` : null}
+    </div>
+  );
+});
+
+declare global {
+  interface Window {
+    __HARNESS_STATE__?: {
+      loadedCount: number;
+      totalRows: number;
+      pagesLoaded: number;
+      prepends: Array<{ t: number; added: number; mergedBoundary: boolean }>;
+      ready: boolean;
+    };
+  }
+}
+
+function readConfig(): HarnessConfig {
+  const params = new URLSearchParams(window.location.search);
+  const pageSizesParam = params.get("pageSizes");
+  return {
+    totalRows: Number(params.get("totalRows") ?? 240),
+    initialRows: Number(params.get("initialRows") ?? 18),
+    pageSizes: pageSizesParam ? pageSizesParam.split(",").map(Number) : [4, 7, 3, 12, 17, 5, 9],
+    pageDelayMs: Number(params.get("pageDelayMs") ?? 450),
+    mergeBoundary: params.get("mergeBoundary") === "1",
+    lateReflow: params.get("lateReflow") === "1",
+    tinyBurst: params.get("tinyBurst") === "1",
+  };
+}
+
+export function HarnessApp() {
+  const cfg = useMemo(readConfig, []);
+  const allRows = useMemo(() => buildRows(cfg), [cfg]);
+  const [windowStart, setWindowStart] = useState(() =>
+    Math.max(0, cfg.totalRows - cfg.initialRows),
+  );
+  const [mergedIds, setMergedIds] = useState<ReadonlyMap<number, string>>(() => new Map());
+  const [loading, setLoading] = useState(false);
+  const pageIndexRef = useRef(0);
+  const timerRef = useRef<number | null>(null);
+  const prependsRef = useRef<Array<{ t: number; added: number; mergedBoundary: boolean }>>([]);
+
+  const rows = useMemo(() => {
+    const slice = allRows.slice(windowStart);
+    if (mergedIds.size === 0) return slice;
+    return slice.map((row) => {
+      const merged = mergedIds.get(row.offset);
+      return merged ? { ...row, id: merged } : row;
+    });
+  }, [allRows, windowStart, mergedIds]);
+
+  const loadOlder = useCallback(() => {
+    if (loading || windowStart <= 0) return;
+    setLoading(true);
+    const pageIdx = pageIndexRef.current;
+    pageIndexRef.current += 1;
+    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;
+        });
+      }
+      prependsRef.current.push({ t: performance.now(), added, mergedBoundary: shouldMerge });
+      setWindowStart(nextStart);
+      setLoading(false);
+    }, cfg.pageDelayMs);
+  }, [loading, windowStart, cfg.pageSizes, cfg.pageDelayMs, cfg.mergeBoundary, allRows]);
+
+  useEffect(
+    () => () => {
+      if (timerRef.current !== null) window.clearTimeout(timerRef.current);
+    },
+    [],
+  );
+
+  const older = useMemo<OlderPages>(
+    () => ({
+      loadOlder,
+      loading,
+      exhausted: windowStart <= 0,
+    }),
+    [loadOlder, loading, windowStart],
+  );
+
+  useLayoutEffect(() => {
+    window.__HARNESS_STATE__ = {
+      loadedCount: rows.length,
+      totalRows: cfg.totalRows,
+      pagesLoaded: pageIndexRef.current,
+      prepends: prependsRef.current,
+      ready: true,
+    };
+  });
+
+  const renderRow = useCallback((row: HarnessRow) => <RowView row={row} />, []);
+
+  return (
+    <div style={{ height: "100vh", display: "flex", flexDirection: "column" }}>
+      <VirtualLog
+        rows={rows}
+        rowInfo={ROW_INFO}
+        renderRow={renderRow}
+        older={older}
+        readingOlder={<span style={{ fontSize: "12px", padding: "0 8px" }}>Loading older...</span>}
+        footer={
+          <div
+            style={{
+              height: "84px",
+              background: "#ffffff",
+              borderTop: "1px solid #d1d5db",
+              padding: "12px",
+              boxSizing: "border-box",
+            }}
+          >
+            Composer footer
+          </div>
+        }
+        label="Harness chat"
+        paddingStart={8}
+        paddingEnd={8}
+      />
+    </div>
+  );
+}
+
+const rootEl = document.getElementById("root");
+if (rootEl) createRoot(rootEl).render(<HarnessApp />);