Skip to content

Commit f873734

Browse files
perf(studio): open a large film ready to play in about 4 s instead of 32 s (#4401)
* perf(studio): keep lint off the preview open path The bundler linted every build only to print a StaticGuard warning; a preview bundle now skips it through a staticGuard option, since Studio lints on its own route. That route now lints in the CLI child-process worker the render path already uses, so seconds of parsing no longer stall the preview and every other Studio request on the server event loop. * perf(parsers): parse identical GSAP source once Studio re-requests the parsed animations of unchanged source on every open, and several lint rules parse the same script in one run. A small memo keyed by the script text serves repeats; each caller gets its own copy. * perf(studio): build each preview document once per content version The preview route rebuilt the document for every browser without a cached copy. It now serves one build per ETag from memory, and the CLI keeps the last build on disk salted with its own file, so a restarted server serves the previous document without stale code. * perf(studio): build the opening film's preview while the browser starts The preview server built the document only when the player asked for it, after Studio had booted, so a first open waited about a second of idle server time. The CLI now requests the opening project's preview right after listening, and requests that arrive while a build runs share it instead of starting another. * perf(studio): request the preview document at page load Studio asked for the preview only once the player mounted, about 640 ms into a first open. It now requests it the moment the page loads, and again when the hash names another project, so the build or cache read overlaps Studio's boot. * feat(studio): show the cached frame 0 while the live preview boots Studio covers the live preview with frame 0 as the thumbnail route last rendered it, sized from the image so the stage does not shift, and removes it when the live frame is ready to show. The request is cache-only, so a miss never starts a render on the open path; the missing poster is rendered after the live frame shows, for the next open. * perf(cli): start Studio before the startup lint finishes hyperframes preview linted the whole project before it listened, 4 to 6 s on a large film, and did so in --json mode where the result is discarded. The lint now runs in the CLI worker while Studio starts and prints its summary when done; --json skips it. * perf(studio): render thumbnails from one loaded page, after the preview boots Every thumbnail opened a page and loaded the whole composition to shoot one frame, and the Compositions card asked for one while the live preview was still booting. The server now keeps one loaded page per preview document and seeks it per frame, reloading only when the project changes; card thumbnails wait for the project first ready preview. * perf(studio): parse GSAP animations after the preview boots Studio asked the server to parse the composition animations while the preview was opening; on a fresh server that cold parse ran on the event loop ahead of the preview build. The request now waits for the live preview to boot, or to fail loading, since only keyframes need it. * perf(cli): find orphaned browsers with one process-table read preview ran pgrep three times and then ps once per matching browser, all synchronously before listening: about half a second on a machine running other headless Chrome. One ps listing now finds every orphan in ~20 ms. * perf(studio): keep lint off the boot Opening a project started two lint processes while Studio booted: the terminal's startup lint and Studio's background lint, ~4 s of CPU next to the boot. Studio's background lint now waits until the live preview has booted, and lint processes run at the lowest CPU priority so they only take idle CPU. * perf(studio): open the editing session after the preview boots Opening a project read the composition source and parsed it for the editing session (linkedom plus hf-id assignment) on the main thread while the live preview was booting on the same thread: ~300 ms on a large film. The session now opens once the preview has booted; nothing the first frame shows needs it. * perf(studio): park the editor overlays until the preview boots The overlay frame loop polled preview geometry and off-canvas indicators from the first frame, forcing layout on a preview document that was still loading, on the thread its boot runs on: ~200 ms before the first frame on a large film. The loop now skips its subscribers until the preview has booted, then wakes. * perf(studio): treat the preview as booted once it can play Work deferred until the boot (editing session, lint, overlays, GSAP parse, card thumbnails) started at timeline-ready, which fires before the asset gate, so the editing-session parse ran inside the wait for play. The Player now latches the boot when the preview can show and play, or fails to load. * fix(studio): keep a left project's deferred work out of the one now open Deferred open-time work (source parse, background lint, editing session) waited on one global boot flag, so leaving a project before its preview booted let the next project's boot run the old project's work and write its results. The wait is now per project and resolves false once another project opens. A preview stuck without an error stops deferring that work after 5 s. * perf(cli): let the play page revalidate instead of refetching hyperframes play served the composition, its assets, the player and the runtime with no validator, so every reload refetched everything, the mp4 in full three times. They now carry an ETag and stay no-cache, so unchanged bytes cost a 304 and an edit is still seen. * fix(cli): serve an edited text asset even when its size and mtime match The play page tagged every asset by mtime and size, so a same-size rewrite within one filesystem tick kept the old tag and the browser kept stale bytes. Text assets now get a content-hash tag; media keeps the mtime and size tag Studio already uses. * fix(studio): close idle thumbnail pages so an idle Studio runs no composition Kept-loaded thumbnail pages stayed open for the life of the server, each running a live composition, so an idle Studio cost server CPU and memory that main does not. A page now closes after 10 s unused, and a page is closed only after the frame still running on it finishes. * fix(studio): stop a first open from reloading the preview once per scene file Studio stamped hf-ids into a composition the first time that composition was served, so opening a film of external scenes wrote to index.html and every scene file mid-session. Each write reached Studio as an outside edit and reloaded the preview, which failed for a large film. The server now stamps every composition once before it starts watching the project. * fix(studio): ignore play until the preview can play, so it is never undone Space (and any play() caller) could start playback before the preview frame finished loading. Its load step then paused and rewound to the restore point, so the play was silently lost. play() now waits for timelineReady, the same gate the Play button already uses. * fix(studio): hold play on a composition switch until the new preview loads Readiness was reset only when the project changed. Drilling into another composition kept the old ready flag while the new preview loaded, so Play or Space could start a play that its load step then undid. * refactor(studio): split background lint and thumbnail page reuse into single-purpose steps Keeps the boot wait in the background lint only, moves page lookup and idle close out of withPage, and drops a suppression the startup worker no longer needs. Behaviour unchanged. * chore(cli): declare the render-setup worker as a fallow entry It is spawned by path from cancellableProcess.ts, so it has no import-graph referrer; the entry list is where the repo records that, replacing the per-file ignore removed in the previous commit. * fix(cli): close a thumbnail page whose load fails The page never leaves the promise that loads it, so when the load throws (a WebGPU composition with no adapter, or the navigation timeout on a big film) nothing could close it. * fix(cli): match text assets by exact type and keep Range on them The pattern anchored only its first alternative, and text assets skipped buildRangeResponse, so a ranged request for a stylesheet or SVG got a full 200. * test: open the next project as Studio does, and read the stamped file once The absent-read guard test switched project without beginning its timeline session, so the per-project boot wait held the read. The stamp test checked then read the same file. * test(cli): rewrite the scene file without opening it first Opening the file by path counted as a check before the later read of the same path. * perf(cli): take a thumbnail's version from the cached project signature Each thumbnail walked the project and hashed every text file for its page version; the adapter already caches that signature and clears it from the watcher. An aborted request now also stops before its screenshot. * fix(studio): keep Play off until the preview's load step has run Play could enable before the preview document's load event, from the runtime's timeline message or from the blank page's load step settling on the preview's first message. The load step then paused and rewound the preview, so a Play pressed in between did nothing; a film with large images loads late enough for this to hit a cold open. Readiness now waits for the document's load step, whichever path asks for it. * refactor(studio): move the preview poster's state into usePreviewPoster NLEPreview.tsx passed the 600-line limit once main grew it; the poster's state and callbacks belong beside PreviewPoster. No behaviour change. * fix(cli): take an earlier thumbnail on a fresh page A composition need not draw the same frame when seeked back, so a kept page that had shown 20 s drew a different 10 s thumbnail than a fresh load. A kept page now only seeks forward, as a render does; an earlier time loads a fresh page. * perf(cli): close a kept thumbnail page a second after its last frame Held for 10 s, the page went on running its composition after the open's thumbnail burst, about 5 % of a core in the thumbnail browser while Studio sat idle. A burst's requests arrive back to back, so it still loads the page once. * fix(studio): count the preview as booted at its first frame The boot waited for every video and audio in the preview to finish buffering, which on a project with media took until the 5 s fallback. The thumbnails, editing session and lint that wait for the boot then started seconds late and kept an idle Studio busy. They now start once the first frame is up; media finishes buffering alongside. * perf(studio): render one thumbnail per composition for its card and clip A composition's sidebar card asked for its frame at 3.00 s and its timeline clip for the clip's midpoint, so opening a project rendered every scene twice. The clip now asks for the card's frame (the midpoint still, for compositions under 3 s), and the thumbnail cache serves both from one render: 20 scene renders drop to 12 on a 12-scene project. * chore: keep each changed file's comment share at or under main's The comment ratchet counts the comment lines this branch added. Each is cut, or kept as one line where it states an invariant (the GSAP parse cache returns copies; the boot starts waiting work at the first frame). The orphan-cleanup docblock is condensed and now names the process-table read it uses instead of the pgrep scan it replaced. No code line changed. * fix(studio): keep a 3 s clip off its end frame and give card and clip one encoded URL A composition exactly 3 s long asked for its thumbnail at 3.00 s, its end instant, which after a fade-out is an empty frame; compositions of 3 s or less now use their midpoint. The card built its thumbnail URL from the raw path while the clip encoded it, so names with & + [ or % asked for two different URLs, and a % in the name made the card's request fail on the server; both now encode. The readiness comment says the boot latches at the first frame, as it has since the boot moved. * fix(studio): encode the card's live preview URL too, and document the bundler's static guard The card's hover preview built its URL from the raw composition path, so a % in the file name made the preview route fail to decode it. The card now builds its composition URL in one place, encoded, for both its thumbnail and its hover preview. The static-guard bundle option keeps a one-line doc (its default and what it warns about); a neighbouring docblock is rewrapped to keep the comment share. * test(cli): mock studio-server once so the signature spy and the history hook both apply The main merge brought a second vi.mock of @hyperframes/studio-server into studioServer.test.ts; the later one replaced the first, so createProjectSignature was no longer a spy and the cached signature test read .mock of undefined. One mock now carries both overrides.
1 parent d6adbdc commit f873734

65 files changed

Lines changed: 1932 additions & 293 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.fallowrc.jsonc‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,8 @@
4242
"packages/producer/src/services/shaderTransitionWorker.ts",
4343
// Off-main-thread /health endpoint, spawned by path from healthWorker.ts.
4444
"packages/producer/src/services/healthWorkerThread.ts",
45+
// Render-setup worker, spawned by path from cancellableProcess.ts.
46+
"packages/cli/src/renderSetupWorker.ts",
4547
// Test fixture worker, spawned by path via the pools' workerEntryPath
4648
// option from the crash-recovery tests; has no import-graph referrer.
4749
"packages/producer/src/services/__fixtures__/crashOnMessageWorker.mjs",

‎packages/cli/src/commands/play.test.ts‎

Lines changed: 65 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { afterEach, describe, expect, it, vi } from "vitest";
2-
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2+
import { mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
33
import { tmpdir } from "node:os";
44
import { join } from "node:path";
55
import { Hono } from "hono";
@@ -152,6 +152,70 @@ async function buildApp(project: ProjectDir, autoProxy: boolean): Promise<Hono>
152152
}
153153

154154
describe("registerCompositionRoute", () => {
155+
it("lets a browser revalidate the composition and its assets instead of refetching them", async () => {
156+
const project = tmpProject();
157+
writeFileSync(join(project.dir, "index.html"), "<html><head></head><body></body></html>");
158+
writeFileSync(join(project.dir, "clip.mp4"), Buffer.from("0123456789", "utf-8"));
159+
const app = await buildApp(project, false);
160+
161+
const etags: Record<string, string> = {};
162+
for (const path of ["/composition/index.html", "/composition/clip.mp4"]) {
163+
const first = await app.request(path);
164+
etags[path] = first.headers.get("ETag") ?? "";
165+
expect(etags[path]).not.toBe("");
166+
expect(first.headers.get("Cache-Control")).toBe("no-cache");
167+
const again = await app.request(path, { headers: { "If-None-Match": etags[path] } });
168+
expect(again.status).toBe(304);
169+
}
170+
171+
writeFileSync(join(project.dir, "clip.mp4"), Buffer.from("0123456789abc", "utf-8"));
172+
const edited = await app.request("/composition/clip.mp4", {
173+
headers: { "If-None-Match": etags["/composition/clip.mp4"] ?? "" },
174+
});
175+
expect(edited.status).toBe(200);
176+
});
177+
178+
it("serves an edited stylesheet even when its size and mtime did not change", async () => {
179+
const project = tmpProject();
180+
const css = join(project.dir, "style.css");
181+
const pinned = new Date("2026-01-01T00:00:00Z");
182+
writeFileSync(css, "a{color:red}");
183+
utimesSync(css, pinned, pinned);
184+
const app = await buildApp(project, false);
185+
const etag = (await app.request("/composition/style.css")).headers.get("ETag") ?? "";
186+
187+
writeFileSync(css, "a{color:tan}");
188+
utimesSync(css, pinned, pinned);
189+
const edited = await app.request("/composition/style.css", {
190+
headers: { "If-None-Match": etag },
191+
});
192+
193+
expect(edited.status).toBe(200);
194+
expect(await edited.text()).toBe("a{color:tan}");
195+
});
196+
197+
it("serves an edited SVG fresh and still answers a Range request on text", async () => {
198+
const project = tmpProject();
199+
const svg = join(project.dir, "logo.svg");
200+
const pinned = new Date("2026-01-01T00:00:00Z");
201+
writeFileSync(svg, "<svg>a</svg>");
202+
utimesSync(svg, pinned, pinned);
203+
const app = await buildApp(project, false);
204+
const etag = (await app.request("/composition/logo.svg")).headers.get("ETag") ?? "";
205+
206+
writeFileSync(svg, "<svg>b</svg>");
207+
utimesSync(svg, pinned, pinned);
208+
const edited = await app.request("/composition/logo.svg", {
209+
headers: { "If-None-Match": etag },
210+
});
211+
expect(edited.status).toBe(200);
212+
expect(await edited.text()).toBe("<svg>b</svg>");
213+
214+
const ranged = await app.request("/composition/logo.svg", { headers: { Range: "bytes=0-3" } });
215+
expect(ranged.status).toBe(206);
216+
expect(await ranged.text()).toBe("<svg");
217+
});
218+
155219
it("answers a Range request on a plain asset with 206 + the requested byte slice", async () => {
156220
const project = tmpProject();
157221
writeFileSync(join(project.dir, "clip.mp4"), Buffer.from("0123456789", "utf-8"));

‎packages/cli/src/commands/play.ts‎

Lines changed: 35 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
injectRuntime,
3838
injectMediaCodecMap,
3939
buildRangeResponse,
40+
revalidatedResponse,
4041
assetContentType,
4142
} from "../utils/compositionServer.js";
4243
import {
@@ -140,20 +141,22 @@ export default defineCommand({
140141
const app = new Hono();
141142

142143
// Serve the player JS
143-
app.get("/player.js", (ctx) => {
144-
return ctx.body(readFileSync(playerPath, "utf-8"), 200, {
145-
"Content-Type": "application/javascript",
146-
"Cache-Control": "no-cache",
147-
});
148-
});
144+
app.get("/player.js", (ctx) =>
145+
revalidatedResponse(
146+
readFileSync(playerPath, "utf-8"),
147+
"application/javascript",
148+
ctx.req.header("If-None-Match"),
149+
),
150+
);
149151

150152
// Serve the runtime JS
151-
app.get("/runtime.js", (ctx) => {
152-
return ctx.body(readFileSync(runtimePath, "utf-8"), 200, {
153-
"Content-Type": "application/javascript",
154-
"Cache-Control": "no-cache",
155-
});
156-
});
153+
app.get("/runtime.js", (ctx) =>
154+
revalidatedResponse(
155+
readFileSync(runtimePath, "utf-8"),
156+
"application/javascript",
157+
ctx.req.header("If-None-Match"),
158+
),
159+
);
157160

158161
const autoProxy = resolveAutoProxy(project.dir, args.proxy as boolean | undefined);
159162
await registerCompositionRoute(app, project, autoProxy);
@@ -230,10 +233,22 @@ export async function registerCompositionRoute(
230233
if (autoProxy) {
231234
html = await injectMediaCodecMap(html, project.dir, [{ html, compSrcPath: reqPath }]);
232235
}
233-
return ctx.html(html);
236+
return revalidatedResponse(html, "text/html; charset=UTF-8", ctx.req.header("If-None-Match"));
234237
}
235238

236239
const contentType = assetContentType(filePath);
240+
// Edited text is caught by a content hash; an mtime tag can repeat for a same-size rewrite.
241+
const isText =
242+
contentType.startsWith("text/") ||
243+
contentType === "application/json" ||
244+
contentType === "image/svg+xml";
245+
if (isText && !ctx.req.header("Range")) {
246+
return revalidatedResponse(
247+
readFileSync(filePath, "utf-8"),
248+
contentType,
249+
ctx.req.header("If-None-Match"),
250+
);
251+
}
237252
const proxyParam = ctx.req.query("hf-proxy");
238253
if (proxyParam !== undefined && isProxyVariantRequest(proxyParam)) {
239254
// Opt-out (or a non-video asset) 404s the param without attempting a
@@ -256,6 +271,7 @@ export async function registerCompositionRoute(
256271
proxyPath,
257272
PROXY_VARIANT_CONFIG[proxyVariant].contentType,
258273
ctx.req.header("Range"),
274+
ctx.req.header("If-None-Match"),
259275
);
260276
} catch (err) {
261277
if (err instanceof ProxyCapacityError) {
@@ -270,7 +286,12 @@ export async function registerCompositionRoute(
270286
}
271287
}
272288

273-
return buildRangeResponse(filePath, contentType, ctx.req.header("Range"));
289+
return buildRangeResponse(
290+
filePath,
291+
contentType,
292+
ctx.req.header("Range"),
293+
ctx.req.header("If-None-Match"),
294+
);
274295
});
275296
}
276297

‎packages/cli/src/commands/preview.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { runCommand } from "citty";
77
import {
88
default as previewCommand,
99
foregroundPreviewReadyPayload,
10+
prebuildPreview,
1011
handlePreviewKillAll,
1112
handlePreviewList,
1213
previewLaunchMode,
@@ -21,6 +22,16 @@ import {
2122
waitForStudioChildClose,
2223
} from "./preview.js";
2324

25+
const lint = vi.hoisted(() => ({ inProcess: vi.fn(), worker: vi.fn() }));
26+
vi.mock("../utils/lintProject.js", async (importOriginal) => ({
27+
...(await importOriginal<typeof import("../utils/lintProject.js")>()),
28+
lintProject: lint.inProcess,
29+
}));
30+
vi.mock("../utils/cancellableProcess.js", async (importOriginal) => ({
31+
...(await importOriginal<typeof import("../utils/cancellableProcess.js")>()),
32+
runRenderSetupWorker: lint.worker,
33+
}));
34+
2435
const tempDirs: string[] = [];
2536

2637
afterEach(() => {
@@ -375,6 +386,62 @@ describe("preview lifecycle JSON failures", () => {
375386
});
376387
});
377388

389+
describe("prebuildPreview", () => {
390+
it("asks the server for the opening film's preview document", async () => {
391+
const fetchApp = vi.fn(async (_request: Request) => new Response(""));
392+
393+
await prebuildPreview(fetchApp, "http://localhost:3002", "Launch #1");
394+
395+
expect(fetchApp.mock.calls[0]![0].url).toBe(
396+
"http://localhost:3002/api/projects/Launch%20%231/preview",
397+
);
398+
});
399+
400+
it("does not fail the start when the build throws", async () => {
401+
const fetchApp = vi.fn(() => {
402+
throw new Error("bundle failed");
403+
});
404+
405+
await expect(prebuildPreview(fetchApp, "http://localhost:3002", "demo")).resolves.toBe(
406+
undefined,
407+
);
408+
});
409+
});
410+
411+
describe("startup lint", () => {
412+
const neverSettles = () => new Promise<never>(() => {});
413+
414+
it("never lints for a --json start", async () => {
415+
lint.inProcess.mockImplementation(neverSettles);
416+
lint.worker.mockImplementation(neverSettles);
417+
const dir = tempProject();
418+
writeFileSync(join(dir, "index.html"), "<html></html>");
419+
vi.spyOn(console, "log").mockImplementation(() => {});
420+
421+
await runCommand(previewCommand, {
422+
rawArgs: [dir, "--background", "--json", "--user-data-dir", join(dir, "profile")],
423+
});
424+
425+
expect(lint.inProcess).not.toHaveBeenCalled();
426+
expect(lint.worker).not.toHaveBeenCalled();
427+
});
428+
429+
it("does not hold a start behind a lint that has not finished", async () => {
430+
lint.inProcess.mockImplementation(neverSettles);
431+
lint.worker.mockImplementation(neverSettles);
432+
const dir = tempProject();
433+
writeFileSync(join(dir, "index.html"), "<html></html>");
434+
const error = vi.spyOn(clack.log, "error").mockImplementation(() => {});
435+
436+
await runCommand(previewCommand, {
437+
rawArgs: [dir, "--background", "--user-data-dir", join(dir, "profile")],
438+
});
439+
440+
expect(error).toHaveBeenCalledWith(expect.stringContaining("--user-data-dir"));
441+
expect(lint.inProcess).not.toHaveBeenCalled();
442+
}, 5_000);
443+
});
444+
378445
describe("foreground preview JSON", () => {
379446
it("emits the same ready session contract before remaining attached", () => {
380447
const dir = tempProject();

‎packages/cli/src/commands/preview.ts‎

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,8 @@ import {
4848
parseRemoteDebuggingPort,
4949
validateRemoteDebuggingPortDeps,
5050
} from "../utils/openBrowser.js";
51-
import { lintProject } from "../utils/lintProject.js";
51+
import type { ProjectLintResult } from "../utils/lintProject.js";
52+
import { runRenderSetupWorker } from "../utils/cancellableProcess.js";
5253
import { formatLintStartupMessage } from "../utils/lintFormat.js";
5354
import {
5455
activeServerOnPort,
@@ -416,19 +417,6 @@ export default defineCommand({
416417
const dir = project.dir;
417418
const projectName = isImplicitCwd ? basename(process.env.PWD ?? dir) : project.name;
418419

419-
// Lint before starting — surface issues for the agent to fix.
420-
const lintResult = await lintProject(dir);
421-
if (!args.json && (lintResult.totalErrors > 0 || lintResult.totalWarnings > 0)) {
422-
console.log();
423-
const verbose = Boolean(args["lint-verbose"]);
424-
for (const line of formatLintStartupMessage(
425-
lintResult,
426-
verbose ? { kind: "verbose" } : { kind: "summary", pointer: "studio" },
427-
))
428-
console.log(line);
429-
console.log();
430-
}
431-
432420
// Validation: --user-data-dir requires --browser-path
433421
if (args["user-data-dir"] && !args["browser-path"]) {
434422
reportPreviewFailure(
@@ -492,6 +480,9 @@ export default defineCommand({
492480
);
493481
}
494482

483+
// Runs in the CLI worker while Studio starts, so it never delays the opening; --json skips it.
484+
const startupLint = args.json ? null : printStartupLint(dir, Boolean(args["lint-verbose"]));
485+
495486
const launchMode = previewLaunchMode({
496487
background: Boolean(args.background),
497488
foreground: Boolean(args.foreground),
@@ -555,6 +546,7 @@ export default defineCommand({
555546
remoteDebuggingPort,
556547
browserNoGpu,
557548
});
549+
await startupLint;
558550
return;
559551
}
560552

@@ -605,6 +597,26 @@ export default defineCommand({
605597
},
606598
});
607599

600+
async function printStartupLint(dir: string, verbose: boolean): Promise<void> {
601+
try {
602+
const lintResult = await runRenderSetupWorker<ProjectLintResult>(
603+
"lint",
604+
{ projectDir: dir },
605+
{ maxBufferBytes: 8 * 1024 * 1024 },
606+
);
607+
if (lintResult.totalErrors === 0 && lintResult.totalWarnings === 0) return;
608+
console.log();
609+
for (const line of formatLintStartupMessage(
610+
lintResult,
611+
verbose ? { kind: "verbose" } : { kind: "summary", pointer: "studio" },
612+
))
613+
console.log(line);
614+
console.log();
615+
} catch (error) {
616+
clack.log.warn(`Lint did not finish: ${errorMessage(error)}`);
617+
}
618+
}
619+
608620
export type PreviewLaunchMode = "background" | "dev" | "local" | "embedded";
609621

610622
export function previewLaunchMode(options: {
@@ -1188,6 +1200,18 @@ export function studioSummaryUrls(
11881200
};
11891201
}
11901202

1203+
/** Builds the preview while the browser starts; a failed build is retried by the player's own request. */
1204+
export function prebuildPreview(
1205+
fetchApp: (request: Request) => Response | Promise<Response>,
1206+
serverUrl: string,
1207+
projectName: string,
1208+
): Promise<unknown> {
1209+
const previewUrl = `${serverUrl}/api/projects/${encodeURIComponent(projectName)}/preview`;
1210+
return Promise.resolve()
1211+
.then(() => fetchApp(new Request(previewUrl)))
1212+
.catch(() => undefined);
1213+
}
1214+
11911215
export function foregroundPreviewReadyPayload(
11921216
projectName: string,
11931217
serverUrl: string,
@@ -1619,6 +1643,7 @@ async function runEmbeddedMode(
16191643
});
16201644
}
16211645
openStudioBrowser(url, pName, options);
1646+
void prebuildPreview(app.fetch, url, pName);
16221647

16231648
// Block until Ctrl+C. Node would normally exit on SIGINT, but the listening
16241649
// HTTP server keeps handles open, so the event loop stays alive after the
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { constants } from "node:os";
2+
import { afterEach, expect, it, vi } from "vitest";
3+
4+
const os = vi.hoisted(() => ({ setPriority: vi.fn() }));
5+
vi.mock("node:os", async (importOriginal) => ({
6+
...(await importOriginal<typeof import("node:os")>()),
7+
setPriority: os.setPriority,
8+
}));
9+
vi.mock("./utils/lintProject.js", () => ({ lintProject: vi.fn(async () => ({ ok: true })) }));
10+
11+
afterEach(() => vi.restoreAllMocks());
12+
13+
it("lints at the lowest CPU priority so it never competes with a Studio boot", async () => {
14+
process.argv[2] = "lint";
15+
process.env.HYPERFRAMES_RENDER_SETUP_INPUT = JSON.stringify({ projectDir: "/project" });
16+
const write = vi.spyOn(process.stdout, "write").mockImplementation(() => true);
17+
18+
await import("./renderSetupWorker.js");
19+
20+
expect(os.setPriority).toHaveBeenCalledWith(constants.priority.PRIORITY_LOW);
21+
expect(write).toHaveBeenCalledWith(expect.stringContaining('{"ok":true}'));
22+
});

0 commit comments

Comments
 (0)