Skip to content

Commit dd29927

Browse files
committed
fix(inspector): reject preview reload races
Return the live document generation from the same page invocation as each query and reject mismatches. Rearm browser cleanup for failures before a page operation starts, and cover reloads across all three live operations.
1 parent 9e0b2a5 commit dd29927

13 files changed

Lines changed: 81 additions & 42 deletions

File tree

‎.fallowrc.jsonc‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
// Inspector is a private Bun service with CLI-driven browser contract
1313
// scripts; its runtime module is bundled by file path into the page.
1414
"packages/inspector/src/{service,server,mcp}.ts",
15+
"packages/inspector/src/liveRuntime.ts",
1516
"packages/inspector/tests/*.ts",
1617
"packages/core/src/runtime/inspection.ts",
1718
"packages/producer/src/regression-harness.ts",
@@ -117,6 +118,12 @@
117118
"packages/cli/bin/**",
118119
],
119120
"ignoreExports": [
121+
// Browser helper public API, paired with elementMap.d.ts and consumed by
122+
// external harnesses rather than another workspace package.
123+
{
124+
"file": "packages/inspector/src/elementMap.js",
125+
"exports": ["createElementMap"],
126+
},
120127
// Public player-state types are consumed by package users outside this
121128
// workspace. Keep the barrel stable even when no in-repo import needs it.
122129
{
@@ -1038,6 +1045,12 @@
10381045
"packages/inspector/src/sourceDependencies.ts",
10391046
"packages/core/src/runtime/timelineInspection.ts",
10401047
"packages/cli/src/commands/timeline.ts",
1048+
// Protocol validators and deterministic report formatters enumerate wire
1049+
// variants explicitly; splitting those branches would scatter one contract.
1050+
"packages/inspector/src/requests.ts",
1051+
"packages/inspector/src/timelineReport.ts",
1052+
"packages/inspector/src/pageQueries.ts",
1053+
"packages/core/src/runtime/timelineValues.ts",
10411054
],
10421055
},
10431056
}

‎packages/inspector/src/elementMap.d.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ export interface ElementNode {
1818
children: number[];
1919
}
2020
export interface ElementDom {
21+
generation: string | null;
2122
nodes: ElementNode[];
2223
limitations: { canvas: number; iframes: number; shadowRoots: number };
2324
}

‎packages/inspector/src/elementMap.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ export function collectElementDom() {
8787
}
8888
if (document.body) visit(document.body, null);
8989
return {
90+
generation: window.__hfLiveInspection?.generation ?? null,
9091
nodes,
9192
limitations: {
9293
canvas: nodes.filter((node) => node.tag === "canvas").length,

‎packages/inspector/src/engine.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,22 @@ export interface SourceContext {
1111
map: ReturnType<Sources["mapper"]>;
1212
}
1313

14-
/** One loaded page of the project, whichever browser holds it. */
1514
export interface InspectionView {
1615
readonly generation: string;
1716
readonly sourceVersion: string;
18-
/** The project's source index and the page's line mapping, built on first use. */
17+
readonly pageGeneration?: string;
1918
sourceContext(): SourceContext;
20-
/** Rejects when the project's sources changed after the page loaded, so an answer never mixes two versions. */
2119
assertCurrent(): Promise<void>;
2220
}
2321

2422
export type ComponentReport = ReturnType<typeof mapInspection>;
2523
export type ElementMapReport = ElementMap & { sourceVersion: string; generation: string };
2624

25+
function assertPageGeneration(view: InspectionView, actual: string | null) {
26+
if (view.pageGeneration !== undefined && actual !== view.pageGeneration)
27+
throw new Error("stale_preview: the preview reloaded; query again");
28+
}
29+
2730
export async function inspectComponents(
2831
runner: PageRunner,
2932
view: InspectionView,
@@ -41,6 +44,7 @@ export async function inspectComponents(
4144
descendants: request.descendants ?? true,
4245
cssRules: sources.cssRules.map(({ id, selector }) => ({ id, selector })),
4346
});
47+
assertPageGeneration(view, raw.generation);
4448
await view.assertCurrent();
4549
return mapInspection(raw, request, {
4650
...context,
@@ -58,6 +62,7 @@ export async function inspectTimeline(
5862
reused: boolean,
5963
): Promise<TimelineReport> {
6064
const raw = await runner.run(timelinePage, request);
65+
assertPageGeneration(view, raw.generation);
6166
await view.assertCurrent();
6267
return formatTimeline(raw, request, {
6368
generation: view.generation,
@@ -71,7 +76,9 @@ export async function inspectElementMap(
7176
view: InspectionView,
7277
file = "index.html",
7378
): Promise<ElementMapReport> {
74-
const map = formatElementMap(await runner.run(collectElementDom, undefined), { file });
79+
const snapshot = await runner.run(collectElementDom, undefined);
80+
assertPageGeneration(view, snapshot.generation);
81+
const map = formatElementMap(snapshot, { file });
7582
await view.assertCurrent();
7683
return { ...map, sourceVersion: view.sourceVersion, generation: view.generation };
7784
}

‎packages/inspector/src/live.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,9 @@ import { assertGeneration, validateInspectRequest, validateTimelineRequest } fro
1717
import { Sources, fingerprint } from "./sources";
1818
import type { InspectRequest, Snippet } from "./types";
1919

20-
/**
21-
* A preview document prepared for inspection in the browser that shows it. The host loads `html` in its preview and
22-
* answers queries by handing in a runner for that frame; nothing here launches a browser or moves the player.
23-
*/
2420
export interface LiveInspection {
2521
readonly html: string;
2622
readonly generation: string;
27-
/** The HTML the host finally served (it may add scripts after bundling), which line mapping must describe. */
2823
finalizeDocument(servedHtml: string): void;
2924
inspect(runner: PageRunner, request: InspectRequest): Promise<ComponentReport>;
3025
timeline(runner: PageRunner, request: TimelineRequest): Promise<TimelineReport>;
@@ -51,6 +46,7 @@ export function prepareLiveInspection(
5146
const view: InspectionView = {
5247
generation,
5348
sourceVersion,
49+
pageGeneration: generation,
5450
sourceContext() {
5551
if (!context) {
5652
const sources = new Sources(project);
@@ -63,7 +59,6 @@ export function prepareLiveInspection(
6359
throw new Error("stale_preview: the project changed; query again once the preview reloads");
6460
},
6561
};
66-
/** The runner must reach this generation's document, and the sources must still be the ones it was built from. */
6762
async function current(runner: PageRunner): Promise<void> {
6863
if ((await previewGeneration(runner)) !== generation)
6964
throw new Error("stale_preview: the preview reloaded; query again");
@@ -100,7 +95,6 @@ export function prepareLiveInspection(
10095
};
10196
}
10297

103-
/** The generation of the live document a runner reaches, or null when it reaches no prepared preview. */
10498
export function previewGeneration(runner: PageRunner): Promise<string | null> {
10599
return runner.run(liveGenerationPage, undefined);
106100
}

‎packages/inspector/src/mcp.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import { componentsTool, timelineTool as timelineDefinition, toolContent } from
44
const url = process.env.HF_INSPECT_URL;
55
if (!url || !/^http:\/\/(127\.0\.0\.1|localhost):\d+$/.test(url))
66
throw new Error("Set HF_INSPECT_URL to the local HF inspection service URL.");
7-
// The harness renames these (hf_grep_components, hf_grep_timeline); hosts with their own MCP use the same definitions.
87
const tool = { name: "inspect_components", ...componentsTool };
98
const timelineTool = { name: "inspect_timeline", ...timelineDefinition };
109
const input = createInterface({ input: process.stdin });

‎packages/inspector/src/pageQueries.ts‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,17 +5,17 @@ import type {
55
} from "../../core/src/runtime/timelineInspection";
66
import type { RuntimeQuery, RuntimeResponse } from "./types";
77

8-
/**
9-
* Runs a function inside the inspected document: Puppeteer's page for headless inspection, the host's preview frame
10-
* for live inspection. `fn` crosses into the page as source text, so it may not refer to anything outside its body.
11-
*/
128
export interface PageRunner {
139
run<A, R>(fn: (arg: A) => R, arg: A): Promise<R>;
1410
}
1511

1612
export interface PageTimeline extends TimelineRuntimeResult {
17-
/** At a boundary: for each animation crossing it, the next one on the same target and property. */
1813
following: TimelineEvent[];
14+
generation: string | null;
15+
}
16+
17+
export interface PageRuntimeResponse extends RuntimeResponse {
18+
generation: string | null;
1919
}
2020

2121
type InspectedWindow = Window & {
@@ -36,7 +36,6 @@ export interface PlayerState {
3636
duration: number | undefined;
3737
}
3838

39-
/** Moves the player, so only a page the inspector owns may run it, never a person's preview. */
4039
export function seekPage(time: number): void {
4140
const player = (window as InspectedWindow).__player;
4241
if (!player) throw new Error("player_unavailable");
@@ -48,18 +47,24 @@ export function playerStatePage(): PlayerState {
4847
return { time: player?.getTime(), duration: player?.getDuration() };
4948
}
5049

51-
export function queryPage(query: RuntimeQuery): RuntimeResponse {
52-
const inspection = (window as InspectedWindow).__hfInspection;
50+
export function queryPage(query: RuntimeQuery): PageRuntimeResponse {
51+
const inspected = window as InspectedWindow;
52+
const inspection = inspected.__hfInspection;
5353
if (!inspection) throw new Error("inspector_unavailable");
54-
return inspection.query(query);
54+
return {
55+
generation: inspected.__hfLiveInspection?.generation ?? null,
56+
...inspection.query(query),
57+
};
5558
}
5659

5760
export function timelinePage(request: TimelineRequest): PageTimeline {
58-
const inspection = (window as InspectedWindow).__hfInspection;
61+
const inspected = window as InspectedWindow;
62+
const inspection = inspected.__hfInspection;
5963
if (!inspection) throw new Error("inspector_unavailable");
6064
const result = inspection.timeline(request);
6165
const following: TimelineEvent[] = [];
62-
if (request.boundary === undefined) return { ...result, following };
66+
const generation = inspected.__hfLiveInspection?.generation ?? null;
67+
if (request.boundary === undefined) return { ...result, following, generation };
6368
const boundary = request.boundary;
6469
const schedule = inspection.timeline({ ...request, boundary: undefined });
6570
for (const crossing of result.events) {
@@ -77,10 +82,9 @@ export function timelinePage(request: TimelineRequest): PageTimeline {
7782
if (next && !following.includes(next)) following.push(next);
7883
}
7984
}
80-
return { ...result, following };
85+
return { ...result, following, generation };
8186
}
8287

83-
/** The generation stamped into a live preview when its document was prepared, or null in any other page. */
8488
export function liveGenerationPage(): string | null {
8589
return (window as InspectedWindow).__hfLiveInspection?.generation ?? null;
8690
}

‎packages/inspector/src/pageServer.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import type { Server } from "node:http";
22

3-
// Chrome's preconnect sockets never send a request, so under Node close() alone never resolves.
43
export function closeServer(server: Server): Promise<void> {
54
const closed = new Promise<void>((done) => server.close(() => done()));
65
server.closeAllConnections();

‎packages/inspector/src/requests.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,6 @@ export function validateTimelineRequest(request: TimelineRequest): void {
6767
if (offset && !request.generation) throw new Error("pagination requires generation");
6868
}
6969

70-
/** A continuation (generation, snippet ids, offset) names the page it was paged from; any other page is stale. */
7170
export function assertGeneration(requested: string | undefined, current: string): void {
7271
if (requested && requested !== current)
7372
throw new Error("stale_generation: query targets again after source changes or idle disposal");

‎packages/inspector/src/service.ts‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,6 @@ import { closeServer } from "./pageServer";
3232
import { Sources, fingerprint } from "./sources";
3333
import type { InspectRequest, Snippet } from "./types";
3434

35-
// Page functions take and return JSON data, for which Puppeteer's handle unwrapping is the identity.
3635
const pageRunner = (page: Page): PageRunner => ({
3736
run: <A, R>(fn: (arg: A) => R, arg: A) =>
3837
page.evaluate(fn as (arg: unknown) => R, arg) as Promise<R>,
@@ -296,22 +295,21 @@ export class Inspector {
296295
return this.serialize(async () => {
297296
if (this.closed) throw new Error("inspector_disposed");
298297
clearTimeout(this.timer);
299-
if (!existsSync(join(this.project, "index.html"))) throw new Error("no-composition");
300-
const { session } = await this.ensure();
301298
try {
299+
if (!existsSync(join(this.project, "index.html"))) throw new Error("no-composition");
300+
const { session } = await this.ensure();
302301
return await inspectElementMap(pageRunner(session.page), this.view(session));
303302
} finally {
304303
this.idle();
305304
}
306305
});
307306
}
308-
/** Test/host diagnostics only; the agent tool does not expose arbitrary page execution. */
309307
async withPage<T>(fn: (page: Page) => Promise<T>) {
310308
return this.serialize(async () => {
311309
if (this.closed) throw new Error("inspector_disposed");
312310
clearTimeout(this.timer);
313-
const { session } = await this.ensure();
314311
try {
312+
const { session } = await this.ensure();
315313
return await fn(session.page);
316314
} finally {
317315
this.idle();

0 commit comments

Comments
 (0)