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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/web-load-visible-files-first.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"hunkdiff": patch
---

Load the files a browser review is showing, or was just asked to jump to, before the rest of a large review, and keep a jumped-to file in place while the others arrive.
23 changes: 17 additions & 6 deletions docs/web-review-client.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ packages/hunk/src/web/
session/sessionEnded.ts tells controls the session ended; they disable, reading stays
stream/highlightGeometry.ts agent attention marks measured over drawn characters
mirror/fileIndex.ts per-file index entries and the pluggable index source
mirror/fileLoadOrder.ts which file a free read takes: jump target, viewport, the rest
store/clientReviewStore.ts the page's local core/review store and gap source loads
panel/SidePanel.tsx the docked, resizable, tabbed side panel frame
panel/panelPreferences.ts panel open state, width, and tab, per browser
Expand Down Expand Up @@ -88,10 +89,15 @@ packages/hunk/src/web/
through `reviewErrorCatalog`.
- **Mirror** (`clientReviewMirror.ts`) owns the published position and the files. It classifies
every publication with `classifyReviewPublication`; a gap (a reload, or the first
publication) loads that generation's `canonical-file` resources in catalog order with
bounded parallelism, through one `createSupersedeQueue`, parsing each with
`parseCanonicalReviewFile`. The first generation is published progressively; a later one
replaces the shown document only once complete, and a failed reload keeps the old one. A
publication) loads that generation's `canonical-file` resources with bounded parallelism,
through one `createSupersedeQueue`, parsing each with `parseCanonicalReviewFile`. Each free
read slot takes the next file from `fileLoadOrder.ts`: a jump's target still waiting for its
file (an agent's navigate, a deep link, go-to-file, a sidebar click), then the files the
stream is about to draw, then the rest in document order; the page names them with
`prioritize`, and reads not yet started follow the new order. The first generation is
published progressively — a wanted file within a frame, the rest batched every 250 ms, since
each published document re-renders the whole stream — and a later one replaces the shown
document only once complete, and a failed reload keeps the old one. A
generation that arrives while the first is still loading replaces nothing finished, so it
loads progressively too and a failure reaches the `failed` stage.
Per-file index entries (path, change kind, stats, flags, line counts, hunk count) are
Expand Down Expand Up @@ -252,6 +258,9 @@ imports; a page fetches only the languages and themes it shows. The largest sing
remembered height and hunk geometry in the render that sees it (`streamMeasurements.ts`), and a
file that collapses drops its geometry, so a reveal never lands on offsets from a drawing that
is gone.
The stream reports the sections in that window, loaded or not, so the missing ones load
first. While the first generation is still loading, a revealed target is held in place
against files landing above it until the reader's own input.
Native scroll anchoring absorbs height changes above the reader, and a reload re-pins the
top file and offset for a moment while files re-render. Pierre's `Virtualizer`/`CodeView`
were not used: they own scrolling of the whole document, which would put sticky headers,
Expand Down Expand Up @@ -641,15 +650,17 @@ the shared-state snapshot lists only marks that still match each file's `content
- `packages/hunk/src/web/**/*.test.ts` — the API client (window boundaries, digest and size
refusals, bounded parallelism, abort), event reader (SSE splitting, chunked reassembly,
digest refusal), event stream (backoff with a fake clock, terminal states), mirror (ordering,
progressive load, supersede, failed reload), and store (local intents, gap source, reload).
progressive load, wanted files first, supersede, failed reload), load order, and store
(local intents, gap source, reload).
- `test/review-conformance/` registers the browser mirror as an ordering consumer, the
browser event reader as an event consumer, and the browser file projection as a geometry
consumer (gaps, empty reasons, and the rows an expanded gap puts in Pierre's metadata), and
the composer's blank-body check against the note-body corpus.
- `test/web/review-stream.e2e.ts` drives a rich review (rename, new, deleted, binary,
too-large, gaps, a non-ASCII path, many files): progressive load, sidebar and stream jumps,
layout and theme switching, gap expansion, reload keeping the reader's place, and axe;
`test/web/review-large.e2e.ts` keeps a 2,000-file review responsive.
`test/web/review-large.e2e.ts` keeps a 2,000-file review responsive and draws a file jumped
to with go-to-file or `hunk session navigate` long before the rest have loaded.
`test/web/review-screenshots.e2e.ts` captures the page when `HUNK_WEB_SCREENSHOT_DIR` is set.
`test/web/review-notes.e2e.ts` drives a headless session with the agent's own commands:
sidecar and STML notes, live comments added, batched, replied to (and a reviewer reply),
Expand Down
15 changes: 13 additions & 2 deletions packages/hunk/src/web/app/ReviewApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -509,9 +509,13 @@ export function ReviewApp({ session }: { session: ReviewSession }) {
return;
}
if (!agentReveal || token <= lastAgentReveal.current) return;
// A target file still loading is not handled yet: the effect runs again as files arrive.
// A target file still loading is loaded next and handled once it arrives: the effect runs
// again as files land.
const { document } = session.review.store.getSnapshot();
if (!document.files.some((file) => file.key === agentReveal.fileKey)) return;
if (!document.files.some((file) => file.key === agentReveal.fileKey)) {
session.mirror.prioritize("target", [agentReveal.fileKey]);
return;
}
lastAgentReveal.current = token;
setRevealPoint({
fileKey: agentReveal.fileKey,
Expand All @@ -527,6 +531,11 @@ export function ReviewApp({ session }: { session: ReviewSession }) {
...(agentReveal.noteId !== undefined ? { activeNoteId: agentReveal.noteId } : {}),
});
}, [agentReveal, review.document, session, setRevealPoint]);
// The files the stream is about to draw load ahead of the rest of a long review.
const prioritizeViewport = useCallback(
(fileKeys: readonly string[]) => session.mirror.prioritize("viewport", fileKeys),
[session],
);
// A note the selection asks to show is where its hunk reveal lands, when nothing more exact
// (an agent's line) is pending for that file.
const noteToReveal = review.reveal.scrollToNote ? selectActiveRevealNoteId(review) : undefined;
Expand Down Expand Up @@ -1168,6 +1177,8 @@ export function ReviewApp({ session }: { session: ReviewSession }) {
{...(streamRevealPoint ? { revealPoint: streamRevealPoint } : {})}
composers={composers}
interaction={interactive.interaction}
onViewportFiles={prioritizeViewport}
loading={mirror.status === "loading"}
viewedStatuses={viewed.statuses}
collapsedFiles={viewed.collapsed}
viewed={viewedControls}
Expand Down
48 changes: 45 additions & 3 deletions packages/hunk/src/web/app/useReviewTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,46 @@ export function useReviewTools(options: ReviewToolsOptions) {
[],
);

// A jump to a file that has not loaded yet (go-to-file or the sidebar early in a long
// review) loads that file next and lands once it arrives; a later jump replaces it.
const pendingJump = useRef<ReviewAddress | undefined>(undefined);
/** Show one address, or wait for its file when it is still loading. */
const showOrWait = useCallback(
(address: ReviewAddress) => {
pendingJump.current = undefined;
if (show(address)) return;
const mirror = session.mirror.getSnapshot();
const loading = mirror.status === "loading" || mirror.updating;
const missing = !session.review.store
.getSnapshot()
.document.files.some((file) => file.key === address.fileKey);
if (!loading || !missing) return;
pendingJump.current = address;
session.mirror.prioritize("target", [address.fileKey]);
},
[session, show],
);
useEffect(() => {
const retry = () => {
const address = pendingJump.current;
if (!address) return;
const loaded = session.review.store
.getSnapshot()
.document.files.some((file) => file.key === address.fileKey);
if (loaded) {
showOrWait(address);
Comment on lines +273 to +277

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.

return;
}
// A generation that finished without the file has nothing to land on.
const mirror = session.mirror.getSnapshot();
if (mirror.status !== "loading" && !mirror.updating) pendingJump.current = undefined;
};
const stops = [session.review.store.subscribe(retry), session.mirror.subscribe(retry)];
return () => {
for (const stop of stops) stop();
};
}, [session, showOrWait]);

/** A deliberate jump: a new history entry, then the move. */
const jumpTo = useCallback(
(address: ReviewAddress) => {
Expand All @@ -256,14 +296,14 @@ export function useReviewTools(options: ReviewToolsOptions) {
// not stack duplicates for Back to walk through.
const here = currentAddress();
if (here && formatReviewAddress(here) === formatReviewAddress(addressAfterJump(address))) {
show(address);
showOrWait(address);
return;
}
if (resolvedInitial.current) writeAddress(here, "replace");
writeAddress(address, "push");
show(address);
showOrWait(address);
},
[currentAddress, show, writeAddress],
[currentAddress, showOrWait, writeAddress],
);

// Resolve the link's address once its target has arrived; until then the page does not
Expand All @@ -289,6 +329,8 @@ export function useReviewTools(options: ReviewToolsOptions) {
resolvedInitial.current = true;
return;
}
// The linked file loads before the rest of the review.
session.mirror.prioritize("target", [address.fileKey]);
const mirror = session.mirror.getSnapshot();
const sharedGeneration = session.shared.getSnapshot().body?.state.generation;
const complete =
Expand Down
54 changes: 52 additions & 2 deletions packages/hunk/src/web/mirror/clientReviewMirror.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { afterEach, describe, expect, test } from "bun:test";
import { createTestDiffFile } from "../../../../../test/helpers/diff-helpers";
import { serveTestWebReview } from "../../../../../test/helpers/web-review-server";
import { ReviewApiError, type ReviewApiClient } from "../transport/apiClient";
import { ClientReviewMirror, type ClientReviewMirrorSnapshot } from "./clientReviewMirror";
import { ReviewApiClient, ReviewApiError } from "../transport/apiClient";
import {
ClientReviewMirror,
type ClientReviewMirrorNotifyWait,
type ClientReviewMirrorSnapshot,
} from "./clientReviewMirror";

const running: Array<() => void> = [];

Expand Down Expand Up @@ -73,6 +77,52 @@ describe("ClientReviewMirror", () => {
expect(ready.slots.every((slot) => slot.index?.path === slot.file?.path)).toBe(true);
});

// Intent: in a long review the file a jump targets, then the files around the viewport,
// load before the rest, and only they are worth a prompt re-render of the page.
test("loads the files the page wants first and shows them sooner than the rest", async () => {
const served = serve(
["alpha", "beta", "gamma", "delta", "epsilon"].map((id) =>
createTestDiffFile({
id,
path: `src/${id}.ts`,
after: `export const ${id} = 1;\n`,
before: `export const ${id} = 0;\n`,
}),
),
);
// One read at a time, so the order reads start in is the order files land in.
const client = new ReviewApiClient({
sessionId: served.sessionId,
capability: served.capability,
fetch: served.fetch,
concurrency: 1,
});
const waits: ClientReviewMirrorNotifyWait[] = [];
const mirror = new ClientReviewMirror({
client,
scheduleNotify: (flush, wait) => {
waits.push(wait);
flush();
},
});
running.push(() => mirror.close());
const landed: string[] = [];
mirror.subscribe(() => {
for (const file of mirror.getSnapshot().document.files) {
if (!landed.includes(file.key)) landed.push(file.key);
}
});
const keys = served.harness.producer.getPublication().document.files.map((file) => file.key);

mirror.prioritize("target", [keys[4]!]);
mirror.prioritize("viewport", [keys[2]!, keys[4]!]);
mirror.observe(await client.publication());
await waitForTestStatus(mirror, "ready");

expect(landed).toEqual([4, 2, 0, 1, 3].map((position) => keys[position]!));
expect(waits).toEqual(["frame", "frame", "batch", "batch", "batch"]);
});

test("ignores a stale publication and moves on an accepted one", async () => {
const served = serve();
const client = served.client();
Expand Down
Loading
Loading