Files
webstudio/apps/builder/app/shared/sync/sync-client.ts
T
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

250 lines
6.7 KiB
TypeScript

import type { Project } from "@webstudio-is/project";
import type { AuthPermit } from "@webstudio-is/trpc-interface/index.server";
import type { SyncEmitter } from "@webstudio-is/sync-client";
import { SyncClient, type SyncStorage } from "~/shared/sync-client";
import {
createObjectPool,
registerContainers,
serverSyncStoreNames,
type ServerSyncState,
} from "./sync-stores";
import { loadBuilderData, type LoadedBuilderData } from "~/shared/builder-data";
import { publicStaticEnv } from "~/env/env.static";
import { isFeatureEnabled } from "@webstudio-is/feature-flags";
import { createSingleplayerSyncClient } from "./singleplayer-client";
import { createMultiplayerSyncClient } from "./multiplayer-client";
import {
$project,
$pages,
$assets,
$instances,
$props,
$dataSources,
$resources,
$breakpoints,
$styleSources,
$styleSourceSelections,
$styles,
$marketplaceProduct,
$projectSettings,
$publisherHost,
resetDataStores,
} from "./data-stores";
let client: SyncClient | undefined;
let currentProjectId: string | undefined;
let modeClient: SyncModeClient | undefined;
let initializationVersion = 0;
type SyncModeClient = {
clientId?: string;
emitter?: SyncEmitter;
storages: SyncStorage[];
destroy(): void;
onDataLoaded(data: LoadedBuilderData): void;
};
const resolveMultiplayerRelayUrl = (
relayUrl: string,
currentHref = typeof window === "undefined" ? undefined : window.location.href
) => {
if (currentHref === undefined) {
return relayUrl;
}
const currentUrl = new URL(currentHref);
const configuredUrl = new URL(relayUrl, currentUrl.origin);
const isRelativeRelayUrl =
relayUrl.startsWith("/") || relayUrl.startsWith(".");
const isLocalWstdDev =
currentUrl.hostname === "wstd.dev" ||
currentUrl.hostname.endsWith(".wstd.dev");
if (isRelativeRelayUrl && isLocalWstdDev && currentUrl.port === "5173") {
return new URL(configuredUrl.pathname, currentUrl.origin).href;
}
return configuredUrl.href;
};
const applyBuilderData = (data: LoadedBuilderData) => {
applyBuilderMetadata(data);
$pages.set(data.pages);
$assets.set(data.assets);
$instances.set(data.instances);
$props.set(data.props);
$dataSources.set(data.dataSources);
$resources.set(data.resources);
$breakpoints.set(data.breakpoints);
$styleSources.set(data.styleSources);
$styleSourceSelections.set(data.styleSourceSelections);
$styles.set(data.styles);
$marketplaceProduct.set(data.marketplaceProduct);
$projectSettings.set(data.projectSettings);
};
const applyBuilderMetadata = (data: LoadedBuilderData) => {
$publisherHost.set(data.publisherHost);
$project.set(data.project);
};
const getServerSyncState = (data: LoadedBuilderData): ServerSyncState =>
new Map(serverSyncStoreNames.map((name) => [name, data[name]]));
/**
* Initialize the sync infrastructure and load project data.
* Can be used from both the builder and dashboard contexts.
*/
export const initializeClientSync = ({
projectId,
authPermit,
authToken,
signal,
onReady,
}: {
projectId: Project["id"];
authPermit: AuthPermit;
authToken?: string;
signal: AbortSignal;
onReady?: () => void;
}) => {
const multiplayerRelayUrl = isFeatureEnabled("multiplayer")
? publicStaticEnv.COLLAB_RELAY_URL?.trim() || undefined
: undefined;
const resolvedMultiplayerRelayUrl =
multiplayerRelayUrl === undefined
? undefined
: resolveMultiplayerRelayUrl(multiplayerRelayUrl);
const useMultiplayer = resolvedMultiplayerRelayUrl !== undefined;
if (useMultiplayer) {
console.info("[builder-sync] multiplayer mode enabled", {
projectId,
relayUrl: resolvedMultiplayerRelayUrl,
});
}
const shouldPreloadStorage =
useMultiplayer === false && authPermit !== "view";
// Note: "view" permit will skip transaction synchronization
// Reset sync client if projectId changed
if (client && currentProjectId !== projectId) {
destroyClientSync();
}
const currentInitializationVersion = ++initializationVersion;
const loadData = (onSuccess: (data: LoadedBuilderData) => void) => {
loadBuilderData({ projectId, signal })
.then((data) => {
if (
signal.aborted ||
currentInitializationVersion !== initializationVersion
) {
return;
}
onSuccess(data);
})
.catch((error) => {
if (
signal.aborted === false &&
currentInitializationVersion === initializationVersion
) {
console.error("[builder-sync] failed to load project data:", error);
}
});
};
const completeDataLoad = (data: LoadedBuilderData) => {
applyBuilderData(data);
modeClient?.onDataLoaded(data);
onReady?.();
};
const connectClient = (initialData?: LoadedBuilderData) => {
registerContainers();
const object = createObjectPool();
const nextModeClient: SyncModeClient =
useMultiplayer && resolvedMultiplayerRelayUrl !== undefined
? createMultiplayerSyncClient({
applyBuilderData,
authPermit,
authToken,
projectId,
relayUrl: resolvedMultiplayerRelayUrl,
signal,
})
: createSingleplayerSyncClient({
authPermit,
authToken,
initialServerState:
initialData === undefined
? undefined
: getServerSyncState(initialData),
projectId,
});
modeClient = nextModeClient;
client = new SyncClient({
role: "leader",
object,
emitter: nextModeClient.emitter,
storages: nextModeClient.storages,
});
if (nextModeClient.clientId !== undefined) {
client.clientId = nextModeClient.clientId;
}
currentProjectId = projectId;
client.connect({
signal,
onReady() {
if (initialData !== undefined) {
applyBuilderMetadata(initialData);
modeClient?.onDataLoaded(initialData);
onReady?.();
return;
}
loadData(completeDataLoad);
},
});
};
// Only register containers once and create sync client
if (!client) {
if (shouldPreloadStorage) {
loadData(connectClient);
return;
}
connectClient();
return;
}
client.connect({
signal,
onReady() {
loadData(completeDataLoad);
},
});
};
/**
* Destroy sync client and reset all data stores.
* Call this when closing the builder or switching between projects.
*/
export const destroyClientSync = () => {
initializationVersion += 1;
modeClient?.destroy();
modeClient = undefined;
client = undefined;
currentProjectId = undefined;
resetDataStores();
};
export const getSyncClient = () => client;
export const __testing__ = {
getServerSyncState,
resolveMultiplayerRelayUrl,
};