Skip to content

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.

fix: Improve MCP authoring and preview reliability (#6105)

Oleg Isonen87968f40ffb0
diff --git a/.github/workflows/visual-regression.yml b/.github/workflows/visual-regression.yml
index 6f169794ff..61a6546306 100644
--- a/.github/workflows/visual-regression.yml
+++ b/.github/workflows/visual-regression.yml
@@ -7,7 +7,7 @@ on:
pull_request:
types: [opened, synchronize, reopened, labeled]
pull_request_target:
- types: [labeled, synchronize]
+ types: [opened, synchronize, reopened, labeled]
concurrency:
# A synchronize action emits both pull_request and pull_request_target. Keep
@@ -41,6 +41,8 @@ jobs:
}
visual-regression:
+ # Same-repository PRs use the unprivileged event. Organization members'
+ # fork PRs are trusted; every other fork revision needs safe-to-deploy.
if: |
github.event_name == 'push' ||
(
@@ -53,13 +55,24 @@ jobs:
) ||
(
github.event_name == 'pull_request_target' &&
- github.event.action == 'labeled' &&
+ github.event.pull_request.head.repo.full_name != github.repository &&
(
- github.event.label.name == 'safe-to-deploy' ||
(
- github.event.label.name == 'visual-change-approved' &&
- github.event.pull_request.head.repo.full_name != github.repository &&
- contains(github.event.pull_request.labels.*.name, 'safe-to-deploy')
+ contains(fromJSON('["OWNER", "MEMBER"]'), github.event.pull_request.author_association) &&
+ (
+ github.event.action != 'labeled' ||
+ github.event.label.name == 'visual-change-approved'
+ )
+ ) ||
+ (
+ github.event.action == 'labeled' &&
+ (
+ github.event.label.name == 'safe-to-deploy' ||
+ (
+ github.event.label.name == 'visual-change-approved' &&
+ contains(github.event.pull_request.labels.*.name, 'safe-to-deploy')
+ )
+ )
)
)
)
@@ -72,6 +85,7 @@ jobs:
with:
fetch-depth: 0
ref: ${{ github.event.pull_request.head.sha || github.sha }}
+ allow-unsafe-pr-checkout: ${{ github.event_name == 'pull_request_target' }}
- uses: ./.github/actions/submodules-checkout
with:
diff --git a/docs/university/mcp.md b/docs/university/mcp.md
index 131809c103..18a3f42f7a 100644
--- a/docs/university/mcp.md
+++ b/docs/university/mcp.md
@@ -139,6 +139,7 @@ Rules:
- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.
- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools '{"tools":["insert-fragment"]}'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.
- 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.
+- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.
- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.
- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.
- 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={() => ...}`.
diff --git a/fixtures/react-router-docker/vite.config.ts b/fixtures/react-router-docker/vite.config.ts
index 482f370c3a..f843eb1b94 100644
--- a/fixtures/react-router-docker/vite.config.ts
+++ b/fixtures/react-router-docker/vite.config.ts
@@ -10,12 +10,22 @@ export default defineConfig({
hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,
},
resolve: {
- conditions: [...sourceConditions, "browser", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "browser",
+ "development|production",
+ ],
},
ssr: {
noExternal: ["nanoid"],
resolve: {
- conditions: [...sourceConditions, "node", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "node",
+ "development|production",
+ ],
},
},
});
diff --git a/fixtures/react-router-vercel/vite.config.ts b/fixtures/react-router-vercel/vite.config.ts
index 482f370c3a..f843eb1b94 100644
--- a/fixtures/react-router-vercel/vite.config.ts
+++ b/fixtures/react-router-vercel/vite.config.ts
@@ -10,12 +10,22 @@ export default defineConfig({
hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,
},
resolve: {
- conditions: [...sourceConditions, "browser", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "browser",
+ "development|production",
+ ],
},
ssr: {
noExternal: ["nanoid"],
resolve: {
- conditions: [...sourceConditions, "node", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "node",
+ "development|production",
+ ],
},
},
});
diff --git a/packages/asset-uploader/src/utils/get-asset-data.test.ts b/packages/asset-uploader/src/utils/get-asset-data.test.ts
index 64d711e745..970a69368f 100644
--- a/packages/asset-uploader/src/utils/get-asset-data.test.ts
+++ b/packages/asset-uploader/src/utils/get-asset-data.test.ts
@@ -49,6 +49,33 @@ describe("asset data overrides", () => {
});
});
+ test("keeps variable axes when upload metadata describes a static font", () => {
+ const variationAxes = {
+ wght: { name: "Weight", min: 100, default: 400, max: 900 },
+ };
+ expect(
+ applyAssetDataOverride(
+ {
+ size: 100,
+ format: "woff2",
+ meta: { family: "Detected Family", variationAxes },
+ },
+ {
+ format: "woff2",
+ meta: {
+ family: "Configured Family",
+ style: "normal",
+ weight: 400,
+ },
+ }
+ )
+ ).toEqual({
+ size: 100,
+ format: "woff2",
+ meta: { family: "Configured Family", variationAxes },
+ });
+ });
+
test("rejects unsupported metadata overrides", () => {
expect(() =>
applyAssetDataOverride(
diff --git a/packages/cli/evaluations/high-impact/agent-runner.test.ts b/packages/cli/evaluations/high-impact/agent-runner.test.ts
index 37ba17b9b3..c69059549d 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.test.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.test.ts
@@ -59,6 +59,8 @@ describe("high-impact agent runner", () => {
"call get-project-settings, list-pages, list-resources, and list-variables"
);
expect(authConstraints).toContain("call create-page exactly once");
+ expect(authConstraints).toContain("copy recipe.createResourceInput");
+ expect(authConstraints).toContain("entire create-resource tool input");
expect(authConstraints).toContain(
'"value":{"type":"string","value":"signed-out"}'
);
@@ -193,6 +195,15 @@ describe("high-impact agent runner", () => {
expect(discoveryPrompt).not.toContain("collectionItem");
expect(discoveryPrompt).toContain("Do not dry-run or plan mutations");
expect(discoveryPrompt).toContain("without reshaping its fields");
+ expect(discoveryPrompt).toContain(
+ "reuse that returned folder id for every uploaded article"
+ );
+ expect(discoveryPrompt).toContain(
+ "exactly two create-assets-resource calls"
+ );
+ expect(discoveryPrompt).toContain(
+ "wrap the one-result detail data as a zero-or-one-item array"
+ );
expect(discoveryPrompt).toContain(
'exactly once with {\\"tools\\":[\\"create-assets-resource\\"]}'
);
diff --git a/packages/cli/evaluations/high-impact/agent-runner.ts b/packages/cli/evaluations/high-impact/agent-runner.ts
index e9d00b39ce..2066178fd8 100644
--- a/packages/cli/evaluations/high-impact/agent-runner.ts
+++ b/packages/cli/evaluations/high-impact/agent-runner.ts
@@ -153,13 +153,14 @@ export const createMinimalAgentTask = (
? [
"For this fixture, meta.guide already returns the required auth discovery and authoring tool schemas. Do not call list-breakpoints because responsive styling is not required, and do not call meta.get-more-tools or any other tool discovery operation. Create exactly one scoped non-secret fixture variable and keep the required state gallery expression-free. Do not call list-variables again after creating it.",
"After meta.guide, call inspect-auth-context exactly once. Do not call get-project-settings, list-pages, list-resources, or list-variables separately.",
- 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once with {"scopeInstanceId":"<returned-account-root-id>","dataSourceName":"accountSession","resource":{"name":"Account session via server","method":"get","url":"/api/auth/session","headers":[],"searchParams":[]}}, again substituting only the returned root id. Do not set exposeAsDataSource separately, parallelize these mutations, or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.',
+ 'After the context read, call create-page exactly once. Then call create-variable exactly once with {"name":"Account preview state","scopeInstanceId":"<returned-account-root-id>","value":{"type":"string","value":"signed-out"}}, substituting only the returned root id. Keep type exactly string; do not invent a state type. Then call create-resource exactly once: copy recipe.createResourceInput from meta.guide as the entire create-resource tool input and substitute only its account root id placeholder. Do not wrap that input in another resource object. Keep name, method, url, headers, and searchParams nested under resource; never move them to the top level. Do not set exposeAsDataSource separately, parallelize these mutations, or retry failed calls. Call insert-fragment-verified only after all three succeed, using their returned ids and pagePath /account. Do not call insert-fragment or verify-bindings separately.',
'Then call verify-page-responsive exactly once with {"path":"/account","viewports":[{"width":1440,"height":900},{"width":390,"height":844}],"source":"session"}. It captures both required screenshots and runs the terminal static audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately.',
]
: []),
...(fixture.id === "markdown-references-discovery-v1"
? [
'Follow the structured recipe returned by meta.guide. Pass each complete recipe object without reshaping its fields, changing only documented id placeholders. Call meta.get-more-tools exactly once with {"tools":["create-assets-resource"]}; do not search by brief or rediscover tools later.',
+ "Create the Blog folder before uploading, and reuse that returned folder id for every uploaded article and both resource queries. Create exactly two create-assets-resource calls and exactly two insert-collection calls: one of each per page. Bind the overview Collection to the many-result overview data. For the detail Collection, wrap the one-result detail data as a zero-or-one-item array and render that item. Do not create repair or replacement resources or Collections.",
"Call each mutation in the documented workflow once as a committed mutation. Do not dry-run or plan mutations. If any tool fails, stop immediately and report the failure; never retry it, repair it with repeated mutations, or continue to verification.",
"Do not call verify-page-responsive until both Collections succeed. Then call it exactly once for /blog and exactly once for /blog/aurora-trails. Stop without retrying if either verification fails.",
]
diff --git a/packages/cli/evaluations/high-impact/evaluation-regression.test.ts b/packages/cli/evaluations/high-impact/evaluation-regression.test.ts
index cb424b3bbc..1d3ec22191 100644
--- a/packages/cli/evaluations/high-impact/evaluation-regression.test.ts
+++ b/packages/cli/evaluations/high-impact/evaluation-regression.test.ts
@@ -75,7 +75,14 @@ describe("evaluation regression comparison", () => {
metrics: {
...baseline.metrics,
durationMs: 1_100,
- tokens: { ...baselineTokens, total: 1_600 },
+ tokens: {
+ ...baselineTokens,
+ input: 1_400,
+ cachedInput: 400,
+ uncachedInput: 1_000,
+ output: 600,
+ total: 2_000,
+ },
},
});
const comparison = compareEvaluationResult(current, baseline);
@@ -88,20 +95,22 @@ describe("evaluation regression comparison", () => {
current: 1_100,
}),
expect.objectContaining({
- metric: "metrics.tokens.total",
- baseline: 1_000,
- current: 1_600,
+ metric: "metrics.tokens.output",
+ baseline: 200,
+ current: 600,
}),
])
);
expect(comparison.regressions).toEqual([
expect.objectContaining({
- metric: "metrics.tokens.total",
- allowed: 1_500,
+ metric: "metrics.tokens.output",
+ allowed: 300,
}),
]);
const noisyCurrent = structuredClone(baseline);
+ noisyCurrent.metrics.tokens!.input = 1_200;
+ noisyCurrent.metrics.tokens!.cachedInput = 800;
noisyCurrent.metrics.tokens!.total = 1_400;
expect(compareEvaluationResult(noisyCurrent, baseline)).toMatchObject({
status: "passed",
@@ -277,6 +286,10 @@ describe("evaluation regression comparison", () => {
if (regressionCurrent.metrics.tokens === undefined) {
throw new Error("Expected token metrics");
}
+ regressionCurrent.metrics.tokens.input = 1_800;
+ regressionCurrent.metrics.tokens.cachedInput = 400;
+ regressionCurrent.metrics.tokens.uncachedInput = 1_400;
+ regressionCurrent.metrics.tokens.output = 1_000;
regressionCurrent.metrics.tokens.total = 2_000;
const regressed = compareEvaluationResult(
regressionCurrent,
@@ -357,7 +370,14 @@ describe("evaluation regression comparison", () => {
...result,
metrics: {
...result.metrics,
- tokens: { ...result.metrics.tokens!, total },
+ tokens: {
+ ...result.metrics.tokens!,
+ input: total,
+ cachedInput: 0,
+ uncachedInput: total,
+ output: total,
+ total,
+ },
},
};
};
diff --git a/packages/cli/evaluations/high-impact/evaluation-regression.ts b/packages/cli/evaluations/high-impact/evaluation-regression.ts
index a7a3730b36..bd054ecb41 100644
--- a/packages/cli/evaluations/high-impact/evaluation-regression.ts
+++ b/packages/cli/evaluations/high-impact/evaluation-regression.ts
@@ -76,8 +76,8 @@ export const isAggregateTokenBaselineNonRegressed = (
if (baseline === undefined) {
continue;
}
- const currentTokens = result.metrics.tokens?.total;
- const baselineTokens = baseline.metrics.tokens?.total;
+ const currentTokens = result.metrics.tokens?.output;
+ const baselineTokens = baseline.metrics.tokens?.output;
if (currentTokens === undefined || baselineTokens === undefined) {
return false;
}
@@ -89,7 +89,7 @@ export const isAggregateTokenBaselineNonRegressed = (
};
const gatedMetricPaths = new Set([
- "metrics.tokens.total",
+ "metrics.tokens.output",
"metrics.mcpCatalog.latestResponseBytes",
"metrics.mcpCatalog.latestInputSchemaBytes",
"metrics.toolCalls.total",
@@ -171,7 +171,7 @@ export const compareEvaluationResult = (
continue;
}
const regressionPercent =
- metric === "metrics.tokens.total"
+ metric === "metrics.tokens.output"
? maxTokenRegressionPercent
: maxMetricRegressionPercent;
const relativeIncrease = Math.floor(
diff --git a/packages/cli/src/cli.test.ts b/packages/cli/src/cli.test.ts
index a19f0da063..bbc8f15c6a 100644
--- a/packages/cli/src/cli.test.ts
+++ b/packages/cli/src/cli.test.ts
@@ -132,6 +132,17 @@ describe("registerCommands", () => {
"single-op-call",
"meta.get_more_tools",
]);
+ expect(
+ getTopLevelMcpToolForwardArgs([
+ "download-asset",
+ '{"assetId":"asset-id"}',
+ ])
+ ).toEqual([
+ "mcp",
+ "single-op-call",
+ "download-asset",
+ '{"assetId":"asset-id"}',
+ ]);
expect(
getTopLevelMcpToolForwardArgs([
"insert-fragment",
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 2ee6254c4f..3be54c117b 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -76,7 +76,16 @@ const topLevelCommandNames: ReadonlySet<string> = new Set([
]);
const mcpOnlyToolNames = new Set(
- listProjectSessionMcpTools(publicApiOperations)
+ listProjectSessionMcpTools(publicApiOperations, {
+ includeImport: true,
+ includeDownloadAsset: true,
+ includeScreenshot: true,
+ includeResponsiveScreenshot: true,
+ includeScreenshotDiff: true,
+ includeInstallOcr: true,
+ includePreview: true,
+ includeRestorePoints: true,
+ })
.map((tool) => tool.name)
.filter((name) => topLevelCommandNames.has(name) === false)
);
diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.ts
index 651c6d388b..7583675a8a 100644
--- a/packages/cli/src/commands/mcp.test.ts
+++ b/packages/cli/src/commands/mcp.test.ts
@@ -85,6 +85,24 @@ afterEach(async () => {
);
});
+const getArraySchemasWithoutItems = (schema: unknown): unknown[] => {
+ if (schema === null || typeof schema !== "object") {
+ return [];
+ }
+ if (Array.isArray(schema)) {
+ return schema.flatMap(getArraySchemasWithoutItems);
+ }
+ const object = schema as Record<string, unknown>;
+ return [
+ ...(object.type === "array" &&
+ object.items === undefined &&
+ object.prefixItems === undefined
+ ? [object]
+ : []),
+ ...Object.values(object).flatMap(getArraySchemasWithoutItems),
+ ];
+};
+
test("documents MCP stdio startup and discovery tools", () => {
const yargs = {
command: vi.fn(() => yargs),
@@ -1023,3 +1041,12 @@ test("exposes asset content editing through MCP discovery", () => {
},
});
});
+
+test("exposes a client-valid update-props schema", () => {
+ const tool = listProjectSessionMcpTools(publicApiOperations).find(
+ ({ name }) => name === "update-props"
+ );
+
+ expect(tool).toBeDefined();
+ expect(getArraySchemasWithoutItems(tool?.inputSchema)).toEqual([]);
+});
diff --git a/packages/cli/src/commands/preview.test.ts b/packages/cli/src/commands/preview.test.ts
index 6bed0dfd6a..7d24dad6f2 100644
--- a/packages/cli/src/commands/preview.test.ts
+++ b/packages/cli/src/commands/preview.test.ts
@@ -1,5 +1,14 @@
import { randomUUID } from "node:crypto";
-import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
+import {
+ mkdir,
+ mkdtemp,
+ readFile,
+ realpath,
+ lstat,
+ rm,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { chdir, cwd } from "node:process";
@@ -391,7 +400,10 @@ test("does not relink generated preview dependencies when already present", asyn
await ensurePreviewDependencies("/tmp/project/.webstudio/preview", {
access,
lstat: vi.fn(async () => ({ isSymbolicLink: () => true })) as never,
- readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ readFile: vi.fn(
+ async () =>
+ '{"dependencies":{"@webstudio-is/sdk":"0.0.0-webstudio-version"}}'
+ ),
symlink,
platform: "linux",
});
@@ -416,7 +428,10 @@ test("uses junctions for generated preview dependencies on windows", async () =>
lstat: vi.fn(async () => {
throw Object.assign(new Error("missing"), { code: "ENOENT" });
}),
- readFile: vi.fn(async () => '{"dependencies":{"vite":"1.0.0"}}'),
+ readFile: vi.fn(
+ async () =>
+ '{"dependencies":{"@webstudio-is/sdk":"0.0.0-webstudio-version"}}'
+ ),
symlink,
platform: "win32",
});
@@ -466,6 +481,62 @@ test("installs isolated generated dependencies when the cli does not ship them",
);
});
+test("replaces a parent workspace dependency link for published previews", async () => {
+ const parentDir = await mkdtemp(
+ join(tmpdir(), "webstudio-parent-workspace-")
+ );
+ const previewProjectDir = join(parentDir, "task", ".webstudio", "preview");
+ const parentNodeModules = join(parentDir, "node_modules");
+ const packagePath = join(
+ "@webstudio-is",
+ "sdk-components-react-router",
+ "package.json"
+ );
+ const execFile = vi.fn(async (_command, args: string[]) => {
+ expect(args).toContain("--workspaces=false");
+ await mkdir(join(previewProjectDir, "node_modules", packagePath, ".."), {
+ recursive: true,
+ });
+ await writeFile(
+ join(previewProjectDir, "node_modules", packagePath),
+ '{"version":"0.289.0"}'
+ );
+ return { stdout: "", stderr: "" };
+ });
+
+ try {
+ await mkdir(join(parentNodeModules, packagePath, ".."), {
+ recursive: true,
+ });
+ await writeFile(
+ join(parentNodeModules, packagePath),
+ '{"version":"0.0.0-webstudio-version"}'
+ );
+ await mkdir(previewProjectDir, { recursive: true });
+ await writeFile(
+ join(previewProjectDir, "package.json"),
+ '{"dependencies":{"@webstudio-is/sdk-components-react-router":"0.289.0"}}'
+ );
+ await symlink(
+ parentNodeModules,
+ join(previewProjectDir, "node_modules"),
+ "dir"
+ );
+
+ await ensurePreviewDependencies(previewProjectDir, { execFile });
+
+ expect(await realpath(join(previewProjectDir, "node_modules"))).not.toBe(
+ await realpath(parentNodeModules)
+ );
+ expect(
+ (await lstat(join(previewProjectDir, "node_modules"))).isSymbolicLink()
+ ).toBe(false);
+ expect(execFile).toHaveBeenCalledOnce();
+ } finally {
+ await rm(parentDir, { recursive: true, force: true });
+ }
+});
+
test("reuses the npm cli that launched webstudio on windows", async () => {
let installed = false;
const execFile = vi.fn(async () => {
diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.ts
index 9e654fecab..31608da722 100644
--- a/packages/cli/src/commands/preview.ts
+++ b/packages/cli/src/commands/preview.ts
@@ -240,6 +240,9 @@ export const ensurePreviewDependencies = async (
...packageJson.dependencies,
...packageJson.devDependencies,
};
+ const usesDevelopmentDependencies = Object.values(
+ requiredDependencies
+ ).includes(developmentCliVersion);
const manifestHash = createHash("sha256")
.update(JSON.stringify(requiredDependencies))
.digest("hex");
@@ -260,6 +263,7 @@ export const ensurePreviewDependencies = async (
const previewNodeModulesStat = await operations.lstat(previewNodeModules);
if (
previewNodeModulesStat.isSymbolicLink() &&
+ usesDevelopmentDependencies &&
(await hasRequiredDependencies(previewNodeModules))
) {
return;
@@ -280,14 +284,16 @@ export const ensurePreviewDependencies = async (
// Continue with the CLI dependency tree or an isolated install.
}
- for (const cliNodeModules of cliNodeModulesCandidates) {
- if (await hasRequiredDependencies(cliNodeModules)) {
- await operations.symlink(
- cliNodeModules,
- previewNodeModules,
- operations.platform === "win32" ? "junction" : "dir"
- );
- return;
+ if (usesDevelopmentDependencies) {
+ for (const cliNodeModules of cliNodeModulesCandidates) {
+ if (await hasRequiredDependencies(cliNodeModules)) {
+ await operations.symlink(
+ cliNodeModules,
+ previewNodeModules,
+ operations.platform === "win32" ? "junction" : "dir"
+ );
+ return;
+ }
}
}
@@ -298,6 +304,7 @@ export const ensurePreviewDependencies = async (
"--no-fund",
"--package-lock=false",
"--loglevel=error",
+ "--workspaces=false",
];
const invocation = getNpmInvocation(installArgs, operations);
diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.ts
index 4a986c3ec7..5f183a9cf2 100644
--- a/packages/cli/src/docs.generated.ts
+++ b/packages/cli/src/docs.generated.ts
@@ -8,7 +8,7 @@ export const cliDocs = {
"manual-llm":
'# Webstudio CLI Manual for LLMs\n\nUse this order. Stop only when a command returns ok:false.\n\nIf you are inside the Webstudio monorepo, the first command discovery should use\nthe local CLI exactly as `node packages/cli/local.js ...` from the repo root. Do\nnot use `packages/cli/bin.js` for local source-tree work; it is the packaged\nbuild entry and may use stale built output. Do not use `pnpm exec webstudio`,\n`pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can\nresolve an older binary.\n\nFor delegated design-system or “use every component” tasks, skip the generic warm-up sequence and start with exactly one MCP command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`. Report that returned checkpoint to the parent/user and stop until continued.\n\n## Use MCP locally or optionally connect a client\n\nDo not install, register, or connect an MCP server merely because the user asks\nyou to edit a Webstudio project. If Webstudio MCP tools are already available,\nuse them. If you have shell access, use the local CLI shortcuts such as\n`webstudio meta.index` and `webstudio list-pages`; they expose the same project\noperations without changing client configuration or restarting the app.\n\nOnly when the user explicitly asks for persistent native MCP integration, run\nthe command for their client:\n\n- Claude Code: `webstudio connect claude`\n- Codex: `webstudio connect codex`\n- Cursor: `webstudio connect cursor`\n- VS Code or GitHub Copilot: `webstudio connect vscode`\n\nRun project operations from the linked project root. If the folder is not\nlinked, ask for an editable Builder share link and run\n`webstudio init --link <share-link> --json`. You can then use local CLI\nshortcuts immediately. Do not run `webstudio sync`, `webstudio connect`, or\nrestart the app unless the user specifically wants native MCP registration:\nMCP reads and edits the latest editable Builder build directly, including for\nprojects that have never been published. Treat the share link as a credential\nand do not include it in committed files, logs, screenshots, or issue reports.\n\nThe optional `connect` command verifies project access before changing client configuration. For\nClaude Code, Cursor, and VS Code it safely merges the `webstudio` server into\nthe client\'s project configuration. For Codex it runs both `codex mcp add` and\n`codex mcp get webstudio`; do not repeat those commands separately. Follow the\nreload, restart, or approval instruction printed by `connect`, then verify the\nloaded MCP connection by asking the client to use Webstudio MCP and list the\nproject pages. Use `--print` only to inspect the generated setup without\nchanging configuration or requiring project access.\n\n## Always\n\n1. webstudio permissions --json\n2. For bounded shell workflows, call MCP tools directly through the CLI shortcut, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and useful when you need to make the MCP boundary obvious. Use `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for multiple calls in one shared CLI session. Use a normal JSON file path for large batches. Use long-running `webstudio mcp` only when your environment is a real MCP client. Do not manually send raw JSON-RPC to `webstudio mcp` from a shell or PTY.\n3. Read MCP `meta.index`, for example `webstudio meta.index`.\n4. Use focused MCP calls with concrete JSON: `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.coverage-plan`, `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"}\'`.\n5. Read overview resources `webstudio://project/tools-overview` or `webstudio://project/components-overview` when useful. Read full resources `webstudio://project/tools` or `webstudio://project/components` only when focused tools are insufficient.\n6. Pick focused MCP read tool.\n7. Pick semantic MCP write tool.\n\nUse `webstudio schema mcp` for a compact MCP tool overview. Add `--verbose` only when exact input schemas for all tools are truly needed; otherwise prefer focused `meta.get-more-tools` and `components.*` calls.\n\nRun these commands from the linked project root. Use the MCP startup status line\'s absolute root for local files; write temporary scripts and artifacts under `<project root>/.temp`, not under a parent workspace.\n\nMonorepo quick path for a simple styled section:\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 --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the readable payload in `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "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>"\n}\n```\n\nSingle quotes inside the JSX keep the JSON valid without backslash-escaped attributes. The same local shortcut form is shorter and 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 --input-file .temp/insert-fragment.json --dry-run\n```\n\nFor this simple path, 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 to get the target `parentInstanceId`.\n\nWhen authoring JSX for `insert-fragment`, use Webstudio component helpers and Webstudio style syntax. Use `ws:style={css\\`...\\`}`for Webstudio-native CSS. For simpler cases, use React-style object syntax such as`style={{ padding: 24 }}`. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX 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\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For 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- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If 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 Discord `#help` at https://wstd.us/community. Give them 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- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. 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, report that command/result, then 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 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 `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get-more-tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\n- Page `status` accepts a fixed HTTP status code as a number from 200 through 599, for example `302`. For a dynamic status, pass JavaScript expression code such as `system.status`.\n- Page metadata update example: use `update-page` with `{"pageId":"page-id","values":{"title":"Pricing | Acme","meta":{"description":"Plans for teams"}}}`.\n- Draft a page with `update-page` and `{"pageId":"page-id","values":{"isDraft":true}}`. It remains editable and previewable but is omitted from every publish target, including staging, and from sitemap output.\n- Stage a draft page for a future publish with `{"pageId":"page-id","values":{"isDraft":false}}`. This clears draft state but does not deploy the site. The home page and `/*` catch-all page cannot be drafts.\n- Resource `url` accepts plain fixed URLs and paths. For computed URLs, pass JavaScript expression code such as `"https://api.example.com/items?tag=" + filters.tag`. Resource header values, search parameter values, and text bodies accept expressions for dynamic values; for fixed text, use `{ "type": "literal", "value": "application/json" }`.\n- Resource update example: use `update-resource` with `{"resourceId":"resource-id","values":{"url":"https://api.example.com/items"}}`.\n- Assets is one system resource that always executes a structured query. `result:"many"` returns the existing ID-keyed collection shape and is the backward-compatible default. `result:"one"`, `result:"first"`, and `result:"last"` return one direct item or `null`; first and last require explicit sorting. `create-assets-resource` without `query` uses the default URL and optional image-dimensions output.\n- For a Markdown-backed blog, create exactly two Builder page definitions: a fixed `/blog` overview and one `/blog/:slug` detail page. Both pages load content through Assets resources. Never create one Builder page per post or duplicate Markdown content into static page structures. Read `get-asset-field-catalog`, validate each structured query with `validate-asset-query`, then call `create-assets-resource` or `update-assets-resource`. Set `values.query:null` to restore the default query.\n- Optimize every explicit Assets query for the deployed content-database size. Use `output.mode:"fields"` and select only fields that are actually rendered or otherwise required by the query. Keep `includeMetadata:false` unless the rendered value needs file metadata; diagnostics are returned separately. Do not use `output.mode:"all"` as a convenience default.\n- Every reachable Assets data source contributes to the shared database. Keep one final resource per rendered query. Update an existing scoped resource instead of creating a placeholder, preview copy, or repair replacement, and remove obsolete duplicate resources and data sources.\n- Make a bounded overview fully static: use literal values for its filters, limit, and offset, add a deterministic ID tie-breaker to its sort, and use `content.mode:"none"`. This lets compilation materialize the small overview result instead of retaining overview-only fields across every candidate article. Reserve runtime expressions for values that are truly dynamic, such as `system.params.slug` on the detail route.\n- Query Markdown files directly and use `content.mode:"markdown-body-ref"` when rendering their bodies. The published database keeps only metadata and document references, filters and paginates first, and fetches the selected Markdown bodies from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding Markdown.\n- `full` and bounded `range` request embedded file bytes. Use them only when the caller explicitly requires the complete source or a byte range.\n- Deferred Markdown bodies exclude frontmatter and resolve conventional relative links and images such as `../images/hero.png` to matching Assets. Markdown Embed permits sanitized figures, audio, video, and iframes, but removes scripts, inline event handlers, and unsafe URLs.\n- For `result:"many"`, Assets expose an ID-keyed map at `<dataSourceName>.data` and `totalCount`/`hasMore` at `<dataSourceName>.meta`; bind a listing Collection to `posts.data`. Single-result modes expose the selected item or `null` directly at `<dataSourceName>.data`, always include its `id`, and expose `totalCount` in meta. Bind detail components and page settings directly from expressions such as `post.data.properties.title`, `post.data.content.text`, and `post.data ? 200 : 404` without a Collection.\n- Use `preview-asset-query` with concrete values before binding expressions in the saved resource. Inspect `__diagnostics__.query` for the temporary query-only footprint and `__diagnostics__.database` for the merged database built from all reachable Assets queries. Only `database.usedBytes` counts toward `database.maxBytes`; query sizes are not separate allowances and must not be summed. Compare `usedBytes`, `unboundedBytes`, and `truncated` within both scopes. A finished Markdown blog must include every source document without truncation, contain no embedded Markdown bodies, and retain only the intended materialized overview query. When merged usage approaches the limit, remove duplicate reachable resources first, then unused output fields, then narrow candidate files. Inspect saved mode and configuration with `list-assets-resources` or `get-assets-resource`; shared index maintenance is automatic.\n- Data variable values support `string`, `number`, `boolean`, and `json`. Use `json` for all arrays, objects, filters, and nested data.\n- Parameters are internal scoped runtime values from pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Public tools should preserve existing parameter records and may reference documented context values such as `system` in expressions where they are already in scope.\n- Use scoped resources for read data. A GET resource created with `scopeInstanceId`/`dataSourceName` defaults to `exposeAsDataSource:true`, becomes a scoped resource data variable, is generated into the page resource `data` map, and may be loaded while rendering the page. Read the loaded resource result from its wrapper, usually `.data`.\n- Use prop-bound resources for actions. A resource created without `scopeInstanceId` and bound to a component prop such as Form `action` with `bind-props` and `binding.type: "resource"` becomes an action resource in the page resource `action` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and anything that should run only from an explicit form/action flow.\n- POST, PUT, and DELETE resources default to `exposeAsDataSource:false`, even with a scope. Set `exposeAsDataSource:true` only for an intentional render-time read such as a GraphQL POST query; provide `scopeInstanceId` and inspect the returned warning. Set it to `false` during `update-resource` to detach existing render-time exposure.\n- For dynamic resource query parameters prefer `searchParams`, for example `{"name":"tag","value":"filters.tag"}`. Use `{"type":"literal","value":"website"}` for fixed request text. Header values can use an expression such as `"Bearer " + auth.token`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Property and index access are made safe automatically, so write direct access without optional chaining. Use nullish coalescing when a fallback is required.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',
"manual-mcp":
- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits 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`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\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>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build 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- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. 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\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
+ '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with a shell-capable agent, it can use the local CLI\ndirectly. Native MCP client registration is optional. Give the editable Builder\nshare link only when the trusted agent asks for it. Treat the share link as a\ncredential: do not include it in committed files, screenshots, logs, or issue\nreports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Check capabilities with `webstudio permissions --json`.\n3. Use shortcut calls such as `webstudio meta.index` and `webstudio insert-fragment \'<json>\' --dry-run` for individual MCP tool calls. Use the explicit equivalent `webstudio mcp single-op-call <tool> \'<json>\'` when you need to force the MCP path, or `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` for bounded multi-call workflows. Use `webstudio mcp run .temp/mcp-calls.json` for large batches.\n4. Start discovery with `meta.index`, then call focused tools with concrete JSON, for example `webstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'`.\n\nDo not run `webstudio sync`, install an MCP server, change client configuration,\nor restart the app for this local CLI workflow.\n\nWhen the user explicitly wants persistent native MCP integration, run\n`webstudio connect claude`, `webstudio connect codex`, `webstudio connect\ncursor`, or `webstudio connect vscode`. This optional command changes client\nconfiguration, so follow its client-specific reload or restart instruction.\nUse `--print` to inspect the generated setup without changing configuration or\nrequiring project access. For Codex, `connect` registers and verifies the server\nthrough the Codex CLI. Before changing client configuration, `connect` verifies\nthat the saved project endpoint is reachable and its credential is accepted.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits 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`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get-more-tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\n### Tool name convention\n\nMCP tool names are opaque strings, not JavaScript property access. A dot separates a namespace from its tool name, and every segment uses lowercase kebab-case. For example, `components.coverage-insert-next` is the `coverage-insert-next` tool in the `components` namespace. Pass the complete name as one CLI argument: `webstudio components.coverage-insert-next`. Batch `mcp run` calls also accept the underscore form advertised by MCP protocol discovery, such as `components_coverage_insert_next`. Unknown names return near matches and direct you to `meta.index`.\n\n### Readable fragment inputs\n\nPrefer `--input-file` for JSX so JSON and shell quoting do not obscure the fragment. For example, save this as `.temp/insert-fragment.json`:\n\n```json\n{\n "parentInstanceId": "root-id",\n "fragment": "<ws.element ws:tag=\'section\' ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag=\'h2\'>Northstar Product OS</ws.element><ws.element ws:tag=\'p\'>Reusable patterns for teams.</ws.element></ws.element>"\n}\n```\n\nThen run `webstudio insert-fragment --input-file .temp/insert-fragment.json`. Single quotes inside the JSX keep the JSON valid and readable without backslash-escaped attributes.\n\nWrite and review larger fragments as JSX before placing them in the `fragment` field. Common patterns:\n\n```tsx\n<ws.element\n ws:tag="section"\n style={{ padding: 32, borderRadius: 16 }}\n>\n <ws.element ws:tag="h2">Operations Console</ws.element>\n <ws.element ws:tag="p">\n React-style object styles become editable Webstudio styles.\n </ws.element>\n</ws.element>\n\n<ws.element\n ws:tag="section"\n ws:tokens={[token("accent", css`color: #0f766e;`)]}\n>\n <ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </ws.element>\n</ws.element>\n\n<ws.element ws:tag="section">\n <radix.Switch>\n <radix.SwitchThumb />\n </radix.Switch>\n</ws.element>\n```\n\nRules:\n\n- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.\n- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools \'{"tools":["insert-fragment"]}\'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.\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- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.\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>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build 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- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. 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\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get-more-tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, and JSON variables. Arrays use JSON.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- Read `meta.session.commitStatus` before interpreting durability. Read-only results report `not-applicable` and retain `committed:false` for compatibility; dry-run plans report `planned`; failed mutations report `failed`; no-op mutations report `unchanged`; durable mutations report `committed` with `meta.session.committed:true`.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP argument examples\n\nExamples below show meaningful argument combinations. Tool schemas are the\nsource of truth. For tools with no required arguments, pass `{}`.\n\n{{mcpArgumentExampleIndex}}\n\n{{contentEngineReferenceMarkdown}}\n\n## Screenshot Verification\n\n{{screenshotVerificationSummary}}\n',
"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 --input-file .temp/insert-fragment.json --dry-run\n```\n\nSave the input as `.temp/insert-fragment.json`; use single quotes for JSX attributes so the JSON needs no backslash escaping:\n\n```json\n{\n "parentInstanceId": "parent-id",\n "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>"\n}\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 --input-file .temp/insert-fragment.json --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\nWhen `report-issue` is available, use it when the user explicitly asks to report a problem. Also use it automatically after a Webstudio-controlled tool crash, hang, malformed result, misleading success, repeated failure of the same documented operation, failed documented recovery, or required undocumented workaround. Do not automatically report expected confirmation/checkpoint flow, a clearly explained invalid input, missing permissions, `PROJECT_SESSION_BUSY`, a recovered version conflict, rate limiting, cancellation, or an offline environment. Write a complete anonymous report with the generalized user story, attempted workflow, expected behavior, actual result, recovery attempts, impact, technical context, acceptance criteria, exact model identifier, and reasoning effort. Never include names, usernames, emails, phone numbers, organizations, project or resource ids, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, exact unique values, or raw contextual tool data.\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":
diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.md
index 666ec04e7c..77bada0c01 100644
--- a/packages/cli/src/docs/manual-mcp.md
+++ b/packages/cli/src/docs/manual-mcp.md
@@ -121,6 +121,7 @@ Rules:
- Inside the Webstudio monorepo, replace `webstudio` in the examples above with `node packages/cli/local.js`, for example `node packages/cli/local.js meta.index`.
- For a simple authored/styled section, run `meta.index`, then `meta.get-more-tools '{"tools":["insert-fragment"]}'`, then `insert-fragment`. Do not grep source files, dump full MCP resources, or write parser scripts first.
- 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.
+- `css` templates accept declarations and `@media` rules. Do not put selectors or unsupported at-rules such as `@keyframes` inside them. `animation` is the component namespace for JSX such as `<animation.AnimateChildren>`; it is not a callable CSS keyframes helper.
- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.
- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.
- 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={() => ...}`.
diff --git a/packages/cli/src/prebuild.test.ts b/packages/cli/src/prebuild.test.ts
index e1096192e5..43a33e14f1 100644
--- a/packages/cli/src/prebuild.test.ts
+++ b/packages/cli/src/prebuild.test.ts
@@ -21,6 +21,7 @@ import {
type DefaultTreeAdapterMap,
} from "parse5";
import { build } from "esbuild";
+import { loadConfigFromFile } from "vite";
import { bundleVersion } from "@webstudio-is/protocol";
import type { Asset, Instance, Prop } from "@webstudio-is/sdk";
import {
@@ -87,6 +88,57 @@ const runGeneratedCommand = async (
});
};
+const linkPackagedPreviewDependencies = async () => {
+ const sourceNodeModules = join(originalCwd, "node_modules");
+ const targetNodeModules = join(tempDir, "node_modules");
+ const webstudioScope = "@webstudio-is";
+ const routerPackage = "sdk-components-react-router";
+
+ await mkdir(targetNodeModules, { recursive: true });
+ for (const entry of await readdir(sourceNodeModules)) {
+ if (entry === webstudioScope) {
+ continue;
+ }
+ await symlink(
+ join(sourceNodeModules, entry),
+ join(targetNodeModules, entry),
+ "dir"
+ );
+ }
+
+ const targetScope = join(targetNodeModules, webstudioScope);
+ await mkdir(targetScope, { recursive: true });
+ for (const entry of await readdir(join(sourceNodeModules, webstudioScope))) {
+ if (entry === routerPackage) {
+ continue;
+ }
+ await symlink(
+ join(sourceNodeModules, webstudioScope, entry),
+ join(targetScope, entry),
+ "dir"
+ );
+ }
+
+ const sourcePackage = join(originalCwd, "..", "sdk-components-react-router");
+ const targetPackage = join(targetScope, routerPackage);
+ await mkdir(join(targetPackage, "lib"), { recursive: true });
+ const packageJson = JSON.parse(
+ await readFile(join(sourcePackage, "package.json"), "utf8")
+ ) as { exports: { ".": Record<string, string> } };
+ delete packageJson.exports["."].webstudio;
+ await writeFile(
+ join(targetPackage, "package.json"),
+ JSON.stringify(packageJson)
+ );
+ await build({
+ entryPoints: [join(sourcePackage, "src", "components.ts")],
+ outfile: join(targetPackage, "lib", "components.js"),
+ bundle: true,
+ format: "esm",
+ packages: "external",
+ });
+};
+
type Redirects = Array<{ old: string; new: string; status?: "301" | "302" }>;
type GeneratedRouteModule = {
loader: (args: { request: Request }) => Response | Promise<Response>;
@@ -1376,6 +1428,45 @@ describe("prebuild", () => {
await expectGeneratedRedirectFallback("app/routes/$.tsx");
});
+ test("builds a generated dynamic route with the packaged React Router SDK", async () => {
+ await writeSiteData(
+ createSiteData({
+ pages: [
+ {
+ id: "home",
+ name: "Home",
+ title: "Home",
+ path: "",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ {
+ id: "post",
+ name: "Post",
+ title: "Post",
+ path: "/blog/:slug",
+ rootInstanceId: "root",
+ meta: {},
+ },
+ ],
+ })
+ );
+
+ await prebuild({ assets: false, template: ["react-router"] });
+ await linkPackagedPreviewDependencies();
+ const loadedConfig = await loadConfigFromFile(
+ { command: "build", mode: "production" },
+ join(tempDir, "vite.config.ts")
+ );
+ expect(loadedConfig?.config.resolve?.conditions).toContain("import");
+ expect(loadedConfig?.config.ssr?.resolve?.conditions).toContain("import");
+ await runGeneratedCommand("react-router", ["build"]);
+
+ await expect(
+ getFilePaths(join(tempDir, "build", "server"))
+ ).resolves.not.toHaveLength(0);
+ }, 30_000);
+
test("preserves an authored catch-all page when redirects are configured", async () => {
await writeSiteData(
createSiteData({
diff --git a/packages/cli/src/preview-server.test.ts b/packages/cli/src/preview-server.test.ts
index 6372124e95..34b2b5ec76 100644
--- a/packages/cli/src/preview-server.test.ts
+++ b/packages/cli/src/preview-server.test.ts
@@ -203,7 +203,7 @@ test("runs generated project production build", async () => {
expect(spawn).toHaveBeenCalledWith("npm", ["run", "build"], {
cwd: "/tmp/preview",
stdio: "inherit",
- env: expect.objectContaining({ NODE_ENV: "production" }),
+ env: expect.objectContaining({ CI: "1", NODE_ENV: "production" }),
});
});
diff --git a/packages/cli/src/preview-server.ts b/packages/cli/src/preview-server.ts
index 9ff294148c..a37482d86d 100644
--- a/packages/cli/src/preview-server.ts
+++ b/packages/cli/src/preview-server.ts
@@ -211,6 +211,7 @@ export const runPreviewBuild = async (
stdio,
env: getPreviewEnv(cwd, {
...processEnv(),
+ CI: "1",
NODE_ENV: "production",
}),
});
diff --git a/packages/cli/templates/react-router/vite.config.ts b/packages/cli/templates/react-router/vite.config.ts
index 482f370c3a..f843eb1b94 100644
--- a/packages/cli/templates/react-router/vite.config.ts
+++ b/packages/cli/templates/react-router/vite.config.ts
@@ -10,12 +10,22 @@ export default defineConfig({
hmr: process.env.WEBSTUDIO_PREVIEW_HMR === "disabled" ? false : undefined,
},
resolve: {
- conditions: [...sourceConditions, "browser", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "browser",
+ "development|production",
+ ],
},
ssr: {
noExternal: ["nanoid"],
resolve: {
- conditions: [...sourceConditions, "node", "development|production"],
+ conditions: [
+ ...sourceConditions,
+ "import",
+ "node",
+ "development|production",
+ ],
},
},
});
diff --git a/packages/css-data/src/parse-css.test.ts b/packages/css-data/src/parse-css.test.ts
index 09229c5caf..4e4638192f 100644
--- a/packages/css-data/src/parse-css.test.ts
+++ b/packages/css-data/src/parse-css.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, test } from "vitest";
import {
camelCaseProperty,
+ hasUnsupportedCssTemplateRules,
parseClassBasedSelector,
parseCss,
parseMediaQuery,
@@ -8,6 +9,40 @@ import {
import { propertyVarTestFixtures } from "./__generated__/property-var-test-fixtures";
describe("Parse CSS", () => {
+ test("detects rules unsupported by template CSS", () => {
+ expect(hasUnsupportedCssTemplateRules("color: red")).toBe(false);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "@media (min-width: 768px) { color: blue }"
+ )
+ ).toBe(false);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "--brand: red; color: var(--brand, currentColor)"
+ )
+ ).toBe(false);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "@MEDIA (min-width: 768px) { color: blue }"
+ )
+ ).toBe(false);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "@keyframes fade { from { opacity: 0 } to { opacity: 1 } }"
+ )
+ ).toBe(true);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "@media (min-width: 768px) { .child { color: blue } }"
+ )
+ ).toBe(true);
+ expect(
+ hasUnsupportedCssTemplateRules(
+ "@media (min-width: 768px) { @keyframes fade { from { opacity: 0 } } }"
+ )
+ ).toBe(true);
+ });
+
test("longhand property name with keyword value", () => {
expect(
parseCss(`.test { background-color: red }`, new Map()).styles
@@ -757,6 +792,11 @@ test("parse media queries", () => {
color: green;
}
}
+ @MEDIA (min-width: 1024px) {
+ a {
+ color: blue;
+ }
+ }
`,
new Map()
).styles
@@ -773,6 +813,12 @@ test("parse media queries", () => {
property: "color",
value: { type: "keyword", value: "green" },
},
+ {
+ breakpoint: `(min-width:1024px)`,
+ selector: "a",
+ property: "color",
+ value: { type: "keyword", value: "blue" },
+ },
]);
});
diff --git a/packages/css-data/src/parse-css.ts b/packages/css-data/src/parse-css.ts
index 410f10e944..ebd0343d85 100644
--- a/packages/css-data/src/parse-css.ts
+++ b/packages/css-data/src/parse-css.ts
@@ -27,6 +27,37 @@ export type ParsedStyleDecl = {
value: StyleValue;
};
+export const hasUnsupportedCssTemplateRules = (source: string): boolean => {
+ try {
+ const ast = csstree.parse(source, { context: "declarationList" });
+ let unsupported = false;
+ let declarationDepth = 0;
+ csstree.walk(ast, {
+ enter(node) {
+ if (node.type === "Declaration") {
+ declarationDepth += 1;
+ }
+ if (
+ node.type === "Rule" ||
+ (node.type === "Raw" && declarationDepth === 0) ||
+ (node.type === "Atrule" && node.name.toLowerCase() !== "media")
+ ) {
+ unsupported = true;
+ return walkSkip;
+ }
+ },
+ leave(node) {
+ if (node.type === "Declaration") {
+ declarationDepth -= 1;
+ }
+ },
+ });
+ return unsupported;
+ } catch {
+ return false;
+ }
+};
+
// @todo we don't parse correctly most of them if not all
const prefixedProperties = [
"-webkit-box-orient",
@@ -765,7 +796,7 @@ export const parseCss = (
}
// All enclosing at-rules must be @media — reject @supports, @keyframes, etc.
- if (atruleStack.some((atrule) => atrule.name !== "media")) {
+ if (atruleStack.some((atrule) => atrule.name.toLowerCase() !== "media")) {
return;
}
diff --git a/packages/fonts/src/schema.test.ts b/packages/fonts/src/schema.test.ts
new file mode 100644
index 0000000000..3659eee754
--- /dev/null
+++ b/packages/fonts/src/schema.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test } from "vitest";
+import { mergeFontMeta } from "./schema";
+
+describe("mergeFontMeta", () => {
+ test("keeps the detected font shape", () => {
+ const variationAxes = {
+ wght: { name: "Weight", min: 100, default: 400, max: 900 },
+ };
+ expect(
+ mergeFontMeta(
+ { family: "Detected Family", variationAxes },
+ { family: "Configured Family", style: "normal", weight: 400 }
+ )
+ ).toEqual({ family: "Configured Family", variationAxes });
+ expect(
+ mergeFontMeta(
+ { family: "Detected Family", style: "normal", weight: 400 },
+ { family: "Configured Family", variationAxes }
+ )
+ ).toEqual({
+ family: "Configured Family",
+ style: "normal",
+ weight: 400,
+ });
+ });
+
+ test("rejects invalid metadata before selecting compatible fields", () => {
+ expect(
+ mergeFontMeta(
+ {
+ family: "Detected Family",
+ variationAxes: {
+ wght: { name: "Weight", min: 100, default: 400, max: 900 },
+ },
+ },
+ { style: "unsupported" }
+ )
+ ).toBeUndefined();
+ });
+});
diff --git a/packages/fonts/src/schema.ts b/packages/fonts/src/schema.ts
index ac01491b31..40dd975b51 100644
--- a/packages/fonts/src/schema.ts
+++ b/packages/fonts/src/schema.ts
@@ -58,3 +58,31 @@ export const fontMetaUpdate = z.union([
]);
export type FontMeta = z.infer<typeof fontMeta>;
+
+export const mergeFontMeta = (
+ current: FontMeta,
+ override: unknown
+): FontMeta | undefined => {
+ const result = fontMetaUpdate.safeParse(override);
+ if (result.success === false) {
+ return;
+ }
+ const { family } = result.data;
+ if ("variationAxes" in current) {
+ const variationAxes =
+ "variationAxes" in result.data ? result.data.variationAxes : undefined;
+ return {
+ ...current,
+ ...(family === undefined ? {} : { family }),
+ ...(variationAxes === undefined ? {} : { variationAxes }),
+ };
+ }
+ const style = "style" in result.data ? result.data.style : undefined;
+ const weight = "weight" in result.data ? result.data.weight : undefined;
+ return {
+ ...current,
+ ...(family === undefined ? {} : { family }),
+ ...(style === undefined ? {} : { style }),
+ ...(weight === undefined ? {} : { weight }),
+ };
+};
diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.ts
index dc909ecbc7..15fd65fdbb 100644
--- a/packages/http-client/src/index.test.ts
+++ b/packages/http-client/src/index.test.ts
@@ -1573,6 +1573,115 @@ test("surfaces asset content revision conflicts", async () => {
).rejects.toMatchObject({ message: "File changed", status: 409 });
});
+test("reports an asset update as successful when the committed content can be confirmed", async () => {
+ const revision = {
+ ...createImageAssetFixture({ id: "asset-id", name: "new_hash.json" }),
+ type: "file" as const,
+ format: "json",
+ meta: {},
+ };
+ const request = vi.fn(
+ async (input: URL | RequestInfo, init?: RequestInit) => {
+ const url = new URL(input.toString());
+ if (init?.method === "PUT") {
+ return new Response("response failed after commit", { status: 500 });
+ }
+ if (url.pathname.endsWith("/content")) {
+ return new Response('{"theme":"dark"}');
+ }
+ return new Response(JSON.stringify({ asset: revision }), {
+ headers: { "content-type": "application/json" },
+ });
+ }
+ );
+
+ await expect(
+ updateProjectAssetContent({
+ ...apiParams,
+ assetId: "asset-id",
+ expectedName: "old_hash.json",
+ readAssetData: async () => '{"theme":"dark"}',
+ request,
+ })
+ ).resolves.toEqual({ asset: revision });
+ expect(request).toHaveBeenCalledTimes(4);
+});
+
+test("does not confirm an asset update while its revision is changing", async () => {
+ const revisions = ["first_hash.json", "second_hash.json"];
+ const request = vi.fn(
+ async (input: URL | RequestInfo, init?: RequestInit) => {
+ const url = new URL(input.toString());
+ if (init?.method === "PUT") {
+ return new Response("response failed after commit", { status: 500 });
+ }
+ if (url.pathname.endsWith("/content")) {
+ return new Response('{"theme":"dark"}');
+ }
+ const name = revisions.shift() ?? "second_hash.json";
+ return new Response(
+ JSON.stringify({
+ asset: {
+ ...createImageAssetFixture({ id: "asset-id", name }),
+ type: "file",
+ format: "json",
+ meta: {},
+ },
+ }),
+ { headers: { "content-type": "application/json" } }
+ );
+ }
+ );
+
+ await expect(
+ updateProjectAssetContent({
+ ...apiParams,
+ assetId: "asset-id",
+ expectedName: "old_hash.json",
+ readAssetData: async () => '{"theme":"dark"}',
+ request,
+ })
+ ).rejects.toMatchObject({ code: "ASSET_UPDATE_COMMIT_UNCERTAIN" });
+});
+
+test("reports recovery guidance when an asset update commit cannot be confirmed", async () => {
+ const current = {
+ ...createImageAssetFixture({ id: "asset-id", name: "old_hash.json" }),
+ type: "file" as const,
+ format: "json",
+ meta: {},
+ };
+ const request = vi.fn(
+ async (input: URL | RequestInfo, init?: RequestInit) => {
+ const url = new URL(input.toString());
+ if (init?.method === "PUT") {
+ return new Response("response failed", { status: 500 });
+ }
+ if (url.pathname.endsWith("/content")) {
+ return new Response('{"theme":"light"}');
+ }
+ return new Response(JSON.stringify({ asset: current }), {
+ headers: { "content-type": "application/json" },
+ });
+ }
+ );
+
+ await expect(
+ updateProjectAssetContent({
+ ...apiParams,
+ assetId: "asset-id",
+ expectedName: "old_hash.json",
+ readAssetData: async () => '{"theme":"dark"}',
+ request,
+ })
+ ).rejects.toMatchObject({
+ code: "ASSET_UPDATE_COMMIT_UNCERTAIN",
+ message: expect.stringContaining(
+ "Read the current asset and download its content"
+ ),
+ });
+});
+
test("updates asset metadata through the unified Assets endpoint", async () => {
const updated = createImageAssetFixture({ id: "asset-id" });
const request = vi.fn(
diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.ts
index 0a3d4e3c5c..4efec8b74d 100644
--- a/packages/http-client/src/index.ts
+++ b/packages/http-client/src/index.ts
@@ -721,6 +721,32 @@ const requestAssetRest = async (
return response;
};
+const toAssetContentBytes = async (data: AssetContentData) =>
+ new Uint8Array(await new Response(data).arrayBuffer());
+
+const hasEqualAssetContent = async (
+ response: Response,
+ expected: AssetContentData
+) => {
+ const [actualBytes, expectedBytes] = await Promise.all([
+ response.arrayBuffer().then((buffer) => new Uint8Array(buffer)),
+ toAssetContentBytes(expected),
+ ]);
+ return (
+ actualBytes.byteLength === expectedBytes.byteLength &&
+ actualBytes.every((byte, index) => byte === expectedBytes[index])
+ );
+};
+
+const createUncertainAssetUpdateError = (cause: unknown) =>
+ Object.assign(
+ new Error(
+ "ASSET_UPDATE_COMMIT_UNCERTAIN: The asset update response failed and the saved content could not be confirmed. Do not retry with the previous expectedName. Read the current asset and download its content before deciding whether another update is needed.",
+ { cause }
+ ),
+ { code: "ASSET_UPDATE_COMMIT_UNCERTAIN" }
+ );
+
export const updateProjectAssetContent = async (
params: Omit<AuthProjectParams, "authToken"> & {
authToken?: string;
@@ -732,16 +758,46 @@ export const updateProjectAssetContent = async (
}
): Promise<{ asset: Asset }> => {
const request = params.request ?? fetch;
+ const data = await params.readAssetData();
const url = createAssetRestUrl({
...params,
path: getAssetContentApiUrl(params.assetId),
});
url.searchParams.set("expectedName", params.expectedName);
- return await requestAssetRestJson(request, url, {
- method: "PUT",
- body: await params.readAssetData(),
- headers: createAssetRestHeaders(params, "application/octet-stream"),
- });
+ try {
+ return await requestAssetRestJson(request, url, {
+ method: "PUT",
+ body: data,
+ headers: createAssetRestHeaders(params, "application/octet-stream"),
+ });
+ } catch (error) {
+ const status =
+ typeof error === "object" && error !== null && "status" in error
+ ? error.status
+ : undefined;
+ if (typeof status === "number" && status < 500) {
+ throw error;
+ }
+ try {
+ const { asset: before } = await getProjectAsset({ ...params, request });
+ const content = await readProjectAssetContent({
+ ...params,
+ request,
+ assetId: params.assetId,
+ });
+ const { asset } = await getProjectAsset({ ...params, request });
+ if (
+ asset.name === before.name &&
+ asset.name !== params.expectedName &&
+ (await hasEqualAssetContent(content, data))
+ ) {
+ return { asset };
+ }
+ } catch {
+ // Fall through to an explicit ambiguous-result error.
+ }
+ throw createUncertainAssetUpdateError(error);
+ }
};
export const updateProjectAsset = async (
@@ -797,7 +853,8 @@ export const listProjectAssets = async (
);
export const getProjectAsset = async (
- params: AuthProjectParams & {
+ params: Omit<AuthProjectParams, "authToken"> & {
+ authToken?: string;
assetId: string;
request?: typeof fetch;
requestOrigin?: string;
@@ -810,7 +867,8 @@ export const getProjectAsset = async (
);
export const readProjectAssetContent = async (
- params: AuthProjectParams & {
+ params: Omit<AuthProjectParams, "authToken"> & {
+ authToken?: string;
assetId: string;
range?: { offset: number; length: number };
request?: typeof fetch;
diff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.ts
index c23d23dfbf..1d3733fc9b 100644
--- a/packages/project-build/src/mcp.test.ts
+++ b/packages/project-build/src/mcp.test.ts
@@ -143,6 +143,31 @@ const getUnresolvedLocalSchemaRefs = (
];
};
+const getArraySchemasWithoutItems = (
+ schema: unknown,
+ path: readonly string[] = []
+): string[] => {
+ if (schema === null || typeof schema !== "object") {
+ return [];
+ }
+ if (Array.isArray(schema)) {
+ return schema.flatMap((value, index) =>
+ getArraySchemasWithoutItems(value, [...path, String(index)])
+ );
+ }
+ const object = schema as Record<string, unknown>;
+ const current =
+ object.type === "array" && object.items === undefined
+ ? [path.join(".")]
+ : [];
+ return [
+ ...current,
+ ...Object.entries(object).flatMap(([name, value]) =>
+ getArraySchemasWithoutItems(value, [...path, name])
+ ),
+ ];
+};
+
const optionalArrayFieldInputSchema = (field: string) =>
getTestInputSchema(
z.object({
@@ -896,6 +921,10 @@ describe("project session mcp adapter", () => {
getUnresolvedLocalSchemaRefs(tool.inputSchema),
`MCP input schema has unresolved local references for ${tool.name}`
).toEqual([]);
+ expect(
+ getArraySchemasWithoutItems(tool.inputSchema),
+ `MCP input schema has array parameters without items for ${tool.name}`
+ ).toEqual([]);
if (tool.outputSchema !== undefined) {
expect(
tool.outputSchema.type,
@@ -915,11 +944,6 @@ describe("project session mcp adapter", () => {
expect(JSON.stringify(imageDescriptionsTool?.inputSchema)).toContain(
"rendered image in context"
);
- expect(
- JSON.stringify(
- tools.find(({ name }) => name === "update-styles")?.inputSchema
- )
- ).toContain("JSON-compatible value.");
expect(
getSuccessfulOutputDataSchema(
tools.find((tool) => tool.name === "refresh")?.outputSchema
@@ -1131,6 +1155,12 @@ describe("project session mcp adapter", () => {
properties: expect.objectContaining({
instanceId: { type: "string" },
property: { type: "string" },
+ value: expect.objectContaining({
+ anyOf: expect.arrayContaining([
+ { type: "string" },
+ { type: "array", items: {} },
+ ]),
+ }),
}),
}),
});
@@ -1236,6 +1266,66 @@ describe("project session mcp adapter", () => {
);
});
+ test("keeps array items valid when deferring an oversized schema", () => {
+ const operation = publicOperation({
+ command: "large-array-input",
+ id: "test.largeArrayInput",
+ description: "Accept a large structured array",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ updates: {
+ type: "array",
+ items: {
+ type: "object",
+ description: "x".repeat(25_000),
+ },
+ },
+ },
+ required: ["updates"],
+ },
+ });
+
+ const [tool] = listProjectSessionMcpTools([operation]);
+ const updates = tool?.inputSchema.properties?.updates as
+ | Record<string, unknown>
+ | undefined;
+
+ expect(JSON.stringify(tool?.inputSchema).length).toBeLessThan(1_000);
+ expect(updates).toMatchObject({
+ type: "array",
+ items: {},
+ });
+ });
+
+ test("adds items to tuple input schemas", () => {
+ const operation = publicOperation({
+ command: "tuple-input",
+ id: "test.tupleInput",
+ description: "Accept a structured tuple",
+ inputSchema: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ coordinates: {
+ type: "array",
+ prefixItems: [{ type: "number" }, { type: "number" }],
+ },
+ },
+ required: ["coordinates"],
+ },
+ });
+
+ const [tool] = listProjectSessionMcpTools([operation]);
+
+ expect(tool?.inputSchema.properties?.coordinates).toMatchObject({
+ type: "array",
+ items: {},
+ prefixItems: [{ type: "number" }, { type: "number" }],
+ });
+ });
+
test("downloads assets through the MCP host", async () => {
const downloadAsset = vi.fn(async ({ assetId }: { assetId: string }) => ({
assetId,
@@ -2796,6 +2886,57 @@ describe("project session mcp adapter", () => {
);
});
+ test("unwraps a redundantly nested create-resource input", async () => {
+ const executeOperation = createExecuteOperation();
+ const createResourceOperation = publicOperation({
+ command: "create-resource",
+ id: "resources.create",
+ method: "mutation",
+ permit: "edit",
+ description: "Create resource",
+ inputSchema: getTestInputSchema(
+ z.object({
+ scopeInstanceId: z.string(),
+ dataSourceName: z.string(),
+ resource: z.object({
+ name: z.string(),
+ method: z.enum(["get", "post"]),
+ url: z.string(),
+ headers: z.array(z.unknown()),
+ searchParams: z.array(z.unknown()).optional(),
+ }),
+ })
+ ),
+ writeNamespaces: ["resources"],
+ invalidatesNamespaces: ["resources"],
+ });
+ const adapter = createProjectSessionMcpCore({
+ operations: [createResourceOperation],
+ createProjectSession: createSessionFactory(),
+ executeOperation,
+ });
+ const input = {
+ scopeInstanceId: "root",
+ dataSourceName: "accountSession",
+ resource: {
+ name: "Account session via server",
+ method: "get",
+ url: "/api/auth/session",
+ headers: [],
+ searchParams: [],
+ },
+ };
+
+ await adapter.callTool({
+ name: "create-resource",
+ input: { resource: input },
+ });
+
+ expect(executeOperation).toHaveBeenCalledWith(
+ expect.objectContaining({ command: "create-resource", input })
+ );
+ });
+
test("suggests page structure tools when page detail input is unsupported", async () => {
const executeOperation: ExecuteOperation = vi.fn();
const adapter = createProjectSessionMcpCore({
@@ -4700,6 +4841,19 @@ describe("project session mcp adapter", () => {
);
expect(authenticatedPageGuide.structuredContent.data).toEqual(
expect.objectContaining({
+ recipe: {
+ createResourceInput: {
+ scopeInstanceId: "<account-root-id>",
+ dataSourceName: "accountSession",
+ resource: {
+ name: "Account session via server",
+ method: "get",
+ url: "/api/auth/session",
+ headers: [],
+ searchParams: [],
+ },
+ },
+ },
workflow: expect.arrayContaining([
expect.stringContaining("existing auth resources"),
expect.stringContaining("Call inspect-auth-context exactly once"),
@@ -4718,10 +4872,8 @@ describe("project session mcp adapter", () => {
expect.stringContaining(
"Do not repeat list-variables when the fixture variable is not referenced"
),
- expect.stringContaining("copy its fixed request URL exactly"),
- expect.stringContaining(
- 'url:"/api/auth/session",headers:[],searchParams:[]'
- ),
+ expect.stringContaining("recipe.createResourceInput"),
+ expect.stringContaining("entire create-resource tool input"),
expect.stringContaining(
"Do not call selector-based structural tools"
),
diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.ts
index 03a165e819..6b09e53995 100644
--- a/packages/project-build/src/mcp.ts
+++ b/packages/project-build/src/mcp.ts
@@ -633,10 +633,9 @@ const jsonCompatibleValueSchema = {
{ type: "number" },
{ type: "boolean" },
{ type: "null" },
- { type: "array" },
+ { type: "array", items: {} },
{ type: "object" },
],
- description: "JSON-compatible value.",
} as const satisfies InputJsonSchema;
const constrainUnconstrainedInputSchemaValue = (
@@ -668,7 +667,9 @@ const constrainUnconstrainedInputSchemas = <Schema extends InputJsonSchema>(
schema.additionalProperties
);
}
- if (schema.items !== undefined) {
+ if (schema.type === "array" && schema.items === undefined) {
+ result.items = {};
+ } else if (schema.items !== undefined) {
result.items = constrainUnconstrainedInputSchemaValue(schema.items);
}
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"] as const) {
@@ -699,6 +700,11 @@ const getCompactSchemaProperty = (schema: InputJsonSchema): InputJsonSchema => {
: `${schema.description.slice(0, 239)}…`;
const compact = {
...(schema.type === undefined ? {} : { type: schema.type }),
+ ...(schema.type === "array"
+ ? {
+ items: {},
+ }
+ : {}),
...(description === undefined ? {} : { description }),
...(schema.enum === undefined ? {} : { enum: schema.enum }),
};
@@ -1027,6 +1033,16 @@ const normalizeOperationInputAliases = ({
command: string;
input: unknown;
}) => {
+ if (
+ command === "create-resource" &&
+ isPlainRecord(input) &&
+ Object.keys(input).length === 1 &&
+ isPlainRecord(input.resource) &&
+ isPlainRecord(input.resource.resource) &&
+ typeof input.resource.scopeInstanceId === "string"
+ ) {
+ return input.resource;
+ }
if (command === "create-page" && isPlainRecord(input)) {
const normalizedInput: Record<string, unknown> =
"description" in input
@@ -5789,13 +5805,26 @@ const metaGoalGuides = [
"Keep all four auth states in the editable component structure even when bindings select only one at runtime. Give each state a visible label using the exact terms signed-out, loading, signed-in, and failed-auth so authors can inspect and verify every state. Use page basic auth only when the user asks for Webstudio's fixed login/password gate; it is not Supabase or Firebase authentication.",
"Use focused resources and variables for public client configuration and session-shaped data. Keep authorization enforcement and privileged provider calls server-side; a hidden Builder element is not an authorization boundary.",
"When fixture/session data must feed a resource, create the page and scoped fixture variables there. Use create-page's returned rootInstanceId directly instead of listing instances to rediscover it. Call list-variables after creation only when a resource expression actually needs the returned encoded name. Do not repeat list-variables when the fixture variable is not referenced, as in the expression-free state gallery, and do not guess or reference variables before they exist.",
- 'Create resources only after their scope and referenced variables exist. When reusing an existing server-mediated auth convention, copy its fixed request URL exactly into resource.url; resource.url is the HTTP request target, not a provider call or session-state expression. For the discovered /api/auth/session convention, use create-resource with resource:{name:"Account session via server",method:"get",url:"/api/auth/session",headers:[],searchParams:[]}, the new page root as scopeInstanceId, and a descriptive dataSourceName. Use literal wrappers only for fixed header, search-parameter, and body text.',
+ "Create resources only after their scope and referenced variables exist. When reusing the discovered /api/auth/session convention, pass recipe.createResourceInput directly as the entire create-resource tool input, unchanged except for its account root id placeholder. Do not wrap it in another resource object. Keep every request field nested under resource. resource.url is the HTTP request target, not a provider call or session-state expression. Use literal wrappers only for fixed header, search-parameter, and body text.",
"Keep the server-mediated session resource as provider-convention evidence, but use only non-secret scoped fixture variables to drive local auth-state visibility. Do not bind that server-only resource into local preview rendering: its endpoint is intentionally absent locally and can recurse through the generated route.",
'Insert signed-out, loading, signed-in, and failed-auth panels together as one expression-free semantic fragment that acts as a state gallery. Keep all four panels visible together for local visual verification; do not add conditional visibility bindings or mutate fixture state solely to capture more screenshots. Use that exact fragment verbatim without adding styles, props, expressions, components, or changing its nesting: <ws.element ws:tag="main"><ws.element ws:tag="section"><ws.element ws:tag="h2">Signed-out</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Loading</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Signed-in</ws.element></ws.element><ws.element ws:tag="section"><ws.element ws:tag="h2">Failed-auth</ws.element></ws.element></ws.element>.',
"Do not call selector-based structural tools such as wrap-instance unless a focused list-instances result supplied the complete non-empty selector from the target through its page root. Prefer direct style, prop, or binding corrections when the structure is already sound.",
'Insert the complete account fragment with insert-fragment-verified and {"pagePath":"/account"} so persisted bindings are checked in the same call. Resolve every returned validity, scope, and reference finding before previewing. If post-commit verification reports an infrastructure failure, do not repeat the insertion; call verify-bindings separately for /account. Updating only a fixture variable\'s literal state does not require another binding verification.',
'Call verify-page-responsive once with path "/account" and the required desktop and mobile viewports; it starts or refreshes the session preview, captures both viewports in one browser session, and immediately runs the static page audit. Do not call preview.start, screenshot, screenshot.responsive, or audit separately. Do not run discovery, inspect-instance, mutate, or repeat binding verification after this terminal verification begins. The screenshots are the rendered evidence and the bundled audit is the static evidence. Do not claim the real provider flow works until redirects, session refresh, failure handling, and protected data access are exercised in its configured environment.',
],
+ recipe: {
+ createResourceInput: {
+ scopeInstanceId: "<account-root-id>",
+ dataSourceName: "accountSession",
+ resource: {
+ name: "Account session via server",
+ method: "get",
+ url: "/api/auth/session",
+ headers: [],
+ searchParams: [],
+ },
+ },
+ },
},
{
pattern:
diff --git a/packages/project-build/src/runtime/components.test.ts b/packages/project-build/src/runtime/components.test.ts
index c42a0583d2..81645f0bd8 100644
--- a/packages/project-build/src/runtime/components.test.ts
+++ b/packages/project-build/src/runtime/components.test.ts
@@ -1311,6 +1311,31 @@ test("inspects webstudio jsx fragment syntax without evaluation", () => {
).not.toThrow();
});
+test("rejects unsupported css rules after interpolation", async () => {
+ await expect(
+ parseWebstudioJsxFragment(
+ '<ws.element ws:tag="div" ws:style={css`${"@keyframes pulse { 0% { opacity: 0; } 100% { opacity: 1; } }"} animation-name: pulse;`} />'
+ )
+ ).rejects.toThrow(
+ "css templates do not support selectors or at-rules such as @keyframes"
+ );
+});
+
+test("explains unmatched jsx without implying session state", async () => {
+ const validFragment = `<$.Box><$.Heading>Title</$.Heading></$.Box>`;
+ await expect(parseWebstudioJsxFragment(validFragment)).resolves.toEqual(
+ expect.objectContaining({ children: expect.any(Array) })
+ );
+ await expect(
+ parseWebstudioJsxFragment(`<$.Box><$.Heading>Title</$.Box>`)
+ ).rejects.toThrow(
+ "Every opening element must use the same closing tag or end with />. Fragment parsing is stateless"
+ );
+ await expect(parseWebstudioJsxFragment(validFragment)).resolves.toEqual(
+ expect.objectContaining({ children: expect.any(Array) })
+ );
+});
+
test("inserts bare template-backed components from webstudio jsx fragments", async () => {
const parent = createParent();
const fragment = await parseWebstudioJsxFragment(`<radix.Switch />`);
@@ -1860,7 +1885,17 @@ test("allows html and fragment syntax inside text values", async () => {
test("suggests built-in helpers for unknown jsx identifiers", async () => {
await expect(parseWebstudioJsxFragment(`<Box />`)).rejects.toThrow(
- "Use built-in helpers only: $, ws, radix, animation, css, token, expression, Variable, Parameter, ResourceValue, ActionValue, AssetValue, PageValue, and PlaceholderValue. Box is not defined"
+ "Use component namespaces $, ws, radix, and animation and value helpers css, token, expression, Variable, Parameter, ResourceValue, ActionValue, AssetValue, PageValue, and PlaceholderValue. Box is not defined"
+ );
+});
+
+test("explains that animation is a component namespace", async () => {
+ await expect(
+ parseWebstudioJsxFragment(
+ '<$.Box data-animation={animation("pulse", css`opacity: 1;`)} />'
+ )
+ ).rejects.toThrow(
+ "animation is a component namespace such as <animation.AnimateChildren>; it is not a callable CSS keyframes helper."
);
});
diff --git a/packages/project-build/src/runtime/jsx/bindings.ts b/packages/project-build/src/runtime/jsx/bindings.ts
index 10c02e0b6d..1862896961 100644
--- a/packages/project-build/src/runtime/jsx/bindings.ts
+++ b/packages/project-build/src/runtime/jsx/bindings.ts
@@ -8,11 +8,22 @@ import {
ResourceValue,
Variable,
createProxy,
- css,
expression,
+ parseTemplateCss,
token,
ws,
} from "@webstudio-is/template";
+import { hasUnsupportedCssTemplateRules } from "@webstudio-is/css-data";
+
+const css = (strings: TemplateStringsArray, ...values: string[]) => {
+ const source = String.raw({ raw: strings }, ...values);
+ if (hasUnsupportedCssTemplateRules(source)) {
+ throw new Error(
+ "css templates do not support selectors or at-rules such as @keyframes. Use declarations and @media rules only. Use Webstudio Animation components for editable animations."
+ );
+ }
+ return parseTemplateCss(source);
+};
const componentBindings = {
$,
@@ -48,10 +59,19 @@ const listFormatter = new Intl.ListFormat("en", {
type: "conjunction",
});
-export const webstudioJsxFragmentBuiltInHelpers = listFormatter.format(
- Object.keys(webstudioJsxRuntimeBindings)
+const webstudioJsxComponentNamespaceNames = listFormatter.format(
+ Object.keys(componentBindings)
+);
+
+const webstudioJsxHelperNames = listFormatter.format(
+ Object.keys(helperBindings)
);
+export const webstudioJsxBindingGuidance = `component namespaces ${webstudioJsxComponentNamespaceNames} and value helpers ${webstudioJsxHelperNames}`;
+
+export const webstudioJsxAnimationGuidance =
+ "animation is a component namespace such as <animation.AnimateChildren>; it is not a callable CSS keyframes helper.";
+
export const webstudioJsxFragmentInputDescription =
- `Webstudio JSX fragment. Use ${webstudioJsxFragmentBuiltInHelpers} helpers. ` +
+ `Webstudio JSX fragment. Use ${webstudioJsxBindingGuidance}. ${webstudioJsxAnimationGuidance} ` +
'Do not access host globals or dynamic code APIs such as process, globalThis, eval, Function, or constructor. Use Webstudio prop names such as class and for, not React aliases className or htmlFor. Use ws:style={css`...`} for Webstudio-native styles, or style={{ padding: 24 }} for React-style object syntax that is converted into editable Webstudio styles. Use Webstudio actions such as onClick={new ActionValue(["event"], expression`console.log(event)`)}; do not pass JavaScript functions such as onClick={() => ...}. Plain prop values must be JSON-compatible: use 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. Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template; use insert-component when you want Webstudio to apply one registered component template automatically. Do not set ws:id; ids are generated by the runtime. The JSX is converted locally before the mutation request is sent.';
diff --git a/packages/project-build/src/runtime/jsx/fragment.server.ts b/packages/project-build/src/runtime/jsx/fragment.server.ts
index e4bd85b366..ea60f49937 100644
--- a/packages/project-build/src/runtime/jsx/fragment.server.ts
+++ b/packages/project-build/src/runtime/jsx/fragment.server.ts
@@ -3,7 +3,8 @@ import type { WebstudioFragment } from "@webstudio-is/sdk";
import { renderTemplate } from "@webstudio-is/template";
import { componentMetas } from "@webstudio-is/sdk-components-registry/metas";
import {
- webstudioJsxFragmentBuiltInHelpers,
+ webstudioJsxAnimationGuidance,
+ webstudioJsxBindingGuidance,
webstudioJsxRuntimeBindings,
} from "./bindings";
import { evaluateJsx } from "./evaluate.server";
@@ -17,6 +18,7 @@ const templateValidationMessagePrefixes = [
"token()",
"ws:style",
"ws:tokens",
+ "css templates",
];
const isTemplateValidationMessage = (message: string) =>
@@ -45,13 +47,19 @@ export const evaluateWebstudioJsxFragment = async (
...webstudioJsxRuntimeBindings,
},
parseErrorMessage: (error) =>
- `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${getErrorMessage(error)}`,
+ `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${getErrorMessage(
+ error
+ )}`,
evaluationErrorMessage: (error) => {
const message = getErrorMessage(error);
if (isTemplateValidationMessage(message)) {
return message;
}
- return `Could not evaluate JSX fragment. Use built-in helpers only: ${webstudioJsxFragmentBuiltInHelpers}. ${message}`;
+ const animationGuidance =
+ message === "animation is not a function"
+ ? ` ${webstudioJsxAnimationGuidance}`
+ : "";
+ return `Could not evaluate JSX fragment. Use ${webstudioJsxBindingGuidance}.${animationGuidance} ${message}`;
},
missingResultMessage: "JSX fragment did not produce Webstudio data.",
});
diff --git a/packages/project-build/src/runtime/jsx/syntax.ts b/packages/project-build/src/runtime/jsx/syntax.ts
index 48fbe50b8f..3d6142233e 100644
--- a/packages/project-build/src/runtime/jsx/syntax.ts
+++ b/packages/project-build/src/runtime/jsx/syntax.ts
@@ -1,6 +1,6 @@
import { Parser } from "acorn";
import jsx from "acorn-jsx";
-import { webstudioJsxFragmentBuiltInHelpers } from "./bindings";
+import { webstudioJsxBindingGuidance } from "./bindings";
import { getErrorMessage, throwWebstudioJsxValidationError } from "./errors";
const JsxParser = Parser.extend(jsx());
@@ -197,7 +197,7 @@ const hasModuleSyntax = (source: string) => {
export const inspectWebstudioJsxFragmentSyntax = (source: string) => {
if (hasModuleSyntax(source)) {
return throwWebstudioJsxValidationError(
- `Do not use import or export in JSX fragments. Use the built-in ${webstudioJsxFragmentBuiltInHelpers} helpers.`,
+ `Do not use import or export in JSX fragments. Use ${webstudioJsxBindingGuidance}.`,
"declarative_jsx_without_modules"
);
}
@@ -205,26 +205,32 @@ export const inspectWebstudioJsxFragmentSyntax = (source: string) => {
try {
ast = parseWebstudioJsxFragmentExpression(source);
} catch (error) {
+ const message = getErrorMessage(error);
+ const recovery = message.startsWith(
+ "Expected corresponding JSX closing tag"
+ )
+ ? " Every opening element must use the same closing tag or end with />. Fragment parsing is stateless, so refresh cannot repair unmatched JSX."
+ : "";
return throwWebstudioJsxValidationError(
- `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${getErrorMessage(error)}`,
+ `Could not parse JSX fragment. Pass Webstudio JSX such as <$.Box><$.Heading>Title</$.Heading></$.Box>. ${message}${recovery}`,
"valid_webstudio_jsx_syntax",
- getErrorMessage(error)
+ message
);
}
const error = visitAst(ast, (node, context) => {
if (node.type === "ImportExpression" || node.type === "Import") {
- return `Do not use dynamic import() in JSX fragments. JSX fragments are declarative Webstudio project data; use the built-in ${webstudioJsxFragmentBuiltInHelpers} helpers.`;
+ return `Do not use dynamic import() in JSX fragments. JSX fragments are declarative Webstudio project data; use ${webstudioJsxBindingGuidance}.`;
}
if (node.type === "Identifier" && typeof node.name === "string") {
if (
restrictedRuntimeIdentifiers.has(node.name) &&
isNonExecutingPropertyName(context) === false
) {
- return `Do not access "${node.name}" in JSX fragments. JSX fragments are declarative Webstudio project data; use the built-in ${webstudioJsxFragmentBuiltInHelpers} helpers.`;
+ return `Do not access "${node.name}" in JSX fragments. JSX fragments are declarative Webstudio project data; use ${webstudioJsxBindingGuidance}.`;
}
}
if (getMemberPropertyName(node) === "constructor") {
- return `Do not access "constructor" in JSX fragments. JSX fragments are declarative Webstudio project data; use the built-in ${webstudioJsxFragmentBuiltInHelpers} helpers.`;
+ return `Do not access "constructor" in JSX fragments. JSX fragments are declarative Webstudio project data; use ${webstudioJsxBindingGuidance}.`;
}
});
if (error !== undefined) {
diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.ts
index 18b0d57344..b7c7c8bea4 100644
--- a/packages/sdk/src/schema/assets.ts
+++ b/packages/sdk/src/schema/assets.ts
@@ -1,6 +1,11 @@
import { z } from "zod";
import { assetFolderId } from "./asset-folders";
-import { fontFormat, fontMeta, fontMetaUpdate } from "@webstudio-is/fonts";
+import {
+ fontFormat,
+ fontMeta,
+ fontMetaUpdate,
+ mergeFontMeta,
+} from "@webstudio-is/fonts";
const assetId = z.string();
@@ -59,16 +64,22 @@ export const asset = z.union([fontAsset, imageAsset, fileAsset]);
export type Asset = z.infer<typeof asset>;
const assetMetaSchemas = {
- font: fontMeta,
image: imageMeta,
file: z.object({}),
-} as const satisfies Record<AssetType, z.ZodType>;
+} as const satisfies Record<Exclude<AssetType, "font">, z.ZodType>;
export const mergeAssetMeta = (
type: AssetType,
current: object,
override: Record<string, unknown>
): Asset["meta"] | undefined => {
+ if (type === "font") {
+ const result = fontMeta.safeParse(current);
+ if (result.success === false) {
+ return;
+ }
+ return mergeFontMeta(result.data, override);
+ }
const merged = { ...current, ...override };
const result = assetMetaSchemas[type].safeParse(merged);
if (
diff --git a/scripts/visual-regression/README.md b/scripts/visual-regression/README.md
index 2157280607..519d99b1d6 100644
--- a/scripts/visual-regression/README.md
+++ b/scripts/visual-regression/README.md
@@ -23,7 +23,9 @@ most recent report without rerunning the comparison with
The HTML report shows baseline, current, and diff images for every mismatch,
plus OCR evidence for changed text. CI uploads the same self-contained report
-as a `visual-regression-report` artifact.
+as a `visual-regression-report` artifact. When a comparison fails, the CI log
+also lists each affected story, source file, pixel mismatch, changed regions,
+warnings, errors, and report artifact paths.
Pixel sensitivity (`0.1`), mismatch tolerance (`0.001%`), viewport, capture,
server, and cache settings live in `config.ts`. Add
diff --git a/scripts/visual-regression/capture.test.ts b/scripts/visual-regression/capture.test.ts
index 480ac7d31e..fc77cdaf48 100644
--- a/scripts/visual-regression/capture.test.ts
+++ b/scripts/visual-regression/capture.test.ts
@@ -3,7 +3,11 @@ import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import test from "node:test";
-import { captureStoryPairs, getInitialCaptureTarget } from "./capture";
+import {
+ captureStoryPairs,
+ getInitialCaptureTarget,
+ getStoryCaptureOptions,
+} from "./capture";
import type { VisualStoryEntry } from "./manifest";
const createEntry = (id: string): VisualStoryEntry => ({
@@ -26,6 +30,18 @@ test("does not initialize a browser for cached removed stories", () => {
);
});
+test("waits for asynchronous canvas paints before capturing", () => {
+ assert.equal(
+ getStoryCaptureOptions({
+ browserPath: "/browser",
+ entry: createEntry("canvas"),
+ output: "/canvas.png",
+ port: 6101,
+ }).waitForTimeout,
+ 250
+ );
+});
+
test("recaptures baseline and current stories on the same browser page", async () => {
const assetDirectory = await mkdtemp(path.join(tmpdir(), "visual-pairs-"));
const calls: string[][] = [];
diff --git a/scripts/visual-regression/capture.ts b/scripts/visual-regression/capture.ts
index ef8e6d307a..25f727492c 100644
--- a/scripts/visual-regression/capture.ts
+++ b/scripts/visual-regression/capture.ts
@@ -60,7 +60,7 @@ export const getStoryCaptureOptions = ({
})}).catch(window.showVisualError)`,
waitForSelector: "#visual-ready, #visual-error",
failForSelector: "#visual-error",
- waitForTimeout: 0,
+ waitForTimeout: visualRegressionConfig.capture.settleTime,
finalizeExpression: "window.finishVisualStory()",
timeout: visualRegressionConfig.capture.timeout,
format: "png",
diff --git a/scripts/visual-regression/config.ts b/scripts/visual-regression/config.ts
index b6bce6595d..56f48efee0 100644
--- a/scripts/visual-regression/config.ts
+++ b/scripts/visual-regression/config.ts
@@ -6,6 +6,7 @@ export const visualRegressionConfig = {
capture: {
viewport: { width: 1280, height: 800 },
timeout: 90_000,
+ settleTime: 250,
concurrency: { minimum: 5, maximum: 8 },
},
comparison: {
diff --git a/scripts/visual-regression/run-utils.test.ts b/scripts/visual-regression/run-utils.test.ts
new file mode 100644
index 0000000000..619c47ef13
--- /dev/null
+++ b/scripts/visual-regression/run-utils.test.ts
@@ -0,0 +1,122 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import {
+ formatVisualRegressionDiagnostics,
+ getIsolatedVerificationServers,
+ getStoryPairs,
+} from "./run-utils";
+
+const createEntry = (id: string) => ({ id, file: `${id}.stories.tsx` });
+
+test("pairs only the requested story ids when manifest sizes differ", () => {
+ const shared = createEntry("shared");
+ assert.deepEqual(
+ getStoryPairs({
+ ids: ["shared"],
+ baselineEntries: {
+ removed: createEntry("removed"),
+ shared,
+ },
+ currentEntries: {
+ added: createEntry("added"),
+ shared,
+ },
+ }),
+ [{ baseline: shared, current: shared }]
+ );
+});
+
+test("rejects a requested story without the same id on both sides", () => {
+ assert.throws(
+ () =>
+ getStoryPairs({
+ ids: ["shared"],
+ baselineEntries: { shared: createEntry("different") },
+ currentEntries: { shared: createEntry("shared") },
+ }),
+ /baseline manifest entry for shared has id different/
+ );
+});
+
+test("uses equivalent isolated story bundles when verifying a cached baseline", () => {
+ assert.deepEqual(
+ getIsolatedVerificationServers({
+ repositoryRoot: "/current",
+ checkout: "/baseline",
+ baselineBundleDirectory: "/baseline-bundle",
+ currentBundleDirectory: "/current-bundle",
+ baselinePort: 6101,
+ currentPort: 6102,
+ pairs: [
+ {
+ baseline: {
+ id: "button",
+ file: "button.baseline.stories.tsx",
+ },
+ current: { id: "button", file: "button.current.stories.tsx" },
+ },
+ ],
+ }),
+ [
+ {
+ root: "/baseline",
+ port: 6101,
+ outputDirectory: "/baseline-bundle",
+ storyFiles: ["button.baseline.stories.tsx"],
+ },
+ {
+ root: "/current",
+ port: 6102,
+ outputDirectory: "/current-bundle",
+ storyFiles: ["button.current.stories.tsx"],
+ },
+ ]
+ );
+});
+
+test("formats actionable visual differences for CI logs", () => {
+ assert.deepEqual(
+ formatVisualRegressionDiagnostics({
+ baselineLabel: "base-sha",
+ currentLabel: "head-sha",
+ durationMs: 100,
+ errors: [],
+ comparisons: [
+ {
+ id: "design-system-color-picker--color-picker",
+ title: "Design system/Color Picker",
+ name: "Color Picker",
+ file: "packages/design-system/src/components/color-picker.stories.tsx",
+ status: "changed",
+ differentPixels: 387,
+ mismatchPercentage: 0.03779296875,
+ regions: [
+ {
+ bounds: { x: 288, y: 128, width: 1, height: 87 },
+ pixelCount: 87,
+ averageColor: {
+ delta: { r: -33, g: -31, b: -25 },
+ dominantChange: {
+ channel: "red",
+ direction: "decrease",
+ magnitude: 33,
+ },
+ },
+ },
+ ],
+ warnings: ["ocr_unavailable"],
+ baselinePath: "assets/color-picker/baseline.png",
+ currentPath: "assets/color-picker/current.png",
+ diffPath: "assets/color-picker/diff.png",
+ },
+ ],
+ }),
+ [
+ "Visual regression diagnostics:",
+ "- changed design-system-color-picker--color-picker (Design system/Color Picker / Color Picker) file=packages/design-system/src/components/color-picker.stories.tsx: 387 pixels, 0.0378% mismatch",
+ " regions: x=288 y=128 width=1 height=87 pixels=87",
+ " warnings: ocr_unavailable",
+ " artifacts: baseline=assets/color-picker/baseline.png current=assets/color-picker/current.png diff=assets/color-picker/diff.png",
+ ]
+ );
+});
diff --git a/scripts/visual-regression/run-utils.ts b/scripts/visual-regression/run-utils.ts
new file mode 100644
index 0000000000..1db37af8e4
--- /dev/null
+++ b/scripts/visual-regression/run-utils.ts
@@ -0,0 +1,139 @@
+import type {
+ ScreenshotComparisonReport,
+ ScreenshotComparisonReportItem,
+} from "@webstudio-is/vision/report";
+
+type VerificationEntry = { id: string; file: string };
+
+export const getStoryPairs = <Entry extends VerificationEntry>({
+ ids,
+ baselineEntries,
+ currentEntries,
+}: {
+ ids: readonly string[];
+ baselineEntries: Readonly<Record<string, Entry>>;
+ currentEntries: Readonly<Record<string, Entry>>;
+}) =>
+ ids.map((id) => {
+ const baseline = baselineEntries[id];
+ const current = currentEntries[id];
+ if (baseline === undefined) {
+ throw new Error(`Baseline manifest is missing story ${id}.`);
+ }
+ if (current === undefined) {
+ throw new Error(`Current manifest is missing story ${id}.`);
+ }
+ if (baseline.id !== id) {
+ throw new Error(
+ `The baseline manifest entry for ${id} has id ${baseline.id}.`
+ );
+ }
+ if (current.id !== id) {
+ throw new Error(
+ `The current manifest entry for ${id} has id ${current.id}.`
+ );
+ }
+ return { baseline, current };
+ });
+
+export const getIsolatedVerificationServers = ({
+ repositoryRoot,
+ checkout,
+ baselineBundleDirectory,
+ currentBundleDirectory,
+ baselinePort,
+ currentPort,
+ pairs,
+}: {
+ repositoryRoot: string;
+ checkout: string;
+ baselineBundleDirectory: string;
+ currentBundleDirectory: string;
+ baselinePort: number;
+ currentPort: number;
+ pairs: readonly {
+ baseline: VerificationEntry;
+ current: VerificationEntry;
+ }[];
+}) => [
+ {
+ root: checkout,
+ port: baselinePort,
+ outputDirectory: baselineBundleDirectory,
+ storyFiles: pairs.map(({ baseline }) => baseline.file),
+ },
+ {
+ root: repositoryRoot,
+ port: currentPort,
+ outputDirectory: currentBundleDirectory,
+ storyFiles: pairs.map(({ current }) => current.file),
+ },
+];
+
+type DiagnosticReportItem = ScreenshotComparisonReportItem & {
+ file?: string;
+};
+
+type DiagnosticReport = Omit<ScreenshotComparisonReport, "comparisons"> & {
+ comparisons: readonly DiagnosticReportItem[];
+};
+
+const formatArtifactPaths = (comparison: DiagnosticReportItem) => {
+ const paths = [
+ ["baseline", comparison.baselinePath],
+ ["current", comparison.currentPath],
+ ["diff", comparison.diffPath],
+ ["contextDiff", comparison.contextDiffPath],
+ ].flatMap(([name, file]) => (file === undefined ? [] : [`${name}=${file}`]));
+ return paths.length === 0 ? undefined : ` artifacts: ${paths.join(" ")}`;
+};
+
+export const formatVisualRegressionDiagnostics = (
+ report: DiagnosticReport
+): string[] => {
+ const lines: string[] = [];
+ if (report.errors.length > 0) {
+ lines.push("Visual regression infrastructure errors:");
+ lines.push(...report.errors.map((error) => `- ${error}`));
+ }
+ const differences = report.comparisons.filter(
+ ({ status }) => status !== "unchanged"
+ );
+ if (differences.length === 0) {
+ return lines;
+ }
+ lines.push("Visual regression diagnostics:");
+ for (const comparison of differences) {
+ const file =
+ comparison.file === undefined ? "" : ` file=${comparison.file}`;
+ const metrics =
+ comparison.differentPixels === undefined ||
+ comparison.mismatchPercentage === undefined
+ ? ""
+ : `: ${comparison.differentPixels} pixels, ${comparison.mismatchPercentage.toFixed(4)}% mismatch`;
+ lines.push(
+ `- ${comparison.status} ${comparison.id} (${comparison.title} / ${comparison.name})${file}${metrics}`
+ );
+ if (comparison.error !== undefined) {
+ lines.push(` error: ${comparison.error}`);
+ }
+ if (comparison.regions !== undefined && comparison.regions.length > 0) {
+ lines.push(
+ ` regions: ${comparison.regions
+ .map(
+ ({ bounds, pixelCount }) =>
+ `x=${bounds.x} y=${bounds.y} width=${bounds.width} height=${bounds.height} pixels=${pixelCount}`
+ )
+ .join("; ")}`
+ );
+ }
+ if (comparison.warnings !== undefined && comparison.warnings.length > 0) {
+ lines.push(` warnings: ${comparison.warnings.join(", ")}`);
+ }
+ const artifacts = formatArtifactPaths(comparison);
+ if (artifacts !== undefined) {
+ lines.push(artifacts);
+ }
+ }
+ return lines;
+};
diff --git a/scripts/visual-regression/run.ts b/scripts/visual-regression/run.ts
index 559517d16c..b70c7b8434 100644
--- a/scripts/visual-regression/run.ts
+++ b/scripts/visual-regression/run.ts
@@ -40,6 +40,11 @@ import {
startVisualStoryServer,
startVisualStoryServers,
} from "./story-server";
+import {
+ formatVisualRegressionDiagnostics,
+ getIsolatedVerificationServers,
+ getStoryPairs,
+} from "./run-utils";
const repositoryRoot = process.cwd();
const outputRoot = path.join(repositoryRoot, ".visual-regression");
@@ -281,6 +286,7 @@ const verifyChangedCaptures = async ({
browserSession,
checkout,
baselineBundleDirectory,
+ currentBundleDirectory,
servers,
}: {
comparisons: Awaited<ReturnType<typeof compareStories>>;
@@ -293,6 +299,7 @@ const verifyChangedCaptures = async ({
browserSession: BrowserScreenshotSession | undefined;
checkout: string;
baselineBundleDirectory: string;
+ currentBundleDirectory: string;
servers: Array<Awaited<ReturnType<typeof startVisualStoryServer>>>;
}) => {
const changedIds = comparisons
@@ -338,22 +345,27 @@ const verifyChangedCaptures = async ({
return { comparisons, performed: true };
}
- const changedPairs = remainingChangedIds.flatMap((id) => {
- const baseline = baselineEntries[id];
- const current = currentEntries[id];
- return baseline === undefined || current === undefined
- ? []
- : [{ baseline, current }];
+ const changedPairs = getStoryPairs({
+ ids: remainingChangedIds,
+ baselineEntries,
+ currentEntries,
});
if (cachedBaseline) {
await installBaselineDependencies(checkout);
+ await Promise.all(servers.map((server) => server.close()));
+ servers.length = 0;
servers.push(
- await startVisualStoryServer({
- root: checkout,
- port: visualRegressionConfig.servers.baselinePort,
- outputDirectory: baselineBundleDirectory,
- storyFiles: changedPairs.map(({ baseline }) => baseline.file),
- })
+ ...(await startVisualStoryServers(
+ getIsolatedVerificationServers({
+ repositoryRoot,
+ checkout,
+ baselineBundleDirectory,
+ currentBundleDirectory,
+ baselinePort: visualRegressionConfig.servers.baselinePort,
+ currentPort: visualRegressionConfig.servers.currentPort,
+ pairs: changedPairs,
+ })
+ ))
);
}
const pairedVerification = await captureStoryPairs({
@@ -561,6 +573,7 @@ const main = async () => {
browserSession,
checkout,
baselineBundleDirectory,
+ currentBundleDirectory,
servers,
});
comparisons = verification.comparisons;
@@ -617,6 +630,9 @@ const main = async () => {
throw new Error("Visual comparison did not produce a report.");
}
await writeScreenshotComparisonReport({ report, reportDirectory });
+ for (const line of formatVisualRegressionDiagnostics(report)) {
+ console.error(line);
+ }
const comparisonResult = classifyScreenshotComparisonReport(report);
const result =
comparisonResult === "failure"