iterate.com / ui

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

Virtual log: what the reader sees stands still when an older page lands and when a row above is measured (#6)

Measured on the Dash's /agents/main feed (28 Nov 2026 00:37 UTC, perf/scroll-check.mjs of /repos/chat): on the way up 114 row jumps (7,289 px). A page of older rows that lands while the reader stands at the list's top pops into the view, and rows above the view that are measured again move what the reader sees.

Causes and fix (virtual-log.tsx, use-reader.ts):
- TanStack anchors a prepend on ONE row, the row at the scroll offset. At the top that is row 0, and the feed's fold gives row 0 a new key when the older page joins its burst: no anchor. Now the first visible row that survived keeps its place.
- A re-measured row above the view was not corrected while the reader went up; a first measurement at the view's top was not corrected at all. Now both are (shouldAdjustScrollPositionOnItemSizeChange).
- A correction was written from the offset of the last scroll event, over a wheel move that came since. Now it goes to the live scrollTop (scrollToFn).
- The overscan counted rows (16 rows of 4 px are no buffer). Now 1,600 px, at least 4 rows, at most 120.

Proof: scripts/check-virtual-log-scroll.ts, a headless Chromium check of 7 scenarios with real wheel input: before, up to 9 visible jumps and 1,358 px in one scenario; after, 0 in all 7 (run twice, by the author and by the reviewer). It is kept as a test with thresholds (scripts/virtual-log-scroll.test.ts). pnpm check passes on 73b58a4 (113 files, 1,256 tests).

Not tested on an iPhone: scroll writes are held while a finger moves, as the core does.

Written by Antigravity (Gemini 4 Neon, high) from the brief of the Claude Code session below, which reviewed it, ran its check again and mended the harness's colours.

Card: tasks/make-the-dash-scroll-and-render-smoothly-on-large-logs-like.md of /repos/task-board.
Session: claude e7bfeefe-1067-494b-8f63-82177cb1beb9 on beelink

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_0158EjAGDfCugWqZ9a2JTTgL

Iterate-Run: /@1527782

jonas, 2026-11-28 00:41 UTC · 5b5842e774dff86a828cdfc9fc65cecf399674da · parent 9dadff7

6 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);
+    }
+  },
+);
M src/components/virtual-log/use-reader.ts
@@ -184,6 +184,7 @@
     touchingRef,
     pressedRef,
     scrollingRef,
+    ownWriteRef,
     follow,
     keepAtEnd,
     runOwnScroll,
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);
+});
M src/components/virtual-log/virtual-log.tsx
@@ -42,14 +42,15 @@
 // Vertical breathing room is `paddingStart` and `paddingEnd`, not wrapper padding the virtualizer
 // cannot see. A row's spacing is padding, not margin, and a row renders its real height at once (no
 // deferred content): the first measurement is the one the anchor trusts.
-import { useCallback, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
 import { ArrowDownIcon, ArrowUpIcon } from "lucide-react";
 import {
-  defaultRangeExtractor,
+  elementScroll,
   useVirtualizer,
   type Range,
   type Rect,
   type Virtualizer,
+  type VirtualizerOptions,
 } from "@tanstack/react-virtual";
 import { cn } from "cn";
 import {
@@ -65,6 +66,12 @@
  *  rows and not on blank. */
 const EDGE_ROWS = 40;
 
+/** Pixel overscan above and below the viewport, so runs of tiny 4 px rows still hold enough
+ *  runway to measure off-screen before scrolling into view, while 2,000 px rows are not over-mounted. */
+const OVERSCAN_PX = 1_600;
+const MIN_OVERSCAN_ROWS = 4;
+const MAX_OVERSCAN_ROWS = 120;
+
 /** The tail's virtual key: its index moves up as rows land above it, and keyed by index its (often
  *  tall) measurement would pass to the row that takes its place. */
 const TAIL_KEY = "virtual-log/tail";
@@ -150,47 +157,31 @@
 }) {
   const scrollRef = useRef<HTMLDivElement>(null);
   const footerRef = useRef<HTMLDivElement>(null);
+  const listContainerRef = useRef<HTMLDivElement | null>(null);
   const reader = useReader(footerRef, rows.length, onAtEndChange);
   const { atEnd, atTop, atEndRef, goingToTopRef, touchingRef, pressedRef, follow, runOwnScroll } =
     reader;
   const attachedToHead = newer.exhausted;
   const visibleTail = attachedToHead ? tail : undefined;
-  const rangeExtractor = useCallback(
-    (range: Range) => {
-      const indexes = defaultRangeExtractor(range);
-      const bound = goingToTopRef.current ? 0 : atEnd ? range.count - EDGE_ROWS : null;
-      if (bound === null) return indexes;
-      const from = Math.max(bound, 0);
-      const edge = Array.from({ length: Math.min(EDGE_ROWS, range.count) }, (_, at) => from + at);
-      return [...new Set([...indexes, ...edge])].sort((a, b) => a - b);
-    },
-    [atEnd, goingToTopRef],
-  );
-  const getItemKey = useCallback(
-    (index: number) => (index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY),
-    [rowInfo, rows],
-  );
-  const estimateSize = useCallback(
-    (index: number) => (index < rows.length ? rowInfo.estimateSize(rows[index]!) : TAIL_ESTIMATE),
-    [rowInfo, rows],
-  );
   const count = rows.length + (visibleTail ? 1 : 0);
-  const virtualizer = useVirtualizer({
+  const virtualizer = useLogVirtualizer({
+    rows,
+    rowInfo,
     count,
-    getScrollElement: () => scrollRef.current,
-    estimateSize,
-    getItemKey,
-    anchorTo: "end",
-    scrollEndThreshold: SCROLL_END_THRESHOLD,
-    overscan: 16,
     paddingStart,
     paddingEnd,
-    observeElementRect: (instance, report) =>
-      observeRowsRect(instance, report, footerRef.current!, () => reader.keepAtEnd(instance)),
-    rangeExtractor,
-    directDomUpdates: true,
-    onChange: reader.keepAtEnd,
+    scrollRef,
+    footerRef,
+    listContainerRef,
+    reader,
   });
+  const setListContainerRef = useCallback(
+    (node: HTMLDivElement | null) => {
+      listContainerRef.current = node;
+      virtualizer.containerRef(node);
+    },
+    [virtualizer],
+  );
 
   const prevFollowTailRef = useRef(followTail);
   useLayoutEffect(() => {
@@ -267,7 +258,7 @@
         {count === 0 ? (
           empty
         ) : (
-          <div ref={virtualizer.containerRef} className="relative w-full">
+          <div ref={setListContainerRef} className="relative w-full">
             {virtualizer.getVirtualItems().map((virtualItem) => (
               <div
                 key={virtualItem.key}
@@ -354,6 +345,307 @@
       {arrived > 0 ? <span className="tabular-nums text-foreground">{arrived} new</span> : null}
     </ScrollBubble>
   );
+}
+
+type LayoutSnapshot = {
+  firstKey: string | null;
+  count: number;
+  items: Array<{ key: string; start: number; end: number }>;
+};
+
+/** Configures TanStack Virtual for a log with pixel-based overscan, live-`scrollTop` compensation
+ *  writes, backward-safe size-change anchoring, and a surviving-row fallback anchor when a prepend
+ *  re-keys the oldest row. */
+function useLogVirtualizer<Row>({
+  rows,
+  rowInfo,
+  count,
+  paddingStart,
+  paddingEnd,
+  scrollRef,
+  footerRef,
+  listContainerRef,
+  reader,
+}: {
+  rows: readonly Row[];
+  rowInfo: VirtualLogRowInfo<Row>;
+  count: number;
+  paddingStart: number;
+  paddingEnd: number;
+  scrollRef: { current: HTMLDivElement | null };
+  footerRef: { current: HTMLDivElement | null };
+  listContainerRef: { current: HTMLDivElement | null };
+  reader: ReturnType<typeof useReader>;
+}) {
+  const { atEnd, atEndRef, goingToTopRef, touchingRef, pressedRef, ownWriteRef } = reader;
+  const currentFirstKey = rows.length > 0 ? rowInfo.key(rows[0]!) : null;
+  const measuredSizesRef = useRef<Map<string, number>>(new Map());
+  const prevLayoutRef = useRef<LayoutSnapshot | null>(null);
+  const prependAnchoredRef = useRef(false);
+  const [, setAnchorTick] = useState(0);
+
+  const getItemKey = useCallback(
+    (index: number) => (index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY),
+    [rowInfo, rows],
+  );
+  const estimateSize = useCallback(
+    (index: number) => (index < rows.length ? rowInfo.estimateSize(rows[index]!) : TAIL_ESTIMATE),
+    [rowInfo, rows],
+  );
+  const rangeExtractor = useCallback(
+    (range: Range) => {
+      if (range.count === 0) return [];
+      const sizeOf = (index: number) => {
+        const key = index < rows.length ? rowInfo.key(rows[index]!) : TAIL_KEY;
+        return measuredSizesRef.current.get(key) ?? estimateSize(index);
+      };
+      const indexes = extractPixelOverscanRange(range, sizeOf);
+      const bound = goingToTopRef.current ? 0 : atEnd ? range.count - EDGE_ROWS : null;
+      if (bound === null) return indexes;
+      const from = Math.max(bound, 0);
+      const edge = Array.from({ length: Math.min(EDGE_ROWS, range.count) }, (_, at) => from + at);
+      return [...new Set([...indexes, ...edge])].sort((a, b) => a - b);
+    },
+    [atEnd, goingToTopRef, rows, rowInfo, estimateSize],
+  );
+  const scrollToFn = useCallback<VirtualizerOptions<HTMLDivElement, Element>["scrollToFn"]>(
+    (offset, options, instance) => {
+      const el = instance.scrollElement;
+      if (!el) return;
+      const prev = prevLayoutRef.current;
+      const isPendingPrepend =
+        prev !== null &&
+        prev.count > 0 &&
+        currentFirstKey !== null &&
+        prev.firstKey !== currentFirstKey &&
+        !prependAnchoredRef.current &&
+        !atEndRef.current &&
+        !goingToTopRef.current;
+      // Size-change compensation (`applyScrollAdjustment(delta)`):
+      // During a prepend commit's ref phase (before `_willUpdate` grows the container and anchors
+      // the prepend), defer scroll writes so we do not clamp against the old height or double-count
+      // with the prepend anchor that runs immediately after in `useLayoutEffect`.
+      // Otherwise `offset` is virtual-core's cached `scrollOffset`, which lags live `el.scrollTop`
+      // during active wheel scrolling: apply `adjustments` relative to live `el.scrollTop`.
+      if (options.adjustments) {
+        if (isPendingPrepend) return;
+        const liveTop = el.scrollTop;
+        const drift = liveTop - offset;
+        const target = Math.max(0, liveTop + options.adjustments);
+        // Inside a ResizeObserver batch, `applyScrollAdjustment` runs before `notify()` grows the
+        // list container's height. Grow it now when a positive adjustment would otherwise clamp.
+        if (
+          options.adjustments > 0 &&
+          listContainerRef.current &&
+          target > el.scrollHeight - el.clientHeight
+        ) {
+          listContainerRef.current.style.height = `${instance.getTotalSize()}px`;
+        }
+        el.scrollTop = target;
+        if (drift !== 0 && instance.scrollOffset !== null) {
+          instance.scrollOffset = Math.max(0, instance.scrollOffset + drift);
+        }
+        return;
+      }
+      // Prepend anchor write from `_willUpdate` (`pendingScrollAnchor`): compute the exact shift
+      // from a surviving visible row and apply it to live `el.scrollTop` so wheel input between
+      // the last `scroll` event and the prepend commit is never overwritten.
+      if (isPendingPrepend && !ownWriteRef.current && options.behavior === undefined) {
+        prependAnchoredRef.current = true;
+        const liveTop = el.scrollTop;
+        const delta = computePrependDelta(prev, rows, rowInfo, instance, liveTop);
+        const target = delta !== null ? Math.max(0, liveTop + delta) : Math.max(0, offset);
+        el.scrollTop = target;
+        instance.scrollOffset = target;
+        return;
+      }
+      elementScroll(offset, options, instance);
+    },
+    [atEndRef, currentFirstKey, goingToTopRef, listContainerRef, ownWriteRef, rows, rowInfo],
+  );
+  const virtualizer = useVirtualizer({
+    count,
+    getScrollElement: () => scrollRef.current,
+    estimateSize,
+    getItemKey,
+    scrollToFn,
+    anchorTo: "end",
+    scrollEndThreshold: SCROLL_END_THRESHOLD,
+    overscan: 16,
+    paddingStart,
+    paddingEnd,
+    observeElementRect: (instance, report) =>
+      observeRowsRect(instance, report, footerRef.current!, () => reader.keepAtEnd(instance)),
+    rangeExtractor,
+    directDomUpdates: true,
+    onChange: (instance) => {
+      reader.keepAtEnd(instance);
+      syncMeasuredSizes(instance, measuredSizesRef.current);
+      const prev = prevLayoutRef.current;
+      if (prev && prev.firstKey === currentFirstKey && prev.count === rows.length) {
+        prevLayoutRef.current = snapshotLayout(instance, currentFirstKey, rows.length);
+      }
+    },
+  });
+
+  useLayoutEffect(() => {
+    virtualizer.shouldAdjustScrollPositionOnItemSizeChange = (item, _delta, instance) => {
+      const scrollOffset = instance.scrollOffset ?? 0;
+      // Any row wholly above the viewport must compensate regardless of scroll direction
+      // (virtual-core's default skips re-measurement when `scrollDirection === "backward"`).
+      if (item.end <= scrollOffset) return true;
+      const viewportHeight = instance.scrollRect?.height ?? 0;
+      const mid = scrollOffset + viewportHeight / 2;
+      const isFirstMeasure = !instance.itemSizeCache.has(item.key);
+      if (isFirstMeasure) {
+        if (item.start < scrollOffset) return true;
+        if (viewportHeight > 0 && item.end <= mid) return true;
+      }
+      // Late reflow of a row strictly in the top half of the viewport keeps the middle row still,
+      // unless the reader just pressed a row to open/close it.
+      if (!pressedRef.current && viewportHeight > 0 && item.end <= mid) return true;
+      return false;
+    };
+  }, [virtualizer, pressedRef]);
+
+  useLayoutEffect(() => {
+    const el = scrollRef.current;
+    const prev = prevLayoutRef.current;
+    const handled = prependAnchoredRef.current;
+    prependAnchoredRef.current = false;
+    syncMeasuredSizes(virtualizer, measuredSizesRef.current);
+
+    if (
+      el &&
+      prev &&
+      !handled &&
+      prev.count > 0 &&
+      rows.length > 0 &&
+      prev.firstKey !== currentFirstKey &&
+      !atEndRef.current &&
+      !goingToTopRef.current &&
+      !touchingRef.current &&
+      !(isIOSWebKit() && virtualizer.isScrolling)
+    ) {
+      // virtual-core's single-key anchor missed (typically because the oldest loaded row merged
+      // with earlier events and changed key). Keep the first surviving visible row still instead.
+      const liveTop = el.scrollTop;
+      const fallbackDelta = computePrependDelta(prev, rows, rowInfo, virtualizer, liveTop);
+      if (fallbackDelta !== null && fallbackDelta !== 0) {
+        const nextOffset = Math.max(0, liveTop + fallbackDelta);
+        el.scrollTop = nextOffset;
+        virtualizer.scrollOffset = nextOffset;
+        prevLayoutRef.current = snapshotLayout(virtualizer, currentFirstKey, rows.length);
+        setAnchorTick((n) => n + 1);
+        return;
+      }
+    }
+
+    prevLayoutRef.current = snapshotLayout(virtualizer, currentFirstKey, rows.length);
+  }, [
+    rows,
+    count,
+    rowInfo,
+    currentFirstKey,
+    scrollRef,
+    virtualizer,
+    atEndRef,
+    goingToTopRef,
+    touchingRef,
+  ]);
+
+  return virtualizer;
+}
+
+/** Expands `[startIndex, endIndex]` by at least `OVERSCAN_PX` (and `MIN_OVERSCAN_ROWS`) on each
+ *  side, capped at `MAX_OVERSCAN_ROWS`. */
+function extractPixelOverscanRange(range: Range, sizeOf: (index: number) => number): number[] {
+  let start = range.startIndex;
+  let pxBefore = 0;
+  let rowsBefore = 0;
+  while (
+    start > 0 &&
+    rowsBefore < MAX_OVERSCAN_ROWS &&
+    (pxBefore < OVERSCAN_PX || rowsBefore < MIN_OVERSCAN_ROWS)
+  ) {
+    start -= 1;
+    pxBefore += sizeOf(start);
+    rowsBefore += 1;
+  }
+  let end = range.endIndex;
+  let pxAfter = 0;
+  let rowsAfter = 0;
+  while (
+    end < range.count - 1 &&
+    rowsAfter < MAX_OVERSCAN_ROWS &&
+    (pxAfter < OVERSCAN_PX || rowsAfter < MIN_OVERSCAN_ROWS)
+  ) {
+    end += 1;
+    pxAfter += sizeOf(end);
+    rowsAfter += 1;
+  }
+  return Array.from({ length: end - start + 1 }, (_, at) => start + at);
+}
+
+function snapshotLayout(
+  instance: Virtualizer<HTMLDivElement, Element>,
+  firstKey: string | null,
+  count: number,
+): LayoutSnapshot {
+  return {
+    firstKey,
+    count,
+    items: instance.getVirtualItems().map((item) => ({
+      key: String(item.key),
+      start: item.start,
+      end: item.end,
+    })),
+  };
+}
+
+function syncMeasuredSizes(
+  instance: Virtualizer<HTMLDivElement, Element>,
+  target: Map<string, number>,
+) {
+  for (const item of instance.getVirtualItems()) {
+    const size = instance.itemSizeCache.get(item.key);
+    if (size !== undefined) target.set(String(item.key), size);
+  }
+}
+
+/** Finds the first surviving visible row from the previous layout and returns how far its layout
+ *  `start` shifted, or `null` if no visible row survived. Stops at the first match in `rows`, so
+ *  prepends stay O(prepended rows) even on 100,000-row logs. */
+function computePrependDelta<Row>(
+  prev: LayoutSnapshot,
+  rows: readonly Row[],
+  rowInfo: VirtualLogRowInfo<Row>,
+  instance: Virtualizer<HTMLDivElement, Element>,
+  liveTop: number,
+): number | null {
+  const candidates = new Map<string, number>();
+  for (const oldItem of prev.items) {
+    if (oldItem.end < liveTop) continue;
+    candidates.set(oldItem.key, oldItem.start);
+  }
+  if (candidates.size === 0) return null;
+  instance.getTotalSize();
+  for (let i = 0; i < rows.length; i += 1) {
+    const oldStart = candidates.get(rowInfo.key(rows[i]!));
+    if (oldStart === undefined) continue;
+    const nextItem = instance.measurementsCache[i];
+    if (!nextItem) continue;
+    return nextItem.start - oldStart;
+  }
+  return null;
+}
+
+/** Matches `@tanstack/virtual-core`'s iOS WebKit check so we never write `scrollTop` during an
+ *  iOS momentum fling. */
+function isIOSWebKit(): boolean {
+  if (typeof navigator === "undefined") return false;
+  if (/iP(hone|od|ad)/.test(navigator.userAgent)) return true;
+  return navigator.platform === "MacIntel" && navigator.maxTouchPoints > 0;
 }
 
 /** Reports the part of the scroller the rows have: all of it less the footer over them. It is the
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 lightgray",
+        padding: row.height <= 8 ? "0 8px" : "4px 8px",
+        fontSize: "12px",
+        overflow: "hidden",
+        background:
+          row.kind === "widget"
+            ? "lavender"
+            : row.kind === "user"
+              ? "ghostwhite"
+              : row.kind === "tiny4"
+                ? "whitesmoke"
+                : "white",
+      }}
+    >
+      {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: "white",
+              borderTop: "1px solid silver",
+              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 />);