Open source website builder and Webflow alternative. Webstudio is an advanced visual builder that connects to any headless CMS, supports all CSS properties, and can be hosted anywhere, including with us.
TypeScript accessibilityalternativecloudflarecloudflare-workersdesignfreefrontendopen-sourceradix-uireactremixweb-developmentwebflowwebsite-builderwebsite-developmentwebsiteswebstudio
feat: Customize Form progress feedback (#6606)
Oleg Isonen9a8ae2dc8f3f
diff --git a/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts b/apps/builder/app/builder/features/settings-panel/form-context-preview.test.tsindex db0857ed44..73e224c81b 100644--- a/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts+++ b/apps/builder/app/builder/features/settings-panel/form-context-preview.test.ts@@ -1,14 +1,124 @@import { expect, test } from "vitest";-import type { DataSource, Instances } from "@webstudio-is/sdk";+import type { DataSource, Instances, Props } from "@webstudio-is/sdk";import { encodeDataVariableId } from "@webstudio-is/sdk";+import { getCompletionTarget } from "~/builder/shared/expression-editor";+import { evaluateExpressionWithinScope } from "~/builder/shared/binding-popover";import { getResourceScopeForInstance } from "./resource-scope";import {getFormDataPreview,getBrowserInfoPreview,getFormParameterName,resolveFormParameterPreview,+ getFormProgressCompletionScope,} from "./form-context-preview";+test("Form file metadata is suggested only for its bound output variable", async () => {+ const instances: Instances = new Map([+ [+ "form",+ { id: "form", type: "instance", component: "ResourceForm", children: [] },+ ],+ [+ "child",+ { id: "child", type: "instance", component: "Text", children: [] },+ ],+ ]);+ const output: DataSource = {+ id: "progress-id",+ type: "variable",+ name: "renamedProgress",+ scopeInstanceId: "form",+ value: {+ type: "json",+ value: { status: "idle", loaded: 0, total: 0, files: [] },+ },+ };+ const unrelated: DataSource = {+ ...output,+ id: "unrelated-id",+ name: "formProgress",+ };+ const props: Props = new Map([+ [+ "callback",+ {+ id: "callback",+ instanceId: "form",+ name: "onProgressChange",+ type: "action",+ value: [+ {+ type: "execute",+ args: ["value"],+ code: `${encodeDataVariableId(output.id)} = value`,+ },+ ],+ },+ ],+ ]);+ const key = encodeDataVariableId(output.id);+ const otherKey = encodeDataVariableId(unrelated.id);+ const actual = { status: "idle", loaded: 0, total: 0, files: [] };+ const scope = { [key]: actual, [otherKey]: actual };+ const args = {+ instances,+ props,+ dataSources: new Map([+ [output.id, output],+ [unrelated.id, unrelated],+ ]),+ scope,+ };+ const completionScope = getFormProgressCompletionScope(args)!;+ expect(+ getCompletionTarget({+ scope: completionScope,+ path: [key, "files", "0"],+ name: "",+ })+ ).toEqual({+ id: "example-file",+ fieldName: "attachment",+ name: "example.txt",+ size: 0,+ type: "text/plain",+ });+ expect(+ getCompletionTarget({+ scope: completionScope,+ path: [otherKey, "files", "0"],+ name: "",+ })+ ).toBeUndefined();+ expect(scope[key].files).toEqual([]);+ expect(+ await evaluateExpressionWithinScope(`${key}.files.length`, scope)+ ).toBe(0);+ expect(completionScope[key]).not.toBe(scope[key]);+ expect(+ getFormProgressCompletionScope({ ...args, scope: { [otherKey]: actual } })+ ).toBeUndefined();++ const selected = {+ ...actual,+ files: [+ {+ id: "real",+ fieldName: "photo",+ name: "photo.png",+ size: 12,+ type: "image/png",+ },+ ],+ };+ expect(+ getFormProgressCompletionScope({+ ...args,+ scope: { ...scope, [key]: selected },+ })+ ).toBeUndefined();+});+test("form context uses mounted browser controls and excludes unchecked controls", () => {const form = document.createElement("form");form.dataset.wsManagedFormId = "form";diff --git a/apps/builder/app/builder/features/settings-panel/form-context-preview.ts b/apps/builder/app/builder/features/settings-panel/form-context-preview.tsindex eacb8afdfd..92fdf0e391 100644--- a/apps/builder/app/builder/features/settings-panel/form-context-preview.ts+++ b/apps/builder/app/builder/features/settings-panel/form-context-preview.ts@@ -1,4 +1,14 @@-import type { DataSource, Instances } from "@webstudio-is/sdk";+import type {+ DataSource,+ DataSources,+ Instances,+ Props,+} from "@webstudio-is/sdk";+import {+ decodeDataSourceVariable,+ encodeDataSourceVariable,+} from "@webstudio-is/sdk";+import { transpileExpression } from "@webstudio-is/expression";import {browserInfoParameterName,formDataParameterName,@@ -86,3 +96,80 @@ export const resolveFormParameterPreview = (: getBrowserInfoPreview(liveBrowserInfo.get(formId));return { name, value: toPublicPreviewValue(value) };};++/** Add an example file only to autocomplete for a visible Form output variable. */+export const getFormProgressCompletionScope = ({+ instances,+ props,+ dataSources,+ scope,+}: {+ instances: Instances;+ props: Props;+ dataSources: DataSources;+ scope: Record<string, unknown>;+}) => {+ let completionScope: Record<string, unknown> | undefined;+ for (const callback of props.values()) {+ if (+ callback.name !== "onProgressChange" ||+ callback.type !== "action" ||+ instances.get(callback.instanceId)?.component !== "ResourceForm"+ ) {+ continue;+ }+ const assigned = new Set<string>();+ for (const action of callback.value) {+ try {+ transpileExpression({+ expression: action.code,+ replaceVariable: (identifier, assignee) => {+ if (assignee) {+ assigned.add(identifier);+ }+ },+ });+ } catch {+ assigned.clear();+ break;+ }+ }+ if (assigned.size !== 1) {+ continue;+ }+ const sourceId = decodeDataSourceVariable(assigned.values().next().value!);+ const source =+ sourceId === undefined ? undefined : dataSources.get(sourceId);+ if (+ source?.type !== "variable" ||+ source.scopeInstanceId !== callback.instanceId+ ) {+ continue;+ }+ const key = encodeDataSourceVariable(source.id);+ const value = scope[key];+ if (+ typeof value !== "object" ||+ value === null ||+ !("files" in value) ||+ !Array.isArray(value.files) ||+ value.files.length !== 0+ ) {+ continue;+ }+ completionScope ??= { ...scope };+ completionScope[key] = {+ ...value,+ files: [+ {+ id: "example-file",+ fieldName: "attachment",+ name: "example.txt",+ size: 0,+ type: "text/plain",+ },+ ],+ };+ }+ return completionScope;+};diff --git a/apps/builder/app/builder/features/settings-panel/form-progress-completion.test.tsx b/apps/builder/app/builder/features/settings-panel/form-progress-completion.test.tsxnew file mode 100644index 0000000000..1b2ca0d70f--- /dev/null+++ b/apps/builder/app/builder/features/settings-panel/form-progress-completion.test.tsx@@ -0,0 +1,159 @@+import { act } from "react-dom/test-utils";+import { createRoot } from "react-dom/client";+import { test, expect, vi } from "vitest";+import { EditorView } from "@codemirror/view";+import { currentCompletions, startCompletion } from "@codemirror/autocomplete";+import { TooltipProvider } from "@webstudio-is/design-system";+import { $builderMode } from "~/shared/nano-states";+import {+ encodeDataSourceVariable,+ type DataSource,+ type Instances,+ type Props,+} from "@webstudio-is/sdk";+import {+ ExpressionCompletionScopeContext,+ ExpressionEditor,+} from "~/builder/shared/expression-editor";+import {+ BindingPopover,+ evaluateExpressionWithinScope,+} from "~/builder/shared/binding-popover";+import { getResourceScopeForInstance } from "./resource-scope";+import { getFormProgressCompletionScope } from "./form-context-preview";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++test("Resource expression suggests example file fields while evaluating real empty files", async () => {+ const variable: DataSource = {+ id: "output",+ type: "variable",+ name: "renamedProgress",+ scopeInstanceId: "form",+ value: {+ type: "json",+ value: { status: "idle", loaded: 0, total: 0, files: [] },+ },+ };+ const instances: Instances = new Map([+ [+ "form",+ { id: "form", type: "instance", component: "ResourceForm", children: [] },+ ],+ ]);+ const props: Props = new Map([+ [+ "callback",+ {+ id: "callback",+ instanceId: "form",+ name: "onProgressChange",+ type: "action",+ value: [+ {+ type: "execute",+ args: ["value"],+ code: `${encodeDataSourceVariable(variable.id)} = value`,+ },+ ],+ },+ ],+ ]);+ const dataSources = new Map([[variable.id, variable]]);+ const actual = { status: "idle", loaded: 0, total: 0, files: [] };+ const { scope, aliases } = getResourceScopeForInstance({+ page: undefined,+ instanceKey: "form,root",+ dataSources,+ variableValuesByInstanceSelector: new Map([+ ["form,root", new Map([[variable.id, actual]])],+ ]),+ formScopeInstanceId: "form",+ formScopeSelector: ["form", "root"],+ });+ const resolve = (value: Record<string, unknown>) =>+ getFormProgressCompletionScope({+ instances,+ props,+ dataSources,+ scope: value,+ });+ const container = document.createElement("div");+ document.body.appendChild(container);+ const root = createRoot(container);+ const previousMode = $builderMode.get();+ $builderMode.set("design");+ try {+ await act(async () =>+ root.render(+ <TooltipProvider>+ <ExpressionCompletionScopeContext.Provider value={resolve}>+ <ExpressionEditor+ value="renamedProgress.files[0]."+ scope={scope}+ aliases={aliases}+ onChange={() => {}}+ onChangeComplete={() => {}}+ />+ </ExpressionCompletionScopeContext.Provider>+ </TooltipProvider>+ )+ );+ const view = EditorView.findFromDOM(container.querySelector(".cm-editor")!);+ expect(view).toBeDefined();+ view!.dispatch({ selection: { anchor: view!.state.doc.length } });+ await act(async () => {+ startCompletion(view!);+ });+ await expect+ .poll(() => currentCompletions(view!.state).map(({ label }) => label))+ .toContain("name");+ expect(currentCompletions(view!.state).map(({ label }) => label)).toEqual(+ expect.arrayContaining(["id", "fieldName", "name", "size", "type"])+ );+ expect(+ await evaluateExpressionWithinScope(+ `${encodeDataSourceVariable(variable.id)}.files.length`,+ scope+ )+ ).toBe(0);+ expect(actual.files).toEqual([]);+ const onRemove = vi.fn();+ await act(async () =>+ root.render(+ <TooltipProvider>+ <ExpressionCompletionScopeContext.Provider value={resolve}>+ <BindingPopover+ scope={scope}+ aliases={aliases}+ variant="bound"+ value={`${encodeDataSourceVariable(variable.id)}.files`}+ onChange={() => {}}+ onRemove={onRemove}+ />+ </ExpressionCompletionScopeContext.Provider>+ </TooltipProvider>+ )+ );+ await act(async () => {+ container+ .querySelector<HTMLButtonElement>('button[data-variant="bound"]')!+ .click();+ await new Promise<void>((resolve) =>+ requestAnimationFrame(() => resolve())+ );+ });+ const reset = document.querySelector<HTMLButtonElement>(+ '[aria-label="Reset binding"]'+ );+ expect(reset).not.toBeNull();+ await act(async () => reset!.click());+ expect(onRemove).toHaveBeenCalledExactlyOnceWith([]);+ } finally {+ await act(async () => root.unmount());+ $builderMode.set(previousMode);+ container.remove();+ }+});diff --git a/apps/builder/app/builder/features/settings-panel/preview-form-response.test.tsx b/apps/builder/app/builder/features/settings-panel/preview-form-response.test.tsxindex 67c51bfd55..2910a1fbe0 100644--- a/apps/builder/app/builder/features/settings-panel/preview-form-response.test.tsx+++ b/apps/builder/app/builder/features/settings-panel/preview-form-response.test.tsx@@ -2,7 +2,7 @@ import { act } from "react-dom/test-utils";import { createRoot } from "react-dom/client";import { afterEach, expect, test, vi } from "vitest";import { TooltipProvider } from "@webstudio-is/design-system";-import { fetch as builderFetch } from "~/shared/fetch.client";+import { updateCsrfToken } from "~/shared/csrf.client";import { $project } from "~/shared/sync/data-stores";import { draftPersistence } from "~/shared/sync/draft-persistence";import { submitPreviewForm } from "~/shared/preview-form-bridge";@@ -34,7 +34,29 @@ vi.mock("@webstudio-is/protocol", async (importOriginal) => ({...(await importOriginal<typeof import("@webstudio-is/protocol")>()),parseBuilderUrl: () => ({ projectId: "project" }),}));-vi.mock("~/shared/fetch.client", () => ({ fetch: vi.fn() }));++class FormRequest {+ static requests: FormRequest[] = [];+ static responseText = "";+ upload = {};+ onload?: () => void;+ status = 200;+ responseText = FormRequest.responseText;++ constructor() {+ FormRequest.requests.push(this);+ }++ open() {}+ setRequestHeader() {}+ getResponseHeader() {+ return "application/json";+ }+ send() {+ queueMicrotask(() => this.onload?.());+ }+ abort() {}+}(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -45,9 +67,13 @@ afterEach(() => {$project.set(undefined);listeners.clear();vi.clearAllMocks();+ vi.unstubAllGlobals();+ FormRequest.requests = [];});test("Preview email response survives metadata refresh and editor reopening, but clears on project switch", async () => {+ updateCsrfToken("fixture");+ vi.stubGlobal("XMLHttpRequest", FormRequest);$project.set({ id: "project", title: "Before" } as never);draftPersistence.reset("project");const exchange = {@@ -69,21 +95,20 @@ test("Preview email response survives metadata refresh and editor reopening, buttruncated: false,},};- vi.mocked(builderFetch).mockResolvedValue(- Response.json({- success: true,- status: 200,- results: [- {- resourceId: "email-resource",- status: 200,- body: { id: "public-form-result" },- },- ],- errors: [],- previewExchanges: [exchange],- })- );+ const response = {+ success: true,+ status: 200,+ results: [+ {+ resourceId: "email-resource",+ status: 200,+ body: { id: "public-form-result" },+ },+ ],+ errors: [],+ previewExchanges: [exchange],+ };+ FormRequest.responseText = JSON.stringify(response);const publish = vi.fn(({ type, payload }: { type: string; payload?: unknown }) => {for (const listener of listeners.get(type) ?? []) {@@ -170,7 +195,7 @@ test("Preview email response survives metadata refresh and editor reopening, butawait expect.poll(() => activePanel()?.textContent).toContain("captured-email-service-response");- expect(builderFetch).toHaveBeenCalledOnce();+ expect(FormRequest.requests).toHaveLength(1);await act(async () => $project.set({ id: "another-project" } as never));expect($previewFormExchanges.get().size).toBe(0);expect($resourcePreviewExchanges.get().size).toBe(0);diff --git a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx b/apps/builder/app/builder/features/settings-panel/settings-panel.tsxindex adf7d79128..96c636954d 100644--- a/apps/builder/app/builder/features/settings-panel/settings-panel.tsx+++ b/apps/builder/app/builder/features/settings-panel/settings-panel.tsx@@ -15,6 +15,10 @@ import { UpgradeIcon } from "@webstudio-is/icons";import { useStore } from "@nanostores/react";import cmsUpgradeBanner from "~/shared/cms-upgrade-banner.svg?url";import { $isDesignMode, $permissions } from "~/shared/nano-states";+import { $dataSources, $instances, $props } from "~/shared/sync/data-stores";+import { ExpressionCompletionScopeContext } from "~/builder/shared/expression-editor";+import { getFormProgressCompletionScope } from "./form-context-preview";+import { useCallback } from "react";export const SettingsPanel = ({selectedInstance,@@ -25,44 +29,54 @@ export const SettingsPanel = ({}) => {const { allowDynamicData } = useStore($permissions);const isDesignMode = useStore($isDesignMode);+ const instances = useStore($instances);+ const props = useStore($props);+ const dataSources = useStore($dataSources);+ const resolveCompletionScope = useCallback(+ (scope: Record<string, unknown>) =>+ getFormProgressCompletionScope({ instances, props, dataSources, scope }),+ [instances, props, dataSources]+ );return (- <Box css={{ pt: theme.spacing[5] }}>- <SettingsSection />+ <ExpressionCompletionScopeContext.Provider value={resolveCompletionScope}>+ <Box css={{ pt: theme.spacing[5] }}>+ <SettingsSection />- <PropsSectionContainer- selectedInstance={selectedInstance}- selectedInstanceKey={selectedInstanceKey}- />+ <PropsSectionContainer+ selectedInstance={selectedInstance}+ selectedInstanceKey={selectedInstanceKey}+ />- {isDesignMode && <VariablesSection />}+ {isDesignMode && <VariablesSection />}- {allowDynamicData === false && (- <PanelBanner>- <img- src={cmsUpgradeBanner}- alt="Upgrade for CMS"- width={rawTheme.spacing[28]}- style={{ aspectRatio: "4.1" }}- />- <Text variant="regularBold">Upgrade for CMS on custom domains</Text>- <Text>- Integrate content from other tools to create blogs, directories, and- any other structured content. You can preview CMS on staging without- upgrading.- </Text>- <Flex align="center" gap={1}>- <UpgradeIcon />- <Link- color="inherit"- target="_blank"- href="https://webstudio.is/pricing"- >- Upgrade to Pro- </Link>- </Flex>- </PanelBanner>- )}- </Box>+ {allowDynamicData === false && (+ <PanelBanner>+ <img+ src={cmsUpgradeBanner}+ alt="Upgrade for CMS"+ width={rawTheme.spacing[28]}+ style={{ aspectRatio: "4.1" }}+ />+ <Text variant="regularBold">Upgrade for CMS on custom domains</Text>+ <Text>+ Integrate content from other tools to create blogs, directories,+ and any other structured content. You can preview CMS on staging+ without upgrading.+ </Text>+ <Flex align="center" gap={1}>+ <UpgradeIcon />+ <Link+ color="inherit"+ target="_blank"+ href="https://webstudio.is/pricing"+ >+ Upgrade to Pro+ </Link>+ </Flex>+ </PanelBanner>+ )}+ </Box>+ </ExpressionCompletionScopeContext.Provider>);};diff --git a/apps/builder/app/builder/features/settings-panel/variables-section.tsx b/apps/builder/app/builder/features/settings-panel/variables-section.tsxindex e554e06d9d..5b7100b1bb 100644--- a/apps/builder/app/builder/features/settings-panel/variables-section.tsx+++ b/apps/builder/app/builder/features/settings-panel/variables-section.tsx@@ -156,6 +156,8 @@ const formVariableDescriptions: Record<string, string> = {browserInfo:"Visitor IP address, browser, language, and referrer available to this Form.",formState: "The current Form state: initial, success, or error.",+ formProgress:+ "Submission activity, upload byte counts, and selected file details.",results:"Responses from selected actions, in order. Each includes the resource name, HTTP status code, and response body.",errors:diff --git a/apps/builder/app/builder/shared/expression-editor.tsx b/apps/builder/app/builder/shared/expression-editor.tsxindex 2be14f28d7..480001dc1b 100644--- a/apps/builder/app/builder/shared/expression-editor.tsx+++ b/apps/builder/app/builder/shared/expression-editor.tsx@@ -1,4 +1,10 @@-import { useEffect, useMemo, type RefObject } from "react";+import {+ createContext,+ useContext,+ useEffect,+ useMemo,+ type RefObject,+} from "react";import { matchSorter } from "match-sorter";import type { SyntaxNode } from "@lezer/common";import { Facet, RangeSetBuilder } from "@codemirror/state";@@ -100,10 +106,16 @@ export const formatValuePreview = (value: unknown) => {type Scope = Record<string, unknown>;+/** Allows an editor owner to supply examples without changing actual values. */+export const ExpressionCompletionScopeContext = createContext<+ ((scope: Scope) => Scope | undefined) | undefined+>(undefined);+type Aliases = Map<string, string>;const VariablesData = Facet.define<{scope: Scope;+ completionScope: Scope;aliases: Aliases;}>();@@ -379,12 +391,12 @@ export const getCompletionReplacement = ({// object (for example `globalThis`). Will enter properties// of the object when completing properties on a directly-named path.const scopeCompletionSource: CompletionSource = (context) => {- const [{ scope }] = context.state.facet(VariablesData);+ const [{ completionScope }] = context.state.facet(VariablesData);const path = completionPath(context);if (path === undefined) {return null;}- const target = getCompletionTarget({ ...path, scope });+ const target = getCompletionTarget({ ...path, scope: completionScope });if (target === undefined) {return null;}@@ -594,6 +606,11 @@ export const ExpressionEditor = ({onChange: (value: string) => void;onChangeComplete: (value: string) => void;}) => {+ const resolveCompletionScope = useContext(ExpressionCompletionScopeContext);+ const completionScope = useMemo(+ () => resolveCompletionScope?.(scope),+ [resolveCompletionScope, scope]+ );const normalizedValue = normalizeEditorValue(value);const { nameById, idByName } = useMemo(() => {const nameById = new Map();@@ -623,6 +640,19 @@ export const ExpressionEditor = ({}return newScope;}, [scope, aliases]);+ const completionScopeWithUnsetVariables = useMemo(() => {+ if (completionScope === undefined) {+ return scopeWithUnsetVariables;+ }+ const newScope: Scope = {};+ for (const [identifier, value] of Object.entries(completionScope)) {+ const name = aliases.get(identifier);+ if (name) {+ newScope[encodeDataVariableName(name)] = value;+ }+ }+ return newScope;+ }, [completionScope, scopeWithUnsetVariables, aliases]);const aliasesWithUnsetVariables = useMemo(() => {const newAliases: typeof aliases = new Map();for (const [_identifier, name] of aliases) {@@ -638,6 +668,7 @@ export const ExpressionEditor = ({javascript({}),VariablesData.of({scope: scopeWithUnsetVariables,+ completionScope: completionScopeWithUnsetVariables,aliases: aliasesWithUnsetVariables,}),// render autocomplete in body@@ -654,7 +685,13 @@ export const ExpressionEditor = ({...(showLineNumbers ? [lineNumbers()] : []),...(size === "full" ? [fullSizeEditorTheme] : []),],- [scopeWithUnsetVariables, aliasesWithUnsetVariables, size, showLineNumbers]+ [+ scopeWithUnsetVariables,+ completionScopeWithUnsetVariables,+ aliasesWithUnsetVariables,+ size,+ showLineNumbers,+ ]);const dialogExtensions = useMemo(() => [diff --git a/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx b/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsxindex 94c9ae4fd1..f476bcd6bf 100644--- a/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/preview-form-lifecycle.test.tsx@@ -10,6 +10,7 @@ import { encodeDataVariableId, type Instance } from "@webstudio-is/sdk";import { $dataSources, $instances, $props } from "~/shared/sync/data-stores";import { $variableValuesByInstanceSelector } from "~/shared/nano-states";import { WebstudioComponentPreview } from "./webstudio-component";+import type { FormProgress } from "@webstudio-is/sdk/form/browser";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -80,6 +81,74 @@ test.each([true, false])(});+test("Preview clears in-flight Form transfer details on renderer switch", async () => {+ $builderMode.set("preview");+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ const submit = vi.fn(() => new Promise<never>(() => {}));+ const Harness = () => {+ const isPreviewMode = useStore($isPreviewMode);+ const [progress, setProgress] = useState<FormProgress>({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+ return (+ <>+ <output data-transfer-files>{progress.files.length}</output>+ <output data-transfer-status>{progress.status}</output>+ <output data-transfer-bytes>+ {progress.loaded}/{progress.total}+ </output>+ {isPreviewMode ? (+ <__testing__.PreviewResourceForm+ action={[{ dataSourceId: "request" }]}+ onManagedSubmit={submit}+ onProgressChange={setProgress}+ >+ <input name="attachment" type="file" />+ <button type="submit">Send</button>+ </__testing__.PreviewResourceForm>+ ) : (+ <div data-renderer="canvas" />+ )}+ </>+ );+ };+ await act(async () => root?.render(<Harness />));+ const input =+ container.querySelector<HTMLInputElement>('input[type="file"]')!;+ const files = new DataTransfer();+ files.items.add(new File(["attached"], "note.txt"));+ input.files = files.files;+ await act(async () => container.querySelector("button")?.click());+ expect(container.querySelector("[data-transfer-files]")?.textContent).toBe(+ "1"+ );+ expect(container.querySelector("[data-transfer-status]")?.textContent).toBe(+ "pending"+ );+ await act(async () => $builderMode.set("design"));+ expect(container.querySelector("[data-transfer-files]")?.textContent).toBe(+ "0"+ );+ expect(container.querySelector("[data-transfer-status]")?.textContent).toBe(+ "idle"+ );+ expect(container.querySelector("[data-transfer-bytes]")?.textContent).toBe(+ "0/0"+ );+ await act(async () => $builderMode.set("preview"));+ expect(container.querySelector("[data-transfer-files]")?.textContent).toBe(+ "0"+ );+ expect(container.querySelector("[data-transfer-status]")?.textContent).toBe(+ "idle"+ );+});+test.each([true, false])("uncontrolled managed Form resets after renderer switch from Preview outcome %s",async (success) => {diff --git a/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx b/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsxindex d1cc305894..f119f0bc61 100644--- a/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx+++ b/apps/builder/app/canvas/features/webstudio-component/preview-resource-form.tsx@@ -10,6 +10,7 @@ import { mergeRefs } from "@react-aria/utils";import { selectorIdAttribute } from "@webstudio-is/react-sdk";import { ResourceForm } from "@webstudio-is/sdk-components-react/components";import type { submitManagedForm } from "@webstudio-is/sdk-components-react";+import type { UploadProgress } from "@webstudio-is/sdk/form/browser";import type { ManagedFormResponse } from "@webstudio-is/sdk/runtime";import { $selectedPageHash } from "~/shared/nano-states/pages";import { $currentSystem } from "~/shared/system";@@ -23,7 +24,8 @@ import { getPreviewCurrentUrl } from "./preview-current-url";export const submitManagedFormFromPreview = (managedFormId: string,values: Parameters<typeof submitManagedForm>[0]["values"],- signal: AbortSignal+ signal: AbortSignal,+ onUploadProgress?: (progress: UploadProgress) => void) => {const currentUrl = getPreviewCurrentUrl($currentSystem.get(),@@ -35,6 +37,7 @@ export const submitManagedFormFromPreview = (managedFormId,path: currentUrl.pathname + currentUrl.search,signal,+ onUploadProgress,});};@@ -47,8 +50,21 @@ export const PreviewResourceForm = forwardRef<const formRef = useRef<HTMLFormElement>(null);const onStateChangeRef = useRef(props.onStateChange);onStateChangeRef.current = props.onStateChange;+ const onProgressChangeRef = useRef(props.onProgressChange);+ onProgressChangeRef.current = props.onProgressChange;const formSelector = (props as Record<string, unknown>)[selectorIdAttribute];- useEffect(() => () => onStateChangeRef.current?.("initial"), []);+ useEffect(+ () => () => {+ onStateChangeRef.current?.("initial");+ onProgressChangeRef.current?.({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+ },+ []+ );const formId = props["data-ws-managed-form-id"];useEffect(() => {const form = formRef.current;@@ -122,9 +138,10 @@ export const getPreviewResourceFormProps = (formId: string) => {getRedirectBaseUrl: () => getPreviewUrl().href,onManagedSubmit: (values: Parameters<typeof submitManagedForm>[0]["values"],- signal: AbortSignal+ signal: AbortSignal,+ onUploadProgress?: (progress: UploadProgress) => void): Promise<ManagedFormResponse> =>- submitManagedFormFromPreview(formId, values, signal),+ submitManagedFormFromPreview(formId, values, signal, onUploadProgress),onSuccessRedirect: (destination: string) =>navigatePreviewFormSuccess(destination,diff --git a/apps/builder/app/shared/fetch.client.ts b/apps/builder/app/shared/fetch.client.tsindex 6af82a60ba..79b1c4efa3 100644--- a/apps/builder/app/shared/fetch.client.ts+++ b/apps/builder/app/shared/fetch.client.ts@@ -13,20 +13,14 @@ import { publicStaticEnv } from "~/env/env.static";*/const _fetch = globalThis.fetch;-/**- * To avoid fetch interception from the canvas, i.e., `globalThis.fetch = () => console.log('INTERCEPTED');`,- * To add csrf token to the headers.- */-export const fetch: typeof globalThis.fetch = async (- requestInfo,- requestInit-) => {+/** Apply the Builder request headers to both fetch and Form uploads. */+export const getBuilderRequestHeaders = (initial?: HeadersInit) => {if (csrfToken === undefined) {toast.error("CSRF token is not set.");throw new Error("CSRF token is not set.");}- const headers = new Headers(requestInit?.headers);+ const headers = new Headers(initial);headers.set("X-CSRF-Token", csrfToken);headers.set(apiClientHeader, "browser");@@ -40,13 +34,10 @@ export const fetch: typeof globalThis.fetch = async (headers.set("x-auth-token", authToken);}- const modifiedInit: RequestInit = {- ...requestInit,- cache: requestInit?.cache ?? "no-store",- headers,- };+ return headers;+};- const response = await _fetch(requestInfo, modifiedInit);+export const inspectBuilderResponse = async (response: Response) => {if (response.ok === false) {const contentType = response.headers.get("Content-Type") ?? "";if (contentType.includes("application/json")) {@@ -64,6 +55,22 @@ export const fetch: typeof globalThis.fetch = async (}}}+};++export const fetch: typeof globalThis.fetch = async (+ requestInfo,+ requestInit+) => {+ const headers = getBuilderRequestHeaders(requestInit?.headers);++ const modifiedInit: RequestInit = {+ ...requestInit,+ cache: requestInit?.cache ?? "no-store",+ headers,+ };++ const response = await _fetch(requestInfo, modifiedInit);+ await inspectBuilderResponse(response);return response;};diff --git a/apps/builder/app/shared/instance-utils/insert.test.tsx b/apps/builder/app/shared/instance-utils/insert.test.tsxindex 375f49c40a..09377e14fb 100644--- a/apps/builder/app/shared/instance-utils/insert.test.tsx+++ b/apps/builder/app/shared/instance-utils/insert.test.tsx@@ -935,6 +935,34 @@ describe("insert webstudio component at", () => {const formId =body?.children[0]?.type === "id" ? body.children[0].value : "";expect($instances.get().get(formId)?.component).toBe("ResourceForm");+ const status = Array.from($instances.get().values()).find(+ (instance) => instance.label === "Progress"+ );+ expect(status).toBeDefined();+ expect(+ Array.from($props.get().values()).find(+ (prop) =>+ prop.instanceId === status?.id && prop.name === "data-ws-show"+ )+ ).toMatchObject({ type: "expression" });+ const summaryId = status?.children.find(+ (child) => child.type === "id"+ )?.value;+ const summary = $instances.get().get(summaryId ?? "");+ const summaryText = summary?.children.find(+ (child) => child.type === "expression"+ );+ if (summaryText?.type !== "expression") {+ throw new Error("Expected a bound Form upload summary");+ }+ expect(+ lintExpression({+ expression: summaryText.value,+ availableVariables: new Set(+ Array.from($dataSources.get().keys(), encodeDataSourceVariable)+ ),+ })+ ).toEqual([]);const formProps = Array.from($props.get().values()).filter(({ instanceId }) => instanceId === formId);@@ -1015,6 +1043,9 @@ describe("insert webstudio component at", () => {);expect(evaluateOwnerBody("")).toBe("Name: Ada");expect(formProps.some(({ name }) => name === "onStateChange")).toBe(true);+ expect(formProps.some(({ name }) => name === "onProgressChange")).toBe(+ true+ );const resultProp = formProps.find(({ name }) => name === "onResultChange");@@ -1039,7 +1070,7 @@ describe("insert webstudio component at", () => {]),})).toEqual([]);- for (const name of ["results", "errors"]) {+ for (const name of ["formProgress", "results", "errors"]) {expect(Array.from($dataSources.get().values()).some((dataSource) =>@@ -1079,6 +1110,18 @@ describe("insert webstudio component at", () => {?.get("onStateChange") as (state: string) => void;expect(onStateChange).toBeTypeOf("function");onStateChange("error");+ const onProgressChange = $propValuesByInstanceSelector+ .get()+ .get(getInstanceKey([formId, "bodyId"]))+ ?.get("onProgressChange") as (value: unknown) => void;+ expect(onProgressChange).toBeTypeOf("function");+ const progress = {+ status: "pending",+ loaded: 4,+ total: 12,+ files: [],+ };+ onProgressChange(progress);const variables = new Map(Array.from($dataSources.get().values()).filter((dataSource) => dataSource.type === "variable")@@ -1089,6 +1132,7 @@ describe("insert webstudio component at", () => {);expect(variables.has("status")).toBe(false);expect(variables.get("formState")).toBe("error");+ expect(variables.get("formProgress")).toBe(progress);expect(variables.get("results")).toBe(result.results);expect(variables.get("errors")).toBe(result.errors);for (const child of $instances.get().get(formId)?.children ?? []) {@@ -1101,7 +1145,7 @@ describe("insert webstudio component at", () => {dataSources: $dataSources.get(),}).map(({ name }) => name);expect(availableNames).toEqual(- expect.arrayContaining(["results", "errors"])+ expect.arrayContaining(["formProgress", "results", "errors"]));}for (const name of ["formData", "browserInfo"]) {diff --git a/apps/builder/app/shared/preview-form-bridge.test.ts b/apps/builder/app/shared/preview-form-bridge.test.tsindex f5d87a494a..a40ce8860f 100644--- a/apps/builder/app/shared/preview-form-bridge.test.ts+++ b/apps/builder/app/shared/preview-form-bridge.test.ts@@ -1,10 +1,16 @@import { draftPersistence } from "./sync/draft-persistence";import { parseBuilderUrl } from "@webstudio-is/protocol";import { beforeEach, afterEach, expect, test, vi } from "vitest";-import { fetch as builderFetch } from "~/shared/fetch.client";+import type { submitManagedForm } from "@webstudio-is/sdk/form/browser";import { submitPreviewForm } from "./preview-form-bridge";import { subscribePreviewFormRequests } from "./preview-form-parent";import { $livePreviewBrowserInfo } from "./preview-form-values";+import { updateCsrfToken } from "./csrf.client";+import { inspectBuilderResponse } from "./fetch.client";+import {+ apiClientHeader,+ apiClientVersionHeader,+} from "@webstudio-is/trpc-interface/api-compatibility";const listeners = vi.hoisted(() => new Map<string, Set<(payload: unknown) => void>>()@@ -29,7 +35,7 @@ vi.mock("@webstudio-is/protocol", async (importOriginal) => ({parseBuilderUrl: () => ({ projectId: "project" }),}));-vi.mock("~/shared/fetch.client", () => ({ fetch: vi.fn() }));+const submit = vi.fn<typeof submitManagedForm>();const sendToCanvas = vi.fn(({ type, payload }: { type: string; payload?: unknown }) => {@@ -40,6 +46,7 @@ const sendToCanvas = vi.fn();beforeEach(() => {+ updateCsrfToken("fixture");draftPersistence.reset(parseBuilderUrl(window.location.href).projectId);});@@ -48,14 +55,22 @@ afterEach(() => {$livePreviewBrowserInfo.set(new Map());listeners.clear();vi.clearAllMocks();+ submit.mockReset();vi.useRealTimers();});-test("Preview sends the current FormData with files through the authenticated Builder fetch", async () => {+test("Preview passes files, request policy, and upload progress through the parent", async () => {const response = {success: true,status: 200,- results: [{ resourceId: "email", status: 200, body: { sent: true } }],+ results: [+ {+ resourceId: "email",+ resourceName: "email",+ status: 200,+ body: { sent: true },+ },+ ],errors: [],previewBrowserInfo: {ip: "203.0.113.10",@@ -64,14 +79,20 @@ test("Preview sends the current FormData with files through the authenticated Bureferrer: "https://builder.example/project",},};- vi.mocked(builderFetch).mockResolvedValue(Response.json(response));- const unsubscribe = subscribePreviewFormRequests(sendToCanvas);+ submit.mockImplementation(async ({ onUploadProgress }) => {+ onUploadProgress?.({ loaded: 4, total: 12 });+ onUploadProgress?.({ loaded: 12, total: 12 });+ return response;+ });+ const unsubscribe = subscribePreviewFormRequests(sendToCanvas, submit);const file = new File(["attached"], "note.txt", { type: "text/plain" });+ const progress: unknown[] = [];const result = submitPreviewForm({values: { email: "[email protected]", attachments: [file] },managedFormId: "form-1",path: "/contact?source=preview",signal: new AbortController().signal,+ onUploadProgress: (update) => progress.push(update),});await expect(result).resolves.toEqual({@@ -90,33 +111,38 @@ test("Preview sends the current FormData with files through the authenticated Bu(resultEvent?.payload as { response?: Record<string, unknown> } | undefined)?.response).not.toHaveProperty("previewBrowserInfo");- expect(builderFetch).toHaveBeenCalledOnce();- const [url, init] = vi.mocked(builderFetch).mock.calls[0];- expect(new URL(String(url)).pathname).toBe("/rest/preview-form");- expect(new URL(String(url)).searchParams.get("path")).toBe(+ expect(progress).toEqual([+ { loaded: 4, total: 12 },+ { loaded: 12, total: 12 },+ ]);+ expect(submit).toHaveBeenCalledOnce();+ const [input] = submit.mock.calls[0];+ expect(new URL(String(input.endpoint)).pathname).toBe("/rest/preview-form");+ expect(new URL(String(input.endpoint)).searchParams.get("path")).toBe("/contact?source=preview");- expect(init?.credentials).toBe("same-origin");- const formData = init?.body as FormData;- expect(formData.get("email")).toBe("[email protected]");- const attachment = formData.get("attachments") as File;+ expect(new Headers(input.headers).get("X-CSRF-Token")).toBe("fixture");+ expect(new Headers(input.headers).get(apiClientHeader)).toBe("browser");+ expect(new Headers(input.headers).get(apiClientVersionHeader)).toBeTruthy();+ expect(input.onResponse).toBe(inspectBuilderResponse);+ expect(input.values.email).toBe("[email protected]");+ const attachment = (input.values.attachments as File[])[0];expect(attachment.name).toBe("note.txt");expect(await attachment.text()).toBe("attached");- expect(formData.get("ws--managed-form-id")).toBe("form-1");- expect(formData.get("ws--managed-form-array-names")).toBe('["attachments"]');+ expect(input.managedFormId).toBe("form-1");unsubscribe();expect($livePreviewBrowserInfo.get()).toEqual(new Map());});test("aborting a Preview submission aborts the parent request and sends no result", async () => {- vi.mocked(builderFetch).mockImplementation((_url, init) => {+ submit.mockImplementation(({ signal }) => {return new Promise((_resolve, reject) => {- init?.signal?.addEventListener("abort", () => {+ signal?.addEventListener("abort", () => {reject(new DOMException("Aborted", "AbortError"));});});});- const unsubscribe = subscribePreviewFormRequests(sendToCanvas);+ const unsubscribe = subscribePreviewFormRequests(sendToCanvas, submit);const controller = new AbortController();const result = submitPreviewForm({values: { email: "[email protected]" },@@ -124,8 +150,8 @@ test("aborting a Preview submission aborts the parent request and sends no resulpath: "/contact",signal: controller.signal,});- await vi.waitFor(() => expect(builderFetch).toHaveBeenCalledOnce());- const requestSignal = vi.mocked(builderFetch).mock.calls[0][1]?.signal;+ await vi.waitFor(() => expect(submit).toHaveBeenCalledOnce());+ const requestSignal = submit.mock.calls[0][0].signal;controller.abort("cancelled");await expect(result).rejects.toBe("cancelled");@@ -161,7 +187,7 @@ test("times out and cleans up when the Builder does not answer", async () => {test("failed persistence returns an error without reaching the Preview endpoint", async () => {draftPersistence.begin("project", "failed-edit");draftPersistence.complete("project", "failed-edit", false);- const unsubscribe = subscribePreviewFormRequests(sendToCanvas);+ const unsubscribe = subscribePreviewFormRequests(sendToCanvas, submit);const result = await submitPreviewForm({values: {},managedFormId: "form",@@ -177,14 +203,14 @@ test("failed persistence returns an error without reaching the Preview endpoint"},],});- expect(builderFetch).not.toHaveBeenCalled();+ expect(submit).not.toHaveBeenCalled();unsubscribe();});test("live Preview values update Builder memory without submitting or saving", async () => {const { publish } = await import("./pubsub");const { $livePreviewFormValues } = await import("./preview-form-values");- const cleanup = subscribePreviewFormRequests(publish);+ const cleanup = subscribePreviewFormRequests(publish, submit);try {publish({type: "previewFormValues",@@ -231,7 +257,7 @@ test("live Preview values update Builder memory without submitting or saving", aexpect($livePreviewFormValues.get().get("form,collection[two],root")).toEqual({ text: "another occurrence" });- expect(builderFetch).not.toHaveBeenCalled();+ expect(submit).not.toHaveBeenCalled();publish({type: "previewFormValues",payload: {@@ -282,11 +308,9 @@ test.each(["network", "draft"])(draftPersistence.begin("project", "failed-edit");draftPersistence.complete("project", "failed-edit", false);} else {- vi.mocked(builderFetch).mockRejectedValueOnce(- new Error("Fixture network failure")- );+ submit.mockRejectedValueOnce(new Error("Fixture network failure"));}- const unsubscribe = subscribePreviewFormRequests(sendToCanvas);+ const unsubscribe = subscribePreviewFormRequests(sendToCanvas, submit);try {const result = await submitPreviewForm({values: {},diff --git a/apps/builder/app/shared/preview-form-bridge.ts b/apps/builder/app/shared/preview-form-bridge.tsindex ca0de6fd3b..2679fe1f41 100644--- a/apps/builder/app/shared/preview-form-bridge.ts+++ b/apps/builder/app/shared/preview-form-bridge.ts@@ -1,5 +1,6 @@import type { ManagedFormResponse } from "@webstudio-is/sdk/runtime";import type { submitManagedForm } from "@webstudio-is/sdk-components-react";+import type { UploadProgress } from "@webstudio-is/sdk/form/browser";import { publish, subscribe } from "~/shared/pubsub";type PreviewFormValues = Parameters<typeof submitManagedForm>[0]["values"];@@ -22,6 +23,7 @@ declare module "~/shared/pubsub" {previewFormSubmit: PreviewFormRequest;previewFormCancel: { id: string };previewFormResult: PreviewFormResult;+ previewFormProgress: { id: string; progress: UploadProgress };}}@@ -31,7 +33,11 @@ export const submitPreviewForm = ({managedFormId,path,signal,-}: Omit<PreviewFormRequest, "id"> & { signal: AbortSignal }) => {+ onUploadProgress,+}: Omit<PreviewFormRequest, "id"> & {+ signal: AbortSignal;+ onUploadProgress?: (progress: UploadProgress) => void;+}) => {if (signal.aborted) {return Promise.reject(signal.reason);}@@ -41,6 +47,7 @@ export const submitPreviewForm = ({const cleanup = () => {clearTimeout(timeoutId);unsubscribe();+ unsubscribeProgress();signal.removeEventListener("abort", onAbort);};const onAbort = () => {@@ -55,6 +62,11 @@ export const submitPreviewForm = ({cleanup();resolve(result.response);});+ const unsubscribeProgress = subscribe("previewFormProgress", (event) => {+ if (event.id === id && !signal.aborted) {+ onUploadProgress?.(event.progress);+ }+ });const timeoutId = setTimeout(() => {cleanup();reject(new Error("Preview Form submission timed out"));diff --git a/apps/builder/app/shared/preview-form-parent.ts b/apps/builder/app/shared/preview-form-parent.tsindex 530c80c97f..d5f97bf879 100644--- a/apps/builder/app/shared/preview-form-parent.ts+++ b/apps/builder/app/shared/preview-form-parent.ts@@ -14,7 +14,10 @@ import {import { parseBuilderUrl } from "@webstudio-is/protocol";import type { Publish } from "~/shared/pubsub";import { subscribe } from "~/shared/pubsub";-import { fetch as builderFetch } from "~/shared/fetch.client";+import {+ getBuilderRequestHeaders,+ inspectBuilderResponse,+} from "~/shared/fetch.client";import { submitManagedForm } from "@webstudio-is/sdk-components-react";import type { PreviewFormRequest } from "./preview-form-bridge";@@ -39,7 +42,10 @@ const getPreviewFormErrorMessage = (error: unknown) => {};/** Keep authenticated Preview requests in the Builder, outside the Canvas. */-export const subscribePreviewFormRequests = (publish: Publish) => {+export const subscribePreviewFormRequests = (+ publish: Publish,+ submit: typeof submitManagedForm = submitManagedForm+) => {const requests = new Map<string, AbortController>();const unsubscribeValues = subscribe("previewFormValues",@@ -70,13 +76,22 @@ export const subscribePreviewFormRequests = (publish: Publish) => {await draftPersistence.wait(projectId, { signal: controller.signal });const endpoint = new URL("/rest/preview-form", window.location.href);endpoint.searchParams.set("path", path);- const response = await submitManagedForm({+ const response = await submit({values,managedFormId,location: window.location.href,endpoint: endpoint.href,- fetch: builderFetch,+ headers: getBuilderRequestHeaders(),+ onResponse: inspectBuilderResponse,signal: controller.signal,+ onUploadProgress: (progress) => {+ if (!controller.signal.aborted) {+ publish({+ type: "previewFormProgress",+ payload: { id, progress },+ });+ }+ },});if (!controller.signal.aborted) {const { previewExchanges, previewBrowserInfo, ...publicResponse } =diff --git a/apps/builder/e2e/tests/preview-managed-form.[shard-1].e2e.ts b/apps/builder/e2e/tests/preview-managed-form.[shard-1].e2e.tsindex ffd67c4f9c..2c072a1c9c 100644--- a/apps/builder/e2e/tests/preview-managed-form.[shard-1].e2e.ts+++ b/apps/builder/e2e/tests/preview-managed-form.[shard-1].e2e.ts@@ -570,30 +570,21 @@ test("Preview Form preserves browser FormData and runs legacy disabled actions i});await page.addInitScript(() => {- const originalFetch = window.fetch;- window.fetch = async (input, init) => {- const formData = init?.body as FormData | undefined;- if (- new URL(- input instanceof Request ? input.url : String(input),- window.location.href- ).pathname === "/rest/preview-form" &&- typeof formData?.getAll === "function"- ) {- const upload = formData.get("upload") as File | null;- const submission = {- tags: formData.getAll("tag"),- fileName: upload?.name,- fileBytes:- typeof upload?.arrayBuffer === "function"- ? Array.from(new Uint8Array(await upload.arrayBuffer()))- : undefined,- };- (- window as Window & { __previewSubmission?: typeof submission }- ).__previewSubmission = submission;+ const originalSend = XMLHttpRequest.prototype.send;+ XMLHttpRequest.prototype.send = function (body) {+ if (body instanceof FormData && body.has("upload")) {+ const upload = body.get("upload");+ if (upload instanceof File) {+ (+ window as Window & { __previewSubmission?: Promise<unknown> }+ ).__previewSubmission = upload.arrayBuffer().then((bytes) => ({+ tags: body.getAll("tag"),+ fileName: upload.name,+ fileBytes: Array.from(new Uint8Array(bytes)),+ }));+ }}- return originalFetch(input, init);+ return originalSend.call(this, body);};});const submissions: Request[] = [];@@ -660,9 +651,10 @@ test("Preview Form preserves browser FormData and runs legacy disabled actions i.frames().map((frame) =>frame.evaluate(- () =>- (window as Window & { __previewSubmission?: unknown })- .__previewSubmission+ async () =>+ await (+ window as Window & { __previewSubmission?: Promise<unknown> }+ ).__previewSubmission)));diff --git a/docs/university/core-components/form.md b/docs/university/core-components/form.mdindex 63868e6a3d..c942b4a58a 100644--- a/docs/university/core-components/form.md+++ b/docs/university/core-components/form.md@@ -25,6 +25,7 @@ Insert **Form (Beta)** from **Components > Forms**. On Webstudio Cloud, the defa- **Email to owner**, which sends the submitted information and page URL to your project recipients.- **Email to visitor**, which sends a confirmation to the submitted email address.- Editable success and error messages.+- An editable message while the Form is submitting.If you haven’t configured project recipients, the owner notification goes to the account holder.@@ -229,15 +230,16 @@ Navigation mode does not use **Success redirect**. Use Resource actions when you## Choose what happens after submission-The default Form contains three containers:+The default Form contains four containers:- **Form content** holds the fields.+- **Progress** shows a message while the Form is submitting.- **Success message** appears after success.- **Error message** appears after failure.-Their **Show** bindings use `formState` to control visibility. By default, success hides the fields and shows the success message. Failure keeps the fields and entered values visible.+Their **Show** bindings use `formProgress.status` for Progress and `formState` for the other containers. By default, the fields remain visible while submitting and after a failure. Success hides the fields and shows the success message.-Select the message containers in Navigator to edit their text and design.+Select the message containers in Navigator to edit their text and design. Progress shows “Submitting…” and, when the browser measures the request, a short byte summary such as “1.2 MB / 3 MB”. The message stays visible while actions finish.### Keep the fields visible@@ -272,15 +274,26 @@ The default Form provides these Variables on the Form and its children:</picture></figure>+The screenshot predates `formProgress`; newly inserted Forms include it as shown below.+| Variable | What it contains || ------------- | ------------------------------------------------------------------------------------------------ || `formData` | Submitted values, keyed by field Name. || `browserInfo` | The page URL and available visitor details, such as browser, language, referrer, and IP address. |-| `formState` | `initial`, `success`, or `error`. |+| `formState` | `initial`, `success`, or `error`. |+| `formProgress` | Submission status, measured request bytes, and selected-file details. || `results` | Action responses in order, including Resource name, HTTP status, and response body. || `errors` | Failed action details, including available status, response body, and error message. |-Use `formData` and `browserInfo` to customize messages and requests. Use `results`, `errors`, and `formState` to display feedback after submission.+Use `formData` and `browserInfo` to customize messages and requests. Use `formProgress.status` to show when a request is pending, `formState` for its outcome, and `results` and `errors` for action feedback.++`formProgress.status` is `pending` while files upload and actions run. It returns to `idle` when the submission finishes or is canceled. `formProgress.loaded` and `formProgress.total` start at `0`. They count bytes sent for the complete request, including fields and multipart encoding, when the browser can measure them. A `total` of `0` means the total is not yet known. Use `formProgress.loaded / formProgress.total` for a percentage only when `total` is greater than zero.++`formProgress.files` lists each selected file with `id`, `fieldName`, `name`, `size` (bytes), and `type` (MIME type). The browser does not provide reliable transferred byte counts for individual files in this request, so only the whole-request measurements appear in `formProgress.loaded` and `formProgress.total`.++When adding a binding inside a Form, autocomplete shows one example file so you can discover these fields. The example is only a suggestion in the editor; the actual `files` value remains empty until a submission includes files.++The default `formProgress` variable is added to newly inserted Forms. Existing Forms keep their current `formState` bindings and submission message. Navigation mode changes the URL without a managed submission, so it leaves `formProgress` idle with no files.Create action Resources on the Form itself when they need these local bindings.diff --git a/docs/university/foundations/variables.md b/docs/university/foundations/variables.mdindex 67f20d47a3..917059a5cb 100644--- a/docs/university/foundations/variables.md+++ b/docs/university/foundations/variables.md@@ -106,7 +106,7 @@ The preview can load the request and show its response, request details, and errA new [Form](../core-components/form.md) includes two email resources. To add another destination, create a REST, GraphQL, or email resource in **Variables** on the Form or an ancestor. Then select the Form and use **Properties & Attributes > Action** to add the resource. Resources defined on the Form can bind to its `formData` and safe `browserInfo` values; ancestor resources cannot bind to those values. HTTP destinations always send POST requests when the Form is submitted, regardless of their configured method for ordinary data loading.-The Form also exposes `formState`, `results`, and `errors` in **Variables**. Use these to show the submission state and inspect the selected actions' responses. See the [Form guide](../core-components/form.md#use-form-variables) for their contents and submission behavior.+The Form also exposes `formState`, `formProgress`, `results`, and `errors` in **Variables**. Use `formProgress` to show submission activity and whole-request upload bytes, `formState` for the outcome, and `results` and `errors` for action responses. See the [Form guide](../core-components/form.md#use-form-variables) for their contents and submission behavior.For a Form-scoped HTTP resource, leave the body unset to forward every named Form field. **Format** defaults to **auto**: text-only Form data is JSON; a body containing uploaded files becomes multipart. Choose **application/json** or **multipart/form-data** when the receiving API requires that format. JSON rejects uploaded files instead of dropping them. Multipart sends repeated values under the same field name and includes uploaded files with their filenames and bytes. Use the [Form upload guide](../core-components/form.md#send-files) for file inputs and the combined request limit.diff --git a/docs/university/mcp.md b/docs/university/mcp.mdindex 4f348fbe45..f7cb69ab35 100644--- a/docs/university/mcp.md+++ b/docs/university/mcp.md@@ -72,10 +72,11 @@ every destination and recipient first. For dynamic checkbox or multiple-select fpass `arrayNames` to preserve an empty or single-value array when the savedfield props do not identify the control. The result reports destination IDs,statuses, and errors without Resource bodies. Managed Email errors include a-code when available. This server simulation does not exercise-client validation, browser event handlers, navigation, file bytes, or actual-browser information. The Builder server loads the saved draft and holds the-Email service credentials; the CLI does not receive those credentials.+code when available. It reports the final outcome, not live Form progress.+This server simulation does not exercise client validation, browser event+handlers, navigation, file bytes, or actual browser information. The Builder+server loads the saved draft and holds the Email service credentials; the CLI+does not receive those credentials.```json{diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex bb565ec5c6..f4b416a264 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": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\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 exactly one direct `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 editable Content Block body content. A missing or second template container makes the block invalid. Verify this structure before handoff.\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\nWhen the Content Block body must be stored in an `.mdx` Asset, use the dedicated `connect-content-block-source`, `switch-content-block-source`, `inspect-content-block-source`, `edit-content-block-source`, `update-content-block-frontmatter`, `reload-content-block-source`, and `disconnect-content-block-source` tools. Do not manipulate its `src` with generic prop tools. Connecting replaces existing Body content, so report `requiresConfirmation:true` and retry with `confirmReplacement:true` only after user approval. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep their template styles. A mismatched child structure replaces defaults, while an explicit empty pair clears defaults and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live, including when a matching template is added after the MDX element. Preserve invalid MDX and unresolved template names, inspect all source-located diagnostics, and resolve revision conflicts by reloading before reapplying the change. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy updates across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFrontmatter is part of the same MDX source. `update-content-block-frontmatter` receives the complete replacement property map, so inspect and preserve properties the user did not ask to remove. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits; MDX-rendered elements are not persistent targets for generic prop or text mutations. Preserve existing `mode:"readwrite"` bindings, which are valid only for exact direct frontmatter paths. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. For an expression-bound source inside a Collection, pass the occurrence\'s scoped values and a distinct stable `renderScope`; for example, resolve `post.assetId` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\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<button onClick={new ActionValue(["event"], expression`console.log(event)`)}>\n Open\n</button>\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 `<Switch><SwitchThumb /></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<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 <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 <h2>Launch metrics</h2>\n <p>A polished card that fades up as it enters the viewport.</p>\n </section>\n</AnimateChildren>\n```\n\nFor Text Animation, keep `AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<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 <AnimateText splitBy="space" slidingWindow={5} easing="easeOutQuart">\n <h2>Animate words with controlled rhythm</h2>\n </AnimateText>\n</AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `StaggerAnimation`:\n\n```tsx\n<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 <StaggerAnimation>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </article>\n <article\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </article>\n </StaggerAnimation>\n</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<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 <VideoAnimation timeline={true}>\n <Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </VideoAnimation>\n</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. When a value or id is known, call `search-project` once instead of passing broad snapshots or several lists to the model. Use semantic list/get reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, and `list-breakpoints` when the structure or target is not known. Use `snapshot` only when exact raw patch paths are 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.\n For a Builder link from **Copy link to instance**, parse the URL with `URL`/`URLSearchParams`. The decoded `instance` query parameter is a comma-separated selector ordered from the target instance to the page root. Pass its first entry to `inspect-instance`, for example `?pageId=page-id&instance=heading-id%2Cslot-id%2Cbody-id` becomes `{"instanceId":"heading-id","include":["props","styles","children","ancestors"]}`. Use `pageId` and the remaining selector entries to check the page and shared Slot occurrence before changing it. Shared Slot descendants are shared records; editing one changes all occurrences. Verify that the configured MCP project matches the linked project before editing; stop if they differ. The URL does not authorize switching projects. If the instance is missing, ask for an updated link instead of guessing another target. Never send a Builder link to screenshot tools or echo its `authToken`.\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, ask whether the user wants visual verification unless they explicitly requested it. Only after they opt in, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate.\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. Ask whether the user wants visual verification unless they explicitly requested screenshots, visual verification, or a rendered audit. Do not start preview, screenshots, screenshot diffs, OCR installation, or rendered audits until they opt in.\n5. After they opt in, keep generated project files current, start preview, and capture the changed page with `screenshot`.\n6. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n7. If the user declines or vision tooling is unavailable, use focused non-visual assertions and state that vision was not run.\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. Ask whether the user wants visual verification unless they explicitly requested it. Do not capture responsive screenshots until they opt in.\n4. 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.\n5. 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}}`.\n6. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n7. 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\nAlways write direct property access in authored expressions, such as\n`formData.subject`. Never type optional property access (`?.`) in an authored\nbinding. The expression compiler inserts it into generated JavaScript to make\nmissing intermediate values safe; that generated syntax is not an authoring\nexample and must not be copied into a binding. Use\n`formData.subject ?? "New message"` when a missing value needs a meaningful\nfallback.\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 contain JavaScript expression source. For fixed text, pass a quoted string expression such as `"Pricing | Acme"`; for computed values, pass code such as `pageTitle ?? "Pricing | Acme"`. An unquoted word is a variable reference, not fixed text.\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- Choose the article format before building a blog. Use `.mdx` with a Content Block for Notion-style visual body editing in Content mode; publishing downloads and compiles each reachable MDX article, which can slow publishing as the blog grows. Use `.md` with Markdown Embed when editors can work in the Markdown file editor in Assets instead; they can edit the source in Content mode but not the body visually on the canvas. `.md` needs no per-article MDX compilation, but the current publish sync still downloads Asset files for both formats, and static generation may read Markdown bodies.\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 or MDX 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 files from Asset storage at runtime. Do not create companion JSON descriptors merely to avoid embedding the document.\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 or MDX 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. It does not render Webstudio MDX elements; connect the `.mdx` file to a Content Block for that workflow.\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`. A query key with one value is a string, while repeated values are an ordered array. For `?tag=red&tag=blue`, `system.search.tag` is `["red", "blue"]`.\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. 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- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\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 expression source for page metadata. Quote fixed text as a JavaScript string literal within the JSON string.\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\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty or single-value array when the saved\nfield props do not identify the control. The result reports destination IDs,\nstatuses, and errors without Resource bodies. Managed Email errors include a\ncode when available. This server simulation does not exercise\nclient validation, browser event handlers, navigation, file bytes, or actual\nbrowser information. The Builder server loads the saved draft and holds the\nEmail service credentials; the CLI does not receive those credentials.\n\n```json\n{\n "path": "/contact",\n "formId": "saved-form-instance-id",\n "values": [{ "name": "email", "value": "[email protected]" }]\n}\n```\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": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\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<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\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. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and 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 `<Switch><SwitchThumb /></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## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\nChoose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\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- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\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- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\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 after publishing.\n- Unpublish staging or production deployments. Unpublish completes without a publish job.\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- Editor links with API access can edit Content Block text and props, insert or move eligible content, delete eligible instances, create pages from templates, change allowed page settings, upload assets, and create asset folders through semantic tools. The server checks each change against Content-mode rules. Raw `apply-patch` remains limited to text and editable props; other asset, folder, and design changes require Builder access.\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- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n### Converting a composite component to HTML\n\n`convert-instance` changes one instance and validates its entire descendant tree after that change. For a Tabs tree, changing `Tabs` to a `div` first fails because `TabsList`, `TabsTrigger`, and `TabsContent` still require their composite parents. Convert from the leaves upward instead: `TabsTrigger` to `ws:element` with tag `button`, `TabsContent` to `ws:element` with tag `div`, `TabsList` to `ws:element` with tag `div`, then `Tabs` to `ws:element` with tag `div`. Pass the complete, current `instanceSelector` for each call, starting with the target. Read the actual tree first; convert every remaining required part before its parent. Each step is a separate mutation, so this recipe is not atomic.\n\nConversion retains instance ids, children (including editable copy), styles, and most props; it removes a legacy `tag` prop and normalizes React prop aliases when converting to `ws:element`. Review component-specific props and behavior afterward: replacing Tabs with HTML does not recreate tab selection, keyboard behavior, or accessibility semantics. If a project requires the whole tree to change in one commit, use `snapshot` to read the current build version and exact records, then a single versioned `apply-patch` transaction for the existing instance component/tag fields. Preserve all existing ids and child references, include any needed prop changes in that same transaction, and verify the final tree.\n\nFor composite media such as Vimeo, inspect the player subtree and surrounding content first. A native `video` cannot retain provider-only parts such as `VimeoPlayButton`, `VimeoSpinner`, or `VimeoPreviewImage`. Use `delete-instance` with `instanceIds` containing the exact obsolete part ids (deleting a part also cleans its descendants and owned data), then `convert-instance` on the player root with `component: "ws:element"`, `tag: "video"`, and its current `instanceSelector`. Keep surrounding wrappers, captions, and other content outside the deletion set; move any content that must survive out of an obsolete part before deleting it. The player keeps its id and styles. Remove the provider-specific props with `delete-props`, using `{"deletions":[{"instanceId":"<player-id>","name":"url"}]}` for the old Vimeo URL prop and adding one entry for each other obsolete prop found during inspection. Then use `update-props` to set the native video source and playback props, and `update-styles` for any styling changes. A native video source must be a playable media URL or asset, not a Vimeo watch-page URL. These are separate semantic mutations; no raw instance patch is needed for this sequence.\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\n### Server-side Form simulation\n\n`forms.simulate-submission` evaluates a saved Form using synthetic string fields\nand the same trusted Builder server Form handler used by Builder Preview. Supply\nthe saved Form instance ID and page path. The server uses this project\'s\npublisher origin. It can trigger the Form\'s configured HTTP and Email Resources, so verify\nevery destination and recipient first. For dynamic checkbox or multiple-select fields,\npass `arrayNames` to preserve an empty or single-value array when the saved\nfield props do not identify the control. The result reports destination IDs,\nstatuses, and errors without Resource bodies. Managed Email errors include a\ncode when available. It reports the final outcome, not live Form progress.\nThis server simulation does not exercise client validation, browser event\nhandlers, navigation, file bytes, or actual browser information. The Builder\nserver loads the saved draft and holds the Email service credentials; the CLI\ndoes not receive those credentials.\n\n```json\n{\n "path": "/contact",\n "formId": "saved-form-instance-id",\n "values": [{ "name": "email", "value": "[email protected]" }]\n}\n```\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": "<section ws:style={css`padding: 32px; display: grid; gap: 16px;`}><h2>Northstar Product OS</h2><p>Reusable patterns for teams.</p></section>"\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<section style={{ padding: 32, borderRadius: 16 }}>\n <h2>Operations Console</h2>\n <p>\n React-style object styles become editable Webstudio styles.\n </p>\n</section>\n\n<section ws:tokens={[token("accent", css`color: #0f766e;`)]}>\n <button\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n >\n Track launch\n </button>\n</section>\n\n<section ws:tokens={[token("accent")]}>Reuse an existing accent token</section>\n\n<section>\n <Switch>\n <SwitchThumb />\n </Switch>\n</section>\n```\n\nUse the two-argument `token` form with a `css` template to define styles in the\nfragment. Use `token("name")` to attach an existing project token; an unknown\nname is an error.\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. Use direct animation component identifiers such as `<AnimateChildren>`; `animation` is accepted only as legacy input and 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 `<Switch><SwitchThumb /></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## MDX-backed Content Blocks\n\nUse a connected `.mdx` Asset when editors should change a Content Block body visually while the document remains stored as a file.\n\nChoose this format before building a blog: each reachable connected MDX article is downloaded and compiled when publishing, so publishing can take longer as the blog grows. If editors only need to edit Markdown source in Assets, use `.md` with Markdown Embed instead. Content mode editors can edit those files in the Markdown file editor, but cannot edit the article body visually on the canvas. `.md` does not need per-article MDX compilation; the current publish sync still transfers Asset files for either format, and static generation may read Markdown bodies.\n\n### Connect a collection to its entry page\n\nWhen MDX files belong to a content collection, connect the collection to its dynamic entry page explicitly. Read the page ID after finding or creating the page, verify that its path has exactly one URL parameter, and store the ID at `x-webstudio.entryPageId` in `collection.json`. Do not assume Webstudio infers the page from its path, Assets query, or Content Block source. Preserve the rest of `collection.json`, and verify **Open on canvas** from both an entry asset menu and **Entry settings** before handoff. If no compatible page exists, leave the field unset and report that entry navigation still needs configuration.\n\n```json\n{\n "x-webstudio": {\n "template": "template.mdx",\n "entries": ["*.mdx"],\n "entryPageId": "<dynamic-entry-page-id>"\n }\n}\n```\n\n1. Create the `.mdx` file under `.webstudio/assets`, then upload it and keep the returned Asset ID.\n2. Inspect the Content Block and verify that it has exactly one direct Templates container. Every custom template referenced from MDX needs a unique top-level instance name. A missing or second Templates container blocks connected MDX materialization and publication.\n3. Connect the Asset with `connect-content-block-source`. Use a stable page-based `renderScope` for a direct occurrence.\n4. If the result returns `requiresConfirmation:true`, tell the user that connecting will replace the existing Body content. Repeat the same call with `confirmReplacement:true` only after approval.\n5. Edit the complete source with `edit-content-block-source`, or replace the complete frontmatter map with `update-content-block-frontmatter`.\n6. Inspect every returned diagnostic. Invalid MDX is preserved, not silently repaired.\n\n```sh\nwebstudio upload-asset \'{"asset":{"name":"article.mdx","type":"file","format":"mdx","meta":{}},"assetsDir":".webstudio/assets"}\'\nwebstudio connect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example","source":{"type":"asset","assetId":"<mdxAssetId>"}}\'\nwebstudio inspect-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio edit-content-block-source --input-file .temp/edit-content-block-source.json\nwebstudio reload-content-block-source \'{"blockInstanceId":"<contentBlockInstanceId>","renderScope":"page:/articles/example"}\'\nwebstudio migrate-content-block-template-references \'{"assetIds":["<mdxAssetId>"],"migration":{"type":"rename","from":"Old template name","to":"New template name"}}\'\n```\n\nPrefer Markdown for standard document content. Markdown nodes automatically use a unique matching semantic template when one exists and keep their normal semantic fallback otherwise. Use lowercase JSX such as `<section>` or `<svg>` for a standard HTML or SVG element with authored properties Markdown cannot express.\n\nReference a uniquely named top-level custom template with capitalized JSX such as `<PromotionCard tone="featured">Content</PromotionCard>`. The template\'s stable **Name** must be a valid JSX component identifier and is independent from its display label. A template name wins over a built-in MDX adapter. Other registered components are unavailable until added to this Content Block\'s Templates. Attributes accept quoted static values and bare booleans. Expressions such as `{false}` are unsupported, as are imports, spreads, functions, and executable JavaScript. Legacy `ws.element` and `ws:name` forms are read for compatibility but are not emitted or recommended. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use the direct component identifier.\n\nWhen explicit JSX children match the designed template structure, their text and supported props overlay the cloned descendants so template styles stay intact. A mismatched child structure replaces the root defaults, and each authored child still resolves through a matching template when possible. An explicit empty pair such as `<PromotionCard></PromotionCard>` clears the defaults. A self-closing reference such as `<PromotionCard />` keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live: adding a missing semantic or named template later also updates existing MDX without rewriting it. Preserve unresolved template names and report their diagnostics.\n\nWhen a template is renamed or deleted, use `migrate-content-block-template-references` to update the affected MDX files. Its first call returns a plan with changed-file, update, omission, and diagnostic counts. Report the plan and repeat the exact request with its `confirmationToken` only after approval. Renames and removals update named JSX and legacy `ws:name` references, including names such as `Image` and `CodeText` when they identify templates. Rename targets must be valid PascalCase JSX identifiers. Removing a paired reference unwraps and preserves its explicit authored children; removing a self-closing reference removes that node because it has no authored children. Invalid files remain unchanged and are reported in diagnostics.\n\nUse the dedicated connect, switch, inspect, edit, update-frontmatter, reload, and disconnect operations instead of creating or deleting the Content Block\'s `src` with generic prop tools. An expression-bound source inside a Collection also needs the occurrence\'s scoped values and a distinct stable `renderScope`. For example, use `source:{"type":"expression","value":"post.assetId"}` with `variables:{"post":{"assetId":"<mdxAssetId>"}}`.\n\n`renderScope` is any non-empty stable identity for one rendered occurrence, such as `page:/articles/example`. It does not load that page, its route parameters, or its resource results. To connect a result-one Assets resource, run `preview-asset-query` with concrete values, keep the saved source expression such as `post.data.id`, and supply the previewed item for this occurrence with `variables:{"post":{"data":{"id":"<mdxAssetId>"}}}`. The operation validates that concrete Asset while persisting the dynamic expression.\n\nA source edit replaces the complete MDX document. A frontmatter update replaces the complete frontmatter property map. Inspect the current source first and preserve everything the user did not ask to change. Store frontmatter images as exact `$ref` objects. Bind editable Image sources to their resolved `.src` with explicit `binding.mode:"readwrite"`; omitting the mode leaves the image visible but not replaceable in Content mode. Bind alt properties to their Asset `.description` with `mode:"read"`. Use `update-content-block-frontmatter` for MCP frontmatter edits. MDX-rendered elements are not persistent instance targets for generic `bind-props` or `update-text` calls. Preserve existing `mode:"readwrite"` bindings when encountered; they are valid only for exact direct paths into the connected document\'s frontmatter. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\n\nIf an edit in a long-lived MCP session reports a revision conflict after another client saved the Asset, call `reload-content-block-source`, inspect the latest source, reapply the requested change, and retry. One-shot CLI calls refresh before each operation and normally cannot reproduce a stale session. Never overwrite the newer revision blindly. Use `disconnect-content-block-source` to remove the connection while leaving the Asset unchanged.\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- `search-project`: find a known value or id with `webstudio search-project \'{"query":"pricing"}\'` or MCP `search-project {"query":"pricing"}`; use focused list/get tools when the target structure is unknown\n\n`meta.guide` returns structured `routing` with the selected workflow and any broad context bundle it recommends. Authentication and design context bundles appear only when their specialized workflow is selected. Set `authoredFragment` when using an authored fragment and `reuseDesignSystem` when its recommendations should retain design-system discovery tools.\n\nSet `taskScope` and `workflow` explicitly; `meta.guide` does not infer them or the authored-fragment flags from the brief. Specialized workflows are `markdown-blog`, `json-ld`, `collection`, `expression`, `authenticated-page`, `font-assets`, `design-input`, `content-block-source`, and `craft`; otherwise use `general`. Use `content-block-source` to connect or edit a Markdown/MDX-backed Content Block, including writable bindings for its designed header. For work that must not change project or local state, pass `{"brief":"Inventory custom code","taskScope":"read-only-audit","workflow":"general"}`. The resulting `read-only-discovery` workflow excludes mutation and side-effecting session tools and uses focused search, list, get, inspect, and snapshot tools.\n\n`search-project` follows normal ProjectSession synchronization, then searches in the CLI process. Namespace filters limit values matched; related namespaces may still supply route and reference context, and synchronization is unchanged. Only paged matches enter model context. Recognized credential fields and asset binary or document bodies are excluded.\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- Search all Builder namespaces for a known value or id without putting complete namespace data in model context.\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 after publishing.\n- Unpublish staging or production deployments. Unpublish completes without a publish job.\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- Editor links with API access can edit Content Block text and props, insert or move eligible content, delete eligible instances, create pages from templates, change allowed page settings, upload assets, and create asset folders through semantic tools. The server checks each change against Content-mode rules. Raw `apply-patch` remains limited to text and editable props; other asset, folder, and design changes require Builder access.\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- Never run visual verification automatically. Ask first unless the user explicitly requested screenshots, visual verification, or a rendered audit; if they do not opt in, use focused non-visual assertions.\n\n### Converting a composite component to HTML\n\n`convert-instance` changes one instance and validates its entire descendant tree after that change. For a Tabs tree, changing `Tabs` to a `div` first fails because `TabsList`, `TabsTrigger`, and `TabsContent` still require their composite parents. Convert from the leaves upward instead: `TabsTrigger` to `ws:element` with tag `button`, `TabsContent` to `ws:element` with tag `div`, `TabsList` to `ws:element` with tag `div`, then `Tabs` to `ws:element` with tag `div`. Pass the complete, current `instanceSelector` for each call, starting with the target. Read the actual tree first; convert every remaining required part before its parent. Each step is a separate mutation, so this recipe is not atomic.\n\nConversion retains instance ids, children (including editable copy), styles, and most props; it removes a legacy `tag` prop and normalizes React prop aliases when converting to `ws:element`. Review component-specific props and behavior afterward: replacing Tabs with HTML does not recreate tab selection, keyboard behavior, or accessibility semantics. If a project requires the whole tree to change in one commit, use `snapshot` to read the current build version and exact records, then a single versioned `apply-patch` transaction for the existing instance component/tag fields. Preserve all existing ids and child references, include any needed prop changes in that same transaction, and verify the final tree.\n\nFor composite media such as Vimeo, inspect the player subtree and surrounding content first. A native `video` cannot retain provider-only parts such as `VimeoPlayButton`, `VimeoSpinner`, or `VimeoPreviewImage`. Use `delete-instance` with `instanceIds` containing the exact obsolete part ids (deleting a part also cleans its descendants and owned data), then `convert-instance` on the player root with `component: "ws:element"`, `tag: "video"`, and its current `instanceSelector`. Keep surrounding wrappers, captions, and other content outside the deletion set; move any content that must survive out of an obsolete part before deleting it. The player keeps its id and styles. Remove the provider-specific props with `delete-props`, using `{"deletions":[{"instanceId":"<player-id>","name":"url"}]}` for the old Vimeo URL prop and adding one entry for each other obsolete prop found during inspection. Then use `update-props` to set the native video source and playback props, and `update-styles` for any styling changes. A native video source must be a playable media URL or asset, not a Vimeo watch-page URL. These are separate semantic mutations; no raw instance patch is needed for this sequence.\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": "<section ws:style={css`padding: 32px; display: grid; gap: 12px;`}><h2>Launch Kit</h2><p>A focused section created with Webstudio JSX.</p><button>Get started</button></section>"\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 exactly one direct `ws:block-template` child. A missing or second template container makes the block invalid. Templates themselves are protected; an editor\'s inserted copy becomes editable Content Block body content. Verify this structure before handoff.\n\nFor an MDX-backed Content Block, use the dedicated content-source tools instead of generic prop mutations: connect, switch, inspect, edit, update frontmatter, reload, or disconnect the source. Confirm before replacing existing Body content. Prefer Markdown for standard document content; it automatically uses unique matching semantic templates. Use lowercase JSX such as `<section>` or `<svg>` for HTML or SVG that Markdown cannot express. Capitalized JSX resolves a unique stable template **Name** or a built-in MDX adapter. Add custom components to this Content Block\'s Templates before referencing them in MDX. The display label is independent. JSX attributes accept quoted values and bare booleans; expressions such as `{false}` are unsupported. Legacy `ws.element` and `ws:name` forms are compatibility input only. Component namespaces such as `$.*`, `radix.*`, and `animation.*` are unsupported; use direct component identifiers. Matching explicit children overlay designed descendants and keep template styles. A mismatched child structure replaces defaults, an explicit empty pair clears defaults, and a self-closing reference keeps them. Editing inherited default content writes it back as explicit JSX children. Template resolution is live when matching templates are added later. Preserve invalid source and unresolved names, inspect all diagnostics, and reload before retrying a revision conflict. A frontmatter update replaces the complete property map; preserve fields the user did not ask to remove. Store frontmatter images as exact `$ref` objects; bind editable Image sources to `.src` with explicit `binding.mode:"readwrite"` and alt properties to the Asset `.description` with `mode:"read"`. Omitting the source mode leaves the image visible but not replaceable in Content mode. Only exact direct frontmatter bindings may use `mode:"readwrite"`. After a template rename or deletion, use `migrate-content-block-template-references` to preview and confirm custom-template JSX and legacy changes across selected MDX files. A confirmed removal unwraps paired references and preserves their authored children; a self-closing reference disappears because it has none.\n\nFor an editable MDX article, use the resource to select the Content Block\'s source Asset (`post.data.id`), then bind article fields inside the block to its document parameter (`document.frontmatter.title`), not query-result properties. Inspect the actual document variable name first. Create writable bindings explicitly: `update-text` uses `expressionBindingMode:"readwrite"`; `bind-props` uses `binding.mode:"readwrite"`. These generic tools target persistent designed instances, such as a header outside the MDX body, not MDX-generated instances. The MDX body is editable through its source mapping; merely placing static or query-bound content inside the block does not make it editable. Use exact direct paths; property access is already safe. Direct bindings through a loaded Markdown or MDX `$ref` ending in `#frontmatter` save to the referenced file, with its write permissions enforced. Shared-record edits affect every document using that record. Computed expressions and JSON/body references remain read-only. Image replacement is supported: a direct Image source binding with `mode:"readwrite"` lets the picker replace the frontmatter `$ref`, while shared Asset metadata is edited in Asset settings. Follow the complete article editability checklist below before handoff.\n\n### Content Block completion checklist\n\nFor every Content Block creation, migration, or repair—with or without MDX—treat Content-mode editability as a delivery requirement for all content the user expects editors to change. Before implementation, inventory each value, its intended UI control, and its write destination. Choose controls by meaning: date/calendar controls for dates, image pickers for image replacement, and direct text or number controls for reading time. Keep fixed punctuation and units outside a directly bound value element; never mix literal and expression children there. Preserve the existing stored type and wording: if `readTime` already stores `4 min read`, bind that whole string directly instead of assuming it stores only a number. Distinguish protected layout/templates from editable content explicitly. Test each field through Content mode, check the saved project data or source file, reload, restore test values, and record passed/failed/not tested. Testing one heading, inspecting bindings, or successfully writing through MCP does not cover the remaining fields. Report missing controls and unsupported writes as unfinished requirements, not successful delivery.\n\n### Complete article editability is required\n\nWhen the user asks for the whole article to be editable in Content mode, this includes every article-owned value: title, excerpt, author details and links, dates, reading time, categories, hero and inline image sources, alternative text, captions, body text, links, and custom-component content and media. Exclude only designer-owned layout, styling, templates, and shared navigation/footer unless the user asks otherwise. A correct preview, a successful MCP write, or an editable body does not prove this requirement is met.\n\nBefore handoff:\n\n1. Inventory every article field, its UI control, binding, and source file/field. Header fields outside **MDX content** are still part of the article and must be editable through the Content Block\'s document bindings.\n2. In Content mode, edit every inventoried field through the UI, including choosing a different hero image and editing link destinations and custom-component props. Do not substitute a raw MDX/YAML edit or an MCP write for this check.\n3. Read the saved source after each edit. Confirm the intended MDX body/frontmatter or referenced author file changed, unrelated content stayed intact, and the edit survives reload. Restore test values and verify restoration.\n4. Mark each field passed, failed, or not tested. Do not claim the article is fully editable while any required field is failed or untested.\n\n**Image replacement is not shared metadata editing.** For frontmatter such as `featureImage: { $ref: "./images/hero.png" }`, bind the Image source directly to `document.frontmatter.featureImage.src` with `binding.mode:"readwrite"` using `bind-props`. In Content mode, **Choose source** replaces the article’s `featureImage.$ref`; it does not overwrite the shared Asset’s resolved `.src`. The resolved URL field stays read-only. Verify the picker, saved reference, and reload—do not infer support from the displayed image alone. Bind alternative text to `.description` to use the shared Asset description; edit it through **Choose source → asset actions → Settings → Description**, which affects every use of that Asset. Do not treat a missing write mode as a platform limitation, and do not defer image replacement over a separate shared-description question.\n\nKeep intended editable values separate from display formatting. For reading time, use three inline sibling text elements: static `— `, one value element bound directly to `document.frontmatter.readingTime` with `expressionBindingMode:"readwrite"`, and static ` min read`. The value element must contain only that binding, not mixed literal and expression children. Preserve whitespace and the stored field type. Do not concatenate labels or units, use template literals, or add fallbacks/formatting calls to an editable binding. Prefer component formatting controls with a directly bound value. Explain unsupported cases and ask before making an intended editable field read-only; do not trade away editability just to match the display.\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 technical 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. The CLI attaches the project ID and recognized entity IDs from the failed tool input; do not copy additional IDs into the authored text. Never include names, usernames, emails, phone numbers, organizations, domains, URLs, IP addresses, local paths, credentials, tokens, customer content, other exact unique values, or raw contextual tool data.\n\nIf a mutation returns an unclear transport or response error, make one read-only check to see whether it committed and include that outcome in the report. For browser startup failures, include the selected browser family, whether fallback was attempted, and any shown exit signal or code, but never an executable path. The CLI adds bounded failure diagnostics automatically; do not paraphrase missing values as facts.\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.mdindex e8dc0ad2ee..f46cd65c70 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -45,10 +45,11 @@ every destination and recipient first. For dynamic checkbox or multiple-select fpass `arrayNames` to preserve an empty or single-value array when the savedfield props do not identify the control. The result reports destination IDs,statuses, and errors without Resource bodies. Managed Email errors include a-code when available. This server simulation does not exercise-client validation, browser event handlers, navigation, file bytes, or actual-browser information. The Builder server loads the saved draft and holds the-Email service credentials; the CLI does not receive those credentials.+code when available. It reports the final outcome, not live Form progress.+This server simulation does not exercise client validation, browser event+handlers, navigation, file bytes, or actual browser information. The Builder+server loads the saved draft and holds the Email service credentials; the CLI+does not receive those credentials.```json{diff --git a/packages/project-build/src/mcp-form.integration.test.ts b/packages/project-build/src/mcp-form.integration.test.tsindex a5602aa4f7..dc0aee3c33 100644--- a/packages/project-build/src/mcp-form.integration.test.ts+++ b/packages/project-build/src/mcp-form.integration.test.ts@@ -32,6 +32,8 @@ const operationCommands = new Set(["create-resource","update-resource","update-props",+ "bind-props",+ "update-styles","get-project-settings","update-project-settings",]);@@ -287,7 +289,6 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>name: "template:form",meta: { component: "form" },});-const inserted = await call("insert-component", {parentInstanceId: "instance-root",component: "form",@@ -340,9 +341,11 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>scopeInstanceId: string;}>;const formState = formVariables.find(({ name }) => name === "formState");+ const progress = formVariables.find(({ name }) => name === "formProgress");const results = formVariables.find(({ name }) => name === "results");const errors = formVariables.find(({ name }) => name === "errors");- expect([formState, results, errors]).toEqual([+ expect([formState, progress, results, errors]).toEqual([+ expect.objectContaining({ scopeInstanceId: form?.id }),expect.objectContaining({ scopeInstanceId: form?.id }),expect.objectContaining({ scopeInstanceId: form?.id }),expect.objectContaining({ scopeInstanceId: form?.id }),@@ -360,6 +363,17 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>}),],}),+ expect.objectContaining({+ name: "onProgressChange",+ type: "action",+ value: [+ expect.objectContaining({+ type: "execute",+ args: ["value"],+ code: `${encodeDataSourceVariable(progress?.id ?? "")} = value`,+ }),+ ],+ }),expect.objectContaining({name: "onResultChange",type: "action",@@ -720,6 +734,61 @@ test("discovers, commits, and reads back the new Form through MCP", async () =>expect.objectContaining({ name: "action", value: remainingActions }),]));++ const statusInstances = await call("list-instances", { pagePath: "/" });+ const status = (+ statusInstances.data.instances as Array<{+ id: string;+ component: string;+ label?: string;+ }>+ ).find(({ label }) => label === "Progress");+ expect(status?.component).toBe("ws:element");+ const progressReference = encodeDataSourceVariable(progress?.id ?? "");+ await call("bind-props", {+ bindings: [+ {+ instanceId: status?.id,+ name: "aria-label",+ binding: {+ type: "expression",+ value: `${progressReference}.loaded + " / " + ${progressReference}.total`,+ },+ },+ ],+ });+ await call("update-styles", {+ updates: [+ {+ instanceId: status?.id,+ property: "color",+ value: { type: "keyword", value: "red" },+ },+ ],+ });+ await call("refresh");+ const styledStatus = await call("inspect-instance", {+ instanceId: status?.id,+ include: ["props", "styles"],+ });+ expect(styledStatus.data.props).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ name: "aria-label",+ type: "expression",+ value: `${progressReference}.loaded + " / " + ${progressReference}.total`,+ }),+ ])+ );+ expect(styledStatus.data.styles).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ instanceId: status?.id,+ property: "color",+ value: { type: "keyword", value: "red" },+ }),+ ])+ );} finally {await client.close();await server.close();diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 50d56cebb6..eb60c89355 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -6029,11 +6029,15 @@ const getTemplateDetails = (input: unknown) => {};}const template = templates.get(item.meta.component);+ const formUsage =+ item.meta.component === "form"+ ? " The Form template adds formProgress: status is idle or pending, loaded and total start at 0 and measure bytes for the whole request; total 0 means unknown. Files contain id, fieldName, name, size, and type without per-file transfer counts. Find its ID with list-variables and read webstudio://project/expressions before binding the editable Progress container or its children with bind-props; style them with update-styles. Browser submission supplies live progress; forms.simulate-submission and preview.submit-form report only final outcomes."+ : "";return {found: true,...item,template: template?.template,- usage: `Use insert-component with component "${item.meta.insert.component}" when you want Webstudio to insert this registered template automatically. The files entry is the shadcn-compatible registry:file representation of the same template payload.`,+ usage: `Use insert-component with component "${item.meta.insert.component}" when you want Webstudio to insert this registered template automatically. The files entry is the shadcn-compatible registry:file representation of the same template payload.${formUsage}`,};};diff --git a/packages/project-build/src/runtime/data.test.tsx b/packages/project-build/src/runtime/data.test.tsxindex 1e409eec7b..f17dfa6d4e 100644--- a/packages/project-build/src/runtime/data.test.tsx+++ b/packages/project-build/src/runtime/data.test.tsx@@ -295,7 +295,7 @@ test.each(["formData", "browserInfo"])(});-test.each(["state", "onStateChange", "onResultChange"])(+test.each(["state", "onStateChange", "onProgressChange", "onResultChange"])("required Form variables bound to %s cannot be deleted by a mutation",(propName) => {const data = renderData(diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.tsindex a2488385f3..758d5d1341 100644--- a/packages/project-build/src/runtime/data.ts+++ b/packages/project-build/src/runtime/data.ts@@ -1613,6 +1613,7 @@ export const isRequiredManagedFormVariable = (const requiredPropNames = new Set(["state","onStateChange",+ "onProgressChange","onResultChange",]);const dataSourceReferences = /\$ws\$dataSource\$[\w$]+/g;diff --git a/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx b/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsxindex 2a4e6434ee..0611455699 100644--- a/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx+++ b/packages/sdk-components-react-remix/src/form-feedback.browser.test.tsx@@ -2,8 +2,11 @@ import { useState } from "react";import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { createMemoryRouter, RouterProvider } from "react-router-dom";-import { afterEach, expect, test, vi } from "vitest";+import { afterEach, beforeEach, expect, test, vi } from "vitest";import { ResourceForm } from "./resource-form";+import { FetchBackedFormRequest } from "../../../scripts/fetch-backed-form-request";++beforeEach(() => vi.stubGlobal("XMLHttpRequest", FetchBackedFormRequest));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }diff --git a/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx b/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsxindex 041d76e3d1..b1c54d3477 100644--- a/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx+++ b/packages/sdk-components-react-remix/src/resource-form-refresh.browser.test.tsx@@ -5,8 +5,11 @@ import {RouterProvider,useLoaderData,} from "react-router-dom";-import { afterEach, expect, test, vi } from "vitest";+import { afterEach, beforeEach, expect, test, vi } from "vitest";import { ResourceForm } from "./resource-form";+import { FetchBackedFormRequest } from "../../../scripts/fetch-backed-form-request";++beforeEach(() => vi.stubGlobal("XMLHttpRequest", FetchBackedFormRequest));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -127,6 +130,11 @@ test("failed submissions skip refresh and a later successful submission refresheawait vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1));await act(async () => container.querySelector("button")?.click());await vi.waitFor(() => expect(posts).toHaveBeenCalledTimes(1));+ await vi.waitFor(() =>+ expect(container.querySelector("form")?.hasAttribute("aria-busy")).toBe(+ false+ )+ );expect(loader).toHaveBeenCalledTimes(1);await act(async () => container.querySelector("button")?.click());await vi.waitFor(() =>diff --git a/packages/sdk-components-react-remix/tsconfig.json b/packages/sdk-components-react-remix/tsconfig.jsonindex fdd08ecde7..0a5df353c7 100644--- a/packages/sdk-components-react-remix/tsconfig.json+++ b/packages/sdk-components-react-remix/tsconfig.json@@ -1,6 +1,7 @@{"extends": "@webstudio-is/tsconfig/base.json","compilerOptions": {+ "rootDir": "../..","types": ["react/canary", "@types/node"]},"exclude": ["vitest.config.ts"]diff --git a/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx b/packages/sdk-components-react-router/src/form-feedback.browser.test.tsxindex c328a2b8c1..3e800ab643 100644--- a/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx+++ b/packages/sdk-components-react-router/src/form-feedback.browser.test.tsx@@ -2,8 +2,11 @@ import { useState } from "react";import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { createMemoryRouter, RouterProvider } from "react-router";-import { afterEach, expect, test, vi } from "vitest";+import { afterEach, beforeEach, expect, test, vi } from "vitest";import { ResourceForm } from "./resource-form";+import { FetchBackedFormRequest } from "../../../scripts/fetch-backed-form-request";++beforeEach(() => vi.stubGlobal("XMLHttpRequest", FetchBackedFormRequest));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }diff --git a/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx b/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsxindex 1ad0e594ff..415e1856a7 100644--- a/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx+++ b/packages/sdk-components-react-router/src/resource-form-refresh.browser.test.tsx@@ -7,8 +7,11 @@ import {ScrollRestoration,useLoaderData,} from "react-router";-import { afterEach, expect, test, vi } from "vitest";+import { afterEach, beforeEach, expect, test, vi } from "vitest";import { ResourceForm } from "./resource-form";+import { FetchBackedFormRequest } from "../../../scripts/fetch-backed-form-request";++beforeEach(() => vi.stubGlobal("XMLHttpRequest", FetchBackedFormRequest));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }@@ -280,6 +283,11 @@ test("failed submissions skip refresh and a later successful submission refresheawait vi.waitFor(() => expect(loader).toHaveBeenCalledTimes(1));await act(async () => container.querySelector("button")?.click());await vi.waitFor(() => expect(posts).toHaveBeenCalledTimes(1));+ await vi.waitFor(() =>+ expect(container.querySelector("form")?.hasAttribute("aria-busy")).toBe(+ false+ )+ );expect(loader).toHaveBeenCalledTimes(1);await act(async () => container.querySelector("button")?.click());await vi.waitFor(() =>diff --git a/packages/sdk-components-react-router/src/resource-form.browser.test.tsx b/packages/sdk-components-react-router/src/resource-form.browser.test.tsxindex f55e65c292..94811eca25 100644--- a/packages/sdk-components-react-router/src/resource-form.browser.test.tsx+++ b/packages/sdk-components-react-router/src/resource-form.browser.test.tsx@@ -2,7 +2,7 @@ import { useState } from "react";import { createRoot } from "react-dom/client";import { act } from "react-dom/test-utils";import { createMemoryRouter, RouterProvider, useLocation } from "react-router";-import { afterEach, expect, test, vi } from "vitest";+import { afterEach, beforeEach, expect, test, vi } from "vitest";import {managedFormArrayNamesFieldName,managedFormIdFieldName,@@ -10,6 +10,9 @@ import {} from "@webstudio-is/sdk/runtime";import { ResourceForm } from "./resource-form";import { RemixForm } from "./remix-form";+import { FetchBackedFormRequest } from "../../../scripts/fetch-backed-form-request";++beforeEach(() => vi.stubGlobal("XMLHttpRequest", FetchBackedFormRequest));(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }diff --git a/packages/sdk-components-react-router/tsconfig.json b/packages/sdk-components-react-router/tsconfig.jsonindex fdd08ecde7..0a5df353c7 100644--- a/packages/sdk-components-react-router/tsconfig.json+++ b/packages/sdk-components-react-router/tsconfig.json@@ -1,6 +1,7 @@{"extends": "@webstudio-is/tsconfig/base.json","compilerOptions": {+ "rootDir": "../..","types": ["react/canary", "@types/node"]},"exclude": ["vitest.config.ts"]diff --git a/packages/sdk-components-react/src/resource-form-http.test.tsx b/packages/sdk-components-react/src/resource-form-http.test.tsxindex 3aed30163c..1a4446a138 100644--- a/packages/sdk-components-react/src/resource-form-http.test.tsx+++ b/packages/sdk-components-react/src/resource-form-http.test.tsx@@ -18,14 +18,17 @@ test("a router-free Form submits to a real JSON endpoint", async () => {window.formStates = [];window.formResults = [];+ window.formProgress = [];createRoot(document.getElementById("root")).render(createElement(ResourceForm, {"data-ws-managed-form-id": "form-one",action: [{ dataSourceId: "destination" }],onStateChange: (state) => window.formStates.push(state),onResultChange: (result) => window.formResults.push(result),+ onProgressChange: (progress) => window.formProgress.push(progress),},createElement("input", { name: "message", defaultValue: "Hello" }),+ createElement("input", { name: "attachment", type: "file" }),createElement("button", { type: "submit" }, "Send")));@@ -127,6 +130,11 @@ test("a router-free Form submits to a real JSON endpoint", async () => {const page = await browser.newPage();await page.goto(url);const form = page.locator("form");+ await page.locator('input[type="file"]').setInputFiles({+ name: "note.txt",+ mimeType: "text/plain",+ buffer: Buffer.from("attached"),+ });await page.getByRole("button", { name: "Send" }).click();await expect.poll(() => requests.length).toBe(1);expect(await form.getAttribute("aria-busy")).toBe("true");@@ -136,7 +144,33 @@ test("a router-free Form submits to a real JSON endpoint", async () => {`/__ws-form?${managedFormRequestParamName}=1`);expect(requests[0].formData.get("message")).toBe("Hello");+ expect((requests[0].formData.get("attachment") as File).name).toBe(+ "note.txt"+ );expect(requests[0].formData.get(managedFormIdFieldName)).toBe("form-one");+ await expect+ .poll(() =>+ page.evaluate(+ () =>+ (+ window as Window & {+ formProgress?: Array<{+ loaded?: number;+ total?: number;+ files: Array<{ name: string }>;+ }>;+ }+ ).formProgress?.some(+ (progress) =>+ progress.total !== undefined &&+ progress.total > 0 &&+ progress.loaded === progress.total &&+ progress.files[0]?.name === "note.txt"+ ) ?? false+ )+ )+ .toBe(true);+ expect(await form.getAttribute("aria-busy")).toBe("true");completeFirstRequest?.();await page.locator('form[data-state="success"]').waitFor();expect(page.url()).toBe(`${url}/`);diff --git a/packages/sdk-components-react/src/resource-form.browser.test.tsx b/packages/sdk-components-react/src/resource-form.browser.test.tsxindex dbcabd9168..586a167484 100644--- a/packages/sdk-components-react/src/resource-form.browser.test.tsx+++ b/packages/sdk-components-react/src/resource-form.browser.test.tsx@@ -7,6 +7,8 @@ import { ResourceForm } from "./resource-form";import { Input } from "./input";import { Textarea } from "./textarea";import { Select } from "./select";+import type { ManagedFormResponse } from "@webstudio-is/sdk/runtime";+import type { UploadProgress } from "@webstudio-is/sdk/form/browser";import {managedFormRequestParamName,managedFormIdFieldName,@@ -16,6 +18,48 @@ import {globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;+class FakeFormRequest {+ static requests: FakeFormRequest[] = [];+ upload: { onload?: (event: ProgressEvent) => void } = {};+ onload?: () => void;+ onerror?: () => void;+ onabort?: () => void;+ status = 200;+ responseText = "";+ url = "";+ body?: FormData;+ withCredentials = false;++ constructor() {+ FakeFormRequest.requests.push(this);+ }++ open(_method: string, url: string) {+ this.url = url;+ }++ setRequestHeader() {}++ getResponseHeader() {+ return "application/json";+ }++ send(body: FormData) {+ this.body = body;+ }++ respond(body: unknown, status = 200) {+ this.status = status;+ this.responseText = JSON.stringify(body);+ this.upload.onload?.({+ loaded: 12,+ total: 12,+ lengthComputable: true,+ } as ProgressEvent);+ this.onload?.();+ }+}+test("a StrictMode Form submits after the effect cleanup probe", async () => {const container = document.createElement("div");document.body.append(container);@@ -134,6 +178,7 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {document.body.append(container);const root = createRoot(container);let signal: AbortSignal | undefined;+ const onProgressChange = vi.fn();try {await act(async () => {root.render(@@ -144,6 +189,7 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {signal = requestSignal;return new Promise(() => {});}}+ onProgressChange={onProgressChange}><button type="submit">Send</button></ResourceForm>@@ -152,11 +198,72 @@ test("a StrictMode Form aborts an active request on real unmount", async () => {});await act(async () => container.querySelector("button")?.click());expect(signal?.aborted).toBe(false);+ expect(onProgressChange).toHaveBeenLastCalledWith(+ expect.objectContaining({ status: "pending" })+ );} finally {await act(async () => root.unmount());container.remove();}expect(signal?.aborted).toBe(true);+ expect(onProgressChange).toHaveBeenLastCalledWith({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+});++test("unmount after a result preserves completed transfer details during refresh", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const onProgressChange = vi.fn();+ let unmounted = false;+ try {+ await act(async () =>+ root.render(+ <ResourceForm+ action={[{ dataSourceId: "resource-one" }]}+ onManagedSubmit={async () => ({+ success: true,+ status: 200,+ results: [],+ errors: [],+ })}+ onSubmissionSuccess={() => new Promise<void>(() => {})}+ onProgressChange={onProgressChange}+ >+ <input name="attachment" type="file" />+ <button type="submit">Send</button>+ </ResourceForm>+ )+ );+ const files = new DataTransfer();+ files.items.add(new File(["photo"], "photo.png", { type: "image/png" }));+ container.querySelector<HTMLInputElement>('input[type="file"]')!.files =+ files.files;+ await act(async () => container.querySelector("button")?.click());+ await vi.waitFor(() =>+ expect(onProgressChange).toHaveBeenLastCalledWith(+ expect.objectContaining({+ status: "idle",+ files: [expect.objectContaining({ name: "photo.png" })],+ })+ )+ );+ const completed = onProgressChange.mock.lastCall?.[0];+ const completedCallCount = onProgressChange.mock.calls.length;+ await act(async () => root.unmount());+ unmounted = true;+ expect(onProgressChange).toHaveBeenLastCalledWith(completed);+ expect(onProgressChange).toHaveBeenCalledTimes(completedCallCount);+ } finally {+ if (!unmounted) {+ await act(async () => root.unmount());+ }+ container.remove();+ }});test("an unconfigured Form blocks native navigation", async () => {@@ -410,7 +517,8 @@ test("a hydrated Form handles submit buttons associated by form id", async () =>{email: "[email protected]",},- expect.any(AbortSignal)+ expect.any(AbortSignal),+ expect.any(Function));} finally {await act(async () => root.unmount());@@ -440,7 +548,8 @@ test("Form passes one structured submission to its dispatcher", async () => {});expect(onManagedSubmit).toHaveBeenCalledExactlyOnceWith({ name: "Ada" },- expect.any(AbortSignal)+ expect.any(AbortSignal),+ expect.any(Function));} finally {await act(async () => root.unmount());@@ -577,7 +686,8 @@ test("file-input settings enforce required uploads and keep optional or multiple{attachments: [first, second],},- expect.any(AbortSignal)+ expect.any(AbortSignal),+ expect.any(Function));await render(false);@@ -596,14 +706,8 @@ test("managed Form submits by HTTP outside a router provider and reports pendingconst root = createRoot(container);const states: string[] = [];const results: unknown[] = [];- let finish!: (response: Response) => void;- const request = vi.fn(- (_input: RequestInfo | URL, _init?: RequestInit) =>- new Promise<Response>((resolve) => {- finish = resolve;- })- );- vi.stubGlobal("fetch", request);+ FakeFormRequest.requests = [];+ vi.stubGlobal("XMLHttpRequest", FakeFormRequest);try {await act(async () =>root.render(@@ -625,43 +729,40 @@ test("managed Form submits by HTTP outside a router provider and reports pendingcontainer.querySelector<HTMLInputElement>('input[type="file"]')!.files =files.files;await act(async () => container.querySelector("button")?.click());- expect(request).toHaveBeenCalledOnce();+ expect(FakeFormRequest.requests).toHaveLength(1);expect(container.querySelector("form")?.getAttribute("aria-busy")).toBe("true");expect(container.querySelector('output[role="status"]')?.textContent).toBe("Submitting…");- const [url, init] = request.mock.calls[0];- const endpoint = new URL(String(url));+ const request = FakeFormRequest.requests[0];+ const endpoint = new URL(request.url);expect(endpoint.searchParams.get(managedFormRequestParamName)).toBe("1");expect(endpoint.pathname).toBe(window.location.pathname === "/"? "/__ws-form": `/__ws-form${window.location.pathname}`);- expect(init?.method).toBe("POST");- expect(init?.credentials).toBe("same-origin");- const body = init?.body as FormData;+ expect(request.withCredentials).toBe(false);+ const body = request.body!;expect(body.get(managedFormIdFieldName)).toBe("form-one");expect(body.getAll("tag")).toEqual(["a", "b"]);expect(await (body.get("upload") as File).text()).toBe("contents");await act(async () =>- finish(- Response.json({- success: true,- status: 200,- results: [- {- resourceId: "destination",- resourceName: "destination",- status: 201,- body: { id: 1 },- },- ],- errors: [],- })- )+ request.respond({+ success: true,+ status: 200,+ results: [+ {+ resourceId: "destination",+ resourceName: "destination",+ status: 201,+ body: { id: 1 },+ },+ ],+ errors: [],+ }));await vi.waitFor(() => expect(states).toEqual(["initial", "success"]));expect(container.querySelector<HTMLInputElement>("[name=tag]")?.value).toBe(@@ -735,7 +836,8 @@ test("Preview runs the supplied submission and reports its result without the puawait vi.waitFor(() => expect(onResultChange).toHaveBeenCalledOnce());expect(onManagedSubmit).toHaveBeenCalledWith(expect.objectContaining({ email: "[email protected]" }),- expect.any(AbortSignal)+ expect.any(AbortSignal),+ expect.any(Function));expect(onResultChange).toHaveBeenCalledWith(expect.objectContaining({ success: true })@@ -748,6 +850,200 @@ test("Preview runs the supplied submission and reports its result without the pu}});+test("Form progress keeps measured bytes through Action completion and resets on cancellation", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const progress: Array<+ Parameters<+ NonNullable<React.ComponentProps<typeof ResourceForm>["onProgressChange"]>+ >[0]+ > = [];+ const states: string[] = [];+ let reportUpload!: (update: UploadProgress) => void;+ let finish!: (response: ManagedFormResponse) => void;+ const onManagedSubmit = vi.fn(+ (+ _values: unknown,+ _signal: AbortSignal,+ onUploadProgress?: (update: UploadProgress) => void+ ) => {+ reportUpload = onUploadProgress!;+ return new Promise<ManagedFormResponse>((resolve) => {+ finish = resolve;+ });+ }+ );+ const render = async (navigationToken: string) =>+ act(async () =>+ root.render(+ <ResourceForm+ action={[{ dataSourceId: "resource-one" }]}+ navigationToken={navigationToken}+ onManagedSubmit={onManagedSubmit}+ onStateChange={(value) => states.push(value)}+ onProgressChange={(value) => progress.push(value)}+ >+ <input name="attachment" type="file" multiple />+ <button type="submit">Send</button>+ </ResourceForm>+ )+ );+ try {+ await render("first-page");+ const files = new DataTransfer();+ files.items.add(new File(["content"], "note.txt"));+ files.items.add(new File(["more"], "more.txt"));+ container.querySelector<HTMLInputElement>("input")!.files = files.files;+ await act(async () => container.querySelector("button")?.click());+ expect(container.querySelector('output[role="status"]')).toBeNull();+ expect(states.at(-1)).toBe("initial");+ expect(progress.at(-1)).toMatchObject({+ status: "pending",+ loaded: 0,+ total: 0,+ files: [+ {+ fieldName: "attachment",+ name: "note.txt",+ size: 7,+ type: "",+ },+ {+ fieldName: "attachment",+ name: "more.txt",+ size: 4,+ type: "",+ },+ ],+ });+ const [firstFileId, secondFileId] = progress+ .at(-1)!+ .files.map(({ id }) => id);+ expect(firstFileId).not.toBe(secondFileId);+ await act(async () => reportUpload({ loaded: 4 }));+ expect(progress.at(-1)).toMatchObject({+ status: "pending",+ loaded: 4,+ total: 0,+ });+ await act(async () => reportUpload({ loaded: 4, total: 12 }));+ expect(progress.at(-1)).toMatchObject({+ status: "pending",+ loaded: 4,+ total: 12,+ files: [{ id: firstFileId }, { id: secondFileId }],+ });+ await act(async () => reportUpload({ loaded: 12, total: 12 }));+ expect(progress.at(-1)).toMatchObject({+ status: "pending",+ loaded: 12,+ total: 12,+ files: [{ id: firstFileId }, { id: secondFileId }],+ });+ expect(progress.at(-1)?.files[0]).not.toHaveProperty("progress");++ await act(async () =>+ finish({ success: false, status: 422, results: [], errors: [] })+ );+ expect(progress.at(-1)).toMatchObject({+ status: "idle",+ loaded: 12,+ total: 12,+ files: [{ id: firstFileId }, { id: secondFileId }],+ });++ const previousUpload = reportUpload;+ await act(async () => container.querySelector("button")?.click());+ expect(states.at(-1)).toBe("initial");+ expect(progress.at(-1)?.status).toBe("pending");+ await act(async () => previousUpload({ loaded: 200, total: 200 }));+ expect(progress.at(-1)).toMatchObject({ loaded: 0, total: 0 });+ const canceledUpload = reportUpload;+ await render("next-page");+ expect(progress.at(-1)).toEqual({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+ await act(async () => canceledUpload({ loaded: 12, total: 12 }));+ expect(progress.at(-1)).toEqual({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+ container.querySelector<HTMLInputElement>("input")!.value = "";+ await act(async () => container.querySelector("button")?.click());+ expect(progress.at(-1)).toEqual({+ status: "pending",+ loaded: 0,+ total: 0,+ files: [],+ });+ await act(async () =>+ finish({ success: true, status: 200, results: [], errors: [] })+ );+ expect(progress.at(-1)).toEqual({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+ });+ expect(states).toEqual([+ "initial",+ "error",+ "initial",+ "initial",+ "success",+ ]);+ } finally {+ await act(async () => root.unmount());+ container.remove();+ }+});++test("Form progress returns to idle when a stale URL makes the result inapplicable", async () => {+ const container = document.createElement("div");+ document.body.append(container);+ const root = createRoot(container);+ const initialUrl = window.location.href;+ const progress: string[] = [];+ const states: string[] = [];+ let finish!: (response: ManagedFormResponse) => void;+ try {+ await act(async () =>+ root.render(+ <ResourceForm+ action={[{ dataSourceId: "resource-one" }]}+ onManagedSubmit={() =>+ new Promise<ManagedFormResponse>((resolve) => {+ finish = resolve;+ })+ }+ onStateChange={(state) => states.push(state)}+ onProgressChange={(value) => progress.push(value.status)}+ >+ <button type="submit">Send</button>+ </ResourceForm>+ )+ );+ await act(async () => container.querySelector("button")?.click());+ expect(progress.at(-1)).toBe("pending");+ window.history.replaceState(null, "", "#details");+ await act(async () =>+ finish({ success: true, status: 200, results: [], errors: [] })+ );+ await vi.waitFor(() => expect(progress.at(-1)).toBe("idle"));+ expect(states).toEqual(["initial"]);+ } finally {+ window.history.replaceState(null, "", initialUrl);+ await act(async () => root.unmount());+ container.remove();+ }+});+test("Preview reports rejected submissions as failures and clears pending state", async () => {const container = document.createElement("div");document.body.append(container);@@ -826,36 +1122,29 @@ test("managed Form reports HTTP and network failures without native navigation",document.body.append(container);const root = createRoot(container);const results: unknown[] = [];- const request = vi- .fn()- .mockRejectedValueOnce(new TypeError("offline"))- .mockResolvedValueOnce(- Response.json(- {- success: false,- status: 502,- results: [- {- resourceId: "destination",- resourceName: "destination",- status: 422,- body: "Rejected",- },- ],- errors: [- {- resourceId: "destination",- resourceName: "destination",- status: 422,- body: "Rejected",- message: "Rejected",- },- ],- },- { status: 502 }- )- );- vi.stubGlobal("fetch", request);+ FakeFormRequest.requests = [];+ vi.stubGlobal("XMLHttpRequest", FakeFormRequest);+ const serverFailure = {+ success: false,+ status: 502,+ results: [+ {+ resourceId: "destination",+ resourceName: "destination",+ status: 422,+ body: "Rejected",+ },+ ],+ errors: [+ {+ resourceId: "destination",+ resourceName: "destination",+ status: 422,+ body: "Rejected",+ message: "Rejected",+ },+ ],+ };const originalUrl = window.location.href;try {await act(async () =>@@ -870,6 +1159,7 @@ test("managed Form reports HTTP and network failures without native navigation",));await act(async () => container.querySelector("button")?.click());+ await act(async () => FakeFormRequest.requests[0].onerror?.());await vi.waitFor(() => expect(results).toHaveLength(1));expect(results[0]).toEqual({success: false,@@ -878,6 +1168,9 @@ test("managed Form reports HTTP and network failures without native navigation",errors: [{ status: 502, body: null, message: "Form submission failed" }],});await act(async () => container.querySelector("button")?.click());+ await act(async () =>+ FakeFormRequest.requests[1].respond(serverFailure, 502)+ );await vi.waitFor(() => expect(results).toHaveLength(2));expect(results[1]).toEqual({success: false,@@ -900,7 +1193,7 @@ test("managed Form reports HTTP and network failures without native navigation",},],});- expect(request).toHaveBeenCalledTimes(2);+ expect(FakeFormRequest.requests).toHaveLength(2);expect(window.location.href).toBe(originalUrl);} finally {await act(async () => root.unmount());diff --git a/packages/sdk-components-react/src/resource-form.tsx b/packages/sdk-components-react/src/resource-form.tsxindex 9a375549d7..4fdb19a1e8 100644--- a/packages/sdk-components-react/src/resource-form.tsx+++ b/packages/sdk-components-react/src/resource-form.tsx@@ -20,11 +20,20 @@ import {getFormDataValue,submitManagedForm,type FormSubmissionCallbacks,+ type FormProgress,+ type UploadProgress,} from "@webstudio-is/sdk/form/browser";import { useFormFeedbackScroll } from "./form-feedback-scroll";export const defaultTag = "form";+const createIdleProgress = (): FormProgress => ({+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+});+export const ResourceForm = forwardRef<ElementRef<typeof defaultTag>,Omit<ComponentProps<typeof defaultTag>, "action"> & {@@ -34,9 +43,11 @@ export const ResourceForm = forwardRef<state?: "initial" | "success" | "error";onStateChange?: (state: "initial" | "success" | "error") => void;onResultChange?: (result: ManagedFormResponse) => void;+ onProgressChange?: (progress: FormProgress) => void;onManagedSubmit?: (formData: ReturnType<typeof getFormDataValue>,- signal: AbortSignal+ signal: AbortSignal,+ onUploadProgress?: (progress: UploadProgress) => void) => void | Promise<ManagedFormResponse>;onQueryNavigate?: (url: string) => void;getRedirectBaseUrl?: () => string;@@ -57,6 +68,7 @@ export const ResourceForm = forwardRef<state,onStateChange,onResultChange,+ onProgressChange,onManagedSubmit,onQueryNavigate,getRedirectBaseUrl,@@ -76,6 +88,8 @@ export const ResourceForm = forwardRef<"initial" | "success" | "error">("initial");const callbacks = useRef<FormSubmissionCallbacks>();+ const progress = useRef<FormProgress>(createIdleProgress());+ const uploadController = useRef<AbortController>();const submissionController = useRef<FormSubmissionController>();submissionController.current ??= new FormSubmissionController(() => callbacks.current!@@ -90,7 +104,13 @@ export const ResourceForm = forwardRef<() => callbacks.current!);}- return () => submissionController.current?.dispose();+ return () => {+ const wasPending = progress.current.status === "pending";+ submissionController.current?.dispose();+ if (wasPending) {+ callbacks.current?.onCancel?.();+ }+ };}, []);const previousNavigationToken = useRef(navigationToken);const currentNavigationToken = useRef(navigationToken);@@ -105,7 +125,29 @@ export const ResourceForm = forwardRef<setInternalState(nextState);onStateChange?.(nextState);};+ const reportProgress = (nextProgress: FormProgress) => {+ progress.current = nextProgress;+ onProgressChange?.(nextProgress);+ };+ const reportUploadProgress = (+ update: UploadProgress,+ controller: AbortController+ ) => {+ if (+ controller.signal.aborted ||+ uploadController.current !== controller+ ) {+ return;+ }+ reportProgress({+ ...progress.current,+ loaded: update.loaded ?? 0,+ total: update.total ?? 0,+ });+ };const reportFailure = (message: string, status = 400) => {+ uploadController.current = undefined;+ reportProgress(createIdleProgress());onResultChange?.({success: false,status,@@ -116,7 +158,17 @@ export const ResourceForm = forwardRef<revealFeedback();};callbacks.current = {- onPending: setPending,+ onPending: (isPending) => {+ setPending(isPending);+ if (!isPending && progress.current.status === "pending") {+ uploadController.current = undefined;+ reportProgress({ ...progress.current, status: "idle" });+ }+ },+ onCancel: () => {+ uploadController.current = undefined;+ reportProgress(createIdleProgress());+ },onResult: (result) => onResultChange?.(result),onState: reportState,onFeedback: revealFeedback,@@ -204,20 +256,44 @@ export const ResourceForm = forwardRef<event.currentTarget,submitter instanceof HTMLElement ? submitter : undefined);+ let fileIndex = 0;+ const files = Object.entries(values).flatMap(([fieldName, value]) =>+ (Array.isArray(value) ? value : [value])+ .filter(+ (entry): entry is File =>+ entry instanceof File && !(entry.name === "" && entry.size === 0)+ )+ .map((file) => ({+ id: String(fileIndex++),+ fieldName,+ name: file.name,+ size: file.size,+ type: file.type,+ }))+ );+ reportProgress({ status: "pending", loaded: 0, total: 0, files });+ const controller = new AbortController();+ uploadController.current = controller;+ const onUploadProgress = (update: UploadProgress) =>+ reportUploadProgress(update, controller);if (onManagedSubmit) {- const controller = new AbortController();let submission: void | Promise<ManagedFormResponse>;try {- submission = onManagedSubmit(values, controller.signal);+ submission = onManagedSubmit(+ values,+ controller.signal,+ onUploadProgress+ );} catch (error) {submission = Promise.reject(error);}if (submission === undefined) {+ uploadController.current = undefined;+ reportProgress(createIdleProgress());return;}return handleSubmission(submission, controller);}- const controller = new AbortController();const submittedNavigationToken = navigationToken;const submittedLocation = window.location.href;return handleSubmission(@@ -226,6 +302,7 @@ export const ResourceForm = forwardRef<managedFormId: managedFormId!,location: submittedLocation,signal: controller.signal,+ onUploadProgress,}),controller,submittedNavigationToken,@@ -264,9 +341,11 @@ export const ResourceForm = forwardRef<<fieldset disabled={!hydrated} style={{ display: "contents" }}><div style={{ display: "contents" }}>{children}</div></fieldset>- <output role="status" aria-live="polite">- {pending ? "Submitting…" : ""}- </output>+ {onProgressChange === undefined && (+ <output role="status" aria-live="polite">+ {pending ? "Submitting…" : ""}+ </output>+ )}</form>);}diff --git a/packages/sdk-components-registry/src/core-templates.test.tsx b/packages/sdk-components-registry/src/core-templates.test.tsxindex 136ee58c8b..4dee006cd2 100644--- a/packages/sdk-components-registry/src/core-templates.test.tsx+++ b/packages/sdk-components-registry/src/core-templates.test.tsx@@ -231,6 +231,69 @@ test("Form error message binds all errors through its authored container", () =>);});+test("Form Progress shows measured request bytes while the Form is pending", () => {+ const fragment = renderCoreTemplate(coreTemplates.form);+ const formProgress = fragment.dataSources?.find(+ ({ name }) => name === "formProgress"+ )!;+ if (formProgress.type !== "variable") {+ throw new Error("Expected a Form progress variable");+ }+ expect(formProgress.value).toEqual({+ type: "json",+ value: { status: "idle", loaded: 0, total: 0, files: [] },+ });+ const status = fragment.instances.find(({ label }) => label === "Progress")!;+ const showStatus = fragment.props.find(+ ({ instanceId, name }) =>+ instanceId === status.id && name === "data-ws-show"+ );+ if (showStatus?.type !== "expression") {+ throw new Error("Expected a Progress visibility binding");+ }+ expect(+ executeExpression(+ showStatus.value.replaceAll(+ encodeDataVariableId(formProgress.id),+ '{status:"pending",files:[]}'+ )+ )+ ).toBe(true);+ expect(+ executeExpression(+ showStatus.value.replaceAll(+ encodeDataVariableId(formProgress.id),+ '{status:"idle",files:[]}'+ )+ )+ ).toBe(false);+ const spanId = status.children.find(({ type }) => type === "id")?.value;+ const span = fragment.instances.find(({ id }) => id === spanId)!;+ const showBytes = fragment.props.find(+ ({ instanceId, name }) => instanceId === span.id && name === "data-ws-show"+ );+ const text = span.children.find(({ type }) => type === "expression");+ if (showBytes?.type !== "expression" || text?.type !== "expression") {+ throw new Error("Expected measured-byte bindings");+ }+ const evaluate = (value: { loaded?: number; total?: number }) => {+ const replaceVariable = (code: string) =>+ code.replaceAll(+ encodeDataVariableId(formProgress.id),+ JSON.stringify(value)+ );+ return {+ visible: executeExpression(replaceVariable(showBytes.value)),+ text: executeExpression(replaceVariable(text.value)),+ };+ };+ expect(evaluate({ loaded: 1_200_000, total: 3_000_000 })).toEqual({+ visible: true,+ text: " 1.2 MB / 3 MB",+ });+ expect(evaluate({ loaded: 400_000 }).visible).toBe(false);+});+test("Form success and error feedback render without DOM markers", () => {const fragment = renderCoreTemplate(coreTemplates.form);const feedback = fragment.instances.filter(diff --git a/packages/sdk-components-registry/src/core-templates.tsx b/packages/sdk-components-registry/src/core-templates.tsxindex e982980d35..a84b0fcad4 100644--- a/packages/sdk-components-registry/src/core-templates.tsx+++ b/packages/sdk-components-registry/src/core-templates.tsx@@ -47,6 +47,12 @@ const blockDocument = new Parameter(contentBlockDocumentProp);const formData = new Parameter(formDataParameterName);const browserInfo = new Parameter(browserInfoParameterName);const formState = new Variable("formState", "initial");+const formProgress = new Variable("formProgress", {+ status: "idle",+ loaded: 0,+ total: 0,+ files: [],+});const formResults = new Variable("results", []);const formErrors = new Variable("errors", []);const formError = new Parameter("collectionItem");@@ -261,6 +267,9 @@ export const coreTemplates = {onStateChange={new ActionValue(["state"], expression`${formState} = state`)}+ onProgressChange={+ new ActionValue(["value"], expression`${formProgress} = value`)+ }onResultChange={new ActionValue(["result"],@@ -308,6 +317,23 @@ export const coreTemplates = {<Button type="submit">{new PlaceholderValue("Submit")}</Button></div>)}+ {setInstanceMeta(+ { label: "Progress" },+ <div+ ws:show={expression`${formProgress}.status === 'pending'`}+ role="status"+ aria-live="polite"+ >+ {new PlaceholderValue("Submitting…")}+ <span+ ws:show={expression`${formProgress}.loaded >= 0 && ${formProgress}.total > 0`}+ >+ {+ expression`" " + ((((${formProgress}.loaded / 100000) + 0.5) | 0) / 10) + " MB / " + ((((${formProgress}.total / 100000) + 0.5) | 0) / 10) + " MB"` as unknown as ReactNode+ }+ </span>+ </div>+ )}{setInstanceMeta({ label: "Success message" },<div ws:show={expression`${formState} === 'success'`} role="status">diff --git a/packages/sdk/src/form/browser-client.test.ts b/packages/sdk/src/form/browser-client.test.tsnew file mode 100644index 0000000000..d9eddb1d56--- /dev/null+++ b/packages/sdk/src/form/browser-client.test.ts@@ -0,0 +1,107 @@+import { afterEach, expect, test, vi } from "vitest";+import { submitManagedForm, type UploadProgress } from "./browser-client";++class FakeRequest {+ static current?: FakeRequest;+ upload: {+ onprogress?: (event: ProgressEvent) => void;+ onload?: (event: ProgressEvent) => void;+ } = {};+ onload?: () => void;+ onerror?: () => void;+ onabort?: () => void;+ status = 200;+ responseText = "";+ url = "";+ body?: FormData;+ headers = new Headers();+ aborted = false;++ constructor() {+ FakeRequest.current = this;+ }++ open(_method: string, url: string) {+ this.url = url;+ }++ setRequestHeader(name: string, value: string) {+ this.headers.set(name, value);+ }++ getResponseHeader(name: string) {+ return name.toLowerCase() === "content-type" ? "application/json" : null;+ }++ send(body: FormData) {+ this.body = body;+ }++ abort() {+ this.aborted = true;+ this.onabort?.();+ }+}++const response = { success: true, status: 200, results: [], errors: [] };+const event = (loaded: number, total: number, lengthComputable = true) =>+ ({ loaded, total, lengthComputable }) as ProgressEvent;++afterEach(() => {+ FakeRequest.current = undefined;+ vi.unstubAllGlobals();+});++test("multipart upload reports measured request bytes and completes before server Actions", async () => {+ vi.stubGlobal("XMLHttpRequest", FakeRequest);+ vi.stubGlobal("window", { location: { origin: "https://example.com" } });+ const updates: UploadProgress[] = [];+ let settled = false;+ const result = submitManagedForm({+ values: { attachment: new File(["file"], "note.txt") },+ managedFormId: "form",+ location: "https://example.com/contact",+ headers: { "X-CSRF-Token": "fixture" },+ onUploadProgress: (update) => updates.push(update),+ }).then((value) => {+ settled = true;+ return value;+ });+ const request = FakeRequest.current!;+ expect(new URL(request.url).pathname).toBe("/__ws-form/contact");+ expect(request.headers.get("X-CSRF-Token")).toBe("fixture");+ expect((request.body?.get("attachment") as File).name).toBe("note.txt");++ request.upload.onprogress?.(event(4, 12));+ request.upload.onload?.(event(12, 12));+ await Promise.resolve();+ expect(updates).toEqual([+ { loaded: 4, total: 12 },+ { loaded: 12, total: 12 },+ ]);+ expect(settled).toBe(false);++ request.responseText = JSON.stringify(response);+ request.onload?.();+ await expect(result).resolves.toEqual(response);+});++test("uncomputable totals stay absent and cancellation aborts the request", async () => {+ vi.stubGlobal("XMLHttpRequest", FakeRequest);+ vi.stubGlobal("window", { location: { origin: "https://example.com" } });+ const controller = new AbortController();+ const updates: UploadProgress[] = [];+ const result = submitManagedForm({+ values: {},+ managedFormId: "form",+ location: "https://example.com/contact",+ signal: controller.signal,+ onUploadProgress: (update) => updates.push(update),+ });+ const request = FakeRequest.current!;+ request.upload.onprogress?.(event(4, 0, false));+ controller.abort("cancelled");+ await expect(result).rejects.toBe("cancelled");+ expect(request.aborted).toBe(true);+ expect(updates).toEqual([{ loaded: 4, total: undefined }]);+});diff --git a/packages/sdk/src/form/browser-client.ts b/packages/sdk/src/form/browser-client.tsindex c07e9de018..1639002751 100644--- a/packages/sdk/src/form/browser-client.ts+++ b/packages/sdk/src/form/browser-client.ts@@ -8,6 +8,81 @@ import {type getFormDataValue,} from "./browser-submission";+export type UploadProgress = {+ loaded?: number;+ total?: number;+};++/** Send one multipart body while observing only the bytes the browser measures. */+const postMultipartForm = ({+ endpoint,+ formData,+ signal,+ headers,+ onUploadProgress,+}: {+ endpoint: URL;+ formData: FormData;+ signal?: AbortSignal;+ headers?: HeadersInit;+ onUploadProgress?: (progress: UploadProgress) => void;+}) =>+ new Promise<Response>((resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason);+ return;+ }+ const xhr = new XMLHttpRequest();+ const cleanup = () => signal?.removeEventListener("abort", onAbort);+ const onAbort = () => xhr.abort();+ xhr.open("POST", endpoint.href);+ for (const [name, value] of new Headers(headers)) {+ xhr.setRequestHeader(name, value);+ }+ const reportUploadProgress = (event: ProgressEvent) => {+ onUploadProgress?.({+ loaded: event.loaded,+ total: event.lengthComputable ? event.total : undefined,+ });+ };+ xhr.upload.onprogress = reportUploadProgress;+ xhr.upload.onload = reportUploadProgress;+ xhr.onload = () => {+ cleanup();+ if (xhr.status === 0) {+ reject(new TypeError("Form submission failed"));+ return;+ }+ resolve(+ new Response(xhr.responseText || null, {+ status: xhr.status,+ headers: {+ "Content-Type": xhr.getResponseHeader("Content-Type") ?? "",+ },+ })+ );+ };+ xhr.onerror = () => {+ cleanup();+ reject(new TypeError("Form submission failed"));+ };+ xhr.onabort = () => {+ cleanup();+ reject(signal?.reason ?? new DOMException("Aborted", "AbortError"));+ };+ signal?.addEventListener("abort", onAbort, { once: true });+ if (signal?.aborted) {+ onAbort();+ return;+ }+ try {+ xhr.send(formData);+ } catch (error) {+ cleanup();+ reject(error);+ }+ });+const failure = (status: number, message: string): ManagedFormResponse => ({success: false,status,@@ -46,14 +121,20 @@ export const submitManagedForm = async ({location,endpoint: endpointOverride,signal,- fetch: request = fetch,+ headers,+ fetch,+ onUploadProgress,+ onResponse,}: {values: ReturnType<typeof getFormDataValue>;managedFormId: string;location: string;endpoint?: string;signal?: AbortSignal;- fetch?: typeof fetch;+ headers?: HeadersInit;+ fetch?: typeof globalThis.fetch;+ onUploadProgress?: (progress: UploadProgress) => void;+ onResponse?: (response: Response) => void | Promise<void>;}): Promise<ManagedFormResponse> => {const formData = createManagedSubmissionFormData({ values, managedFormId });const endpoint = new URL(endpointOverride ?? location, location);@@ -65,12 +146,21 @@ export const submitManagedForm = async ({endpoint.searchParams.set(managedFormRequestParamName, "1");}try {- const response = await request(endpoint, {- method: "POST",- body: formData,- credentials: "same-origin",- signal,- });+ const response = fetch+ ? await fetch(endpoint, {+ method: "POST",+ body: formData,+ signal,+ headers,+ })+ : await postMultipartForm({+ endpoint,+ formData,+ signal,+ headers,+ onUploadProgress,+ });+ await onResponse?.(response);const body: unknown = await response.json();return isManagedFormResponse(body)? bodydiff --git a/packages/sdk/src/form/browser-lifecycle.test.ts b/packages/sdk/src/form/browser-lifecycle.test.tsindex ef3db3a408..e6eeb120aa 100644--- a/packages/sdk/src/form/browser-lifecycle.test.ts+++ b/packages/sdk/src/form/browser-lifecycle.test.ts@@ -69,6 +69,23 @@ test("refresh failure cannot replace a successful POST result", async () => {expect(callbacks.onFeedback).toHaveBeenCalledOnce();});+test("rejected submission clears pending before reporting failure", async () => {+ const callbacks = createCallbacks();+ const events: string[] = [];+ callbacks.onPending = (pending) => events.push(pending ? "pending" : "idle");+ callbacks.onResult = () => events.push("result");+ callbacks.onState = () => events.push("state");+ const controller = new FormSubmissionController(() => callbacks);+ controller.submit(+ Promise.reject(new Error("network failed")),+ new AbortController(),+ undefined,+ "https://example.com/form"+ );+ await settle();+ expect(events.slice(0, 4)).toEqual(["pending", "idle", "result", "state"]);+});+test("duplicate submission aborts and observes the rejected promise", async () => {const callbacks = createCallbacks();const controller = new FormSubmissionController(() => callbacks);@@ -121,3 +138,35 @@ test("disposed controller aborts and observes the rejected promise", async () =>expect(callbacks.onResult).not.toHaveBeenCalled();expect(callbacks.onState).not.toHaveBeenCalled();});++test("cancel resets an active submission and ignores its late result", async () => {+ const callbacks = createCallbacks();+ callbacks.onCancel = vi.fn();+ const controller = new FormSubmissionController(() => callbacks);+ let resolve!: (response: ManagedFormResponse) => void;+ const delayed = new Promise<ManagedFormResponse>((done) => {+ resolve = done;+ });+ const abort = new AbortController();+ expect(+ controller.submit(delayed, abort, undefined, "https://example.com/form")+ ).toBe(true);++ controller.cancel();+ expect(abort.signal.aborted).toBe(true);+ expect(controller.pending).toBe(false);+ expect(callbacks.onCancel).toHaveBeenCalledOnce();+ resolve(success);+ await settle();+ expect(callbacks.onResult).not.toHaveBeenCalled();+ expect(callbacks.onState).not.toHaveBeenCalled();++ controller.submit(+ Promise.resolve(success),+ new AbortController(),+ undefined,+ "https://example.com/form"+ );+ await settle();+ expect(callbacks.onState).toHaveBeenCalledExactlyOnceWith("success");+});diff --git a/packages/sdk/src/form/browser-lifecycle.ts b/packages/sdk/src/form/browser-lifecycle.tsindex 9f614a802d..ce8eaffc47 100644--- a/packages/sdk/src/form/browser-lifecycle.ts+++ b/packages/sdk/src/form/browser-lifecycle.ts@@ -3,8 +3,22 @@ import type { ManagedFormResponse } from "./shared";export type FormSubmissionState = "initial" | "success" | "error";+export type FormProgress = {+ status: "idle" | "pending";+ loaded?: number;+ total?: number;+ files: Array<{+ id: string;+ fieldName: string;+ name: string;+ size: number;+ type: string;+ }>;+};+export type FormSubmissionCallbacks = {onPending: (pending: boolean) => void;+ onCancel?: () => void;onResult: (result: ManagedFormResponse) => void;onState: (state: FormSubmissionState) => void;onFeedback: () => void;@@ -36,10 +50,14 @@ export class FormSubmissionController {}cancel() {+ const wasPending = this.pending;this.active?.abort();this.active = undefined;if (!this.disposed) {this.getCallbacks().onPending(false);+ if (wasPending) {+ this.getCallbacks().onCancel?.();+ }}}@@ -104,6 +122,7 @@ export class FormSubmissionController {return;}const callbacks = this.getCallbacks();+ callbacks.onPending(false);const message =error instanceof Error ? error.message : "Form submission failed";callbacks.onResult({diff --git a/scripts/check-fixture-sizes.ts b/scripts/check-fixture-sizes.tsindex 462be1c1a2..283b0c0064 100644--- a/scripts/check-fixture-sizes.ts+++ b/scripts/check-fixture-sizes.ts@@ -5,7 +5,7 @@ const execFileAsync = promisify(execFile);const fixtureLimits = [["./fixtures/ssg-cloudflare-pages/dist/client", 364],- ["./fixtures/react-router-netlify/build/client", 376],+ ["./fixtures/react-router-netlify/build/client", 380],["./fixtures/webstudio-features/build/client", 3684],] as const;diff --git a/scripts/fetch-backed-form-request.ts b/scripts/fetch-backed-form-request.tsnew file mode 100644index 0000000000..b03a5716f0--- /dev/null+++ b/scripts/fetch-backed-form-request.ts@@ -0,0 +1,58 @@+/** Lets router and Remix tests keep their existing fetch-backed endpoint fakes. */+export class FetchBackedFormRequest {+ upload: { onload?: (event: ProgressEvent) => void } = {};+ onload?: () => void;+ onerror?: () => void;+ onabort?: () => void;+ status = 0;+ responseText = "";+ private url = "";+ private headers = new Headers();+ private response?: Response;+ private controller = new AbortController();++ open(_method: string, url: string) {+ this.url = url;+ }++ setRequestHeader(name: string, value: string) {+ this.headers.set(name, value);+ }++ getResponseHeader(name: string) {+ return this.response?.headers.get(name) ?? null;+ }++ send(body: FormData) {+ fetch(this.url, {+ method: "POST",+ body,+ headers: this.headers,+ signal: this.controller.signal,+ })+ .then(async (response) => {+ if (this.controller.signal.aborted) {+ return;+ }+ this.upload.onload?.({+ loaded: 0,+ total: 0,+ lengthComputable: false,+ } as ProgressEvent);+ this.response = response;+ this.status = response.status;+ this.responseText = await response.text();+ this.onload?.();+ })+ .catch(() => {+ if (!this.controller.signal.aborted) {+ this.onerror?.();+ }+ });+ }++ abort() {+ this.controller.abort();+ this.onabort?.();+ }+}