Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Fast MCP iterative previews (#5947)
Oleg Isonenb2a34f1713d4
diff --git a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts+++ b/fixtures/react-router-cloudflare/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx b/fixtures/react-router-cloudflare/app/__generated__/_index.tsxindex 816886d638..3064b027a9 100644--- a/fixtures/react-router-cloudflare/app/__generated__/_index.tsx+++ b/fixtures/react-router-cloudflare/app/__generated__/_index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 43;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2025-01-04T11:01:50.091Z";diff --git a/fixtures/react-router-cloudflare/app/root.tsx b/fixtures/react-router-cloudflare/app/root.tsxindex ae64304577..f006c0cc92 100644--- a/fixtures/react-router-cloudflare/app/root.tsx+++ b/fixtures/react-router-cloudflare/app/root.tsx@@ -11,7 +11,12 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +54,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts b/fixtures/react-router-docker/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/react-router-docker/app/__generated__/$resources.assets.ts+++ b/fixtures/react-router-docker/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/react-router-docker/app/__generated__/_index.tsx b/fixtures/react-router-docker/app/__generated__/_index.tsxindex 816886d638..3064b027a9 100644--- a/fixtures/react-router-docker/app/__generated__/_index.tsx+++ b/fixtures/react-router-docker/app/__generated__/_index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 43;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2025-01-04T11:01:50.091Z";diff --git a/fixtures/react-router-docker/app/root.tsx b/fixtures/react-router-docker/app/root.tsxindex ae64304577..f006c0cc92 100644--- a/fixtures/react-router-docker/app/root.tsx+++ b/fixtures/react-router-docker/app/root.tsx@@ -11,7 +11,12 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +54,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/react-router-docker/vite.config.ts b/fixtures/react-router-docker/vite.config.tsindex 994cf66075..f8a0782b3c 100644--- a/fixtures/react-router-docker/vite.config.ts+++ b/fixtures/react-router-docker/vite.config.ts@@ -6,6 +6,9 @@ const sourceConditions =export default defineConfig({plugins: [reactRouter()],+ server: {+ hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,+ },resolve: {conditions: [...sourceConditions, "browser", "development|production"],},diff --git a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts b/fixtures/react-router-netlify/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts+++ b/fixtures/react-router-netlify/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/react-router-netlify/app/__generated__/_index.tsx b/fixtures/react-router-netlify/app/__generated__/_index.tsxindex 816886d638..3064b027a9 100644--- a/fixtures/react-router-netlify/app/__generated__/_index.tsx+++ b/fixtures/react-router-netlify/app/__generated__/_index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 43;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2025-01-04T11:01:50.091Z";diff --git a/fixtures/react-router-netlify/app/root.tsx b/fixtures/react-router-netlify/app/root.tsxindex ae64304577..f006c0cc92 100644--- a/fixtures/react-router-netlify/app/root.tsx+++ b/fixtures/react-router-netlify/app/root.tsx@@ -11,7 +11,12 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +54,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts b/fixtures/react-router-vercel/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts+++ b/fixtures/react-router-vercel/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/react-router-vercel/app/__generated__/_index.tsx b/fixtures/react-router-vercel/app/__generated__/_index.tsxindex 816886d638..3064b027a9 100644--- a/fixtures/react-router-vercel/app/__generated__/_index.tsx+++ b/fixtures/react-router-vercel/app/__generated__/_index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 43;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2025-01-04T11:01:50.091Z";diff --git a/fixtures/react-router-vercel/app/root.tsx b/fixtures/react-router-vercel/app/root.tsxindex ae64304577..f006c0cc92 100644--- a/fixtures/react-router-vercel/app/root.tsx+++ b/fixtures/react-router-vercel/app/root.tsx@@ -11,7 +11,12 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +54,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/react-router-vercel/vite.config.ts b/fixtures/react-router-vercel/vite.config.tsindex 994cf66075..f8a0782b3c 100644--- a/fixtures/react-router-vercel/vite.config.ts+++ b/fixtures/react-router-vercel/vite.config.ts@@ -6,6 +6,9 @@ const sourceConditions =export default defineConfig({plugins: [reactRouter()],+ server: {+ hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,+ },resolve: {conditions: [...sourceConditions, "browser", "development|production"],},diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsxindex edd1e99cca..fe06a3d837 100644--- a/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx+++ b/fixtures/ssg-cloudflare-pages/app/__generated__/_index.tsx@@ -17,6 +17,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 38;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2024-07-29T12:50:07.515Z";diff --git a/fixtures/ssg-cloudflare-pages/renderer/+onRenderHtml.tsx b/fixtures/ssg-cloudflare-pages/renderer/+onRenderHtml.tsxindex d793abce88..f7a96c9728 100644--- a/fixtures/ssg-cloudflare-pages/renderer/+onRenderHtml.tsx+++ b/fixtures/ssg-cloudflare-pages/renderer/+onRenderHtml.tsx@@ -4,6 +4,7 @@ import type { OnRenderHtmlSync } from "vike/types";import {CustomCode,projectId,+ projectVersion,lastPublished,// @todo think about how to make __generated__ typeable/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */@@ -19,6 +20,7 @@ export const onRenderHtml: OnRenderHtmlSync = (pageContext) => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsxindex 7fa9a1c098..658c1bb7b2 100644--- a/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx+++ b/fixtures/ssg-netlify-by-project-id/app/__generated__/_index.tsx@@ -14,6 +14,8 @@ import {export const projectId = "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e";+export const projectVersion = 7;+export const projectDomain = "fixture-client-do-not-touch-wsmel";export const lastPublished = "2026-01-04T10:46:48.415Z";diff --git a/fixtures/ssg-netlify-by-project-id/renderer/+onRenderHtml.tsx b/fixtures/ssg-netlify-by-project-id/renderer/+onRenderHtml.tsxindex d793abce88..f7a96c9728 100644--- a/fixtures/ssg-netlify-by-project-id/renderer/+onRenderHtml.tsx+++ b/fixtures/ssg-netlify-by-project-id/renderer/+onRenderHtml.tsx@@ -4,6 +4,7 @@ import type { OnRenderHtmlSync } from "vike/types";import {CustomCode,projectId,+ projectVersion,lastPublished,// @todo think about how to make __generated__ typeable/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */@@ -19,6 +20,7 @@ export const onRenderHtml: OnRenderHtmlSync = (pageContext) => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.tsindex fb507cabf1..6274fdf61e 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/$resources.assets.ts@@ -1,11 +1,11 @@export const assets = {"1d8bf4398f643f5333d415091507d778aaed62f28883642636cbed0be156a0ee": {- url: "/cgi/image/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg?format=raw",+ url: "/assets/iconly_svg_converted-converted_zMaMiAAutUl8XrITgz7d1.svg",width: 14,height: 16,},d0974db9300c1a3b0fb8b291dd9fabd45ad136478908394280af2f7087e3aecd: {- url: "/cgi/image/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg?format=raw",+ url: "/assets/147-1478573_cat-icon-png-black-cat-png-icon.png_ZJ6-qJjk1RlFzuYwyCXdp.jpeg",width: 820,height: 985,},diff --git a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsxindex 811a19ce7a..3457077bd5 100644--- a/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx+++ b/fixtures/webstudio-cloudflare-template/app/__generated__/_index.tsx@@ -19,6 +19,8 @@ import {export const projectId = "d845c167-ea07-4875-b08d-83e97c09dcce";+export const projectVersion = 38;+export const projectDomain = "cli-basic-test-d0osr";export const lastPublished = "2024-07-29T12:50:07.515Z";diff --git a/fixtures/webstudio-cloudflare-template/app/root.tsx b/fixtures/webstudio-cloudflare-template/app/root.tsxindex 0fde2045df..38c46cb8d6 100644--- a/fixtures/webstudio-cloudflare-template/app/root.tsx+++ b/fixtures/webstudio-cloudflare-template/app/root.tsx@@ -8,7 +8,12 @@ import type {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -46,6 +51,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts b/fixtures/webstudio-features/app/__generated__/$resources.assets.tsindex f3e3d47278..4905f46368 100644--- a/fixtures/webstudio-features/app/__generated__/$resources.assets.ts+++ b/fixtures/webstudio-features/app/__generated__/$resources.assets.ts@@ -1,25 +1,25 @@export const assets = {"2b151fc7b4b0324e6ab78c40f72c7f59273f81fb1be3d08b3f9976428601b95e": {- url: "/cgi/asset/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3?format=raw",+ url: "/assets/e-mail-39993_vrxyjxQv3j67Krs62Vz7Y.mp3",},"4afe692f78ec0530e355a551a3860302c4478037db7b25a3bdae82c32c78634d": {- url: "/cgi/asset/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm?format=raw",+ url: "/assets/webm-example_2r_6VmRBjhAy3ldaqz0gk.webm",},"7cf5892080fa66b5e6175ffd2d27c304ee6b09ce1f21847a95000225ad1afa59": {- url: "/cgi/image/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png?format=raw",+ url: "/assets/cat_silhouette_BDpTbUFSpVbfUWQZNxbBG.png",width: 790,height: 786,},"9a8bc926-7804-4d3f-af81-69196b1d2ed8": {- url: "/cgi/image/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp?format=raw",+ url: "/assets/small-avif-kitty_FnabJsioMWpBtXZSGf4DR.webp",width: 100,height: 100,},cbf6b1b052e52b256cef54a032a546bf43bf3f5441be4d1c5eeaabce26903d78: {- url: "/cgi/asset/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4?format=raw",+ url: "/assets/video_QamtUWsD-ShifhzZLoNIv_ald_1xtyEb3uHhFb7nCQa.mp4",},"cd939c56-bcdd-4e64-bd9c-567a9bccd3da": {- url: "/cgi/image/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg?format=raw",+ url: "/assets/_937084ed-a798-49fe-8664-df93a2af605e_uiBk3o6UWdqolyakMvQJ9.jpeg",width: 1024,height: 1024,},diff --git a/fixtures/webstudio-features/app/__generated__/_index.tsx b/fixtures/webstudio-features/app/__generated__/_index.tsxindex fe9a11f496..532391737a 100644--- a/fixtures/webstudio-features/app/__generated__/_index.tsx+++ b/fixtures/webstudio-features/app/__generated__/_index.tsx@@ -22,6 +22,8 @@ import {export const projectId = "cddc1d44-af37-4cb6-a430-d300cf6f932d";+export const projectVersion = 634;+export const projectDomain = "webstudio-fixture-project-a-0su3o";export const lastPublished = "2026-01-15T16:19:55.574Z";diff --git a/fixtures/webstudio-features/app/root.tsx b/fixtures/webstudio-features/app/root.tsxindex ae64304577..f006c0cc92 100644--- a/fixtures/webstudio-features/app/root.tsx+++ b/fixtures/webstudio-features/app/root.tsx@@ -11,7 +11,12 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import {+ CustomCode,+ projectId,+ projectVersion,+ lastPublished,+} from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +54,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/packages/cli/src/async-utils.test.ts b/packages/cli/src/async-utils.test.tsnew file mode 100644index 0000000000..a71bb39fac--- /dev/null+++ b/packages/cli/src/async-utils.test.ts@@ -0,0 +1,42 @@+import { expect, test } from "vitest";+import { createExclusiveAsyncRunner } from "./async-utils";++test("runs asynchronous work exclusively in call order", async () => {+ const runExclusive = createExclusiveAsyncRunner();+ const events: string[] = [];+ let releaseFirst: () => void = () => undefined;+ let markFirstStarted: () => void = () => undefined;+ const firstStarted = new Promise<void>((resolve) => {+ markFirstStarted = resolve;+ });+ const firstBlocked = new Promise<void>((resolve) => {+ releaseFirst = resolve;+ });++ const first = runExclusive(async () => {+ events.push("first:start");+ markFirstStarted();+ await firstBlocked;+ events.push("first:end");+ });+ const second = runExclusive(async () => {+ events.push("second");+ });+ await firstStarted;+ expect(events).toEqual(["first:start"]);++ releaseFirst();+ await Promise.all([first, second]);+ expect(events).toEqual(["first:start", "first:end", "second"]);+});++test("continues after a failed run", async () => {+ const runExclusive = createExclusiveAsyncRunner();++ await expect(+ runExclusive(async () => {+ throw new Error("failed");+ })+ ).rejects.toThrow("failed");+ await expect(runExclusive(async () => "complete")).resolves.toBe("complete");+});diff --git a/packages/cli/src/async-utils.ts b/packages/cli/src/async-utils.tsnew file mode 100644index 0000000000..3937c29f93--- /dev/null+++ b/packages/cli/src/async-utils.ts@@ -0,0 +1,16 @@+export const createExclusiveAsyncRunner = () => {+ let queue = Promise.resolve();+ return async <Result>(callback: () => Promise<Result>) => {+ const previousRun = queue;+ let releaseCurrentRun: () => void = () => undefined;+ queue = new Promise((resolve) => {+ releaseCurrentRun = resolve;+ });+ await previousRun.catch(() => undefined);+ try {+ return await callback();+ } finally {+ releaseCurrentRun();+ }+ };+};diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.tsindex 3472cf9b88..d340c1b999 100644--- a/packages/cli/src/commands/api-command-docs.test.ts+++ b/packages/cli/src/commands/api-command-docs.test.ts@@ -85,10 +85,15 @@ const createMetadataOnlyMcpAdapter = () =>installUrl: "",warnings: [],}),- startPreview: async () => ({ url: "http://localhost:5173", running: true }),+ startPreview: async () => ({+ url: "http://localhost:5173",+ running: true,+ mode: "iterative",+ }),getPreviewStatus: async () => ({url: "http://localhost:5173",running: true,+ mode: "iterative",}),});diff --git a/packages/cli/src/commands/mcp-preview.test.ts b/packages/cli/src/commands/mcp-preview.test.tsindex 8806888ce8..60b194bb5b 100644--- a/packages/cli/src/commands/mcp-preview.test.ts+++ b/packages/cli/src/commands/mcp-preview.test.ts@@ -1,5 +1,72 @@import { expect, test, vi } from "vitest";-import { createMcpPreviewHandlers } from "./mcp-preview";+import {+ createMcpPreviewHandlers,+ createPreviewFreshness,+} from "./mcp-preview";++test("does not mark a preview fresh after a newer mutation", () => {+ const freshness = createPreviewFreshness();+ const capturedRevision = freshness.capture();++ freshness.markStale();+ freshness.markFresh(capturedRevision);++ expect(freshness.isStale()).toBe(true);+ const currentRevision = freshness.capture();+ freshness.markFresh(currentRevision);+ expect(freshness.isStale()).toBe(false);+});++test("coalesces overlapping refreshes of the same stale preview", async () => {+ const freshness = createPreviewFreshness();+ let releasePreparation: () => void = () => undefined;+ const preparationBlocked = new Promise<void>((resolve) => {+ releasePreparation = resolve;+ });+ const preparePreview = vi.fn(async () => {+ await preparationBlocked;+ return { cwd: "/tmp/preview" };+ });+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ canReuse: vi.fn(() => true),+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:5173${path}`),+ };+ const captureScreenshot = createCaptureScreenshotMock([]);+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: freshness.isStale,+ captureFreshness: freshness.capture,+ markFresh: freshness.markFresh,+ preparePreview,+ captureScreenshot,+ });++ const firstCapture = handlers.captureScreenshot({+ path: "/first",+ viewport: { width: 1280, height: 720 },+ });+ const secondCapture = handlers.captureScreenshot({+ path: "/second",+ viewport: { width: 1280, height: 720 },+ });+ await vi.waitFor(() => expect(preparePreview).toHaveBeenCalledOnce());+ releasePreparation();+ await Promise.all([firstCapture, secondCapture]);++ expect(preparePreview).toHaveBeenCalledOnce();+ expect(preview.startAndWait).toHaveBeenCalledOnce();+ expect(captureScreenshot).toHaveBeenCalledTimes(2);+});const createCaptureScreenshotMock = (events: string[]) =>vi.fn(async (options) => {@@ -33,10 +100,18 @@ test("captures stale path screenshots through the restarted preview server", asyevents.push("session");});const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "production" as const,+ })),startAndWait: vi.fn(async (options) => {events.push(`start:${options.cwd}:${options.restart}`);- return { url: "http://127.0.0.1:3000/", running: true };+ return {+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ };}),resolveUrl: vi.fn((path: string) => {events.push(`resolve:${path}`);@@ -96,7 +171,7 @@ test("captures stale path screenshots through the restarted preview server", asyexpect(prepareSessionDataFile).not.toHaveBeenCalled();expect(progress).toEqual(["tool screenshot preparing generated preview project",- "tool screenshot starting production preview server",+ "tool screenshot starting iterative preview server","tool screenshot capturing http://127.0.0.1:3000/pricing",]);});@@ -104,10 +179,18 @@ test("captures stale path screenshots through the restarted preview server", asytest("passes explicit preview source to preview preparation", async () => {const events: string[] = [];const preview = {- status: vi.fn(() => ({ url: "", running: false })),+ status: vi.fn(() => ({+ url: "",+ running: false,+ mode: "production" as const,+ })),startAndWait: vi.fn(async (options) => {events.push(`start:${options.cwd}:${options.restart}`);- return { url: "http://127.0.0.1:3000/", running: true };+ return {+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ };}),resolveUrl: vi.fn(),};@@ -136,7 +219,11 @@ test("passes explicit preview source to preview preparation", async () => {expect(preparePreview).toHaveBeenCalledWith("session",- prepareSessionDataFile+ prepareSessionDataFile,+ {+ preserveGeneratedProject: false,+ prepareForIncrementalGeneration: true,+ });expect(prepareSessionDataFile).toHaveBeenCalledOnce();expect(events).toEqual([@@ -145,13 +232,17 @@ test("passes explicit preview source to preview preparation", async () => {]);expect(progress).toEqual(["tool preview.start preparing generated preview project",- "tool preview.start starting production preview server",+ "tool preview.start starting iterative preview server",]);});test("rejects invalid external image domains before preparing preview", async () => {const preview = {- status: vi.fn(() => ({ url: "", running: false })),+ status: vi.fn(() => ({+ url: "",+ running: false,+ mode: "production" as const,+ })),startAndWait: vi.fn(),resolveUrl: vi.fn(),};@@ -182,7 +273,11 @@ test("rejects invalid external image domains before preparing preview", async ()test("captures fresh path screenshots through the running preview server", async () => {const events: string[] = [];const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),startAndWait: vi.fn(),resolveUrl: vi.fn((path: string) => {events.push(`resolve:${path}`);@@ -202,7 +297,7 @@ test("captures fresh path screenshots through the running preview server", asynccaptureScreenshot,});- await handlers.captureScreenshot(+ const result = await handlers.captureScreenshot({path: "/about",viewport: { width: 1440, height: 900 },@@ -225,17 +320,65 @@ test("captures fresh path screenshots through the running preview server", asyncfullPage: true,}));+ expect(result.previewMode).toBe("iterative");expect(progress).toEqual(["tool screenshot capturing http://127.0.0.1:3000/about",]);});+test("does not regenerate for repeated explicit options that match preview", async () => {+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ canReuse: vi.fn(() => true),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:5173${path}`),+ };+ const preparePreview = vi.fn();+ const captureScreenshot = createCaptureScreenshotMock([]);+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => false,+ preparePreview,+ captureScreenshot,+ });++ await handlers.captureScreenshot({+ path: "/about",+ host: "127.0.0.1",+ port: 5173,+ imageDomains: ["images.example.com"],+ viewport: { width: 1440, height: 900 },+ });++ expect(preview.canReuse).toHaveBeenCalledWith({+ host: "127.0.0.1",+ port: 5173,+ imageDomains: ["images.example.com"],+ mode: "iterative",+ });+ expect(preparePreview).not.toHaveBeenCalled();+ expect(preview.startAndWait).not.toHaveBeenCalled();+ expect(captureScreenshot).toHaveBeenCalledOnce();+});+test("reuses and closes one browser capture session for session screenshots", async () => {const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),startAndWait: vi.fn(),resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),- stop: vi.fn(async () => ({ url: "", running: false })),+ stop: vi.fn(async () => ({+ url: "",+ running: false,+ mode: "iterative" as const,+ })),};const capture = createCaptureScreenshotMock([]);const close = vi.fn(async () => undefined);@@ -268,12 +411,123 @@ test("reuses and closes one browser capture session for session screenshots", asexpect(preview.stop).toHaveBeenCalledOnce();});+test("waits for an active capture before stopping preview resources", async () => {+ let finishCapture: () => void = () => undefined;+ const captureBlocked = new Promise<void>((resolve) => {+ finishCapture = resolve;+ });+ const capture = vi.fn(async () => {+ await captureBlocked;+ return createCaptureScreenshotMock([])({+ url: "http://127.0.0.1:5173/",+ width: 1280,+ height: 720,+ });+ });+ const close = vi.fn(async () => undefined);+ const stop = vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: false,+ mode: "iterative" as const,+ }));+ const handlers = createMcpPreviewHandlers({+ preview: {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ stop,+ },+ isStale: () => false,+ createCaptureSession: vi.fn(() => ({+ capture,+ capturePage: vi.fn(async () => []),+ close,+ })),+ });++ const captureResult = handlers.captureScreenshot({+ path: "/",+ viewport: { width: 1280, height: 720 },+ });+ await vi.waitFor(() => expect(capture).toHaveBeenCalledOnce());+ const stopResult = handlers.stopPreview();+ await Promise.resolve();+ expect(stop).not.toHaveBeenCalled();+ expect(close).not.toHaveBeenCalled();++ finishCapture();+ await captureResult;+ await stopResult;+ expect(close).toHaveBeenCalledOnce();+ expect(stop).toHaveBeenCalledOnce();+});++test("recreates the capture session when the browser configuration changes", async () => {+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),+ };+ const firstClose = vi.fn(async () => undefined);+ const secondClose = vi.fn(async () => undefined);+ const createCaptureSession = vi+ .fn()+ .mockReturnValueOnce({+ capture: createCaptureScreenshotMock([]),+ capturePage: vi.fn(async () => []),+ close: firstClose,+ })+ .mockReturnValueOnce({+ capture: createCaptureScreenshotMock([]),+ capturePage: vi.fn(async () => []),+ close: secondClose,+ });+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => false,+ createCaptureSession,+ });++ await handlers.captureScreenshot({+ path: "/one",+ source: "session",+ browser: "chromium",+ viewport: { width: 1440, height: 900 },+ });+ await handlers.captureScreenshot({+ path: "/two",+ source: "session",+ browser: "chrome",+ viewport: { width: 1440, height: 900 },+ });++ expect(createCaptureSession).toHaveBeenCalledTimes(2);+ expect(firstClose).toHaveBeenCalledOnce();+ expect(secondClose).not.toHaveBeenCalled();+});+test("stops the owned preview when browser capture cleanup fails", async () => {const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),startAndWait: vi.fn(),resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),- stop: vi.fn(async () => ({ url: "", running: false })),+ stop: vi.fn(async () => ({+ url: "",+ running: false,+ mode: "iterative" as const,+ })),};const cleanupError = new Error("browser cleanup failed");const createCaptureSession = vi.fn(() => ({@@ -301,7 +555,11 @@ test("stops the owned preview when browser capture cleanup fails", async () => {test("captures one session page across multiple viewports through resize", async () => {const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:3000/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),startAndWait: vi.fn(),resolveUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`),};@@ -330,7 +588,6 @@ test("captures one session page across multiple viewports through resize", async},{path: "/responsive",- source: "session",viewport: { width: 1440, height: 900 },waitForTimeout: 0,},@@ -353,6 +610,53 @@ test("captures one session page across multiple viewports through resize", asyncexpect(preview.startAndWait).not.toHaveBeenCalled();});+test.each([+ ["browser", { browser: "chromium" as const }, { browser: "chrome" as const }],+ ["mode", { mode: "iterative" as const }, { mode: "production" as const }],+ ["host", { host: "127.0.0.1" }, { host: "localhost" }],+ ["port", { port: 5173 }, { port: 5174 }],+ [+ "image domains",+ { imageDomains: ["one.example.com"] as string[] },+ { imageDomains: ["two.example.com"] as string[] },+ ],+] as const)(+ "rejects resized captures with mixed %s",+ async (_, first, second) => {+ const createCaptureSession = vi.fn();+ const handlers = createMcpPreviewHandlers({+ preview: {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:3000/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn(),+ },+ createCaptureSession,+ });++ await expect(+ handlers.capturePageScreenshots([+ {+ path: "/responsive",+ source: "session",+ ...first,+ viewport: { width: 375, height: 812 },+ },+ {+ path: "/responsive",+ source: "session",+ ...second,+ viewport: { width: 1440, height: 900 },+ },+ ])+ ).rejects.toThrow("one session preview target and browser configuration");+ expect(createCaptureSession).not.toHaveBeenCalled();+ }+);+test("captures path screenshots through an existing base URL without preview", async () => {const events: string[] = [];const preview = {@@ -373,7 +677,7 @@ test("captures path screenshots through an existing base URL without preview", acaptureScreenshot,});- await handlers.captureScreenshot(+ const result = await handlers.captureScreenshot({baseUrl: "http://127.0.0.1:5177",path: "/design-system",@@ -391,6 +695,7 @@ test("captures path screenshots through an existing base URL without preview", aexpect(preview.resolveUrl).not.toHaveBeenCalled();expect(preparePreview).not.toHaveBeenCalled();expect(events).toEqual(["capture:http://127.0.0.1:5177/design-system"]);+ expect(result).not.toHaveProperty("previewMode");expect(progress).toEqual(["tool screenshot capturing http://127.0.0.1:5177/design-system",]);@@ -427,12 +732,20 @@ test("rejects authenticated Builder URLs as generated preview targets", async ()test("captures path screenshots through an explicit preview target", async () => {const events: string[] = [];const preview = {- status: vi.fn(() => ({ url: "http://127.0.0.1:5173/", running: true })),+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "production" as const,+ })),startAndWait: vi.fn(async (options) => {events.push(`start:${options.cwd}:${options.host}:${options.port}:${options.restart}`);- return { url: "http://127.0.0.1:5175/", running: true };+ return {+ url: "http://127.0.0.1:5175/",+ running: true,+ mode: "iterative" as const,+ };}),resolveUrl: vi.fn((path: string) => {events.push(`resolve:${path}`);@@ -467,3 +780,243 @@ test("captures path screenshots through an explicit preview target", async () =>"capture:http://127.0.0.1:5175/design-system",]);});++test("refreshes stale iterative preview without restarting server or browser", async () => {+ const capture = vi.fn(async () => ({+ output: "current.png",+ browser: {+ browser: "chromium" as const,+ path: "/browser",+ source: "path" as const,+ },+ viewport: { width: 1280, height: 720 },+ fullPage: false,+ elapsedMs: 1,+ warnings: [],+ }));+ const close = vi.fn(async () => undefined);+ const createCaptureSession = vi.fn(() => ({+ capture,+ capturePage: vi.fn(),+ close,+ }));+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ canReuse: vi.fn(() => true),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ };+ const preparePreview = vi.fn(async () => ({ cwd: "/tmp/preview" }));+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => true,+ preparePreview,+ createCaptureSession: createCaptureSession as never,+ });++ await handlers.captureScreenshot({+ path: "/",+ imageDomains: ["images.example.com"],+ viewport: { width: 1280, height: 720 },+ });++ expect(preparePreview).toHaveBeenCalledWith("session", undefined, {+ preserveGeneratedProject: true,+ prepareForIncrementalGeneration: true,+ });+ expect(preview.startAndWait).toHaveBeenCalledWith(+ expect.objectContaining({+ imageDomains: ["images.example.com"],+ mode: "iterative",+ restart: false,+ })+ );+ expect(preview.canReuse).toHaveBeenCalledWith({+ host: undefined,+ port: undefined,+ imageDomains: ["images.example.com"],+ mode: "iterative",+ });+ expect(createCaptureSession).toHaveBeenCalledOnce();+ expect(close).not.toHaveBeenCalled();+});++test.each([+ ["local", "session"],+ ["session", "local"],+] as const)(+ "refreshes iterative preview when source changes from %s to %s",+ async (initialSource, nextSource) => {+ let running = false;+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(async () => {+ running = true;+ return {+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ };+ }),+ canReuse: vi.fn(() => running),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ };+ const preparePreview = vi.fn(async () => ({ cwd: "/tmp/preview" }));+ const handlers = createMcpPreviewHandlers({+ preview,+ isStale: () => false,+ preparePreview,+ captureScreenshot: createCaptureScreenshotMock([]),+ });++ await handlers.startPreview({ source: initialSource });+ await handlers.captureScreenshot({+ path: "/",+ source: nextSource,+ viewport: { width: 1280, height: 720 },+ });++ expect(preparePreview).toHaveBeenNthCalledWith(2, nextSource, undefined, {+ preserveGeneratedProject: true,+ prepareForIncrementalGeneration: true,+ });+ expect(preview.startAndWait).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({ restart: false })+ );+ }+);++test("restarts production preview instead of incrementally reusing it", async () => {+ const preview = {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "production" as const,+ })),+ startAndWait: vi.fn(async () => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "production" as const,+ })),+ resolveUrl: vi.fn(),+ };+ const preparePreview = vi.fn(async () => ({ cwd: "/tmp/preview" }));+ const handlers = createMcpPreviewHandlers({ preview, preparePreview });++ await handlers.startPreview({ mode: "production" });++ expect(preparePreview).toHaveBeenCalledWith("session", undefined, {+ preserveGeneratedProject: false,+ prepareForIncrementalGeneration: false,+ });+ expect(preview.startAndWait).toHaveBeenCalledWith(+ expect.objectContaining({ mode: "production", restart: true })+ );+});++test("rejects a generated route that rendered Builder chrome", async () => {+ const handlers = createMcpPreviewHandlers({+ preview: {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ },+ isStale: () => false,+ captureScreenshot: vi.fn(async () => ({+ output: "builder.png",+ browser: {+ browser: "chromium" as const,+ path: "/browser",+ source: "path" as const,+ },+ viewport: { width: 1280, height: 720 },+ fullPage: false,+ elapsedMs: 1,+ warnings: [],+ navigation: {+ requestedUrl: "http://127.0.0.1:5173/",+ finalUrl: "http://127.0.0.1:5173/",+ redirects: [],+ documentReadyState: "complete",+ generatedSiteRootPresent: false,+ layoutStable: true,+ },+ })),+ });++ await expect(+ handlers.captureScreenshot({+ path: "/",+ viewport: { width: 1280, height: 720 },+ })+ ).rejects.toMatchObject({ code: "SCREENSHOT_NOT_GENERATED_SITE" });+});++test("rejects resized generated routes that rendered Builder chrome", async () => {+ const capturePage = vi.fn(async () => [+ {+ output: "builder.png",+ browser: {+ browser: "chromium" as const,+ path: "/browser",+ source: "path" as const,+ },+ viewport: { width: 1280, height: 720 },+ fullPage: false,+ elapsedMs: 1,+ warnings: [],+ navigation: {+ requestedUrl: "http://127.0.0.1:5173/",+ finalUrl: "http://127.0.0.1:5173/",+ redirects: [],+ documentReadyState: "complete",+ generatedSiteRootPresent: false,+ layoutStable: true,+ },+ },+ ]);+ const handlers = createMcpPreviewHandlers({+ preview: {+ status: vi.fn(() => ({+ url: "http://127.0.0.1:5173/",+ running: true,+ mode: "iterative" as const,+ })),+ startAndWait: vi.fn(),+ resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),+ },+ isStale: () => false,+ createCaptureSession: vi.fn(() => ({+ capture: vi.fn(),+ capturePage,+ close: vi.fn(),+ })) as never,+ });++ await expect(+ handlers.capturePageScreenshots([+ {+ path: "/",+ source: "session",+ viewport: { width: 1280, height: 720 },+ },+ ])+ ).rejects.toMatchObject({ code: "SCREENSHOT_NOT_GENERATED_SITE" });+});diff --git a/packages/cli/src/commands/mcp-preview.ts b/packages/cli/src/commands/mcp-preview.tsindex f416583856..1013b5ed74 100644--- a/packages/cli/src/commands/mcp-preview.ts+++ b/packages/cli/src/commands/mcp-preview.ts@@ -1,9 +1,14 @@-import { createPreviewController } from "../preview-server";+import {+ arePreviewImageDomainsEqual,+ createPreviewController,+ type PreviewMode,+} from "../preview-server";import {captureScreenshotWithBrowserInstall,createScreenshotCaptureSession,} from "../screenshot";import { inspectGeneratedBuildMetrics } from "../generated-build-metrics";+import { createExclusiveAsyncRunner } from "../async-utils";import {preparePreviewProject,previewDefaultTemplate,@@ -15,13 +20,16 @@ type McpPreviewController = Pick<ReturnType<typeof createPreviewController>,"startAndWait" | "status" | "resolveUrl"> &- Partial<Pick<ReturnType<typeof createPreviewController>, "stop">>;+ Partial<+ Pick<ReturnType<typeof createPreviewController>, "canReuse" | "stop">+ >;type McpPreviewInput = {host?: string;port?: number;source?: PreviewSource;imageDomains?: string[];+ mode?: PreviewMode;};type CaptureScreenshotInput = Parameters<@@ -48,6 +56,7 @@ type McpScreenshotInput = {waitForTimeout?: number;timeout?: number;source?: PreviewSource;+ mode?: PreviewMode;format?: "png" | "jpeg" | "webp";quality?: number;scale?: number;@@ -57,9 +66,72 @@ type McpToolProgress = {report: (message: string) => void;};+export const createPreviewFreshness = () => {+ let revision = 0;+ let freshRevision = -1;+ return {+ markStale() {+ revision += 1;+ },+ isStale: () => freshRevision !== revision,+ capture: () => revision,+ markFresh(capturedRevision: number) {+ if (capturedRevision === revision) {+ freshRevision = revision;+ }+ },+ };+};++type CaptureSessionConfig = Pick<+ CaptureScreenshotInput,+ "browser" | "browserPath"+>;++const getCaptureSessionConfig = (+ input: McpScreenshotInput+): CaptureSessionConfig => ({+ browser: input.browser ?? "auto",+ browserPath: input.browserPath,+});++const isSameCaptureSessionConfig = (+ left: CaptureSessionConfig,+ right: CaptureSessionConfig+) => left.browser === right.browser && left.browserPath === right.browserPath;++const defaultPreviewSource = "session" satisfies PreviewSource;+const getPreviewSource = (source: PreviewSource | undefined): PreviewSource =>+ source ?? defaultPreviewSource;++const getPreviewTarget = (input: McpPreviewInput) => ({+ source: getPreviewSource(input.source),+ mode: input.mode ?? "iterative",+ host: input.host ?? "127.0.0.1",+ port: input.port ?? 5173,+ imageDomains: input.imageDomains,+});++const isSamePreviewTarget = (+ left: ReturnType<typeof getPreviewTarget>,+ right: ReturnType<typeof getPreviewTarget>+) =>+ left.source === right.source &&+ left.mode === right.mode &&+ left.host === right.host &&+ left.port === right.port &&+ arePreviewImageDomainsEqual(left.imageDomains, right.imageDomains);+const prepareDefaultPreviewProject = (- source: PreviewSource = "local",- prepareSessionDataFile?: () => Promise<void>+ source: PreviewSource = defaultPreviewSource,+ prepareSessionDataFile?: () => Promise<void>,+ {+ preserveGeneratedProject = false,+ prepareForIncrementalGeneration = false,+ }: {+ preserveGeneratedProject?: boolean;+ prepareForIncrementalGeneration?: boolean;+ } = {}) =>preparePreviewProject({assets: true,@@ -70,11 +142,14 @@ const prepareDefaultPreviewProject = (silent: true,includeDraftPages: true,prepareSessionDataFile,+ preserveGeneratedProject,+ prepareForIncrementalGeneration,});export const createMcpPreviewHandlers = ({preview,isStale = () => true,+ captureFreshness = () => 0,markFresh = () => undefined,preparePreview = prepareDefaultPreviewProject,prepareSessionDataFile,@@ -83,7 +158,8 @@ export const createMcpPreviewHandlers = ({}: {preview: McpPreviewController;isStale?: () => boolean;- markFresh?: () => void;+ captureFreshness?: () => number;+ markFresh?: (freshness: number) => void;preparePreview?: typeof prepareDefaultPreviewProject;prepareSessionDataFile?: () => Promise<void>;captureScreenshot?: typeof captureScreenshotWithBrowserInstall;@@ -92,12 +168,50 @@ export const createMcpPreviewHandlers = ({let captureSession:| ReturnType<typeof createScreenshotCaptureSession>| undefined;+ let captureSessionConfig: CaptureSessionConfig | undefined;+ let activeSource: PreviewSource | undefined;+ const runPreviewLifecycle = createExclusiveAsyncRunner();const closeCaptureSession = async () => {try {await captureSession?.close();} finally {captureSession = undefined;+ captureSessionConfig = undefined;+ }+ };+ const getCaptureSession = async (input: McpScreenshotInput) => {+ if (createCaptureSession === undefined) {+ throw new Error("Reusable screenshot capture is unavailable.");}+ const nextConfig = getCaptureSessionConfig(input);+ if (+ captureSessionConfig !== undefined &&+ isSameCaptureSessionConfig(captureSessionConfig, nextConfig) === false+ ) {+ await closeCaptureSession();+ }+ captureSession ??= createCaptureSession();+ captureSessionConfig = nextConfig;+ return captureSession;+ };+ const isPreviewTargetCompatible = (+ input: McpPreviewInput,+ mode: PreviewMode,+ status: ReturnType<McpPreviewController["status"]>+ ) => {+ return (+ preview.canReuse?.({+ host: input.host,+ port: input.port,+ imageDomains: input.imageDomains,+ mode,+ }) ??+ (status.running &&+ status.mode === mode &&+ input.host === undefined &&+ input.port === undefined &&+ input.imageDomains === undefined)+ );};const rejectBuilderUrl = (value: string) => {let url: URL;@@ -110,14 +224,10 @@ export const createMcpPreviewHandlers = ({url.hostname.startsWith("p-") &&(url.hostname.endsWith(".wstd.dev") ||url.hostname.endsWith(".apps.webstudio.is"));- if (- isProjectHost &&- url.searchParams.has("authToken") &&- url.searchParams.has("mode")- ) {+ if (isProjectHost) {throw Object.assign(new Error(- "This is an authenticated Builder/share URL, not a generated-site preview. Use the share URL with webstudio init --link, then capture a generated route with screenshot { path }, or pass an intentional standalone site URL without Builder authentication parameters."+ 'This is a Webstudio Builder/share URL, not a generated site. Link the project with webstudio init --link, then capture only the generated site with screenshot { path: "/" }. Do not screenshot the Builder UI.'),{ code: "BUILDER_URL_IS_NOT_SITE_PREVIEW" });@@ -138,34 +248,53 @@ export const createMcpPreviewHandlers = ({rejectBuilderUrl(input.baseUrl);return new URL(input.path, input.baseUrl).toString();}- const hasExplicitPreviewTarget =- input.host !== undefined || input.port !== undefined;+ const mode = input.mode ?? "iterative";+ const source = getPreviewSource(input.source);+ const previewStatus = preview.status();+ const targetCompatible = isPreviewTargetCompatible(+ input,+ mode,+ previewStatus+ );if (- preview.status().running === false ||- isStale() ||- hasExplicitPreviewTarget+ previewStatus.running === false ||+ targetCompatible === false ||+ (activeSource !== undefined && activeSource !== source) ||+ isStale()) {- await closeCaptureSession();+ const canReusePreview = mode === "iterative" && targetCompatible;+ if (canReusePreview === false) {+ await closeCaptureSession();+ }validatePreviewServerOptions({host: input.host ?? "127.0.0.1",port: input.port ?? 5173,imageDomains: input.imageDomains,});progress?.report("tool screenshot preparing generated preview project");+ const freshness = captureFreshness();const previewProject = await preparePreview(- input.source,- prepareSessionDataFile+ source,+ prepareSessionDataFile,+ {+ preserveGeneratedProject: canReusePreview && mode === "iterative",+ prepareForIncrementalGeneration: mode === "iterative",+ }+ );+ progress?.report(+ `tool screenshot ${canReusePreview ? "refreshing" : "starting"} ${mode} preview server`);- progress?.report("tool screenshot starting production preview server");await preview.startAndWait({cwd: previewProject.cwd,buildCacheKey: previewProject.buildCacheKey,host: input.host,port: input.port,imageDomains: input.imageDomains,- restart: true,+ mode,+ restart: canReusePreview === false,});- markFresh();+ activeSource = source;+ markFresh(freshness);}return preview.resolveUrl(input.path);};@@ -188,119 +317,212 @@ export const createMcpPreviewHandlers = ({quality: input.quality,scale: input.scale,});+ const assertGeneratedSiteCapture = (+ input: McpScreenshotInput,+ result: Awaited<ReturnType<typeof captureScreenshot>>+ ) => {+ if (+ input.path !== undefined &&+ input.baseUrl === undefined &&+ result.navigation?.generatedSiteRootPresent === false+ ) {+ throw Object.assign(+ new Error(+ 'Screenshot did not render the generated Webstudio site. Capture the route with screenshot { path: "/" }; do not capture the Builder UI.'+ ),+ { code: "SCREENSHOT_NOT_GENERATED_SITE" }+ );+ }+ return result;+ };return {async startPreview(input: McpPreviewInput, progress?: McpToolProgress) {- await closeCaptureSession();- validatePreviewServerOptions({- host: input.host ?? "127.0.0.1",- port: input.port ?? 5173,- imageDomains: input.imageDomains,- });- progress?.report(- "tool preview.start preparing generated preview project"- );- const previewProject = await preparePreview(- input.source,- prepareSessionDataFile- );- progress?.report("tool preview.start starting production preview server");- const result = await preview.startAndWait({- ...input,- cwd: previewProject.cwd,- buildCacheKey: previewProject.buildCacheKey,- restart: true,+ return await runPreviewLifecycle(async () => {+ const mode = input.mode ?? "iterative";+ const source = getPreviewSource(input.source);+ const canReusePreview =+ mode === "iterative" &&+ isPreviewTargetCompatible(input, mode, preview.status());+ if (canReusePreview === false) {+ await closeCaptureSession();+ }+ validatePreviewServerOptions({+ host: input.host ?? "127.0.0.1",+ port: input.port ?? 5173,+ imageDomains: input.imageDomains,+ });+ progress?.report(+ "tool preview.start preparing generated preview project"+ );+ const freshness = captureFreshness();+ const previewProject = await preparePreview(+ source,+ prepareSessionDataFile,+ {+ preserveGeneratedProject: canReusePreview && mode === "iterative",+ prepareForIncrementalGeneration: mode === "iterative",+ }+ );+ progress?.report(+ `tool preview.start ${canReusePreview ? "refreshing" : "starting"} ${mode} preview server`+ );+ const result = await preview.startAndWait({+ ...input,+ mode,+ cwd: previewProject.cwd,+ buildCacheKey: previewProject.buildCacheKey,+ restart: canReusePreview === false,+ });+ activeSource = source;+ markFresh(freshness);+ return {+ ...result,+ ...(mode === "production"+ ? {+ generatedBuildMetrics: await inspectGeneratedBuildMetrics(+ previewProject.cwd+ ),+ }+ : {}),+ };});- markFresh();- return {- ...result,- generatedBuildMetrics: await inspectGeneratedBuildMetrics(- previewProject.cwd- ),- };},async captureScreenshot(input: McpScreenshotInput,progress?: McpToolProgress) {- const url = await resolveScreenshotUrl(input, progress);- progress?.report(`tool screenshot capturing ${url}`);- const captureOptions = getCaptureOptions(input, url);- if (input.source === "session" && createCaptureSession !== undefined) {- captureSession ??= createCaptureSession();- return await captureSession.capture(captureOptions);- }- return await captureScreenshot({- ...captureOptions,- isJson: false,- isMcp: true,- isInteractive: false,- confirmInstall: async () => false,+ return await runPreviewLifecycle(async () => {+ const startedAt = Date.now();+ const url = await resolveScreenshotUrl(input, progress);+ const previewReadyAt = Date.now();+ progress?.report(`tool screenshot capturing ${url}`);+ const captureOptions = getCaptureOptions(input, url);+ let result: Awaited<ReturnType<typeof captureScreenshot>>;+ if (+ getPreviewSource(input.source) !== "local" &&+ createCaptureSession !== undefined+ ) {+ result = await (+ await getCaptureSession(input)+ ).capture(captureOptions);+ } else {+ result = await captureScreenshot({+ ...captureOptions,+ isJson: false,+ isMcp: true,+ isInteractive: false,+ confirmInstall: async () => false,+ });+ }+ const completedAt = Date.now();+ return {+ ...assertGeneratedSiteCapture(input, result),+ ...(input.path !== undefined && input.baseUrl === undefined+ ? { previewMode: preview.status().mode }+ : {}),+ lifecycleTimings: {+ previewRefreshMs: previewReadyAt - startedAt,+ captureMs: completedAt - previewReadyAt,+ totalMs: completedAt - startedAt,+ },+ };});},async capturePageScreenshots(inputs: readonly McpScreenshotInput[],progress?: McpToolProgress) {- const firstInput = inputs[0];- if (firstInput === undefined) {- return [];- }- if (- createCaptureSession === undefined ||- firstInput.source !== "session" ||- inputs.some((input) => input.source !== firstInput.source)- ) {- throw new Error(- "Resized screenshot capture requires session preview pages."+ return await runPreviewLifecycle(async () => {+ const firstInput = inputs[0];+ if (firstInput === undefined) {+ return [];+ }+ const previewTarget = getPreviewTarget(firstInput);+ if (+ createCaptureSession === undefined ||+ previewTarget.source === "local" ||+ inputs.some(+ (input) =>+ isSamePreviewTarget(getPreviewTarget(input), previewTarget) ===+ false ||+ isSameCaptureSessionConfig(+ getCaptureSessionConfig(input),+ getCaptureSessionConfig(firstInput)+ ) === false+ )+ ) {+ throw new Error(+ "Resized screenshot capture requires one session preview target and browser configuration."+ );+ }+ const urls: string[] = [];+ for (const input of inputs) {+ urls.push(await resolveScreenshotUrl(input, progress));+ }+ progress?.report(+ `tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`);- }- const urls: string[] = [];- for (const input of inputs) {- urls.push(await resolveScreenshotUrl(input, progress));- }- progress?.report(- `tool screenshot capturing ${new Set(urls).size} pages across ${inputs.length} viewport widths`- );- captureSession ??= createCaptureSession();- return await captureSession.capturePage(- inputs.map((input, index) => {- const url = urls[index];- if (url === undefined) {- throw new Error("Screenshot URL resolution was incomplete.");+ const results = await (+ await getCaptureSession(firstInput)+ ).capturePage(+ inputs.map((input, index) => {+ const url = urls[index];+ if (url === undefined) {+ throw new Error("Screenshot URL resolution was incomplete.");+ }+ return getCaptureOptions(input, url);+ })+ );+ return results.map((result, index) => {+ const input = inputs[index];+ if (input === undefined) {+ throw new Error("Screenshot input was omitted from the batch.");}- return getCaptureOptions(input, url);- })- );+ return {+ ...assertGeneratedSiteCapture(input, result),+ ...(input.path !== undefined && input.baseUrl === undefined+ ? { previewMode: preview.status().mode }+ : {}),+ };+ });+ });},async stopPreview() {- const errors: unknown[] = [];- try {- await closeCaptureSession();- } catch (error) {- errors.push(error);- }- let result;- try {- if (preview.stop === undefined) {- throw new Error("Preview controller cannot stop its owned preview.");+ return await runPreviewLifecycle(async () => {+ const errors: unknown[] = [];+ try {+ await closeCaptureSession();+ } catch (error) {+ errors.push(error);}- result = await preview.stop();- } catch (error) {- errors.push(error);- }- if (errors.length === 1) {- throw errors[0];- }- if (errors.length > 1) {- throw new AggregateError(- errors,- "Could not clean up screenshot capture or stop the owned preview."- );- }- if (result === undefined) {- throw new Error("Preview controller did not return its stopped state.");- }- return result;+ let result;+ try {+ if (preview.stop === undefined) {+ throw new Error(+ "Preview controller cannot stop its owned preview."+ );+ }+ result = await preview.stop();+ activeSource = undefined;+ } catch (error) {+ errors.push(error);+ }+ if (errors.length === 1) {+ throw errors[0];+ }+ if (errors.length > 1) {+ throw new AggregateError(+ errors,+ "Could not clean up screenshot capture or stop the owned preview."+ );+ }+ if (result === undefined) {+ throw new Error(+ "Preview controller did not return its stopped state."+ );+ }+ return result;+ });},};};diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex 5fd95f21bb..f881fcfc18 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -70,7 +70,10 @@ import {} from "./mcp-batch";import { apiCompatibilityHeaders } from "./api";import { importProject as importProjectCommand } from "./import";-import { createMcpPreviewHandlers } from "./mcp-preview";+import {+ createMcpPreviewHandlers,+ createPreviewFreshness,+} from "./mcp-preview";import type {CommonYargsArgv,StrictYargsOptionsToInterface,@@ -861,17 +864,13 @@ const createCliMcpHost = async ({);await prepareMcpProjectSession(session);const preview = createPreviewController({ host: "127.0.0.1", port: 5173 });- let isPreviewStale = true;- const markPreviewStale = () => {- isPreviewStale = true;- };+ const previewFreshness = createPreviewFreshness();const previewHandlers = createMcpPreviewHandlers({preview,createCaptureSession: createScreenshotCaptureSession,- isStale: () => isPreviewStale,- markFresh: () => {- isPreviewStale = false;- },+ isStale: previewFreshness.isStale,+ captureFreshness: previewFreshness.capture,+ markFresh: previewFreshness.markFresh,prepareSessionDataFile: async () => {await writeCliProjectSessionDataFile(getLoadedProjectSessionSnapshot(session),@@ -880,23 +879,39 @@ const createCliMcpHost = async ({);},});+ type ScreenshotResult = Awaited<+ ReturnType<typeof previewHandlers.captureScreenshot>+ >;+ type ResizedScreenshotResult = Awaited<+ ReturnType<typeof previewHandlers.capturePageScreenshots>+ >[number];const toProjectSessionScreenshotResult = (- result: Awaited<ReturnType<typeof previewHandlers.captureScreenshot>>- ) => ({- output: result.output,- browserPath: result.browser.path,- browser: result.browser.browser,- viewport: result.viewport,- fullPage: result.fullPage,- elapsedMs: result.elapsedMs,- warnings: result.warnings,- navigation: result.navigation,- layout: result.layout,- timings: result.timings,- });+ result: ScreenshotResult | ResizedScreenshotResult+ ) => {+ const navigation = result.navigation ?? result.layout?.navigation;+ return {+ output: result.output,+ browserPath: result.browser.path,+ browser: result.browser.browser,+ viewport: result.viewport,+ fullPage: result.fullPage,+ elapsedMs: result.elapsedMs,+ warnings: result.warnings,+ previewMode: result.previewMode,+ renderedProjectId: navigation?.projectId,+ renderedProjectVersion: navigation?.projectVersion,+ ...("lifecycleTimings" in result+ ? { lifecycleTimings: result.lifecycleTimings }+ : {}),+ navigation: result.navigation,+ layout: result.layout,+ timings: result.timings,+ };+ };const host: CliMcpHost = {operations,createProjectSession: () => session,+ onProjectSessionChange: previewFreshness.markStale,executeOperation: async ({ command, input, dryRun }) => {const result = await executeProjectSessionApiOperation({command,@@ -906,7 +921,7 @@ const createCliMcpHost = async ({dryRun,});if (dryRun !== true && shouldInvalidatePreview(command)) {- markPreviewStale();+ previewFreshness.markStale();}return result;},@@ -930,7 +945,11 @@ const createCliMcpHost = async ({code: "NOT_FOUND",});}- return await session.restoreSnapshot(restorePoint, { dryRun });+ const result = await session.restoreSnapshot(restorePoint, { dryRun });+ if (dryRun !== true) {+ previewFreshness.markStale();+ }+ return result;},},async importProject(input) {@@ -961,7 +980,7 @@ const createCliMcpHost = async ({}throw error;}- markPreviewStale();+ previewFreshness.markStale();return { imported: true as const };},async downloadAsset(input) {diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.tsindex 1dffb05ea0..e5d62e53b5 100644--- a/packages/cli/src/commands/preview.test.ts+++ b/packages/cli/src/commands/preview.test.ts@@ -17,6 +17,7 @@ import {previewOptions,} from "./preview";import type { CommonYargsArgv } from "./yargs-types";+import { generatedFilesManifest } from "../prebuild";test("rejects empty preview host", async () => {await expect(@@ -300,6 +301,45 @@ test("revalidates dependencies when reusing a cached preview build", async () =>expect(prebuildProject).not.toHaveBeenCalled();});+test("regenerates a production cache before using it for iterative preview", async () => {+ const previousDirectory = cwd();+ const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);+ const previewProjectDir = join(projectDir, ".webstudio", "preview");+ const prebuildProject = vi.fn(async () => undefined);++ await mkdir(join(projectDir, ".webstudio"), { recursive: true });+ await mkdir(previewProjectDir, { recursive: true });+ await writeFile(join(projectDir, ".webstudio", "data.json"), "{}");+ await writeFile(join(projectDir, ".webstudio", "config.json"), "{}");+ await writeFile(+ join(previewProjectDir, ".webstudio-preview-build"),+ "cache-key"+ );+ chdir(projectDir);+ try {+ const result = await preparePreviewProject({+ assets: true,+ template: [],+ generate: true,+ prepareForIncrementalGeneration: true,+ prebuildProject,+ ensureDependencies: vi.fn(async () => undefined),+ getBuildCacheKey: vi.fn(async () => "cache-key"),+ });++ expect(result.buildRequired).toBe(true);+ } finally {+ chdir(previousDirectory);+ await rm(projectDir, { recursive: true, force: true });+ }++ expect(prebuildProject).toHaveBeenCalledWith({+ assets: true,+ template: ["defaults", "react-router"],+ preserveRouteTemplates: true,+ });+});+test("links local workspace preview dependencies without asking npm for placeholder versions", async () => {const symlink = vi.fn(async () => undefined);const cliNodeModules = getNodeModulesSearchPaths(import.meta.url).find(@@ -498,6 +538,42 @@ test("materializes session data before previewing from session source", async ()});});+test("refreshes an iterative generated project without replacing its directory", async () => {+ const previousDirectory = cwd();+ const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);+ const previewProjectDir = join(projectDir, ".webstudio", "preview");+ const prebuildProject = vi.fn(async () => {+ await expect(+ readFile(join(previewProjectDir, "server-marker"), "utf8")+ ).resolves.toBe("running");+ });++ await mkdir(join(projectDir, ".webstudio"), { recursive: true });+ await mkdir(join(previewProjectDir, "app", "route-templates"), {+ recursive: true,+ });+ await mkdir(join(previewProjectDir, ".webstudio"), { recursive: true });+ await writeFile(join(projectDir, ".webstudio", "data.json"), "{}");+ await writeFile(join(previewProjectDir, "server-marker"), "running");+ await writeFile(join(previewProjectDir, generatedFilesManifest), "[]");+ chdir(projectDir);+ try {+ await preparePreviewProject({+ assets: true,+ template: [],+ generate: true,+ preserveGeneratedProject: true,+ prebuildProject,+ ensureDependencies: vi.fn(async () => undefined),+ });+ } finally {+ chdir(previousDirectory);+ await rm(projectDir, { recursive: true, force: true });+ }++ expect(prebuildProject).toHaveBeenCalledOnce();+});+test("uses current project directory when generation is disabled", async () => {const previousDirectory = cwd();const projectDir = join(tmpdir(), `webstudio-preview-test-${randomUUID()}`);diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsindex 230be9a2a5..fa4bdd5c0b 100644--- a/packages/cli/src/commands/preview.ts+++ b/packages/cli/src/commands/preview.ts@@ -18,7 +18,11 @@ import { chdir, cwd } from "node:process";import { promisify } from "node:util";import { log } from "@clack/prompts";import { builderNamespaces } from "@webstudio-is/project-build/contracts";-import { prebuild } from "../prebuild";+import {+ projectPreviewSources,+ type ProjectPreviewSource,+} from "@webstudio-is/project-build/visual";+import { generatedFilesManifest, prebuild } from "../prebuild";import { LOCAL_CONFIG_FILE, LOCAL_DATA_FILE } from "../config";import { HandledCliError } from "../errors";import {@@ -41,10 +45,11 @@ import {} from "../project-session";import { LOCAL_ASSETS_DIR } from "../asset-files";import packageJson from "../../package.json" with { type: "json" };+import { createExclusiveAsyncRunner } from "../async-utils";export const previewDefaultTemplate = ["defaults", "react-router"] as const;-export const previewSources = ["local", "session"] as const;-export type PreviewSource = (typeof previewSources)[number];+export const previewSources = projectPreviewSources;+export type PreviewSource = ProjectPreviewSource;const getPreviewTemplates = (template: string[]) => {const templates =@@ -305,33 +310,12 @@ const runInDirectory = async <Result>(}};-let runInDirectoryQueue = Promise.resolve();--const runExclusive = async <Result>(callback: () => Promise<Result>) => {- const previousRun = runInDirectoryQueue;- let releaseCurrentRun: () => void = () => undefined;- runInDirectoryQueue = new Promise((resolve) => {- releaseCurrentRun = resolve;- });- await previousRun.catch(() => undefined);- try {- return await callback();- } finally {- releaseCurrentRun();- }-};+const runExclusive = createExclusiveAsyncRunner();-const preparePreviewDirectory = async (projectDir: string) => {- const previewProjectDir = getPreviewProjectDir(projectDir);- await mkdir(previewProjectDir, { recursive: true });- const entries = await readdir(previewProjectDir);- await Promise.all(- entries- .filter((entry) => entry !== "node_modules")- .map((entry) =>- rm(join(previewProjectDir, entry), { recursive: true, force: true })- )- );+const copyPreviewProjectFiles = async (+ projectDir: string,+ previewProjectDir: string+) => {await mkdir(join(previewProjectDir, ".webstudio"), { recursive: true });for (const file of localPreviewFiles) {await copyFile(join(projectDir, file), join(previewProjectDir, file)).catch(@@ -347,6 +331,35 @@ const preparePreviewDirectory = async (projectDir: string) => {});}+};++const hasIncrementalGenerationInputs = async (previewProjectDir: string) => {+ return await Promise.all([+ access(join(previewProjectDir, "app", "route-templates")),+ access(join(previewProjectDir, generatedFilesManifest)),+ ]).then(+ () => true,+ () => false+ );+};++const preparePreviewDirectory = async (+ projectDir: string,+ preserveGeneratedProject: boolean+) => {+ const previewProjectDir = getPreviewProjectDir(projectDir);+ await mkdir(previewProjectDir, { recursive: true });+ if (preserveGeneratedProject === false) {+ const entries = await readdir(previewProjectDir);+ await Promise.all(+ entries+ .filter((entry) => entry !== "node_modules")+ .map((entry) =>+ rm(join(previewProjectDir, entry), { recursive: true, force: true })+ )+ );+ }+ await copyPreviewProjectFiles(projectDir, previewProjectDir);return previewProjectDir;};@@ -429,6 +442,8 @@ export const preparePreviewProject = async ({getBuildCacheKey = getPreviewBuildCacheKey,silent = false,includeDraftPages = false,+ preserveGeneratedProject = false,+ prepareForIncrementalGeneration = false,prepareSessionDataFile = async () => {const connection = await resolveApiConnection();const session = createCliProjectSession({ connection });@@ -451,6 +466,8 @@ export const preparePreviewProject = async ({getBuildCacheKey?: typeof getPreviewBuildCacheKey;silent?: boolean;includeDraftPages?: boolean;+ preserveGeneratedProject?: boolean;+ prepareForIncrementalGeneration?: boolean;prepareSessionDataFile?: () => Promise<void>;}): Promise<{cwd: string;@@ -495,12 +512,16 @@ export const preparePreviewProject = async ({template,includeDraftPages,});+ const hasIncrementalInputs =+ await hasIncrementalGenerationInputs(previewProjectDir);+ const canReuseCachedProject =+ prepareForIncrementalGeneration === false || hasIncrementalInputs;if (buildCacheKey !== undefined) {const cachedBuildKey = await readFile(join(previewProjectDir, previewBuildCacheMarker),"utf8").catch(() => undefined);- if (cachedBuildKey === buildCacheKey) {+ if (cachedBuildKey === buildCacheKey && canReuseCachedProject) {await ensureDependencies(previewProjectDir);return { cwd: previewProjectDir, buildCacheKey, buildRequired: false };}@@ -508,13 +529,19 @@ export const preparePreviewProject = async ({if (generate) {await runExclusive(async () => {- await preparePreviewDirectory(projectDir);+ const reuseGeneratedProject =+ preserveGeneratedProject && hasIncrementalInputs;+ await preparePreviewDirectory(projectDir, reuseGeneratedProject);await runInDirectory(previewProjectDir, async () => {await prebuildProject({assets,template: getPreviewTemplates(template),...(silent ? { silent: true } : {}),...(includeDraftPages ? { includeDraftPages: true } : {}),+ ...(reuseGeneratedProject ? { incremental: true } : {}),+ ...(prepareForIncrementalGeneration+ ? { preserveRouteTemplates: true }+ : {}),});});await ensureDependencies(previewProjectDir);diff --git a/packages/cli/src/commands/screenshot.test.ts b/packages/cli/src/commands/screenshot.test.tsindex 065650bc7c..a5f10b8d73 100644--- a/packages/cli/src/commands/screenshot.test.ts+++ b/packages/cli/src/commands/screenshot.test.ts@@ -104,10 +104,12 @@ test("captures a project route through a temporary production preview", async ()startAndWait: vi.fn(async () => ({url: "http://127.0.0.1:5180/",running: true,+ mode: "production" as const,})),stop: vi.fn(async () => ({url: "http://127.0.0.1:5180/",running: false,+ mode: "production" as const,})),resolveUrl: vi.fn(() => "http://127.0.0.1:5180/pricing"),};@@ -165,10 +167,12 @@ test("fails a generated project route that returns an HTTP error", async () => {startAndWait: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "production" as const,})),stop: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: false,+ mode: "production" as const,})),resolveUrl: vi.fn(() => "http://127.0.0.1:5173/missing"),};@@ -227,10 +231,12 @@ test("stops the temporary preview when project route capture fails", async () =>startAndWait: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "production" as const,})),stop: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: false,+ mode: "production" as const,})),resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),};@@ -259,6 +265,7 @@ test("stops the temporary preview when startup fails", async () => {stop: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: false,+ mode: "production" as const,})),resolveUrl: vi.fn(() => "http://127.0.0.1:5173/"),};diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex bc3528abec..6d55c656a6 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,7 +2,7 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":200}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599 or a JavaScript expression string for a dynamic status.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n- MCP tool: update-asset {"assetId":"<fontAssetId>","values":{"meta":{"family":"Rajdhani","style":"normal","weight":600}}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n- Font metadata updates merge with the detected metadata and are validated before committing; use this to correct a family, style, or weight after upload.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":@@ -12,7 +12,7 @@ export const cliDocs = {"mcp-startup-epilogue":'If you are inside the Webstudio monorepo, use the local CLI exactly as `node packages/cli/local.js ...` as your first command path. Do not use `packages/cli/bin.js` for local source-tree work; it is the packaged build entry and may use stale built output.\n\nPlain `webstudio mcp` starts the stdio MCP server for real MCP clients. Do not manually type or pipe raw JSON-RPC frames into it from an interactive shell or PTY. From a shell, use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for one bounded tool call. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for small multi-call batches in one shared CLI session. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nPut each local CLI call in its own shell command; do not chain helper commands with `&&`, `;`, command substitution, or shell wrappers around the CLI when reporting a CLI step. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`; those can resolve an older binary. For example:\n\n```sh\nnode packages/cli/local.js mcp single-op-call meta.index\nnode packages/cli/local.js mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js mcp single-op-call insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":- '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder URL containing `authToken` and `mode` to `screenshot`; use `path` after\nstarting preview, or use `baseUrl` only for an intentional generated site that\nis already running.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',+ '# MCP Vision Verification\n\n## Generated App Dependency Notes\n\n- `preview.start` and `webstudio preview` install generated app dependencies under `.webstudio/preview` and reuse them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n\n## Visual Verification Rule\n\nFor visual/design work, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session before finishing and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.\n\nAn authenticated project share URL is used with `webstudio init --link`; it is\nnot a generated-site preview URL. Project screenshots and rendered audits use\nthe generated local preview owned by the current CLI/MCP process. Do not pass a\nBuilder/share URL to `screenshot`, even without query parameters. Use `path`\nafter starting preview, or use `baseUrl` only for an intentional generated site\nthat is already running. Path captures verify the generated-site root marker\nand fail instead of returning a screenshot of Builder chrome.\n\n## Vision Verification Loop\n\n- Make focused page/content/style changes with semantic MCP tools.\n- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.\n- {{dependency-notes}}\n- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.\n- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.\n- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- {{diff}} When a baseline PNG exists, call screenshot.diff with baselinePath, currentPath, and outputDir for each page/viewport pair. Add expectedText when a specific visible phrase must be present; its assertions report pass/fail plus found and missing text. Add expectedVisual to set pass/fail limits for mismatch percentage, the number of changed regions, or an overall dominant color/brightness direction.\n- {{diff}} Read screenshot.diff textAnalysis: it reports OCR status plus text that appeared, disappeared, moved, changed content, or changed font/style geometry. If OCR is unavailable, expectedText assertions fail and textAnalysis reports why; ask the user for permission to install Tesseract, then call vision.install-ocr with { "confirm": true }, or rely on visual inspection.\n- Inspect every viewport PNG and any diff artifacts with vision, then compare layout, OCR text evidence, color, spacing, imagery, and responsive framing against the user intent.\n- If the screenshot does not match, apply another focused mutation and repeat screenshot verification.\n\n## Workflow Summary With Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.\n\n## Workflow Summary Without Diff\n\nFor visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.\n\nEach screenshot result includes rendered `layout` metrics when the local browser\nprovides them. `layout.horizontalOverflow: true` is deterministic evidence that\nthe rendered document exceeds the requested viewport width. Use vision for\nclipping, wrapping, hierarchy, and other judgments that layout dimensions alone\ncannot establish.\n\nPass `includeImageMetrics: true` when an ordinary screenshot needs\n`layout.images`; rendered audit enables it automatically. The array includes\neach rendered image\'s Webstudio instance id when available, loading mode,\ncompletion state, natural dimensions, rendered dimensions, and document\nposition. Rendered audits use this evidence to report broken images, eager\nloading below the fold, and sources more than 2x the rendered dimensions in\nboth axes. Oversized-source results are optimization evidence, not universal\nperformance conformance.\n\nPass `includeResourceMetrics: true` when an ordinary screenshot needs sanitized\nResource Timing evidence; rendered audit enables it automatically. Resource\nmetrics contain only the URL pathname, initiator type, transfer/body sizes,\nduration, and browser-provided render-blocking status. Origins and query strings\nare omitted. Rendered audits report explicitly blocking resources and legacy\n`.ttf`, `.otf`, or `.woff` font files without applying a universal byte-size\nbudget.\n\n## Screenshot Verification Summary\n\nInside a long-running MCP server, call preview.start once, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.\n\n## Screenshot Diff Evidence\n\n- Pixel evidence: total mismatch, changed regions, dominant color/luminance direction, diffPath, and contextDiffPath.\n- OCR evidence: textAnalysis.status, provider, and changes for appeared/disappeared/content_changed/moved/font_changed text. expectedText adds pass/fail assertions plus found and missing current-screen text. expectedVisual adds pass/fail quantitative checks for mismatch percentage, changed-region count, and the overall dominant color/brightness direction.\n- OCR dependency: screenshot.diff uses the system tesseract binary when available. If missing, it returns ocr_unavailable_tesseract_not_found_or_failed and still returns pixel evidence.\n- OCR install: MCP cannot prompt. Ask the user first; if they agree, call vision.install-ocr with { "confirm": true }. If automatic install is unavailable, follow the returned installUrl.\n- Final judgment: OCR and pixel diff are evidence. A vision-capable model must still inspect screenshots/diff artifacts and compare the rendered result to user intent.\n',} as const;export const cliDocTitles = {diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex b2eab86f2c..c0895d054e 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -145,9 +145,9 @@ Commands:Notes:-- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.+- Use this after page/content/style mutations so a vision-capable AI can see the generated site from the current MCP session. Use `path`; never pass a Webstudio Builder/share URL or capture Builder chrome.- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.-- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.+- Iterative mode is the default: after MCP mutations, path screenshots ensure generated project files are current, wait for the exact session version, and perform an ordinary page reload without Vite HMR. The preview server and browser stay alive. Use `{"mode":"production"}` only for release-like verification; rendered audit does this automatically.- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process's preview controller.diff --git a/packages/cli/src/docs/mcp-vision.md b/packages/cli/src/docs/mcp-vision.mdindex ade20c5f01..2e879801ac 100644--- a/packages/cli/src/docs/mcp-vision.md+++ b/packages/cli/src/docs/mcp-vision.md@@ -8,21 +8,22 @@## Visual Verification Rule-For visual/design work, use preview.start and screenshot after generated project files are current so vision can inspect the rendered result before finishing. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.+For visual/design work, use `preview.start` and `screenshot({ path })` so vision can inspect the current MCP session before finishing and verify that generated project files are current. Iterative preview is the default: it keeps one generated-site server and browser alive, regenerates changed files, and performs an ordinary page reload without Vite HMR. Use `mode: "production"` only for release-like verification; rendered audit selects it automatically. `preview.start` is long-lived and cannot be used through one-shot `mcp single-op-call`; from a shell, use `webstudio mcp run` for preview.start/screenshot/preview.stop in one shared process, or use a long-running MCP server. When a baseline exists, use screenshot.diff to get pixel regions, OCR text changes, and diff PNG artifacts.An authenticated project share URL is used with `webstudio init --link`; it isnot a generated-site preview URL. Project screenshots and rendered audits usethe generated local preview owned by the current CLI/MCP process. Do not pass a-Builder URL containing `authToken` and `mode` to `screenshot`; use `path` after-starting preview, or use `baseUrl` only for an intentional generated site that-is already running.+Builder/share URL to `screenshot`, even without query parameters. Use `path`+after starting preview, or use `baseUrl` only for an intentional generated site+that is already running. Path captures verify the generated-site root marker+and fail instead of returning a screenshot of Builder chrome.## Vision Verification Loop- Make focused page/content/style changes with semantic MCP tools.-- Make sure generated project files are current, then call preview.start to build the app and keep the production-like generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.+- Call preview.start once to keep the iterative generated site running. In shell-driven workflows, run preview.start, screenshot, and preview.stop inside one `webstudio mcp run` call so they share the same preview owner.- {{dependency-notes}}-- After MCP mutations, path-based screenshots regenerate/restart preview as needed before capture; when preview is fresh in the same long-running MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview without starting or restarting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process's preview controller.+- After MCP mutations, path-based screenshots regenerate the current session in place, wait for its exact project version, and normally reload the route. The server and browser remain alive. From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running generated site without starting it. Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview; a separate one-shot `single-op-call` process does not own another process's preview controller.- For multi-page work, capture each changed page by path through the same preview server, for example screenshot({ path: "/" }), screenshot({ path: "/pricing" }), and screenshot({ path: "/about" }). The screenshot tool navigates directly to the requested route; no browser click navigation is required.- For responsive work, call list-breakpoints first, then capture screenshots at viewport widths based on the Builder breakpoints plus a narrow mobile and desktop width.- Call screenshot with { path: "/" } or the changed page path and viewport such as { width: 375, height: 812 } and { width: 1440, height: 900 }. For an existing preview in another process, call screenshot with { baseUrl: "http://127.0.0.1:5177", path: "/" }. Use waitForSelector when the page has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.@@ -33,11 +34,11 @@ is already running.## Workflow Summary With Diff-For visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing.+For visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Use screenshot.diff on each baseline/current page or viewport pair when a baseline exists, then inspect pixel regions, OCR textAnalysis, and PNG/diff artifacts with vision before finishing. Use mode: "production" only for release-like verification.## Workflow Summary Without Diff-For visual/design work, make sure generated project files are current, call preview.start to build and start the production-like preview server, then screenshot({ path, viewport }) for every changed page path; for responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths; inspect every PNG with vision before finishing.+For visual/design work, call preview.start once to start the iterative generated-site preview, then screenshot({ path, viewport }) after each focused mutation; path screenshots regenerate changed files and reload the route in the existing server and browser. For responsive work, use list-breakpoints and capture each changed page at Builder breakpoint widths plus mobile and desktop widths. Inspect every PNG with vision before finishing. Use mode: "production" only for release-like verification.Each screenshot result includes rendered `layout` metrics when the local browserprovides them. `layout.horizontalOverflow: true` is deterministic evidence that@@ -64,7 +65,7 @@ budget.## Screenshot Verification Summary-Inside a long-running MCP server, prefer preview.start plus screenshot({ path, viewport }) after generated project files are current, so a fresh production-like preview server is available for fast repeated checks across multiple pages. After MCP mutations, path screenshots restart preview as needed before capture; when preview is fresh in that same MCP server, repeated path screenshots reuse the running server. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.+Inside a long-running MCP server, call preview.start once, then use screenshot({ path, viewport }) for fast repeated checks across multiple pages. Iterative mode is the default: after MCP mutations, path screenshots regenerate changed files and reload the requested route while keeping the server and browser alive. Use mode: "production" only for release-like verification. From one-shot shell calls or another process, use screenshot({ baseUrl, path, viewport }) to capture an already-running preview/site without generating, building, starting, or restarting preview. Use path values such as "/", "/pricing", or "/about" to capture specific generated routes. For responsive work, read list-breakpoints and capture one familiar device viewport inside each Builder breakpoint range before using vision. Screenshot waits for load by default, then fonts and two layout frames; pass waitForSelector for app readiness, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout for final settling. When a baseline exists, use screenshot.diff for changed regions, OCR textAnalysis, and diff artifacts on each baseline/current screenshot pair. Outside MCP, use `webstudio screenshot --path /pricing --output pricing.png` for one temporary generated preview capture, or keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot` for repeated captures.## Screenshot Diff Evidencediff --git a/packages/cli/src/framework-react-router.ts b/packages/cli/src/framework-react-router.tsindex 2872d9414f..e00a04486f 100644--- a/packages/cli/src/framework-react-router.ts+++ b/packages/cli/src/framework-react-router.ts@@ -1,34 +1,39 @@import { join } from "node:path";-import { readFile, rm } from "node:fs/promises";+import { readFile } from "node:fs/promises";import { generateRemixRoute } from "@webstudio-is/react-sdk";import {baseComponentImportSource,createFrameworkComponentRegistry,} from "@webstudio-is/sdk-components-registry/framework";import * as reactRouterComponents from "@webstudio-is/sdk-components-react-router";-import type { Framework } from "./framework";--export const createFramework = async (): Promise<Framework> => {- const routeTemplatesDir = join("app", "route-templates");+import {+ cleanupFrameworkTemplates,+ routeTemplatesDirectory,+ type Framework,+ type FrameworkOptions,+} from "./framework";+export const createFramework = async (+ options: FrameworkOptions = {}+): Promise<Framework> => {const htmlTemplate = await readFile(- join(routeTemplatesDir, "html.tsx"),+ join(routeTemplatesDirectory, "html.tsx"),"utf8");const xmlTemplate = await readFile(- join(routeTemplatesDir, "xml.tsx"),+ join(routeTemplatesDirectory, "xml.tsx"),"utf8");const textTemplate = await readFile(- join(routeTemplatesDir, "text.tsx"),+ join(routeTemplatesDirectory, "text.tsx"),"utf8");const defaultSitemapTemplate = await readFile(- join(routeTemplatesDir, "default-sitemap.tsx"),+ join(routeTemplatesDirectory, "default-sitemap.tsx"),"utf8");// cleanup route templates after reading to not bloat generated code- await rm(routeTemplatesDir, { recursive: true, force: true });+ await cleanupFrameworkTemplates(options);const reactRouter = "@webstudio-is/sdk-components-react-router";const { components, metas } = createFrameworkComponentRegistry({diff --git a/packages/cli/src/framework-remix.ts b/packages/cli/src/framework-remix.tsindex bfea4e1287..5eaca7b20d 100644--- a/packages/cli/src/framework-remix.ts+++ b/packages/cli/src/framework-remix.ts@@ -1,34 +1,39 @@import { join } from "node:path";-import { readFile, rm } from "node:fs/promises";+import { readFile } from "node:fs/promises";import { generateRemixRoute } from "@webstudio-is/react-sdk";import {baseComponentImportSource,createFrameworkComponentRegistry,} from "@webstudio-is/sdk-components-registry/framework";import * as remixComponents from "@webstudio-is/sdk-components-react-remix";-import type { Framework } from "./framework";--export const createFramework = async (): Promise<Framework> => {- const routeTemplatesDir = join("app", "route-templates");+import {+ cleanupFrameworkTemplates,+ routeTemplatesDirectory,+ type Framework,+ type FrameworkOptions,+} from "./framework";+export const createFramework = async (+ options: FrameworkOptions = {}+): Promise<Framework> => {const htmlTemplate = await readFile(- join(routeTemplatesDir, "html.tsx"),+ join(routeTemplatesDirectory, "html.tsx"),"utf8");const xmlTemplate = await readFile(- join(routeTemplatesDir, "xml.tsx"),+ join(routeTemplatesDirectory, "xml.tsx"),"utf8");const textTemplate = await readFile(- join(routeTemplatesDir, "text.tsx"),+ join(routeTemplatesDirectory, "text.tsx"),"utf8");const defaultSitemapTemplate = await readFile(- join(routeTemplatesDir, "default-sitemap.tsx"),+ join(routeTemplatesDirectory, "default-sitemap.tsx"),"utf8");// cleanup route templates after reading to not bloat generated code- await rm(routeTemplatesDir, { recursive: true, force: true });+ await cleanupFrameworkTemplates(options);const remix = "@webstudio-is/sdk-components-react-remix";const { components, metas } = createFrameworkComponentRegistry({diff --git a/packages/cli/src/framework-vike-ssg.ts b/packages/cli/src/framework-vike-ssg.tsindex 1090fb1d25..33dcc55c56 100644--- a/packages/cli/src/framework-vike-ssg.ts+++ b/packages/cli/src/framework-vike-ssg.ts@@ -1,11 +1,16 @@import { join } from "node:path";-import { readFile, rm } from "node:fs/promises";+import { readFile } from "node:fs/promises";import { isPathnamePattern } from "@webstudio-is/sdk";import {baseComponentImportSource,createFrameworkComponentRegistry,} from "@webstudio-is/sdk-components-registry/framework";-import type { Framework } from "./framework";+import {+ cleanupFrameworkTemplates,+ routeTemplatesDirectory,+ type Framework,+ type FrameworkOptions,+} from "./framework";const generateVikeRoute = (pagePath: string) => {if (pagePath === "/") {@@ -14,24 +19,24 @@ const generateVikeRoute = (pagePath: string) => {return pagePath;};-export const createFramework = async (): Promise<Framework> => {- const routeTemplatesDir = join("app", "route-templates");-+export const createFramework = async (+ options: FrameworkOptions = {}+): Promise<Framework> => {const htmlPageTemplate = await readFile(- join(routeTemplatesDir, "html", "+Page.tsx"),+ join(routeTemplatesDirectory, "html", "+Page.tsx"),"utf8");const htmlHeadTemplate = await readFile(- join(routeTemplatesDir, "html", "+Head.tsx"),+ join(routeTemplatesDirectory, "html", "+Head.tsx"),"utf8");const htmlDataTemplate = await readFile(- join(routeTemplatesDir, "html", "+data.ts"),+ join(routeTemplatesDirectory, "html", "+data.ts"),"utf8");// cleanup route templates after reading to not bloat generated code- await rm(routeTemplatesDir, { recursive: true, force: true });+ await cleanupFrameworkTemplates(options);const { components, metas } = createFrameworkComponentRegistry();diff --git a/packages/cli/src/framework.ts b/packages/cli/src/framework.tsindex 27f7c6bacf..e23f96ff9e 100644--- a/packages/cli/src/framework.ts+++ b/packages/cli/src/framework.ts@@ -1,5 +1,18 @@+import { rm } from "node:fs/promises";+import { join } from "node:path";import type { WsComponentMeta } from "@webstudio-is/sdk";+export type FrameworkOptions = { preserveTemplates?: boolean };+export const routeTemplatesDirectory = join("app", "route-templates");++export const cleanupFrameworkTemplates = async ({+ preserveTemplates = false,+}: FrameworkOptions = {}) => {+ if (preserveTemplates === false) {+ await rm(routeTemplatesDirectory, { recursive: true, force: true });+ }+};+type FrameworkTemplateEntry = {file: string;template: string;diff --git a/packages/cli/src/fs-utils.test.ts b/packages/cli/src/fs-utils.test.tsindex c248288c8c..5835e85ed2 100644--- a/packages/cli/src/fs-utils.test.ts+++ b/packages/cli/src/fs-utils.test.ts@@ -1,8 +1,20 @@import { afterEach, beforeEach, expect, test } from "vitest";-import { mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";+import {+ mkdtemp,+ readFile,+ readdir,+ rm,+ stat,+ writeFile,+} from "node:fs/promises";import { join } from "node:path";import { tmpdir } from "node:os";-import { loadJSONFile, withFileLock, writeFileAtomic } from "./fs-utils";+import {+ loadJSONFile,+ withFileLock,+ writeFileAtomic,+ writeFileIfChanged,+} from "./fs-utils";const originalCwd = process.cwd();let tempDir: string;@@ -40,6 +52,18 @@ test("writes files atomically without leaving temporary files", async () => {await expect(readdir("nested")).resolves.toEqual(["data.txt"]);});+test("writes a file only when its content changes", async () => {+ await expect(writeFileIfChanged("data.txt", "first")).resolves.toBe(true);+ const firstInode = (await stat("data.txt")).ino;++ await expect(writeFileIfChanged("data.txt", "first")).resolves.toBe(false);+ expect((await stat("data.txt")).ino).toBe(firstInode);+ await expect(writeFileIfChanged("data.txt", "second")).resolves.toBe(true);++ await expect(readFile("data.txt", "utf8")).resolves.toBe("second");+ expect((await stat("data.txt")).ino).not.toBe(firstInode);+});+test("releases file locks when an operation fails", async () => {await expect(withFileLock("nested/data.json", async () => {diff --git a/packages/cli/src/fs-utils.ts b/packages/cli/src/fs-utils.tsindex ee44fb8f9f..0bb3c574c8 100644--- a/packages/cli/src/fs-utils.ts+++ b/packages/cli/src/fs-utils.ts@@ -54,6 +54,14 @@ export const writeFileAtomic = async (filePath: string, content: string) => {}};+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));diff --git a/packages/cli/src/mcp-guidance.test.ts b/packages/cli/src/mcp-guidance.test.tsindex 728e2654f6..c6ff06a650 100644--- a/packages/cli/src/mcp-guidance.test.ts+++ b/packages/cli/src/mcp-guidance.test.ts@@ -17,6 +17,13 @@ test("documents generated app setup for visual verification", () => {"generated project files are current");expect(screenshotVerificationSummary).toContain("preview.start");+ expect(screenshotVerificationSummary).toContain(+ "Iterative mode is the default"+ );+ expect(screenshotVerificationSummary).not.toContain("production-like");+ expect(screenshotVerificationSummary).not.toContain(+ "path screenshots restart preview"+ );expect(screenshotVerificationSummary).toContain("list-breakpoints");expect(screenshotVerificationSummary).toContain("viewport");});diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.tsindex 85cd831614..b0d32f1ccb 100644--- a/packages/cli/src/prebuild.test.ts+++ b/packages/cli/src/prebuild.test.ts@@ -5,7 +5,9 @@ import {readdir,readFile,rm,+ stat,symlink,+ utimes,writeFile,} from "node:fs/promises";import { join } from "node:path";@@ -289,6 +291,109 @@ describe("generateRedirectsModule", () => {});describe("prebuild", () => {+ test("incrementally replaces only changed generated files", async () => {+ const siteData = createSiteData({+ pages: [+ {+ id: "home",+ name: "Home",+ title: "Home",+ path: "",+ rootInstanceId: "root",+ meta: {},+ },+ {+ id: "pricing",+ name: "Pricing",+ title: "Pricing",+ path: "/pricing",+ rootInstanceId: "root",+ meta: {},+ },+ {+ id: "about",+ name: "About",+ title: "About",+ path: "/about",+ rootInstanceId: "root",+ meta: {},+ },+ ],+ });+ await writeSiteData(siteData);+ await prebuild({+ assets: false,+ template: ["react-router"],+ preserveRouteTemplates: true,+ });+ const unchangedFile = "app/__generated__/[about]._index.tsx";+ const unchangedTime = new Date("2000-01-01T00:00:00.000Z");+ await utimes(unchangedFile, unchangedTime, unchangedTime);+ const pricingFile = "app/__generated__/[pricing]._index.tsx";+ const pricingRoute = "app/routes/[pricing]._index.tsx";+ const templateRoute = "app/routes/[robots.txt].tsx";+ await writeFile("app/routes/custom.tsx", "custom", "utf8");++ siteData.build.version += 1;+ siteData.build.pages.pages = siteData.build.pages.pages.filter(+ (page) => page.id !== "pricing"+ );+ await writeSiteData(siteData);+ await prebuild({+ assets: false,+ template: ["react-router"],+ incremental: true,+ });++ siteData.build.version += 1;+ await writeSiteData(siteData);+ await prebuild({+ assets: false,+ template: ["react-router"],+ incremental: true,+ });++ expect((await stat(unchangedFile)).mtimeMs).toBe(unchangedTime.getTime());+ await expect(+ readFile("app/__generated__/_index.tsx", "utf8")+ ).resolves.toContain(+ `export const projectVersion = ${siteData.build.version};`+ );+ await expect(readFile(pricingFile, "utf8")).rejects.toThrow("ENOENT");+ await expect(readFile(pricingRoute, "utf8")).rejects.toThrow("ENOENT");+ await expect(readFile(templateRoute, "utf8")).resolves.toContain(+ "User-agent"+ );+ await expect(readFile("app/routes/custom.tsx", "utf8")).resolves.toBe(+ "custom"+ );+ });++ test("rejects generated manifests that point outside owned output", async () => {+ const outsideFile = "outside.ts";+ await writeSiteData(createSiteData());+ await prebuild({+ assets: false,+ template: ["react-router"],+ preserveRouteTemplates: true,+ });+ await writeFile(outsideFile, "preserve", "utf8");+ await writeFile(+ ".webstudio/generated-files.json",+ JSON.stringify([outsideFile]),+ "utf8"+ );++ await expect(+ prebuild({+ assets: false,+ template: ["react-router"],+ incremental: true,+ })+ ).rejects.toThrow("Generated files manifest is invalid.");+ await expect(readFile(outsideFile, "utf8")).resolves.toBe("preserve");+ });+test("excludes draft pages from published output", async () => {await writeSiteData(createSiteData({diff --git a/packages/cli/src/prebuild.ts b/packages/cli/src/prebuild.tsindex d45e00a504..2c5351e844 100644--- a/packages/cli/src/prebuild.ts+++ b/packages/cli/src/prebuild.ts@@ -1,4 +1,12 @@-import { basename, dirname, join, normalize, relative } from "node:path";+import {+ basename,+ dirname,+ isAbsolute,+ join,+ normalize,+ relative,+ sep,+} from "node:path";import { existsSync } from "node:fs";import { rm, cp, readFile, writeFile, readdir } from "node:fs/promises";import { cwd, exit } from "node:process";@@ -54,6 +62,7 @@ import {createFileIfNotExists,createFolderIfNotExists,loadJSONFile,+ writeFileIfChanged,} from "./fs-utils";import { htmlToJsx } from "./html-to-jsx";import { compareMedia } from "@webstudio-is/css-engine";@@ -63,6 +72,15 @@ import { createFramework as createRemixFramework } from "./framework-remix";import { createFramework as createReactRouterFramework } from "./framework-react-router";import { createFramework as createVikeSsgFramework } from "./framework-vike-ssg";+export const generatedFilesManifest = join(+ ".webstudio",+ "generated-files.json"+);+const appRoot = "app";+const generatedDir = join(appRoot, "__generated__");+const routesDir = join(appRoot, "routes");+const generatedOutputDirectories = [generatedDir, routesDir] as const;+type SiteDataByPage = {[id: Page["id"]]: {page: Page;@@ -137,17 +155,56 @@ const readAssetBaseUrl = async (constantsPath: string) => {const writeWsAuthResources = async (generatedDir: string,pages: Pages,- projectSettings?: PublishedProjectBundle["build"]["projectSettings"]+ projectSettings:+ | PublishedProjectBundle["build"]["projectSettings"]+ | undefined,+ writeGeneratedFile: (file: string, content: string) => Promise<unknown>) => {const { content, module } = createAuthConfigResources(pages, projectSettings);await createFolderIfNotExists(dirname(LOCAL_AUTH_FILE));- await writeFile(LOCAL_AUTH_FILE, content);- await createFileIfNotExists(+ await writeFileIfChanged(LOCAL_AUTH_FILE, content);+ await writeGeneratedFile(join(generatedDir, "$resources.wsauth.server.ts"),module);};+const isGeneratedOutputPath = (path: string) =>+ generatedOutputDirectories.some((directory) => {+ const relativePath = relative(directory, path);+ return (+ relativePath !== "" &&+ relativePath !== ".." &&+ relativePath.startsWith(`..${sep}`) === false &&+ isAbsolute(relativePath) === false+ );+ });++const readGeneratedFilesManifest = async () => {+ const value = JSON.parse(await readFile(generatedFilesManifest, "utf8"));+ if (+ Array.isArray(value) === false ||+ value.some(+ (path) =>+ typeof path !== "string" || isGeneratedOutputPath(path) === false+ )+ ) {+ throw new Error("Generated files manifest is invalid.");+ }+ return new Set<string>(value);+};++const removeObsoleteGeneratedFiles = async (+ previousFiles: ReadonlySet<string>,+ generatedFiles: ReadonlySet<string>+) => {+ for (const path of previousFiles) {+ if (generatedFiles.has(path) === false) {+ await rm(path, { force: true });+ }+ }+};+/*** Check if template is internal cli template or external path*/@@ -264,6 +321,10 @@ export const prebuild = async (options: {silent?: boolean;/** Generate draft routes for local verification without publishing them. */includeDraftPages?: boolean;+ /** Preserve the generated tree and atomically replace only changed files. */+ incremental?: boolean;+ /** Retain route template inputs for a later incremental generation. */+ preserveRouteTemplates?: boolean;}) => {const buildRoot = cwd();const feedback = options.silent@@ -309,28 +370,52 @@ export const prebuild = async (options: {feedback.step("Scaffolding the project files");- const appRoot = "app";+ if (options.incremental !== true) {+ await rm(generatedDir, { recursive: true, force: true });+ }- const generatedDir = join(appRoot, "__generated__");- await rm(generatedDir, { recursive: true, force: true });+ if (options.incremental !== true) {+ await rm(routesDir, { recursive: true, force: true });+ }- const routesDir = join(appRoot, "routes");- await rm(routesDir, { recursive: true, force: true });+ const generatedFiles = new Set<string>();+ const previousGeneratedFiles =+ options.incremental === true+ ? await readGeneratedFilesManifest()+ : new Set<string>();+ const writeGeneratedFile = async (file: string, content: string) => {+ generatedFiles.add(normalize(file));+ if (options.incremental === true) {+ return await writeFileIfChanged(file, content);+ }+ await createFileIfNotExists(file, content);+ return true;+ };// force npm to install with not matching peer dependenciesawait writeFile(join(cwd(), ".npmrc"), npmrc);- for (const template of options.template) {- await copyTemplates(template);+ if (options.incremental !== true) {+ for (const template of options.template) {+ await copyTemplates(template);+ }}+ const preserveRouteTemplates =+ options.incremental === true || options.preserveRouteTemplates === true;let framework;if (options.template.includes("ssg")) {- framework = await createVikeSsgFramework();+ framework = await createVikeSsgFramework({+ preserveTemplates: preserveRouteTemplates,+ });} else if (options.template.includes("react-router")) {- framework = await createReactRouterFramework();+ framework = await createReactRouterFramework({+ preserveTemplates: preserveRouteTemplates,+ });} else {- framework = await createRemixFramework();+ framework = await createRemixFramework({+ preserveTemplates: preserveRouteTemplates,+ });}const assetBaseUrl = await readAssetBaseUrl(join(cwd(), "app/constants.mjs"));@@ -361,7 +446,8 @@ export const prebuild = async (options: {await writeWsAuthResources(generatedDir,pages,- siteData.build.projectSettings+ siteData.build.projectSettings,+ writeGeneratedFile);const siteDataByPage: SiteDataByPage = {};const fontAssetsByPage: Record<Page["id"], string[]> = {};@@ -518,7 +604,7 @@ export const prebuild = async (options: {true,});- await createFileIfNotExists(join(generatedDir, "index.css"), cssText);+ await writeGeneratedFile(join(generatedDir, "index.css"), cssText);for (const page of generatedPages) {const scope = createScope([@@ -654,6 +740,8 @@ export const prebuild = async (options: {export const projectId = "${siteData.build.projectId}";+ ${pagePath === "/" ? `export const projectVersion = ${siteData.build.version};` : ""}+export const projectDomain = ${JSON.stringify(siteData.projectDomain)};export const lastPublished = "${new Date(siteData.build.createdAt).toISOString()}";@@ -735,10 +823,10 @@ export const prebuild = async (options: {const generatedBasename = generateRemixRoute(pagePath);const clientFile = join(generatedDir, `${generatedBasename}.tsx`);- await createFileIfNotExists(clientFile, pageExports);+ await writeGeneratedFile(clientFile, pageExports);const serverFile = join(generatedDir, `${generatedBasename}.server.tsx`);- await createFileIfNotExists(serverFile, serverExports);+ await writeGeneratedFile(serverFile, serverExports);const getTemplates = framework[documentType];for (const { file, template } of getTemplates({ pagePath })) {@@ -768,7 +856,7 @@ export const prebuild = async (options: {"__CSS__",importFrom(`./app/__generated__/index.css`, file));- await createFileIfNotExists(file, content);+ await writeGeneratedFile(file, content);}}@@ -778,10 +866,10 @@ export const prebuild = async (options: {"__SITEMAP__",importFrom(`./app/__generated__/$resources.sitemap.xml`, file));- await createFileIfNotExists(file, content);+ await writeGeneratedFile(file, content);}- await createFileIfNotExists(+ await writeGeneratedFile(join(generatedDir, "$resources.sitemap.xml.ts"),`export const sitemap = ${JSON.stringify(@@ -807,20 +895,20 @@ export const prebuild = async (options: {]));- await createFileIfNotExists(+ await writeGeneratedFile(join(generatedDir, "$resources.assets.ts"),`export const assets = ${JSON.stringify(assetsById, null, 2)};`);- await createFileIfNotExists(+ await writeGeneratedFile(join(generatedDir, "$resources.redirects.ts"),generateRedirectsModule(pages.redirects));if (pages.redirects !== undefined && pages.redirects.length > 0) {- await createFileIfNotExists(+ await writeGeneratedFile(join(routesDir, "$.tsx"),generateRedirectFallbackRoute(options.template.includes("react-router") ? "react-router" : "remix"@@ -828,6 +916,14 @@ export const prebuild = async (options: {);}+ if (options.incremental === true) {+ await removeObsoleteGeneratedFiles(previousGeneratedFiles, generatedFiles);+ }+ await writeFileIfChanged(+ generatedFilesManifest,+ JSON.stringify([...generatedFiles].sort(), undefined, 2)+ );+if (options.assets === true && siteData.assets.length > 0) {const downloading = createProgress();downloading.start("Downloading fonts and images");diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.tsindex 5c87e23683..e784c66575 100644--- a/packages/cli/src/preview-server.test.ts+++ b/packages/cli/src/preview-server.test.ts@@ -84,6 +84,25 @@ test("builds npm production preview args", () => {]);});+test("builds iterative preview args for an ordinary reload server", () => {+ expect(+ getPreviewStartArgs({+ host: "127.0.0.1",+ port: 5173,+ mode: "iterative",+ })+ ).toEqual([+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5173",+ "--strictPort",+ ]);+});+test("uses the platform npm executable for preview commands", () => {expect(getPreviewCommand("linux")).toBe("npm");expect(getPreviewCommand("darwin")).toBe("npm");@@ -248,11 +267,13 @@ test("preview controller builds once and reuses a running server", async () => {url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "production",});await expect(controller.start()).resolves.toEqual({url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "production",});expect(controller.resolveUrl("/pricing")).toBe("http://127.0.0.1:5173/pricing"@@ -269,6 +290,45 @@ test("preview controller builds once and reuses a running server", async () => {});});+test("iterative preview starts without a production build", async () => {+ const process = createPreviewProcess();+ const spawn = vi.fn(() => process);+ const controller = createPreviewController(+ {+ host: "127.0.0.1",+ port: 5173,+ cwd: "/tmp/preview",+ mode: "iterative",+ },+ createDependencies({ spawn: spawn as never })+ );++ await expect(controller.start()).resolves.toMatchObject({+ running: true,+ mode: "iterative",+ });+ expect(spawn).toHaveBeenCalledOnce();+ expect(spawn).toHaveBeenCalledWith(+ "npm",+ [+ "run",+ "dev",+ "--",+ "--host",+ "127.0.0.1",+ "--port",+ "5173",+ "--strictPort",+ ],+ expect.objectContaining({+ env: expect.objectContaining({+ NODE_ENV: "development",+ WEBSTUDIO_PREVIEW_HMR: "disabled",+ }),+ })+ );+});+test("preview controller reuses a matching persisted production build", async () => {const process = createPreviewProcess();const spawn = vi.fn(() => process);@@ -314,7 +374,16 @@ test("preview controller rejects incompatible start options while running", asyn);resolveProcessExit(buildProcess);+ expect(controller.canReuse()).toBe(false);await controller.start();+ expect(controller.canReuse()).toBe(true);+ expect(controller.canReuse({ host: "127.0.0.1", port: 5173 })).toBe(true);+ expect(controller.canReuse({ port: 3000 })).toBe(false);+ expect(controller.canReuse({ cwd: "/tmp/other-preview" })).toBe(false);+ expect(controller.canReuse({ mode: "iterative" })).toBe(false);+ expect(controller.canReuse({ imageDomains: ["images.example.com"] })).toBe(+ false+ );await expect(controller.start({ port: 3000 })).rejects.toThrow("Preview server is already running at http://127.0.0.1:5173/"@@ -344,6 +413,10 @@ test("preview controller passes image domains to the managed server", async () =await controller.start({ imageDomains: ["images.example.com"] });+ expect(controller.canReuse({ imageDomains: ["images.example.com"] })).toBe(+ true+ );+expect(spawn).toHaveBeenLastCalledWith("npm",["run", "start"],@@ -386,12 +459,14 @@ test("preview controller stops the running server", async () => {url: "http://127.0.0.1:5173/",pid: undefined,running: false,+ mode: "production",});expect(process.kill).toHaveBeenCalledOnce();await expect(controller.stop()).resolves.toEqual({url: "http://127.0.0.1:5173/",pid: undefined,running: false,+ mode: "production",});});@@ -413,11 +488,13 @@ test("preview controller reuses custom running options when start has no optionsurl: "http://127.0.0.1:3000/",pid: 123,running: true,+ mode: "production",});await expect(controller.start()).resolves.toEqual({url: "http://127.0.0.1:3000/",pid: 123,running: true,+ mode: "production",});});@@ -444,18 +521,56 @@ test("preview controller can restart a running server after rebuilding", async (url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "production",});resolveProcessExit(firstProcess);await expect(controller.start({ restart: true })).resolves.toEqual({url: "http://127.0.0.1:5173/",pid: 456,running: true,+ mode: "production",});expect(firstProcess.kill).toHaveBeenCalledOnce();expect(spawn).toHaveBeenCalledTimes(4);});+test("ignores a delayed exit from a previously owned preview server", async () => {+ let firstExit: (() => void) | undefined;+ const firstProcess = createPreviewProcess({+ once: vi.fn((event: string, callback: () => void) => {+ if (event === "exit") {+ firstExit = callback;+ }+ return undefined;+ }) as never,+ kill: vi.fn(() => false),+ });+ const secondProcess = createPreviewProcess({ pid: 456 });+ const spawn = vi+ .fn()+ .mockReturnValueOnce(firstProcess)+ .mockReturnValueOnce(secondProcess);+ const controller = createPreviewController(+ {+ host: "127.0.0.1",+ port: 5173,+ cwd: "/tmp/preview",+ mode: "iterative",+ },+ createDependencies({ spawn: spawn as never })+ );++ await controller.start();+ await controller.start({ restart: true });+ firstExit?.();++ expect(controller.status()).toMatchObject({+ pid: 456,+ running: true,+ });+});+test("waits for preview server readiness", async () => {const fetch = vi.fn()@@ -518,7 +633,7 @@ test("requires the exact generated project even when build assets match", asynctimeoutMs: 1,intervalMs: 5,requiredAssetNames: ["index-new.css"],- requiredProjectId: "expected-project",+ requiredProject: { projectId: "expected-project" },},createDependencies({ fetch }))@@ -542,13 +657,40 @@ test("accepts the generated preview with the expected project marker", async (){timeoutMs: 1000,requiredAssetNames: ["index-new.css"],- requiredProjectId: "expected-project",+ requiredProject: { projectId: "expected-project" },},createDependencies({ fetch }))).resolves.toBeUndefined();});+test("waits for the exact generated session version", async () => {+ const fetch = vi+ .fn()+ .mockResolvedValueOnce(+ new Response(+ '<html data-ws-project="project" data-ws-version="4"></html>'+ )+ )+ .mockResolvedValueOnce(+ new Response(+ '<html data-ws-project="project" data-ws-version="5"></html>'+ )+ );++ await waitForPreviewReady(+ "http://127.0.0.1:5173/",+ {+ timeoutMs: 1000,+ intervalMs: 5,+ requiredProject: { projectId: "project", version: 5 },+ },+ createDependencies({ fetch })+ );++ expect(fetch).toHaveBeenCalledTimes(2);+});+test("rejects stale preview servers that serve a previous build", async () => {const fetch = vi.fn(async () =>@@ -592,6 +734,7 @@ test("preview controller waits when starting through startAndWait", async () =>url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "production",});expect(fetch).toHaveBeenCalledWith("http://127.0.0.1:5173/", {method: "GET",diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.tsindex bccd4b407f..e1c3608a28 100644--- a/packages/cli/src/preview-server.ts+++ b/packages/cli/src/preview-server.ts@@ -6,10 +6,15 @@ import {import { cp, mkdir, readFile, readdir, writeFile } from "node:fs/promises";import { createServer as createTcpServer } from "node:net";import { delimiter, dirname, join, parse } from "node:path";+import { parse as parseHtml, type DefaultTreeAdapterMap } from "parse5";+import type { ProjectPreviewMode } from "@webstudio-is/project-build/visual";++export type PreviewMode = ProjectPreviewMode;export type PreviewServerOptions = {host: string;port: number;+ mode?: PreviewMode;cwd?: string;imageDomains?: string[];};@@ -109,10 +114,19 @@ export const getPreviewUrl = ({export const getPreviewBuildArgs = () => ["run", "build"];-export const getPreviewStartArgs = (_options: PreviewServerOptions) => [- "run",- "start",-];+export const getPreviewStartArgs = (options: PreviewServerOptions) =>+ options.mode === "iterative"+ ? [+ "run",+ "dev",+ "--",+ "--host",+ options.host,+ "--port",+ String(options.port),+ "--strictPort",+ ]+ : ["run", "start"];export const getPreviewCommand = (platform: typeof process.platform = process.platform@@ -195,7 +209,10 @@ export const startPreviewServer = (...(options.imageDomains === undefined? {}: { DOMAINS: options.imageDomains.join(",") }),- NODE_ENV: "production",+ NODE_ENV: options.mode === "iterative" ? "development" : "production",+ ...(options.mode === "iterative"+ ? { WEBSTUDIO_PREVIEW_HMR: "disabled" }+ : {}),}),});@@ -219,6 +236,7 @@ export type PreviewControllerResult = {url: string;pid?: number;running: boolean;+ mode: PreviewMode;};type PreviewControllerStartOptions = Partial<PreviewServerOptions> & {@@ -226,7 +244,7 @@ type PreviewControllerStartOptions = Partial<PreviewServerOptions> & {buildCacheKey?: string;};-const areStringArraysEqual = (+export const arePreviewImageDomainsEqual = (left: string[] | undefined,right: string[] | undefined) =>@@ -238,7 +256,7 @@ const areStringArraysEqual = (export const previewBuildCacheMarker = ".webstudio-preview-build";-const getPreviewProjectId = async (+const getPreviewProjectIdentity = async (cwd: string | undefined,dependencies = defaultPreviewServerDependencies) => {@@ -248,11 +266,16 @@ const getPreviewProjectId = async (try {const data = JSON.parse(await dependencies.readFile(join(cwd, ".webstudio", "data.json"), "utf8")- ) as { build?: { projectId?: unknown } };+ ) as { build?: { projectId?: unknown; version?: unknown } };if (typeof data.build?.projectId !== "string") {throw new Error("projectId is missing");}- return data.build.projectId;+ return {+ projectId: data.build.projectId,+ ...(typeof data.build.version === "number"+ ? { version: data.build.version }+ : {}),+ };} catch (error) {throw new Error(`Could not identify the generated preview project in ${join(cwd, ".webstudio", "data.json")}.`,@@ -261,11 +284,35 @@ const getPreviewProjectId = async (}};-const hasProjectMarker = (html: string, projectId: string) => {- const escapedProjectId = projectId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");- return new RegExp(- `data-ws-project\\s*=\\s*(["'])${escapedProjectId}\\1`- ).test(html);+const getGeneratedSiteIdentity = (html: string) => {+ const document = parseHtml(html);+ const visit = (+ node: DefaultTreeAdapterMap["node"]+ ): { projectId: string; version?: number } | undefined => {+ if ("attrs" in node && Array.isArray(node.attrs)) {+ const attributes = new Map(+ node.attrs.map(({ name, value }) => [name, value])+ );+ const projectId = attributes.get("data-ws-project");+ const versionValue = attributes.get("data-ws-version");+ if (projectId !== undefined) {+ const version = Number(versionValue);+ return {+ projectId,+ ...(Number.isFinite(version) ? { version } : {}),+ };+ }+ }+ if ("childNodes" in node) {+ for (const child of node.childNodes) {+ const identity = visit(child);+ if (identity !== undefined) {+ return identity;+ }+ }+ }+ };+ return visit(document);};export const waitForPreviewReady = async (@@ -275,13 +322,13 @@ export const waitForPreviewReady = async (intervalMs = 250,isRunning,requiredAssetNames = [],- requiredProjectId,+ requiredProject,}: {timeoutMs?: number;intervalMs?: number;isRunning?: () => boolean;requiredAssetNames?: string[];- requiredProjectId?: string;+ requiredProject?: { projectId: string; version?: number };} = {},dependencies = defaultPreviewServerDependencies) => {@@ -304,16 +351,16 @@ export const waitForPreviewReady = async (signal: AbortSignal.timeout(attemptTimeoutMs),});if (response.status < 500) {- if (- requiredAssetNames.length === 0 &&- requiredProjectId === undefined- ) {+ if (requiredAssetNames.length === 0 && requiredProject === undefined) {return;}const html = await response.text();+ const identity = getGeneratedSiteIdentity(html);const servesExpectedProject =- requiredProjectId === undefined ||- hasProjectMarker(html, requiredProjectId);+ requiredProject === undefined ||+ (identity?.projectId === requiredProject.projectId &&+ (requiredProject.version === undefined ||+ identity.version === requiredProject.version));const servesLatestAssets =requiredAssetNames.length === 0 ||requiredAssetNames.some((name) => html.includes(name));@@ -392,7 +439,41 @@ export const createPreviewController = (url: getPreviewUrl(currentOptions),pid: server?.process.pid,running: isRunning(),+ mode: currentOptions.mode ?? "production",});+ const resolveOptions = (+ options: PreviewControllerStartOptions+ ): PreviewServerOptions => {+ const running = isRunning();+ return {+ host: options.host ?? (running ? currentOptions.host : defaults.host),+ port: options.port ?? (running ? currentOptions.port : defaults.port),+ cwd: options.cwd ?? (running ? currentCwd : defaults.cwd),+ imageDomains:+ options.imageDomains ??+ (running ? currentOptions.imageDomains : defaults.imageDomains),+ mode:+ options.mode ??+ (running ? currentOptions.mode : defaults.mode) ??+ "production",+ };+ };+ const canReuse = (options: PreviewControllerStartOptions = {}) => {+ if (isRunning() === false) {+ return false;+ }+ const nextOptions = resolveOptions(options);+ return (+ nextOptions.host === currentOptions.host &&+ nextOptions.port === currentOptions.port &&+ nextOptions.cwd === currentCwd &&+ nextOptions.mode === (currentOptions.mode ?? "production") &&+ arePreviewImageDomainsEqual(+ nextOptions.imageDomains,+ currentOptions.imageDomains+ )+ );+ };const stop = async () => {if (server === undefined) {return;@@ -418,25 +499,10 @@ export const createPreviewController = (options: PreviewControllerStartOptions = {}): Promise<PreviewControllerResult> => {const running = isRunning();- const nextOptions = {- host: options.host ?? (running ? currentOptions.host : defaults.host),- port: options.port ?? (running ? currentOptions.port : defaults.port),- cwd: options.cwd ?? (running ? currentCwd : defaults.cwd),- imageDomains:- options.imageDomains ??- (running ? currentOptions.imageDomains : defaults.imageDomains),- };+ const nextOptions = resolveOptions(options);if (running) {if (options.restart !== true) {- if (- nextOptions.host !== currentOptions.host ||- nextOptions.port !== currentOptions.port ||- nextOptions.cwd !== currentCwd ||- areStringArraysEqual(- nextOptions.imageDomains,- currentOptions.imageDomains- ) === false- ) {+ if (canReuse(options) === false) {throw new Error(`Preview server is already running at ${getPreviewUrl(currentOptions)}. Stop it before starting a different preview server.`);@@ -454,8 +520,9 @@ export const createPreviewController = (.readFile(join(currentCwd, previewBuildCacheMarker), "utf8").catch(() => undefined);if (- options.buildCacheKey === undefined ||- cachedBuildKey !== options.buildCacheKey+ nextOptions.mode === "production" &&+ (options.buildCacheKey === undefined ||+ cachedBuildKey !== options.buildCacheKey)) {await runPreviewBuild(dependencies, currentCwd, ["ignore",@@ -470,39 +537,43 @@ export const createPreviewController = (}}serverOutput = "";- server = startPreviewServer(+ const startedServer = startPreviewServer({...nextOptions,stdio: ["ignore", "pipe", "pipe"],},dependencies);- server.process.stdout?.on("data", appendServerOutput);- server.process.stderr?.on("data", appendServerOutput);- server.process.once("exit", () => {- server = undefined;+ server = startedServer;+ startedServer.process.stdout?.on("data", appendServerOutput);+ startedServer.process.stderr?.on("data", appendServerOutput);+ startedServer.process.once("exit", () => {+ if (server === startedServer) {+ server = undefined;+ }});return getStatus();};return {+ canReuse,start,async startAndWait(options: PreviewControllerStartOptions = {}): Promise<PreviewControllerResult> {const nextCwd = options.cwd ?? (isRunning() ? currentCwd : defaults.cwd);- const requiredProjectId = await getPreviewProjectId(+ const requiredProject = await getPreviewProjectIdentity(nextCwd,dependencies);const result = await start(options);- const requiredAssetNames = await getPreviewCssAssetNames(- currentCwd,- dependencies- );+ const requiredAssetNames =+ result.mode === "production"+ ? await getPreviewCssAssetNames(currentCwd, dependencies)+ : [];try {await waitForPreviewReady(result.url,- { isRunning, requiredAssetNames, requiredProjectId },+ { isRunning, requiredAssetNames, requiredProject },dependencies);} catch (error) {diff --git a/packages/cli/src/screenshot-browser-cdp.ts b/packages/cli/src/screenshot-browser-cdp.tsindex d79b4d76aa..0c81753d60 100644--- a/packages/cli/src/screenshot-browser-cdp.ts+++ b/packages/cli/src/screenshot-browser-cdp.ts@@ -365,6 +365,8 @@ const waitForSelector = async (type BrowserReadiness = {documentReadyState: string;generatedSiteRootPresent: boolean;+ projectId?: string;+ projectVersion?: number;layoutStable: boolean;};@@ -379,6 +381,14 @@ const waitForFontsAndFrames = async (documentReadyState: document.readyState,generatedSiteRootPresent:document.documentElement.hasAttribute("data-ws-project"),+ projectId:+ document.documentElement.getAttribute("data-ws-project") ?? undefined,+ projectVersion: (() => {+ const attribute = document.documentElement.getAttribute("data-ws-version");+ if (attribute === null) return undefined;+ const value = Number(attribute);+ return Number.isFinite(value) ? value : undefined;+ })(),width: document.documentElement.scrollWidth,height: document.documentElement.scrollHeight,}))`,@@ -395,6 +405,8 @@ const waitForFontsAndFrames = async (): value is {documentReadyState: string;generatedSiteRootPresent: boolean;+ projectId?: string;+ projectVersion?: number;width: number;height: number;} =>@@ -404,6 +416,12 @@ const waitForFontsAndFrames = async (typeof value.documentReadyState === "string" &&"generatedSiteRootPresent" in value &&typeof value.generatedSiteRootPresent === "boolean" &&+ ("projectId" in value === false ||+ value.projectId === undefined ||+ typeof value.projectId === "string") &&+ ("projectVersion" in value === false ||+ value.projectVersion === undefined ||+ typeof value.projectVersion === "number") &&"width" in value &&typeof value.width === "number" &&"height" in value &&@@ -428,6 +446,12 @@ const waitForFontsAndFrames = async (return {documentReadyState: value.documentReadyState,generatedSiteRootPresent: value.generatedSiteRootPresent,+ ...(value.projectId === undefined+ ? {}+ : { projectId: value.projectId }),+ ...(value.projectVersion === undefined+ ? {}+ : { projectVersion: value.projectVersion }),layoutStable: true,};}@@ -435,6 +459,12 @@ const waitForFontsAndFrames = async (return {documentReadyState: value.documentReadyState,generatedSiteRootPresent: value.generatedSiteRootPresent,+ ...(value.projectId === undefined+ ? {}+ : { projectId: value.projectId }),+ ...(value.projectVersion === undefined+ ? {}+ : { projectVersion: value.projectVersion }),layoutStable: false,};}@@ -533,6 +563,8 @@ export type BrowserScreenshotNavigation = {redirects: string[];documentReadyState: string;generatedSiteRootPresent: boolean;+ projectId?: string;+ projectVersion?: number;layoutStable: boolean;};diff --git a/packages/cli/src/screenshot.test.ts b/packages/cli/src/screenshot.test.tsindex fc2e5025df..8d0693eeba 100644--- a/packages/cli/src/screenshot.test.ts+++ b/packages/cli/src/screenshot.test.ts@@ -406,8 +406,6 @@ test("resets a reusable capture session after browser startup rejects", async ()await expect(session.capture(options)).rejects.toThrow("Browser exited before its DevTools endpoint became ready.");- await expect(session.close()).resolves.toBeUndefined();-await expect(session.capture(options)).rejects.toThrow("Browser exited before its DevTools endpoint became ready.");diff --git a/packages/cli/src/screenshot.ts b/packages/cli/src/screenshot.tsindex 81a5631db1..40ecd3239f 100644--- a/packages/cli/src/screenshot.ts+++ b/packages/cli/src/screenshot.ts@@ -608,6 +608,26 @@ export const createScreenshotCaptureSession = (let browserPromise: Promise<BrowserCandidate> | undefined;let browserSession: BrowserScreenshotSession | undefined;let browserSessionPromise: Promise<BrowserScreenshotSession> | undefined;+ const getBrowserSession = async (+ options: BrowserScreenshotOptions+ ): Promise<BrowserScreenshotSession> => {+ if (browserSession !== undefined) {+ return browserSession;+ }+ const pendingSession =+ browserSessionPromise ??+ createBrowserScreenshotSession(options, dependencies);+ browserSessionPromise = pendingSession;+ try {+ browserSession = await pendingSession;+ return browserSession;+ } catch (error) {+ if (browserSessionPromise === pendingSession) {+ browserSessionPromise = undefined;+ }+ throw error;+ }+ };return {async capture(options: CaptureScreenshotOptions) {browserPromise ??= resolveScreenshotBrowser(options, dependencies);@@ -622,21 +642,19 @@ export const createScreenshotCaptureSession = ("A reusable screenshot session cannot switch browser executables.");}- browserSessionPromise ??= createBrowserScreenshotSession(+ const activeBrowserSession = await getBrowserSession(getBrowserScreenshotOptions(options,resolvedBrowser.path,options.output ?? "",dependencies- ),- dependencies+ ));- browserSession ??= await browserSessionPromise;return await captureResolvedScreenshot(options,resolvedBrowser,dependencies,- browserSession+ activeBrowserSession);},async capturePage(optionsList: readonly CaptureScreenshotOptions[]) {@@ -683,12 +701,10 @@ export const createScreenshotCaptureSession = (};}));- browserSessionPromise ??= createBrowserScreenshotSession(- captures[0].browserOptions,- dependencies+ const activeBrowserSession = await getBrowserSession(+ captures[0].browserOptions);- browserSession ??= await browserSessionPromise;- const layouts = await browserSession.capturePage(+ const layouts = await activeBrowserSession.capturePage(captures.map((capture) => capture.browserOptions));return captures.map(({ options, output }, index) => {diff --git a/packages/cli/templates/defaults/app/root.tsx b/packages/cli/templates/defaults/app/root.tsxindex 0fde2045df..924b93aada 100644--- a/packages/cli/templates/defaults/app/root.tsx+++ b/packages/cli/templates/defaults/app/root.tsx@@ -8,7 +8,7 @@ import type {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import { CustomCode, projectId, projectVersion, lastPublished } from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -46,6 +46,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/packages/cli/templates/react-router/app/root.tsx b/packages/cli/templates/react-router/app/root.tsxindex ae64304577..70df0a2fbb 100644--- a/packages/cli/templates/react-router/app/root.tsx+++ b/packages/cli/templates/react-router/app/root.tsx@@ -11,7 +11,7 @@ import {import { redirectRequest } from "./redirect-url";// @todo think about how to make __generated__ typeable// @ts-ignore-import { CustomCode, projectId, lastPublished } from "./__generated__/_index";+import { CustomCode, projectId, projectVersion, lastPublished } from "./__generated__/_index";// @ts-ignoreimport { redirects } from "./__generated__/$resources.redirects";@@ -49,6 +49,7 @@ const Root = () => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/packages/cli/templates/react-router/vite.config.ts b/packages/cli/templates/react-router/vite.config.tsindex 994cf66075..f8a0782b3c 100644--- a/packages/cli/templates/react-router/vite.config.ts+++ b/packages/cli/templates/react-router/vite.config.ts@@ -6,6 +6,9 @@ const sourceConditions =export default defineConfig({plugins: [reactRouter()],+ server: {+ hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,+ },resolve: {conditions: [...sourceConditions, "browser", "development|production"],},diff --git a/packages/cli/templates/ssg/renderer/+onRenderHtml.tsx b/packages/cli/templates/ssg/renderer/+onRenderHtml.tsxindex d793abce88..f7a96c9728 100644--- a/packages/cli/templates/ssg/renderer/+onRenderHtml.tsx+++ b/packages/cli/templates/ssg/renderer/+onRenderHtml.tsx@@ -4,6 +4,7 @@ import type { OnRenderHtmlSync } from "vike/types";import {CustomCode,projectId,+ projectVersion,lastPublished,// @todo think about how to make __generated__ typeable/* eslint-disable-next-line @typescript-eslint/ban-ts-comment */@@ -19,6 +20,7 @@ export const onRenderHtml: OnRenderHtmlSync = (pageContext) => {<htmllang={lang}data-ws-project={projectId}+ data-ws-version={projectVersion}data-ws-last-published={lastPublished}><head>diff --git a/packages/project-build/src/mcp-rendered-audit.test.ts b/packages/project-build/src/mcp-rendered-audit.test.tsindex 1700101998..58a27e500e 100644--- a/packages/project-build/src/mcp-rendered-audit.test.ts+++ b/packages/project-build/src/mcp-rendered-audit.test.ts@@ -498,13 +498,18 @@ describe("rendered audit evidence", () => {});expect(startPreview).toHaveBeenCalledWith(- expect.objectContaining({ port: 0, source: "session" }),+ expect.objectContaining({+ port: 0,+ source: "session",+ mode: "production",+ }),expect.any(Object));expect(capturePageScreenshots).toHaveBeenCalledOnce();expect(capturePageScreenshots).toHaveBeenCalledWith([expect.objectContaining({path: "/page",+ mode: "production",output: ".webstudio/audits/screenshots/page-1440x900.webp",viewport: { width: 1440, height: 900 },waitForTimeout: 0,diff --git a/packages/project-build/src/mcp-rendered-audit.ts b/packages/project-build/src/mcp-rendered-audit.tsindex 227d87725d..70161c9257 100644--- a/packages/project-build/src/mcp-rendered-audit.ts+++ b/packages/project-build/src/mcp-rendered-audit.ts@@ -15,6 +15,7 @@ import { isRecord } from "./shared/type-utils";import type {ProjectSessionScreenshotInput,ProjectSessionScreenshotResult,+ ProjectSessionPreviewInput,} from "./mcp";import {createConfirmationToken,@@ -76,7 +77,7 @@ const readAllPaginatedItems = async (};type StartPreview = (- input: { source: "session"; port: number; imageDomains?: string[] },+ input: ProjectSessionPreviewInput & { source: "session"; port: number },progress: { report: (message: string) => void }) => Promise<{ url: string; generatedBuildMetrics?: unknown }>;@@ -167,6 +168,7 @@ const getRenderedAuditScreenshotInput = ({path: pagePath,output: `.webstudio/audits/screenshots/${pageId.replaceAll(/[^a-z0-9_-]/gi, "_")}-${viewport.width}x${viewport.height}.webp`,source: "session",+ mode: "production",viewport: { width: viewport.width, height: viewport.height },fullPage: true,includeImageMetrics: performanceEnabled,@@ -1221,6 +1223,7 @@ export const augmentAuditWithRenderedChecks = async ({const previewResult = await startPreview({source: "session",+ mode: "production",port: automaticPreviewPort,imageDomains: renderedInput.imageDomains,},diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex 04ceebea49..9e4d4b8abd 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -973,7 +973,7 @@ describe("project session mcp adapter", () => {`Missing MCP output schema for ${command}`).toMatchObject({type: "object",- required: ["url", "running"],+ required: ["url", "running", "mode"],properties: {url: { type: "string" },pid: { type: "integer" },@@ -1600,10 +1600,12 @@ describe("project session mcp adapter", () => {const startPreview = vi.fn(async () => ({url: "http://127.0.0.1:5177",running: true,+ mode: "production" as const,}));const stopPreview = vi.fn(async () => ({url: "http://127.0.0.1:5173",running: false,+ mode: "production" as const,}));const captureScreenshot = vi.fn(async (input) => ({output: `/tmp/${input.viewport.width}.png`,@@ -3427,10 +3429,12 @@ describe("project session mcp adapter", () => {})),});+ const onProjectSessionChange = vi.fn();const adapter = createProjectSessionMcpCore({operations: publicMcpOperations,createProjectSession: createSessionFactory(session),executeOperation: createExecuteOperation(),+ onProjectSessionChange,});const status = await adapter.callTool({ name: "status" });@@ -3476,6 +3480,7 @@ describe("project session mcp adapter", () => {expect(reset.structuredContent.meta.session).toEqual(expect.objectContaining({ operationId: "project-session.reset" }));+ expect(onProjectSessionChange).toHaveBeenCalledTimes(2);});test("calls meta tools without initializing project session", async () => {@@ -5570,10 +5575,12 @@ describe("project session mcp adapter", () => {startPreview: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "iterative" as const,})),getPreviewStatus: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "iterative" as const,})),guidance: testMcpGuidance,});@@ -5784,7 +5791,7 @@ describe("project session mcp adapter", () => {},})).rejects.toThrow(- "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, or imageDomains."+ "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, mode, or imageDomains.");});@@ -5993,6 +6000,7 @@ describe("project session mcp adapter", () => {url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "iterative" as const,};});@@ -6000,10 +6008,12 @@ describe("project session mcp adapter", () => {url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "iterative" as const,}));const stopPreview = vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: false,+ mode: "iterative" as const,}));const adapter = createProjectSessionMcpCore({operations: publicMcpOperations,@@ -6057,15 +6067,18 @@ describe("project session mcp adapter", () => {url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "iterative",});expect(status.structuredContent.data).toEqual({url: "http://127.0.0.1:5173/",pid: 123,running: true,+ mode: "iterative",});expect(stopped.structuredContent.data).toEqual({url: "http://127.0.0.1:5173/",running: false,+ mode: "iterative",});expect(index.structuredContent.data).toEqual(expect.objectContaining({@@ -6985,10 +6998,12 @@ describe("project session mcp adapter", () => {startPreview: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "iterative" as const,})),getPreviewStatus: vi.fn(async () => ({url: "http://127.0.0.1:5173/",running: true,+ mode: "iterative" as const,})),captureScreenshot: vi.fn(async () => ({output: "current.png",diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 95cb7f3bcc..d999eee67e 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -40,6 +40,12 @@ import {type ScreenshotWaitUntil,} from "./visual/screenshot-browser";import type { ScreenshotDiffResult } from "./visual/screenshot-diff";+import {+ projectPreviewModes,+ projectPreviewSources,+ type ProjectPreviewMode,+ type ProjectPreviewSource,+} from "./visual/preview";import { Server } from "@modelcontextprotocol/sdk/server/index.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";@@ -127,6 +133,26 @@ export type McpErrorCodeResolver = (error: unknown) => string | undefined;export type McpTransport = Transport;type McpLogLevel = "info" | "error";+export const projectSessionPreviewSources = projectPreviewSources;+export type ProjectSessionPreviewSource = ProjectPreviewSource;++export const projectSessionPreviewModes = projectPreviewModes;+export type ProjectSessionPreviewMode = ProjectPreviewMode;++type ProjectSessionScreenshotNavigation = {+ requestedUrl: string;+ finalUrl: string;+ status?: number;+ statusText?: string;+ mimeType?: string;+ redirects: string[];+ documentReadyState: string;+ generatedSiteRootPresent: boolean;+ projectId?: string;+ projectVersion?: number;+ layoutStable: boolean;+};+export type ProjectSessionScreenshotInput = {url?: string;baseUrl?: string;@@ -135,7 +161,8 @@ export type ProjectSessionScreenshotInput = {host?: string;port?: number;imageDomains?: string[];- source?: "local" | "session";+ source?: ProjectSessionPreviewSource;+ mode?: ProjectSessionPreviewMode;viewport: {width: number;height: number;@@ -166,6 +193,14 @@ export type ProjectSessionScreenshotResult = {fullPage: boolean;elapsedMs: number;warnings: readonly string[];+ previewMode?: ProjectSessionPreviewMode;+ renderedProjectId?: string;+ renderedProjectVersion?: number;+ lifecycleTimings?: {+ previewRefreshMs: number;+ captureMs: number;+ totalMs: number;+ };timings?: {wallMs: number;targetSetupMs: number;@@ -177,29 +212,9 @@ export type ProjectSessionScreenshotResult = {artifactWriteMs: number;targetCleanupMs: number;};- navigation?: {- requestedUrl: string;- finalUrl: string;- status?: number;- statusText?: string;- mimeType?: string;- redirects: string[];- documentReadyState: string;- generatedSiteRootPresent: boolean;- layoutStable: boolean;- };+ navigation?: ProjectSessionScreenshotNavigation;layout?: {- navigation?: {- requestedUrl: string;- finalUrl: string;- status?: number;- statusText?: string;- mimeType?: string;- redirects: string[];- documentReadyState: string;- generatedSiteRootPresent: boolean;- layoutStable: boolean;- };+ navigation?: ProjectSessionScreenshotNavigation;documentType?: string;viewportWidth: number;viewportHeight: number;@@ -283,14 +298,16 @@ type InstallOcr = () => Promise<ProjectSessionInstallOcrResult>;export type ProjectSessionPreviewInput = {host?: string;port?: number;- source?: "local" | "session";+ source?: ProjectSessionPreviewSource;imageDomains?: string[];+ mode?: ProjectSessionPreviewMode;};export type ProjectSessionPreviewResult = {url: string;pid?: number;running: boolean;+ mode: ProjectSessionPreviewMode;};type StartPreview = (@@ -341,6 +358,16 @@ const isScreenshotBrowser = (value: unknown): value is ScreenshotBrowser =>typeof value === "string" &&screenshotBrowserChoices.includes(value as ScreenshotBrowser);+const isProjectSessionPreviewSource = (+ value: unknown+): value is ProjectSessionPreviewSource =>+ projectSessionPreviewSources.some((source) => source === value);++const isProjectSessionPreviewMode = (+ value: unknown+): value is ProjectSessionPreviewMode =>+ projectSessionPreviewModes.some((mode) => mode === value);+const getRequestParams = (request: unknown) =>isRecord(request) && isRecord(request.params) ? request.params : {};@@ -1075,7 +1102,7 @@ const getNormalizedOperationInput = (const screenshotInputSchema = {...emptyInputSchema,description:- "Capture a visual screenshot for AI vision review. Pass { url } for any absolute URL, { path } inside the same long-running MCP server after preview.start, or { baseUrl, path } to capture from an already-running preview/site without starting preview. Use repeated { path } captures to verify multiple generated-site pages.",+ 'Capture the generated site for AI vision review. For the configured project, use { path: "/" }; this refreshes the current MCP session and reloads only the generated site. Never pass a Webstudio Builder/share URL or screenshot the Builder UI. Use { url } only for an intentional standalone external site, or { baseUrl, path } for an existing generated-site server.',properties: {url: {type: "string",@@ -1160,11 +1187,18 @@ const screenshotInputSchema = {},source: {type: "string",- enum: ["local", "session"],- default: "local",+ enum: projectSessionPreviewSources,+ default: "session",description:"When screenshot needs to start/restart preview for a path, choose local for .webstudio/data.json or session for the current ProjectSession snapshot after MCP edits.",},+ mode: {+ type: "string",+ enum: projectSessionPreviewModes,+ default: "iterative",+ description:+ "Iterative keeps one development server and browser alive while reloading after MCP edits. Production performs a full generated build and is intended for audits and release-like verification.",+ },host: {type: "string",default: "127.0.0.1",@@ -1397,7 +1431,7 @@ const installOcrInputSchema = {const previewInputSchema = {...emptyInputSchema,description:- "Regenerate local project files when needed, build them, and start or inspect a long-lived production-like generated-site preview server for visual verification.",+ "Start or refresh the generated-site preview. Iterative mode is the default for repeated MCP edit and screenshot cycles: it keeps one server alive, regenerates the current session, and uses normal page reloads without HMR. Use production mode for release-like audits.",properties: {host: {type: "string",@@ -1409,11 +1443,16 @@ const previewInputSchema = {},source: {type: "string",- enum: ["local", "session"],- default: "local",+ enum: projectSessionPreviewSources,+ default: "session",description:"Project data source for generated preview: local uses .webstudio/data.json; session materializes the current ProjectSession snapshot first, which is the right choice after MCP mutations.",},+ mode: {+ type: "string",+ enum: projectSessionPreviewModes,+ default: "iterative",+ },imageDomains: {type: "array",description:@@ -2064,8 +2103,9 @@ const previewDataSchema = {url: { type: "string" },pid: { type: "integer" },running: { type: "boolean" },+ mode: { type: "string", enum: projectSessionPreviewModes },},- required: ["url", "running"],+ required: ["url", "running", "mode"],additionalProperties: false,} as const satisfies InputJsonSchema;@@ -2701,7 +2741,7 @@ const previewTools: readonly ProjectSessionMcpTool[] = [createProjectSessionMcpTool({name: "preview.start",description:- "Regenerate local project files when needed, build them, then start or restart a production-like generated-site preview server for fast visual verification while MCP is running.",+ "Start or refresh a generated-site preview. The iterative default keeps the server and browser alive and normally reloads the generated route after each MCP edit; production mode performs the full build used by audits.",inputSchema: previewInputSchema,outputSchema: getMcpOutputSchema(previewDataSchema),mcpExamples: getMcpExamples("preview.start"),@@ -5803,9 +5843,13 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {}}const source = input.source === undefined ? undefined : input.source;- if (source !== undefined && source !== "local" && source !== "session") {+ if (source !== undefined && isProjectSessionPreviewSource(source) === false) {throw new Error("screenshot source must be local or session.");}+ const mode = input.mode === undefined ? undefined : input.mode;+ if (mode !== undefined && isProjectSessionPreviewMode(mode) === false) {+ throw new Error("screenshot mode must be iterative or production.");+ }const host = typeof input.host === "string" ? input.host : undefined;if (host !== undefined && host.length === 0) {throw new Error("screenshot host must not be empty.");@@ -5841,10 +5885,11 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {host !== undefined ||port !== undefined ||source !== undefined ||+ mode !== undefined ||imageDomains !== undefined) {throw new Error(- "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, or imageDomains."+ "screenshot baseUrl uses an existing preview/site and cannot be combined with host, port, source, mode, or imageDomains.");}}@@ -5857,6 +5902,7 @@ const getScreenshotInput = (input: unknown): ProjectSessionScreenshotInput => {port,imageDomains,source,+ mode,viewport: { width, height },fullPage: input.fullPage === true,includeImageMetrics: input.includeImageMetrics === true,@@ -6036,9 +6082,13 @@ const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {throw new Error("preview port must be an integer between 1 and 65535.");}const source = input.source === undefined ? undefined : input.source;- if (source !== undefined && source !== "local" && source !== "session") {+ if (source !== undefined && isProjectSessionPreviewSource(source) === false) {throw new Error("preview source must be local or session.");}+ const mode = input.mode === undefined ? undefined : input.mode;+ if (mode !== undefined && isProjectSessionPreviewMode(mode) === false) {+ throw new Error("preview mode must be iterative or production.");+ }const imageDomains = input.imageDomains;if (imageDomains !== undefined &&@@ -6057,6 +6107,7 @@ const getPreviewInput = (input: unknown): ProjectSessionPreviewInput => {host,port,source,+ mode,imageDomains,};};@@ -6117,6 +6168,7 @@ type ProjectSessionMcpCoreOptions<Command extends string> = {manifest: RenderedAuditArtifactManifest) => Promise<string>;restorePoints?: ProjectSessionRestorePointHandlers;+ onProjectSessionChange?: () => void;};type ProjectSessionRestorePointHandlers = {@@ -6148,6 +6200,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({reportToolProgress,storeRenderedAuditArtifacts,restorePoints,+ onProjectSessionChange,}: ProjectSessionMcpCoreOptions<Command>) => {let session: ReturnType<CreateProjectSession> | undefined;let pendingCheckpoint: ProjectSessionMcpCheckpoint | undefined;@@ -6454,11 +6507,15 @@ export const createProjectSessionMcpCore = <Command extends string = string>({if (name === "refresh") {const session = getSession();await session.initialize();- return toCallResult(await session.refresh(getRefreshNamespaces(input)));+ const result = await session.refresh(getRefreshNamespaces(input));+ onProjectSessionChange?.();+ return toCallResult(result);}if (name === "reset-session") {const session = getSession();- return toCallResult(await session.reset());+ const result = await session.reset();+ onProjectSessionChange?.();+ return toCallResult(result);}if (name === "create-restore-point" && restorePoints !== undefined) {return toMetaResult(@@ -6835,6 +6892,7 @@ export const createProjectSessionMcpServer = async <reportLog,storeRenderedAuditArtifacts,restorePoints,+ onProjectSessionChange,onInitialized,toolHeartbeatIntervalMs = 10_000,}: Omit<ProjectSessionMcpCoreOptions<Command>, "reportToolProgress"> & {@@ -6877,6 +6935,7 @@ export const createProjectSessionMcpServer = async <guidance,storeRenderedAuditArtifacts,restorePoints,+ onProjectSessionChange,reportToolProgress: (message) => {sendLog("info", message);},diff --git a/packages/project-build/src/visual.ts b/packages/project-build/src/visual.tsindex 237a684159..2246bd753a 100644--- a/packages/project-build/src/visual.ts+++ b/packages/project-build/src/visual.ts@@ -1,2 +1,3 @@+export * from "./visual/preview";export * from "./visual/screenshot-browser";export * from "./visual/screenshot-diff";diff --git a/packages/project-build/src/visual/preview.ts b/packages/project-build/src/visual/preview.tsnew file mode 100644index 0000000000..36ad752e33--- /dev/null+++ b/packages/project-build/src/visual/preview.ts@@ -0,0 +1,5 @@+export const projectPreviewSources = ["local", "session"] as const;+export type ProjectPreviewSource = (typeof projectPreviewSources)[number];++export const projectPreviewModes = ["iterative", "production"] as const;+export type ProjectPreviewMode = (typeof projectPreviewModes)[number];