Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
fix(studio): reload the preview only when a file it loaded changes (#4570)
Miguel Ángele00baefb5c53
diff --git a/docs/images/preview-reload-evidence/after.webm b/docs/images/preview-reload-evidence/after.webmdeleted file mode 100644index 194fb4601b..0000000000Binary files a/docs/images/preview-reload-evidence/after.webm and /dev/null differdiff --git a/docs/images/preview-reload-evidence/before.webm b/docs/images/preview-reload-evidence/before.webmdeleted file mode 100644index 7d81639f82..0000000000Binary files a/docs/images/preview-reload-evidence/before.webm and /dev/null differdiff --git a/docs/schema/hyperframes.json b/docs/schema/hyperframes.jsonindex 04699649ff..d950bc6fe0 100644--- a/docs/schema/hyperframes.json+++ b/docs/schema/hyperframes.json@@ -79,20 +79,6 @@}}}- },- "preview": {- "type": "object",- "additionalProperties": false,- "properties": {- "watchIgnore": {- "type": "array",- "items": {- "type": "string",- "minLength": 1- },- "description": "Project-relative files or directories that should not trigger preview reloads (literal paths, not glob patterns). Directory entries include their descendants. Does not exclude files from rendering or serving. hyperframes.json always triggers a reload."- }- }}}}diff --git a/docs/studio/troubleshooting.mdx b/docs/studio/troubleshooting.mdxindex a0ca48111a..5715d146c9 100644--- a/docs/studio/troubleshooting.mdx+++ b/docs/studio/troubleshooting.mdx@@ -57,28 +57,3 @@ For lower-level failures, continue to [general troubleshooting](/guides/troubles- [Work with source and an agent](/studio/source)- [Finish, render, and share](/guides/export-and-share)- [Diagnose a project or CLI problem](/guides/troubleshooting)--## Preview keeps restarting while tools write reports--Preview watches project files so source and asset edits appear automatically.-If an agent or check command writes notes and reports inside your project, exclude-those outputs from live reload in `hyperframes.json`:--```json-{- "preview": {- "watchIgnore": ["docs", "references/check-results.json"]- }-}-```--Entries are literal project-relative file or directory paths, not globs. A directory-entry includes its descendants, but not similarly named siblings. Only exclude-files the composition does not use: ignored files remain available to the server-and renderer, but edits to them will not automatically reload the player or its-thumbnails. Changes to this setting take effect without restarting the server;-`hyperframes.json` itself always triggers a reload.--Atomic-save temporary files (`.tmp`, `.tmp.<pid>.<hex>`, `.swp`, `.swo`, and trailing-`~`) do not trigger preview reloads. Renaming them to the final source filename-still does.diff --git a/packages/cli/src/server/studioServer.test.ts b/packages/cli/src/server/studioServer.test.tsindex 961d4a8b39..67d366a4d7 100644--- a/packages/cli/src/server/studioServer.test.ts+++ b/packages/cli/src/server/studioServer.test.ts@@ -671,25 +671,96 @@ describe("Studio file-change SSE", () => {const encodedVersion = (content: string): string =>fileContentVersion(content).replaceAll('"', '\\"');- it("does not deliver report or temporary-file changes, but delivers the final source save", async () => {+ /** A project whose preview has been loaded once, as an open Studio tab does on its first render. */+ async function previewedProject(): Promise<{ projectDir: string; projectUrl: string }> {const projectDir = tmpProject();- writeFileSync(join(projectDir, "index.html"), "<html>before</html>");+ mkdirSync(join(projectDir, "assets"));+ writeFileSync(join(projectDir, "assets", "logo.png"), "logo-v1");+ writeFileSync(+ join(projectDir, "index.html"),+ '<html><body><div data-composition-id="root"><img src="assets/logo.png"></div></body></html>',+ );+ server = createStudioServer({ projectDir });+ const projectUrl = `/api/projects/${encodeURIComponent(basename(projectDir))}`;+ expect((await server.app.request(`${projectUrl}/preview`)).status).toBe(200);+ expect((await server.app.request(`${projectUrl}/preview/assets/logo.png`)).status).toBe(200);+ return { projectDir, projectUrl };+ }++ it("marks a notes write as not affecting the preview, so the tab does not reload", async () => {+ const { projectDir } = await previewedProject();+ const [stream] = await subscribe(1);++ writeFileSync(join(projectDir, "notes.md"), "review notes");+ mockWatcher.emit("change", "rename", "notes.md");++ const payload = await nextEvent(stream!);+ expect(payload).toContain('"path":"notes.md"');+ expect(payload).toContain('"affectsPreview":false');+ expect(payload).toContain('"affectedCompositions":[]');+ });++ it("marks a write to an asset the preview loaded as affecting it", async () => {+ const { projectDir } = await previewedProject();+ const [stream] = await subscribe(1);++ writeFileSync(join(projectDir, "assets", "logo.png"), "logo-v2");+ mockWatcher.emit("change", "change", "assets/logo.png");++ expect(await nextEvent(stream!)).toContain('"affectsPreview":true');+ });++ it("reloads when a folder holding an asset the preview missed is moved in", async () => {+ const { projectDir, projectUrl } = await previewedProject();+ expect((await server!.app.request(`${projectUrl}/preview/media/clip.png`)).status).toBe(404);+ const [stream] = await subscribe(1);++ mkdirSync(join(projectDir, "media"));+ writeFileSync(join(projectDir, "media", "clip.png"), "clip");+ mockWatcher.emit("change", "rename", "media");++ const payload = await nextEvent(stream!);+ expect(payload).toContain('"path":"media"');+ expect(payload).toContain('"affectsPreview":true');+ });++ it("reloads when a folder holding an asset the preview loaded is moved out", async () => {+ const { projectDir } = await previewedProject();+ const [stream] = await subscribe(1);++ renameSync(join(projectDir, "assets"), join(tmpProject(), "assets"));+ mockWatcher.emit("change", "rename", "assets");++ expect(await nextEvent(stream!)).toContain('"affectsPreview":true');+ });++ it("still delivers a new file in a folder an old watchIgnore listed, for the file tree", async () => {+ const { projectDir } = await previewedProject();writeFileSync(join(projectDir, "hyperframes.json"),JSON.stringify({ preview: { watchIgnore: ["docs"] } }),);+ const [stream] = await subscribe(1);++ mkdirSync(join(projectDir, "docs"));+ writeFileSync(join(projectDir, "docs", "report.json"), "{}");+ mockWatcher.emit("change", "rename", "docs/report.json");++ const payload = await nextEvent(stream!);+ expect(payload).toContain('"path":"docs/report.json"');+ expect(payload).toContain('"affectsPreview":false');+ });++ it("counts every write as affecting the preview until the preview has loaded anything", async () => {+ const projectDir = tmpProject();+ writeFileSync(join(projectDir, "index.html"), "<html></html>");server = createStudioServer({ projectDir });- const streams = await subscribe(2);- mockWatcher.emit("change", "change", "docs/report.json");- mockWatcher.emit("change", "rename", "index.html.tmp.97896.1d3e1712ad2c");- await new Promise((resolve) => setTimeout(resolve, 60));- writeFileSync(join(projectDir, "index.html"), "<html>after</html>");- mockWatcher.emit("change", "rename", "index.html");- for (const payload of await Promise.all(streams.map(nextEvent))) {- expect(payload).toContain('"path":"index.html"');- expect(payload).not.toContain("report.json");- expect(payload).not.toContain(".tmp");- }+ const [stream] = await subscribe(1);++ writeFileSync(join(projectDir, "notes.md"), "notes");+ mockWatcher.emit("change", "rename", "notes.md");++ expect(await nextEvent(stream!)).toContain('"affectsPreview":true');});it("labels a Studio write for every open subscriber, not just the first", async () => {diff --git a/packages/cli/src/server/studioServer.ts b/packages/cli/src/server/studioServer.tsindex 35b4fa8d52..3ae36dc6f3 100644--- a/packages/cli/src/server/studioServer.ts+++ b/packages/cli/src/server/studioServer.ts@@ -45,7 +45,7 @@ import {getMimeType,affectsProjectSignature,compositionsAffectedBy,- shouldReloadPreview,+ affectsPreview,type PreviewApiAdapter,PREVIEW_BUNDLE_OPTIONS,createPreviewDocumentStore,@@ -876,6 +876,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {// identity for an unlabelled change, and without it every duplicate// delivery of one watcher event drains and reloads again.const receipt = identifyFileWrite(absPath, version ?? DELETED_VERSION);+ const reloads = affectsPreview(projectDir, path);// `projectId` so a stale tab — one still pointed at a project this// server no longer serves, because `hyperframes preview` reused this// port for a different folder (see ProjectUnreachableBanner's doc@@ -892,8 +893,9 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {path,version,projectId: project.id,+ affectsPreview: reloads,// Which thumbnails this write can change; null means all of them.- affectedCompositions: compositionsAffectedBy(projectDir, path),+ affectedCompositions: reloads ? compositionsAffectedBy(projectDir, path) : [],...receipt,}),})@@ -902,9 +904,7 @@ export function createStudioServer(options: StudioServerOptions): StudioServer {// Re-applied here because the watcher now also emits the signature// manifest files, which must not trigger a browser reload.const wrappedListener = (changedPath: string) => {- if (shouldWatchProjectFile(changedPath) && shouldReloadPreview(projectDir, changedPath)) {- listener(changedPath);- }+ if (shouldWatchProjectFile(changedPath)) listener(changedPath);};watcher.addListener(wrappedListener);stream.onAbort(() => watcher.removeListener(wrappedListener));diff --git a/packages/cli/src/utils/projectConfig.test.ts b/packages/cli/src/utils/projectConfig.test.tsindex 8373cf4ba3..5a3ebd93b4 100644--- a/packages/cli/src/utils/projectConfig.test.ts+++ b/packages/cli/src/utils/projectConfig.test.ts@@ -50,23 +50,6 @@ describe("projectConfig", () => {});});- it("preserves preview watch exclusions through config writes and authoring updates", () => {- const dir = tmp();- try {- writeProjectConfig(dir, {- ...DEFAULT_PROJECT_CONFIG,- preview: { watchIgnore: ["./docs/", "reports/check.json"] },- });- expect(readProjectConfig(dir)?.preview).toEqual({- watchIgnore: ["docs", "reports/check.json"],- });- seedProjectAuthoringSkill(dir, "music-to-video");- expect(readProjectConfig(dir)?.preview?.watchIgnore).toEqual(["docs", "reports/check.json"]);- } finally {- rmSync(dir, { recursive: true, force: true });- }- });-describe("normalizeConfig", () => {it("fills in defaults for missing fields", () => {const result = normalizeConfig({ registry: "https://alt.example.com" });diff --git a/packages/cli/src/utils/projectConfig.ts b/packages/cli/src/utils/projectConfig.tsindex c0ff0320d3..1266b76feb 100644--- a/packages/cli/src/utils/projectConfig.ts+++ b/packages/cli/src/utils/projectConfig.ts@@ -7,7 +7,6 @@* point at custom registries or reshape their project layout.*/-import { normalizePreviewWatchIgnore } from "@hyperframes/studio-server";import { readFileSync, writeFileSync } from "node:fs";import { join, resolve } from "node:path";import { DEFAULT_REGISTRY_URL } from "../registry/index.js";@@ -60,7 +59,6 @@ export interface ProjectConfig {paths: ProjectConfigPaths;/** Media handling options (e.g. auto-proxying of browser-hostile codecs). */media?: ProjectConfigMedia;- preview?: { watchIgnore?: string[] };/*** Owning authoring-workflow skill slug (e.g. "product-launch-video"). Stamped* by `hyperframes init --skill` or seeded from the first `hyperframes render@@ -153,9 +151,6 @@ export function normalizeConfig(partial: Partial<ProjectConfig>): ProjectConfig? partial.media.autoProxy: DEFAULT_PROJECT_CONFIG.media?.autoProxy,},- preview: partial.preview- ? { watchIgnore: normalizePreviewWatchIgnore(partial.preview.watchIgnore) }- : undefined,// Slug-gate on read so a hand-edited or corrupt value never reaches the// telemetry stream; an invalid slug simply drops the attribution.authoringSkill: normalizeSkillSlug(partial.authoringSkill),diff --git a/packages/cli/src/utils/projectConfigSchema.test.ts b/packages/cli/src/utils/projectConfigSchema.test.tsindex 162b2b0d98..36adaa3205 100644--- a/packages/cli/src/utils/projectConfigSchema.test.ts+++ b/packages/cli/src/utils/projectConfigSchema.test.ts@@ -43,7 +43,6 @@ const EVERY_WRITTEN_KEY: Required<ProjectConfig> = {registry: "https://example.test/registry",paths: DEFAULT_PROJECT_CONFIG.paths,media: { autoProxy: true },- preview: { watchIgnore: ["docs", "references/check-results.json"] },authoringSkill: "product-launch-video",registryItems: [EVERY_RECORD_FIELD],};diff --git a/packages/core/src/compiler/htmlBundler.test.ts b/packages/core/src/compiler/htmlBundler.test.tsindex 840d92a0f6..8f229f9333 100644--- a/packages/core/src/compiler/htmlBundler.test.ts+++ b/packages/core/src/compiler/htmlBundler.test.ts@@ -80,6 +80,38 @@ function makeSymlinkProject(}describe("bundleToSingleHtml", () => {+ it("reports every project file it reads or looks for through onRead", async () => {+ const dir = makeTempProject({+ "index.html": `<!doctype html><html><head>+ <link rel="stylesheet" href="style.css"><link rel="stylesheet" href="missing.css">+ </head><body>+ <div data-composition-id="root" data-width="320" data-height="180" data-start="0" data-duration="2">+ <img src="small.svg">+ <div data-composition-id="intro" data-composition-src="scenes/intro.html" data-start="0" data-duration="1"></div>+ </div>+ <script src="app.js"></script>+ <script>window.__timelines = window.__timelines || {}; window.__timelines.root = {}</script>+ </body></html>`,+ "style.css": '@import "base.css"; .a { color: red; }',+ "base.css": ".b { color: blue; }",+ "app.js": "window.appLoaded = true;",+ "small.svg": '<svg xmlns="http://www.w3.org/2000/svg"></svg>',+ "scenes/intro.html": `<template><div data-composition-id="intro" data-width="320" data-height="180">+ <link rel="stylesheet" href="intro.css"><p>intro</p></div></template>`,+ "scenes/intro.css": ".intro { color: green; }",+ "notes.md": "not part of the film",+ });+ const reads = new Set<string>();++ await bundleToSingleHtml(dir, { onRead: (file) => reads.add(file) });++ const expected = ["index.html", "style.css", "base.css", "missing.css", "app.js", "small.svg"];+ for (const file of [...expected, "scenes/intro.html", "scenes/intro.css"]) {+ expect(reads).toContain(join(dir, file));+ }+ expect(reads).not.toContain(join(dir, "notes.md"));+ });+it("bundles a direct composition entry with paths relative to its file", async () => {const dir = makeTempProject({"index.html": "<html><body>wrong entry</body></html>",diff --git a/packages/core/src/compiler/htmlBundler.ts b/packages/core/src/compiler/htmlBundler.tsindex 6eab1480ee..63ebf6681a 100644--- a/packages/core/src/compiler/htmlBundler.ts+++ b/packages/core/src/compiler/htmlBundler.ts@@ -11,6 +11,7 @@ export { FLATTENED_INNER_ROOT_STRIP_ATTRS } from "../runtime/flattenedRoot";import { parseHostVariableValues, warnUnknownEnumValues } from "../runtime/getVariables";import { sanitizeCssValue } from "../runtime/applyVariableBindings";import { cssVariableName } from "../tokenSlug";+import { AsyncLocalStorage } from "async_hooks";import { readFileSync, existsSync, statSync } from "fs";import { resolve, relative, dirname, isAbsolute, sep } from "path";import { CSS_URL_RE, isNonRelativeUrl } from "./assetPaths.js";@@ -86,7 +87,14 @@ function isRelativeUrl(url: string): boolean {return !isNonRelativeUrl(url) && !isAbsolute(url);}+const bundleReads = new AsyncLocalStorage<(filePath: string) => void>();++function noteRead(filePath: string): void {+ bundleReads.getStore()?.(filePath);+}+function safeReadFile(filePath: string): string | null {+ noteRead(filePath);if (!existsSync(filePath)) return null;try {return readFileSync(filePath, "utf-8");@@ -257,6 +265,7 @@ function inlineCssFile(}function safeReadFileBuffer(filePath: string): Buffer | null {+ noteRead(filePath);if (!existsSync(filePath)) return null;try {return readFileSync(filePath);@@ -828,6 +837,7 @@ export interface BundleOptions {sceneParts?: boolean;/** Warn when the compiled HTML breaks the HyperFrames contract (default true). */staticGuard?: boolean;+ onRead?: (filePath: string) => void;}/**@@ -938,10 +948,12 @@ function hoistCompositionScripts(}}-export async function bundleToSingleHtml(- projectDir: string,- options?: BundleOptions,-): Promise<string> {+export function bundleToSingleHtml(projectDir: string, options?: BundleOptions): Promise<string> {+ const bundle = () => bundleProject(projectDir, options);+ return options?.onRead ? bundleReads.run(options.onRead, bundle) : bundle();+}++async function bundleProject(projectDir: string, options?: BundleOptions): Promise<string> {const entryFile = options?.entryFile ?? "index.html";const indexPath = resolveWithinProject(projectDir, entryFile);if (!indexPath || !existsSync(indexPath)) {@@ -954,6 +966,7 @@ export async function bundleToSingleHtml(};const readSource = options?.stampHfIds ? ensureHfIds : (html: string) => html;+ noteRead(indexPath);const rawHtml = readSource(readFileSync(indexPath, "utf-8"));const compiled = await compileHtml(rawHtml, sourceDir, options?.probeMediaDuration);@@ -1040,6 +1053,7 @@ export async function bundleToSingleHtml(// document; project-root refs with no such sibling stay as authored.assetExists: (path: string) => {const resolved = resolveEntryPath(path);+ if (resolved) noteRead(resolved);return resolved !== null && existsSync(resolved);},flattenInnerRoot: prepareFlattenedInnerRoot,diff --git a/packages/studio-server/src/helpers/previewReads.ts b/packages/studio-server/src/helpers/previewReads.tsnew file mode 100644index 0000000000..0a032e794e--- /dev/null+++ b/packages/studio-server/src/helpers/previewReads.ts@@ -0,0 +1,95 @@+import { readlinkSync } from "node:fs";+import { dirname, join, parse, relative, resolve } from "node:path";+import { STUDIO_SIGNATURE_MANIFEST_PATHS } from "./projectSignature.js";+import { realFilePath } from "./safePath.js";++const ALWAYS_AFFECTS = ["hyperframes.json", ...STUDIO_SIGNATURE_MANIFEST_PATHS];+const REFERENCE =+ /\b(?:src|href|poster|data-composition-src)\s*=\s*(?:"([^"\n]*)"|'([^'\n]*)')|url\(\s*(?:"([^"\n]*)"|'([^'\n]*)'|([^"'\s)]+))/gi;+// macOS and Windows volumes ignore letter case by default, so it is not part of a path's identity there.+const pathKey =+ process.platform === "darwin" || process.platform === "win32"+ ? (path: string) => resolve(path).toLowerCase()+ : (path: string) => resolve(path);+// ponytail: grows until restart, so a file a film stopped using still reloads; reset per build if that matters.+const readsByProject = new Map<string, Set<string>>();+const builtProjects = new Set<string>();+const projectKey = (projectDir: string) => pathKey(realFilePath(resolve(projectDir)));+const inRealProject = (projectDir: string, path: string) =>+ join(realFilePath(resolve(projectDir)), relative(resolve(projectDir), resolve(projectDir, path)));++const readLink = (path: string): string | null => {+ try {+ return readlinkSync(path);+ } catch {+ return null;+ }+};++// Walks `path` as the OS does, returning every link it passes and where it ends up.+function linksOnTheWay(path: string): string[] {+ const passed: string[] = [];+ let at = parse(path).root;+ let rest = path.slice(at.length).split(/[\\/]+/);+ for (let hops = 0; rest.length > 0; ) {+ const part = rest.shift()!;+ if (!part || part === ".") continue;+ if (part === "..") {+ at = dirname(at);+ continue;+ }+ const next = join(at, part);+ const target = hops < 40 ? readLink(next) : null;+ if (target === null) {+ at = next;+ continue;+ }+ hops++;+ passed.push(next);+ const root = parse(target).root;+ if (root) at = root;+ rest = [...target.slice(root.length).split(/[\\/]+/), ...rest];+ }+ passed.push(at);+ return passed;+}++// A link's target can be created or retargeted later, so every read resolves it again.+export function recordPreviewRead(projectDir: string, filePath: string): void {+ const key = projectKey(projectDir);+ let reads = readsByProject.get(key);+ if (!reads) readsByProject.set(key, (reads = new Set()));+ const read = inRealProject(projectDir, filePath);+ for (const found of [read, ...linksOnTheWay(read)]) {+ for (let path = pathKey(found); !reads.has(path); path = dirname(path)) reads.add(path);+ }+}++export function recordPreviewReferences(projectDir: string, html: string): void {+ const named = new Set<string>();+ for (const match of html.matchAll(REFERENCE)) {+ const url = (match[1] ?? match[2] ?? match[3] ?? match[4] ?? match[5] ?? "").trim();+ if (!url || /^(?:[a-z][a-z0-9+.-]*:|[/#])/i.test(url)) continue;+ const path = url.split(/[?#]/)[0] ?? "";+ let decoded = path;+ try {+ decoded = decodeURIComponent(path);+ } catch {+ // A malformed escape names the file literally.+ }+ if (decoded) named.add(decoded);+ }+ for (const path of named) recordPreviewRead(projectDir, path);+}++export function recordPreviewBuilt(projectDir: string): void {+ for (const path of ALWAYS_AFFECTS) recordPreviewRead(projectDir, path);+ builtProjects.add(projectKey(projectDir));+}++// Every write counts until this process built the preview; a folder event counts when a loaded file is inside it.+export function affectsPreview(projectDir: string, changedPath: string): boolean {+ const key = projectKey(projectDir);+ if (!builtProjects.has(key)) return true;+ return readsByProject.get(key)?.has(pathKey(inRealProject(projectDir, changedPath))) ?? false;+}diff --git a/packages/studio-server/src/helpers/previewWatchIgnore.test.ts b/packages/studio-server/src/helpers/previewWatchIgnore.test.tsdeleted file mode 100644index 13e609a540..0000000000--- a/packages/studio-server/src/helpers/previewWatchIgnore.test.ts+++ /dev/null@@ -1,106 +0,0 @@-import { afterEach, describe, expect, it } from "vitest";-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";-import { tmpdir } from "node:os";-import { join } from "node:path";-import { normalizePreviewWatchIgnore, shouldReloadPreview } from "./previewWatchIgnore";--const directories: string[] = [];-function project(config: unknown = {}): string {- const dir = mkdtempSync(join(tmpdir(), "hf-watch-ignore-"));- directories.push(dir);- writeFileSync(join(dir, "hyperframes.json"), JSON.stringify(config));- return dir;-}-afterEach(() => {- for (const dir of directories.splice(0)) rmSync(dir, { recursive: true, force: true });-});--describe("preview reload filtering", () => {- it("defaults to reloading arbitrary assets, data, and source files", () => {- const dir = project();- for (const path of [- "index.html",- "assets/photo.jpg",- "data.json",- "docs/data.md",- "scene.tsx",- ]) {- expect(shouldReloadPreview(dir, path)).toBe(true);- }- });-- it("ignores literal paths and directory descendants without matching siblings", () => {- const dir = project({ preview: { watchIgnore: ["./docs/", "reports\\checks.json"] } });- for (const path of ["docs", "docs/a.json", "docs\\a.md", "reports/checks.json"]) {- expect(shouldReloadPreview(dir, path)).toBe(false);- }- for (const path of ["docs-other/a.json", "reports/other.json", "index.html"]) {- expect(shouldReloadPreview(dir, path)).toBe(true);- }- expect(shouldReloadPreview(dir, join(dir, "docs", "report.json"))).toBe(false);- });-- it("always reloads config and reads changed settings without restarting", () => {- const dir = project({ preview: { watchIgnore: ["docs", "hyperframes.json"] } });- expect(shouldReloadPreview(dir, "hyperframes.json")).toBe(true);- expect(shouldReloadPreview(dir, "docs/report.json")).toBe(false);- writeFileSync(join(dir, "hyperframes.json"), "{}");- expect(shouldReloadPreview(dir, "docs/report.json")).toBe(true);- });-- it("ignores atomic-save artifacts while retaining the final source and ordinary names", () => {- const dir = project();- for (const path of [- "index.html.tmp",- "docs/edit.md.tmp.97896.1d3e1712ad2c",- ".index.html.swp",- "index.html.swo",- "index.html~",- ]) {- expect(shouldReloadPreview(dir, path)).toBe(false);- }- for (const path of ["index.html", "templates/a.html", "photo.tmp.jpg"]) {- expect(shouldReloadPreview(dir, path)).toBe(true);- }- });-- it("fails open on malformed or missing configuration", () => {- for (const config of [null, [], { preview: null }, { preview: { watchIgnore: "docs" } }]) {- expect(shouldReloadPreview(project(config), "docs/report.json")).toBe(true);- }- const dir = project();- writeFileSync(join(dir, "hyperframes.json"), "{");- expect(shouldReloadPreview(dir, "index.html")).toBe(true);- rmSync(join(dir, "hyperframes.json"));- expect(shouldReloadPreview(dir, "index.html")).toBe(true);- });-- it("handles long runs of separators in untrusted settings", () => {- const separators = "/".repeat(100_000);- expect(normalizePreviewWatchIgnore([`docs${separators}`])).toEqual(["docs"]);- expect(normalizePreviewWatchIgnore([`docs${separators}report.json`])).toEqual([]);- });-- it("rejects exclusions that could hide the whole project or escape its root", () => {- expect(- normalizePreviewWatchIgnore([- "",- ".",- "./",- "..",- "../a",- "/tmp",- "C:\\tmp",- "a/../b",- "**",- null,- 5,- "docs",- ]),- ).toEqual(["docs"]);- const dir = project();- expect(shouldReloadPreview(dir, dir)).toBe(false);- expect(shouldReloadPreview(dir, join(dir, ".."))).toBe(false);- expect(shouldReloadPreview(dir, join(dir, "..", "other.html"))).toBe(false);- });-});diff --git a/packages/studio-server/src/helpers/previewWatchIgnore.ts b/packages/studio-server/src/helpers/previewWatchIgnore.tsdeleted file mode 100644index 948db2ad9d..0000000000--- a/packages/studio-server/src/helpers/previewWatchIgnore.ts+++ /dev/null@@ -1,47 +0,0 @@-import { readFileSync } from "node:fs";-import { isAbsolute, relative, resolve } from "node:path";--const CONFIG_FILE = "hyperframes.json";--export function normalizePreviewWatchIgnore(value: unknown): string[] {- if (!Array.isArray(value)) return [];- return value.flatMap((entry: unknown) => {- if (typeof entry !== "string") return [];- const normalized = entry.replace(/\\/g, "/").replace(/^\.\//, "");- let end = normalized.length;- while (end > 0 && normalized[end - 1] === "/") end -= 1;- const path = normalized.slice(0, end);- if (- !path ||- path.startsWith("/") ||- /[:*?[\]]/.test(path) ||- path.split("/").some((part) => !part || part === "." || part === "..")- ) {- return [];- }- return [path];- });-}--function readIgnoredPaths(projectDir: string): string[] {- try {- const config: unknown = JSON.parse(readFileSync(resolve(projectDir, CONFIG_FILE), "utf8"));- if (!config || typeof config !== "object" || !("preview" in config)) return [];- const preview = config.preview;- if (!preview || typeof preview !== "object" || !("watchIgnore" in preview)) return [];- return normalizePreviewWatchIgnore(preview.watchIgnore);- } catch {- return [];- }-}--export function shouldReloadPreview(projectDir: string, changedPath: string): boolean {- const path = relative(resolve(projectDir), resolve(projectDir, changedPath)).replace(/\\/g, "/");- if (!path || path === ".." || path.startsWith("../") || isAbsolute(path)) return false;- if (path === CONFIG_FILE) return true;- const name = path.split("/").at(-1) ?? "";- if (/\.tmp(?:\.\d+\.[a-f\d]+)?$/i.test(name) || /\.(?:swp|swo)$|~$/.test(name)) return false;- return !readIgnoredPaths(projectDir).some(- (ignored) => path === ignored || path.startsWith(`${ignored}/`),- );-}diff --git a/packages/studio-server/src/helpers/projectSignature.ts b/packages/studio-server/src/helpers/projectSignature.tsindex 4787015f0b..7978a9f86a 100644--- a/packages/studio-server/src/helpers/projectSignature.ts+++ b/packages/studio-server/src/helpers/projectSignature.ts@@ -32,7 +32,7 @@ const SIGNATURE_EXCLUDED_DIRS = new Set(["renders",]);const MAX_SIGNATURE_TEXT_BYTES = 2_000_000;-const STUDIO_SIGNATURE_MANIFEST_PATHS = [+export const STUDIO_SIGNATURE_MANIFEST_PATHS = [".hyperframes/studio-manual-edits.json",".hyperframes/studio-motion.json",] as const;diff --git a/packages/studio-server/src/index.ts b/packages/studio-server/src/index.tsindex 95515d7114..fc7b2cc8dd 100644--- a/packages/studio-server/src/index.ts+++ b/packages/studio-server/src/index.ts@@ -1,7 +1,7 @@-export { shouldReloadPreview, normalizePreviewWatchIgnore } from "./helpers/previewWatchIgnore.js";export { createStudioApi } from "./createStudioApi.js";export { createProjectSignature, affectsProjectSignature } from "./helpers/projectSignature.js";export { compositionsAffectedBy } from "./helpers/compositionInputs.js";+export { affectsPreview } from "./helpers/previewReads.js";export {DEFAULT_HISTORY_ROOT,openProjectHistory,diff --git a/packages/studio-server/src/routes/preview.test.ts b/packages/studio-server/src/routes/preview.test.tsindex 6fe2e8835e..e08a13370c 100644--- a/packages/studio-server/src/routes/preview.test.ts+++ b/packages/studio-server/src/routes/preview.test.ts@@ -17,12 +17,18 @@ import {writeSync,} from "node:fs";import { tmpdir } from "node:os";-import { join } from "node:path";+import { join, parse } from "node:path";import { ensureHfIds } from "@hyperframes/parsers/hf-ids";import { PREVIEW_BUNDLE_OPTIONS, registerPreviewRoutes } from "./preview";import { registerFileRoutes } from "./files";import { createPreviewDocumentStore } from "../helpers/previewDocumentStore";import type { StudioApiAdapter } from "../types";+import {+ affectsPreview,+ recordPreviewBuilt,+ recordPreviewRead,+ recordPreviewReferences,+} from "../helpers/previewReads";const tempDirs: string[] = [];@@ -1482,6 +1488,204 @@ describe("hf-proxy negotiation and media codec map injection (U3)", () => {});});+describe("what the preview loaded", () => {+ it("counts the files the bundle reads and the document names, not other project files", async () => {+ const projectDir = createProjectDir();+ writeFileSync(+ join(projectDir, "index.html"),+ '<html><head><link rel="stylesheet" href="style.css"></head><body><img src="assets/loader.gif"></body></html>',+ );+ const app = new Hono();+ registerPreviewRoutes(+ app,+ createAdapter(projectDir, {+ bundle: async (dir, options) => {+ options?.onRead?.(join(dir, "from-bundler.css"));+ return null;+ },+ // As the CLI does with an animated GIF: the document it serves names a derived copy.+ transformPreviewHtml: async ({ html }) =>+ html.replace("assets/loader.gif", ".hyperframes/gif/loader.webm"),+ }),+ );++ const res = await app.request("http://localhost/projects/demo/preview");+ expect(res.status).toBe(200);+ expect(await res.text()).toContain(".hyperframes/gif/loader.webm");++ expect(affectsPreview(projectDir, "from-bundler.css")).toBe(true);+ expect(affectsPreview(projectDir, "style.css")).toBe(true);+ expect(affectsPreview(projectDir, "assets/loader.gif")).toBe(true);+ expect(affectsPreview(projectDir, "notes.md")).toBe(false);+ });++ it("scans a document with a long run of spaces inside url( in linear time", () => {+ const started = performance.now();+ const css = `<style>a { background: url(${" ".repeat(200_000)}</style>`;+ recordPreviewReferences(createProjectDir(), css);+ recordPreviewReferences(createProjectDir(), `url("${'url("a'.repeat(100_000)}`);+ expect(performance.now() - started).toBeLessThan(1000);+ });++ it("records every reference form a document uses, and the folders holding them", () => {+ const projectDir = createProjectDir();+ recordPreviewReferences(+ projectDir,+ `<img src='a.png'><i style="x: url('b.png')"></i><i style='y: url("c.png")'></i><i style="z: url(img/deep/d.png)"></i>`,+ );+ recordPreviewBuilt(projectDir);++ for (const path of ["a.png", "b.png", "c.png", "img/deep/d.png", "img/deep", "img"]) {+ expect(affectsPreview(projectDir, path)).toBe(true);+ }+ expect(affectsPreview(projectDir, "im")).toBe(false);+ });++ it.skipIf(process.platform === "win32")(+ "counts an edit to the file a symlinked asset points at",+ async () => {+ const projectDir = createProjectDir();+ writeFileSync(join(projectDir, "index.html"), "<html><body></body></html>");+ mkdirSync(join(projectDir, "assets"));+ writeFileSync(join(projectDir, "assets", "actual.css"), "a {}");+ symlinkSync("actual.css", join(projectDir, "assets", "alias.css"));+ const app = new Hono();+ registerPreviewRoutes(app, createAdapter(projectDir, { bundle: async () => null }));+ expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200);+ const alias = await app.request("http://localhost/projects/demo/preview/assets/alias.css");+ expect(alias.status).toBe(200);++ expect(affectsPreview(projectDir, "assets/actual.css")).toBe(true);+ expect(affectsPreview(projectDir, "assets/other.css")).toBe(false);+ },+ );++ it.skipIf(process.platform === "win32")(+ "counts creating the missing target of a symlinked asset the preview asked for",+ async () => {+ const projectDir = createProjectDir();+ writeFileSync(join(projectDir, "index.html"), "<html><body></body></html>");+ mkdirSync(join(projectDir, "assets"));+ symlinkSync("actual.css", join(projectDir, "assets", "alias.css"));+ const app = new Hono();+ registerPreviewRoutes(app, createAdapter(projectDir, { bundle: async () => null }));+ expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200);+ const alias = await app.request("http://localhost/projects/demo/preview/assets/alias.css");+ expect(alias.status).toBe(404);++ expect(affectsPreview(projectDir, "assets/actual.css")).toBe(true);+ },+ );++ it.skipIf(process.platform === "win32")(+ "counts an edit to the new target of a symlinked asset retargeted after it loaded",+ async () => {+ const projectDir = createProjectDir();+ writeFileSync(join(projectDir, "index.html"), "<html><body></body></html>");+ mkdirSync(join(projectDir, "assets"));+ writeFileSync(join(projectDir, "assets", "first.css"), "a {}");+ writeFileSync(join(projectDir, "assets", "second.css"), "b {}");+ symlinkSync("first.css", join(projectDir, "assets", "alias.css"));+ const app = new Hono();+ registerPreviewRoutes(app, createAdapter(projectDir, { bundle: async () => null }));+ const aliasUrl = "http://localhost/projects/demo/preview/assets/alias.css";+ expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200);+ expect((await app.request(aliasUrl)).status).toBe(200);++ rmSync(join(projectDir, "assets", "alias.css"));+ symlinkSync("second.css", join(projectDir, "assets", "alias.css"));+ expect(affectsPreview(projectDir, "assets/alias.css")).toBe(true);+ expect((await app.request(aliasUrl)).status).toBe(200);++ expect(affectsPreview(projectDir, "assets/second.css")).toBe(true);+ },+ );++ it.skipIf(process.platform === "win32")(+ "counts retargeting a link the read passed through on the way to its file",+ () => {+ const projectDir = realpathSync(createProjectDir());+ for (const version of ["v1", "v2"]) {+ mkdirSync(join(projectDir, "libs", version, "audio"), { recursive: true });+ writeFileSync(join(projectDir, "libs", version, "audio", "a.mp3"), version);+ }+ symlinkSync("v1", join(projectDir, "libs", "current"));+ symlinkSync("libs/current/audio", join(projectDir, "media"));+ recordPreviewRead(projectDir, "media/a.mp3");+ recordPreviewBuilt(projectDir);++ expect(affectsPreview(projectDir, "libs/current")).toBe(true);+ expect(affectsPreview(projectDir, "libs/v1/audio/a.mp3")).toBe(true);+ expect(affectsPreview(projectDir, "libs/v2/audio/a.mp3")).toBe(false);+ },+ );++ it.skipIf(process.platform === "win32")(+ "follows a link target's .. from where the link lands, as the system does",+ () => {+ const projectDir = realpathSync(createProjectDir());+ mkdirSync(join(projectDir, "deep", "nested"), { recursive: true });+ mkdirSync(join(projectDir, "m"));+ writeFileSync(join(projectDir, "deep", "real.mp3"), "x");+ symlinkSync("deep/nested", join(projectDir, "sub"));+ symlinkSync("../sub/../real.mp3", join(projectDir, "m", "a.mp3"));+ recordPreviewRead(projectDir, "m/a.mp3");+ recordPreviewBuilt(projectDir);++ expect(affectsPreview(projectDir, "deep/real.mp3")).toBe(true);+ },+ );++ it.skipIf(process.platform === "win32")(+ "matches a project recorded by its real folder and watched through a link to it",+ () => {+ const realDir = realpathSync(createProjectDir());+ const linkDir = join(createProjectDir(), "linked-project");+ symlinkSync(realDir, linkDir);+ recordPreviewRead(realDir, "style.css");+ recordPreviewBuilt(realDir);++ expect(affectsPreview(linkDir, join(linkDir, "style.css"))).toBe(true);+ expect(affectsPreview(linkDir, join(linkDir, "notes.md"))).toBe(false);+ },+ );++ it("records the folders of a read in a project at the filesystem root", () => {+ const root = parse(process.cwd()).root;+ recordPreviewRead(root, "media/clip.png");+ recordPreviewBuilt(root);+ expect(affectsPreview(root, "media")).toBe(true);+ });++ it("counts a folder event when a file the preview asked for is inside it", async () => {+ const projectDir = createProjectDir();+ writeFileSync(join(projectDir, "index.html"), "<html><body></body></html>");+ const app = new Hono();+ registerPreviewRoutes(app, createAdapter(projectDir, { bundle: async () => null }));+ expect((await app.request("http://localhost/projects/demo/preview")).status).toBe(200);+ expect(+ (await app.request("http://localhost/projects/demo/preview/media/clip.png")).status,+ ).toBe(404);++ expect(affectsPreview(projectDir, "media")).toBe(true);+ expect(affectsPreview(projectDir, join(projectDir, "media"))).toBe(true);+ expect(affectsPreview(projectDir, "med")).toBe(false);+ expect(affectsPreview(projectDir, "docs")).toBe(false);+ });++ it("counts every write until this process has built the preview, even after serving an asset", async () => {+ const projectDir = createProjectDir();+ writeFileSync(join(projectDir, "logo.png"), "logo");+ const app = new Hono();+ registerPreviewRoutes(app, createAdapter(projectDir));++ expect((await app.request("http://localhost/projects/demo/preview/logo.png")).status).toBe(200);++ expect(affectsPreview(projectDir, "index.html")).toBe(true);+ expect(affectsPreview(projectDir, "notes.md")).toBe(true);+ });+});+describe("hf-proxy codec probe", () => {afterEach(() => {vi.resetModules();diff --git a/packages/studio-server/src/routes/preview.ts b/packages/studio-server/src/routes/preview.tsindex 7f64b0f854..3b7f404bdb 100644--- a/packages/studio-server/src/routes/preview.ts+++ b/packages/studio-server/src/routes/preview.ts@@ -25,6 +25,11 @@ import {} from "../helpers/studioMotionRenderScript.js";import { ensureHfIds } from "@hyperframes/parsers/hf-ids";import { settledFileTag } from "../helpers/fileVersion.js";+import {+ recordPreviewBuilt,+ recordPreviewRead,+ recordPreviewReferences,+} from "../helpers/previewReads.js";import { isVariablesPayload, VARIABLES_PAYLOAD_ERROR } from "../helpers/variablesPayload.js";import { injectPreviewVariables } from "../helpers/previewVariables.js";import {@@ -296,13 +301,15 @@ function resolveProjectMainHtml(projectId: string,): { html: string; compositionPath: string } | null {const indexPath = join(projectDir, "index.html");+ const blockHtmlPath = join(projectDir, `${projectId}.html`);+ recordPreviewRead(projectDir, indexPath);+ recordPreviewRead(projectDir, blockHtmlPath);if (existsSync(indexPath)) {return {html: readFileSync(indexPath, "utf-8"),compositionPath: "index.html",};}- const blockHtmlPath = join(projectDir, `${projectId}.html`);if (existsSync(blockHtmlPath)) {return {html: readFileSync(blockHtmlPath, "utf-8"),@@ -355,7 +362,10 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): voconst normalizedDisk = diskMain ? ensureHfIds(diskMain.html) : null;try {- let bundled = await adapter.bundle(project.dir, { stampHfIds: true });+ let bundled = await adapter.bundle(project.dir, {+ stampHfIds: true,+ onRead: (filePath) => recordPreviewRead(project.dir, filePath),+ });let mainCompositionPath = "index.html";if (!bundled) {if (!diskMain) return null;@@ -365,6 +375,8 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vobundled = stripEmbeddedRuntimeScripts(normalizedDisk ?? diskMain.html);mainCompositionPath = diskMain.compositionPath;}+ recordPreviewReferences(project.dir, bundled);+ recordPreviewBuilt(project.dir);// Inject runtime if not already present (check URL pattern and bundler attribute)if (@@ -491,6 +503,9 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): voconst previewVariables = vars.values;const compPath = requestSubPath(c.req.url, "projects/:id/preview/comp");const compFile = resolveWithinProject(project.dir, compPath);+ if (compFile) recordPreviewRead(project.dir, compFile);+ // The sub-composition document takes its head from the root.+ recordPreviewRead(project.dir, "index.html");if (!compFile || !existsSync(compFile) || !statSync(compFile).isFile()) {return c.text("not found", 404);}@@ -520,6 +535,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): vostamped,);if (!html) return c.text("not found", 404);+ recordPreviewReferences(project.dir, html);html = ensureHfIds(await transformPreviewHtml(html, adapter, project, compPath));html = injectStudioPreviewAugmentations(html, adapter, project.dir, compPath);if (previewVariables) html = injectPreviewVariables(html, previewVariables);@@ -542,6 +558,7 @@ export function registerPreviewRoutes(api: Hono, adapter: PreviewApiAdapter): voif (!file) {return c.text("not found", 404);}+ recordPreviewRead(project.dir, file);const stat = existsSync(file) ? statSync(file) : null;if (!stat?.isFile()) {return c.text("not found", 404);diff --git a/packages/studio-server/src/types.ts b/packages/studio-server/src/types.tsindex bd33cc5449..12c041b942 100644--- a/packages/studio-server/src/types.ts+++ b/packages/studio-server/src/types.ts@@ -115,7 +115,10 @@ export interface StudioApiAdapter {history?: (project: ResolvedProject) => Promise<ProjectHistory | null> | ProjectHistory | null;/** Bundle a project directory into a single HTML string, forwarding `options` over the host's own. */- bundle(projectDir: string, options?: Pick<BundleOptions, "stampHfIds">): Promise<string | null>;+ bundle(+ projectDir: string,+ options?: Pick<BundleOptions, "stampHfIds" | "onRead">,+ ): Promise<string | null>;/** Optional: cached signature for project files that should invalidate preview frame caches. */getProjectSignature?: (projectDir: string) => string;diff --git a/packages/studio/src/components/editor/manualEdits.ts b/packages/studio/src/components/editor/manualEdits.tsindex 7d826d7395..a562312fe2 100644--- a/packages/studio/src/components/editor/manualEdits.ts+++ b/packages/studio/src/components/editor/manualEdits.ts@@ -11,6 +11,7 @@ export {export {readFileChangeAffectedCompositions,+ readFileChangeAffectsPreview,readFileChangeField,readStudioFileChangePath,} from "./manualEditsParsing";diff --git a/packages/studio/src/components/editor/manualEditsParsing.ts b/packages/studio/src/components/editor/manualEditsParsing.tsindex e01816d09f..eabc7d2fe1 100644--- a/packages/studio/src/components/editor/manualEditsParsing.ts+++ b/packages/studio/src/components/editor/manualEditsParsing.ts@@ -34,6 +34,10 @@ export function readStudioFileChangePath(payload: unknown): string | null {return path === null ? null : normalizeStudioFileChangePath(path);}+export function readFileChangeAffectsPreview(payload: unknown): boolean {+ return asPayloadRecord(payload)?.affectsPreview !== false;+}+/*** The compositions whose thumbnails a change can alter, or `null` for all of them. Anything* but a list of paths (an older server, the Vite dev host) reads as "all".diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsxindex bac6a98b8d..ce42ce6b00 100644--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx@@ -94,6 +94,55 @@ describe("external file change coordinator", () => {expect(refreshFileTree).toHaveBeenCalledOnce();});+ it("refreshes the file tree but not Preview for a file the preview never loaded", async () => {+ const order: string[] = [];+ await mountCoordinator({+ reloadPreview: () => order.push("preview"),+ reloadSdkSession: () => order.push("sdk"),+ refreshFileTree: () => {+ order.push("tree");+ },+ });+ await act(async () =>+ handler?.({ path: "notes.md", content: "notes", version: "v1", affectsPreview: false }),+ );+ expect(order).toEqual(["sdk", "tree"]);+ });++ it("still reloads Preview when a notes change replaces a waiting film change", async () => {+ let release = () => {};+ const inFlight = new Promise<void>((resolve) => (release = resolve));+ const reloadPreview = vi.fn();+ const reloadSdkSession = vi.fn();+ const onAcceptedPersistedFileChange = vi.fn();+ let drains = 0;+ await mountCoordinator({+ reloadPreview,+ reloadSdkSession,+ onAcceptedPersistedFileChange,+ drainPendingChanges: async () => {+ if (drains++ === 0) await inFlight;+ return { status: "clean" as const };+ },+ });+ await act(async () => handler?.({ path: "index.html", content: "a", version: "v1" }));+ await act(async () =>+ handler?.({+ path: "scene.html",+ content: "b",+ version: "v2",+ affectedCompositions: ["scene.html"],+ }),+ );+ await act(async () =>+ handler?.({ path: "notes.md", content: "c", version: "v3", affectsPreview: false }),+ );+ await act(async () => release());+ expect(reloadPreview).toHaveBeenCalledTimes(2);+ expect(reloadSdkSession).toHaveBeenLastCalledWith("scene.html");+ expect(onAcceptedPersistedFileChange).toHaveBeenLastCalledWith("scene.html", ["scene.html"]);+ });+it("does not refresh the tree for a suppressed self-write echo", async () => {const refreshFileTree = vi.fn();await mountCoordinator({ refreshFileTree });diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.tsindex d15c4aabcf..fc148c9a2b 100644--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts@@ -1,6 +1,7 @@import { useCallback, useEffect, useRef, useState, type MutableRefObject } from "react";import {readFileChangeAffectedCompositions,+ readFileChangeAffectsPreview,readFileChangeField,readStudioFileChangePath,} from "../components/editor/manualEdits";@@ -231,9 +232,12 @@ export function useExternalFileChangeCoordinator({}, [loadConflictSnapshot, projectId, recoveryFilePath]);const reloadAcceptedGeneration = useCallback(- (path: string) => {- logReload("reload", { path, by: "external-change coordinator" });- reloadPreview();+ (path: string, affectsPreview = true) => {+ logReload(affectsPreview ? "reload" : "file-tree only", {+ path,+ by: "external-change coordinator",+ });+ if (affectsPreview) reloadPreview();reloadSdkSession(path);// Fire-and-forget: a failed refresh leaves the tree as stale as it was,// which is the status quo this exists to improve on, not a new failure@@ -279,7 +283,7 @@ export function useExternalFileChangeCoordinator({if (!mountedRef.current || generation !== generationRef.current) return;setBlocked(null);onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(payload));- reloadAcceptedGeneration(path);+ reloadAcceptedGeneration(path, readFileChangeAffectsPreview(payload));return;}const content = readFileChangeContent(payload);@@ -410,7 +414,12 @@ export function useExternalFileChangeCoordinator({return;}- pendingPayloadRef.current = { payload };+ const waiting = pendingPayloadRef.current?.payload;+ const waitingChangeOutranksThis =+ waiting != null &&+ readFileChangeAffectsPreview(waiting) &&+ !readFileChangeAffectsPreview(payload);+ if (!waitingChangeOutranksThis) pendingPayloadRef.current = { payload };void startDrainLoop();},[projectId, pendingTimelineEditPathRef, startDrainLoop, onAcceptedPersistedFileChange],@@ -456,7 +465,7 @@ export function useExternalFileChangeCoordinator({await deleteConflictSnapshot?.(projectId, path);setBlocked(null);onAcceptedPersistedFileChange(path, readFileChangeAffectedCompositions(current.payload));- reloadAcceptedGeneration(path);+ reloadAcceptedGeneration(path, readFileChangeAffectsPreview(current.payload));},[deleteConflictSnapshot,diff --git a/packages/studio/vite.adapter.projects.test.ts b/packages/studio/vite.adapter.projects.test.tsindex 88d3d1cf99..2f844da539 100644--- a/packages/studio/vite.adapter.projects.test.ts+++ b/packages/studio/vite.adapter.projects.test.ts@@ -187,7 +187,7 @@ describe("dynamic preview ownership", () => {compute: () => "signature",watch: (dir) => {// Ownership must exist before newly watched files can emit events.- expect(previewChangeOwner(owners, join(dir, "index.html"))).toBe("new-project");+ expect(previewChangeOwner(owners, join(dir, "index.html"))?.projectId).toBe("new-project");watched.push(dir);},});@@ -205,8 +205,9 @@ describe("dynamic preview ownership", () => {cache.get(project.dir);writeFileSync(join(dir, "index.html"), "after");expect(watched).toEqual([realpathSync(dir)]);- expect(previewChangeOwner(owners, join(realpathSync(dir), "index.html"))).toBe("new-project");- expect(previewChangeOwner(owners, join(realpathSync(dir), "index.html.tmp"))).toBeNull();+ expect(previewChangeOwner(owners, join(realpathSync(dir), "index.html"))?.projectId).toBe(+ "new-project",+ );});});diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.tsindex 9b4ae7144f..c5c1ed9045 100644--- a/packages/studio/vite.config.ts+++ b/packages/studio/vite.config.ts@@ -150,6 +150,7 @@ function devProjectApi(): Plugin {expectedVersion: string,) => { path: string; version: string; writeToken: string } | null;fileContentVersion: (content: string) => string;+ affectsPreview: (projectDir: string, changedPath: string) => boolean;DELETED_VERSION: string;openProjectHistory: typeof openProjectHistory;} | null = null;@@ -166,6 +167,7 @@ function devProjectApi(): Plugin {for (const name of ["identifyFileWrite","fileContentVersion",+ "affectsPreview","openProjectHistory",] as const) {if (typeof mod[name] !== "function") {@@ -278,11 +280,19 @@ function devProjectApi(): Plugin {const receipt = studioServer? studioServer.identifyFileWrite(filePath, version ?? studioServer.DELETED_VERSION): null;- const projectId = owner;+ // The API records what the preview loaded in this same module, so ask it here.+ const reloads = studioServer?.affectsPreview(owner.projectDir, filePath) ?? true;server.ws.send({type: "custom",event: "hf:file-change",- data: { path: filePath, version, projectId, ...receipt },+ data: {+ path: filePath,+ version,+ projectId: owner.projectId,+ affectsPreview: reloads,+ ...(reloads ? {} : { affectedCompositions: [] }),+ ...receipt,+ },});});server.httpServer?.on("close", () => void projectWatcher.close());diff --git a/packages/studio/vite.preview-watch.test.ts b/packages/studio/vite.preview-watch.test.tsindex 5ab0e1f3da..3b09178afc 100644--- a/packages/studio/vite.preview-watch.test.ts+++ b/packages/studio/vite.preview-watch.test.ts@@ -1,4 +1,4 @@-import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";+import { mkdtempSync, mkdirSync, rmSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -10,24 +10,23 @@ afterEach(() => {});describe("Vite preview change ownership", () => {- it("uses a symlink target's project id and config without leaking into sibling projects", () => {+ it("names the project that owns a path, and none for a path outside every project", () => {const root = mkdtempSync(join(tmpdir(), "hf-vite-watch-"));dirs.push(root);const a = join(root, "external");const b = join(root, "external-other");for (const path of [a, b]) mkdirSync(path);- writeFileSync(- join(a, "hyperframes.json"),- JSON.stringify({ preview: { watchIgnore: ["docs"] } }),- );const projects = new Map([[a, "symlink-project"],[b, "other-project"],]);- expect(previewChangeOwner(projects, join(a, "index.html"))).toBe("symlink-project");- expect(previewChangeOwner(projects, join(a, "docs", "report.json"))).toBeNull();- expect(previewChangeOwner(projects, join(a, "index.html.tmp"))).toBeNull();- expect(previewChangeOwner(projects, join(b, "docs", "report.json"))).toBe("other-project");+ expect(previewChangeOwner(projects, join(a, "index.html"))).toEqual({+ projectDir: a,+ projectId: "symlink-project",+ });+ expect(previewChangeOwner(projects, join(b, "docs", "report.json"))?.projectId).toBe(+ "other-project",+ );expect(previewChangeOwner(projects, join(root, "outside.html"))).toBeNull();});@@ -43,7 +42,7 @@ describe("Vite preview change ownership", () => {[nested, "nested"],]),join(nested, "index.html"),- ),+ )?.projectId,).toBe("nested");});});diff --git a/packages/studio/vite.preview-watch.ts b/packages/studio/vite.preview-watch.tsindex 76242d07c8..b99a10dc63 100644--- a/packages/studio/vite.preview-watch.ts+++ b/packages/studio/vite.preview-watch.ts@@ -1,13 +1,12 @@import { sep } from "node:path";-import { shouldReloadPreview } from "@hyperframes/studio-server";+/** The watched project that owns `filePath`, nearest root first when projects nest. */export function previewChangeOwner(watchedProjects: ReadonlyMap<string, string>,filePath: string,-): string | null {+): { projectDir: string; projectId: string } | null {const owner = [...watchedProjects].sort(([left], [right]) => right.length - left.length).find(([dir]) => filePath.startsWith(dir + sep));- if (!owner || !shouldReloadPreview(owner[0], filePath)) return null;- return owner[1];+ return owner ? { projectDir: owner[0], projectId: owner[1] } : null;}diff --git a/scripts/check-no-main-deletions.mjs b/scripts/check-no-main-deletions.mjsindex 71d899409c..eb60193418 100644--- a/scripts/check-no-main-deletions.mjs+++ b/scripts/check-no-main-deletions.mjs@@ -1083,6 +1083,16 @@ export const ALLOWED_DELETIONS = new Map(["registry/examples/vscode-theme-visualizer/scripts/build-theme-registry.mjs","removed in the 2026-09 low-use catalog cut, see the PR",],+ [+ "packages/studio-server/src/helpers/previewWatchIgnore.ts",+ "preview.watchIgnore is replaced by reloading only when a file the preview loaded changes",+ ],+ [+ "packages/studio-server/src/helpers/previewWatchIgnore.test.ts",+ "tests for the removed preview.watchIgnore helper",+ ],+ ["docs/images/preview-reload-evidence/after.webm", "evidence video no page referenced"],+ ["docs/images/preview-reload-evidence/before.webm", "evidence video no page referenced"],]);export function parseBase(argv, fallback = "origin/main") {