Skip to content

perf(web): load the files the reader is looking at first - #1354

Merged
benvinegar merged 1 commit into
mainfrom
perf/web-load-visible-files-first
Nov 22, 2026
Merged

benvinegar merged 1 commit into
mainfrom
perf/web-load-visible-files-first

Conversation

@benvinegar

@benvinegar benvinegar commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Problem

The browser review loads a review's canonical-file resources in catalog order, 4 at a time, and every batch of landed files re-rendered the whole stream (all 2,000 sections, the sidebar, the minimap) and re-observed every section with a new IntersectionObserver. The main thread was saturated by rendering, so reads crawled: on main, after jumping to the last file of a 2,000-file review (hunk session navigate <id> --file <last>), that file stayed "Loading…" for ~30 s, until everything else had loaded. A go-to-file or sidebar jump to a file that had not loaded yet silently did nothing. review-large.e2e.ts hid this behind 120 s timeouts.

Approach

  • Load order (mirror/fileLoadOrder.ts, new): each free read slot takes the next file from a live order: a jump's target still waiting for its file (agent navigate, deep link, go-to-file, sidebar), then the files the stream is about to draw (its mount window, 1.5 viewports), then the rest in document order. The page names them with ClientReviewMirror.prioritize("target" | "viewport", keys); reads not started yet follow the new order, reads in flight finish. ReviewApiClient.readResources takes an optional ReviewResourceReadOrder (pull-based) instead of a fixed index walk. Concurrency is unchanged (the shared bound of 4), the supersede queue still cancels an older generation's load, and aborted reads are still dropped at the daemon.
  • Notification cadence: a wanted file is published within a frame (16 ms); background files are batched every 250 ms, because each published document re-renders a stream as long as the review. The mirror builds a snapshot lazily once per notification instead of copying the slot array per landed file (that was O(n²) over a load).
  • Jumps to files not loaded yet: go-to-file and sidebar jumps now wait for (and prioritize) the file, like agent reveals and deep links already did; a later jump replaces the wait.
  • Stability while loading: files landing above a revealed target change height (the plan's reserved rows include gap separators the index's line counts do not), and native scroll anchoring did not keep the target put, so the viewport drifted and viewport anchoring moved the selection. While the first generation is loading, a revealed target is now re-placed from the body ResizeObserver (before paint) and keeps the selection until the reader's own wheel, touch, pointer, or key input, or a scroll command. After loading, behavior is as before.
  • Per-file cost: the stream re-observes sections only when the set of file keys changes, not on every landed file; an unmeasured resource is hashed once (its second hash verified the bytes against their own digest).

Non-goals: no change to the daemon/session side, the wire, or the shared read concurrency; no worker-based highlighting (Pierre already only mounts files near the viewport). Mirror-the-TUI does not apply (the terminal loads its document locally).

Measurements

Same machine (Linux, 4 vCPU, shared with other jobs, so absolute numbers moved between runs), Chromium headless 1280×720, production (minified) build of each tree. "Target rows" is from issuing the jump to the jumped-to file's diff rows existing in its shadow root (includes the hunk session navigate CLI process, 0.4–1.6 s); "all loaded" is until the toolbar's load progress disappears; heap is CDP JSHeapUsedSize sampled every 200 ms (peak) and after a forced GC at the end.

Scenario Target rows All loaded Peak heap Heap after GC
2,000 tiny files, navigate --file <last> (3 runs) main 39.8 / 42.4 / 33.8 s 39.9 / 42.6 / 34.0 s 289 / 317 / 279 MB 61 MB
this PR 3.2 / 2.5 / 2.5 s 9.0 / 7.8 / 7.0 s 173 / 173 / 162 MB 61 MB
2,000 tiny files, go-to-file to the last file main never (jump ignored) 34.0 s 279 MB 59 MB
this PR 2.6 s 7.3 s 143 MB 60 MB
48 MB patch, 1,688 files, navigate --file <last> main 51.0 s 51.6 s 517 MB 164 MB
this PR 6.1 s 15.5 s 214 MB 163 MB

An earlier, quieter run on main measured 32.1 s / 32.2 s / 274 MB for the first row. The heap that remains after GC is the loaded document itself and is unchanged; the peak drop is garbage from the per-file re-renders. In this PR's runs the target file stayed selected and in view after everything finished loading.

Benchmark script (Playwright, uses the repo's web test harness)

Save as bench/load.bench.ts next to bench/playwright.config.ts (testDir: ".", testMatch: "**/*.bench.ts", workers: 1, timeout: 900_000, use: devices["Desktop Chrome"]), symlink bench/node_modules to the checkout's node_modules, bun run build:web in the checkout, then:

HUNK_ROOT=/path/to/checkout node_modules/.bin/playwright test --config bench/playwright.config.ts
# BENCH_JUMP=picker for go-to-file; BENCH_INPUT=/path/to.patch BENCH_LAST=<path> for a patch
import { test } from "@playwright/test";
import { join } from "node:path";

const ROOT = process.env.HUNK_ROOT!;
const INPUT = process.env.BENCH_INPUT ?? "--many=2000";
const LAST = process.env.BENCH_LAST ?? "pkg19/dir9/file-1999.ts";
const JUMP = process.env.BENCH_JUMP ?? "navigate";

test(`load ${INPUT}`, async ({ page }) => {
  const { startTestWebReview } = await import(join(ROOT, "test/web/webTestHarness.ts"));
  const review = await startTestWebReview(INPUT);
  try {
    await page.addInitScript(() =>
      window.localStorage.setItem("hunk.review.view", '{"sidebarMode":"flat"}'),
    );
    const cdp = await page.context().newCDPSession(page);
    await cdp.send("Performance.enable");
    const heap = async () =>
      (await cdp.send("Performance.getMetrics")).metrics.find((m) => m.name === "JSHeapUsedSize")!.value;
    let peak = 0;
    let sampling = true;
    const sampler = (async () => {
      while (sampling) {
        peak = Math.max(peak, await heap().catch(() => 0));
        await new Promise((r) => setTimeout(r, 200));
      }
    })();

    await page.goto(review.url);
    await page.getByTestId("file-count").filter({ hasText: /files?$/ }).waitFor({ timeout: 120_000 });
    const jumped = Date.now();
    if (JUMP === "navigate") {
      await review.hunk(["session", "navigate", review.sessionId, "--file", LAST, "--hunk", "1"]);
    } else {
      await page.getByTestId("review-stream").focus();
      await page.keyboard.press("Control+p");
      await page.keyboard.type(LAST.split("/").pop()!);
      await page.getByTestId("go-to-file").getByRole("option").first().waitFor();
      await page.keyboard.press("Enter");
    }
    let targetRowsMs = -1;
    const rows = page
      .waitForFunction(
        (path) => {
          const section = document.querySelector(`section[aria-label="${CSS.escape(path)}"]`);
          return Boolean(section?.querySelector("diffs-container")?.shadowRoot?.querySelector("[data-line]"));
        },
        LAST,
        { timeout: 300_000, polling: 50 },
      )
      .then(() => (targetRowsMs = Date.now() - jumped));
    await page.getByTestId("load-progress").waitFor({ state: "detached", timeout: 300_000 });
    const allLoadedMs = Date.now() - jumped;
    await Promise.race([rows, new Promise((r) => setTimeout(r, 5_000))]);
    sampling = false;
    await sampler;
    await cdp.send("HeapProfiler.collectGarbage");
    const mb = (bytes: number) => +(bytes / 2 ** 20).toFixed(1);
    console.log(JSON.stringify({ targetRowsMs, allLoadedMs, peakHeapMB: mb(peak), heapAfterGcMB: mb(await heap()) }));
  } finally {
    await review.stop();
  }
});

The patch was generated with 1,688 modified .ts files of 4 hunks × (3 context + 45 removed + 45 added + 3 context) lines each (≈48 MB). Note: a 41 MB patch shaped as 12 hunks × 10 lines per file never registered with the daemon (the page waited for the publication). I saw it on this branch, whose session side is identical to main; it looks like a separate session-side limit and is not touched here.

Tests and checks

  • bun run typecheck, bun run lint, bun run format:check, bun run deps:check: pass.
  • bun test packages/hunk/src/web test/review-conformance scripts/quality/source-boundaries.test.ts: 535 pass. New: fileLoadOrder.test.ts (target, viewport, background order; live reprioritization; each file once), a mirror test (target and viewport files land first and notify on a frame, the rest batched), and an apiClient test (reads follow a caller's order).
  • bun run build:web && npx playwright test --config test/web/playwright.config.ts --trace off test/web/review-large.e2e.ts test/web/review-stream.e2e.ts test/web/review-stream-measurement.e2e.ts test/web/review-keyboard.e2e.ts test/web/review-palette.e2e.ts test/web/review-notes.e2e.ts test/web/review-shell.e2e.ts test/web/review-sidebar.e2e.ts test/web/review-interactive.e2e.ts: all pass (73 tests).
  • review-large.e2e.ts is tightened: right after the file count shows, a go-to-file jump to file 1000 and then hunk session navigate to file 1999 must each be selected and draw diff rows within 15 s (previously ~30 s on an idle machine, so this keeps headroom for a loaded runner and still fails on the old ordering); the whole load must finish within 90 s (was 120 s), and the navigated file must still be selected and in view afterwards. Run against main, the new test fails at the go-to-file step (the jump is ignored), and with that step removed it fails at the navigate step (15 s timeout).

Platforms: Linux only (Chromium headless). Not tested on macOS or Windows.

Repro

bun run build:web
# a 2,000-file staged review (as test/web/fixtures/rich-review.ts writeManyReviewRepo builds), then:
hunk diff --staged --web
hunk session navigate <session> --file pkg19/dir9/file-1999.ts --hunk 1   # right after the page opens

Known limitations

  • Total load time is still bounded by re-rendering the full stream on each batch (now ~4 per second); a stream that re-renders only changed sections would cut it further.
  • The held reveal is released only by the reader's input (wheel, touch, pointer, key, scroll commands, minimap); a script that sets scrollTop directly during the first load does not release it until loading ends.
  • Viewport priority is the stream's whole mount window in document order, not nearest-first.

https://claude.ai/code/session_01Nn5HpgDBQrjicbK5ZoZnMG


Generated by Claude Code

A large browser review loaded every canonical file in catalog order and re-rendered the
whole stream for each batch, so a file jumped to at the end of a 2,000-file review stayed
"Loading…" for ~30 s. Free read slots now take a jump's target (agent navigate, deep link,
go-to-file, sidebar), then the files near the viewport, then the rest in document order;
wanted files are shown within a frame and background files are batched every 250 ms.
Go-to-file and sidebar jumps to a file that has not loaded yet now wait for it instead of
doing nothing, and a revealed file stays in place while files above it land.

The stream no longer re-observes every section when a file lands, the mirror builds each
snapshot once per notification instead of copying the slots per file, and an unmeasured
resource is hashed once instead of twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Nn5HpgDBQrjicbK5ZoZnMG
@greptile-apps

greptile-apps Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The changes affect loading and navigation across browser-based reviews.

Fix cancellation of waiting jumps before merging so Back cannot be undone by a file arriving later.

Findings

  1. P1 Back leaves waiting jumps active ▶
Fix with agent prompt
### Issue 1
packages/hunk/src/web/app/useReviewTools.tsx:273-277
Pick an unloaded file in go-to-file, then press Back before it arrives. `onPopState` calls `show` without clearing `pendingJump`, so this retry jumps to the abandoned file when it loads. The selection subscription also overwrites the current history entry with that file’s address.

Clear or replace the waiting jump when browser history moves, and test Back while the chosen file is still loading.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

This PR loads jump targets and nearby files before background files.

  • Jump targets and files near the reader load before the rest of the review.
  • Files arriving during a review cause fewer expensive page updates.
  • A revealed file stays selected and in view while the first load finishes.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Free read slot] --> B{Unread jump target?}
  B -->|Yes| E[Read file]
  B -->|No| C{Unread nearby file?}
  C -->|Yes| E
  C -->|No| D[Next file in document order]
  D --> E
  E --> F{File wanted now?}
  F -->|Yes| G[Notify within a frame]
  F -->|No| H[Batch background updates]
  G --> I[Update review document]
  H --> I
Loading

Reviews (1) · Last reviewed commit: "perf(web): load the files the reader is ..." · Reviewed by Greptile

Comment on lines +273 to +277
const loaded = session.review.store
.getSnapshot()
.document.files.some((file) => file.key === address.fileKey);
if (loaded) {
showOrWait(address);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Back leaves waiting jumps active

Pick an unloaded file in go-to-file, then press Back before it arrives. onPopState calls show without clearing pendingJump, so this retry jumps to the abandoned file when it loads. The selection subscription also overwrites the current history entry with that file’s address.

Clear or replace the waiting jump when browser history moves, and test Back while the chosen file is still loading.

Prompt To Fix With AI
This is a comment left during a code review.
Path: packages/hunk/src/web/app/useReviewTools.tsx
Line: 273-277

Comment:
**Back leaves waiting jumps active**

Pick an unloaded file in go-to-file, then press Back before it arrives. `onPopState` calls `show` without clearing `pendingJump`, so this retry jumps to the abandoned file when it loads. The selection subscription also overwrites the current history entry with that file’s address.

Clear or replace the waiting jump when browser history moves, and test Back while the chosen file is still loading.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@benvinegar
benvinegar merged commit 70c505a into main Nov 22, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants