Files
webstudio/apps/builder/e2e/flows/data-variables.ts
Oleg IsonenandClaude Fable 5 071a4d9a85 feat: MCP update 3 (#5864)
## Summary

This update adds new MCP and CLI capabilities for project auditing,
structured data, project-specific agent instructions, focused project
search, safer bulk editing, image descriptions, font discovery, visual
verification, and external registry inspection.

## New Capabilities

### Audit projects

- Run a single `audit` command across accessibility, SEO, security,
assets, styles, and performance.
- Limit an audit to selected scopes, pages, or severity levels.
- Receive stable findings with locations and suggested fixes.
- Run rendered audits across desktop, mobile, and Builder breakpoint
widths.
- Detect horizontal overflow, broken images, oversized images, eager
below-fold images, render-blocking resources, and legacy font formats.
- Identify unused assets, tokens, CSS variables, local styles, and
breakpoints.
- Identify duplicate token declarations.
- Detect accessibility issues involving names, labels, headings,
landmarks, IDs, keyboard focus, ARIA, iframes, and autoplaying media.
- Detect SEO issues involving titles, descriptions, language, social
images, and structured data.
- Detect unsafe new-tab links and write resources exposed during page
rendering.

### Search an entire project

- Search project text, labels, props, resources, assets, and styles
through `search-project`.
- Find relevant records without downloading and reparsing the full
project snapshot.
- Scope searches to the relevant project-data areas.

### Add validated JSON-LD

- Add structured data with a dedicated JSON-LD component.
- Place JSON-LD inside the page Head Slot.
- Edit JSON in a purpose-built code editor.
- Prevent structurally invalid JSON-LD from being saved.
- Validate Schema.org types, properties, and values.
- Find invalid, missing, unknown, deprecated, or incompatible structured
data through the SEO audit.
- Let agents discover the correct JSON-LD workflow without using page
custom metadata or a generic HTML embed.

### Configure project-specific agent instructions

- Add AI-agent instructions from the new **Agents** section in Project
Settings.
- Synchronize those instructions into a managed root `AGENTS.md`.
- Update or remove the managed file automatically during project sync.
- Protect existing user-owned `AGENTS.md` files from being overwritten.
- Share the instructions with authenticated CLI and MCP agents.
- Keep agent instructions out of publicly readable production bundles.

### Generate and manage image descriptions

- Audit image assets for missing descriptions.
- Let a vision-capable agent inspect each image in its rendered context.
- Save generated descriptions to multiple image assets in one operation.
- Mark images as intentionally decorative.
- Reuse the saved asset description wherever the image is used.
- Re-run the audit to verify that missing-description findings are
resolved.

### Perform bounded bulk replacements

- Replace matching literal text across selected pages with
`replace-text`.
- Replace matching fixed prop text with `replace-prop-text`.
- Replace matching resource names or URLs with `replace-resource-text`.
- Restrict replacements by page, instance, prop, resource, field, match
mode, and maximum change count.
- Leave dynamic expressions unchanged.

### Inspect element ancestry

- Return an element’s direct parent in instance listings.
- Request the complete ancestor chain when inspecting an element.
- Understand tree placement without rebuilding the instance hierarchy
from raw project data.

### Discover available fonts

- List uploaded font families through `list-fonts`.
- Discover available system font stacks.
- Inspect font family, style, weight, format, and associated asset
information before applying typography.

### Inspect external component registries

- Inspect a local or remote shadcn-style registry item.
- Read its description, files, dependencies, targets, and documentation.
- Receive an explicit Webstudio compatibility report.
- Inspect registry metadata without installing or executing external
code.

### Capture generated project routes directly

- Run `webstudio screenshot --path /route` against the configured
project.
- Generate a temporary production-style preview automatically.
- Capture the requested route.
- Stop the temporary preview after capture.
- Avoid manually building and starting a preview for a single
screenshot.

### Assert visual changes

- Add expected text to screenshot comparisons.
- Set maximum pixel mismatch limits.
- Set minimum or maximum changed-region counts.
- Assert whether overall brightness or a color channel moved in the
expected direction.
- Use these assertions as pass/fail evidence for visual changes.

### Require compatible CLI versions

- Send the project-bundle contract version with CLI synchronization
requests.
- Stop incompatible CLI versions before they receive incomplete project
data.
- Tell users exactly how to update the CLI or run the latest version
once.
- Prevent older clients from silently dropping project settings.

## Upgrade Note

This branch introduces a new synchronized project-bundle contract. Older
CLI versions must update before synchronizing against the new API.

```sh
npm install -g webstudio@latest
```

Or run the latest version once:

```sh
npx webstudio@latest <command>
```

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 11:27:58 +02:00

213 lines
6.3 KiB
TypeScript

import { createServer } from "node:http";
import type { Page } from "playwright";
import { selectCanvasTextInstance } from "./canvas-selection";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
const getVariableForm = (page: Page) =>
page
.locator("form")
.filter({ has: page.locator('input[name="name"]') })
.last();
const closeVariablePanelAndWaitForSave = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page });
await page.getByRole("button", { name: "Close" }).last().click();
await save;
await page
.getByText("New Variable", { exact: true })
.waitFor({ state: "hidden" });
await waitForSyncStatus({ page, status: "idle" });
};
const openNewVariablePanel = async ({ page }: { page: Page }) => {
await page.getByRole("tab", { name: "Settings" }).click();
await page.getByRole("button", { name: "Add data variable" }).click();
await page.getByText("New Variable", { exact: true }).waitFor();
};
const selectVariableType = async ({
page,
next,
}: {
page: Page;
next: string;
}) => {
await page
.getByText("Type", { exact: true })
.locator("xpath=following::button[1]")
.click();
await page
.getByRole("option", { name: new RegExp(`^${next}( Pro)?$`) })
.click();
};
const fillVariableName = async ({
page,
name,
}: {
page: Page;
name: string;
}) => {
await getVariableForm(page).locator('input[name="name"]').fill(name);
};
export const selectContentInstance = async ({ page }: { page: Page }) => {
await selectCanvasTextInstance({ page, text: "Initial content" });
await page
.getByText("No instance selected", { exact: true })
.waitFor({ state: "hidden" });
await page.getByRole("tab", { name: "Settings" }).click();
await page
.getByRole("button", { name: "Add data variable" })
.waitFor({ state: "visible" });
};
export const bindSelectedTextContentToExpression = async ({
page,
expression,
}: {
page: Page;
expression: string;
}) => {
await page.getByText("Text Content", { exact: true }).waitFor();
await page.getByText("Text Content", { exact: true }).hover();
await page
.getByText("Text Content", { exact: true })
.locator("xpath=following::button[@data-variant][1]")
.click();
const bindingDialog = page.getByRole("dialog", { name: "Binding" });
await bindingDialog.waitFor();
const expressionEditor = bindingDialog.locator(".cm-content").last();
await expressionEditor.click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.insertText(expression);
const save = waitForChangeToBeSaved({ page });
try {
await page.keyboard.press("ControlOrMeta+Enter");
await save;
} catch (error) {
const dialogText = await bindingDialog.innerText().catch(() => "");
throw new Error(
`Expected Text Content binding ${JSON.stringify(expression)} to save. Binding dialog: ${dialogText}`,
{ cause: error }
);
}
await waitForSyncStatus({ page, status: "idle" });
await page.keyboard.press("Escape");
};
export const createHttpResourceVariable = async ({
page,
name,
url,
}: {
page: Page;
name: string;
url: string;
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await selectVariableType({ page, next: "Resource" });
await page.getByRole("textbox", { name: "URL" }).fill(url);
await closeVariablePanelAndWaitForSave({ page });
};
export const createGraphqlResourceVariable = async ({
page,
name,
url,
query,
}: {
page: Page;
name: string;
url: string;
query: string;
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await selectVariableType({ page, next: "GraphQL" });
await page.getByRole("textbox", { name: "URL" }).fill(url);
await page.getByRole("textbox", { name: "Query" }).fill(query);
await closeVariablePanelAndWaitForSave({ page });
};
export const createSystemResourceVariable = async ({
page,
name,
resource = "Sitemap",
}: {
page: Page;
name: string;
resource?: "Sitemap" | "Current Date" | "Assets";
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await selectVariableType({ page, next: "System Resource" });
if (resource !== "Sitemap") {
await getVariableForm(page)
.getByText("Resource", { exact: true })
.locator("xpath=following::button[1]")
.click();
await page.getByRole("option", { name: resource, exact: true }).click();
}
await closeVariablePanelAndWaitForSave({ page });
};
export const startJsonResourceServer = async ({ title }: { title: string }) => {
const server = createServer((_request, response) => {
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
});
response.end(JSON.stringify({ title }));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolve());
});
const address = server.address();
if (address === null || typeof address === "string") {
await new Promise<void>((resolve) => server.close(() => resolve()));
throw new Error("Expected a numeric local resource server port.");
}
return {
url: `http://127.0.0.1:${address.port}/posts`,
close: async () =>
await new Promise<void>((resolve) => server.close(() => resolve())),
};
};
export const startGraphqlResourceServer = async ({
title,
}: {
title: string;
}) => {
const server = createServer((request, response) => {
if (request.method !== "POST") {
response.writeHead(405).end();
return;
}
response.writeHead(200, {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/json",
});
response.end(JSON.stringify({ data: { post: { title } } }));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolve());
});
const address = server.address();
if (address === null || typeof address === "string") {
await new Promise<void>((resolve) => server.close(() => resolve()));
throw new Error("Expected a numeric local GraphQL server port.");
}
return {
url: `http://127.0.0.1:${address.port}/graphql`,
close: async () =>
await new Promise<void>((resolve) => server.close(() => resolve())),
};
};