Files
webstudio/packages/cli/src/fs-utils.ts
T
Oleg Isonen b2a34f1713 feat: Fast MCP iterative previews (#5947)
## Summary

This PR documents a measured architecture plan for making the MCP
edit-to-screenshot loop fast enough and reliable enough for iterative
site authoring. It intentionally changes no runtime behavior yet.

The current implementation rebuilds a production preview after small
committed mutations. Testing an editable local clone of the production
Webstudio homepage also exposed a correctness gap: a path screenshot
called directly after a mutation can return a stale, byte-identical
image.

## Measured baseline

Repository fixture:

- committed text edit: **24-25 ms**
- post-edit regeneration, production build, and server restart: **7.9
s**
- first screenshot after restart and browser relaunch: **9.1 s**
- combined first post-edit screenshot: **17.1 s**
- unchanged warm screenshot: **1.1 s**

Production homepage, read-only:

- remote refresh: **3.1 s**
- complete production preview preparation/start: **16.0 s**
- cold homepage screenshot: **10.2 s**
- unchanged warm screenshot: **1.36 s**
- predicted post-edit screenshot from measured phases: **approximately
26.2 s**

Editable local production-homepage clone:

- retained **43 routes** and **266 homepage text nodes**
- committed heading mutation: **0.81-0.87 s**
- explicit post-edit preview generation/build/start: **11.6-12.6 s**
- first screenshot after explicit preview start: **9.8-11.8 s**
- complete mutation-to-visible-screenshot cycle: **22.9-25.2 s**
- complete edit, verify, screenshot, restore, and stop run: **52.7 s**

The changed screenshot visibly rendered the test heading, and the
restored screenshot matched the original byte for byte.

## Correctness finding

Calling a path screenshot directly after the committed mutation took
**20.1 s**, but both post-edit captures were byte-identical to the
baseline and rendered the old heading. Explicitly calling
`preview.start({ source: "session" })` made the edit visible.

The reported generated-build version also remained at 1 while the
project session advanced through versions 4 and 5. Current screenshot
output therefore cannot prove that it rendered the mutation it is meant
to verify.

## Proposed direction

- [ ] Introduce explicit iterative and production preview modes under
one controller contract.
- [ ] Keep a Vite development preview and browser alive for MCP
authoring screenshots.
- [ ] Preserve production preview for rendered audits and final
verification.
- [ ] Regenerate from the authoritative project session, wait for Vite
compilation, then normally reload the retained browser page.
- [ ] Make a direct post-mutation path screenshot refresh the latest
committed session without using HMR.
- [ ] Add a project-version freshness handshake so stale screenshots
fail.
- [ ] Serialize and coalesce regeneration after rapid mutations.
- [ ] Return preview mode, rendered project version, and complete phase
timings.
- [ ] Add lifecycle, integration, and local agent evaluation coverage.

## Performance target

Warm edit-to-screenshot latency should be at most **3 seconds p95**
across ten sequential small edits, without invoking `npm run build`,
`npm run start`, or launching another browser.

## Verification

- [x] Measured the source CLI against the authenticated repository
fixture.
- [x] Measured the production homepage without changing production.
- [x] Synchronized the production bundle into a disposable local Builder
project.
- [x] Committed and visually verified a real heading edit through local
MCP.
- [x] Restored the original heading and verified the restored screenshot
byte for byte.
- [x] Reproduced the stale direct-screenshot behavior.
- [x] Formatted the plan with `oxfmt`.
- [x] Verified the documentation diff with `git diff --check`.

The complete architecture, race handling, test matrix, acceptance
criteria, and non-goals are in
`apps/builder/docs/mcp-iterative-preview-plan.md`.
2026-07-24 01:05:10 +02:00

107 lines
2.6 KiB
TypeScript

import { dirname } from "node:path";
import { randomUUID } from "node:crypto";
import {
access,
mkdir,
rename,
rm,
writeFile,
constants,
readFile,
} from "node:fs/promises";
export const isFileExists = async (filePath: string) => {
try {
await access(filePath, constants.F_OK);
return true;
} catch {
return false;
}
};
export const createFileIfNotExists = async (
filePath: string,
content?: string
) => {
const dir = dirname(filePath);
await createFolderIfNotExists(dir);
try {
await access(filePath, constants.F_OK);
} catch {
await writeFile(filePath, content ?? "", "utf8");
}
};
export const createFolderIfNotExists = async (folderPath: string) => {
try {
await access(folderPath, constants.F_OK);
} catch {
await mkdir(folderPath, { recursive: true });
}
};
export const writeFileAtomic = async (filePath: string, content: string) => {
const temporaryFilePath = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
await createFolderIfNotExists(dirname(filePath));
try {
await writeFile(temporaryFilePath, content, "utf8");
await rename(temporaryFilePath, filePath);
} catch (error) {
await rm(temporaryFilePath, { force: true });
throw error;
}
};
export const writeFileIfChanged = async (filePath: string, content: string) => {
if ((await readFile(filePath, "utf8").catch(() => undefined)) === content) {
return false;
}
await writeFileAtomic(filePath, content);
return true;
};
const wait = (duration: number) =>
new Promise((resolve) => setTimeout(resolve, duration));
export const withFileLock = async <Result>(
filePath: string,
callback: () => Promise<Result>
) => {
const lockPath = `${filePath}.lock`;
await createFolderIfNotExists(dirname(filePath));
const start = Date.now();
while (true) {
try {
await mkdir(lockPath, { recursive: false });
break;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") {
throw error;
}
if (Date.now() - start > 10_000) {
throw new Error(`Timed out waiting for file lock ${lockPath}`);
}
await wait(50);
}
}
try {
return await callback();
} finally {
await rm(lockPath, { recursive: true, force: true });
}
};
export const loadJSONFile = async <T>(filePath: string): Promise<T | null> => {
try {
const content = await readFile(filePath, "utf8");
return JSON.parse(content) as T;
} catch (error) {
if (error instanceof Error && "code" in error && error.code === "ENOENT") {
return null;
}
throw error;
}
};