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: Add asset folders to asset manager and improve asset manager UX (#5892)
Oleg Isonen878d6f1de196
diff --git a/.github/actions/vercel/action.yaml b/.github/actions/vercel/action.yamlindex dcf47f5f0d..07f0be0b44 100644--- a/.github/actions/vercel/action.yaml+++ b/.github/actions/vercel/action.yaml@@ -45,8 +45,7 @@ runs:steps:- id: branchrun: |- CLEAN_NAME="${REF_NAME/.staging/}"- CLEAN_NAME=$( echo "${CLEAN_NAME}" | sed 's/[^a-zA-Z0-9_-]//g' | tr A-Z a-z | tr _ - | sed 's/-\{2,\}/-/g' )+ CLEAN_NAME=$(.github/actions/vercel/deployment-alias.sh "${REF_NAME}")echo "value=${CLEAN_NAME}" >> $GITHUB_OUTPUTshell: bashenv:diff --git a/.github/actions/vercel/deployment-alias.sh b/.github/actions/vercel/deployment-alias.shnew file mode 100755index 0000000000..94c23a7c00--- /dev/null+++ b/.github/actions/vercel/deployment-alias.sh@@ -0,0 +1,15 @@+#!/usr/bin/env bash++set -euo pipefail++ref_name="${1:?A git ref name is required}"+alias="${ref_name/.staging/}"+alias=$(echo "${alias}" | sed 's/[^a-zA-Z0-9_-]//g' | tr '[:upper:]_' '[:lower:]-' | sed 's/-\{2,\}/-/g')++# Project requests use p-<uuid>-dot-<alias>, which must fit in a 63-byte DNS label.+if (( ${#alias} > 20 )); then+ hash=$(printf '%s' "${alias}" | git hash-object --stdin | cut -c1-7)+ alias="${alias:0:12}-${hash}"+fi++printf '%s\n' "${alias}"diff --git a/.github/workflows/vercel-deploy-staging.yml b/.github/workflows/vercel-deploy-staging.ymlindex ce65d3d961..69e4b8f534 100644--- a/.github/workflows/vercel-deploy-staging.yml+++ b/.github/workflows/vercel-deploy-staging.yml@@ -128,13 +128,16 @@ jobs:outputs:development-builder-host: ${{ steps.host.outputs.value }}steps:+ - uses: actions/checkout@v4+ with:+ ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.head.sha || github.sha }}+- id: hostshell: bashenv:REF_NAME: ${{ github.event_name == 'pull_request_target' && format('pr-{0}', github.event.pull_request.number) || github.ref_name }}run: |- clean_name="${REF_NAME/.staging/}"- clean_name=$(echo "${clean_name}" | sed 's/[^a-zA-Z0-9_-]//g' | tr A-Z a-z | tr _ - | sed 's/-\{2,\}/-/g')+ clean_name=$(.github/actions/vercel/deployment-alias.sh "${REF_NAME}")echo "value=${clean_name}.development.webstudio.is" >> "$GITHUB_OUTPUT"fixtures-test:diff --git a/apps/builder/app/builder/features/assets/assets.tsx b/apps/builder/app/builder/features/assets/assets.tsxindex fa201c576a..992ae1c4aa 100644--- a/apps/builder/app/builder/features/assets/assets.tsx+++ b/apps/builder/app/builder/features/assets/assets.tsx@@ -4,30 +4,65 @@ import {Separator,Tooltip,} from "@webstudio-is/design-system";-import { BrushCleaningIcon } from "@webstudio-is/icons";+import { BrushCleaningIcon, NewFolderIcon } from "@webstudio-is/icons";+import { useRef, useState } from "react";+import { useStore } from "@nanostores/react";import { AssetManager } from "~/builder/shared/asset-manager";-import { AssetUpload } from "~/builder/shared/assets";+import { AssetUpload, type AssetUploadHandle } from "~/builder/shared/assets";import { openDeleteUnusedAssetsDialog } from "~/builder/shared/asset-manager/delete-unused-assets";+import { CreateAssetFolderDialog } from "~/builder/shared/asset-manager/asset-folder-dialogs";+import { $authPermit } from "~/shared/nano-states";export const AssetsPanel = (_props: { onClose: () => void }) => {+ const [folderId, setFolderId] = useState<string>();+ const [createFolderOpen, setCreateFolderOpen] = useState(false);+ const uploadRef = useRef<AssetUploadHandle>(null);+ const authPermit = useStore($authPermit);return (<><PanelTitlesuffix={<>+ <Tooltip content="Create folder">+ <IconButton+ disabled={authPermit === "view"}+ aria-label="Create asset folder"+ onClick={() => setCreateFolderOpen(true)}+ >+ <NewFolderIcon />+ </IconButton>+ </Tooltip><Tooltip content="Delete unused assets"><IconButton onClick={openDeleteUnusedAssetsDialog}><BrushCleaningIcon /></IconButton></Tooltip>- <AssetUpload type="file" />+ <AssetUpload ref={uploadRef} type="file" folderId={folderId} /></>}>Assets</PanelTitle><Separator />- <AssetManager />+ <AssetManager+ folderId={folderId}+ onFolderChange={setFolderId}+ canManageFolders={authPermit !== "view"}+ panelActions={{+ ...(authPermit === "view"+ ? {}+ : {+ createFolder: () => setCreateFolderOpen(true),+ upload: () => uploadRef.current?.open(),+ }),+ deleteUnusedAssets: openDeleteUnusedAssetsDialog,+ }}+ />+ <CreateAssetFolderDialog+ open={createFolderOpen}+ onOpenChange={setCreateFolderOpen}+ currentFolderId={folderId}+ /></>);};diff --git a/apps/builder/app/builder/features/pages/page-settings.stories.tsx b/apps/builder/app/builder/features/pages/page-settings.stories.tsxindex e6c67349ef..8a5fb36b64 100644--- a/apps/builder/app/builder/features/pages/page-settings.stories.tsx+++ b/apps/builder/app/builder/features/pages/page-settings.stories.tsx@@ -82,6 +82,7 @@ $project.set({name: "very-very-very-long-long-image-name.jpg",filename: null,description: null,+ folderId: null,},latestBuildVirtual: null,domainsVirtual: [],diff --git a/apps/builder/app/builder/features/sync-status.tsx b/apps/builder/app/builder/features/sync-status.tsxindex b085f21d3d..7f7c429308 100644--- a/apps/builder/app/builder/features/sync-status.tsx+++ b/apps/builder/app/builder/features/sync-status.tsx@@ -14,7 +14,7 @@ import { OfflineIcon } from "@webstudio-is/icons";import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";const syncStatusDotSavedDuration = 2000;-const syncStatusDotPendingColor = "#f4c430";+const syncStatusDotPendingColor = theme.colors.backgroundStatusAttention;const $isOnline = atom(false);const syncStatusDotConfig = {idle: {diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-actions.ts b/apps/builder/app/builder/shared/asset-manager/asset-folder-actions.tsnew file mode 100644index 0000000000..733ed9dfa5--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-actions.ts@@ -0,0 +1,39 @@+import { executeRuntimeMutation } from "~/shared/instance-utils/data";++export const createAssetFolder = (values: {+ name: string;+ parentId: string | undefined;+}) => executeRuntimeMutation({ id: "assetFolders.create", input: values });++const updateAssetFolder = (+ folderId: string,+ values: { name?: string; parentId?: string | null }+) =>+ executeRuntimeMutation({+ id: "assetFolders.update",+ input: { folderId, values },+ });++export const saveAssetFolder = (+ folderId: string,+ values: { name: string; parentId: string | undefined }+) =>+ updateAssetFolder(folderId, {+ name: values.name,+ parentId: values.parentId ?? null,+ });++export const deleteAssetFolder = (folderId: string) =>+ executeRuntimeMutation({+ id: "assetFolders.delete",+ input: { folderId },+ });++export const moveAssetToFolder = (+ assetId: string,+ folderId: string | undefined+) =>+ executeRuntimeMutation({+ id: "assets.update",+ input: { assetId, values: { folderId: folderId ?? null } },+ });diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsxnew file mode 100644index 0000000000..cd71ae6987--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-breadcrumbs.tsx@@ -0,0 +1,125 @@+import {+ Button,+ ContextMenu,+ ContextMenuTrigger,+ Flex,+ ScrollAreaNative,+ Separator,+ Text,+ theme,+} from "@webstudio-is/design-system";+import type { AssetFolderHierarchy } from "@webstudio-is/sdk";+import { ChevronRightIcon } from "@webstudio-is/icons";+import { useEffect, useRef, type ReactElement } from "react";+import { AssetManagerItemContextMenuContent } from "./asset-manager-item-menu";++const PasteTarget = ({+ children,+ folderId,+ canPaste,+ onPaste,+}: {+ children: ReactElement;+ folderId: string | undefined;+ canPaste?: (folderId: string | undefined) => boolean;+ onPaste?: (folderId: string | undefined) => void;+}) => {+ if (onPaste === undefined || canPaste?.(folderId) === false) {+ return children;+ }+ return (+ <ContextMenu>+ <ContextMenuTrigger asChild>{children}</ContextMenuTrigger>+ <AssetManagerItemContextMenuContent+ actions={{ paste: () => onPaste(folderId) }}+ />+ </ContextMenu>+ );+};++export const AssetFolderBreadcrumbs = ({+ hierarchy,+ folderId,+ onChange,+ canPaste,+ onPaste,+}: {+ hierarchy: AssetFolderHierarchy;+ folderId: string | undefined;+ onChange: (folderId: string | undefined) => void;+ canPaste?: (folderId: string | undefined) => boolean;+ onPaste?: (folderId: string | undefined) => void;+}) => {+ const path = hierarchy.getPath(folderId);+ const currentFolderRef = useRef<HTMLButtonElement>(null);+ useEffect(() => {+ currentFolderRef.current?.scrollIntoView({+ block: "nearest",+ inline: "nearest",+ });+ }, [folderId]);+ return (+ <>+ <Separator />+ <ScrollAreaNative+ css={{+ width: "100%",+ overflowX: "auto",+ overflowY: "hidden",+ scrollbarWidth: "none",+ "&::-webkit-scrollbar": { display: "none" },+ flexShrink: 0,+ marginBottom: `calc(-1 * ${theme.panel.paddingBlock})`,+ }}+ aria-label="Asset folder path"+ >+ <Flex+ align="center"+ gap={1}+ css={{+ minWidth: "max-content",+ minHeight: theme.spacing[12],+ paddingInline: theme.spacing[2],+ paddingBlock: theme.spacing[2],+ }}+ >+ <PasteTarget+ folderId={undefined}+ canPaste={canPaste}+ onPaste={onPaste}+ >+ <Button+ ref={folderId === undefined ? currentFolderRef : undefined}+ color="ghost"+ aria-current={folderId === undefined ? "location" : undefined}+ onClick={() => onChange(undefined)}+ >+ <Text css={{ minWidth: "3ch" }}>Root</Text>+ </Button>+ </PasteTarget>+ {path.map((folder) => (+ <Flex key={folder.id} align="center" shrink={false}>+ <ChevronRightIcon size={12} />+ <PasteTarget+ folderId={folder.id}+ canPaste={canPaste}+ onPaste={onPaste}+ >+ <Button+ ref={folder.id === folderId ? currentFolderRef : undefined}+ color="ghost"+ aria-current={folder.id === folderId ? "location" : undefined}+ onClick={() => onChange(folder.id)}+ >+ <Text truncate css={{ minWidth: "3ch", maxWidth: 160 }}>+ {folder.name}+ </Text>+ </Button>+ </PasteTarget>+ </Flex>+ ))}+ </Flex>+ </ScrollAreaNative>+ </>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsxnew file mode 100644index 0000000000..3def45b28f--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.test.tsx@@ -0,0 +1,114 @@+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, expect, test, vi } from "vitest";+import { $assetFolders } from "~/shared/sync/data-stores";+import {+ AssetFolderSettingsDialog,+ CreateAssetFolderDialog,+} from "./asset-folder-dialogs";+import {+ createAssetFolderFixture,+ createAssetFoldersFixture,+} from "@webstudio-is/sdk/testing";+import { createAssetManagerTestRenderer } from "./test-utils";++const renderer = createAssetManagerTestRenderer();++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ });+});++afterEach(() => {+ renderer.cleanup();+ $assetFolders.set(new Map());+ vi.unstubAllGlobals();+});++test("Escape closes folder settings without closing the assets panel", () => {+ const folder = createAssetFolderFixture({+ id: "folder",+ name: "Documents",+ });+ $assetFolders.set(createAssetFoldersFixture(folder));+ const onPanelClose = vi.fn();+ const onSettingsOpenChange = vi.fn();++ renderer.render(+ <div+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ onPanelClose();+ }+ }}+ >+ <AssetFolderSettingsDialog+ folder={folder}+ open+ onOpenChange={onSettingsOpenChange}+ />+ </div>+ );++ act(() => {+ document.activeElement?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })+ );+ });++ expect(onSettingsOpenChange).toHaveBeenCalledWith(false);+ expect(onPanelClose).not.toHaveBeenCalled();+});++test.each([+ { initialDeleteConfirmation: false, focusedAction: "Save" },+ { initialDeleteConfirmation: true, focusedAction: "Delete folder" },+])(+ "focuses $focusedAction as the rightmost folder settings action",+ ({ initialDeleteConfirmation, focusedAction }) => {+ const folder = createAssetFolderFixture({+ id: "folder",+ name: "Documents",+ });+ $assetFolders.set(createAssetFoldersFixture(folder));++ renderer.render(+ <AssetFolderSettingsDialog+ folder={folder}+ open+ onOpenChange={vi.fn()}+ initialDeleteConfirmation={initialDeleteConfirmation}+ />+ );++ expect(document.activeElement?.textContent).toBe(focusedAction);+ }+);++test("focuses the folder name while the rightmost Create action is disabled", () => {+ renderer.render(+ <CreateAssetFolderDialog+ open+ onOpenChange={vi.fn()}+ currentFolderId={undefined}+ />+ );++ expect(document.activeElement).toBe(+ document.querySelector("#asset-folder-name")+ );+ expect(+ Array.from(document.querySelectorAll("button")).find(+ (button) => button.textContent === "Create folder"+ )?.disabled+ ).toBe(true);+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsxnew file mode 100644index 0000000000..746314eccd--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-dialogs.tsx@@ -0,0 +1,258 @@+import {+ useLayoutEffect,+ useMemo,+ useState,+ type KeyboardEvent,+ type ReactNode,+} from "react";+import { useStore } from "@nanostores/react";+import {+ Box,+ Button,+ Dialog,+ DialogContent,+ DialogTitle,+ Flex,+ Grid,+ InputField,+ Label,+ Text,+ theme,+} from "@webstudio-is/design-system";+import {+ createAssetFolderHierarchy,+ type AssetFolder,+} from "@webstudio-is/sdk";+import { TrashIcon } from "@webstudio-is/icons";+import { $assetFolders } from "~/shared/sync/data-stores";+import { AssetFolderSelector } from "./asset-folder-selector";+import {+ createAssetFolder,+ deleteAssetFolder,+ saveAssetFolder,+} from "./asset-folder-actions";++type AssetFolderFormValues = {+ name: string;+ parentId: string | undefined;+};++const runAndClose = (+ action: () => unknown,+ onOpenChange: (open: boolean) => void+) => {+ if (action() !== undefined) {+ onOpenChange(false);+ }+};++const stopEscapePropagation = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.stopPropagation();+ }+};++const AssetFolderForm = ({+ id,+ open,+ initialName,+ initialParentId,+ excludedFolderId,+ autoFocusSubmit = false,+ submitLabel,+ secondaryAction,+ onSubmit,+}: {+ id: string;+ open: boolean;+ initialName: string;+ initialParentId: string | undefined;+ excludedFolderId?: string;+ autoFocusSubmit?: boolean;+ submitLabel: string;+ secondaryAction?: ReactNode;+ onSubmit: (values: AssetFolderFormValues) => void;+}) => {+ const folders = useStore($assetFolders);+ const hierarchy = useMemo(+ () => createAssetFolderHierarchy(folders),+ [folders]+ );+ const [name, setName] = useState(initialName);+ const [parentId, setParentId] = useState(initialParentId);++ useLayoutEffect(() => {+ if (open) {+ setName(initialName);+ setParentId(initialParentId);+ }+ }, [initialName, initialParentId, open]);++ const normalizedName = name.trim();+ const duplicate =+ hierarchy.findByName({+ name,+ parentId,+ excludeIds:+ excludedFolderId === undefined+ ? undefined+ : new Set([excludedFolderId]),+ }) !== undefined;+ const canSubmit = normalizedName.length > 0 && duplicate === false;+ const submit = () => {+ if (canSubmit) {+ onSubmit({ name: normalizedName, parentId });+ }+ };++ return (+ <Grid gap={3} css={{ padding: theme.panel.padding }}>+ <Grid gap={1}>+ <Label htmlFor={id}>Folder</Label>+ <InputField+ id={id}+ autoFocus={autoFocusSubmit === false}+ value={name}+ color={duplicate ? "error" : undefined}+ onChange={(event) => setName(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ submit();+ }+ }}+ />+ {duplicate && (+ <Text color="destructive" variant="tiny">+ A folder with this name already exists here.+ </Text>+ )}+ </Grid>+ <AssetFolderSelector+ value={parentId}+ onChange={setParentId}+ excludedFolderId={excludedFolderId}+ rootLabel="Parent folder"+ />+ <Flex justify="end" gap={2}>+ {secondaryAction}+ <Button+ autoFocus={autoFocusSubmit}+ disabled={canSubmit === false}+ onClick={submit}+ >+ {submitLabel}+ </Button>+ </Flex>+ </Grid>+ );+};++export const CreateAssetFolderDialog = ({+ open,+ onOpenChange,+ currentFolderId,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ currentFolderId: string | undefined;+}) => {+ const create = (values: AssetFolderFormValues) =>+ runAndClose(() => createAssetFolder(values), onOpenChange);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ minWidth={360}+ aria-describedby={undefined}+ onKeyDown={stopEscapePropagation}+ >+ <DialogTitle>New folder</DialogTitle>+ <AssetFolderForm+ id="asset-folder-name"+ open={open}+ initialName=""+ initialParentId={currentFolderId}+ submitLabel="Create folder"+ onSubmit={create}+ />+ </DialogContent>+ </Dialog>+ );+};++export const AssetFolderSettingsDialog = ({+ folder,+ open,+ onOpenChange,+ initialDeleteConfirmation = false,+}: {+ folder: AssetFolder;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ initialDeleteConfirmation?: boolean;+}) => {+ const [confirmDelete, setConfirmDelete] = useState(false);+ useLayoutEffect(() => {+ if (open) {+ setConfirmDelete(initialDeleteConfirmation);+ }+ }, [initialDeleteConfirmation, open]);++ const save = (values: AssetFolderFormValues) =>+ runAndClose(() => saveAssetFolder(folder.id, values), onOpenChange);++ const remove = () =>+ runAndClose(() => deleteAssetFolder(folder.id), onOpenChange);++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent+ minWidth={360}+ aria-describedby={undefined}+ onKeyDown={stopEscapePropagation}+ >+ <DialogTitle>+ {confirmDelete ? "Delete folder" : "Folder settings"}+ </DialogTitle>+ {confirmDelete ? (+ <Box css={{ padding: theme.panel.padding }}>+ <Text>+ Delete “{folder.name}”? Everything inside this folder, including+ nested folders and assets, will be deleted.+ </Text>+ <Flex justify="end" gap={2} css={{ marginTop: theme.spacing[4] }}>+ <Button+ autoFocus+ color="destructive"+ prefix={<TrashIcon />}+ onClick={remove}+ >+ Delete folder+ </Button>+ </Flex>+ </Box>+ ) : (+ <AssetFolderForm+ id={`asset-folder-name-${folder.id}`}+ open={open}+ initialName={folder.name}+ initialParentId={folder.parentId}+ excludedFolderId={folder.id}+ autoFocusSubmit+ submitLabel="Save"+ onSubmit={save}+ secondaryAction={+ <Button+ color="destructive"+ prefix={<TrashIcon />}+ onClick={() => setConfirmDelete(true)}+ >+ Delete+ </Button>+ }+ />+ )}+ </DialogContent>+ </Dialog>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.tsnew file mode 100644index 0000000000..ee0f1af8e6--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.test.ts@@ -0,0 +1,85 @@+import { describe, expect, test } from "vitest";+import {+ createAssetFolderSelectorLevels,+ getAssetFolderSelectValue,+} from "./asset-folder-selector";+import {+ createAssetFolderFixture,+ createAssetFoldersFixture as folders,+} from "@webstudio-is/sdk/testing";++const folder = (id: string, parentId?: string) =>+ createAssetFolderFixture({ id, parentId });++describe("asset folder selector levels", () => {+ const values = folders(+ folder("parent"),+ folder("child", "parent"),+ folder("grandchild", "child"),+ folder("sibling")+ );++ test("selects every segment of the current folder path", () => {+ const levels = createAssetFolderSelectorLevels({+ folders: values,+ value: "grandchild",+ });++ expect(levels.map(({ selected }) => selected.folderId)).toEqual([+ "parent",+ "child",+ "grandchild",+ ]);+ expect(levels[0].options.map(({ folderId }) => folderId)).toEqual([+ undefined,+ "parent",+ "sibling",+ ]);+ expect(levels[0].options[0].label).toBe("Root");+ });++ test("excludes a folder and all descendants when choosing its parent", () => {+ const levels = createAssetFolderSelectorLevels({+ folders: values,+ value: undefined,+ excludedFolderId: "parent",+ });++ expect(levels).toHaveLength(1);+ expect(levels[0].options.map(({ folderId }) => folderId)).toEqual([+ undefined,+ "sibling",+ ]);+ });++ test("supports context-specific labeling for the root level", () => {+ const [level] = createAssetFolderSelectorLevels({+ folders: values,+ value: undefined,+ rootLabel: "Parent folder",+ });++ expect(level.ariaLabel).toBe("Parent folder");+ });++ test("falls back to Root when the selected folder no longer exists", () => {+ const [level] = createAssetFolderSelectorLevels({+ folders: values,+ value: "missing",+ });++ expect(level.selected).toEqual({+ label: "Root",+ folderId: undefined,+ });+ });++ test("uses non-empty unique select values for Root and folders", () => {+ expect(+ getAssetFolderSelectValue({ label: "Root", folderId: undefined })+ ).toBe("no-folder");+ expect(+ getAssetFolderSelectValue({ label: "Folder", folderId: "no-folder" })+ ).toBe("folder:no-folder");+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsxnew file mode 100644index 0000000000..5431f44f29--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-selector.tsx@@ -0,0 +1,203 @@+import {+ useCallback,+ useEffect,+ useId,+ useMemo,+ useRef,+ useState,+} from "react";+import { useStore } from "@nanostores/react";+import { Flex, Grid, Label, Select } from "@webstudio-is/design-system";+import { ChevronRightIcon } from "@webstudio-is/icons";+import {+ createAssetFolderHierarchy,+ type AssetFolders,+} from "@webstudio-is/sdk";+import { $assetFolders } from "~/shared/sync/data-stores";++type Option = { label: string; folderId: string | undefined };+const defaultRootLabel = "Top level folder";++export const getAssetFolderSelectValue = (option: Option) =>+ option.folderId === undefined ? "no-folder" : `folder:${option.folderId}`;++export const createAssetFolderSelectorLevels = ({+ folders,+ value,+ excludedFolderId,+ rootLabel = defaultRootLabel,+}: {+ folders: AssetFolders;+ value: string | undefined;+ excludedFolderId?: string;+ rootLabel?: string;+}) => {+ const hierarchy = createAssetFolderHierarchy(folders);+ const excludedIds =+ excludedFolderId === undefined+ ? new Set<string>()+ : hierarchy.getSubtreeIds(excludedFolderId);+ const getChildren = (parentId: string | undefined) =>+ hierarchy+ .getChildren(parentId)+ .filter((folder) => excludedIds.has(folder.id) === false)+ .toSorted((left, right) => left.name.localeCompare(right.name));+ const path = hierarchy+ .getPath(value)+ .filter(({ id }) => excludedIds.has(id) === false);+ const topOptions: Option[] = [+ { label: "Root", folderId: undefined },+ ...getChildren(undefined).map((folder) => ({+ label: folder.name,+ folderId: folder.id,+ })),+ ];+ const levels = [+ {+ ariaLabel: rootLabel,+ options: topOptions,+ selected:+ topOptions.find(({ folderId }) => folderId === path[0]?.id) ??+ topOptions[0],+ },+ ];++ path.forEach((folder, index) => {+ const children = getChildren(folder.id);+ if (children.length === 0) {+ return;+ }+ const options: Option[] = [+ {+ label: "This folder",+ folderId: folder.id,+ },+ ...children.map((child) => ({+ label: child.name,+ folderId: child.id,+ })),+ ];+ const nextId = path[index + 1]?.id;+ levels.push({+ ariaLabel: `Asset subfolder level ${index + 1}`,+ options,+ selected:+ options.find(({ folderId }) => folderId === nextId) ?? options[0],+ });+ });+ return levels;+};++export const AssetFolderSelector = ({+ value,+ onChange,+ excludedFolderId,+ rootLabel = defaultRootLabel,+ disabled,+ deferChangesUntilBlur = false,+}: {+ value: string | undefined;+ onChange: (folderId: string | undefined) => void;+ excludedFolderId?: string;+ rootLabel?: string;+ disabled?: boolean;+ deferChangesUntilBlur?: boolean;+}) => {+ const folders = useStore($assetFolders);+ const selectId = useId();+ const [draftValue, setDraftValue] = useState(value);+ const pendingValue = useRef<{ folderId: string | undefined }>();+ const openSelects = useRef(new Set<number>());+ const onChangeRef = useRef(onChange);+ onChangeRef.current = onChange;++ const commitPendingValue = useCallback(() => {+ const pending = pendingValue.current;+ if (pending === undefined) {+ return;+ }+ pendingValue.current = undefined;+ onChangeRef.current(pending.folderId);+ }, []);++ useEffect(() => {+ if (pendingValue.current === undefined) {+ setDraftValue(value);+ }+ }, [value]);++ useEffect(+ () => () => {+ if (deferChangesUntilBlur) {+ commitPendingValue();+ }+ },+ [commitPendingValue, deferChangesUntilBlur]+ );++ const levels = useMemo(+ () =>+ createAssetFolderSelectorLevels({+ folders,+ value: draftValue,+ excludedFolderId,+ rootLabel,+ }),+ [draftValue, excludedFolderId, folders, rootLabel]+ );++ return (+ <Grid+ gap={1}+ onBlurCapture={(event) => {+ if (deferChangesUntilBlur === false) {+ return;+ }+ const selector = event.currentTarget;+ queueMicrotask(() => {+ if (+ openSelects.current.size > 0 ||+ selector.contains(document.activeElement)+ ) {+ return;+ }+ commitPendingValue();+ });+ }}+ >+ <Label htmlFor={`${selectId}-0`}>{rootLabel}</Label>+ <Flex align="center" gap={1} wrap="wrap">+ {levels.map((level, index) => (+ <Flex key={level.ariaLabel} align="center" gap={1}>+ {index > 0 && <ChevronRightIcon size={12} />}+ <Select+ id={`${selectId}-${index}`}+ aria-label={level.ariaLabel}+ options={level.options}+ value={level.selected}+ disabled={disabled}+ getLabel={(option: Option) => option.label}+ getValue={getAssetFolderSelectValue}+ onOpenChange={(open) => {+ if (open) {+ openSelects.current.add(index);+ } else {+ openSelects.current.delete(index);+ }+ }}+ onChange={(option: Option) => {+ setDraftValue(option.folderId);+ if (deferChangesUntilBlur) {+ pendingValue.current = { folderId: option.folderId };+ } else {+ onChange(option.folderId);+ }+ }}+ css={{ width: "auto", minWidth: "8ch", maxWidth: "18ch" }}+ />+ </Flex>+ ))}+ </Flex>+ </Grid>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsxnew file mode 100644index 0000000000..1ae18ab02a--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-thumbnail.tsx@@ -0,0 +1,247 @@+import { useEffect, useRef, useState } from "react";+import { useStore } from "@nanostores/react";+import { ChevronRightIcon, FolderIcon } from "@webstudio-is/icons";+import type { AssetFolder } from "@webstudio-is/sdk";+import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";+import {+ draggable,+ dropTargetForElements,+} from "@atlaskit/pragmatic-drag-and-drop/element/adapter";+import { AssetFolderSettingsDialog } from "./asset-folder-dialogs";+import {+ AssetThumbnailCard,+ AssetThumbnailGroup,+} from "./asset-thumbnail-card";+import {+ $assetManagerClipboard,+ canPasteAssetManagerItem,+ createAssetManagerClipboardActions,+ pasteAssetManagerItem,+} from "./asset-manager-clipboard";+import { setAssetManagerDragPreview } from "./asset-manager-drag-preview";+import { getAssetManagerDragItems } from "./asset-manager-drag";+import { type AssetManagerItemActions } from "./asset-manager-item-menu";+import type { AssetManagerSelection } from "./asset-manager-selection";+import {+ AssetManagerThumbnail,+ AssetManagerThumbnailMenu,+ type AssetManagerThumbnailInteractions,+} from "./asset-manager-thumbnail";++export const FolderThumbnail = ({+ folder,+ selected,+ interactions,+ onOpen,+ canManage,+ canMoveItems,+ onMoveItems,+ path,+ onElementChange,+ forcedSelection,+ selectionActions,+}: {+ folder: AssetFolder;+ selected: boolean;+ interactions: AssetManagerThumbnailInteractions;+ onOpen: () => void;+ canManage: boolean;+ canMoveItems: (+ items: readonly AssetManagerSelection[],+ folderId: string+ ) => boolean;+ onMoveItems: (+ items: readonly AssetManagerSelection[],+ folderId: string+ ) => void;+ path?: string;+ onElementChange?: (element: HTMLElement | null) => void;+ forcedSelection?: boolean;+ selectionActions?: AssetManagerItemActions;+}) => {+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [deleteConfirmationOpen, setDeleteConfirmationOpen] = useState(false);+ const [isDropTarget, setIsDropTarget] = useState(false);+ const elementRef = useRef<HTMLElement | null>(null);+ const clipboard = useStore($assetManagerClipboard);+ const getDragItems = interactions.getDragItems;++ const openSettings = (confirmDelete = false) => {+ setDeleteConfirmationOpen(confirmDelete);+ setSettingsOpen(true);+ };+ const item = {+ type: "folder" as const,+ id: folder.id,+ projectId: folder.projectId,+ };+ const actions: AssetManagerItemActions = {+ open: onOpen,+ ...(canManage+ ? {+ settings: () => openSettings(),+ ...createAssetManagerClipboardActions(item),+ paste:+ clipboard?.projectId !== folder.projectId ||+ canPasteAssetManagerItem(folder.id) === false+ ? undefined+ : () => pasteAssetManagerItem(folder.id),+ delete: () => openSettings(true),+ }+ : {}),+ };++ useEffect(() => {+ const element = elementRef.current;+ if (element === null || canManage === false) {+ return;+ }+ return combine(+ draggable({+ element,+ onGenerateDragPreview: ({ nativeSetDragImage, location }) => {+ setAssetManagerDragPreview({+ nativeSetDragImage,+ sourceElement: element,+ input: location.initial.input,+ items: getDragItems({ type: "folder", id: folder.id }),+ });+ },+ getInitialData: () => ({+ kind: "asset-folder",+ id: folder.id,+ items: getDragItems({ type: "folder", id: folder.id }),+ }),+ }),+ dropTargetForElements({+ element,+ canDrop: ({ source }) => {+ const items = getAssetManagerDragItems(source.data);+ return items.length > 0 && canMoveItems(items, folder.id);+ },+ onDragEnter: () => setIsDropTarget(true),+ onDragLeave: () => setIsDropTarget(false),+ onDrop: ({ source }) => {+ setIsDropTarget(false);+ const items = getAssetManagerDragItems(source.data);+ if (items.length === 0) {+ return;+ }+ onMoveItems(items, folder.id);+ },+ })+ );+ }, [canManage, canMoveItems, folder.id, getDragItems, onMoveItems]);++ const displayedActions =+ forcedSelection && selected ? (selectionActions ?? actions) : actions;++ return (+ <>+ <AssetManagerThumbnail+ item={{ type: "folder", id: folder.id }}+ actions={displayedActions}+ interactions={interactions}+ selected={selected}+ forcedSelection={forcedSelection}+ thumbnailRef={(element) => {+ elementRef.current = element;+ onElementChange?.(element);+ }}+ label={folder.name}+ path={path}+ preview={<FolderIcon size={40} />}+ aria-label={`Folder ${folder.name}`}+ aria-description="Double-click to open. Drag assets or folders here to move them."+ data-is-drop-over={isDropTarget ? "true" : undefined}+ clickable+ dropTarget={isDropTarget}+ onDoubleClick={onOpen}+ onKeyDown={(event) => {+ if (event.key === "Enter") {+ event.preventDefault();+ onOpen();+ }+ }}+ header={+ canManage ? (+ <AssetManagerThumbnailMenu+ actions={displayedActions}+ label={`Actions for ${folder.name}`}+ onPointerDown={() => interactions.onContextMenuSelection(item)}+ />+ ) : undefined+ }+ />+ {canManage && (+ <AssetFolderSettingsDialog+ folder={folder}+ open={settingsOpen}+ onOpenChange={setSettingsOpen}+ initialDeleteConfirmation={deleteConfirmationOpen}+ />+ )}+ </>+ );+};++const backNavigationDelayMs = 2000;++export const BackThumbnail = ({+ onOpen,+ onElementChange,+}: {+ onOpen: () => void;+ onElementChange?: (element: HTMLElement | null) => void;+}) => {+ const elementRef = useRef<HTMLElement | null>(null);+ const timerRef = useRef<ReturnType<typeof setTimeout>>();+ const [isDragOver, setIsDragOver] = useState(false);++ useEffect(() => {+ const element = elementRef.current;+ if (element === null) {+ return;+ }+ const cancelNavigation = () => {+ clearTimeout(timerRef.current);+ timerRef.current = undefined;+ setIsDragOver(false);+ };+ const cleanup = dropTargetForElements({+ element,+ canDrop: ({ source }) => getAssetManagerDragItems(source.data).length > 0,+ onDragEnter: () => {+ clearTimeout(timerRef.current);+ setIsDragOver(true);+ timerRef.current = setTimeout(onOpen, backNavigationDelayMs);+ },+ onDragLeave: cancelNavigation,+ onDrop: cancelNavigation,+ });+ return () => {+ clearTimeout(timerRef.current);+ cleanup();+ };+ }, [onOpen]);++ return (+ <AssetThumbnailGroup>+ <AssetThumbnailCard+ ref={(element) => {+ elementRef.current = element;+ onElementChange?.(element);+ }}+ as="button"+ type="button"+ label="Back"+ preview={+ <ChevronRightIcon size={48} style={{ transform: "rotate(180deg)" }} />+ }+ clickable+ dropTarget={isDragOver}+ onClick={onOpen}+ />+ </AssetThumbnailGroup>+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.test.tsnew file mode 100644index 0000000000..e6a296f59d--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.test.ts@@ -0,0 +1,106 @@+import { describe, expect, test } from "vitest";+import { createAssetFolderHierarchy, type Asset } from "@webstudio-is/sdk";+import {+ filterAssetFolders,+ formatAssetFolderPath,+ sortAssetFolders,+} from "./asset-folder-utils";+import {+ createAssetFolderFixture,+ createAssetFoldersFixture,+} from "@webstudio-is/sdk/testing";++const folder = (+ id: string,+ parentId?: string,+ createdAt = "2026-01-01T00:00:00.000Z"+) => createAssetFolderFixture({ id, parentId, createdAt });++const asset = (id: string, folderId: string, size: number): Asset =>+ ({+ id,+ projectId: "project",+ name: `${id}.pdf`,+ type: "file",+ size,+ format: "pdf",+ createdAt: "2026-01-01T00:00:00.000Z",+ folderId,+ meta: {},+ }) as Asset;++describe("asset folder utilities", () => {+ const parent = folder("parent");+ const child = folder("child", "parent");+ const sibling = folder("sibling", undefined, "2026-02-01T00:00:00.000Z");+ const folders = createAssetFoldersFixture(parent, child, sibling);+ const hierarchy = createAssetFolderHierarchy(folders);++ test("formats a full breadcrumb path", () => {+ expect(formatAssetFolderPath(hierarchy, "child")).toBe(+ "Root / parent / child"+ );+ expect(formatAssetFolderPath(hierarchy, undefined)).toBe("Root");+ });++ test.each([+ ["name", "asc", ["parent", "sibling"]],+ ["name", "desc", ["sibling", "parent"]],+ ["createdAt", "asc", ["parent", "sibling"]],+ ["createdAt", "desc", ["sibling", "parent"]],+ ["size", "asc", ["sibling", "parent"]],+ ["size", "desc", ["parent", "sibling"]],+ ] as const)("sorts folders by %s %s", (sortBy, order, expected) => {+ const sorted = sortAssetFolders({+ folders: [parent, sibling],+ hierarchy,+ assets: [asset("nested", "child", 20), asset("direct", "sibling", 10)],+ sortState: { sortBy, order },+ });+ expect(sorted.map(({ id }) => id)).toEqual(expected);+ });++ test("searches folders throughout the current subtree", () => {+ const nestedMatch = createAssetFolderFixture({+ id: "nested-match",+ parentId: child.id,+ name: "Product photos",+ });+ const outsideMatch = createAssetFolderFixture({+ id: "outside-match",+ parentId: sibling.id,+ name: "Product exports",+ });+ const searchableFolders = createAssetFoldersFixture(+ parent,+ child,+ sibling,+ nestedMatch,+ outsideMatch+ );++ expect(+ filterAssetFolders({+ folders: searchableFolders,+ hierarchy: createAssetFolderHierarchy(searchableFolders),+ currentFolderId: parent.id,+ searchQuery: "product",+ compatibleAssets: [],+ hideEmptyFolders: false,+ }).map(({ id }) => id)+ ).toEqual([nestedMatch.id]);+ });++ test("hides constrained-picker folders without compatible descendants", () => {+ expect(+ filterAssetFolders({+ folders,+ hierarchy,+ currentFolderId: undefined,+ searchQuery: "",+ compatibleAssets: [asset("compatible", child.id, 20)],+ hideEmptyFolders: true,+ }).map(({ id }) => id)+ ).toEqual([parent.id]);+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.ts b/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.tsnew file mode 100644index 0000000000..9603baccf6--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-folder-utils.ts@@ -0,0 +1,95 @@+import {+ type Asset,+ type AssetFolder,+ type AssetFolders,+ type AssetFolderHierarchy,+} from "@webstudio-is/sdk";+import type { SortState } from "./utils";++export const sortAssetFolders = ({+ folders,+ hierarchy,+ assets,+ sortState,+}: {+ folders: AssetFolder[];+ hierarchy: AssetFolderHierarchy;+ assets: Iterable<Asset>;+ sortState: SortState;+}) => {+ const direction = sortState.order === "asc" ? 1 : -1;+ const sizes =+ sortState.sortBy === "size"+ ? hierarchy.getAggregateAssetSizes(assets)+ : new Map<string, number>();+ return [...folders].sort((left, right) => {+ let comparison = 0;+ if (sortState.sortBy === "name") {+ comparison = left.name.localeCompare(right.name);+ } else if (sortState.sortBy === "createdAt") {+ comparison =+ new Date(left.createdAt).getTime() -+ new Date(right.createdAt).getTime();+ } else {+ comparison = (sizes.get(left.id) ?? 0) - (sizes.get(right.id) ?? 0);+ }+ if (comparison === 0) {+ return left.name.localeCompare(right.name) * direction;+ }+ return comparison * direction;+ });+};++export const formatAssetFolderPath = (+ hierarchy: AssetFolderHierarchy,+ folderId: string | undefined+) => {+ const path = hierarchy.getPath(folderId);+ return path.length === 0+ ? "Root"+ : `Root / ${path.map(({ name }) => name).join(" / ")}`;+};++export const filterAssetFolders = ({+ folders,+ hierarchy,+ currentFolderId,+ searchQuery,+ compatibleAssets,+ hideEmptyFolders,+}: {+ folders: AssetFolders;+ hierarchy: AssetFolderHierarchy;+ currentFolderId: string | undefined;+ searchQuery: string;+ compatibleAssets: Iterable<Asset>;+ hideEmptyFolders: boolean;+}) => {+ const normalizedSearch = searchQuery.trim().toLocaleLowerCase();+ const candidates =+ normalizedSearch === ""+ ? hierarchy.getChildren(currentFolderId)+ : Array.from(hierarchy.getDescendantIds(currentFolderId)).flatMap(+ (folderId) => {+ const folder = folders.get(folderId);+ return folder !== undefined &&+ folder.name.toLocaleLowerCase().includes(normalizedSearch)+ ? [folder]+ : [];+ }+ );++ if (hideEmptyFolders === false) {+ return [...candidates];+ }++ const foldersWithCompatibleAssets = new Set<string>();+ for (const asset of compatibleAssets) {+ for (const folder of hierarchy.getPath(asset.folderId)) {+ foldersWithCompatibleAssets.add(folder.id);+ }+ }+ return candidates.filter((folder) =>+ foldersWithCompatibleAssets.has(folder.id)+ );+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.tsnew file mode 100644index 0000000000..30e19a2479--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.test.ts@@ -0,0 +1,86 @@+import { afterEach, expect, test } from "vitest";+import {+ $assetManagerClipboard,+ canPasteAssetManagerItem,+ copyAssetManagerItem,+ cutAssetManagerItem,+ pasteAssetManagerItem,+} from "./asset-manager-clipboard";+import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";+import { createAssetFolderFixture } from "@webstudio-is/sdk/testing";++afterEach(() => {+ $assetManagerClipboard.set(undefined);+ $assetFolders.set(new Map());+ $assets.set(new Map());+ $project.set(undefined);+});++test("tracks copy and cut operations independently from item selection", () => {+ copyAssetManagerItem({ type: "asset", id: "asset", projectId: "project" });+ expect($assetManagerClipboard.get()).toEqual({+ operation: "copy",+ items: [{ type: "asset", id: "asset", projectId: "project" }],+ projectId: "project",+ });++ cutAssetManagerItem({+ type: "folder",+ id: "folder",+ projectId: "project",+ });+ expect($assetManagerClipboard.get()).toEqual({+ operation: "cut",+ items: [{ type: "folder", id: "folder", projectId: "project" }],+ projectId: "project",+ });+});++test("does nothing when there is no clipboard item to paste", () => {+ expect(pasteAssetManagerItem(undefined)).toBeUndefined();+});++test("clears clipboard items that were deleted before pasting", () => {+ $project.set({ id: "project" } as never);+ copyAssetManagerItem({ type: "asset", id: "missing", projectId: "project" });++ expect(canPasteAssetManagerItem(undefined)).toBe(false);+ expect(pasteAssetManagerItem(undefined)).toBeUndefined();+ expect($assetManagerClipboard.get()).toBeUndefined();+});++test("does not paste into a folder that no longer exists", () => {+ const folder = createAssetFolderFixture({ id: "folder" });+ $project.set({ id: "project" } as never);+ $assetFolders.set(new Map([[folder.id, folder]]));+ copyAssetManagerItem({+ type: "folder",+ id: folder.id,+ projectId: "project",+ });++ expect(canPasteAssetManagerItem("missing")).toBe(false);+ expect(pasteAssetManagerItem("missing")).toBeUndefined();+ expect($assetManagerClipboard.get()).toBeDefined();+});++test("prevents cutting a folder into one of its descendants", () => {+ const parent = createAssetFolderFixture({ id: "parent" });+ const child = createAssetFolderFixture({ id: "child", parentId: parent.id });+ $project.set({ id: "project" } as never);+ $assetFolders.set(+ new Map([+ [parent.id, parent],+ [child.id, child],+ ])+ );+ cutAssetManagerItem({+ type: "folder",+ id: parent.id,+ projectId: "project",+ });++ expect(canPasteAssetManagerItem(child.id)).toBe(false);+ expect(pasteAssetManagerItem(child.id)).toBeUndefined();+ expect($assetManagerClipboard.get()).toBeDefined();+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.tsnew file mode 100644index 0000000000..70453d1db8--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-clipboard.ts@@ -0,0 +1,122 @@+import { atom } from "nanostores";+import { createAssetFolderHierarchy } from "@webstudio-is/sdk";+import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";+import {+ duplicateAssetManagerItems,+ moveAssetManagerItems,+ normalizeAssetManagerItems,+ type AssetManagerItem,+} from "./asset-manager-operations";++export type AssetManagerClipboardItem = {+ operation: "copy" | "cut";+ items: AssetManagerItem[];+ projectId: string;+};++export const $assetManagerClipboard = atom<+ AssetManagerClipboardItem | undefined+>(undefined);++const setAssetManagerClipboard = (+ operation: AssetManagerClipboardItem["operation"],+ itemOrItems: AssetManagerItem | readonly AssetManagerItem[]+) => {+ const items = Array.isArray(itemOrItems) ? [...itemOrItems] : [itemOrItems];+ const projectId = items[0]?.projectId;+ if (+ projectId === undefined ||+ items.some((item) => item.projectId !== projectId)+ ) {+ return;+ }+ $assetManagerClipboard.set({ operation, items, projectId });+};++export const copyAssetManagerItem = (+ itemOrItems: AssetManagerItem | readonly AssetManagerItem[]+) => setAssetManagerClipboard("copy", itemOrItems);++export const cutAssetManagerItem = (+ itemOrItems: AssetManagerItem | readonly AssetManagerItem[]+) => setAssetManagerClipboard("cut", itemOrItems);++export const duplicateAssetManagerItem = (+ itemOrItems: AssetManagerItem | readonly AssetManagerItem[],+ targetFolderId?: string | null+) => {+ const items = Array.isArray(itemOrItems) ? itemOrItems : [itemOrItems];+ return duplicateAssetManagerItems(items, targetFolderId);+};++export const createAssetManagerClipboardActions = (item: AssetManagerItem) => ({+ cut: () => cutAssetManagerItem(item),+ copy: () => copyAssetManagerItem(item),+ duplicate: () => duplicateAssetManagerItem(item),+});++const getClipboardItems = () => {+ const clipboard = $assetManagerClipboard.get();+ const projectId = $project.get()?.id;+ if (clipboard === undefined || clipboard.projectId !== projectId) {+ return;+ }+ const folders = $assetFolders.get();+ const items = normalizeAssetManagerItems({+ items: clipboard.items,+ folders,+ assets: $assets.get(),+ });+ return { clipboard, folders, items };+};++const canPasteToFolder = (+ data: NonNullable<ReturnType<typeof getClipboardItems>>,+ folderId: string | undefined+) => {+ if (+ data.items.length === 0 ||+ (folderId !== undefined && data.folders.has(folderId) === false)+ ) {+ return false;+ }+ if (data.clipboard.operation === "copy" || folderId === undefined) {+ return true;+ }+ const hierarchy = createAssetFolderHierarchy(data.folders);+ return data.items.every(+ (item) =>+ item.type === "asset" ||+ hierarchy.getSubtreeIds(item.id).has(folderId) === false+ );+};++export const canPasteAssetManagerItem = (folderId: string | undefined) => {+ const data = getClipboardItems();+ return data !== undefined && canPasteToFolder(data, folderId);+};++export const pasteAssetManagerItem = (folderId: string | undefined) => {+ const data = getClipboardItems();+ if (data === undefined) {+ const clipboard = $assetManagerClipboard.get();+ if (clipboard !== undefined && clipboard.projectId !== $project.get()?.id) {+ $assetManagerClipboard.set(undefined);+ }+ return;+ }+ if (data.items.length === 0) {+ $assetManagerClipboard.set(undefined);+ return;+ }+ if (canPasteToFolder(data, folderId) === false) {+ return;+ }+ const { clipboard, items } = data;+ if (clipboard.operation === "copy") {+ duplicateAssetManagerItems(items, folderId ?? null);+ } else {+ moveAssetManagerItems(items, folderId);+ $assetManagerClipboard.set(undefined);+ }+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.test.tsxnew file mode 100644index 0000000000..9995e8b5a1--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.test.tsx@@ -0,0 +1,44 @@+import { expect, test, vi } from "vitest";+import { renderAssetManagerDragPreview } from "./asset-manager-drag-preview";++test("renders selected thumbnails as a stacked drag preview", () => {+ const first = document.createElement("button");+ const second = document.createElement("button");+ first.setAttribute("data-asset-manager-drag-key", "asset:1");+ second.setAttribute("data-asset-manager-drag-key", "folder:2");+ first.getBoundingClientRect = vi.fn(() => ({+ width: 80,+ height: 60,+ })) as never;+ document.body.appendChild(first);+ document.body.appendChild(second);+ const container = document.createElement("div");++ expect(+ renderAssetManagerDragPreview({+ container,+ items: [+ { type: "asset", id: "1" },+ { type: "folder", id: "2" },+ ],+ })+ ).toBe(true);+ expect(container.children).toHaveLength(2);+ expect(container.style.width).toBe("86px");+ expect(container.style.height).toBe("66px");+ expect((container.lastElementChild as HTMLElement).style.top).toBe("0px");++ first.remove();+ second.remove();+});++test("keeps the native preview for a single item", () => {+ const container = document.createElement("div");+ expect(+ renderAssetManagerDragPreview({+ container,+ items: [{ type: "asset", id: "missing" }],+ })+ ).toBe(false);+ expect(container.children).toHaveLength(0);+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.tsnew file mode 100644index 0000000000..00cc85371a--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag-preview.ts@@ -0,0 +1,87 @@+import { preserveOffsetOnSource } from "@atlaskit/pragmatic-drag-and-drop/element/preserve-offset-on-source";+import { setCustomNativeDragPreview } from "@atlaskit/pragmatic-drag-and-drop/element/set-custom-native-drag-preview";+import {+ getAssetManagerSelectionKey,+ type AssetManagerSelection,+} from "./asset-manager-selection";++const previewItemLimit = 4;+const previewItemOffset = 6;+const dragItemAttribute = "data-asset-manager-drag-key";++export const getAssetManagerDragKeyProps = (item: AssetManagerSelection) => ({+ [dragItemAttribute]: getAssetManagerSelectionKey(item),+});++export const renderAssetManagerDragPreview = ({+ container,+ items,+}: {+ container: HTMLElement;+ items: readonly AssetManagerSelection[];+}) => {+ const elementsByKey = new Map(+ Array.from(+ document.querySelectorAll<HTMLElement>(`[${dragItemAttribute}]`)+ ).map((element) => [element.getAttribute(dragItemAttribute), element])+ );+ const elements = items.flatMap((item) => {+ const element = elementsByKey.get(getAssetManagerSelectionKey(item));+ return element === undefined ? [] : [element];+ });+ if (elements.length < 2) {+ return false;+ }++ const previewElements = elements.slice(0, previewItemLimit);+ const { width, height } = previewElements[0]!.getBoundingClientRect();+ const maximumOffset = previewItemOffset * (previewElements.length - 1);+ Object.assign(container.style, {+ width: `${width + maximumOffset}px`,+ height: `${height + maximumOffset}px`,+ });++ previewElements.reverse().forEach((element, reverseIndex) => {+ const index = previewElements.length - reverseIndex - 1;+ const clone = element.cloneNode(true) as HTMLElement;+ clone.removeAttribute("id");+ clone.removeAttribute("tabindex");+ clone.setAttribute("aria-hidden", "true");+ clone.inert = true;+ Object.assign(clone.style, {+ position: "absolute",+ top: `${previewItemOffset * index}px`,+ left: `${previewItemOffset * index}px`,+ width: `${width}px`,+ height: `${height}px`,+ pointerEvents: "none",+ });+ container.appendChild(clone);+ });+ return true;+};++export const setAssetManagerDragPreview = ({+ nativeSetDragImage,+ sourceElement,+ input,+ items,+}: {+ nativeSetDragImage: Parameters<+ typeof setCustomNativeDragPreview+ >[0]["nativeSetDragImage"];+ sourceElement: HTMLElement;+ input: Parameters<typeof preserveOffsetOnSource>[0]["input"];+ items: readonly AssetManagerSelection[];+}) => {+ if (items.length < 2) {+ return;+ }+ setCustomNativeDragPreview({+ nativeSetDragImage,+ getOffset: preserveOffsetOnSource({ element: sourceElement, input }),+ render: ({ container }) => {+ renderAssetManagerDragPreview({ container, items });+ },+ });+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.test.tsnew file mode 100644index 0000000000..71e3ccc71b--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.test.ts@@ -0,0 +1,23 @@+import { expect, test } from "vitest";+import { getAssetManagerDragItems } from "./asset-manager-drag";++test("reads multiselect and legacy single-item drag data", () => {+ expect(+ getAssetManagerDragItems({+ items: [+ { type: "asset", id: "asset" },+ { type: "folder", id: "folder" },+ { type: "invalid", id: "ignored" },+ ],+ })+ ).toEqual([+ { type: "asset", id: "asset" },+ { type: "folder", id: "folder" },+ ]);+ expect(getAssetManagerDragItems({ kind: "asset", id: "asset" })).toEqual([+ { type: "asset", id: "asset" },+ ]);+ expect(+ getAssetManagerDragItems({ kind: "asset-folder", id: "folder" })+ ).toEqual([{ type: "folder", id: "folder" }]);+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.tsnew file mode 100644index 0000000000..34539d3905--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-drag.ts@@ -0,0 +1,40 @@+import type { AssetManagerSelection } from "./asset-manager-selection";++type DragData = Record<string | symbol, unknown>;++const parseDragItem = (value: unknown): AssetManagerSelection | undefined => {+ if (typeof value !== "object" || value === null) {+ return;+ }+ const item = value as Record<string, unknown>;+ if (+ (item.type !== "asset" && item.type !== "folder") ||+ typeof item.id !== "string"+ ) {+ return;+ }+ return { type: item.type, id: item.id };+};++export const getAssetManagerDragItems = (+ data: DragData+): AssetManagerSelection[] => {+ if (Array.isArray(data.items)) {+ return data.items.flatMap((item) => {+ const parsed = parseDragItem(item);+ return parsed === undefined ? [] : [parsed];+ });+ }+ if (+ (data.kind === "asset" || data.kind === "asset-folder") &&+ typeof data.id === "string"+ ) {+ return [+ {+ type: data.kind === "asset" ? "asset" : "folder",+ id: data.id,+ },+ ];+ }+ return [];+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.test.tsnew file mode 100644index 0000000000..2ae33e4b7e--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.test.ts@@ -0,0 +1,82 @@+import { expect, test, vi } from "vitest";+import { getAssetManagerItemMenuItems } from "./asset-manager-item-menu";++test("uses one ordered command model for context and dropdown menus", () => {+ const action = vi.fn();+ const items = getAssetManagerItemMenuItems({+ open: action,+ settings: action,+ createFolder: action,+ upload: action,+ cut: action,+ copy: action,+ paste: action,+ duplicate: action,+ download: action,+ replace: action,+ deleteUnusedAssets: action,+ delete: action,+ });++ expect(items.map(({ name }) => name)).toEqual([+ "createFolder",+ "upload",+ "open",+ "settings",+ "cut",+ "copy",+ "paste",+ "duplicate",+ "download",+ "replace",+ "deleteUnusedAssets",+ "delete",+ ]);+ expect(items.find(({ name }) => name === "delete")).toMatchObject({+ destructive: true,+ separatorBefore: true,+ });+ expect(items.find(({ name }) => name === "deleteUnusedAssets")).toMatchObject(+ { separatorBefore: true }+ );+ expect(+ Object.fromEntries(+ items+ .filter(({ shortcut }) => shortcut !== undefined)+ .map(({ name, shortcut }) => [name, shortcut])+ )+ ).toEqual({+ cut: ["meta", "x"],+ copy: ["meta", "c"],+ paste: ["meta", "v"],+ duplicate: ["meta", "d"],+ delete: ["backspace"],+ });+});++test("orders panel actions independently of unavailable item actions", () => {+ const action = vi.fn();+ const items = getAssetManagerItemMenuItems({+ createFolder: action,+ upload: action,+ paste: action,+ deleteUnusedAssets: action,+ });++ expect(items.map(({ name }) => name)).toEqual([+ "createFolder",+ "upload",+ "paste",+ "deleteUnusedAssets",+ ]);+});++test("keeps unavailable panel actions visible but disabled", () => {+ const action = vi.fn();+ const items = getAssetManagerItemMenuItems(+ { paste: action },+ { disabledActions: new Set(["paste"]) }+ );++ expect(items).toMatchObject([{ name: "paste", disabled: true }]);+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsxnew file mode 100644index 0000000000..4c80e004d1--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-item-menu.tsx@@ -0,0 +1,179 @@+import { Fragment } from "react";+import {+ ContextMenuContent,+ ContextMenuItem,+ ContextMenuItemRightSlot,+ ContextMenuSeparator,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuItemRightSlot,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+ Kbd,+ SmallIconButton,+ theme,+} from "@webstudio-is/design-system";+import { EllipsesIcon } from "@webstudio-is/icons";++export type AssetManagerItemActions = Partial<+ Record<+ | "open"+ | "settings"+ | "cut"+ | "copy"+ | "paste"+ | "duplicate"+ | "download"+ | "replace"+ | "createFolder"+ | "upload"+ | "deleteUnusedAssets"+ | "delete",+ () => void+ >+>;+export type AssetManagerItemActionName = keyof AssetManagerItemActions;++type ItemDefinition = {+ name: keyof AssetManagerItemActions;+ label: string;+ shortcut?: readonly string[];+ separatorBefore?: boolean;+ destructive?: boolean;+};++const itemDefinitions: readonly ItemDefinition[] = [+ { name: "createFolder", label: "Create folder" },+ { name: "upload", label: "Upload asset" },+ { name: "open", label: "Open" },+ { name: "settings", label: "Settings" },+ {+ name: "cut",+ label: "Cut",+ shortcut: ["meta", "x"],+ separatorBefore: true,+ },+ { name: "copy", label: "Copy", shortcut: ["meta", "c"] },+ { name: "paste", label: "Paste", shortcut: ["meta", "v"] },+ { name: "duplicate", label: "Duplicate", shortcut: ["meta", "d"] },+ { name: "download", label: "Download", separatorBefore: true },+ { name: "replace", label: "Replace file" },+ {+ name: "deleteUnusedAssets",+ label: "Delete unused assets",+ separatorBefore: true,+ },+ {+ name: "delete",+ label: "Delete",+ shortcut: ["backspace"],+ separatorBefore: true,+ destructive: true,+ },+] as const;++const menuContentStyle = { minWidth: 120 };+const shortcutStyle = { paddingLeft: theme.spacing[5] };++export const getAssetManagerItemMenuItems = (+ actions: AssetManagerItemActions,+ {+ disabledActions,+ }: {+ disabledActions?: ReadonlySet<AssetManagerItemActionName>;+ } = {}+) =>+ itemDefinitions.flatMap((definition) =>+ actions[definition.name] === undefined+ ? []+ : [+ {+ ...definition,+ action: actions[definition.name],+ disabled: disabledActions?.has(definition.name) ?? false,+ },+ ]+ );++const AssetManagerItemMenuItems = ({+ actions,+ disabledActions,+ variant,+}: {+ actions: AssetManagerItemActions;+ disabledActions?: ReadonlySet<AssetManagerItemActionName>;+ variant: "context" | "dropdown";+}) => {+ const Item = variant === "context" ? ContextMenuItem : DropdownMenuItem;+ const ItemRightSlot =+ variant === "context"+ ? ContextMenuItemRightSlot+ : DropdownMenuItemRightSlot;+ const Separator =+ variant === "context" ? ContextMenuSeparator : DropdownMenuSeparator;+ return getAssetManagerItemMenuItems(actions, {+ disabledActions,+ }).map((item, index) => (+ <Fragment key={item.name}>+ {item.separatorBefore && index > 0 && <Separator />}+ <Item+ disabled={item.disabled}+ destructive={item.destructive}+ onSelect={item.action}+ >+ {item.label}+ {item.shortcut !== undefined && (+ <ItemRightSlot css={shortcutStyle}>+ <Kbd value={item.shortcut} />+ </ItemRightSlot>+ )}+ </Item>+ </Fragment>+ ));+};++export const AssetManagerItemContextMenuContent = ({+ actions,+ disabledActions,+}: {+ actions: AssetManagerItemActions;+ disabledActions?: ReadonlySet<AssetManagerItemActionName>;+}) => (+ <ContextMenuContent css={menuContentStyle}>+ <AssetManagerItemMenuItems+ actions={actions}+ disabledActions={disabledActions}+ variant="context"+ />+ </ContextMenuContent>+);++export const AssetManagerItemActionsDropdown = ({+ actions,+ disabledActions,+ triggerLabel = "Actions",+ triggerTabIndex,+}: {+ actions: AssetManagerItemActions;+ disabledActions?: ReadonlySet<AssetManagerItemActionName>;+ triggerLabel?: string;+ triggerTabIndex?: number;+}) => (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <SmallIconButton+ aria-label={triggerLabel}+ tabIndex={triggerTabIndex}+ icon={<EllipsesIcon />}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" css={menuContentStyle}>+ <AssetManagerItemMenuItems+ actions={actions}+ disabledActions={disabledActions}+ variant="dropdown"+ />+ </DropdownMenuContent>+ </DropdownMenu>+);diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-marquee.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-marquee.tsnew file mode 100644index 0000000000..3a53073738--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-marquee.ts@@ -0,0 +1,156 @@+import {+ createAssetManagerSelectionRect,+ doAssetManagerSelectionRectsIntersect,+ getAssetManagerSelectionKey,+ type AssetManagerSelection,+} from "./asset-manager-selection";++export type AssetManagerMarqueeRect = {+ left: number;+ top: number;+ width: number;+ height: number;+};++const activationDistance = 4;+const scrollEdge = 24;+const scrollStep = 12;++export const startAssetManagerMarquee = ({+ pointerId,+ start,+ panel,+ listbox,+ items,+ initialSelection,+ getItemElement,+ onSelectionChange,+ onRectChange,+ onFinish,+ onCancel,+}: {+ pointerId: number;+ start: { x: number; y: number };+ panel: HTMLElement;+ listbox: HTMLElement;+ items: readonly AssetManagerSelection[];+ initialSelection: readonly AssetManagerSelection[];+ getItemElement: (item: AssetManagerSelection) => HTMLElement | undefined;+ onSelectionChange: (items: AssetManagerSelection[]) => void;+ onRectChange: (rect: AssetManagerMarqueeRect | undefined) => void;+ onFinish: (items: AssetManagerSelection[], active: boolean) => void;+ onCancel: () => void;+}) => {+ let latestSelection = [...initialSelection];+ let active = false;+ let disposed = false;+ const previousUserSelect = document.documentElement.style.userSelect;+ const scrollViewport = listbox.closest<HTMLElement>(+ "[data-radix-scroll-area-viewport]"+ );+ const getBounds = () =>+ scrollViewport?.getBoundingClientRect() ?? panel.getBoundingClientRect();++ const cleanup = () => {+ if (disposed) {+ return;+ }+ disposed = true;+ document.removeEventListener("pointermove", handlePointerMove);+ document.removeEventListener("pointerup", handlePointerUp);+ document.removeEventListener("pointercancel", handlePointerCancel);+ document.documentElement.style.userSelect = previousUserSelect;+ onRectChange(undefined);+ };++ const handlePointerMove = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) {+ return;+ }+ const distance = Math.hypot(+ event.clientX - start.x,+ event.clientY - start.y+ );+ if (active === false && distance < activationDistance) {+ return;+ }+ if (active === false) {+ active = true;+ document.documentElement.style.userSelect = "none";+ }+ event.preventDefault();++ const bounds = getBounds();+ if (+ scrollViewport !== null &&+ typeof scrollViewport.scrollBy === "function"+ ) {+ const scrollTop =+ event.clientY < bounds.top + scrollEdge+ ? -scrollStep+ : event.clientY > bounds.bottom - scrollEdge+ ? scrollStep+ : 0;+ if (scrollTop !== 0) {+ scrollViewport.scrollBy({ top: scrollTop });+ }+ }++ const end = {+ x: Math.min(Math.max(event.clientX, bounds.left), bounds.right),+ y: Math.min(Math.max(event.clientY, bounds.top), bounds.bottom),+ };+ const selectionRect = createAssetManagerSelectionRect(start, end);+ const intersectingItems = items.filter((item) => {+ const element = getItemElement(item);+ return (+ element !== undefined &&+ doAssetManagerSelectionRectsIntersect(+ selectionRect,+ element.getBoundingClientRect()+ )+ );+ });+ const selectedKeys = new Set(+ initialSelection.map(getAssetManagerSelectionKey)+ );+ latestSelection = [+ ...initialSelection,+ ...intersectingItems.filter(+ (item) => selectedKeys.has(getAssetManagerSelectionKey(item)) === false+ ),+ ];+ onSelectionChange(latestSelection);++ const panelRect = panel.getBoundingClientRect();+ onRectChange({+ left: selectionRect.left - panelRect.left,+ top: selectionRect.top - panelRect.top,+ width: selectionRect.right - selectionRect.left,+ height: selectionRect.bottom - selectionRect.top,+ });+ };++ const handlePointerUp = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) {+ return;+ }+ cleanup();+ onFinish(latestSelection, active);+ };++ const handlePointerCancel = (event: PointerEvent) => {+ if (event.pointerId !== pointerId) {+ return;+ }+ cleanup();+ onCancel();+ };++ document.addEventListener("pointermove", handlePointerMove, {+ passive: false,+ });+ document.addEventListener("pointerup", handlePointerUp);+ document.addEventListener("pointercancel", handlePointerCancel);+ return cleanup;+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.test.tsnew file mode 100644index 0000000000..abec6029b3--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.test.ts@@ -0,0 +1,211 @@+import { beforeEach, describe, expect, test } from "vitest";+import type { Asset } from "@webstudio-is/sdk";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ $assetFolders,+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $projectSettings,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+} from "~/shared/sync/data-stores";+import {+ $authPermit,+ $builderMode,+ $selectedPageId,+} from "~/shared/nano-states";+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";+import {+ createAssetFoldersFixture,+ createAssetFolderFixture,+} from "@webstudio-is/sdk/testing";+import {+ deleteAssetManagerItems,+ duplicateAssetManagerItems,+ moveAssetManagerItems,+ normalizeAssetManagerItems,+} from "./asset-manager-operations";++const createAsset = (id: string, folderId?: string): Asset => ({+ id,+ projectId: "project",+ name: `${id}.png`,+ format: "png",+ size: 1,+ type: "image",+ meta: { width: 1, height: 1 },+ createdAt: "2026-01-01T00:00:00.000Z",+ folderId,+});++test("normalizes bulk operations to independent roots", () => {+ const parent = createAssetFolderFixture({ id: "parent" });+ const child = createAssetFolderFixture({ id: "child", parentId: parent.id });+ const sibling = createAssetFolderFixture({ id: "sibling" });+ const nestedAsset = createAsset("nested-asset", child.id);+ const rootAsset = createAsset("root-asset");++ expect(+ normalizeAssetManagerItems({+ items: [+ { type: "folder", id: child.id },+ { type: "asset", id: nestedAsset.id },+ { type: "folder", id: parent.id },+ { type: "folder", id: sibling.id },+ { type: "asset", id: rootAsset.id },+ { type: "asset", id: rootAsset.id },+ ],+ folders: createAssetFoldersFixture(parent, child, sibling),+ assets: new Map([+ [nestedAsset.id, nestedAsset],+ [rootAsset.id, rootAsset],+ ]),+ })+ ).toEqual([+ { type: "folder", id: parent.id },+ { type: "folder", id: sibling.id },+ { type: "asset", id: rootAsset.id },+ ]);+});++test("removes items that no longer exist", () => {+ expect(+ normalizeAssetManagerItems({+ items: [+ { type: "folder", id: "missing-folder" },+ { type: "asset", id: "missing-asset" },+ ],+ folders: new Map(),+ assets: new Map(),+ })+ ).toEqual([]);+});++registerContainers();++describe("Asset Manager bulk mutations", () => {+ beforeEach(() => {+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];+ serverSyncStore.popAll();+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $builderMode.set("design");+ $authPermit.set("build");+ $instances.set(+ new Map([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: "Body",+ children: [],+ },+ ],+ ])+ );+ $props.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ $assetFolders.set(new Map());+ $assets.set(new Map());+ });++ test("moves mixed items as one undoable and redoable transaction", () => {+ const source = createAssetFolderFixture({ id: "source" });+ const target = createAssetFolderFixture({ id: "target" });+ const asset = createAsset("asset");+ $assetFolders.set(createAssetFoldersFixture(source, target));+ $assets.set(new Map([[asset.id, asset]]));++ moveAssetManagerItems(+ [+ { type: "folder", id: source.id },+ { type: "asset", id: asset.id },+ ],+ target.id+ );++ expect($assetFolders.get().get(source.id)?.parentId).toBe(target.id);+ expect($assets.get().get(asset.id)?.folderId).toBe(target.id);++ serverSyncStore.undo();+ expect($assetFolders.get().get(source.id)?.parentId).toBeUndefined();+ expect($assets.get().get(asset.id)?.folderId).toBeUndefined();++ serverSyncStore.redo();+ expect($assetFolders.get().get(source.id)?.parentId).toBe(target.id);+ expect($assets.get().get(asset.id)?.folderId).toBe(target.id);+ });++ test("duplicates mixed items as one undoable transaction", () => {+ const source = createAssetFolderFixture({ id: "source" });+ const target = createAssetFolderFixture({ id: "target" });+ const asset = createAsset("asset");+ $assetFolders.set(createAssetFoldersFixture(source, target));+ $assets.set(new Map([[asset.id, asset]]));++ duplicateAssetManagerItems(+ [+ { type: "folder", id: source.id },+ { type: "asset", id: asset.id },+ ],+ target.id+ );++ expect($assetFolders.get()).toHaveLength(3);+ expect($assets.get()).toHaveLength(2);+ serverSyncStore.undo();+ expect($assetFolders.get()).toEqual(+ createAssetFoldersFixture(source, target)+ );+ expect($assets.get()).toEqual(new Map([[asset.id, asset]]));+ });++ test("deletes mixed items as one undoable transaction", () => {+ const folder = createAssetFolderFixture({ id: "folder" });+ const asset = createAsset("asset");+ $assetFolders.set(createAssetFoldersFixture(folder));+ $assets.set(new Map([[asset.id, asset]]));++ deleteAssetManagerItems([+ { type: "folder", id: folder.id },+ { type: "asset", id: asset.id },+ ]);++ expect($assetFolders.get()).toEqual(new Map());+ expect($assets.get()).toEqual(new Map());+ serverSyncStore.undo();+ expect($assetFolders.get()).toEqual(createAssetFoldersFixture(folder));+ expect($assets.get()).toEqual(new Map([[asset.id, asset]]));+ });++ test("rejects a bulk move that would create a folder cycle", () => {+ const parent = createAssetFolderFixture({ id: "parent" });+ const child = createAssetFolderFixture({+ id: "child",+ parentId: parent.id,+ });+ $assetFolders.set(createAssetFoldersFixture(parent, child));++ expect(() =>+ moveAssetManagerItems([{ type: "folder", id: parent.id }], child.id)+ ).toThrow();+ expect($assetFolders.get()).toEqual(+ createAssetFoldersFixture(parent, child)+ );+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.tsnew file mode 100644index 0000000000..2bf0d03180--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-operations.ts@@ -0,0 +1,148 @@+import {+ createAssetFolderHierarchy,+ type Asset,+ type AssetFolder,+} from "@webstudio-is/sdk";+import {+ executeRuntimeMutationSequence,+ type RuntimeMutationOperation,+} from "~/shared/instance-utils/data";+import { onNextTransactionComplete } from "~/shared/sync/project-queue";+import { invalidateAssets } from "~/shared/resources";+import {+ getAssetManagerSelectionKey,+ type AssetManagerSelection,+} from "./asset-manager-selection";++export type AssetManagerItem = AssetManagerSelection & { projectId: string };++export const normalizeAssetManagerItems = ({+ items,+ folders,+ assets,+}: {+ items: readonly AssetManagerSelection[];+ folders: ReadonlyMap<string, AssetFolder>;+ assets: ReadonlyMap<string, Asset>;+}): AssetManagerSelection[] => {+ const uniqueItems = Array.from(+ new Map(+ items.map((item) => [getAssetManagerSelectionKey(item), item])+ ).values()+ ).filter((item) =>+ item.type === "folder" ? folders.has(item.id) : assets.has(item.id)+ );+ const selectedFolderIds = new Set(+ uniqueItems.flatMap((item) => (item.type === "folder" ? [item.id] : []))+ );+ const hierarchy = createAssetFolderHierarchy(new Map(folders));+ const rootFolderIds = new Set(+ Array.from(selectedFolderIds).filter((folderId) =>+ hierarchy+ .getPath(folderId)+ .slice(0, -1)+ .every((ancestor) => selectedFolderIds.has(ancestor.id) === false)+ )+ );+ const coveredFolderIds = new Set(+ Array.from(rootFolderIds).flatMap((folderId) =>+ Array.from(hierarchy.getSubtreeIds(folderId))+ )+ );+ return uniqueItems.filter((item) => {+ if (item.type === "folder") {+ return rootFolderIds.has(item.id);+ }+ const asset = assets.get(item.id)!;+ return (+ asset.folderId === undefined ||+ coveredFolderIds.has(asset.folderId) === false+ );+ });+};++const getOperations = ({+ items,+ folderId,+ operation,+}: {+ items: readonly AssetManagerSelection[];+ folderId?: string | null;+ operation: "duplicate" | "move";+}): RuntimeMutationOperation[] =>+ items.map((item) => {+ if (operation === "duplicate") {+ return item.type === "asset"+ ? {+ id: "assets.duplicate" as const,+ input: {+ assetId: item.id,+ ...(folderId === undefined ? {} : { folderId }),+ },+ }+ : {+ id: "assetFolders.duplicate" as const,+ input: {+ folderId: item.id,+ ...(folderId === undefined ? {} : { parentId: folderId }),+ },+ };+ }+ return item.type === "asset"+ ? {+ id: "assets.update" as const,+ input: { assetId: item.id, values: { folderId: folderId ?? null } },+ }+ : {+ id: "assetFolders.update" as const,+ input: { folderId: item.id, values: { parentId: folderId ?? null } },+ };+ });++export const duplicateAssetManagerItems = (+ items: readonly AssetManagerSelection[],+ targetFolderId?: string | null+) =>+ executeRuntimeMutationSequence(+ getOperations({ items, folderId: targetFolderId, operation: "duplicate" })+ );++export const moveAssetManagerItems = (+ items: readonly AssetManagerSelection[],+ targetFolderId: string | undefined+) =>+ executeRuntimeMutationSequence(+ getOperations({ items, folderId: targetFolderId, operation: "move" })+ );++export const deleteAssetManagerItems = (+ items: readonly AssetManagerSelection[]+) => {+ const assetIds = items.flatMap((item) =>+ item.type === "asset" ? [item.id] : []+ );+ const operations: RuntimeMutationOperation[] = [+ ...(assetIds.length === 0+ ? []+ : [+ {+ id: "assets.delete" as const,+ input: { assetIdsOrPrefixes: assetIds, force: true },+ },+ ]),+ ...items.flatMap((item) =>+ item.type === "folder"+ ? [+ {+ id: "assetFolders.delete" as const,+ input: { folderId: item.id },+ },+ ]+ : []+ ),+ ];+ executeRuntimeMutationSequence(operations);+ if (assetIds.length > 0 || items.some((item) => item.type === "folder")) {+ onNextTransactionComplete(invalidateAssets);+ }+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.test.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.test.tsnew file mode 100644index 0000000000..ab3b19daf4--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.test.ts@@ -0,0 +1,99 @@+import { describe, expect, test } from "vitest";+import {+ addAssetManagerSelection,+ createAssetManagerSelectionRect,+ doAssetManagerSelectionRectsIntersect,+ getAdjacentAssetManagerSelection,+ getAssetManagerSelectionRange,+ includesAssetManagerSelection,+ toggleAssetManagerSelection,+ type AssetManagerSelection,+} from "./asset-manager-selection";++const items: AssetManagerSelection[] = [+ { type: "folder", id: "folder-1" },+ { type: "folder", id: "folder-2" },+ { type: "asset", id: "asset-1" },+ { type: "asset", id: "asset-2" },+];++describe("Asset Manager multiselect", () => {+ test("normalizes marquee coordinates and detects intersecting thumbnails", () => {+ const selectionRect = createAssetManagerSelectionRect(+ { x: 100, y: 80 },+ { x: 20, y: 10 }+ );+ expect(selectionRect).toEqual({+ left: 20,+ top: 10,+ right: 100,+ bottom: 80,+ });+ expect(+ doAssetManagerSelectionRectsIntersect(selectionRect, {+ left: 90,+ top: 70,+ right: 120,+ bottom: 100,+ })+ ).toBe(true);+ expect(+ doAssetManagerSelectionRectsIntersect(selectionRect, {+ left: 101,+ top: 10,+ right: 120,+ bottom: 30,+ })+ ).toBe(false);+ });++ test("builds forward and backward ranges in displayed order", () => {+ expect(getAssetManagerSelectionRange(items, items[0]!, items[2]!)).toEqual(+ items.slice(0, 3)+ );+ expect(getAssetManagerSelectionRange(items, items[3]!, items[1]!)).toEqual(+ items.slice(1, 4)+ );+ });++ test("falls back to the target when the anchor is no longer visible", () => {+ expect(+ getAssetManagerSelectionRange(+ items,+ { type: "folder", id: "missing" },+ items[2]!+ )+ ).toEqual([items[2]]);+ });++ test("toggles non-contiguous items without duplicating identities", () => {+ const selected = [items[0]!, items[2]!];+ expect(toggleAssetManagerSelection(selected, items[2]!)).toEqual([+ items[0],+ ]);+ expect(toggleAssetManagerSelection(selected, items[3]!)).toEqual([+ items[0],+ items[2],+ items[3],+ ]);+ expect(addAssetManagerSelection(selected, items[2]!)).toEqual(selected);+ expect(includesAssetManagerSelection(selected, items[2]!)).toBe(true);+ });++ test("finds adjacent items without wrapping at collection boundaries", () => {+ expect(+ getAdjacentAssetManagerSelection({+ items,+ current: items[1]!,+ direction: "previous",+ })+ ).toEqual(items[0]);+ expect(+ getAdjacentAssetManagerSelection({+ items,+ current: items[3]!,+ direction: "next",+ })+ ).toBeUndefined();+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.ts b/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.tsnew file mode 100644index 0000000000..15d52a98b5--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-selection.ts@@ -0,0 +1,104 @@+export type AssetManagerSelection =+ | { type: "asset"; id: string }+ | { type: "folder"; id: string };++export type AssetManagerSelectionRect = {+ left: number;+ top: number;+ right: number;+ bottom: number;+};++export const createAssetManagerSelectionRect = (+ start: { x: number; y: number },+ end: { x: number; y: number }+): AssetManagerSelectionRect => ({+ left: Math.min(start.x, end.x),+ top: Math.min(start.y, end.y),+ right: Math.max(start.x, end.x),+ bottom: Math.max(start.y, end.y),+});++export const doAssetManagerSelectionRectsIntersect = (+ left: AssetManagerSelectionRect,+ right: AssetManagerSelectionRect+) =>+ left.left <= right.right &&+ left.right >= right.left &&+ left.top <= right.bottom &&+ left.bottom >= right.top;++export const getAssetManagerSelectionKey = (+ item: AssetManagerSelection+): string => `${item.type}:${item.id}`;++export const isSameAssetManagerSelection = (+ left: AssetManagerSelection | undefined,+ right: AssetManagerSelection | undefined+) =>+ left !== undefined &&+ right !== undefined &&+ left.type === right.type &&+ left.id === right.id;++export const includesAssetManagerSelection = (+ selection: readonly AssetManagerSelection[],+ item: AssetManagerSelection+) => selection.some((selected) => isSameAssetManagerSelection(selected, item));++export const getAssetManagerSelectionRange = (+ items: readonly AssetManagerSelection[],+ anchor: AssetManagerSelection,+ target: AssetManagerSelection+): AssetManagerSelection[] => {+ const anchorIndex = items.findIndex((item) =>+ isSameAssetManagerSelection(item, anchor)+ );+ const targetIndex = items.findIndex((item) =>+ isSameAssetManagerSelection(item, target)+ );+ if (anchorIndex === -1 || targetIndex === -1) {+ return [target];+ }+ const start = Math.min(anchorIndex, targetIndex);+ const end = Math.max(anchorIndex, targetIndex);+ return items.slice(start, end + 1);+};++export const toggleAssetManagerSelection = (+ selection: readonly AssetManagerSelection[],+ item: AssetManagerSelection+): AssetManagerSelection[] =>+ includesAssetManagerSelection(selection, item)+ ? selection.filter(+ (selected) => isSameAssetManagerSelection(selected, item) === false+ )+ : [...selection, item];++export const addAssetManagerSelection = (+ selection: readonly AssetManagerSelection[],+ item: AssetManagerSelection+): AssetManagerSelection[] =>+ includesAssetManagerSelection(selection, item)+ ? [...selection]+ : [...selection, item];++export const getAdjacentAssetManagerSelection = ({+ items,+ current,+ direction,+}: {+ items: readonly AssetManagerSelection[];+ current: AssetManagerSelection;+ direction: "previous" | "next";+}): AssetManagerSelection | undefined => {+ const currentIndex = items.findIndex((item) =>+ isSameAssetManagerSelection(item, current)+ );+ if (currentIndex === -1) {+ return;+ }+ const nextIndex =+ direction === "previous" ? currentIndex - 1 : currentIndex + 1;+ return items[nextIndex];+};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsxnew file mode 100644index 0000000000..ddb3a7a659--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager-thumbnail.tsx@@ -0,0 +1,152 @@+import {+ forwardRef,+ type ComponentProps,+ type KeyboardEvent,+ type MouseEvent,+ type PointerEvent,+ type ReactNode,+ type Ref,+} from "react";+import { getAssetManagerDragKeyProps } from "./asset-manager-drag-preview";+import {+ AssetThumbnailCard,+ AssetThumbnailGroup,+ AssetThumbnailHeader,+ AssetThumbnailMenu,+} from "./asset-thumbnail-card";+import {+ AssetManagerItemActionsDropdown,+ type AssetManagerItemActions,+} from "./asset-manager-item-menu";+import type { AssetManagerSelection } from "./asset-manager-selection";++export type AssetManagerThumbnailInteractions = {+ onSelectionChange: (item: AssetManagerSelection, selected: boolean) => void;+ onItemPointerDown: (+ item: AssetManagerSelection,+ event: PointerEvent<HTMLElement>+ ) => void;+ onItemClick: (+ item: AssetManagerSelection,+ event: MouseEvent<HTMLElement>+ ) => void;+ onModifiedArrow: (+ item: AssetManagerSelection,+ event: KeyboardEvent<HTMLElement>+ ) => void;+ onExitMultiselect?: () => void;+ onContextMenuSelection: (item: AssetManagerSelection) => void;+ onContextMenuActions: (actions: AssetManagerItemActions) => void;+ getDragItems: (item: AssetManagerSelection) => AssetManagerSelection[];+};++type AssetManagerThumbnailProps = Omit<+ ComponentProps<typeof AssetThumbnailCard>,+ "aria-pressed" | "as" | "onContextMenu" | "ref" | "selected" | "type"+> & {+ actions: AssetManagerItemActions;+ interactions: AssetManagerThumbnailInteractions;+ item: AssetManagerSelection;+ header?: ReactNode;+ selected?: boolean;+ forcedSelection?: boolean;+ thumbnailRef?: Ref<HTMLElement>;+};++export const AssetManagerThumbnail = ({+ actions,+ interactions,+ item,+ header,+ selected,+ forcedSelection = false,+ thumbnailRef,+ ...cardProps+}: AssetManagerThumbnailProps) => {+ const { onClick, onKeyDown, onPointerDown, ...restCardProps } = cardProps;+ return (+ <AssetThumbnailGroup+ data-asset-manager-thumbnail=""+ role="option"+ aria-selected={forcedSelection ? selected : undefined}+ selected={selected}+ onFocusChange={(selected) =>+ interactions.onSelectionChange(item, selected)+ }+ onContextMenu={(event) => {+ interactions.onContextMenuSelection(item);+ interactions.onContextMenuActions(actions);+ event.currentTarget+ .querySelector<HTMLElement>("[data-asset-manager-thumbnail-button]")+ ?.focus();+ }}+ >+ <AssetThumbnailCard+ {...restCardProps}+ {...getAssetManagerDragKeyProps(item)}+ data-asset-manager-thumbnail-button=""+ ref={thumbnailRef}+ as="button"+ type="button"+ selected={selected}+ onPointerDown={(event) => {+ onPointerDown?.(event);+ if (event.defaultPrevented === false) {+ interactions.onItemPointerDown(item, event);+ }+ }}+ onClick={(event) => {+ onClick?.(event);+ if (event.defaultPrevented === false) {+ interactions.onItemClick(item, event);+ }+ }}+ onKeyDown={(event) => {+ if (+ (event.shiftKey || event.metaKey || event.ctrlKey) &&+ ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(+ event.key+ )+ ) {+ interactions.onModifiedArrow(item, event);+ } else if (+ event.key === "Escape" &&+ interactions.onExitMultiselect !== undefined+ ) {+ event.preventDefault();+ event.stopPropagation();+ interactions.onExitMultiselect();+ }+ if (event.defaultPrevented === false) {+ onKeyDown?.(event);+ }+ }}+ />+ {header !== undefined && (+ <AssetThumbnailHeader data-asset-thumbnail-header="">+ {header}+ </AssetThumbnailHeader>+ )}+ </AssetThumbnailGroup>+ );+};++type AssetManagerThumbnailMenuProps = {+ actions: AssetManagerItemActions;+ label: string;+ onPointerDown?: () => void;+};++export const AssetManagerThumbnailMenu = forwardRef<+ HTMLDivElement,+ AssetManagerThumbnailMenuProps+>(({ actions, label, onPointerDown }, ref) => (+ <AssetThumbnailMenu ref={ref} onPointerDown={onPointerDown}>+ <AssetManagerItemActionsDropdown+ actions={actions}+ triggerLabel={label}+ triggerTabIndex={-1}+ />+ </AssetThumbnailMenu>+));+AssetManagerThumbnailMenu.displayName = "AssetManagerThumbnailMenu";diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsxnew file mode 100644index 0000000000..b386e40d89--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.test.tsx@@ -0,0 +1,773 @@+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import type { Asset } from "@webstudio-is/sdk";+import { createDefaultPages } from "@webstudio-is/project-build";+import {+ $assetFolders,+ $assets,+ $breakpoints,+ $dataSources,+ $instances,+ $pages,+ $project,+ $projectSettings,+ $props,+ $resources,+ $styleSourceSelections,+ $styleSources,+ $styles,+} from "~/shared/sync/data-stores";+import {+ $authPermit,+ $builderMode,+ $selectedPageId,+} from "~/shared/nano-states";+import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";+import { AssetManager } from "./asset-manager";+import { $assetManagerClipboard } from "./asset-manager-clipboard";+import {+ createAssetFolderFixture,+ createAssetFoldersFixture,+} from "@webstudio-is/sdk/testing";+import { createAssetManagerTestRenderer } from "./test-utils";++const renderer = createAssetManagerTestRenderer();+registerContainers();++beforeEach(() => {+ vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+ );+ Element.prototype.scrollIntoView = vi.fn();+ vi.stubGlobal("requestAnimationFrame", (callback: FrameRequestCallback) => {+ callback(0);+ return 0;+ });+ vi.stubGlobal(+ "DOMRect",+ class {+ static fromRect(rect: Partial<DOMRect> = {}) {+ const x = rect.x ?? 0;+ const y = rect.y ?? 0;+ const width = rect.width ?? 0;+ const height = rect.height ?? 0;+ return {+ x,+ y,+ width,+ height,+ top: y,+ right: x + width,+ bottom: y + height,+ left: x,+ toJSON: () => ({}),+ };+ }+ }+ );+ $assets.set(new Map());+ $assetManagerClipboard.set(undefined);+ $authPermit.set("build");+ serverSyncStore.transactionManager.currentStack = [];+ serverSyncStore.transactionManager.undoneStack = [];+ serverSyncStore.popAll();+ const pages = createDefaultPages({ rootInstanceId: "body" });+ $pages.set(pages);+ $selectedPageId.set(pages.homePageId);+ $builderMode.set("design");+ $instances.set(+ new Map([+ [+ "body",+ {+ type: "instance" as const,+ id: "body",+ component: "Body",+ children: [],+ },+ ],+ ])+ );+ $props.set(new Map());+ $breakpoints.set(new Map());+ $styleSourceSelections.set(new Map());+ $styleSources.set(new Map());+ $styles.set(new Map());+ $dataSources.set(new Map());+ $resources.set(new Map());+ $projectSettings.set({ meta: {}, compiler: {} });+ $project.set({ id: "project" } as never);+ $assetFolders.set(+ createAssetFoldersFixture(+ createAssetFolderFixture({ id: "alpha", name: "Alpha" }),+ createAssetFolderFixture({ id: "bravo", name: "Bravo" }),+ createAssetFolderFixture({ id: "charlie", name: "Charlie" })+ )+ );+});++afterEach(() => {+ renderer.cleanup();+ $assetFolders.set(new Map());+ $assets.set(new Map());+ $assetManagerClipboard.set(undefined);+ $project.set(undefined);+ vi.unstubAllGlobals();+});++const renderManager = (canManageFolders = true) =>+ renderer.render(+ <TooltipProvider>+ <AssetManager canManageFolders={canManageFolders} />+ </TooltipProvider>+ );++const getOptions = (container: HTMLElement) =>+ Array.from(container.querySelectorAll<HTMLElement>('[role="option"]')).map(+ (option) => ({+ option,+ button: option.querySelector<HTMLButtonElement>("button")!,+ })+ );++const pointerDown = (+ element: HTMLElement,+ modifiers: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {}+) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("pointerdown", {+ bubbles: true,+ button: 0,+ ...modifiers,+ })+ );+ element.focus();+ });+};++const keyDown = (+ element: HTMLElement,+ key: string,+ modifiers: { shiftKey?: boolean; metaKey?: boolean; ctrlKey?: boolean } = {}+) => {+ act(() => {+ element.dispatchEvent(+ new KeyboardEvent("keydown", {+ key,+ bubbles: true,+ cancelable: true,+ ...modifiers,+ })+ );+ });+};++const openContextMenu = (element: HTMLElement) => {+ act(() => {+ element.dispatchEvent(+ new MouseEvent("contextmenu", {+ bubbles: true,+ button: 2,+ cancelable: true,+ })+ );+ });+};++const dismissContextMenu = () => {+ act(() => {+ document.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "Escape",+ bubbles: true,+ cancelable: true,+ })+ );+ });+};++const selectContextMenuItem = (+ element: HTMLElement,+ label: "Copy" | "Cut" | "Duplicate" | "Delete"+) => {+ openContextMenu(element);+ const item = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((candidate) => candidate.textContent?.startsWith(label));+ expect(item).toBeDefined();+ act(() => item?.click());+};++const createAsset = (id: string): Asset => ({+ id,+ projectId: "project",+ name: `${id}.png`,+ format: "png",+ size: 1,+ type: "image",+ meta: { width: 1, height: 1 },+ createdAt: "2026-01-01T00:00:00.000Z",+});++describe("Asset Manager multiselect interactions", () => {+ test("marquee-selects every thumbnail intersecting the pointer rectangle", () => {+ const container = renderManager();+ const options = getOptions(container);+ const listbox = container.querySelector<HTMLElement>('[role="listbox"]')!;+ const viewport = listbox.closest<HTMLElement>(+ "[data-radix-scroll-area-viewport]"+ )!;+ viewport.getBoundingClientRect = () =>+ ({+ left: 0,+ top: 0,+ right: 300,+ bottom: 300,+ width: 300,+ height: 300,+ x: 0,+ y: 0,+ toJSON: () => ({}),+ }) as DOMRect;+ options.forEach(({ button }, index) => {+ const left = 20 + index * 60;+ button.getBoundingClientRect = () =>+ ({+ left,+ top: 20,+ right: left + 50,+ bottom: 70,+ width: 50,+ height: 50,+ x: left,+ y: 20,+ toJSON: () => ({}),+ }) as DOMRect;+ });++ act(() => {+ viewport.dispatchEvent(+ new MouseEvent("pointerdown", {+ bubbles: true,+ button: 0,+ clientX: 10,+ clientY: 10,+ })+ );+ document.dispatchEvent(+ new MouseEvent("pointermove", {+ bubbles: true,+ clientX: 125,+ clientY: 80,+ })+ );+ });++ expect(container.querySelector("[data-asset-manager-marquee]")).not.toBe(+ null+ );+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true", "false"]);++ act(() => {+ document.dispatchEvent(+ new MouseEvent("pointerup", {+ bubbles: true,+ clientX: 125,+ clientY: 80,+ })+ );+ });+ expect(container.querySelector("[data-asset-manager-marquee]")).toBe(null);+ expect(document.activeElement).toBe(options[0]!.button);+ });++ test("keeps single selection focus-based until Shift + Click", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ expect(+ options.every(+ ({ option }) => option.hasAttribute("aria-selected") === false+ )+ ).toBe(true);++ pointerDown(options[2]!.button, { shiftKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true", "true"]);++ pointerDown(options[1]!.button);+ act(() => options[1]?.button.click());+ expect(+ options.every(+ ({ option }) => option.hasAttribute("aria-selected") === false+ )+ ).toBe(true);+ expect(document.activeElement).toBe(options[1]!.button);+ });++ test("exits multiselect when clicking outside thumbnails", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[2]!.button, { shiftKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true", "true"]);++ pointerDown(container.querySelector<HTMLInputElement>("input")!);+ expect(+ options.every(+ ({ option }) => option.hasAttribute("aria-selected") === false+ )+ ).toBe(true);+ });++ test("keeps multiselect during pointer down so selected items can be dragged", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[2]!.button, { metaKey: true });++ act(() => {+ options[2]?.button.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "false", "true"]);++ act(() => options[2]?.button.click());+ expect(+ options.every(+ ({ option }) => option.hasAttribute("aria-selected") === false+ )+ ).toBe(true);+ });++ test.each([{ metaKey: true }, { ctrlKey: true }])(+ "initializes a non-contiguous selection with Cmd/Ctrl + Click",+ (modifier) => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());++ pointerDown(options[2]!.button, modifier);+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "false", "true"]);+ }+ );++ test.each([{ shiftKey: true }, { metaKey: true }, { ctrlKey: true }])(+ "initializes selection with a modifier + Arrow",+ (modifier) => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ act(() => {+ options[0]?.button.dispatchEvent(+ new KeyboardEvent("keydown", {+ key: "ArrowRight",+ bubbles: true,+ ...modifier,+ })+ );+ });++ expect(+ options+ .slice(0, 2)+ .map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true"]);+ expect(document.activeElement).toBe(options[1]!.button);++ act(() => {+ options[1]?.button.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Escape", bubbles: true })+ );+ });+ expect(+ options.every(+ ({ option }) => option.hasAttribute("aria-selected") === false+ )+ ).toBe(true);+ }+ );++ test("preserves the range anchor while Shift + Arrow extends and contracts", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());++ keyDown(options[0]!.button, "ArrowRight", { shiftKey: true });+ keyDown(options[1]!.button, "ArrowRight", { shiftKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true", "true"]);++ keyDown(options[2]!.button, "ArrowLeft", { shiftKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "true", "false"]);+ expect(document.activeElement).toBe(options[1]!.button);+ });++ test("toggles individual items without changing the original anchor", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());++ pointerDown(options[2]!.button, { metaKey: true });+ pointerDown(options[0]!.button, { metaKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["false", "false", "true"]);++ pointerDown(options[1]!.button, { ctrlKey: true });+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["false", "true", "true"]);+ });++ test("selects mixed items and applies a bulk action to the complete selection", () => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[3]!.button, { ctrlKey: true });++ expect(+ container+ .querySelector('[role="listbox"]')+ ?.getAttribute("aria-multiselectable")+ ).toBe("true");+ expect(+ options.map(({ option }) => option.getAttribute("aria-selected"))+ ).toEqual(["true", "false", "false", "true"]);+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "2 items selected."+ );++ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ '[aria-label="Actions for asset.png"]'+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const copyItem = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith("Copy"));+ act(() => copyItem?.click());++ expect($assetManagerClipboard.get()).toEqual({+ operation: "copy",+ items: [+ { type: "folder", id: "charlie", projectId: "project" },+ { type: "asset", id: "asset", projectId: "project" },+ ],+ projectId: "project",+ });+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "2 items copied."+ );+ });++ test("clears forced selection and restores focus when results disappear", () => {+ const container = renderManager();+ let options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[2]!.button, { metaKey: true });++ act(() => {+ $assetFolders.set(+ createAssetFoldersFixture(+ createAssetFolderFixture({ id: "bravo", name: "Bravo" })+ )+ );+ });+ options = getOptions(container);+ expect(options).toHaveLength(1);+ expect(options[0]?.option.hasAttribute("aria-selected")).toBe(false);+ expect(document.activeElement).toBe(options[0]!.button);+ });++ test("preserves bulk actions while interacting with a portaled menu", () => {+ const container = renderManager();+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[2]!.button, { metaKey: true });++ act(() => {+ container+ .querySelector<HTMLButtonElement>('[aria-label="Actions for Alpha"]')+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const deleteItem = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).find((item) => item.textContent?.startsWith("Delete"));+ expect(deleteItem).toBeDefined();+ act(() => {+ deleteItem?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ deleteItem?.click();+ });+ expect(document.body.textContent).toContain("Delete selected items");+ });++ test.each(["Copy", "Cut"] as const)(+ "%s from the context menu targets the complete multiselection",+ (action) => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const options = getOptions(container);+ openContextMenu(options[0]!.button);+ dismissContextMenu();+ act(() => options[0]?.button.focus());+ pointerDown(options.at(-1)!.button, { ctrlKey: true });++ selectContextMenuItem(options[0]!.button, action);++ const selectedFolderId = options[0]!.button+ .getAttribute("aria-label")+ ?.replace("Folder ", "")+ .toLowerCase();+ expect($assetManagerClipboard.get()).toEqual({+ operation: action.toLowerCase(),+ items: [+ { type: "folder", id: selectedFolderId, projectId: "project" },+ { type: "asset", id: "asset", projectId: "project" },+ ],+ projectId: "project",+ });+ }+ );++ test("Duplicate from the context menu targets the complete multiselection", () => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const options = getOptions(container);+ openContextMenu(options[0]!.button);+ dismissContextMenu();+ act(() => options[0]?.button.focus());+ pointerDown(options.at(-1)!.button, { ctrlKey: true });++ selectContextMenuItem(options[0]!.button, "Duplicate");++ expect($assetFolders.get()).toHaveLength(4);+ expect($assets.get()).toHaveLength(2);+ });++ test("Delete from the context menu targets the complete multiselection", () => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const options = getOptions(container);+ openContextMenu(options[0]!.button);+ dismissContextMenu();+ act(() => options[0]?.button.focus());+ pointerDown(options.at(-1)!.button, { ctrlKey: true });++ selectContextMenuItem(options[0]!.button, "Delete");++ expect(document.body.textContent).toContain("Delete 2 selected items?");+ });++ test("thumbnail context requests replace the panel actions", () => {+ const upload = vi.fn();+ const container = renderer.render(+ <TooltipProvider>+ <AssetManager canManageFolders panelActions={{ upload }} />+ </TooltipProvider>+ );+ const options = getOptions(container);+ act(() => options[0]?.button.focus());+ pointerDown(options[2]!.button, { ctrlKey: true });++ act(() => {+ options[0]!.option.dispatchEvent(+ new MouseEvent("contextmenu", {+ bubbles: true,+ button: 2,+ cancelable: true,+ })+ );+ });++ const labels = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ ).map((item) => item.textContent);+ expect(labels.some((label) => label?.startsWith("Copy"))).toBe(true);+ expect(labels).not.toContain("Upload asset");+ });+});++describe("Asset Manager shortcuts", () => {+ test("prevents handled shortcuts from reaching global builder commands", () => {+ const container = renderManager();+ const button = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ const globalHandler = vi.fn();+ document.addEventListener("keydown", globalHandler);+ act(() => button.focus());+ const event = new KeyboardEvent("keydown", {+ key: "c",+ metaKey: true,+ bubbles: true,+ cancelable: true,+ });++ act(() => button.dispatchEvent(event));+ document.removeEventListener("keydown", globalHandler);++ expect(event.defaultPrevented).toBe(true);+ expect(globalHandler).not.toHaveBeenCalled();+ });++ test.each([+ {+ label: "Folder Alpha",+ item: { type: "folder" as const, id: "alpha" },+ },+ {+ label: "asset.png",+ item: { type: "asset" as const, id: "asset" },+ },+ ])("copies and cuts the focused $item.type", ({ label, item }) => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const button =+ item.type === "folder"+ ? container.querySelector<HTMLButtonElement>(`[aria-label="${label}"]`)!+ : getOptions(container).at(-1)!.button;+ act(() => button.focus());++ keyDown(button, "c", { metaKey: true });+ expect($assetManagerClipboard.get()).toEqual({+ operation: "copy",+ items: [{ ...item, projectId: "project" }],+ projectId: "project",+ });++ keyDown(button, "x", { ctrlKey: true });+ expect($assetManagerClipboard.get()).toEqual({+ operation: "cut",+ items: [{ ...item, projectId: "project" }],+ projectId: "project",+ });+ });++ test("applies copy and duplicate shortcuts to the complete multiselection", () => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const folderButton = container.querySelector<HTMLButtonElement>(+ '[aria-label="Folder Alpha"]'+ )!;+ const assetButton = getOptions(container).at(-1)!.button;+ act(() => folderButton.focus());+ pointerDown(assetButton, { ctrlKey: true });++ keyDown(assetButton, "c", { metaKey: true });+ expect($assetManagerClipboard.get()?.items).toEqual([+ { type: "folder", id: "alpha", projectId: "project" },+ { type: "asset", id: "asset", projectId: "project" },+ ]);++ keyDown(assetButton, "d", { ctrlKey: true });+ expect($assetFolders.get()).toHaveLength(4);+ expect($assets.get()).toHaveLength(2);+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "2 items duplicated."+ );+ });++ test("pastes into the open folder with Cmd/Ctrl + V", () => {+ const asset = createAsset("asset");+ act(() => {+ $assets.set(new Map([[asset.id, asset]]));+ $assetManagerClipboard.set({+ operation: "copy",+ items: [{ type: "asset", id: asset.id, projectId: "project" }],+ projectId: "project",+ });+ });+ const container = renderManager();+ const button = getOptions(container).at(-1)!.button;+ act(() => button.focus());++ keyDown(button, "v", { metaKey: true });++ expect($assets.get()).toHaveLength(2);+ expect(container.querySelector('[role="status"]')?.textContent).toBe(+ "1 item pasted into Root."+ );+ });++ test.each(["Backspace", "Delete"])(+ "%s opens confirmation for the focused item",+ (key) => {+ const asset = createAsset("asset");+ act(() => $assets.set(new Map([[asset.id, asset]])));+ const container = renderManager();+ const button = getOptions(container).at(-1)!.button;+ act(() => button.focus());++ keyDown(button, key);++ expect(document.body.textContent).toContain("Delete 1 selected item?");+ expect(document.activeElement?.textContent).toBe("Delete");+ expect($assets.get()).toHaveLength(1);+ }+ );++ test("does not expose the delete shortcut in view mode", () => {+ const asset = createAsset("asset");+ act(() => {+ $assets.set(new Map([[asset.id, asset]]));+ $authPermit.set("view");+ });+ const container = renderManager(false);+ const button = getOptions(container).at(-1)!.button;+ act(() => button.focus());++ keyDown(button, "Delete");++ expect(document.body.textContent).not.toContain("Delete selected items");+ expect($assets.get()).toHaveLength(1);+ });++ test("leaves native editing shortcuts available in the search field", () => {+ const container = renderManager();+ const search = container.querySelector<HTMLInputElement>("input")!;+ act(() => search.focus());++ keyDown(search, "c", { metaKey: true });+ keyDown(search, "x", { ctrlKey: true });+ keyDown(search, "Backspace");++ expect($assetManagerClipboard.get()).toBeUndefined();+ expect(document.body.textContent).not.toContain("Delete selected items");+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsxindex 0e2a113b6b..3a615ad656 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-manager.tsx@@ -1,50 +1,212 @@-import { useState, useMemo } from "react";import {+ useCallback,+ useEffect,+ useLayoutEffect,+ useRef,+ useState,+ useMemo,+ type ComponentProps,+ type KeyboardEvent,+ type MouseEvent,+ type PointerEvent as ReactPointerEvent,+ type ReactNode,+} from "react";+import { flushSync } from "react-dom";+import { useStore } from "@nanostores/react";+import {+ Box,+ Button,+ Dialog,+ DialogContent,+ DialogTitle,Flex,Grid,+ Text,findNextListItemIndex,theme,useSearchFieldKeys,} from "@webstudio-is/design-system";-import type { Asset, AllowedFileExtension } from "@webstudio-is/sdk";+import { TrashIcon } from "@webstudio-is/icons";+import { dropTargetForElements } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";import {acceptToMimePatterns,+ createAssetFolderHierarchy,doesAssetMatchMimePatterns,+ type Asset,+ type AllowedFileExtension,} from "@webstudio-is/sdk";-import { AssetsShell, type AssetContainer, useAssets } from "../assets";+import { AssetsShell, useAssets } from "../assets";import { AssetThumbnail } from "./asset-thumbnail";+import { BackThumbnail, FolderThumbnail } from "./asset-folder-thumbnail";import { AssetFilters } from "./asset-filters";import { AssetSortSelect } from "./asset-sort";+import { $assetFolders, $project } from "~/shared/sync/data-stores";+import { AssetFolderBreadcrumbs } from "./asset-folder-breadcrumbs";+import {+ filterAssetFolders,+ formatAssetFolderPath,+ sortAssetFolders,+} from "./asset-folder-utils";import {getInitialExtensions,calculateFormatCounts,filterAndSortAssets,- findAssetIndex,+ getAssetManagerSelectionIndex,+ getNearestAssetManagerSelection,+ isAssetManagerSelectionVisible,+ type AssetManagerSelection,type SortState,} from "./utils";+import {+ $assetManagerClipboard,+ canPasteAssetManagerItem,+ copyAssetManagerItem,+ cutAssetManagerItem,+ duplicateAssetManagerItem,+ pasteAssetManagerItem,+} from "./asset-manager-clipboard";+import {+ AssetManagerItemContextMenuContent,+ type AssetManagerItemActions,+} from "./asset-manager-item-menu";+import {+ addAssetManagerSelection,+ getAdjacentAssetManagerSelection,+ getAssetManagerSelectionKey,+ getAssetManagerSelectionRange,+ includesAssetManagerSelection,+ isSameAssetManagerSelection,+ toggleAssetManagerSelection,+} from "./asset-manager-selection";+import {+ startAssetManagerMarquee,+ type AssetManagerMarqueeRect,+} from "./asset-manager-marquee";+import {+ deleteAssetManagerItems,+ moveAssetManagerItems,+ normalizeAssetManagerItems,+ type AssetManagerItem,+} from "./asset-manager-operations";+import { getAssetManagerDragItems } from "./asset-manager-drag";+import type { AssetManagerThumbnailInteractions } from "./asset-manager-thumbnail";+import { $authPermit } from "~/shared/nano-states";++type FolderNavigationProps =+ | { folderId?: never; onFolderChange?: never }+ | {+ folderId: string | undefined;+ onFolderChange: (folderId: string | undefined) => void;+ };-type AssetManagerProps = {+type AssetManagerProps = FolderNavigationProps & {onChange?: (assetId: Asset["id"]) => void;- /** acceptable file types in the `<imput accept>` attribute format */+ /** acceptable file types in the `<input accept>` attribute format */accept?: string;+ canManageFolders?: boolean;+ panelActions?: Partial<+ Pick<+ AssetManagerItemActions,+ "createFolder" | "upload" | "deleteUnusedAssets"+ >+ >;};-export const AssetManager = ({ accept = "*", onChange }: AssetManagerProps) => {+const AssetGrid = ({+ children,+ ...props+}: { children: ReactNode } & Omit<ComponentProps<typeof Grid>, "children">) => (+ <Grid+ {...props}+ columns={3}+ gap="2"+ css={{+ minHeight: "100%",+ alignContent: "start",+ paddingInline: theme.panel.paddingInline,+ }}+ >+ {children}+ </Grid>+);++export const AssetManager = ({+ accept = "*",+ onChange,+ folderId,+ onFolderChange,+ canManageFolders = false,+ panelActions,+}: AssetManagerProps) => {const { assetContainers } = useAssets();+ const folders = useStore($assetFolders);+ const project = useStore($project);+ const authPermit = useStore($authPermit);+ const clipboard = useStore($assetManagerClipboard);+ const folderHierarchy = useMemo(+ () => createAssetFolderHierarchy(folders),+ [folders]+ );+ const mimePatterns = useMemo(() => acceptToMimePatterns(accept), [accept]);+ const [internalFolderId, setInternalFolderId] = useState(folderId);+ const [selection, setSelection] = useState<AssetManagerSelection>();+ const [forcedSelection, setForcedSelection] =+ useState<AssetManagerSelection[]>();+ const [selectionAnchor, setSelectionAnchor] =+ useState<AssetManagerSelection>();+ const [pendingDeleteItems, setPendingDeleteItems] =+ useState<AssetManagerSelection[]>();+ const [announcement, setAnnouncement] = useState("");+ const [marqueeRect, setMarqueeRect] = useState<AssetManagerMarqueeRect>();+ const [itemContextMenu, setItemContextMenu] = useState<{+ actions?: AssetManagerItemActions;+ instance: number;+ }>({ instance: 0 });+ const itemElements = useRef(new Map<string, HTMLElement>());+ const panelElement = useRef<HTMLDivElement | null>(null);+ const backElement = useRef<HTMLElement | null>(null);+ const cleanupMarquee = useRef<() => void>();+ const pendingFocus = useRef<"back" | AssetManagerSelection>();+ const currentFolderId =+ onFolderChange === undefined ? internalFolderId : folderId;+ const setCurrentFolderId = useCallback(+ (nextFolderId: string | undefined) => {+ if (onFolderChange === undefined) {+ setInternalFolderId(nextFolderId);+ } else {+ onFolderChange(nextFolderId);+ }+ setSelection(undefined);+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setAnnouncement(+ nextFolderId === undefined+ ? "Opened Root."+ : `Opened folder ${folders.get(nextFolderId)?.name ?? "folder"}.`+ );+ },+ [folders, onFolderChange]+ );++ useEffect(() => {+ if (+ currentFolderId !== undefined &&+ folders.has(currentFolderId) === false+ ) {+ setCurrentFolderId(undefined);+ }+ }, [currentFolderId, folders, setCurrentFolderId]);// Only show assets that match the accept constraint so incompatible types// (e.g. video files) can never be selected from an image picker.const compatibleContainers = useMemo(() => {- const patterns = acceptToMimePatterns(accept);- if (patterns === "*") {+ if (mimePatterns === "*") {return assetContainers;}return assetContainers.filter((container) =>- doesAssetMatchMimePatterns(container.asset, patterns)+ doesAssetMatchMimePatterns(container.asset, mimePatterns));- }, [accept, assetContainers]);-- const [selectedIndex, setSelectedIndex] = useState(-1);+ }, [assetContainers, mimePatterns]);const [selectedExtensions, setSelectedExtensions] = useState<AllowedFileExtension[] | "*"@@ -62,8 +224,20 @@ export const AssetManager = ({ accept = "*", onChange }: AssetManagerProps) => {const searchProps = useSearchFieldKeys({onMove({ direction }) {+ const selectedIndex = getAssetManagerSelectionIndex(+ navigableItems,+ selection+ );if (direction === "current") {- const assetContainer = filteredItems[selectedIndex];+ const selectedItem = navigableItems[selectedIndex];+ if (selectedItem?.type === "folder") {+ pendingFocus.current = "back";+ setCurrentFolderId(selectedItem.id);+ return;+ }+ const assetContainer = filteredItems.find(+ ({ asset }) => asset.id === selectedItem?.id+ );if (assetContainer?.status === "uploaded") {onChange?.(assetContainer.asset.id);}@@ -71,64 +245,821 @@ export const AssetManager = ({ accept = "*", onChange }: AssetManagerProps) => {}const nextIndex = findNextListItemIndex(selectedIndex,- filteredItems.length,+ navigableItems.length,direction);- setSelectedIndex(nextIndex);+ setSelection(navigableItems[nextIndex]);+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);},});+ const searchQuery = searchProps.value.trim();+ const isSearching = searchQuery.length > 0;++ const filteredItems = useMemo(() => {+ const descendantIds = folderHierarchy.getDescendantIds(currentFolderId);+ const scopedContainers = compatibleContainers.filter(({ asset }) => {+ const folderId = folderHierarchy.resolveFolderId(asset.folderId);+ if (isSearching) {+ return (+ currentFolderId === undefined ||+ folderId === currentFolderId ||+ (folderId !== undefined && descendantIds.has(folderId))+ );+ }+ return folderId === currentFolderId;+ });+ return filterAndSortAssets({+ assetContainers: scopedContainers,+ selectedExtensions,+ searchQuery,+ sortState,+ });+ }, [+ compatibleContainers,+ currentFolderId,+ folderHierarchy,+ selectedExtensions,+ isSearching,+ searchQuery,+ sortState,+ ]);++ const uploadedCompatibleAssets = useMemo(+ () =>+ compatibleContainers.flatMap((container) =>+ container.status === "uploaded" ? [container.asset] : []+ ),+ [compatibleContainers]+ );++ const visibleFolders = useMemo(() => {+ const matchingFolders = filterAssetFolders({+ folders,+ hierarchy: folderHierarchy,+ currentFolderId,+ searchQuery,+ compatibleAssets: uploadedCompatibleAssets,+ hideEmptyFolders: mimePatterns !== "*",+ });+ return sortAssetFolders({+ folders: matchingFolders,+ hierarchy: folderHierarchy,+ assets: uploadedCompatibleAssets,+ sortState,+ });+ }, [+ currentFolderId,+ folders,+ folderHierarchy,+ mimePatterns,+ searchQuery,+ sortState,+ uploadedCompatibleAssets,+ ]);++ const navigableItems: AssetManagerSelection[] = useMemo(+ () => [+ ...visibleFolders.map(({ id }) => ({ type: "folder" as const, id })),+ ...filteredItems.map(({ asset }) => ({+ type: "asset" as const,+ id: asset.id,+ })),+ ],+ [filteredItems, visibleFolders]+ );++ const previousNavigableItems = useRef(navigableItems);+ useLayoutEffect(() => {+ if (+ forcedSelection?.some(+ (item) =>+ isAssetManagerSelectionVisible(+ item,+ filteredItems,+ visibleFolders+ ) === false+ )+ ) {+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ }+ if (+ isAssetManagerSelectionVisible(+ selection,+ filteredItems,+ visibleFolders+ ) === false+ ) {+ const nextSelection = getNearestAssetManagerSelection(+ previousNavigableItems.current,+ navigableItems,+ selection+ );+ setSelection(nextSelection);+ if (nextSelection !== undefined) {+ window.requestAnimationFrame(() => {+ if (document.activeElement === document.body) {+ itemElements.current+ .get(`${nextSelection.type}:${nextSelection.id}`)+ ?.focus();+ }+ });+ }+ }+ previousNavigableItems.current = navigableItems;+ }, [+ filteredItems,+ forcedSelection,+ navigableItems,+ selection,+ visibleFolders,+ ]);++ useLayoutEffect(() => {+ const target = pendingFocus.current;+ pendingFocus.current = undefined;+ if (target === "back") {+ backElement.current?.focus();+ } else if (target !== undefined) {+ itemElements.current.get(`${target.type}:${target.id}`)?.focus();+ }+ }, [currentFolderId]);++ const registerItemElement = (+ item: AssetManagerSelection,+ element: HTMLElement | null+ ) => {+ const key = `${item.type}:${item.id}`;+ if (element === null) {+ itemElements.current.delete(key);+ } else {+ itemElements.current.set(key, element);+ }+ };++ const openFolder = (folderId: string) => {+ pendingFocus.current = "back";+ setCurrentFolderId(folderId);+ };++ const handleFocusChange = (item: AssetManagerSelection, focused: boolean) => {+ if (focused) {+ setSelection(item);+ } else if (+ forcedSelection === undefined &&+ isSameAssetManagerSelection(selection, item)+ ) {+ setSelection(undefined);+ }+ };++ const announceSelection = (items: readonly AssetManagerSelection[]) =>+ setAnnouncement(+ `${items.length} ${items.length === 1 ? "item" : "items"} selected.`+ );++ const exitMultiselect = () => {+ if (forcedSelection === undefined) {+ return;+ }+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setAnnouncement("Multiselect ended.");+ };++ const handleItemPointerDown = (+ item: AssetManagerSelection,+ event: ReactPointerEvent<HTMLElement>+ ) => {+ if (canManageFolders === false || event.button !== 0) {+ return;+ }+ const hasToggleModifier = event.metaKey || event.ctrlKey;+ if (event.shiftKey === false && hasToggleModifier === false) {+ if (+ forcedSelection !== undefined &&+ includesAssetManagerSelection(forcedSelection, item)+ ) {+ return;+ }+ exitMultiselect();+ setSelection(item);+ return;+ }+ const anchor = selectionAnchor ?? selection;+ if (+ anchor === undefined ||+ (forcedSelection === undefined &&+ isSameAssetManagerSelection(anchor, item))+ ) {+ return;+ }+ const nextSelection = event.shiftKey+ ? getAssetManagerSelectionRange(navigableItems, anchor, item)+ : toggleAssetManagerSelection(forcedSelection ?? [anchor], item);+ setForcedSelection(nextSelection);+ setSelectionAnchor(anchor);+ announceSelection(nextSelection);+ };++ const handleItemClick = (+ item: AssetManagerSelection,+ event: MouseEvent<HTMLElement>+ ) => {+ if (+ forcedSelection === undefined ||+ event.shiftKey ||+ event.metaKey ||+ event.ctrlKey ||+ includesAssetManagerSelection(forcedSelection, item) === false+ ) {+ return;+ }+ exitMultiselect();+ setSelection(item);+ };++ const handleModifiedArrow = (+ item: AssetManagerSelection,+ event: KeyboardEvent<HTMLElement>+ ) => {+ if (canManageFolders === false) {+ return;+ }+ const nextItem = getAdjacentAssetManagerSelection({+ items: navigableItems,+ current: item,+ direction:+ event.key === "ArrowLeft" || event.key === "ArrowUp"+ ? "previous"+ : "next",+ });+ if (nextItem === undefined) {+ return;+ }+ event.preventDefault();+ const anchor = selectionAnchor ?? item;+ const nextSelection = event.shiftKey+ ? getAssetManagerSelectionRange(navigableItems, anchor, nextItem)+ : addAssetManagerSelection(forcedSelection ?? [item], nextItem);+ setForcedSelection(nextSelection);+ setSelectionAnchor(anchor);+ setSelection(nextItem);+ announceSelection(nextSelection);+ itemElements.current.get(`${nextItem.type}:${nextItem.id}`)?.focus();+ };- const filteredItems = useMemo(+ const handleContextMenuSelection = (item: AssetManagerSelection) => {+ if (+ forcedSelection !== undefined &&+ includesAssetManagerSelection(forcedSelection, item)+ ) {+ return;+ }+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setSelection(item);+ };++ const isItemSelected = (item: AssetManagerSelection) =>+ forcedSelection === undefined+ ? isSameAssetManagerSelection(selection, item)+ : includesAssetManagerSelection(forcedSelection, item);++ const getFolderName = useCallback(+ (folderId: string | undefined) =>+ folderId === undefined+ ? "Root"+ : (folders.get(folderId)?.name ?? "folder"),+ [folders]+ );++ const assetsById = useMemo(() =>- filterAndSortAssets({- assetContainers: compatibleContainers,- selectedExtensions,- searchQuery: searchProps.value,- sortState,+ new Map(+ assetContainers.flatMap((container) =>+ container.status === "uploaded"+ ? [[container.asset.id, container.asset] as const]+ : []+ )+ ),+ [assetContainers]+ );++ const normalizeItems = useCallback(+ (items: readonly AssetManagerSelection[]) =>+ normalizeAssetManagerItems({+ items,+ folders,+ assets: assetsById,}),- [compatibleContainers, selectedExtensions, searchProps.value, sortState]+ [assetsById, folders]+ );++ const normalizedSelection = useMemo(+ () =>+ normalizeItems(+ forcedSelection ?? (selection === undefined ? [] : [selection])+ ),+ [forcedSelection, normalizeItems, selection]+ );+ const normalizedForcedSelection =+ forcedSelection === undefined ? [] : normalizedSelection;+ const normalizedShortcutSelection = normalizedSelection.filter(+ (item) => item.type === "asset" || canManageFolders+ );+ const shortcutItems =+ project === undefined || authPermit === "view"+ ? []+ : normalizedShortcutSelection.map((item) => ({+ ...item,+ projectId: project.id,+ }));+ const getItemCountLabel = (items: readonly AssetManagerSelection[]) =>+ `${items.length} ${items.length === 1 ? "item" : "items"}`;+ const copyItems = (items: readonly AssetManagerItem[]) => {+ copyAssetManagerItem(items);+ setAnnouncement(`${getItemCountLabel(items)} copied.`);+ };+ const cutItems = (items: readonly AssetManagerItem[]) => {+ cutAssetManagerItem(items);+ setAnnouncement(`${getItemCountLabel(items)} cut.`);+ };+ const duplicateItems = (items: readonly AssetManagerItem[]) => {+ duplicateAssetManagerItem(items);+ setAnnouncement(`${getItemCountLabel(items)} duplicated.`);+ };+ const selectedProjectItems =+ project === undefined+ ? []+ : normalizedForcedSelection.map((item) => ({+ ...item,+ projectId: project.id,+ }));+ const selectionActions: AssetManagerItemActions =+ selectedProjectItems.length === 0+ ? {}+ : {+ cut: () => cutItems(selectedProjectItems),+ copy: () => copyItems(selectedProjectItems),+ duplicate: () => duplicateItems(selectedProjectItems),+ delete: () => setPendingDeleteItems(normalizedForcedSelection),+ };++ const moveItems = useCallback(+ (items: readonly AssetManagerSelection[], parentId: string | undefined) => {+ const normalizedItems = normalizeItems(items);+ moveAssetManagerItems(normalizedItems, parentId);+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setAnnouncement(+ `${normalizedItems.length} items moved to ${getFolderName(parentId)}.`+ );+ },+ [getFolderName, normalizeItems]+ );+ const canMoveItems = useCallback(+ (items: readonly AssetManagerSelection[], folderId: string) =>+ items.every(+ (item) =>+ item.type === "asset" ||+ folderHierarchy.getSubtreeIds(item.id).has(folderId) === false+ ),+ [folderHierarchy]+ );++ useEffect(() => {+ const element = panelElement.current;+ if (element === null || canManageFolders === false) {+ return;+ }+ return dropTargetForElements({+ element,+ canDrop: ({ source }) => {+ const items = getAssetManagerDragItems(source.data);+ return (+ items.length > 0 &&+ items.every(+ (item) =>+ item.type === "asset" ||+ currentFolderId === undefined ||+ folderHierarchy.getSubtreeIds(item.id).has(currentFolderId) ===+ false+ )+ );+ },+ onDrop: ({ source, location }) => {+ if (location.current.dropTargets[0]?.element !== element) {+ return;+ }+ const items = getAssetManagerDragItems(source.data);+ if (items.length > 0) {+ moveItems(items, currentFolderId);+ }+ },+ });+ }, [canManageFolders, currentFolderId, folderHierarchy, moveItems]);++ const getDragItems = useCallback(+ (item: AssetManagerSelection) =>+ forcedSelection !== undefined &&+ includesAssetManagerSelection(forcedSelection, item)+ ? forcedSelection+ : [item],+ [forcedSelection]);- const handleSelect = (assetContainer?: AssetContainer) => {- setSelectedIndex(findAssetIndex(filteredItems, assetContainer?.asset.id));+ const backCard =+ currentFolderId === undefined ? undefined : (+ <BackThumbnail+ onElementChange={(element) => {+ backElement.current = element;+ }}+ onOpen={() => {+ pendingFocus.current = { type: "folder", id: currentFolderId };+ setCurrentFolderId(folders.get(currentFolderId)?.parentId);+ }}+ />+ );++ const panelContextMenuActions: AssetManagerItemActions = {+ ...panelActions,+ ...(canManageFolders+ ? { paste: () => pasteAssetManagerItem(currentFolderId) }+ : {}),+ };+ const disabledPanelActions = new Set<keyof AssetManagerItemActions>();+ if (+ clipboard === undefined ||+ clipboard.projectId !== project?.id ||+ canPasteAssetManagerItem(currentFolderId) === false+ ) {+ disabledPanelActions.add("paste");+ }+ const canPaste =+ canManageFolders && canPasteAssetManagerItem(currentFolderId);+ const handleShortcut = (event: KeyboardEvent<HTMLElement>) => {+ if (panelElement.current?.contains(event.target as Node) === false) {+ return;+ }+ const target = event.target;+ if (+ target instanceof HTMLElement &&+ (target.matches("input, textarea, select") ||+ target.isContentEditable ||+ target.closest("[contenteditable]") !== null)+ ) {+ return;+ }+ const key = event.key.toLowerCase();+ const hasCommandModifier = event.metaKey || event.ctrlKey;+ const isItemCommand =+ hasCommandModifier &&+ event.altKey === false &&+ event.shiftKey === false &&+ ["c", "x", "v", "d"].includes(key);+ const isDeleteCommand =+ hasCommandModifier === false &&+ event.altKey === false &&+ event.shiftKey === false &&+ ["backspace", "delete"].includes(key);+ if (isItemCommand === false && isDeleteCommand === false) {+ return;+ }+ event.preventDefault();+ event.stopPropagation();++ if (key === "c" && shortcutItems.length > 0) {+ copyItems(shortcutItems);+ } else if (key === "x" && shortcutItems.length > 0) {+ cutItems(shortcutItems);+ } else if (key === "d" && shortcutItems.length > 0) {+ duplicateItems(shortcutItems);+ } else if (key === "v" && canPaste) {+ const pastedItemCount = clipboard?.items.length ?? 0;+ pasteAssetManagerItem(currentFolderId);+ setAnnouncement(+ `${pastedItemCount} ${+ pastedItemCount === 1 ? "item" : "items"+ } pasted into ${getFolderName(currentFolderId)}.`+ );+ } else if (isDeleteCommand && shortcutItems.length > 0) {+ setPendingDeleteItems(normalizedShortcutSelection);+ }+ };+ const hasPanelContextMenuActions = Object.values(+ panelContextMenuActions+ ).some((action) => action !== undefined);+ const showItemContextMenu = (actions: AssetManagerItemActions) => {+ flushSync(() => {+ setItemContextMenu(({ instance }) => ({+ actions,+ instance: instance + 1,+ }));+ });+ };+ const thumbnailInteractions: AssetManagerThumbnailInteractions = {+ onSelectionChange: handleFocusChange,+ onItemPointerDown: handleItemPointerDown,+ onItemClick: handleItemClick,+ onModifiedArrow: handleModifiedArrow,+ onExitMultiselect:+ forcedSelection === undefined ? undefined : exitMultiselect,+ onContextMenuSelection: handleContextMenuSelection,+ onContextMenuActions: showItemContextMenu,+ getDragItems,+ };++ useEffect(() => () => cleanupMarquee.current?.(), []);++ const handlePanelPointerDown = (+ event: ReactPointerEvent<HTMLElement>,+ listViewport: HTMLElement | null+ ) => {+ if (+ canManageFolders === false ||+ event.button !== 0 ||+ event.pointerType === "touch" ||+ event.target instanceof Element === false ||+ event.target.closest("[data-asset-manager-thumbnail]") !== null+ ) {+ return;+ }++ if (listViewport?.contains(event.target) !== true) {+ setSelection(undefined);+ exitMultiselect();+ return;+ }++ const listbox = listViewport.querySelector<HTMLElement>('[role="listbox"]');+ if (listbox === null) {+ return;+ }++ cleanupMarquee.current?.();+ const panel = panelElement.current;+ if (panel === null) {+ return;+ }++ const hasAddModifier = event.shiftKey || event.metaKey || event.ctrlKey;+ const initialSelection = hasAddModifier+ ? (forcedSelection ?? (selection === undefined ? [] : [selection]))+ : [];+ if (hasAddModifier === false) {+ setSelection(undefined);+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ }++ cleanupMarquee.current = startAssetManagerMarquee({+ pointerId: event.pointerId,+ start: { x: event.clientX, y: event.clientY },+ panel,+ listbox,+ items: navigableItems,+ initialSelection,+ getItemElement: (item) =>+ itemElements.current.get(getAssetManagerSelectionKey(item)),+ onSelectionChange: setForcedSelection,+ onRectChange: setMarqueeRect,+ onFinish: (items, active) => {+ cleanupMarquee.current = undefined;+ if (active === false) {+ return;+ }+ if (items.length === 0) {+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setSelection(undefined);+ announceSelection([]);+ return;+ }+ const focusedItem = items[0];+ setForcedSelection(items);+ setSelectionAnchor(focusedItem);+ setSelection(focusedItem);+ announceSelection(items);+ itemElements.current+ .get(getAssetManagerSelectionKey(focusedItem))+ ?.focus({ preventScroll: true });+ },+ onCancel: () => {+ cleanupMarquee.current = undefined;+ setForcedSelection(+ initialSelection.length === 0 ? undefined : [...initialSelection]+ );+ },+ });};return (- <AssetsShell- filters={- <Flex gap="2" grow>- <AssetFilters- formatCounts={formatCounts}- value={selectedExtensions}- onChange={setSelectedExtensions}- />- <AssetSortSelect value={sortState} onValueChange={setSortState} />- </Flex>- }- searchProps={searchProps}- isEmpty={filteredItems.length === 0}- type="file"- accept={accept}- >- <>- <Grid- columns={3}- gap="2"- css={{ paddingInline: theme.panel.paddingInline }}- >- {filteredItems.map((assetContainer, index) => (- <AssetThumbnail- key={assetContainer.asset.id}- assetContainer={assetContainer}- onSelect={handleSelect}- onChange={(assetContainer) => {- onChange?.(assetContainer.asset.id);+ <>+ <AssetsShell+ filters={+ <Flex gap="2" grow>+ <AssetFilters+ formatCounts={formatCounts}+ value={selectedExtensions}+ onChange={setSelectedExtensions}+ />+ <AssetSortSelect value={sortState} onValueChange={setSortState} />+ </Flex>+ }+ searchProps={searchProps}+ isEmpty={filteredItems.length === 0 && visibleFolders.length === 0}+ emptyMessage={isSearching ? "No matching assets or folders" : undefined}+ emptyContent={+ backCard === undefined ? undefined : (+ <AssetGrid role="listbox" aria-multiselectable={canManageFolders}>+ {backCard}+ </AssetGrid>+ )+ }+ interactionOverlay={+ marqueeRect === undefined ? undefined : (+ <Box+ data-asset-manager-marquee=""+ css={{+ position: "absolute",+ left: marqueeRect.left,+ top: marqueeRect.top,+ width: marqueeRect.width,+ height: marqueeRect.height,+ pointerEvents: "none",+ backgroundColor: `color-mix(in srgb, ${theme.colors.backgroundPrimary} 12%, transparent)`,+ border: `1px solid ${theme.colors.borderFocus}`,+ zIndex: 1,}}- state={index === selectedIndex ? "selected" : undefined}/>- ))}- </Grid>- </>- </AssetsShell>+ )+ }+ type="file"+ accept={accept}+ folderId={currentFolderId}+ onElementChange={(element) => {+ panelElement.current = element;+ }}+ onPointerDown={handlePanelPointerDown}+ onContextMenu={(event) => {+ if (+ event.target instanceof Element === false ||+ event.target.closest("[data-asset-manager-thumbnail]") === null+ ) {+ flushSync(() => {+ setItemContextMenu(({ instance }) => ({+ instance: instance + 1,+ }));+ });+ }+ }}+ onKeyDown={handleShortcut}+ contextMenu={+ hasPanelContextMenuActions ? (+ <AssetManagerItemContextMenuContent+ key={itemContextMenu.instance}+ actions={itemContextMenu.actions ?? panelContextMenuActions}+ disabledActions={+ itemContextMenu.actions === undefined+ ? disabledPanelActions+ : undefined+ }+ />+ ) : undefined+ }+ footer={+ <AssetFolderBreadcrumbs+ hierarchy={folderHierarchy}+ folderId={currentFolderId}+ onChange={setCurrentFolderId}+ canPaste={canManageFolders ? canPasteAssetManagerItem : undefined}+ onPaste={canManageFolders ? pasteAssetManagerItem : undefined}+ />+ }+ >+ <>+ <Box+ role="status"+ aria-live="polite"+ css={{+ position: "absolute",+ width: 1,+ height: 1,+ overflow: "hidden",+ clip: "rect(0 0 0 0)",+ }}+ >+ {announcement}+ </Box>+ <AssetGrid role="listbox" aria-multiselectable={canManageFolders}>+ <>+ {backCard}+ {visibleFolders.map((folder) => (+ <FolderThumbnail+ key={folder.id}+ folder={folder}+ interactions={thumbnailInteractions}+ selected={isItemSelected({ type: "folder", id: folder.id })}+ forcedSelection={forcedSelection !== undefined}+ selectionActions={+ forcedSelection === undefined ? undefined : selectionActions+ }+ canManage={canManageFolders}+ canMoveItems={canMoveItems}+ onOpen={() => openFolder(folder.id)}+ path={+ isSearching+ ? formatAssetFolderPath(folderHierarchy, folder.parentId)+ : undefined+ }+ onElementChange={(element) =>+ registerItemElement(+ { type: "folder", id: folder.id },+ element+ )+ }+ onMoveItems={moveItems}+ />+ ))}+ {filteredItems.map((assetContainer) => (+ <AssetThumbnail+ key={assetContainer.asset.id}+ assetContainer={assetContainer}+ interactions={thumbnailInteractions}+ selectionActions={+ forcedSelection === undefined ? undefined : selectionActions+ }+ onChange={(assetContainer) => {+ onChange?.(assetContainer.asset.id);+ }}+ selected={isItemSelected({+ type: "asset",+ id: assetContainer.asset.id,+ })}+ forcedSelection={forcedSelection !== undefined}+ folderPath={+ isSearching+ ? formatAssetFolderPath(+ folderHierarchy,+ assetContainer.asset.folderId+ )+ : undefined+ }+ canDrag={canManageFolders}+ onElementChange={(element) =>+ registerItemElement(+ { type: "asset", id: assetContainer.asset.id },+ element+ )+ }+ />+ ))}+ </>+ </AssetGrid>+ </>+ </AssetsShell>+ <Dialog+ open={pendingDeleteItems !== undefined}+ onOpenChange={(open) => {+ if (open === false) {+ setPendingDeleteItems(undefined);+ }+ }}+ >+ <DialogContent minWidth={360} aria-describedby={undefined}>+ <DialogTitle>Delete selected items</DialogTitle>+ <Box css={{ padding: theme.panel.padding }}>+ <Text>+ Delete {pendingDeleteItems?.length ?? 0} selected+ {pendingDeleteItems?.length === 1 ? " item" : " items"}?+ Everything inside selected folders will also be deleted.+ </Text>+ <Flex justify="end" css={{ marginTop: theme.panel.paddingBlock }}>+ <Button+ autoFocus+ color="destructive"+ prefix={<TrashIcon />}+ onClick={() => {+ const items = pendingDeleteItems ?? [];+ deleteAssetManagerItems(items);+ setPendingDeleteItems(undefined);+ setForcedSelection(undefined);+ setSelectionAnchor(undefined);+ setAnnouncement(+ `${items.length} ${+ items.length === 1 ? "item" : "items"+ } deleted.`+ );+ }}+ >+ Delete+ </Button>+ </Flex>+ </Box>+ </DialogContent>+ </Dialog>+ </>);};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsxnew file mode 100644index 0000000000..0c9f2d20ab--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.test.tsx@@ -0,0 +1,80 @@+import { afterEach, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import { createAssetManagerTestRenderer } from "./test-utils";+import { AssetDeleteDialog, AssetSettings } from "./asset-settings";++const renderer = createAssetManagerTestRenderer();+vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+);+afterEach(renderer.cleanup);++test("describes an unused asset in the delete confirmation", () => {+ renderer.render(+ <AssetDeleteDialog+ open+ onOpenChange={vi.fn()}+ asset={{+ id: "asset",+ projectId: "project",+ name: "document.pdf",+ format: "pdf",+ size: 100,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ }}+ />+ );++ expect(document.body.textContent).toContain("Delete “document.pdf”?");+ expect(document.body.textContent).not.toContain("cannot be undone");+ expect(document.activeElement?.textContent).toBe("Delete");+});++test("uses an auto-growing textarea for the asset description", () => {+ renderer.render(+ <TooltipProvider>+ <AssetSettings+ open+ onOpenChange={vi.fn()}+ asset={{+ id: "asset",+ projectId: "project",+ name: "image.png",+ format: "png",+ size: 100,+ type: "image",+ meta: { width: 100, height: 100 },+ description: "A useful description",+ createdAt: "2026-01-01T00:00:00.000Z",+ }}+ >+ <button>Anchor</button>+ </AssetSettings>+ </TooltipProvider>+ );++ const description = document.querySelector<HTMLTextAreaElement>(+ "#asset-manager-description"+ );+ expect(description?.value).toBe("A useful description");+ expect(description?.rows).toBe(1);+ expect(+ document.querySelector('label[for="asset-manager-description"]')+ ).toBeInstanceOf(HTMLLabelElement);+ expect(document.body.textContent).toContain("Asset settings");+ const settingsIndicator = document.querySelector<HTMLElement>(+ "[data-asset-settings-usage-indicator]"+ );+ const thumbnailIndicator = document.querySelector<HTMLElement>(+ "[data-asset-thumbnail-indicator]"+ );+ expect(settingsIndicator).toBeInstanceOf(HTMLElement);+ expect(settingsIndicator?.className).toBe(thumbnailIndicator?.className);+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsxsimilarity index 78%rename from apps/builder/app/builder/shared/asset-manager/asset-info.tsxrename to apps/builder/app/builder/shared/asset-manager/asset-settings.tsxindex 2645b5e461..a5e494f9cb 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-info.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-settings.tsx@@ -1,10 +1,10 @@import isValidFilename from "valid-filename";-import { useCallback, useEffect, useRef, useState } from "react";+import { useEffect, useRef, useState, type ReactNode } from "react";import { useDebouncedCallback } from "use-debounce";import prettyBytes from "pretty-bytes";import { computed } from "nanostores";import { useStore } from "@nanostores/react";-import { getMimeTypeByExtension, IMAGE_MIME_TYPES } from "@webstudio-is/sdk";+import { getMimeTypeByExtension } from "@webstudio-is/sdk";import type { Asset, Instance } from "@webstudio-is/sdk";import {Box,@@ -13,7 +13,6 @@ import {Dialog,DialogContent,DialogTitle,- DialogTrigger,Flex,Grid,IconButton,@@ -21,12 +20,13 @@ import {InputField,Label,Popover,+ PopoverAnchor,PopoverContent,PopoverTitle,- PopoverTrigger,SmallIconButton,styled,Text,+ TextArea,textVariants,theme,Tooltip,@@ -37,7 +37,6 @@ import {CopyIcon,DimensionsIcon,DownloadIcon,- GearIcon,InfoCircleIcon,PageIcon,RefreshCcwIcon,@@ -58,8 +57,7 @@ import { selectPage } from "~/shared/nano-states";import { findPageAndSelectorByInstanceId } from "@webstudio-is/project-build/runtime";import { $selectedPageId } from "~/shared/nano-states";import { executeRuntimeMutation } from "~/shared/instance-utils/data";-import { deleteAssets, replaceAsset } from "~/builder/shared/assets";-import { validateFiles } from "~/builder/shared/assets/asset-upload";+import { deleteAssets } from "~/builder/shared/assets";import {$activeInspectorPanel,setActiveSidebarPanel,@@ -74,6 +72,8 @@ import {formatAssetName,parseAssetName,} from "@webstudio-is/project-build/runtime";+import { AssetFolderSelector } from "./asset-folder-selector";+import { moveAssetToFolder } from "./asset-folder-actions";import { getAssetUrl } from "~/builder/shared/assets/asset-utils";import { getFormattedAspectRatio } from "./utils";import { CopyToClipboard } from "~/shared/copy-to-clipboard";@@ -236,12 +236,10 @@ const AssetUsagesList = ({ usages }: { usages: AssetUsage[] }) => {);};-const UsageDot = styled(Box, {- width: 6,- height: 6,- backgroundColor: "#000",- border: "1px solid white",- boxShadow: "0 0 3px rgb(0, 0, 0)",+const AssetUsageIndicator = styled(Box, {+ width: 4,+ height: 4,+ backgroundColor: theme.colors.backgroundStatusAttention,borderRadius: "50%",pointerEvents: "none",});@@ -288,12 +286,18 @@ const useLocalValue = <Type extends string>(] as const;};-const AssetInfoContent = ({+const AssetSettingsContent = ({asset,usages,+ onDelete,+ onReplace,+ focusName,}: {asset: Asset;usages: AssetUsage[];+ onDelete?: () => void;+ onReplace?: () => void;+ focusName: boolean;}) => {const { canDownloadAssets } = useStore($permissions);const { size, meta, id, name } = asset;@@ -342,22 +346,11 @@ const AssetInfoContent = ({});- const authPermit = useStore($authPermit);- const replaceInputRef = useRef<HTMLInputElement>(null);-- const handleReplaceFile = useCallback(- (event: React.ChangeEvent<HTMLInputElement>) => {- const files = validateFiles(Array.from(event.target.files ?? []));- const file = files[0];- if (file) {- replaceAsset(id, file);- }- // Reset input so the same file can be selected again- event.target.value = "";- },- [id]- );+ const moveToFolder = (newFolderId: string | undefined) => {+ moveAssetToFolder(asset.id, newFolderId);+ };+ const authPermit = useStore($authPermit);let downloadError: undefined | string;if (authPermit === "view") {downloadError =@@ -414,7 +407,7 @@ const AssetInfoContent = ({alignItems: "center",}}>- <UsageDot />+ <AssetUsageIndicator data-asset-settings-usage-indicator="" /></Flex><Text variant="labels">{usages.length} uses</Text></Flex>@@ -428,6 +421,7 @@ const AssetInfoContent = ({><InputFieldid="asset-manager-filename"+ autoFocus={focusName}color={filenameError ? "error" : undefined}value={filename}onChange={(event) => {@@ -451,11 +445,24 @@ const AssetInfoContent = ({<InfoCircleIcon /></Tooltip></Label>- <InputField+ <TextAreaid="asset-manager-description"placeholder='Enter "alt" text'+ rows={1}+ maxRows={6}+ autoGrowvalue={description}- onChange={(event) => setDescription(event.target.value)}+ onChange={setDescription}+ />+ </Grid>++ <Grid css={{ padding: theme.panel.padding, gap: 4 }}>+ <AssetFolderSelector+ value={asset.folderId}+ onChange={moveToFolder}+ rootLabel="Folder"+ disabled={authPermit === "view"}+ deferChangesUntilBlur/></Grid>@@ -483,54 +490,17 @@ const AssetInfoContent = ({</Button></Tooltip>) : usages.length === 0 ? (- <Button- color="destructive"- onClick={() => deleteAssets([id])}- prefix={<TrashIcon />}- >+ <Button color="destructive" onClick={onDelete} prefix={<TrashIcon />}>Delete</Button>) : (- <Dialog>- <DialogTrigger asChild>- <Button>Review & delete</Button>- </DialogTrigger>- <DialogContent minWidth={360}>- <DialogTitle>Delete asset?</DialogTitle>- <Box css={{ padding: theme.panel.padding }}>- <Text css={{ marginBottom: "1em" }}>- This asset is used in following places:- </Text>- <AssetUsagesList usages={usages} />- <Flex>- <Button- css={{- marginLeft: "auto",- marginTop: theme.panel.paddingBlock,- }}- color="destructive"- prefix={<TrashIcon />}- onClick={() => deleteAssets([id])}- >- Delete- </Button>- </Flex>- </Box>- </DialogContent>- </Dialog>+ <Button onClick={onDelete}>Review & delete</Button>)}<Flex gap="1">{isImage && (<>- <input- ref={replaceInputRef}- type="file"- accept={IMAGE_MIME_TYPES.join(", ")}- style={{ display: "none" }}- onChange={handleReplaceFile}- />- {replaceError ? (+ {replaceError || onReplace === undefined ? (<Tooltip side="bottom" content={replaceError}><IconButton disabled><RefreshCcwIcon />@@ -538,10 +508,7 @@ const AssetInfoContent = ({</Tooltip>) : (<Tooltip side="bottom" content="Replace asset">- <IconButton- aria-label="Replace asset"- onClick={() => replaceInputRef.current?.click()}- >+ <IconButton aria-label="Replace asset" onClick={onReplace}><RefreshCcwIcon /></IconButton></Tooltip>@@ -571,52 +538,93 @@ const AssetInfoContent = ({);};-const triggerVisibilityVar = `--ws-asset-info-trigger-visibility`;--export const assetInfoCssVars = ({ show }: { show: boolean }) => ({- [triggerVisibilityVar]: show ? "visible" : "hidden",-});+export const AssetDeleteDialog = ({+ asset,+ open,+ onOpenChange,+}: {+ asset: Asset;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) => {+ const usagesByAssetId = useStore($usagesByAssetId);+ const usages = usagesByAssetId.get(asset.id) ?? [];+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent minWidth={360} aria-describedby={undefined}>+ <DialogTitle>Delete asset?</DialogTitle>+ <Box css={{ padding: theme.panel.padding }}>+ <Text>Delete “{formatAssetName(asset)}”?</Text>+ {usages.length > 0 && (+ <>+ <Text css={{ marginTop: "1em", marginBottom: "1em" }}>+ This asset is used in the following places:+ </Text>+ <AssetUsagesList usages={usages} />+ </>+ )}+ <Flex justify="end" css={{ marginTop: theme.panel.paddingBlock }}>+ <Button+ autoFocus+ color="destructive"+ prefix={<TrashIcon />}+ onClick={() => deleteAssets([asset.id])}+ >+ Delete+ </Button>+ </Flex>+ </Box>+ </DialogContent>+ </Dialog>+ );+};-export const AssetInfo = ({ asset }: { asset: Asset }) => {+export const AssetSettings = ({+ asset,+ open,+ onOpenChange,+ onDelete,+ onReplace,+ focusName = false,+ children,+}: {+ asset: Asset;+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onDelete?: () => void;+ onReplace?: () => void;+ focusName?: boolean;+ children: ReactNode;+}) => {const usagesByAssetId = useStore($usagesByAssetId);const usages = usagesByAssetId.get(asset.id) ?? [];+ const deleteAsset =+ onDelete === undefined+ ? undefined+ : () => {+ onOpenChange(false);+ onDelete();+ };return (- <>- <Popover modal>- <PopoverTrigger asChild>- <SmallIconButton- title="Options"- tabIndex={-1}- css={{- visibility: `var(${triggerVisibilityVar}, hidden)`,- position: "absolute",- color: theme.colors.backgroundIconSubtle,- top: theme.spacing[3],- right: theme.spacing[3],- cursor: "pointer",- transition: "opacity 100ms ease",- "& svg": {- fill: `oklch(from ${theme.colors.white} l c h / 0.9)`,- },- "&:hover": {- color: theme.colors.backgroundIconSubtle,- background: "transparent",- "& svg": {- fill: `oklch(from ${theme.colors.white} l c h / 1)`,- },- },- }}- icon={<GearIcon />}- />- </PopoverTrigger>- <PopoverContent css={{ minWidth: 250 }}>- <PopoverTitle>Asset details</PopoverTitle>- <AssetInfoContent asset={asset} usages={usages} />- </PopoverContent>- </Popover>+ <Popover modal open={open} onOpenChange={onOpenChange}>{usages.length === 0 && (- <UsageDot css={{ position: "absolute", top: 9, right: 9 }} />+ <AssetUsageIndicator+ role="img"+ aria-label="Unused asset"+ data-asset-thumbnail-indicator=""+ />)}- </>+ <PopoverAnchor asChild>{children}</PopoverAnchor>+ <PopoverContent css={{ minWidth: 250 }}>+ <PopoverTitle>Asset settings</PopoverTitle>+ <AssetSettingsContent+ asset={asset}+ usages={usages}+ onDelete={deleteAsset}+ onReplace={onReplace}+ focusName={focusName}+ />+ </PopoverContent>+ </Popover>);};diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.test.tsxnew file mode 100644index 0000000000..b9c96320fe--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.test.tsx@@ -0,0 +1,50 @@+import { afterEach, describe, expect, test, vi } from "vitest";+import { AssetThumbnailCard } from "./asset-thumbnail-card";+import { createAssetManagerTestRenderer } from "./test-utils";++const renderer = createAssetManagerTestRenderer();+afterEach(renderer.cleanup);++describe("AssetThumbnailCard", () => {+ test("renders folder and Back thumbnails as native buttons", () => {+ const onClick = vi.fn();+ const container = renderer.render(+ <AssetThumbnailCard+ as="button"+ type="button"+ preview={<span data-testid="preview">icon</span>}+ label="Back"+ clickable+ onClick={onClick}+ />+ );++ const button = container.querySelector("button");+ expect(button?.type).toBe("button");+ expect(button?.textContent).toBe("iconBack");+ expect(container.querySelector("[data-testid=preview]")).not.toBeNull();++ button?.click();+ expect(onClick).toHaveBeenCalledOnce();+ });++ test("renders asset metadata in the same thumbnail component", () => {+ const container = renderer.render(+ <AssetThumbnailCard+ preview={<span>preview</span>}+ label="Hero"+ labelSuffix=".png"+ path="Root / Images"+ tabIndex={0}+ >+ <span>asset actions</span>+ </AssetThumbnailCard>+ );++ expect(container.querySelector("button")).toBeNull();+ expect(container.firstElementChild?.getAttribute("tabindex")).toBe("0");+ expect(container.textContent).toBe(+ "previewHero.pngRoot / Imagesasset actions"+ );+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.tsxnew file mode 100644index 0000000000..7f307bf3de--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail-card.tsx@@ -0,0 +1,220 @@+import {+ forwardRef,+ type ComponentProps,+ type FocusEvent,+ type KeyboardEvent,+ type MouseEventHandler,+ type ReactNode,+ type Ref,+} from "react";+import {+ ArrowFocus,+ Box,+ Flex,+ styled,+ Text,+ theme,+} from "@webstudio-is/design-system";++const thumbnailActionVisibility = "--ws-thumbnail-action-visibility";+const showThumbnailAction = { [thumbnailActionVisibility]: "visible" };+const focusOutline = {+ outline: `1px solid ${theme.colors.borderFocus}`,+ outlineOffset: -1,+};++const thumbnailActionVisibilityValue = `var(${thumbnailActionVisibility}, hidden)`;++const ThumbnailGroup = styled(Box, {+ position: "relative",+ minWidth: 0,+ variants: {+ selected: {+ true: showThumbnailAction,+ },+ },+ "&:hover, &:focus-within": showThumbnailAction,+ "&:hover > [data-asset-thumbnail]": {+ backgroundColor: theme.colors.backgroundAssetcardHover,+ },+});++type AssetThumbnailGroupProps = ComponentProps<typeof ThumbnailGroup> & {+ selected?: boolean;+ onFocusChange?: (focused: boolean) => void;+};++export const AssetThumbnailGroup = forwardRef<+ HTMLDivElement,+ AssetThumbnailGroupProps+>(({ onFocusChange, onFocus, onBlur, onKeyDown, ...props }, forwardedRef) => (+ <ArrowFocus+ render={({ handleKeyDown }) => (+ <ThumbnailGroup+ {...props}+ ref={forwardedRef}+ onFocus={(event: FocusEvent<HTMLDivElement>) => {+ onFocus?.(event);+ if (event.currentTarget.contains(event.relatedTarget) === false) {+ onFocusChange?.(true);+ }+ }}+ onBlur={(event: FocusEvent<HTMLDivElement>) => {+ onBlur?.(event);+ if (event.currentTarget.contains(event.relatedTarget) === false) {+ onFocusChange?.(false);+ }+ }}+ onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {+ onKeyDown?.(event);+ if (+ event.defaultPrevented === false &&+ (event.key === "ArrowLeft" || event.key === "ArrowRight")+ ) {+ handleKeyDown(event);+ }+ }}+ />+ )}+ />+));+AssetThumbnailGroup.displayName = "AssetThumbnailGroup";++export const AssetThumbnailHeader = styled("header", {+ position: "absolute",+ zIndex: 1,+ top: 0,+ left: 0,+ right: 0,+ boxSizing: "border-box",+ display: "flex",+ alignItems: "flex-start",+ padding: theme.spacing[3],+ paddingRight: theme.spacing[4],+ pointerEvents: "none",+});++export const AssetThumbnailMenu = styled(Box, {+ marginLeft: "auto",+ visibility: thumbnailActionVisibilityValue,+ pointerEvents: "auto",+ "& button": {+ borderRadius: theme.borderRadius[3],+ },+ "& svg": {+ filter: "drop-shadow(0 0 1px rgba(255, 255, 255, 0.9))",+ },+});++const Root = styled("div", {+ all: "unset",+ WebkitUserDrag: "element",+ boxSizing: "border-box",+ position: "relative",+ display: "flex",+ minWidth: 0,+ width: "100%",+ justifyContent: "center",+ alignItems: "center",+ flexDirection: "column",+ borderRadius: theme.borderRadius[4],+ outline: "none",+ gap: theme.spacing[3],+ overflow: "hidden",+ padding: 2,+ "&:hover, &:focus-visible": {+ ...showThumbnailAction,+ backgroundColor: theme.colors.backgroundAssetcardHover,+ },+ "&:focus-visible": {+ ...focusOutline,+ },+ variants: {+ selected: {+ true: {+ ...focusOutline,+ backgroundColor: theme.colors.backgroundAssetcardHover,+ ...showThumbnailAction,+ },+ },+ dropTarget: {+ true: {+ outline: `2px solid ${theme.colors.borderFocus}`,+ backgroundColor: theme.colors.backgroundAssetcardHover,+ },+ },+ clickable: {+ true: { cursor: "pointer" },+ },+ },+});++const Preview = styled(Box, {+ width: "100%",+ height: theme.spacing[19],+ flexShrink: 0,+ position: "relative",+ display: "flex",+ alignItems: "center",+ justifyContent: "center",+});++const Label = styled(Flex, {+ width: "100%",+ paddingBottom: 4,+});++type AssetThumbnailCardProps = Omit<+ ComponentProps<typeof Root>,+ "children" | "as"+> & {+ as?: "div" | "button";+ type?: "button";+ preview: ReactNode;+ label: ReactNode;+ labelSuffix?: ReactNode;+ path?: string;+ children?: ReactNode;+ onPreviewClick?: MouseEventHandler<HTMLDivElement>;+};++export const AssetThumbnailCard = forwardRef<+ HTMLElement,+ AssetThumbnailCardProps+>(+ (+ {+ as = "div",+ preview,+ label,+ labelSuffix,+ path,+ children,+ onPreviewClick,+ ...props+ },+ forwardedRef+ ) => (+ <Root+ {...props}+ as={as}+ ref={forwardedRef as Ref<HTMLDivElement>}+ data-asset-thumbnail=""+ >+ <Preview onClick={onPreviewClick}>{preview}</Preview>+ <Label justify="center">+ <Text variant="tiny" truncate>+ {label}+ </Text>+ {labelSuffix !== undefined && <Text variant="tiny">{labelSuffix}</Text>}+ </Label>+ {path !== undefined && (+ <Text variant="tiny" color="subtle" truncate css={{ width: "100%" }}>+ {path}+ </Text>+ )}+ {children}+ </Root>+ )+);+AssetThumbnailCard.displayName = "AssetThumbnailCard";diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsxnew file mode 100644index 0000000000..a443f34e60--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.test.tsx@@ -0,0 +1,349 @@+import { Fragment, type ComponentProps } from "react";+import { act } from "react-dom/test-utils";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { TooltipProvider } from "@webstudio-is/design-system";+import { AssetThumbnail } from "./asset-thumbnail";+import { BackThumbnail, FolderThumbnail } from "./asset-folder-thumbnail";+import { createAssetFolderFixture } from "@webstudio-is/sdk/testing";+import { $assetManagerClipboard } from "./asset-manager-clipboard";+import { createAssetManagerTestRenderer } from "./test-utils";+import { $authPermit } from "~/shared/nano-states";+import type { AssetManagerThumbnailInteractions } from "./asset-manager-thumbnail";+import { $assetFolders, $assets, $project } from "~/shared/sync/data-stores";++const folder = createAssetFolderFixture({ id: "folder", name: "Documents" });+const uploadedAssetContainer: ComponentProps<+ typeof AssetThumbnail+>["assetContainer"] = {+ status: "uploaded",+ asset: {+ id: "asset",+ projectId: "project",+ name: "document.pdf",+ format: "pdf",+ size: 100,+ type: "file",+ meta: {},+ createdAt: "2026-01-01T00:00:00.000Z",+ },+};++const createInteractions = (+ onSelectionChange = vi.fn()+): AssetManagerThumbnailInteractions => ({+ onSelectionChange: (_item, selected) => onSelectionChange(selected),+ onItemPointerDown: vi.fn(),+ onItemClick: vi.fn(),+ onModifiedArrow: vi.fn(),+ onContextMenuSelection: vi.fn(),+ onContextMenuActions: vi.fn(),+ getDragItems: (item) => [item],+});++const createFolderThumbnail = (+ props: Partial<ComponentProps<typeof FolderThumbnail>> = {}+) => (+ <FolderThumbnail+ folder={folder}+ selected={false}+ canManage={false}+ interactions={createInteractions()}+ canMoveItems={() => false}+ onOpen={vi.fn()}+ onMoveItems={vi.fn()}+ {...props}+ />+);++const createUploadedAssetThumbnail = () => (+ <AssetThumbnail+ assetContainer={uploadedAssetContainer}+ interactions={createInteractions()}+ />+);++const openSettingsFromActionsMenu = ({+ container,+ triggerLabel,+ settingsTitle,+}: {+ container: HTMLElement;+ triggerLabel: string;+ settingsTitle: string;+}) => {+ const actions = container.querySelector<HTMLButtonElement>(+ `[aria-label="${triggerLabel}"]`+ );+ act(() => {+ actions?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });++ expect(document.body.textContent).not.toContain(settingsTitle);+ const menuItems = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ );+ const settings = menuItems.find((item) => item.textContent === "Settings");+ const rename = menuItems.find((item) => item.textContent === "Rename");+ expect(settings).toBeDefined();+ expect(rename).toBeUndefined();+ act(() => settings?.click());+};++const renderer = createAssetManagerTestRenderer();+vi.stubGlobal(+ "ResizeObserver",+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+);+beforeEach(() => {+ $authPermit.set("build");+ $project.set({ id: "project" } as never);+ $assetFolders.set(new Map([[folder.id, folder]]));+ if (uploadedAssetContainer.status === "uploaded") {+ $assets.set(+ new Map([[uploadedAssetContainer.asset.id, uploadedAssetContainer.asset]])+ );+ }+});+afterEach(() => {+ renderer.cleanup();+ $assetManagerClipboard.set(undefined);+ $assetFolders.set(new Map());+ $assets.set(new Map());+ $project.set(undefined);+});++describe("AssetThumbnail", () => {+ test("renders asset, folder, and Back components through the shared card", () => {+ const container = renderer.render(+ <Fragment>+ <AssetThumbnail+ assetContainer={{+ status: "uploading",+ objectURL: "blob:document",+ asset: {+ id: "asset",+ name: "document.pdf",+ filename: undefined,+ format: "pdf",+ description: undefined,+ type: "file",+ folderId: "folder",+ },+ }}+ interactions={createInteractions()}+ />+ {createFolderThumbnail()}+ <BackThumbnail onOpen={vi.fn()} />+ </Fragment>+ );++ const thumbnails = container.querySelectorAll("[data-asset-thumbnail]");+ const managedThumbnails = container.querySelectorAll(+ "[data-asset-manager-thumbnail]"+ );+ expect(thumbnails).toHaveLength(3);+ expect(managedThumbnails).toHaveLength(2);+ expect(thumbnails[0]?.tagName).toBe("BUTTON");+ expect(thumbnails[1]?.tagName).toBe("BUTTON");+ expect(thumbnails[2]?.tagName).toBe("BUTTON");+ expect(container.textContent).toContain("document.pdf");+ expect(container.textContent).toContain("Documents");+ expect(container.textContent).toContain("Back");++ const backIcon = thumbnails[2]?.querySelector("svg");+ expect(backIcon?.children).toHaveLength(1);+ expect(backIcon?.firstElementChild?.tagName).toBe("path");+ expect(backIcon?.firstElementChild?.getAttribute("vector-effect")).toBe(+ "non-scaling-stroke"+ );+ });++ test("uses focus for folder selection and opens only on activation", () => {+ const onOpen = vi.fn();+ const onSelectionChange = vi.fn();+ const container = renderer.render(+ createFolderThumbnail({+ selected: true,+ forcedSelection: true,+ interactions: createInteractions(onSelectionChange),+ onOpen,+ })+ );++ const button = container.querySelector("button");+ const outside = document.createElement("button");+ document.body.appendChild(outside);+ expect(+ button?.closest('[role="option"]')?.getAttribute("aria-selected")+ ).toBe("true");+ button?.focus();+ expect(onSelectionChange).toHaveBeenLastCalledWith(true);+ outside.focus();+ expect(onSelectionChange).toHaveBeenLastCalledWith(false);++ button?.click();+ expect(onOpen).not.toHaveBeenCalled();++ button?.dispatchEvent(new MouseEvent("dblclick", { bubbles: true }));+ expect(onOpen).toHaveBeenCalledOnce();++ button?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true })+ );+ expect(onOpen).toHaveBeenCalledTimes(2);++ button?.dispatchEvent(+ new KeyboardEvent("keydown", { key: " ", bubbles: true })+ );+ expect(onOpen).toHaveBeenCalledTimes(2);+ });++ describe.each([+ {+ variant: "folder",+ thumbnailLabel: "Folder Documents",+ triggerLabel: "Actions for Documents",+ settingsTitle: "Folder settings",+ shortcutActions: ["Cut", "Copy", "Paste", "Duplicate", "Delete"],+ render: () => createFolderThumbnail({ canManage: true }),+ },+ {+ variant: "asset",+ thumbnailLabel: undefined,+ triggerLabel: "Actions for document.pdf",+ settingsTitle: "Asset settings",+ shortcutActions: ["Cut", "Copy", "Duplicate", "Delete"],+ render: createUploadedAssetThumbnail,+ },+ ])("$variant thumbnail actions", (thumbnail) => {+ const render = () =>+ renderer.render(<TooltipProvider>{thumbnail.render()}</TooltipProvider>);++ test("skips actions with Tab and reaches them with arrow keys", () => {+ const container = render();+ const card = container.querySelector<HTMLButtonElement>(+ thumbnail.thumbnailLabel === undefined+ ? "[data-asset-thumbnail]"+ : `[aria-label="${thumbnail.thumbnailLabel}"]`+ );+ const actions = container.querySelector<HTMLButtonElement>(+ `[aria-label="${thumbnail.triggerLabel}"]`+ );++ expect(card?.tabIndex).toBe(0);+ expect(actions?.tabIndex).toBe(-1);+ expect(+ actions?.closest("header")?.getAttribute("data-asset-thumbnail-header")+ ).toBe("");++ card?.focus();+ card?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })+ );+ expect(document.activeElement).toBe(actions);++ actions?.dispatchEvent(+ new KeyboardEvent("keydown", { key: "ArrowLeft", bubbles: true })+ );+ expect(document.activeElement).toBe(card);+ });++ test("opens settings from the actions menu", () => {+ const container = render();+ openSettingsFromActionsMenu({+ container,+ triggerLabel: thumbnail.triggerLabel,+ settingsTitle: thumbnail.settingsTitle,+ });+ expect(document.body.textContent).toContain(thumbnail.settingsTitle);+ expect(+ document+ .querySelector('[role="dialog"]')+ ?.querySelector('[aria-label="Actions"]')+ ).toBeNull();+ });++ test("shows keyboard shortcuts in the actions menu", () => {+ $assetManagerClipboard.set({+ operation: "copy",+ items: [{ type: "asset", id: "asset", projectId: "project" }],+ projectId: "project",+ });+ const container = render();+ act(() => {+ container+ .querySelector<HTMLButtonElement>(+ `[aria-label="${thumbnail.triggerLabel}"]`+ )+ ?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });+ const menuItems = Array.from(+ document.body.querySelectorAll<HTMLElement>('[role="menuitem"]')+ );++ for (const label of thumbnail.shortcutActions) {+ const item = menuItems.find((item) =>+ item.textContent?.startsWith(label)+ );+ expect(item?.querySelector("kbd"), label).toBeInstanceOf(HTMLElement);+ }+ });+ });++ test("shows the unused asset indicator in the thumbnail", () => {+ const container = renderer.render(+ <TooltipProvider>{createUploadedAssetThumbnail()}</TooltipProvider>+ );++ const header = container.querySelector<HTMLElement>(+ "header[data-asset-thumbnail-header]"+ );+ expect(+ header?.querySelector('[role="img"][aria-label="Unused asset"]')+ ).toBeInstanceOf(HTMLElement);+ expect(+ header?.querySelector('[aria-label="Actions for document.pdf"]')+ ).toBeInstanceOf(HTMLButtonElement);+ });++ test("does not offer paste from another project on a folder", () => {+ $assetManagerClipboard.set({+ operation: "copy",+ items: [+ {+ type: "asset",+ id: "asset",+ projectId: "another-project",+ },+ ],+ projectId: "another-project",+ });+ const container = renderer.render(+ <TooltipProvider>+ {createFolderThumbnail({ canManage: true })}+ </TooltipProvider>+ );+ const actions = container.querySelector<HTMLButtonElement>(+ '[aria-label="Actions for Documents"]'+ );+ act(() => {+ actions?.dispatchEvent(+ new MouseEvent("pointerdown", { bubbles: true, button: 0 })+ );+ });++ expect(+ Array.from(document.body.querySelectorAll('[role="menuitem"]')).some(+ (item) => item.textContent === "Paste"+ )+ ).toBe(false);+ });+});diff --git a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsxindex 7d0c00096c..c481e55dbd 100644--- a/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx+++ b/apps/builder/app/builder/shared/asset-manager/asset-thumbnail.tsx@@ -1,13 +1,13 @@-import type { KeyboardEvent, FocusEvent } from "react";-import { Box, Flex, styled, Text } from "@webstudio-is/design-system";+import { useEffect, useRef, useState, type KeyboardEvent } from "react";+import { useStore } from "@nanostores/react";+import { Box, styled, Text } from "@webstudio-is/design-system";import { PageIcon, TextCapitalizeIcon } from "@webstudio-is/icons";import { wsVideoLoader } from "@webstudio-is/image";import { UploadingAnimation } from "./uploading-animation";-import { AssetInfo, assetInfoCssVars } from "./asset-info";+import { AssetDeleteDialog, AssetSettings } from "./asset-settings";import type { AssetContainer } from "~/builder/shared/assets";import { Image } from "./image";import brokenImage from "~/shared/images/broken-image-placeholder.svg";-import { theme } from "@webstudio-is/design-system";import {formatAssetName,parseAssetName,@@ -16,9 +16,23 @@ import type { IconComponent } from "@webstudio-is/icons";import type { AllowedFileExtension } from "@webstudio-is/sdk";import {FILE_EXTENSIONS_BY_CATEGORY,+ IMAGE_MIME_TYPES,detectAssetType,} from "@webstudio-is/sdk";import type { MimeCategory } from "@webstudio-is/sdk";+import { draggable } from "@atlaskit/pragmatic-drag-and-drop/element/adapter";+import { $authPermit, $permissions } from "~/shared/nano-states";+import { replaceAsset } from "~/builder/shared/assets";+import { validateFiles } from "~/builder/shared/assets/asset-upload";+import { getAssetUrl } from "~/builder/shared/assets/asset-utils";+import { createAssetManagerClipboardActions } from "./asset-manager-clipboard";+import { setAssetManagerDragPreview } from "./asset-manager-drag-preview";+import { type AssetManagerItemActions } from "./asset-manager-item-menu";+import {+ AssetManagerThumbnail,+ AssetManagerThumbnailMenu,+ type AssetManagerThumbnailInteractions,+} from "./asset-manager-thumbnail";const FORMAT_CATEGORIES = FILE_EXTENSIONS_BY_CATEGORY;@@ -40,33 +54,7 @@ const getFileIcon = (format: string): IconComponent => {return PageIcon;};-const StyledWebstudioImage = styled(Image, {- position: "absolute",- width: "100%",- height: "100%",- objectFit: "contain",-- // This is shown only if an image was not loaded and broken- // From the spec:- // - The pseudo-elements generated by ::before and ::after are contained by the element's formatting box,- // and thus don't apply to "replaced" elements such as <img>, or to <br> elements- // Not in spec but supported by all browsers:- // - broken image is not a "replaced" element so this style is applied- "&::after": {- content: "' '",- position: "absolute",- width: "100%",- height: "100%",- left: 0,- top: 0,- backgroundSize: "contain",- backgroundRepeat: "no-repeat",- backgroundPosition: "center",- backgroundImage: `url(${brokenImage})`,- },-});--const StyledWebstudioVideo = styled("video", {+const mediaPreviewStyle = {position: "absolute",width: "100%",height: "100%",@@ -90,49 +78,10 @@ const StyledWebstudioVideo = styled("video", {backgroundPosition: "center",backgroundImage: `url(${brokenImage})`,},-});--const ThumbnailContainer = styled(Box, {- position: "relative",- display: "flex",- justifyContent: "center",- alignItems: "center",- flexDirection: "column",- borderRadius: theme.borderRadius[4],- outline: "none",- gap: theme.spacing[3],- overflow: "hidden",- padding: 2,- "&:hover": {- ...assetInfoCssVars({ show: true }),- backgroundColor: theme.colors.backgroundAssetcardHover,- },- variants: {- status: {- uploading: {},- uploaded: {},- deleting: {},- },- state: {- selected: {- outline: `1px solid ${theme.colors.borderFocus}`,- outlineOffset: -1,- backgroundColor: theme.colors.backgroundAssetcardHover,- ...assetInfoCssVars({ show: true }),- },- },- },-});+} as const;-const Thumbnail = styled(Box, {- width: "100%",- height: theme.spacing[19],- flexShrink: 0,- position: "relative",- display: "flex",- alignItems: "center",- justifyContent: "center",-});+const StyledWebstudioImage = styled(Image, mediaPreviewStyle);+const StyledWebstudioVideo = styled("video", mediaPreviewStyle);const GenericFilePreview = ({ext,@@ -167,87 +116,190 @@ const GenericFilePreview = ({type AssetThumbnailProps = {assetContainer: AssetContainer;- onSelect: (assetContainer?: AssetContainer) => void;+ interactions: AssetManagerThumbnailInteractions;onChange?: (assetContainer: AssetContainer) => void;- state?: "selected";+ selected?: boolean;+ forcedSelection?: boolean;+ folderPath?: string;+ canDrag?: boolean;+ onElementChange?: (element: HTMLElement | null) => void;+ selectionActions?: AssetManagerItemActions;};export const AssetThumbnail = ({assetContainer,- onSelect,+ interactions,onChange,- state,+ selected,+ forcedSelection,+ folderPath,+ canDrag = false,+ onElementChange,+ selectionActions,}: AssetThumbnailProps) => {+ const elementRef = useRef<HTMLElement | null>(null);+ const replaceInputRef = useRef<HTMLInputElement>(null);+ const [settingsOpen, setSettingsOpen] = useState(false);+ const [deleteOpen, setDeleteOpen] = useState(false);+ const authPermit = useStore($authPermit);+ const { canDownloadAssets } = useStore($permissions);const { asset } = assetContainer;+ const getDragItems = interactions.getDragItems;const { basename, ext } = parseAssetName(asset.name);const alt = asset.description ?? formatAssetName(asset);const isUploading = assetContainer.status === "uploading";const assetType = detectAssetType(asset.name);+ const item = {+ type: "asset" as const,+ id: asset.id,+ projectId:+ assetContainer.status === "uploaded"+ ? assetContainer.asset.projectId+ : "uploading",+ };+ const download = () => {+ if (assetContainer.status !== "uploaded") {+ return;+ }+ const link = document.createElement("a");+ link.download = formatAssetName(assetContainer.asset);+ link.href = getAssetUrl(assetContainer.asset, window.location.origin).href;+ link.click();+ };+ const actions: AssetManagerItemActions =+ assetContainer.status === "uploading"+ ? {}+ : {+ settings: () => setSettingsOpen(true),+ ...(authPermit === "view"+ ? {}+ : {+ ...createAssetManagerClipboardActions(item),+ delete: () => setDeleteOpen(true),+ ...(asset.type === "image"+ ? { replace: () => replaceInputRef.current?.click() }+ : {}),+ }),+ ...(authPermit !== "view" && canDownloadAssets ? { download } : {}),+ };++ const handleReplaceFile = (event: React.ChangeEvent<HTMLInputElement>) => {+ const file = validateFiles(Array.from(event.target.files ?? []))[0];+ if (file !== undefined) {+ replaceAsset(asset.id, file);+ }+ event.target.value = "";+ };++ useEffect(() => {+ const element = elementRef.current;+ if (element === null || canDrag === false || isUploading) {+ return;+ }+ return draggable({+ element,+ onGenerateDragPreview: ({ nativeSetDragImage, location }) => {+ setAssetManagerDragPreview({+ nativeSetDragImage,+ sourceElement: element,+ input: location.initial.input,+ items: getDragItems({ type: "asset", id: asset.id }),+ });+ },+ getInitialData: () => ({+ kind: "asset",+ id: asset.id,+ items: getDragItems({ type: "asset", id: asset.id }),+ }),+ });+ }, [asset.id, canDrag, getDragItems, isUploading]);++ const displayedActions =+ forcedSelection && selected ? (selectionActions ?? actions) : actions;return (- <ThumbnailContainer- title={alt}- tabIndex={0}- status={assetContainer.status}- state={state}- onFocus={() => {- onSelect?.(assetContainer);- }}- onBlur={(event: FocusEvent) => {- const isFocusWithin = event.currentTarget.contains(event.relatedTarget);- if (isFocusWithin === false) {- onSelect();- }- }}- onKeyDown={(event: KeyboardEvent) => {- if (event.code === "Enter") {- onChange?.(assetContainer);+ <>+ <input+ ref={replaceInputRef}+ type="file"+ accept={IMAGE_MIME_TYPES.join(", ")}+ hidden+ onChange={handleReplaceFile}+ />+ <AssetManagerThumbnail+ item={{ type: "asset", id: asset.id }}+ actions={displayedActions}+ interactions={interactions}+ selected={selected}+ forcedSelection={forcedSelection}+ thumbnailRef={(element) => {+ elementRef.current = element;+ onElementChange?.(element);+ }}+ title={alt}+ preview={+ assetType === "image" ? (+ <StyledWebstudioImage+ assetId={asset.id}+ name={asset.name}+ objectURL={+ assetContainer.status === "uploading"+ ? assetContainer.objectURL+ : undefined+ }+ alt={alt}+ width={64}+ />+ ) : assetType === "video" ? (+ <StyledWebstudioVideo+ src={+ assetContainer.status === "uploading"+ ? assetContainer.objectURL+ : wsVideoLoader({ src: asset.name })+ }+ />+ ) : (+ <GenericFilePreview ext={ext} format={asset.format} />+ )}- }}- >- <Thumbnail- onClick={() => {- onChange?.(assetContainer);+ label={asset.filename ?? basename}+ labelSuffix={`.${ext}`}+ path={folderPath}+ onPreviewClick={() => onChange?.(assetContainer)}+ onKeyDown={(event: KeyboardEvent) => {+ if (event.code === "Enter") {+ onChange?.(assetContainer);+ }}}+ header={+ assetContainer.status === "uploaded" ? (+ <AssetSettings+ asset={assetContainer.asset}+ open={settingsOpen}+ onOpenChange={(open) => {+ setSettingsOpen(open);+ }}+ onDelete={actions.delete}+ onReplace={actions.replace}+ >+ <AssetManagerThumbnailMenu+ actions={displayedActions}+ label={`Actions for ${formatAssetName(asset)}`}+ onPointerDown={() => interactions.onContextMenuSelection(item)}+ />+ </AssetSettings>+ ) : undefined+ }>- {assetType === "image" ? (- // Image files - show preview- <StyledWebstudioImage- assetId={asset.id}- name={asset.name}- objectURL={- assetContainer.status === "uploading"- ? assetContainer.objectURL- : undefined- }- alt={alt}- // width={64} used for Image optimizations it should be approximately equal to the width of the picture on the screen in px- width={64}- />- ) : assetType === "video" ? (- // Video files - show video thumbnail (first frame)- <StyledWebstudioVideo- src={- assetContainer.status === "uploading"- ? assetContainer.objectURL- : wsVideoLoader({ src: asset.name })- }- />- ) : (- // Other files - show icon based on category- <GenericFilePreview ext={ext} format={asset.format} />- )}- </Thumbnail>- <Flex css={{ width: "100%", paddingBottom: 4 }} justify="center">- <Text variant="tiny" truncate>- {asset.filename ?? basename}- </Text>- <Text variant="tiny">.{ext}</Text>- </Flex>+ {isUploading && <UploadingAnimation />}+ </AssetManagerThumbnail>{assetContainer.status === "uploaded" && (- <AssetInfo asset={assetContainer.asset} />+ <AssetDeleteDialog+ asset={assetContainer.asset}+ open={deleteOpen}+ onOpenChange={setDeleteOpen}+ />)}- {isUploading && <UploadingAnimation />}- </ThumbnailContainer>+ </>);};diff --git a/apps/builder/app/builder/shared/asset-manager/test-utils.tsx b/apps/builder/app/builder/shared/asset-manager/test-utils.tsxnew file mode 100644index 0000000000..e1fe26c420--- /dev/null+++ b/apps/builder/app/builder/shared/asset-manager/test-utils.tsx@@ -0,0 +1,26 @@+import type { ReactNode } from "react";+import { createRoot, type Root } from "react-dom/client";+import { act } from "react-dom/test-utils";++(+ globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }+).IS_REACT_ACT_ENVIRONMENT = true;++export const createAssetManagerTestRenderer = () => {+ let root: Root | undefined;++ return {+ render(element: ReactNode) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ root = createRoot(container);+ act(() => root?.render(element));+ return container;+ },+ cleanup() {+ act(() => root?.unmount());+ root = undefined;+ document.body.innerHTML = "";+ },+ };+};diff --git a/apps/builder/app/builder/shared/asset-manager/utils.test.ts b/apps/builder/app/builder/shared/asset-manager/utils.test.tsindex 155b23e4e2..a77520cf08 100644--- a/apps/builder/app/builder/shared/asset-manager/utils.test.ts+++ b/apps/builder/app/builder/shared/asset-manager/utils.test.ts@@ -6,6 +6,9 @@ import {calculateFormatCounts,filterAndSortAssets,findAssetIndex,+ getAssetManagerSelectionIndex,+ getNearestAssetManagerSelection,+ isAssetManagerSelectionVisible,sortAssets,getAssetFormat,type SortState,@@ -182,6 +185,16 @@ describe("filterAndSortAssets", () => {expect(result[0].asset.name).toBe("apple.jpg");});+ test("treats whitespace-only search as empty", () => {+ const result = filterAndSortAssets({+ assetContainers: containers,+ selectedExtensions: "*",+ searchQuery: " ",+ sortState: { sortBy: "createdAt", order: "asc" },+ });+ expect(result).toHaveLength(containers.length);+ });+test("applies both extension filter and search", () => {const sortState: SortState = { sortBy: "createdAt", order: "asc" };const result = filterAndSortAssets({@@ -237,6 +250,75 @@ describe("findAssetIndex", () => {});});+describe("asset manager selection", () => {+ const first = createAssetContainer(+ "first",+ "first.png",+ "png",+ "image",+ "2024-01-01"+ );+ const second = createAssetContainer(+ "second",+ "second.png",+ "png",+ "image",+ "2024-01-02"+ );++ test("tracks mixed folder and asset selections by id", () => {+ const folder = { type: "folder", id: "folder" } as const;+ const firstAsset = { type: "asset", id: first.asset.id } as const;+ const secondAsset = { type: "asset", id: second.asset.id } as const;+ expect(+ getAssetManagerSelectionIndex(+ [folder, firstAsset, secondAsset],+ secondAsset+ )+ ).toBe(2);+ expect(+ getAssetManagerSelectionIndex(+ [secondAsset, folder, firstAsset],+ secondAsset+ )+ ).toBe(0);+ });++ test("detects selections hidden by filtering", () => {+ expect(+ isAssetManagerSelectionVisible(+ { type: "asset", id: "second" },+ [first],+ []+ )+ ).toBe(false);+ expect(+ isAssetManagerSelectionVisible(+ { type: "folder", id: "nested" },+ [],+ [{ id: "sibling" }]+ )+ ).toBe(false);+ });++ test("selects the nearest remaining item after the focused item is removed", () => {+ const first = { type: "folder", id: "first" } as const;+ const removed = { type: "folder", id: "removed" } as const;+ const last = { type: "asset", id: "last" } as const;++ expect(+ getNearestAssetManagerSelection(+ [first, removed, last],+ [first, last],+ removed+ )+ ).toEqual(last);+ expect(+ getNearestAssetManagerSelection([first, last], [first], last)+ ).toEqual(first);+ });+});+describe("sortAssets", () => {const containers = [createAssetContainer("1", "zebra.jpg", "jpeg", "image", "2024-01-03"),diff --git a/apps/builder/app/builder/shared/asset-manager/utils.ts b/apps/builder/app/builder/shared/asset-manager/utils.tsindex 1b558ea43b..e00120d732 100644--- a/apps/builder/app/builder/shared/asset-manager/utils.ts+++ b/apps/builder/app/builder/shared/asset-manager/utils.ts@@ -5,6 +5,12 @@ import {doesAssetMatchMimePatterns,} from "@webstudio-is/sdk";import type { AssetContainer } from "../assets";+import {+ isSameAssetManagerSelection,+ type AssetManagerSelection,+} from "./asset-manager-selection";++export type { AssetManagerSelection } from "./asset-manager-selection";export type SortField = "name" | "size" | "createdAt";export type SortOrder = "asc" | "desc";@@ -140,8 +146,9 @@ export const filterAndSortAssets = ({}// Apply search- if (searchQuery !== "") {- filtered = matchSorter(filtered, searchQuery, {+ const normalizedSearchQuery = searchQuery.trim();+ if (normalizedSearchQuery !== "") {+ filtered = matchSorter(filtered, normalizedSearchQuery, {keys: [(item) => item.asset.name],});}@@ -162,3 +169,36 @@ export const findAssetIndex = (}return assetContainers.findIndex((item) => item.asset.id === assetId);};++export const getAssetManagerSelectionIndex = (+ items: AssetManagerSelection[],+ selection: AssetManagerSelection | undefined+) =>+ selection === undefined+ ? -1+ : items.findIndex((item) => isSameAssetManagerSelection(item, selection));++export const getNearestAssetManagerSelection = (+ previousItems: AssetManagerSelection[],+ nextItems: AssetManagerSelection[],+ selection: AssetManagerSelection | undefined+) => {+ if (selection === undefined || nextItems.length === 0) {+ return;+ }+ const previousIndex = getAssetManagerSelectionIndex(previousItems, selection);+ return nextItems[Math.min(Math.max(previousIndex, 0), nextItems.length - 1)];+};++export const isAssetManagerSelectionVisible = (+ selection: AssetManagerSelection | undefined,+ assetContainers: AssetContainer[],+ folders: Array<{ id: string }>+) => {+ if (selection === undefined) {+ return true;+ }+ return selection.type === "asset"+ ? findAssetIndex(assetContainers, selection.id) !== -1+ : folders.some(({ id }) => id === selection.id);+};diff --git a/apps/builder/app/builder/shared/assets/asset-panel-state.tsx b/apps/builder/app/builder/shared/assets/asset-panel-state.tsxnew file mode 100644index 0000000000..be7b300ee5--- /dev/null+++ b/apps/builder/app/builder/shared/assets/asset-panel-state.tsx@@ -0,0 +1,41 @@+import { Flex, Text, theme } from "@webstudio-is/design-system";+import { UploadIcon } from "@webstudio-is/icons";++export const AssetPanelState = ({+ message,+ description,+ active = false,+}: {+ message: string;+ description?: string;+ active?: boolean;+}) => (+ <Flex+ align="center"+ justify="center"+ direction="column"+ css={{+ flex: 1,+ minHeight: 0,+ margin: theme.spacing[4],+ color: active+ ? theme.colors.foregroundMain+ : theme.colors.foregroundSubtle,+ border: `1px dashed ${active ? theme.colors.foregroundMain : "transparent"}`,+ }}+ >+ <Flex align="center" gap={1} shrink={false}>+ <UploadIcon />+ <Text variant="regularBold">{message}</Text>+ </Flex>+ {description !== undefined && (+ <Text+ color="subtle"+ align="center"+ css={{ maxWidth: theme.spacing[28], marginTop: theme.spacing[2] }}+ >+ {description}+ </Text>+ )}+ </Flex>+);diff --git a/apps/builder/app/builder/shared/assets/asset-upload.test.tsx b/apps/builder/app/builder/shared/assets/asset-upload.test.tsxnew file mode 100644index 0000000000..324131b1ef--- /dev/null+++ b/apps/builder/app/builder/shared/assets/asset-upload.test.tsx@@ -0,0 +1,45 @@+import { createRef } from "react";+import { afterEach, expect, test, vi } from "vitest";+import { $authPermit } from "~/shared/nano-states";+import { createAssetManagerTestRenderer } from "../asset-manager/test-utils";+import {+ AssetUpload,+ groupFilesByAssetType,+ type AssetUploadHandle,+} from "./asset-upload";++const renderer = createAssetManagerTestRenderer();+afterEach(() => {+ renderer.cleanup();+ $authPermit.set("view");+ vi.restoreAllMocks();+});++test("opens the same file input from its imperative action", () => {+ $authPermit.set("build");+ const inputClick = vi+ .spyOn(HTMLInputElement.prototype, "click")+ .mockImplementation(() => {});+ const ref = createRef<AssetUploadHandle>();++ renderer.render(<AssetUpload ref={ref} type="file" folderId="folder" />);+ ref.current?.open();++ expect(inputClick).toHaveBeenCalledOnce();+});++test("groups upload files by their detected asset type", () => {+ const image = new File([], "image.png", { type: "image/png" });+ const video = new File([], "video.mp4", { type: "video/mp4" });+ const document = new File([], "document.pdf", {+ type: "application/pdf",+ });++ expect(groupFilesByAssetType([image, video, document])).toEqual(+ new Map([+ ["image", [image]],+ ["video", [video]],+ ["file", [document]],+ ])+ );+});diff --git a/apps/builder/app/builder/shared/assets/asset-upload.tsx b/apps/builder/app/builder/shared/assets/asset-upload.tsxindex 3f07db81dc..c98c17b6e2 100644--- a/apps/builder/app/builder/shared/assets/asset-upload.tsx+++ b/apps/builder/app/builder/shared/assets/asset-upload.tsx@@ -1,4 +1,9 @@-import { type ChangeEvent, useRef } from "react";+import {+ forwardRef,+ type ChangeEvent,+ useImperativeHandle,+ useRef,+} from "react";import { useStore } from "@nanostores/react";import { Button, Flex, Tooltip, toast } from "@webstudio-is/design-system";import { UploadIcon } from "@webstudio-is/icons";@@ -21,7 +26,18 @@ export const validateFiles = (files: File[]) => {return files.filter((file) => file.size <= maxSize);};-const useUpload = () => {+export const groupFilesByAssetType = (files: readonly File[]) => {+ const filesByType = new Map<AssetType, File[]>();+ for (const file of files) {+ const type = detectAssetType(file.name);+ const groupedFiles = filesByType.get(type) ?? [];+ groupedFiles.push(file);+ filesByType.set(type, groupedFiles);+ }+ return filesByType;+};++const useUpload = (folderId?: string) => {const inputRef = useRef<HTMLInputElement | null>(null);const onChange = (event: ChangeEvent<HTMLFormElement>) => {@@ -32,19 +48,8 @@ const useUpload = () => {}const files = validateFiles(Array.from(input?.files ?? []));- // Group files by their detected type- const filesByType = new Map<AssetType, File[]>();- for (const file of files) {- const detectedType = detectAssetType(file.name);- if (!filesByType.has(detectedType)) {- filesByType.set(detectedType, []);- }- filesByType.get(detectedType)!.push(file);- }-- // Upload each group with the correct type- for (const [detectedType, filesOfType] of filesByType) {- uploadAssets(detectedType, filesOfType);+ for (const [detectedType, filesOfType] of groupFilesByAssetType(files)) {+ uploadAssets(detectedType, filesOfType, { folderId });}form.reset();@@ -105,48 +110,69 @@ export const acceptUploadType = (type AssetUploadProps = {type: AssetType;accept?: string;+ folderId?: string;};-const EnabledAssetUpload = ({ accept, type }: AssetUploadProps) => {- const { inputRef, onChange } = useUpload();-- return (- <form onChange={onChange}>- <input- accept={accept ?? acceptMap[type]}- type="file"- name={type}- multiple- ref={inputRef}- style={{ display: "none" }}- />- <Button- aria-label="Upload asset"- color="ghost"- type="button"- onClick={() => inputRef?.current?.click()}- prefix={<UploadIcon />}- ></Button>- </form>- );+export type AssetUploadHandle = {+ open: () => void;};-export const AssetUpload = ({ type, accept }: AssetUploadProps) => {- const authPermit = useStore($authPermit);-- if (authPermit !== "view") {- // Split into a separate component to avoid using `useUpload` hook unnecessarily- // (It's hard to mock this hook in storybook)- return <EnabledAssetUpload type={type} accept={accept} />;+const EnabledAssetUpload = forwardRef<AssetUploadHandle, AssetUploadProps>(+ ({ accept, type, folderId }, forwardedRef) => {+ const { inputRef, onChange } = useUpload(folderId);+ useImperativeHandle(forwardedRef, () => ({+ open: () => inputRef.current?.click(),+ }));++ return (+ <form onChange={onChange}>+ <input+ accept={accept ?? acceptMap[type]}+ type="file"+ name={type}+ multiple+ ref={inputRef}+ style={{ display: "none" }}+ />+ <Button+ aria-label="Upload asset"+ color="ghost"+ type="button"+ onClick={() => inputRef?.current?.click()}+ prefix={<UploadIcon />}+ ></Button>+ </form>+ );}+);+EnabledAssetUpload.displayName = "EnabledAssetUpload";++export const AssetUpload = forwardRef<AssetUploadHandle, AssetUploadProps>(+ ({ type, accept, folderId }, forwardedRef) => {+ const authPermit = useStore($authPermit);++ if (authPermit !== "view") {+ // Split into a separate component to avoid using `useUpload` hook unnecessarily+ // (It's hard to mock this hook in storybook)+ return (+ <EnabledAssetUpload+ ref={forwardedRef}+ type={type}+ accept={accept}+ folderId={folderId}+ />+ );+ }- return (- <Flex>- <Tooltip side="bottom" content="View mode. You can't upload assets.">- <Button css={{ flexGrow: 1 }} prefix={<UploadIcon />} disabled={true}>- Upload- </Button>- </Tooltip>- </Flex>- );-};+ return (+ <Flex>+ <Tooltip side="bottom" content="View mode. You can't upload assets.">+ <Button css={{ flexGrow: 1 }} prefix={<UploadIcon />} disabled={true}>+ Upload+ </Button>+ </Tooltip>+ </Flex>+ );+ }+);+AssetUpload.displayName = "AssetUpload";diff --git a/apps/builder/app/builder/shared/assets/asset-utils.test.ts b/apps/builder/app/builder/shared/assets/asset-utils.test.tsindex bbfb92fa35..ad88e39da2 100644--- a/apps/builder/app/builder/shared/assets/asset-utils.test.ts+++ b/apps/builder/app/builder/shared/assets/asset-utils.test.ts@@ -130,6 +130,23 @@ describe("detectAssetType", () => {});describe("uploadingFileDataToAsset", () => {+ test("preserves the upload destination folder in the preview asset", () => {+ const result = uploadingFileDataToAsset({+ source: "file",+ file: new File(["content"], "document.pdf", {+ type: "application/pdf",+ }),+ assetId: "test-id",+ fingerprintId: "test-fingerprint",+ uploadName: "test-upload-name",+ type: "file",+ objectURL: "blob:test",+ folderId: "folder-id",+ });++ expect(result.folderId).toBe("folder-id");+ });+test("extracts format from MIME type for font with valid MIME", () => {const file = new File(["content"], "InterVariable.woff2", {type: "font/woff2",diff --git a/apps/builder/app/builder/shared/assets/asset-utils.ts b/apps/builder/app/builder/shared/assets/asset-utils.tsindex 462e1130d1..6f7e767b84 100644--- a/apps/builder/app/builder/shared/assets/asset-utils.ts+++ b/apps/builder/app/builder/shared/assets/asset-utils.ts@@ -116,35 +116,21 @@ export const uploadingFileDataToAsset = (}const assetType = detectAssetType(fileName);-- if (assetType === "video") {- // Videos should be file type, not image type- const asset: Asset = {- id: fileData.assetId,- name: fileName,- format,- type: "file",- description: "",- createdAt: "",- projectId: "",- size: 0,- meta: {},- };-- return asset;- }+ const base = {+ id: fileData.assetId,+ name: fileName,+ description: "",+ createdAt: "",+ projectId: "",+ size: 0,+ folderId: fileData.folderId,+ };if (assetType === "image") {const asset: ImageAsset = {- id: fileData.assetId,- name: fileName,+ ...base,format,type: "image",- description: "",- createdAt: "",- projectId: "",- size: 0,-meta: {width: Number.NaN,height: Number.NaN,@@ -156,14 +142,9 @@ export const uploadingFileDataToAsset = (if (assetType === "font") {const asset: FontAsset = {- id: fileData.assetId,- name: fileName,+ ...base,format: format as FontAsset["format"],type: "font",- description: "",- createdAt: "",- projectId: "",- size: 0,meta: {family: "system",style: "normal",@@ -174,16 +155,11 @@ export const uploadingFileDataToAsset = (return asset;}- // Default to file type for all other types (documents, code, audio, etc.)+ // Videos and other non-image/font uploads use the generic file type.const asset: Asset = {- id: fileData.assetId,- name: fileName,+ ...base,format,type: "file",- description: "",- createdAt: "",- projectId: "",- size: 0,meta: {},};diff --git a/apps/builder/app/builder/shared/assets/assets-shell.test.tsx b/apps/builder/app/builder/shared/assets/assets-shell.test.tsxnew file mode 100644index 0000000000..d39c786d92--- /dev/null+++ b/apps/builder/app/builder/shared/assets/assets-shell.test.tsx@@ -0,0 +1,60 @@+import { act } from "react-dom/test-utils";+import { afterEach, describe, expect, test } from "vitest";+import {+ ContextMenuContent,+ ContextMenuItem,+} from "@webstudio-is/design-system";+import { createAssetManagerTestRenderer } from "../asset-manager/test-utils";+import { AssetsShell } from "./assets-shell";++Object.defineProperty(globalThis, "DOMRect", {+ configurable: true,+ value: {+ fromRect: ({ x = 0, y = 0, width = 0, height = 0 }: DOMRectInit = {}) => ({+ x,+ y,+ width,+ height,+ top: y,+ right: x + width,+ bottom: y + height,+ left: x,+ }),+ },+});++const renderer = createAssetManagerTestRenderer();+afterEach(renderer.cleanup);++describe("AssetsShell", () => {+ test("opens its context menu from panel chrome outside the asset list", () => {+ const container = renderer.render(+ <AssetsShell+ searchProps={{}}+ isEmpty={false}+ type="file"+ contextMenu={+ <ContextMenuContent>+ <ContextMenuItem>Paste</ContextMenuItem>+ </ContextMenuContent>+ }+ >+ <div>Asset list</div>+ </AssetsShell>+ );++ const search = container.querySelector("input");+ act(() => {+ search?.dispatchEvent(+ new MouseEvent("contextmenu", {+ bubbles: true,+ cancelable: true,+ clientX: 10,+ clientY: 10,+ })+ );+ });++ expect(document.body.textContent).toContain("Paste");+ });+});diff --git a/apps/builder/app/builder/shared/assets/assets-shell.tsx b/apps/builder/app/builder/shared/assets/assets-shell.tsxindex 8969f29800..f2989776e8 100644--- a/apps/builder/app/builder/shared/assets/assets-shell.tsx+++ b/apps/builder/app/builder/shared/assets/assets-shell.tsx@@ -4,18 +4,23 @@ import {useState,type ComponentProps,type JSX,+ type PointerEvent,} from "react";import type { AssetType } from "@webstudio-is/asset-uploader";import {+ ContextMenu,+ ContextMenuTrigger,Flex,ScrollArea,SearchField,- Text,theme,} from "@webstudio-is/design-system";-import { acceptUploadType, validateFiles } from "./asset-upload";-import { detectAssetType } from "@webstudio-is/sdk";-import { NotFound } from "./not-found";+import {+ acceptUploadType,+ groupFilesByAssetType,+ validateFiles,+} from "./asset-upload";+import { AssetPanelState } from "./asset-panel-state";import { Separator } from "./separator";import { combine } from "@atlaskit/pragmatic-drag-and-drop/combine";import {@@ -26,7 +31,6 @@ import { dropTargetForExternal } from "@atlaskit/pragmatic-drag-and-drop/externaimport invariant from "tiny-invariant";import type { ContainsSource } from "@atlaskit/pragmatic-drag-and-drop/dist/types/public-utils/external/native-types";import { uploadAssets } from "./upload-assets";-import { UploadIcon } from "@webstudio-is/icons";import {IDLE,isBlockedByBackdrop,@@ -39,9 +43,22 @@ type AssetsShellProps = {filters?: JSX.Element;searchProps: ComponentProps<typeof SearchField>;children: JSX.Element;+ interactionOverlay?: JSX.Element;+ footer?: JSX.Element;type: AssetType;accept?: string;isEmpty: boolean;+ emptyMessage?: string;+ emptyContent?: JSX.Element;+ folderId?: string;+ contextMenu?: JSX.Element;+ onContextMenu?: ComponentProps<typeof Flex>["onContextMenu"];+ onPointerDown?: (+ event: PointerEvent<HTMLElement>,+ listViewport: HTMLElement | null+ ) => void;+ onKeyDown?: ComponentProps<typeof Flex>["onKeyDown"];+ onElementChange?: (element: HTMLDivElement | null) => void;};const containsFilesOrUri = (parameter: ContainsSource) => {@@ -57,11 +74,22 @@ export const AssetsShell = ({filters,searchProps,isEmpty,+ emptyMessage = "Drop files here",+ emptyContent,children,+ interactionOverlay,+ footer,+ folderId,+ contextMenu,+ onContextMenu,+ onPointerDown,+ onKeyDown,+ onElementChange,type,accept,}: AssetsShellProps) => {- const ref = useRef<HTMLDivElement>(null);+ const ref = useRef<HTMLDivElement | null>(null);+ const listViewportRef = useRef<HTMLDivElement | null>(null);const [monitorState, setMonitorState] =useState<ExternalMonitorDragState>(IDLE);@@ -147,37 +175,35 @@ export const AssetsShell = ({return false;});- // Group files by their detected type- const filesByType = new Map<string, File[]>();- for (const file of files) {- const detectedType = detectAssetType(file.name);- if (!filesByType.has(detectedType)) {- filesByType.set(detectedType, []);- }- filesByType.get(detectedType)!.push(file);- }-- // Upload each group with the correct type- for (const [detectedType, filesOfType] of filesByType) {- uploadAssets(detectedType as AssetType, filesOfType);+ for (const [detectedType, filesOfType] of groupFilesByAssetType(+ files+ )) {+ uploadAssets(detectedType, filesOfType, { folderId });}- uploadAssets(type, droppedUrls);+ uploadAssets(type, droppedUrls, { folderId });},}));- }, [accept, containsByType, type]);+ }, [accept, containsByType, folderId, type]);const dragState = Math.max(monitorState, dropTargetState);- return (+ const shell = (<Flex- ref={ref}+ ref={(element) => {+ ref.current = element;+ onElementChange?.(element);+ }}+ onPointerDown={(event) => onPointerDown?.(event, listViewportRef.current)}+ onContextMenu={onContextMenu}+ onKeyDown={onKeyDown}direction="column"css={{overflow: "hidden",paddingBlock: theme.panel.paddingBlock,flex: 1,+ minHeight: 0,position: "relative",}}>@@ -196,39 +222,63 @@ export const AssetsShell = ({{filters}</Flex><Separator />- {isEmpty && <NotFound />}- <ScrollArea css={{ display: "flex", flexDirection: "column" }}>- {children}- </ScrollArea>+ {isEmpty ? (+ <Flex direction="column" css={{ flex: 1, minHeight: 0 }}>+ {emptyContent}+ <AssetPanelState+ message={emptyMessage}+ active={dragState === OVER}+ description={+ emptyMessage === "Drop files here"+ ? "Drop files from anywhere into this panel."+ : undefined+ }+ />+ </Flex>+ ) : (+ <ScrollArea+ ref={listViewportRef}+ css={{+ display: "flex",+ flexDirection: "column",+ flex: 1,+ minHeight: 0,+ }}+ >+ {children}+ </ScrollArea>+ )}+ {interactionOverlay}+ {footer}<Flexcss={{position: "absolute",inset: 0,- display: dragState !== IDLE ? "flex" : "none",+ display: dragState !== IDLE && isEmpty === false ? "flex" : "none",backgroundColor: theme.colors.backgroundPanel,- opacity: 0.85,color:dragState === OVER? theme.colors.foregroundMain: theme.colors.foregroundSubtle,}}>- <Flex- align="center"- justify="center"- css={{- position: "absolute",- inset: theme.spacing[4],- border: `2px dashed ${dragState === OVER ? theme.colors.foregroundMain : theme.colors.foregroundMoreSubtle}`,- }}- >- <Flex align={"center"} gap={1}>- <UploadIcon />-- <Text variant={"regularBold"}>Drop files here</Text>- </Flex>- </Flex>+ <AssetPanelState+ message="Drop files here"+ description="Drop files from anywhere into this panel."+ active={dragState === OVER}+ /></Flex></Flex>);++ if (contextMenu === undefined) {+ return shell;+ }++ return (+ <ContextMenu>+ <ContextMenuTrigger asChild>{shell}</ContextMenuTrigger>+ {contextMenu}+ </ContextMenu>+ );};diff --git a/apps/builder/app/builder/shared/assets/not-found.tsx b/apps/builder/app/builder/shared/assets/not-found.tsxdeleted file mode 100644index 599a7143c3..0000000000--- a/apps/builder/app/builder/shared/assets/not-found.tsx+++ /dev/null@@ -1,9 +0,0 @@-import { Flex, Text } from "@webstudio-is/design-system";--export const NotFound = () => {- return (- <Flex align="center" justify="center" css={{ height: 100 }}>- <Text>No matching assets</Text>- </Flex>- );-};diff --git a/apps/builder/app/builder/shared/assets/types.ts b/apps/builder/app/builder/shared/assets/types.tsindex a9427a0705..28e0fe62c8 100644--- a/apps/builder/app/builder/shared/assets/types.ts+++ b/apps/builder/app/builder/shared/assets/types.ts@@ -2,7 +2,7 @@ import type { Asset } from "@webstudio-is/sdk";type PreviewAsset = Pick<Asset,- "name" | "filename" | "id" | "format" | "description" | "type"+ "name" | "filename" | "id" | "format" | "description" | "type" | "folderId">;export type UploadedAssetContainer = {diff --git a/apps/builder/app/builder/shared/assets/upload-assets.test.ts b/apps/builder/app/builder/shared/assets/upload-assets.test.tsindex 23019b52b8..6da71b49b0 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.test.ts+++ b/apps/builder/app/builder/shared/assets/upload-assets.test.ts@@ -6,7 +6,8 @@ vi.mock("~/shared/fetch.client", () => ({fetch: vi.fn(),}));-const { createUploadTicket, deduplicateAssetName, uploadAsset } = __testing__;+const { createUploadTicket, deduplicateAssetName, getFilesData, uploadAsset } =+ __testing__;const fetchMock = vi.mocked(fetch);describe("upload-assets", () => {@@ -61,6 +62,20 @@ describe("upload-assets", () => {expect(onError).toHaveBeenCalledWith("network down");});+ test("keeps the selected folder throughout upload preparation", async () => {+ const [fileData] = await getFilesData(+ "image",+ [new URL("https://example.com/image.png")],+ "folder-id"+ );++ expect(fileData).toMatchObject({+ source: "url",+ folderId: "folder-id",+ url: "https://example.com/image.png",+ });+ });+describe("deduplicateAssetName", () => {test("returns original name when no duplicates exist", () => {const existingNames = new Set(["other-file.png", "another-file.jpg"]);diff --git a/apps/builder/app/builder/shared/assets/upload-assets.tsx b/apps/builder/app/builder/shared/assets/upload-assets.tsxindex 6995e4792a..88d90e92dc 100644--- a/apps/builder/app/builder/shared/assets/upload-assets.tsx+++ b/apps/builder/app/builder/shared/assets/upload-assets.tsx@@ -13,7 +13,7 @@ import {$uploadingFilesDataStore,type UploadingFileData,} from "~/shared/nano-states";-import { $assets } from "~/shared/sync/data-stores";+import { $assetFolders, $assets } from "~/shared/sync/data-stores";import { $project } from "~/shared/sync/data-stores";import { onNextTransactionComplete } from "~/shared/sync/project-queue";import { invalidateAssets } from "~/shared/resources";@@ -54,9 +54,13 @@ const safeSetAsset = (asset: Asset, projectId: string) => {return;}+ const folderId =+ asset.folderId !== undefined && $assetFolders.get().has(asset.folderId)+ ? asset.folderId+ : undefined;executeRuntimeMutation({id: "assets.add",- input: { asset },+ input: { asset: { ...asset, folderId } },});onNextTransactionComplete(() => {@@ -66,7 +70,8 @@ const safeSetAsset = (asset: Asset, projectId: string) => {const getFilesData = async <T extends File | URL>(type: AssetType,- filesOrUrls: T[]+ filesOrUrls: T[],+ folderId?: string): Promise<UploadingFileData[]> => {const filesData: UploadingFileData[] = [];for (const fileOrUrl of filesOrUrls) {@@ -80,6 +85,7 @@ const getFilesData = async <T extends File | URL>(type,file: fileOrUrl,objectURL: URL.createObjectURL(fileOrUrl),+ folderId,});continue;}@@ -93,6 +99,7 @@ const getFilesData = async <T extends File | URL>(type,url: fileOrUrl.href,objectURL: fileOrUrl.href,+ folderId,});}@@ -260,7 +267,8 @@ const createUploadTicket = async ({const handleAfterSubmit = (assetId: string,data: AssetActionResponse,- projectId: string+ projectId: string,+ folderId?: string) => {warnOnce(data.uploadedAssets?.length !== 1,@@ -278,7 +286,7 @@ const handleAfterSubmit = (// update store with new asset and set current idsafeSetAsset(- { ...uploadedAsset, id: uploadedAsset.id || assetId },+ { ...uploadedAsset, id: uploadedAsset.id || assetId, folderId },projectId);};@@ -348,7 +356,7 @@ const processUpload = async (onCompleted: (data) => {URL.revokeObjectURL(fileData.objectURL);deleteUploadingFileData(assetId);- handleAfterSubmit(assetId, data, projectId);+ handleAfterSubmit(assetId, data, projectId, fileData.folderId);},onError: (error) => {URL.revokeObjectURL(fileData.objectURL);@@ -364,7 +372,8 @@ const processUpload = async (export const uploadAssets = async <T extends File | URL>(type: AssetType,- filesOrUrls: T[]+ filesOrUrls: T[],+ options: { folderId?: string } = {}): Promise<Map<T, string>> => {const projectId = $project.get()?.id;const authToken = $authToken.get();@@ -372,7 +381,7 @@ export const uploadAssets = async <T extends File | URL>(return new Map();}- const filesData = await getFilesData(type, filesOrUrls);+ const filesData = await getFilesData(type, filesOrUrls, options.folderId);// Filter out duplicates inside filesDataconst uniqFilesDataMap = new Map(@@ -459,5 +468,6 @@ export const uploadAssets = async <T extends File | URL>(export const __testing__ = {createUploadTicket,deduplicateAssetName,+ getFilesData,uploadAsset,};diff --git a/apps/builder/app/routes/rest.assets_.$name.tsx b/apps/builder/app/routes/rest.assets_.$name.tsxindex 5893076cb8..7c8d0ddf7b 100644--- a/apps/builder/app/routes/rest.assets_.$name.tsx+++ b/apps/builder/app/routes/rest.assets_.$name.tsx@@ -78,6 +78,7 @@ export const action = async (props: ActionFunctionArgs) => {const url = new URL(request.url);const projectId = url.searchParams.get("projectId");+ const folderId = url.searchParams.get("folderId") ?? undefined;const rawAssetType = url.searchParams.get("type");const isApiUpload = projectId !== null || rawAssetType !== null;@@ -120,6 +121,7 @@ export const action = async (props: ActionFunctionArgs) => {projectId,type: assetType,filename: params.name,+ folderId,},context);diff --git a/apps/builder/app/services/api-router.server.test.ts b/apps/builder/app/services/api-router.server.test.tsindex c66b878e2b..4861d1838e 100644--- a/apps/builder/app/services/api-router.server.test.ts+++ b/apps/builder/app/services/api-router.server.test.ts@@ -18,6 +18,7 @@ import {} from "@webstudio-is/trpc-interface/index.server";import { db as authDb } from "@webstudio-is/authorization-token/index.server";import { blockComponent } from "@webstudio-is/sdk";+import * as assetUploader from "@webstudio-is/asset-uploader/index.server";import { apiRouter, __testing__ } from "./api-router.server";import {getApiRouterProcedures,@@ -102,6 +103,43 @@ describe("api router build operation adapters", () => {});});+ test("loads assets and folders together for build snapshots", async () => {+ const build = {+ id: "build-1",+ projectId: "project-1",+ version: 1,+ pages: createDefaultPages({ rootInstanceId: "root" }),+ } as unknown as Awaited<+ ReturnType<typeof projectBuild.loadDevBuildByProjectId>+ >;+ const asset = { id: "asset-1", folderId: "folder-1" };+ const folder = { id: "folder-1", name: "Images" };+ vi.spyOn(authDb, "getTokenInfo").mockResolvedValue(createToken());+ vi.spyOn(authorizeProject, "hasProjectPermit").mockResolvedValue(true);+ vi.spyOn(projectBuild, "loadDevBuildByProjectId").mockResolvedValue(build);+ const loadAssetData = vi+ .spyOn(assetUploader, "loadAssetDataByProject")+ .mockResolvedValue({ assets: [asset], assetFolders: [folder] } as never);+ const loadFolders = vi.spyOn(assetUploader, "loadAssetFoldersByProject");++ const caller = createCaller({+ ...createContext(true),+ apiClient: { type: "cli", version: "0.276.0" },+ });++ await expect(+ caller.build.get({+ projectId: "project-1",+ include: ["assets", "assetFolders"],+ })+ ).resolves.toMatchObject({+ assets: [asset],+ assetFolders: [folder],+ });+ expect(loadAssetData).toHaveBeenCalledOnce();+ expect(loadFolders).not.toHaveBeenCalled();+ });+test("public operation catalog paths exist on the api router", () => {const procedures = getApiRouterProcedures(apiRouter);diff --git a/apps/builder/app/services/api-router.server.ts b/apps/builder/app/services/api-router.server.tsindex daf34cec62..3eb9c703a3 100644--- a/apps/builder/app/services/api-router.server.ts+++ b/apps/builder/app/services/api-router.server.ts@@ -27,7 +27,10 @@ import {paginateOutput,paginatedOutputInputSchema,} from "@webstudio-is/project-build/runtime";-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";+import {+ loadAssetDataByProject,+ loadAssetFoldersByProject,+} from "@webstudio-is/asset-uploader/index.server";import { buildPatchTransaction } from "@webstudio-is/protocol/schema";import {publicApiContractVersion,@@ -40,7 +43,7 @@ import {loadApiToken,} from "./api-permits.server";import { componentMetas } from "~/shared/component-metas.server";-import { type Asset } from "@webstudio-is/sdk";+import { type Asset, type AssetFolder } from "@webstudio-is/sdk";import {applyContentModeTransaction,getContentModeCapabilities,@@ -299,12 +302,14 @@ const commitRuntimeMutation = async <id,build,assets,+ assetFolders,input,commit,}: {id: RuntimeOperationId;build: Awaited<ReturnType<typeof loadDevBuildByProjectId>>;assets?: Asset[];+ assetFolders?: AssetFolder[];input: unknown;commit: BuildCommit;}) => {@@ -312,6 +317,7 @@ const commitRuntimeMutation = async <id,build,assets,+ assetFolders,input,});if (mutation.noop || mutation.payload.length === 0) {@@ -417,16 +423,23 @@ const runtimeContentOrBuildMutation = <}));+const loadRuntimeAssetData = async (ctx: AppContext, projectId: string) => {+ return loadAssetDataByProject(projectId, ctx, {+ skipPermissionsCheck: true,+ });+};+const runtimeAssetsQuery = <Result = unknown>(id: RuntimeOperationId) =>projectQuery(runtimeProjectInput(id), "view", async ({ ctx, input }) => {- const assets = await loadAssetsByProject(input.projectId, ctx, {- skipPermissionsCheck: true,- });- const build = await loadDevBuildByProjectId(ctx, input.projectId);+ const [{ assets, assetFolders }, build] = await Promise.all([+ loadRuntimeAssetData(ctx, input.projectId),+ loadDevBuildByProjectId(ctx, input.projectId),+ ]);return executeApiRuntimeOperation<Result>({id,build,assets,+ assetFolders,input,});});@@ -437,13 +450,15 @@ const runtimeAssetsMutation = <Result extends Record<string, unknown> = {}>(buildMutation(runtimeMutationInput(id, true),async ({ ctx, input, build, commit }) => {- const assets = await loadAssetsByProject(input.projectId, ctx, {- skipPermissionsCheck: true,- });+ const { assets, assetFolders } = await loadRuntimeAssetData(+ ctx,+ input.projectId+ );return await commitRuntimeMutation<Result>({id,build,assets,+ assetFolders,input,commit,});@@ -633,7 +648,19 @@ export const apiRouter = router({projectId: input.projectId,});if (include.has("assets")) {- snapshot.assets = await loadAssetsByProject(input.projectId, ctx);+ const { assets, assetFolders } = await loadAssetDataByProject(+ input.projectId,+ ctx+ );+ snapshot.assets = assets;+ if (include.has("assetFolders")) {+ snapshot.assetFolders = assetFolders;+ }+ } else if (include.has("assetFolders")) {+ snapshot.assetFolders = await loadAssetFoldersByProject(+ input.projectId,+ ctx+ );}return snapshot;diff --git a/apps/builder/app/services/api-runtime.server.ts b/apps/builder/app/services/api-runtime.server.tsindex f3dd5cfeee..9c6602a185 100644--- a/apps/builder/app/services/api-runtime.server.ts+++ b/apps/builder/app/services/api-runtime.server.ts@@ -6,32 +6,37 @@ import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";import type { BuilderState } from "@webstudio-is/project-build/state";import { createBuilderStateFromCompactBuild } from "@webstudio-is/project-build/state";-import { type Asset } from "@webstudio-is/sdk";+import { type Asset, type AssetFolder } from "@webstudio-is/sdk";import { throwApiError } from "./api-errors.server";export const createBuilderRuntimeState = (build: CompactBuild,- assets?: Asset[]+ assets?: Asset[],+ assetFolders?: AssetFolder[]): BuilderState =>createBuilderStateFromCompactBuild(- assets === undefined ? build : { ...build, assets }+ assets === undefined && assetFolders === undefined+ ? build+ : { ...build, assets, assetFolders });export const executeApiRuntimeOperation = async <Result>({id,build,assets,+ assetFolders,input,}: {id: RuntimeOperationId;build: CompactBuild;assets?: Asset[];+ assetFolders?: AssetFolder[];input: unknown;}): Promise<Result> => {try {return await executeBuilderRuntimeOperation<Result>({id,- state: createBuilderRuntimeState(build, assets),+ state: createBuilderRuntimeState(build, assets, assetFolders),input,context: {createId: builderRuntimeContext.createId,@@ -60,5 +65,6 @@ export const executeApiRuntimeMutation = <id: RuntimeOperationId;build: CompactBuild;assets?: Asset[];+ assetFolders?: AssetFolder[];input: unknown;}) => executeApiRuntimeOperation<BuilderRuntimeMutation<Result>>(args);diff --git a/apps/builder/app/services/build-router.server.ts b/apps/builder/app/services/build-router.server.tsindex 44947692c4..c533467373 100644--- a/apps/builder/app/services/build-router.server.ts+++ b/apps/builder/app/services/build-router.server.ts@@ -22,7 +22,7 @@ import type { BuildPatchTransaction } from "@webstudio-is/project/index.server";import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";import { parseWebstudioJsxFragment } from "@webstudio-is/project-build/transfer/server";import { serializePages } from "@webstudio-is/project-migrations/pages";-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";+import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/index.server";import {checkProjectBuildPermissionInput,importProjectBundleInput,@@ -230,13 +230,15 @@ export const loadBuilderDataByProjectId = async (throw new Error("Project must have project userId defined");}- const build = await loadDevBuildByProjectId(ctx, project.id);- const assets = await loadAssetsByProject(project.id, ctx);+ const [build, assetData] = await Promise.all([+ loadDevBuildByProjectId(ctx, project.id),+ loadAssetDataByProject(project.id, ctx),+ ]);return {...build,pages: serializePages(build.pages),- assets,+ ...assetData,project,publisherHost: env.PUBLISHER_HOST,};diff --git a/apps/builder/app/services/project-import.server.test.ts b/apps/builder/app/services/project-import.server.test.tsindex 433490fa10..4e30e174a4 100644--- a/apps/builder/app/services/project-import.server.test.ts+++ b/apps/builder/app/services/project-import.server.test.ts@@ -5,6 +5,7 @@ import {createPublishedProjectBundleFixture,} from "@webstudio-is/protocol/fixtures";import { type PublishedProjectBundle } from "@webstudio-is/protocol";+import { createAssetRows } from "@webstudio-is/asset-uploader/index.server";import {__testing__,importPublishedProjectBundle,@@ -13,10 +14,10 @@ import {const {assertBundleVersion,assertImportedAssetFilesUploaded,+ normalizeImportedAssetFolderData,assertImportedAssetNames,assertProjectBuildPermit,createBuildImportUpdate,- createImportedAssetRows,getImportedPreviewImageAssetId,} = __testing__;@@ -85,6 +86,7 @@ const createPostgrestClient = (options: {existingFileNames?: string[];fileFilters?: [string, string][];+ insertedFolders?: Array<{ id: string; projectId: string }>;} = {}) => ({from: (table: string) => {@@ -160,6 +162,22 @@ const createPostgrestClient = (};}+ if (table === "AssetFolder") {+ return {+ delete: () => ({+ eq: async () => {+ calls.push("asset-folders-delete");+ return { error: undefined };+ },+ }),+ insert: async (rows: Array<{ id: string; projectId: string }>) => {+ calls.push("asset-folders-insert");+ options.insertedFolders?.push(...rows);+ return { error: undefined };+ },+ };+ }+throw new Error(`Unexpected table ${table}`);},});@@ -243,8 +261,8 @@ describe("build import helpers", () => {test("remaps imported asset rows to destination project", () => {expect(- createImportedAssetRows({- assets: [+ createAssetRows(+ [createData().assets[0],{...createData().assets[0],@@ -253,8 +271,8 @@ describe("build import helpers", () => {description: undefined,},],- projectId: "destination-project",- })+ "destination-project"+ )).toEqual([{id: "asset-1",@@ -262,6 +280,7 @@ describe("build import helpers", () => {name: "image.png",filename: "Image",description: "Hero image",+ folderId: null,},{id: "asset-2",@@ -269,10 +288,56 @@ describe("build import helpers", () => {name: "image.png",filename: null,description: null,+ folderId: null,},]);});+ test("validates folder hierarchy and moves orphaned assets to root", () => {+ const parent = {+ id: "parent",+ projectId: "source-project",+ name: "Parent",+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ const child = { ...parent, id: "child", name: "Child", parentId: "parent" };++ expect(() =>+ normalizeImportedAssetFolderData(+ [child, parent],+ [{ ...createData().assets[0], folderId: "child" }]+ )+ ).not.toThrow();+ expect(() =>+ normalizeImportedAssetFolderData(+ [parent],+ [{ ...createData().assets[0], folderId: "missing" }]+ )+ ).not.toThrow();+ expect(+ normalizeImportedAssetFolderData(+ [parent],+ [{ ...createData().assets[0], folderId: "missing" }]+ ).assets[0]+ ).not.toHaveProperty("folderId");+ });++ test("normalizes imported asset folder names", () => {+ const normalized = normalizeImportedAssetFolderData(+ [+ {+ id: "folder",+ projectId: "source-project",+ name: " Media ",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ []+ );++ expect(normalized.folders[0]?.name).toBe("Media");+ });+test("updates the build before replacing asset rows", async () => {const calls: string[] = [];@@ -300,11 +365,45 @@ describe("build import helpers", () => {"build-update","project-preview-reset","assets-delete",+ "asset-folders-delete","assets-insert","project-preview-update",]);});+ test("inserts the complete folder hierarchy in one request", async () => {+ const calls: string[] = [];+ const insertedFolders: Array<{ id: string; projectId: string }> = [];+ const parent = {+ id: "parent",+ projectId: "source-project",+ name: "Parent",+ createdAt: "2026-01-01T00:00:00.000Z",+ };+ const child = { ...parent, id: "child", name: "Child", parentId: "parent" };++ await importPublishedProjectBundle(+ {+ ctx: {+ postgrest: {+ client: createPostgrestClient(calls, { insertedFolders }),+ },+ } as never,+ data: createData({ assets: [], assetFolders: [child, parent] }),+ projectId: "target-project",+ },+ { hasProjectPermit, loadDevBuildByProjectId }+ );++ expect(calls.filter((call) => call === "asset-folders-insert")).toEqual([+ "asset-folders-insert",+ ]);+ expect(insertedFolders).toEqual([+ { ...parent, projectId: "target-project", parentId: null },+ { ...child, projectId: "target-project" },+ ]);+ });+test("allows importing data without version when check is explicitly ignored", async () => {const calls: string[] = [];diff --git a/apps/builder/app/services/project-import.server.ts b/apps/builder/app/services/project-import.server.tsindex 2c2587646c..562a85a06d 100644--- a/apps/builder/app/services/project-import.server.ts+++ b/apps/builder/app/services/project-import.server.ts@@ -9,6 +9,10 @@ import {serializeStyles,serializeStyleSourceSelections,} from "@webstudio-is/project-build/persistence";+import {+ createAssetFolderRows,+ createAssetRows,+} from "@webstudio-is/asset-uploader/index.server";import { loadDevBuildByProjectId } from "@webstudio-is/project-build/server";import {migratePages,@@ -28,7 +32,10 @@ import {} from "@webstudio-is/protocol";import {getHomePage,+ normalizeAssetFolderData,+ assetFolders as assetFoldersSchema,type Asset,+ type AssetFolder,type Breakpoint,type DataSource,type Instance,@@ -147,6 +154,21 @@ const assertImportedAssets = (assets: Asset[]) => {assertImportedAssetNames(assets);};+const normalizeImportedAssetFolderData = (+ folders: AssetFolder[],+ assets: Asset[]+) => {+ const folderMap = new Map(folders.map((folder) => [folder.id, folder]));+ if (folderMap.size !== folders.length) {+ throw new Error("Imported asset folder id is duplicated.");+ }+ const validatedFolders = assetFoldersSchema.parse(folderMap);+ return normalizeAssetFolderData({+ assets,+ folders: Array.from(validatedFolders.values()),+ });+};+const assertImportedAssetFilesUploaded = async ({assets,ctx,@@ -201,10 +223,12 @@ const assertImportedAssetFilesUploaded = async ({const replaceProjectAssetRows = async ({assets,+ assetFolders,ctx,projectId,}: {assets: Asset[];+ assetFolders: AssetFolder[];ctx: AppContext;projectId: string;}) => {@@ -224,33 +248,35 @@ const replaceProjectAssetRows = async ({throw deletedAssets.error;}+ const deletedFolders = await ctx.postgrest.client+ .from("AssetFolder")+ .delete()+ .eq("projectId", projectId);+ if (deletedFolders.error) {+ throw deletedFolders.error;+ }++ if (assetFolders.length > 0) {+ const insertedFolder = await ctx.postgrest.client+ .from("AssetFolder")+ .insert(createAssetFolderRows(assetFolders, projectId));+ if (insertedFolder.error) {+ throw insertedFolder.error;+ }+ }+if (assets.length === 0) {return;}const insertedAssets = await ctx.postgrest.client.from("Asset")- .insert(createImportedAssetRows({ assets, projectId }));+ .insert(createAssetRows(assets, projectId));if (insertedAssets.error) {throw insertedAssets.error;}};-const createImportedAssetRows = ({- assets,- projectId,-}: {- assets: Asset[];- projectId: string;-}) =>- assets.map((asset) => ({- id: asset.id,- projectId,- name: asset.name,- filename: asset.filename ?? null,- description: asset.description ?? null,- }));-const updateProjectPreviewImage = async ({assetId,ctx,@@ -300,9 +326,11 @@ export const importPublishedProjectBundle = async (const nextVersion = build.version + 1;assertImportedAssets(data.assets);+ const { assets: importedAssets, folders: importedAssetFolders } =+ normalizeImportedAssetFolderData(data.assetFolders ?? [], data.assets);await assertImportedAssetFilesUploaded({- assets: data.assets,+ assets: importedAssets,ctx,projectId,});@@ -331,7 +359,12 @@ export const importPublishedProjectBundle = async (throw new Error("Unable to import project bundle because build changed.");}- await replaceProjectAssetRows({ assets: data.assets, ctx, projectId });+ await replaceProjectAssetRows({+ assets: importedAssets,+ assetFolders: importedAssetFolders,+ ctx,+ projectId,+ });await updateProjectPreviewImage({assetId: getImportedPreviewImageAssetId(data),@@ -345,10 +378,10 @@ export const importPublishedProjectBundle = async (export const __testing__ = {assertProjectBuildPermit,assertBundleVersion,- createImportedAssetRows,createBuildImportUpdate,getImportedPreviewImageAssetId,assertImportedAssetNames,assertImportedAssets,+ normalizeImportedAssetFolderData,assertImportedAssetFilesUploaded,};diff --git a/apps/builder/app/shared/builder-data.ts b/apps/builder/app/shared/builder-data.tsindex 37aa6f6964..fcdd1f162d 100644--- a/apps/builder/app/shared/builder-data.ts+++ b/apps/builder/app/shared/builder-data.ts@@ -1,4 +1,8 @@-import { getStyleDeclKey, type WebstudioData } from "@webstudio-is/sdk";+import {+ getStyleDeclKey,+ type AssetFolders,+ type WebstudioData,+} from "@webstudio-is/sdk";import { migratePages } from "@webstudio-is/project-migrations/pages";import {type MarketplaceProduct,@@ -7,24 +11,11 @@ import {import type { Project } from "@webstudio-is/project";import type { inferRouterOutputs } from "@trpc/server";import type { AppRouter } from "~/services/trcp-router.server";-import { $project } from "~/shared/sync/data-stores";-import {- $assets,- $breakpoints,- $dataSources,- $instances,- $marketplaceProduct,- $projectSettings,- $pages,- $props,- $resources,- $styleSourceSelections,- $styleSources,- $styles,-} from "~/shared/sync/data-stores";+import { $project, readBuilderStateStores } from "~/shared/sync/data-stores";import { nativeClient } from "~/shared/trpc/trpc-client";-export type BuilderData = WebstudioData & {+export type BuilderData = Omit<WebstudioData, "assetFolders"> & {+ assetFolders: AssetFolders;marketplaceProduct: undefined | MarketplaceProduct;projectSettings: ProjectSettings;project: Project;@@ -36,7 +27,8 @@ export type LoadedBuilderData = BuilderData &Pick<LoadDataOutput, "id" | "version" | "publisherHost" | "projectId">;export const getBuilderData = (): BuilderData => {- const pages = $pages.get();+ const data = readBuilderStateStores();+ const { pages, projectSettings } = data;if (pages === undefined) {throw Error(`Cannot get webstudio data with empty pages`);}@@ -44,23 +36,13 @@ export const getBuilderData = (): BuilderData => {if (project === undefined) {throw Error(`Cannot get webstudio data with empty project`);}- const projectSettings = $projectSettings.get();if (projectSettings === undefined) {throw Error(`Cannot get webstudio data with empty project settings`);}return {+ ...data,pages,project,- instances: $instances.get(),- props: $props.get(),- dataSources: $dataSources.get(),- resources: $resources.get(),- breakpoints: $breakpoints.get(),- styleSourceSelections: $styleSourceSelections.get(),- styleSources: $styleSources.get(),- styles: $styles.get(),- assets: $assets.get(),- marketplaceProduct: $marketplaceProduct.get(),projectSettings,};};@@ -94,6 +76,7 @@ export const loadBuilderData = async ({project: data.project,publisherHost: data.publisherHost,assets: hydrateIdMap(data.assets),+ assetFolders: hydrateIdMap(data.assetFolders),instances: hydrateIdMap(data.instances),dataSources: hydrateIdMap(data.dataSources),resources: hydrateIdMap(data.resources),diff --git a/apps/builder/app/shared/db/canvas.server.ts b/apps/builder/app/shared/db/canvas.server.tsindex 383929a058..8b66daf2b3 100644--- a/apps/builder/app/shared/db/canvas.server.ts+++ b/apps/builder/app/shared/db/canvas.server.ts@@ -8,13 +8,14 @@ import {loadDevBuildByProjectId,} from "@webstudio-is/project-build/server";import { collectFontFamiliesFromStyleDecls } from "@webstudio-is/project-build/runtime";-import { loadAssetsByProject } from "@webstudio-is/asset-uploader/index.server";+import { loadAssetDataByProject } from "@webstudio-is/asset-uploader/index.server";import type { AppContext } from "@webstudio-is/trpc-interface/index.server";import {findPageByIdOrPath,getAllPages,getStyleDeclKey,type Asset,+ type AssetFolder,} from "@webstudio-is/sdk";import { serializePages } from "@webstudio-is/project-migrations/pages";import { loadById } from "@webstudio-is/project/index.server";@@ -35,9 +36,11 @@ class ProjectNotPublishedError extends Error {const serializeProjectBundle = ({build,assets,+ assetFolders = [],}: {build: Build;assets: Asset[];+ assetFolders?: AssetFolder[];}): ProjectBundle => {const page = findPageByIdOrPath("/", build.pages);@@ -81,17 +84,19 @@ const serializeProjectBundle = ({page,pages: getAllPages(build.pages),assets: usedAssets,+ assetFolders,};};const createProjectBundle = async (build: Build,context: AppContext-): Promise<ProjectBundle> =>- serializeProjectBundle({+): Promise<ProjectBundle> => {+ return serializeProjectBundle({build,- assets: await loadAssetsByProject(build.projectId, context),+ ...(await loadAssetDataByProject(build.projectId, context)),});+};const loadProductionCanvasDataAndProject = async (buildId: string,diff --git a/apps/builder/app/shared/instance-utils/data.ts b/apps/builder/app/shared/instance-utils/data.tsindex ae1b3a467c..055e9f2f3a 100644--- a/apps/builder/app/shared/instance-utils/data.ts+++ b/apps/builder/app/shared/instance-utils/data.ts@@ -14,21 +14,7 @@ import { builderRuntimeContext } from "@webstudio-is/project-build/runtime";import { type BuilderRuntimeMutation } from "@webstudio-is/project-build/runtime";import { $canOpenPageTemplates, $selectedPage } from "../nano-states";import { createTransactionFromBuilderPatchPayload } from "../sync/builder-patch";-import {- $assets,- $breakpoints,- $dataSources,- $instances,- $marketplaceProduct,- $pages,- $projectSettings,- $project,- $props,- $resources,- $styles,- $styleSourceSelections,- $styleSources,-} from "../sync/data-stores";+import { $project, readBuilderStateStores } from "../sync/data-stores";type RuntimeMutationResult<Id extends BuilderRuntimeMutationOperationId> =Extract<BuilderRuntimeOperationResult<Id>, BuilderRuntimeMutation>;@@ -173,23 +159,15 @@ export const executeRuntimeMutationAsync = async <};export const getWebstudioData = () => {- const pages = $pages.get();+ const data = readBuilderStateStores();+ const { pages } = data;if (pages === undefined) {throw Error(`Cannot get webstudio data with empty pages`);}- const projectSettings = $projectSettings.get() ?? { meta: {}, compiler: {} };+ const projectSettings = data.projectSettings ?? { meta: {}, compiler: {} };return {+ ...data,pages,- instances: $instances.get(),- props: $props.get(),- dataSources: $dataSources.get(),- resources: $resources.get(),- breakpoints: $breakpoints.get(),- styleSourceSelections: $styleSourceSelections.get(),- styleSources: $styleSources.get(),- styles: $styles.get(),- assets: $assets.get(),- marketplaceProduct: $marketplaceProduct.get(),projectSettings,};};diff --git a/apps/builder/app/shared/nano-states/misc.ts b/apps/builder/app/shared/nano-states/misc.tsindex 59b5a61bdd..ca9b71faa1 100644--- a/apps/builder/app/shared/nano-states/misc.ts+++ b/apps/builder/app/shared/nano-states/misc.ts@@ -130,6 +130,7 @@ export type UploadingFileData = Simplify<uploadName: string;type: AssetType;objectURL: string;+ folderId?: string;} & (| {source: "file";diff --git a/apps/builder/app/shared/sync/data-stores.ts b/apps/builder/app/shared/sync/data-stores.tsindex 2fae4cf5b2..1817227cb1 100644--- a/apps/builder/app/shared/sync/data-stores.ts+++ b/apps/builder/app/shared/sync/data-stores.ts@@ -5,6 +5,7 @@import { atom } from "nanostores";import type {+ AssetFolders,Assets,Breakpoints,DataSources,@@ -27,6 +28,7 @@ export const $project = atom<Project | undefined>();export const $pages = atom<undefined | Pages>(undefined);export const $assets = atom<Assets>(new Map());+export const $assetFolders = atom<AssetFolders>(new Map());export const $instances = atom<Instances>(new Map());@@ -65,6 +67,22 @@ export const $projectSettings = atom<undefined | ProjectSettings>();export const $publisherHost = atom<string>("wstd.work");+export const readBuilderStateStores = () => ({+ pages: $pages.get(),+ assets: $assets.get(),+ assetFolders: $assetFolders.get(),+ instances: $instances.get(),+ props: $props.get(),+ dataSources: $dataSources.get(),+ resources: $resources.get(),+ breakpoints: $breakpoints.get(),+ styleSources: $styleSources.get(),+ styleSourceSelections: $styleSourceSelections.get(),+ styles: $styles.get(),+ marketplaceProduct: $marketplaceProduct.get(),+ projectSettings: $projectSettings.get(),+});+/*** Get initial values for all data stores.* Used for resetting stores when switching between projects.@@ -73,6 +91,7 @@ const getInitialDataStoreValues = () => ({project: undefined,pages: undefined,assets: new Map(),+ assetFolders: new Map(),instances: new Map(),props: new Map(),dataSources: new Map(),@@ -95,6 +114,7 @@ export const resetDataStores = () => {$project.set(initial.project);$pages.set(initial.pages);$assets.set(initial.assets);+ $assetFolders.set(initial.assetFolders);$instances.set(initial.instances);$props.set(initial.props);$dataSources.set(initial.dataSources);diff --git a/apps/builder/app/shared/sync/patch/patch-service.server.ts b/apps/builder/app/shared/sync/patch/patch-service.server.tsindex 4e86e1470d..2c2afdebc1 100644--- a/apps/builder/app/shared/sync/patch/patch-service.server.ts+++ b/apps/builder/app/shared/sync/patch/patch-service.server.ts@@ -41,6 +41,7 @@ const namespaceBuildColumns = {instances: ["instances"],props: ["props"],assets: [],+ assetFolders: [],styleSourceSelections: ["styleSourceSelections"],styleSources: ["styleSources"],styles: ["styles"],diff --git a/apps/builder/app/shared/sync/sync-client.test.ts b/apps/builder/app/shared/sync/sync-client.test.tsindex 3422f32156..58f335cd32 100644--- a/apps/builder/app/shared/sync/sync-client.test.ts+++ b/apps/builder/app/shared/sync/sync-client.test.ts@@ -23,6 +23,7 @@ describe("getServerSyncState", () => {dataSources: "dataSources",resources: "resources",assets: "assets",+ assetFolders: "assetFolders",marketplaceProduct: "marketplaceProduct",projectSettings: "projectSettings",} as unknown as LoadedBuilderData;@@ -42,6 +43,7 @@ describe("getServerSyncState", () => {["dataSources", "dataSources"],["resources", "resources"],["assets", "assets"],+ ["assetFolders", "assetFolders"],["projectSettings", "projectSettings"],["marketplaceProduct", "marketplaceProduct"],])diff --git a/apps/builder/app/shared/sync/sync-client.ts b/apps/builder/app/shared/sync/sync-client.tsindex 51e71bdf66..284bf2fe98 100644--- a/apps/builder/app/shared/sync/sync-client.ts+++ b/apps/builder/app/shared/sync/sync-client.ts@@ -17,6 +17,7 @@ import {$project,$pages,$assets,+ $assetFolders,$instances,$props,$dataSources,@@ -70,6 +71,7 @@ const applyBuilderData = (data: LoadedBuilderData) => {applyBuilderMetadata(data);$pages.set(data.pages);$assets.set(data.assets);+ $assetFolders.set(data.assetFolders);$instances.set(data.instances);$props.set(data.props);$dataSources.set(data.dataSources);diff --git a/apps/builder/app/shared/sync/sync-stores.ts b/apps/builder/app/shared/sync/sync-stores.tsindex ea6b61a415..7c68b21187 100644--- a/apps/builder/app/shared/sync/sync-stores.ts+++ b/apps/builder/app/shared/sync/sync-stores.ts@@ -66,6 +66,7 @@ import {$styleSources,$styleSourceSelections,$assets,+ $assetFolders,$resources,} from "~/shared/sync/data-stores";import { $pointerPosition } from "../awareness";@@ -104,6 +105,7 @@ const serverSyncStores = {dataSources: $dataSources,resources: $resources,assets: $assets,+ assetFolders: $assetFolders,projectSettings: $projectSettings,marketplaceProduct: $marketplaceProduct,} as const;diff --git a/apps/builder/dev/backend.sh b/apps/builder/dev/backend.shindex bed5706cd7..c65f2f2f3c 100644--- a/apps/builder/dev/backend.sh+++ b/apps/builder/dev/backend.sh@@ -2,7 +2,7 @@builder_backend_init() {ROOT_DIR="${ROOT_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)}"- SCHEMA_SNAPSHOT="${SCHEMA_SNAPSHOT:-$ROOT_DIR/apps/builder/e2e/schema/current.sql}"+ SCHEMA_SNAPSHOT="${SCHEMA_SNAPSHOT:-$ROOT_DIR/.cache/builder-e2e/schema-$(builder_backend_migrations_fingerprint).sql}"COMPOSE_ENV=(--env-file "$ROOT_DIR/apps/builder/.env")@@ -15,6 +15,25 @@ builder_backend_init() {)}+builder_backend_migrations_fingerprint() {+ (+ cd "$ROOT_DIR"+ {+ find packages/prisma-client/prisma/migrations \+ -mindepth 1 -maxdepth 1 -type d -print+ find packages/prisma-client/prisma/migrations \+ -type f \( -name migration.sql -o -name migration.ts \) -print+ } | LC_ALL=C sort | while IFS= read -r path; do+ if [ -f "$path" ]; then+ printf '%s ' "$path"+ git hash-object "$path"+ else+ printf '%s directory\n' "$path"+ fi+ done+ ) | git hash-object --stdin+}+builder_compose() {docker compose "${COMPOSE_ENV[@]}" "${COMPOSE_FILES[@]}" "$@"}@@ -104,10 +123,11 @@ builder_backend_bootstrap() {auto)if [ -f "$SCHEMA_SNAPSHOT" ]; thenbuilder_backend_bootstrap_schema_snapshot- echo "Bootstrapped database from $SCHEMA_SNAPSHOT"+ echo "Bootstrapped database from cached schema $SCHEMA_SNAPSHOT"else- echo "No schema snapshot found at $SCHEMA_SNAPSHOT; falling back to migrations"+ echo "No cached schema found at $SCHEMA_SNAPSHOT; running migrations"builder_backend_migrate+ builder_backend_write_schema_snapshotfi;;*)@@ -127,9 +147,15 @@ builder_backend_bootstrap_if_empty() {builder_backend_write_schema_snapshot() {mkdir -p "$(dirname "$SCHEMA_SNAPSHOT")"- builder_compose exec -T db \+ local temporary_snapshot="${SCHEMA_SNAPSHOT}.tmp.$$"+ if builder_compose exec -T db \sh -c 'pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --schema-only --no-owner --no-privileges' \- >"$SCHEMA_SNAPSHOT"+ >"$temporary_snapshot"; then+ mv "$temporary_snapshot" "$SCHEMA_SNAPSHOT"+ else+ rm -f "$temporary_snapshot"+ return 1+ fiecho "Wrote $SCHEMA_SNAPSHOT"}diff --git a/apps/builder/e2e/README.md b/apps/builder/e2e/README.mdindex d5e3030450..58dd36911c 100644--- a/apps/builder/e2e/README.md+++ b/apps/builder/e2e/README.md@@ -8,6 +8,15 @@ Use the full command for CI-like validation:pnpm e2e:builder```+The first run after the migrations change applies the regular migration+pipeline and writes an ignored schema cache under `.cache/builder-e2e`.+Subsequent runs in the same checkout restore that cache. CI does not preserve+it between runs. Refresh it explicitly with:++```sh+pnpm e2e:builder:refresh-schema-cache+```+For local test authoring, keep the e2e backend and Builder dev server runningand rerun only the matching test. This avoids rebuilding Builder and avoidsrestarting Docker for every edit.diff --git a/apps/builder/e2e/flows/assets-panel.ts b/apps/builder/e2e/flows/assets-panel.tsindex f277c011dd..a0511c4da8 100644--- a/apps/builder/e2e/flows/assets-panel.ts+++ b/apps/builder/e2e/flows/assets-panel.ts@@ -1,6 +1,7 @@import path from "node:path";import type { Page } from "playwright";import { waitForChangeToBeSaved } from "./sync-status";+import { dragPointer } from "./drag";const assetFixturePath = (filename: string) =>path.join(process.cwd(), "e2e", "fixtures", "assets", filename);@@ -16,14 +17,64 @@ const getAssetTitleLocator = ({return page.locator(`[title^="${name}"]`).first();};-export const openAssetsPanel = async ({ page }: { page: Page }) => {- await page.getByRole("tab", { name: "Assets" }).click();+export const openAssetsPanel = async ({+ page,+ force = false,+}: {+ page: Page;+ force?: boolean;+}) => {+ await page.getByRole("tab", { name: "Assets" }).click({ force });await page.getByRole("tabpanel", { name: "Assets" }).getByRole("button", { name: "Upload asset" }).waitFor();};+export const createAssetFolder = async ({+ page,+ name,+}: {+ page: Page;+ name: string;+}) => {+ await page.getByRole("button", { name: "Create asset folder" }).click();+ const dialog = page.getByRole("dialog", { name: "New folder" });+ await dialog.getByLabel("Folder", { exact: true }).fill(name);+ await Promise.all([+ waitForChangeToBeSaved({ page }),+ dialog.getByRole("button", { name: "Create folder" }).click(),+ ]);+ return page.getByRole("button", { name: `Folder ${name}`, exact: true });+};++export const dragAssetToFolder = async ({+ page,+ assetTitle,+ folderName,+}: {+ page: Page;+ assetTitle: string;+ folderName: string;+}) => {+ const asset = page.getByTitle(assetTitle);+ const folder = page.getByRole("button", {+ name: `Folder ${folderName}`,+ exact: true,+ });+ await Promise.all([+ waitForChangeToBeSaved({ page, timeout: 30_000 }),+ dragPointer({+ page,+ source: asset,+ target: folder,+ ready: async () =>+ (await folder.getAttribute("data-is-drop-over")) === "true",+ }),+ ]);+ await asset.waitFor({ state: "hidden" });+};+export const uploadAsset = async ({page,filename,@@ -41,7 +92,7 @@ export const uploadAsset = async ({return title;};-export const openAssetDetails = async ({+export const openAssetSettings = async ({page,filename,}: {@@ -50,8 +101,12 @@ export const openAssetDetails = async ({}) => {const asset = page.getByTitle(filename);await asset.hover();- await asset.getByRole("button", { name: "Options" }).click();- await page.getByText("Asset details").waitFor();+ await asset+ .locator("..")+ .getByRole("button", { name: `Actions for ${filename}` })+ .click();+ await page.getByRole("menuitem", { name: "Settings" }).click();+ await page.getByText("Asset settings").waitFor();};export const replaceSelectedAsset = async ({@@ -78,8 +133,11 @@ export const deleteSelectedAsset = async ({page: Page;filename: string;}) => {- const save = waitForChangeToBeSaved({ page });await page.getByRole("button", { name: "Delete" }).click();+ const deleteDialog = page.getByRole("dialog", { name: "Delete asset?" });+ await deleteDialog.waitFor();+ const save = waitForChangeToBeSaved({ page });+ await deleteDialog.getByRole("button", { name: "Delete" }).click();await page.getByTitle(filename).waitFor({ state: "hidden" });await save;};diff --git a/apps/builder/e2e/flows/drag.ts b/apps/builder/e2e/flows/drag.tsindex f64ba96da2..4f1d915ff8 100644--- a/apps/builder/e2e/flows/drag.ts+++ b/apps/builder/e2e/flows/drag.ts@@ -3,7 +3,7 @@ import { waitForChangeToBeSaved } from "./sync-status";type Bounds = { x: number; y: number; width: number; height: number };-const dragPointer = async ({+export const dragPointer = async ({page,source,target,diff --git a/apps/builder/e2e/run-local.sh b/apps/builder/e2e/run-local.shindex c0f45e472c..c337205eb1 100644--- a/apps/builder/e2e/run-local.sh+++ b/apps/builder/e2e/run-local.sh@@ -3,6 +3,20 @@ set -euo pipefailROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"COMPOSE_OVERRIDE_FILE="$ROOT_DIR/apps/builder/docker-compose.e2e.yaml"++# Keep the disposable E2E backend independent from the persistent local+# development backend. In particular, E2E cleanup must never remove the local+# database volume.+export COMPOSE_PROJECT_NAME="${E2E_COMPOSE_PROJECT_NAME:-builder-e2e}"+export PGPORT="${E2E_PGPORT:-55434}"+export POSTGREST_PORT="${E2E_POSTGREST_PORT:-55435}"+export POSTGRES_DB="${E2E_POSTGRES_DB:-webstudio}"+export POSTGRES_USER="${E2E_POSTGRES_USER:-postgres}"+export POSTGRES_PASSWORD="${E2E_POSTGRES_PASSWORD:-pass}"+export DATABASE_URL="${E2E_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${PGPORT}/${POSTGRES_DB}?pgbouncer=true}"+export DIRECT_URL="${E2E_DIRECT_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${PGPORT}/${POSTGRES_DB}}"+export POSTGREST_URL="${E2E_POSTGREST_URL:-http://localhost:${POSTGREST_PORT}}"+source "$ROOT_DIR/apps/builder/dev/backend.sh"builder_backend_initdiff --git a/apps/builder/e2e/schema/README.md b/apps/builder/e2e/schema/README.mddeleted file mode 100644index d187b76aac..0000000000--- a/apps/builder/e2e/schema/README.md+++ /dev/null@@ -1,10 +0,0 @@-This directory stores the optional e2e database schema snapshot.--The snapshot should contain database structure only. Test data belongs in the-typed fixtures under `apps/builder/e2e/fixtures`.--Refresh the snapshot with:--```sh-pnpm e2e:builder:update-schema-```diff --git a/apps/builder/e2e/schema/current.sql b/apps/builder/e2e/schema/current.sqldeleted file mode 100644index edda6ef144..0000000000--- a/apps/builder/e2e/schema/current.sql+++ /dev/null@@ -1,1466 +0,0 @@------ PostgreSQL database dump-----\restrict J29mZQHzSYuDPm8eRJiWoDBJq2TAh0b0ii1URRuunEM0BP9wmmC5I93noDiexdr---- Dumped from database version 16.14 (Debian 16.14-1.pgdg13+1)--- Dumped by pg_dump version 16.14 (Debian 16.14-1.pgdg13+1)--SET statement_timeout = 0;-SET lock_timeout = 0;-SET idle_in_transaction_session_timeout = 0;-SET client_encoding = 'UTF8';-SET standard_conforming_strings = on;-SELECT pg_catalog.set_config('search_path', '', false);-SET check_function_bodies = false;-SET xmloption = content;-SET client_min_messages = warning;-SET row_security = off;------- Name: uuid-ossp; Type: EXTENSION; Schema: -; Owner: ------CREATE EXTENSION IF NOT EXISTS "uuid-ossp" WITH SCHEMA public;-------- Name: EXTENSION "uuid-ossp"; Type: COMMENT; Schema: -; Owner: ------COMMENT ON EXTENSION "uuid-ossp" IS 'generate universally unique identifiers (UUIDs)';-------- Name: AuthorizationRelation; Type: TYPE; Schema: public; Owner: ------CREATE TYPE public."AuthorizationRelation" AS ENUM (- 'viewers',- 'editors',- 'builders',- 'administrators'-);-------- Name: DomainStatus; Type: TYPE; Schema: public; Owner: ------CREATE TYPE public."DomainStatus" AS ENUM (- 'INITIALIZING',- 'ACTIVE',- 'ERROR',- 'PENDING'-);-------- Name: MarketplaceApprovalStatus; Type: TYPE; Schema: public; Owner: ------CREATE TYPE public."MarketplaceApprovalStatus" AS ENUM (- 'UNLISTED',- 'PENDING',- 'APPROVED',- 'REJECTED'-);-------- Name: PublishStatus; Type: TYPE; Schema: public; Owner: ------CREATE TYPE public."PublishStatus" AS ENUM (- 'PENDING',- 'PUBLISHED',- 'FAILED'-);-------- Name: UploadStatus; Type: TYPE; Schema: public; Owner: ------CREATE TYPE public."UploadStatus" AS ENUM (- 'UPLOADING',- 'UPLOADED'-);---SET default_tablespace = '';--SET default_table_access_method = heap;------- Name: Project; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Project" (- id text NOT NULL,- title text NOT NULL,- domain text NOT NULL,- "userId" text,- "isDeleted" boolean DEFAULT false NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "previewImageAssetId" text,- "marketplaceApprovalStatus" public."MarketplaceApprovalStatus" DEFAULT 'UNLISTED'::public."MarketplaceApprovalStatus" NOT NULL,- tags text[],- "workspaceId" uuid-);-------- Name: clone_project(text, text, text, text); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public.clone_project(project_id text, user_id text, title text, domain text) RETURNS public."Project"- LANGUAGE plpgsql- AS $$-DECLARE- old_project "Project";- new_project "Project";-BEGIN- SELECT * FROM "Project" WHERE id=project_id INTO old_project;-- INSERT INTO "Project" (- id,- "userId",- title,- domain- )- VALUES (- extensions.uuid_generate_v4(),- user_id,- title,- domain- )- RETURNING * INTO new_project;-- INSERT INTO "Asset" (id, name, "projectId")- SELECT asset.id, asset.name, new_project.id AS "projectId"- FROM "Asset" AS asset, "File" AS file- WHERE- asset.name = file.name AND- file.status = 'UPLOADED' AND- asset."projectId" = old_project.id;-- -- set preview image asset after copying assets to the project- UPDATE "Project"- SET "previewImageAssetId"= old_project."previewImageAssetId"- WHERE id=new_project.id;-- INSERT INTO "Build" (- id,- "projectId",- pages,- "styleSources",- "styleSourceSelections",- styles,- breakpoints,- props,- instances,- "dataSources",- resources- )- SELECT- extensions.uuid_generate_v4() AS id,- new_project.id AS "projectId",- pages,- "styleSources",- "styleSourceSelections",- styles,- breakpoints,- props,- instances,- "dataSources",- resources- FROM "Build"- WHERE "projectId" = old_project.id AND deployment IS NULL;-- RETURN new_project;-END;-$$;-------- Name: create_production_build(text, text); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public.create_production_build(project_id text, deployment text) RETURNS text- LANGUAGE plpgsql- AS $$-DECLARE- new_build_id text;-BEGIN- INSERT INTO "Build" (- version,- "lastTransactionId",- pages,- breakpoints,- styles,- "styleSources",- "styleSourceSelections",- props,- "dataSources",- resources,- instances,- "marketplaceProduct",- "projectSettings",- "publishStatus",- "projectId",- id,- deployment- )- SELECT- version,- "lastTransactionId",- pages,- breakpoints,- styles,- "styleSources",- "styleSourceSelections",- props,- "dataSources",- resources,- instances,- "marketplaceProduct",- "projectSettings",- "publishStatus",- "projectId",- extensions.uuid_generate_v4() as id,- create_production_build.deployment as deployment- FROM "Build"- WHERE "projectId" = project_id AND "Build"."deployment" IS NULL- RETURNING "id" INTO new_build_id;-- RETURN new_build_id;-END;-$$;-------- Name: database_cleanup(timestamp without time zone, timestamp without time zone); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public.database_cleanup(from_date timestamp without time zone DEFAULT '2020-01-01 00:00:00'::timestamp without time zone, to_date timestamp without time zone DEFAULT '2099-12-31 23:59:59'::timestamp without time zone) RETURNS void- LANGUAGE plpgsql- AS $$-BEGIN- WITH latest_builds AS (- SELECT "buildId" FROM "Project" p, LATERAL "latestProjectDomainBuildVirtual"(p)- UNION- SELECT "buildId" FROM "Project" p, LATERAL "latestBuildVirtual"(p)- UNION- SELECT lb."buildId"- FROM "Project" p, LATERAL "domainsVirtual"(p) dv, LATERAL "latestBuildVirtual"(dv) lb- )- UPDATE "Build"- SET- "styleSources" = '[]'::text,- styles = '[]'::text,- breakpoints = '[]'::text,- "styleSourceSelections" = '[]'::text,- props = '[]'::text,- instances = '[]'::text,- "dataSources" = '[]'::text,- resources = '[]'::text,- "marketplaceProduct" = '{}'::text,- "projectSettings" = '{"meta":{},"compiler":{}}'::text,- "isCleaned" = TRUE- WHERE deployment IS NOT NULL- AND id NOT IN (SELECT "buildId" FROM latest_builds)- AND "isCleaned" = FALSE- AND "createdAt" BETWEEN from_date AND to_date; -- Filter by date range (for testing purposes)-END;-$$;-------- Name: domainsVirtual; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."domainsVirtual" (- id text NOT NULL,- "domainId" text NOT NULL,- "projectId" text NOT NULL,- domain text NOT NULL,- status public."DomainStatus" DEFAULT 'INITIALIZING'::public."DomainStatus" NOT NULL,- error text,- "domainTxtRecord" text,- "expectedTxtRecord" text NOT NULL,- cname text NOT NULL,- verified boolean DEFAULT false NOT NULL,- "createdAt" timestamp(3) with time zone NOT NULL,- "updatedAt" timestamp(3) with time zone NOT NULL-);-------- Name: TABLE "domainsVirtual"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON TABLE public."domainsVirtual" IS 'Virtual table representing domains related to each project. This table enforces a 1-1 relationship with the Project table and is used for API interaction (postgrest types).';-------- Name: COLUMN "domainsVirtual"."domainId"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."domainId" IS 'Unique identifier for the domain (Domain table reference).';-------- Name: COLUMN "domainsVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."projectId" IS 'Unique identifier for the project, acting as the primary key (1-1 relationship with Project table).';-------- Name: COLUMN "domainsVirtual".domain; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual".domain IS 'The domain name (must not be NULL).';-------- Name: COLUMN "domainsVirtual".status; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual".status IS 'Current status of the domain, with a default of INITIALIZING.';-------- Name: COLUMN "domainsVirtual".error; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual".error IS 'Optional error message field populated if the domain status is ERROR.';-------- Name: COLUMN "domainsVirtual"."domainTxtRecord"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."domainTxtRecord" IS 'Current TXT record for the domain, coming from the Domain table.';-------- Name: COLUMN "domainsVirtual"."expectedTxtRecord"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."expectedTxtRecord" IS 'Expected TXT record for the domain, pulled from the ProjectDomain table.';-------- Name: COLUMN "domainsVirtual".verified; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual".verified IS 'Boolean flag indicating whether the domain is verified (true if TXT records match, false otherwise).';-------- Name: COLUMN "domainsVirtual"."createdAt"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."createdAt" IS 'Timestamp indicating when the ProjectDomain entry was created.';-------- Name: COLUMN "domainsVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."domainsVirtual"."updatedAt" IS 'Timestamp indicating when the Domain was last updated.';-------- Name: domainsVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public."domainsVirtual"(public."Project") RETURNS SETOF public."domainsVirtual"- LANGUAGE sql STABLE- AS $_$- -- This function retrieves all the domain information associated with a specific project by joining the Domain and ProjectDomain tables.- -- It returns a result set conforming to the "domainsVirtual" structure, including fields such as domain status, error, verification status, etc.- SELECT- "Domain".id || '-' || "ProjectDomain"."projectId" as id,- "Domain".id AS "domainId", -- Domain ID from Domain table- "ProjectDomain"."projectId", -- Project ID from ProjectDomain table- "Domain".domain, -- Domain name- "Domain".status, -- Current domain status- "Domain".error, -- Error message, if any- "Domain"."txtRecord" AS "domainTxtRecord", -- Current TXT record from Domain table- "ProjectDomain"."txtRecord" AS "expectedTxtRecord", -- Expected TXT record from ProjectDomain table- "ProjectDomain"."cname" AS "cname",- CASE- WHEN "Domain"."txtRecord" = "ProjectDomain"."txtRecord" THEN true -- If TXT records match, domain is verified- ELSE false- END AS "verified", -- Boolean flag for verification status- "ProjectDomain"."createdAt", -- Creation timestamp from ProjectDomain table- "Domain"."updatedAt" -- Last updated timestamp from Domain table- FROM- "Domain"- JOIN- "ProjectDomain" ON "Domain".id = "ProjectDomain"."domainId" -- Joining Domain and ProjectDomain on domainId- WHERE- "ProjectDomain"."projectId" = $1.id -- Filtering by projectId passed as an argument to the function- ORDER BY "ProjectDomain"."createdAt", "Domain".id; -- Stable sort-$_$;-------- Name: FUNCTION "domainsVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: ------COMMENT ON FUNCTION public."domainsVirtual"(public."Project") IS 'Function that retrieves domain-related data for a given project by joining the Domain and ProjectDomain tables. It returns a result set that conforms to the structure defined in the domainsVirtual virtual table.';-------- Name: Build; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Build" (- id text NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- pages text NOT NULL,- "projectId" text NOT NULL,- "styleSources" text DEFAULT '[]'::text NOT NULL,- styles text DEFAULT '[]'::text NOT NULL,- breakpoints text DEFAULT '[]'::text NOT NULL,- "styleSourceSelections" text DEFAULT '[]'::text NOT NULL,- props text DEFAULT '[]'::text NOT NULL,- instances text DEFAULT '[]'::text NOT NULL,- "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- version integer DEFAULT 0 NOT NULL,- deployment text,- "publishStatus" public."PublishStatus" DEFAULT 'PENDING'::public."PublishStatus" NOT NULL,- "dataSources" text DEFAULT '[]'::text NOT NULL,- "lastTransactionId" text,- resources text DEFAULT '[]'::text NOT NULL,- "marketplaceProduct" text DEFAULT '{}'::text NOT NULL,- "projectSettings" text DEFAULT '{"meta":{},"compiler":{}}'::text NOT NULL,- "isCleaned" boolean DEFAULT false-);-------- Name: DashboardProject; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public."DashboardProject" AS- SELECT id,- title,- tags,- domain,- "userId",- "workspaceId",- "isDeleted",- "createdAt",- "previewImageAssetId",- "marketplaceApprovalStatus",- (EXISTS ( SELECT 1- FROM public."Build"- WHERE (("Build"."projectId" = "Project".id) AND ("Build".deployment IS NOT NULL)))) AS "isPublished"- FROM public."Project";-------- Name: latestBuildVirtual; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."latestBuildVirtual" (- "buildId" text NOT NULL,- "projectId" text NOT NULL,- "domainsVirtualId" text NOT NULL,- domain text NOT NULL,- "createdAt" timestamp(3) with time zone NOT NULL,- "publishStatus" public."PublishStatus" NOT NULL,- "updatedAt" timestamp(3) with time zone DEFAULT now() NOT NULL-);-------- Name: TABLE "latestBuildVirtual"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON TABLE public."latestBuildVirtual" IS 'Virtual table representing the latest build for each project, enforcing a 1-1 relationship with the Project table. Used ONLY for postgrest types';-------- Name: COLUMN "latestBuildVirtual"."projectId"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."latestBuildVirtual"."projectId" IS 'Identifier for the project, enforcing a 1-1 relationship with the Project table as a primary key';-------- Name: COLUMN "latestBuildVirtual"."updatedAt"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON COLUMN public."latestBuildVirtual"."updatedAt" IS 'Timestamp indicating when the Build was last updated';-------- Name: latestBuildVirtual(public."DashboardProject"); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public."latestBuildVirtual"(public."DashboardProject") RETURNS SETOF public."latestBuildVirtual"- LANGUAGE sql STABLE ROWS 1- AS $_$-SELECT- lbv.*-FROM- "Project" p,- LATERAL "latestBuildVirtual"(p) lbv-WHERE- p.id = $1.id-LIMIT 1;--$_$;-------- Name: FUNCTION "latestBuildVirtual"(public."DashboardProject"); Type: COMMENT; Schema: public; Owner: ------COMMENT ON FUNCTION public."latestBuildVirtual"(public."DashboardProject") IS 'Wrapper function to make latestBuildVirtual work with DashboardProject view for PostgREST computed fields.';-------- Name: latestBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public."latestBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual"- LANGUAGE sql STABLE ROWS 1- AS $_$-SELECT- b.id AS "buildId",- b."projectId",- '' as "domainsVirtualId",- -- Use CASE to determine which domain to select based on conditions- CASE- WHEN (b.deployment :: jsonb ->> 'projectDomain') = p.domain- OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain]) THEN p.domain- ELSE d.domain- END AS "domain",- b."createdAt",- b."publishStatus",- b."updatedAt"-FROM- "Build" b- JOIN "Project" p ON b."projectId" = p.id- LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id- LEFT JOIN "Domain" d ON d.id = pd."domainId"-WHERE- b."projectId" = $1.id- AND b.deployment IS NOT NULL -- 'destination' IS NULL for backward compatibility; 'destination' = 'saas' for non-static builds- AND (- (b.deployment :: jsonb ->> 'destination') IS NULL- OR (b.deployment :: jsonb ->> 'destination') = 'saas'- )- AND (- -- Check if 'projectDomain' matches p.domain- (b.deployment :: jsonb ->> 'projectDomain') = p.domain -- Check if 'domains' contains p.domain or d.domain- OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain])- OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [d.domain])- )-ORDER BY- b."createdAt" DESC-LIMIT- 1;--$_$;-------- Name: FUNCTION "latestBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: ------COMMENT ON FUNCTION public."latestBuildVirtual"(public."Project") IS 'This function computes the latest build for a project, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.';-------- Name: latestBuildVirtual(public."domainsVirtual"); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public."latestBuildVirtual"(public."domainsVirtual") RETURNS SETOF public."latestBuildVirtual"- LANGUAGE sql STABLE ROWS 1- AS $_$-SELECT- b.id AS "buildId",- b."projectId",- '' as "domainsVirtualId",- d."domain",- b."createdAt",- b."publishStatus",- b."updatedAt"-FROM- "Build" b- JOIN "Domain" d ON d.id = $1."domainId"-WHERE- b."projectId" = $1."projectId"- AND b.deployment IS NOT NULL- AND (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [d.domain])-ORDER BY- b."createdAt" DESC-LIMIT- 1;--$_$;-------- Name: FUNCTION "latestBuildVirtual"(public."domainsVirtual"); Type: COMMENT; Schema: public; Owner: ------COMMENT ON FUNCTION public."latestBuildVirtual"(public."domainsVirtual") IS 'Returns the latest build for a given project and domain as a computed field for PostgREST.';-------- Name: latestProjectDomainBuildVirtual(public."Project"); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") RETURNS SETOF public."latestBuildVirtual"- LANGUAGE sql STABLE ROWS 1- AS $_$-SELECT- b.id AS "buildId",- b."projectId",- '' as "domainsVirtualId",- p.domain AS "domain",- b."createdAt",- b."publishStatus",- b."updatedAt"-FROM- "Build" b- JOIN "Project" p ON b."projectId" = p.id- LEFT JOIN "ProjectDomain" pd ON pd."projectId" = p.id-WHERE- b."projectId" = $1.id- AND b.deployment IS NOT NULL- AND (- (b.deployment :: jsonb ->> 'destination') IS NULL- OR (b.deployment :: jsonb ->> 'destination') = 'saas'- )- AND (- (b.deployment :: jsonb ->> 'projectDomain') = p.domain- OR (b.deployment :: jsonb -> 'domains') @> to_jsonb(array [p.domain])- )-ORDER BY- b."createdAt" DESC-LIMIT- 1;--$_$;-------- Name: FUNCTION "latestProjectDomainBuildVirtual"(public."Project"); Type: COMMENT; Schema: public; Owner: ------COMMENT ON FUNCTION public."latestProjectDomainBuildVirtual"(public."Project") IS 'This function computes the latest build for a project domain, ensuring it is a production (non-static) build, where the domain matches either the Project.domain field or exists in the related Domain table. It provides backward compatibility for older records with a missing "destination" field.';-------- Name: restore_development_build(text, text); Type: FUNCTION; Schema: public; Owner: ------CREATE FUNCTION public.restore_development_build(project_id text, from_build_id text) RETURNS text- LANGUAGE plpgsql- AS $$-BEGIN- UPDATE "Build"- SET- "version" = source."version",- "lastTransactionId" = source."lastTransactionId",- "pages" = source."pages",- "breakpoints" = source."breakpoints",- "styles" = source."styles",- "styleSources" = source."styleSources",- "styleSourceSelections" = source."styleSourceSelections",- "props" = source."props",- "dataSources" = source."dataSources",- "resources" = source."resources",- "instances" = source."instances",- "marketplaceProduct" = source."marketplaceProduct",- "projectSettings" = source."projectSettings"- FROM (- SELECT * FROM "Build"- WHERE "projectId" = project_id AND "id" = from_build_id- ) as source- WHERE "Build"."projectId" = project_id AND "Build"."deployment" IS NULL;- RETURN 'OK';-END;-$$;-------- Name: AuthorizationToken; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."AuthorizationToken" (- token text NOT NULL,- "projectId" text NOT NULL,- name text DEFAULT ''::text NOT NULL,- relation public."AuthorizationRelation" DEFAULT 'viewers'::public."AuthorizationRelation" NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "canClone" boolean DEFAULT true NOT NULL,- "canCopy" boolean DEFAULT true NOT NULL,- "canPublish" boolean DEFAULT false NOT NULL,- "canUseApi" boolean DEFAULT false NOT NULL-);-------- Name: ApprovedMarketplaceProduct; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public."ApprovedMarketplaceProduct" AS- SELECT DISTINCT ON ("projectId") "projectId",- "marketplaceProduct",- ( SELECT auth.token- FROM public."AuthorizationToken" auth- WHERE ((auth."projectId" = build."projectId") AND (auth.relation = 'viewers'::public."AuthorizationRelation"))- ORDER BY auth.token- LIMIT 1) AS "authorizationToken"- FROM public."Build" build- WHERE ((deployment IS NOT NULL) AND ("projectId" IN ( SELECT "Project".id- FROM public."Project"- WHERE (("Project"."isDeleted" = false) AND ("Project"."marketplaceApprovalStatus" = ('APPROVED'::text)::public."MarketplaceApprovalStatus")))))- ORDER BY "projectId", "createdAt" DESC, id;-------- Name: Asset; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Asset" (- id text NOT NULL,- "projectId" text NOT NULL,- name text NOT NULL,- description text,- filename text-);-------- Name: ClientReferences; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."ClientReferences" (- reference text DEFAULT public.uuid_generate_v4() NOT NULL,- service text NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "userId" text NOT NULL-);-------- Name: Domain; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Domain" (- id text NOT NULL,- domain text NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "txtRecord" text,- status public."DomainStatus" DEFAULT 'INITIALIZING'::public."DomainStatus" NOT NULL,- error text,- "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL-);-------- Name: File; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."File" (- name text NOT NULL,- format text NOT NULL,- size integer NOT NULL,- description text,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- meta text DEFAULT '{}'::text NOT NULL,- status public."UploadStatus" DEFAULT 'UPLOADING'::public."UploadStatus" NOT NULL,- "uploaderProjectId" text,- "isDeleted" boolean DEFAULT false NOT NULL,- "updatedAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL-);-------- Name: LatestStaticBuildPerProject; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public."LatestStaticBuildPerProject" AS- SELECT DISTINCT ON ("projectId") id AS "buildId",- "projectId",- "updatedAt",- "publishStatus"- FROM public."Build" bld- WHERE ((deployment IS NOT NULL) AND (((deployment)::jsonb ->> 'destination'::text) = 'static'::text))- ORDER BY "projectId", "createdAt" DESC, id;-------- Name: Notification; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Notification" (- id uuid DEFAULT gen_random_uuid() NOT NULL,- type text NOT NULL,- "recipientId" text NOT NULL,- "senderId" text NOT NULL,- status text DEFAULT 'pending'::text NOT NULL,- payload jsonb DEFAULT '{}'::jsonb NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL,- "respondedAt" timestamp(3) with time zone-);-------- Name: Product; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Product" (- id text NOT NULL,- name text NOT NULL,- description text,- features text[],- images text[],- meta jsonb NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL-);-------- Name: ProjectDomain; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."ProjectDomain" (- "projectId" text NOT NULL,- "domainId" text NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "txtRecord" text NOT NULL,- cname text NOT NULL-);-------- Name: TransactionLog; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."TransactionLog" (- "eventId" text NOT NULL,- "productId" text,- "userId" text,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- "eventData" jsonb,- "eventCreated" integer GENERATED ALWAYS AS ((("eventData" #>> '{created}'::text[]))::integer) STORED,- "eventType" text GENERATED ALWAYS AS (("eventData" #>> '{type}'::text[])) STORED,- status text GENERATED ALWAYS AS (("eventData" #>> '{data,object,status}'::text[])) STORED,- "customerId" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer}'::text[])) STORED,- "customerEmail" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,customer_details,email}'::text[])) STORED,- "subscriptionId" text GENERATED ALWAYS AS (-CASE- WHEN (("eventData" #>> '{data,object,object}'::text[]) = 'subscription'::text) THEN ("eventData" #>> '{data,object,id}'::text[])- ELSE ("eventData" #>> '{data,object,subscription}'::text[])-END) STORED,- "paymentIntent" text GENERATED ALWAYS AS (("eventData" #>> '{data,object,payment_intent}'::text[])) STORED-);-------- Name: User; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."User" (- id text NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT CURRENT_TIMESTAMP NOT NULL,- email text,- image text,- provider text,- username text,- "projectsTags" jsonb DEFAULT '[]'::jsonb NOT NULL-);-------- Name: UserProduct; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public."UserProduct" AS-( SELECT tl."userId",- tl."subscriptionId",- tl."productId",- tl."customerId",- tl."customerEmail"- FROM public."TransactionLog" tl- WHERE ((tl.status = 'complete'::text) AND (tl."eventType" = 'checkout.session.completed'::text) AND (NOT (EXISTS ( SELECT 1- FROM public."TransactionLog" failed- WHERE ((failed."eventType" = 'checkout.session.async_payment_failed'::text) AND ((failed."eventData" #>> '{data,object,id}'::text[]) = (tl."eventData" #>> '{data,object,id}'::text[])) AND (failed."eventCreated" >= tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1- FROM public."TransactionLog" tlexsists- WHERE ((tlexsists."subscriptionId" = tl."subscriptionId") AND (tlexsists."eventType" = 'customer.subscription.deleted'::text) AND (tlexsists.status = 'canceled'::text) AND (tlexsists."eventCreated" > tl."eventCreated"))))) AND (NOT (EXISTS ( SELECT 1- FROM public."TransactionLog" tlexsists- WHERE ((tlexsists."paymentIntent" = tl."paymentIntent") AND (tlexsists."eventType" = 'charge.refunded'::text) AND (tlexsists.status = 'succeeded'::text) AND (tlexsists."eventCreated" > tl."eventCreated"))))))- ORDER BY tl."userId", tl."eventCreated" DESC)-UNION ALL- SELECT "TransactionLog"."userId",- "TransactionLog"."subscriptionId",- "TransactionLog"."productId",- "TransactionLog"."customerId",- "TransactionLog"."customerEmail"- FROM public."TransactionLog"- WHERE ("TransactionLog"."eventType" = 'appsumo.activate'::text);-------- Name: Workspace; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."Workspace" (- id uuid DEFAULT gen_random_uuid() NOT NULL,- name text NOT NULL,- "isDefault" boolean DEFAULT false NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL,- "userId" text NOT NULL,- "isDeleted" boolean DEFAULT false NOT NULL-);-------- Name: WorkspaceMember; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public."WorkspaceMember" (- "workspaceId" uuid NOT NULL,- "userId" text NOT NULL,- relation public."AuthorizationRelation" DEFAULT 'administrators'::public."AuthorizationRelation" NOT NULL,- "createdAt" timestamp(3) with time zone DEFAULT now() NOT NULL,- "removedAt" timestamp(3) with time zone-);-------- Name: WorkspaceProjectAuthorization; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public."WorkspaceProjectAuthorization" AS- SELECT w."userId",- p.id AS "projectId",- 'own'::text AS relation- FROM (public."Workspace" w- JOIN public."Project" p ON ((p."workspaceId" = w.id)))- WHERE ((w."isDeleted" = false) AND (p."isDeleted" = false))-UNION ALL- SELECT wm."userId",- p.id AS "projectId",- (wm.relation)::text AS relation- FROM ((public."WorkspaceMember" wm- JOIN public."Workspace" w ON ((w.id = wm."workspaceId")))- JOIN public."Project" p ON ((p."workspaceId" = wm."workspaceId")))- WHERE ((wm."removedAt" IS NULL) AND (w."isDeleted" = false) AND (p."isDeleted" = false));-------- Name: _prisma_migrations; Type: TABLE; Schema: public; Owner: ------CREATE TABLE public._prisma_migrations (- id character varying(36) NOT NULL,- checksum character varying(64) NOT NULL,- finished_at timestamp with time zone,- migration_name character varying(255) NOT NULL,- logs text,- rolled_back_at timestamp with time zone,- started_at timestamp with time zone DEFAULT now() NOT NULL,- applied_steps_count integer DEFAULT 0 NOT NULL-);-------- Name: published_builds; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public.published_builds AS- SELECT id AS "buildId",- "projectId",- "createdAt",- ( SELECT string_agg(list.value, ', '::text) AS string_agg- FROM jsonb_array_elements_text(((build.deployment)::jsonb -> 'domains'::text)) list(value)) AS domains- FROM public."Build" build- WHERE ((deployment IS NOT NULL) AND ("isCleaned" = false))- ORDER BY "projectId", "createdAt" DESC;-------- Name: user_publish_count; Type: VIEW; Schema: public; Owner: ------CREATE VIEW public.user_publish_count AS- SELECT DISTINCT "Project"."userId" AS user_id,- count(*) AS count- FROM (public."Build"- LEFT JOIN public."Project" ON (("Project".id = "Build"."projectId")))- WHERE ((date_trunc('day'::text, "Build"."createdAt") = date_trunc('day'::text, now())) AND ("Build".deployment IS NOT NULL))- GROUP BY "Project"."userId";-------- Name: Asset Asset_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Asset"- ADD CONSTRAINT "Asset_pkey" PRIMARY KEY (id, "projectId");-------- Name: AuthorizationToken AuthorizationToken_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."AuthorizationToken"- ADD CONSTRAINT "AuthorizationToken_pkey" PRIMARY KEY (token, "projectId");-------- Name: Build Build_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Build"- ADD CONSTRAINT "Build_pkey" PRIMARY KEY (id, "projectId");-------- Name: ClientReferences ClientReferences_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."ClientReferences"- ADD CONSTRAINT "ClientReferences_pkey" PRIMARY KEY ("userId", service);-------- Name: Domain Domain_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Domain"- ADD CONSTRAINT "Domain_pkey" PRIMARY KEY (id);-------- Name: File File_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."File"- ADD CONSTRAINT "File_pkey" PRIMARY KEY (name);-------- Name: Notification Notification_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Notification"- ADD CONSTRAINT "Notification_pkey" PRIMARY KEY (id);-------- Name: Product Product_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Product"- ADD CONSTRAINT "Product_pkey" PRIMARY KEY (id);-------- Name: ProjectDomain ProjectDomain_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."ProjectDomain"- ADD CONSTRAINT "ProjectDomain_pkey" PRIMARY KEY ("projectId", "domainId");-------- Name: Project Project_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Project"- ADD CONSTRAINT "Project_pkey" PRIMARY KEY (id);-------- Name: TransactionLog TransactionLog_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."TransactionLog"- ADD CONSTRAINT "TransactionLog_pkey" PRIMARY KEY ("eventId");-------- Name: User User_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."User"- ADD CONSTRAINT "User_pkey" PRIMARY KEY (id);-------- Name: WorkspaceMember WorkspaceMember_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."WorkspaceMember"- ADD CONSTRAINT "WorkspaceMember_pkey" PRIMARY KEY ("workspaceId", "userId");-------- Name: Workspace Workspace_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Workspace"- ADD CONSTRAINT "Workspace_pkey" PRIMARY KEY (id);-------- Name: _prisma_migrations _prisma_migrations_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public._prisma_migrations- ADD CONSTRAINT _prisma_migrations_pkey PRIMARY KEY (id);-------- Name: domainsVirtual domainsVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."domainsVirtual"- ADD CONSTRAINT "domainsVirtual_pkey" PRIMARY KEY (id);-------- Name: latestBuildVirtual latestBuildVirtual_buildId_key; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_buildId_key" UNIQUE ("buildId");-------- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_key; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_key" UNIQUE ("domainsVirtualId");-------- Name: latestBuildVirtual latestBuildVirtual_pkey; Type: CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_pkey" PRIMARY KEY ("projectId");-------- Name: AuthorizationToken_token_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "AuthorizationToken_token_key" ON public."AuthorizationToken" USING btree (token);-------- Name: Build_dev_index; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Build_dev_index" ON public."Build" USING btree ("projectId") WHERE (deployment IS NULL);-------- Name: Build_id_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Build_id_key" ON public."Build" USING btree (id);-------- Name: Build_projectId_createdAt_idx; Type: INDEX; Schema: public; Owner: ------CREATE INDEX "Build_projectId_createdAt_idx" ON public."Build" USING btree ("projectId", "createdAt" DESC);-------- Name: INDEX "Build_projectId_createdAt_idx"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON INDEX public."Build_projectId_createdAt_idx" IS 'Used to speedup ApprovedMarketplaceProduct view';-------- Name: ClientReferences_reference_service_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "ClientReferences_reference_service_key" ON public."ClientReferences" USING btree (reference, service);-------- Name: Domain_domain_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Domain_domain_key" ON public."Domain" USING btree (domain);-------- Name: Notification_recipientId_status_idx; Type: INDEX; Schema: public; Owner: ------CREATE INDEX "Notification_recipientId_status_idx" ON public."Notification" USING btree ("recipientId", status);-------- Name: ProjectDomain_domainId_idx; Type: INDEX; Schema: public; Owner: ------CREATE INDEX "ProjectDomain_domainId_idx" ON public."ProjectDomain" USING btree ("domainId");-------- Name: ProjectDomain_txtRecord_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "ProjectDomain_txtRecord_key" ON public."ProjectDomain" USING btree ("txtRecord");-------- Name: Project_domain_isDeleted_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Project_domain_isDeleted_key" ON public."Project" USING btree (domain, "isDeleted");-------- Name: Project_domain_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Project_domain_key" ON public."Project" USING btree (domain);-------- Name: Project_id_domain_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Project_id_domain_key" ON public."Project" USING btree (id, domain);-------- Name: Project_id_isDeleted_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Project_id_isDeleted_key" ON public."Project" USING btree (id, "isDeleted");-------- Name: Project_isDeleted_marketplaceApprovalStatus_idx; Type: INDEX; Schema: public; Owner: ------CREATE INDEX "Project_isDeleted_marketplaceApprovalStatus_idx" ON public."Project" USING btree ("isDeleted", "marketplaceApprovalStatus");-------- Name: INDEX "Project_isDeleted_marketplaceApprovalStatus_idx"; Type: COMMENT; Schema: public; Owner: ------COMMENT ON INDEX public."Project_isDeleted_marketplaceApprovalStatus_idx" IS 'Used to speedup ApprovedMarketplaceProduct view';-------- Name: TransactionLog_eventId_productId_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "TransactionLog_eventId_productId_key" ON public."TransactionLog" USING btree ("eventId", "productId");-------- Name: User_email_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "User_email_key" ON public."User" USING btree (email);-------- Name: WorkspaceMember_userId_idx; Type: INDEX; Schema: public; Owner: ------CREATE INDEX "WorkspaceMember_userId_idx" ON public."WorkspaceMember" USING btree ("userId");-------- Name: Workspace_userId_isDefault_key; Type: INDEX; Schema: public; Owner: ------CREATE UNIQUE INDEX "Workspace_userId_isDefault_key" ON public."Workspace" USING btree ("userId", "isDefault") WHERE ("isDefault" = true);-------- Name: Asset Asset_name_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Asset"- ADD CONSTRAINT "Asset_name_fkey" FOREIGN KEY (name) REFERENCES public."File"(name) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: AuthorizationToken AuthorizationToken_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."AuthorizationToken"- ADD CONSTRAINT "AuthorizationToken_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: Build Build_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Build"- ADD CONSTRAINT "Build_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: ClientReferences ClientReferences_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."ClientReferences"- ADD CONSTRAINT "ClientReferences_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: File File_uploaderProjectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."File"- ADD CONSTRAINT "File_uploaderProjectId_fkey" FOREIGN KEY ("uploaderProjectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE SET NULL;-------- Name: ProjectDomain ProjectDomain_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."ProjectDomain"- ADD CONSTRAINT "ProjectDomain_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: ProjectDomain ProjectDomain_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."ProjectDomain"- ADD CONSTRAINT "ProjectDomain_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: Project Project_previewImageAssetId_id_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Project"- ADD CONSTRAINT "Project_previewImageAssetId_id_fkey" FOREIGN KEY ("previewImageAssetId", id) REFERENCES public."Asset"(id, "projectId") ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: Project Project_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Project"- ADD CONSTRAINT "Project_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL;-------- Name: Project Project_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Project"- ADD CONSTRAINT "Project_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE SET NULL;-------- Name: TransactionLog TransactionLog_productId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."TransactionLog"- ADD CONSTRAINT "TransactionLog_productId_fkey" FOREIGN KEY ("productId") REFERENCES public."Product"(id) ON UPDATE CASCADE ON DELETE SET NULL;-------- Name: TransactionLog TransactionLog_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."TransactionLog"- ADD CONSTRAINT "TransactionLog_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE SET NULL;-------- Name: WorkspaceMember WorkspaceMember_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."WorkspaceMember"- ADD CONSTRAINT "WorkspaceMember_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE CASCADE;-------- Name: WorkspaceMember WorkspaceMember_workspaceId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."WorkspaceMember"- ADD CONSTRAINT "WorkspaceMember_workspaceId_fkey" FOREIGN KEY ("workspaceId") REFERENCES public."Workspace"(id) ON UPDATE CASCADE ON DELETE CASCADE;-------- Name: Workspace Workspace_userId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."Workspace"- ADD CONSTRAINT "Workspace_userId_fkey" FOREIGN KEY ("userId") REFERENCES public."User"(id) ON UPDATE CASCADE ON DELETE RESTRICT;-------- Name: domainsVirtual domainsVirtual_domainId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."domainsVirtual"- ADD CONSTRAINT "domainsVirtual_domainId_fkey" FOREIGN KEY ("domainId") REFERENCES public."Domain"(id);-------- Name: domainsVirtual domainsVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."domainsVirtual"- ADD CONSTRAINT "domainsVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id);-------- Name: latestBuildVirtual latestBuildVirtual_buildId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_buildId_fkey" FOREIGN KEY ("buildId") REFERENCES public."Build"(id);-------- Name: latestBuildVirtual latestBuildVirtual_domainsVirtualId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_domainsVirtualId_fkey" FOREIGN KEY ("domainsVirtualId") REFERENCES public."domainsVirtual"(id);-------- Name: latestBuildVirtual latestBuildVirtual_projectId_fkey; Type: FK CONSTRAINT; Schema: public; Owner: ------ALTER TABLE ONLY public."latestBuildVirtual"- ADD CONSTRAINT "latestBuildVirtual_projectId_fkey" FOREIGN KEY ("projectId") REFERENCES public."Project"(id);-------- PostgreSQL database dump complete-----\unrestrict J29mZQHzSYuDPm8eRJiWoDBJq2TAh0b0ii1URRuunEM0BP9wmmC5I93noDiexdrdiff --git a/apps/builder/e2e/tests/asset-folders.[shard-1].e2e.ts b/apps/builder/e2e/tests/asset-folders.[shard-1].e2e.tsnew file mode 100644index 0000000000..2ec846c5c1--- /dev/null+++ b/apps/builder/e2e/tests/asset-folders.[shard-1].e2e.ts@@ -0,0 +1,536 @@+import {+ createAssetFolder,+ dragAssetToFolder,+ openAssetsPanel,+ openAssetSettings,+ uploadAsset,+} from "../flows/assets-panel";+import { openProjectBuilder } from "../flows/builder";+import { loginWithSecret } from "../flows/dashboard";+import { dragPointer } from "../flows/drag";+import {+ waitForChangeToBeSaved,+ waitForSyncStatus,+} from "../flows/sync-status";+import { createContentModeProject } from "../fixtures/content-mode-suite";+import { dashboardUrl, newIsolatedPage, newPage, test } from "../harness";++test("Cloning a project preserves nested asset folders", async () => {+ const email = "[email protected]";+ const sourceTitle = "Asset Folder Clone Source";+ const cloneTitle = "Asset Folder Clone Result";+ const fixture = await createContentModeProject({+ email,+ title: sourceTitle,+ builderToken: "asset-folder-clone-e2e-builder-token",+ });+ const page = await newPage();++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const parent = await createAssetFolder({ page, name: "Clone parent" });+ await parent.dblclick();+ const child = await createAssetFolder({ page, name: "Clone child" });+ await child.dblclick();+ const assetTitle = await uploadAsset({+ page,+ filename: "upload-image.svg",+ });++ await loginWithSecret({ page, email });+ const cloneUrl = new URL("/dashboard", dashboardUrl);+ cloneUrl.searchParams.set("projectToCloneAuthToken", fixture.builderToken);+ await page.goto(cloneUrl.href);+ const cloneDialog = page.getByRole("dialog", { name: "Clone project" });+ await cloneDialog.locator('input[name="title"]').fill(cloneTitle);+ await cloneDialog+ .getByRole("button", { name: "Clone", exact: true })+ .click();++ const clonedProjectTitle = page.getByText(cloneTitle, { exact: true });+ await clonedProjectTitle.waitFor();+ const clonedProjectCard = clonedProjectTitle.locator(+ "xpath=ancestor::div[.//a][1]"+ );+ await clonedProjectCard.locator("a").first().click();+ await page.waitForURL(/https:\/\/p-[^.]+\.wstd\.dev:\d+\//);+ await openAssetsPanel({ page, force: true });+ await page+ .getByRole("button", { name: "Folder Clone parent", exact: true })+ .press("Enter");+ await page+ .getByRole("button", { name: "Folder Clone child", exact: true })+ .press("Enter");+ await page.getByTitle(assetTitle).waitFor();+ } finally {+ await page.close();+ }+});++test("Asset can be dragged into a folder", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Drag E2E",+ builderToken: "asset-folder-drag-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();+ const filename = "upload-image.svg";+ const folderName = "Images";++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const assetTitle = await uploadAsset({ page, filename });+ const folder = await createAssetFolder({ page, name: folderName });++ await dragAssetToFolder({ page, assetTitle, folderName });+ await folder.dblclick();+ await page.getByTitle(assetTitle).waitFor();++ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await page+ .getByRole("button", { name: `Folder ${folderName}`, exact: true })+ .dblclick();+ await page.getByTitle(assetTitle).waitFor();+ await waitForSyncStatus({ page, status: "idle" });+ } finally {+ await close();+ }+});++test("Dragging over Back navigates to parent folders before dropping", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Back Drag E2E",+ builderToken: "asset-folder-back-drag-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });++ const parent = await createAssetFolder({ page, name: "Parent" });+ await parent.dblclick();+ const child = await createAssetFolder({ page, name: "Child" });+ await child.dblclick();+ const grandchild = await createAssetFolder({ page, name: "Grandchild" });+ await grandchild.dblclick();+ const assetTitle = await uploadAsset({+ page,+ filename: "upload-image.svg",+ });+ const asset = page.getByTitle(assetTitle);+ const assetBounds = await asset.boundingBox();+ if (assetBounds === null) {+ throw new Error("Expected visible asset drag source");+ }++ const from = {+ x: assetBounds.x + assetBounds.width / 2,+ y: assetBounds.y + assetBounds.height / 2,+ };+ await page.mouse.move(from.x, from.y);+ await page.mouse.down();+ try {+ await page.mouse.move(from.x + 8, from.y + 8, { steps: 4 });++ for (const folderName of ["Grandchild", "Child"]) {+ const back = page.getByRole("button", { name: "Back", exact: true });+ const backBounds = await back.boundingBox();+ if (backBounds === null) {+ throw new Error("Expected visible Back drag target");+ }+ await page.mouse.move(+ backBounds.x - 4,+ backBounds.y + backBounds.height / 2+ );+ await page.mouse.move(+ backBounds.x + backBounds.width / 2,+ backBounds.y + backBounds.height / 2,+ { steps: 4 }+ );+ await page+ .getByRole("button", {+ name: `Folder ${folderName}`,+ exact: true,+ })+ .waitFor({ timeout: 5_000 });+ }++ const assetGrid = page.getByRole("listbox");+ const gridBounds = await assetGrid.boundingBox();+ if (gridBounds === null) {+ throw new Error("Expected visible asset grid drop target");+ }+ await page.mouse.move(+ gridBounds.x + gridBounds.width - 4,+ gridBounds.y + gridBounds.height - 4,+ { steps: 4 }+ );+ const save = waitForChangeToBeSaved({ page, timeout: 30_000 });+ await page.mouse.up();+ await save;+ } catch (error) {+ await page.mouse.up();+ throw error;+ }++ await page.getByTitle(assetTitle).waitFor();+ await page+ .getByRole("button", { name: "Folder Child", exact: true })+ .waitFor();+ } finally {+ await close();+ }+});++test("Asset folder changes wait until the nested selector loses focus", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Selector E2E",+ builderToken: "asset-folder-selector-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });++ const parent = await createAssetFolder({ page, name: "Parent" });+ await parent.dblclick();+ await createAssetFolder({ page, name: "Child" });+ await page.getByRole("button", { name: "Back", exact: true }).click();++ const assetTitle = await uploadAsset({+ page,+ filename: "upload-image.svg",+ });+ await openAssetSettings({ page, filename: assetTitle });++ const settings = page.getByText("Asset settings");+ const topLevelSelect = page.getByRole("combobox", {+ name: "Folder",+ exact: true,+ });+ await topLevelSelect.click();+ await page.getByRole("option", { name: "Parent", exact: true }).click();+ await settings.waitFor();++ const childSelect = page.getByRole("combobox", {+ name: "Asset subfolder level 1",+ exact: true,+ });+ await childSelect.click();+ await page.getByRole("option", { name: "Child", exact: true }).click();+ await settings.waitFor();++ await Promise.all([+ waitForChangeToBeSaved({ page, timeout: 30_000 }),+ page.locator("#asset-manager-filename").click(),+ ]);+ await settings.waitFor({ state: "hidden" });++ await parent.dblclick();+ await page+ .getByRole("button", { name: "Folder Child", exact: true })+ .dblclick();+ await page.getByTitle(assetTitle).waitFor();+ } finally {+ await close();+ }+});++test("Multiselected assets can be dragged into a folder", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Multidrag E2E",+ builderToken: "asset-folder-multidrag-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();+ const folderName = "Selected assets";++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const firstAssetTitle = await uploadAsset({+ page,+ filename: "upload-image.svg",+ });+ const secondAssetTitle = await uploadAsset({+ page,+ filename: "replacement-image.svg",+ });+ const folder = await createAssetFolder({ page, name: folderName });+ const firstAsset = page.getByTitle(firstAssetTitle);+ const secondAsset = page.getByTitle(secondAssetTitle);++ await firstAsset.click();+ await secondAsset.click({+ modifiers: [process.platform === "darwin" ? "Meta" : "Control"],+ });+ if (+ (await page.locator('[role="option"][aria-selected="true"]').count()) !==+ 2+ ) {+ throw new Error("Expected both assets to be selected before dragging");+ }++ await dragAssetToFolder({+ page,+ assetTitle: secondAssetTitle,+ folderName,+ });+ await firstAsset.waitFor({ state: "hidden" });+ await folder.dblclick();+ await page.getByTitle(firstAssetTitle).waitFor();+ await page.getByTitle(secondAssetTitle).waitFor();+ } finally {+ await close();+ }+});++test("Assets can be selected by dragging across the panel", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Lasso Select E2E",+ builderToken: "asset-folder-lasso-select-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const firstAssetTitle = await uploadAsset({+ page,+ filename: "upload-image.svg",+ });+ const secondAssetTitle = await uploadAsset({+ page,+ filename: "replacement-image.svg",+ });+ const firstAsset = page.getByTitle(firstAssetTitle);+ const secondAsset = page.getByTitle(secondAssetTitle);+ const firstBounds = await firstAsset.boundingBox();+ const secondBounds = await secondAsset.boundingBox();+ const viewport = firstAsset.locator(+ "xpath=ancestor::*[@data-radix-scroll-area-viewport]"+ );+ const viewportBounds = await viewport.boundingBox();+ if (+ firstBounds === null ||+ secondBounds === null ||+ viewportBounds === null+ ) {+ throw new Error("Expected visible assets and asset-list viewport");+ }++ const start = {+ x: viewportBounds.x + viewportBounds.width - 2,+ y: viewportBounds.y + viewportBounds.height - 2,+ };+ const end = {+ x: Math.min(firstBounds.x, secondBounds.x) - 2,+ y: Math.min(firstBounds.y, secondBounds.y) - 2,+ };+ await page.mouse.move(start.x, start.y);+ await page.mouse.down();+ try {+ await page.mouse.move(end.x, end.y, { steps: 10 });+ await page.locator("[data-asset-manager-marquee]").waitFor();+ } finally {+ await page.mouse.up();+ }++ for (const asset of [firstAsset, secondAsset]) {+ const option = asset.locator("xpath=ancestor::*[@role='option']");+ if ((await option.getAttribute("aria-selected")) !== "true") {+ throw new Error(+ "Expected dragging across the panel to select both assets"+ );+ }+ }+ } finally {+ await close();+ }+});++test("Multiselected folders can be dragged into a folder", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Multifolder Drag E2E",+ builderToken: "asset-folder-multifolder-drag-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const destination = await createAssetFolder({+ page,+ name: "Destination",+ });+ const alpha = await createAssetFolder({ page, name: "Alpha" });+ const bravo = await createAssetFolder({ page, name: "Bravo" });++ await alpha.click();+ await bravo.click({+ modifiers: [process.platform === "darwin" ? "Meta" : "Control"],+ });+ if (+ (await page.locator('[role="option"][aria-selected="true"]').count()) !==+ 2+ ) {+ throw new Error("Expected both folders to be selected before dragging");+ }++ await Promise.all([+ waitForChangeToBeSaved({ page, timeout: 30_000 }),+ dragPointer({+ page,+ source: bravo,+ target: destination,+ ready: async () =>+ (await destination.getAttribute("data-is-drop-over")) === "true",+ }),+ ]);+ await alpha.waitFor({ state: "hidden" });+ await bravo.waitFor({ state: "hidden" });+ await destination.dblclick();+ await page+ .getByRole("button", { name: "Folder Alpha", exact: true })+ .waitFor();+ await page+ .getByRole("button", { name: "Folder Bravo", exact: true })+ .waitFor();+ } finally {+ await close();+ }+});++test("Folders can be multiselected and deleted as one operation", async () => {+ const fixture = await createContentModeProject({+ email: "[email protected]",+ title: "Asset Folder Multiselect E2E",+ builderToken: "asset-folder-multiselect-e2e-builder-token",+ });+ const { page, close } = await newIsolatedPage();+ const folderNames = ["Alpha", "Bravo", "Charlie"];++ try {+ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await waitForSyncStatus({ page, status: "idle" });+ await openAssetsPanel({ page });+ const folders = [];+ for (const name of folderNames) {+ folders.push(await createAssetFolder({ page, name }));+ }++ await folders[1]!.click({ button: "right" });+ await page.getByRole("menuitem", { name: "Settings" }).waitFor();+ await page.keyboard.press("Escape");++ await folders[0]!.click();+ await folders[2]!.click({ modifiers: ["Shift"] });+ const options = page.getByRole("option");+ for (const folder of folders) {+ const option = options.filter({ has: folder });+ if ((await option.getAttribute("aria-selected")) !== "true") {+ throw new Error("Expected Shift + Click to select the folder range");+ }+ }++ await page.keyboard.press("Escape");+ await folders[0]!.click();+ await folders[2]!.click({+ modifiers: [process.platform === "darwin" ? "Meta" : "Control"],+ });+ const selectedOptions = page.locator(+ '[role="option"][aria-selected="true"]'+ );+ if ((await selectedOptions.count()) !== 2) {+ throw new Error("Expected Cmd/Ctrl + Click to select two folders");+ }++ await folders[0]!.click({ button: "right" });+ await page.getByRole("menuitem", { name: "Delete" }).click();+ const deleteDialog = page+ .getByRole("dialog")+ .filter({ hasText: "Delete selected items" });+ await deleteDialog.waitFor();+ await Promise.all([+ waitForChangeToBeSaved({ page }),+ deleteDialog.getByRole("button", { name: "Delete" }).click(),+ ]);++ await folders[0]!.waitFor({ state: "hidden" });+ await folders[2]!.waitFor({ state: "hidden" });+ await folders[1]!.waitFor({ state: "visible" });++ await openProjectBuilder({+ page,+ projectId: fixture.projectId,+ authToken: fixture.builderToken,+ });+ await openAssetsPanel({ page });+ await page+ .getByRole("button", { name: "Folder Bravo", exact: true })+ .waitFor();+ for (const deletedName of ["Alpha", "Charlie"]) {+ if (+ await page+ .getByRole("button", { name: `Folder ${deletedName}`, exact: true })+ .isVisible()+ ) {+ throw new Error(`Expected ${deletedName} to stay deleted after reload`);+ }+ }+ } finally {+ await close();+ }+});diff --git a/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts b/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.tsindex c99e7df1ce..7b463ac66e 100644--- a/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts+++ b/apps/builder/e2e/tests/content-mode-editing.[shard-1].e2e.ts@@ -1,6 +1,6 @@import {deleteSelectedAsset,- openAssetDetails,+ openAssetSettings,openAssetsPanel,replaceSelectedAsset,uploadAsset,@@ -193,11 +193,11 @@ test("Editor can upload, replace, and delete asset in content mode", async () =>let replacementAssetTitle = "";await measure("content mode replace asset", async () => {- await openAssetDetails({ page, filename: uploadedAssetTitle });+ await openAssetSettings({ page, filename: uploadedAssetTitle });const assetId = await page.locator("#asset-manager-id").inputValue();if (assetId.length === 0) {throw new Error(- "Expected Asset details to expose the uploaded asset id"+ "Expected Asset settings to expose the uploaded asset id");}await page.getByText("0 uses", { exact: true }).waitFor();@@ -208,7 +208,7 @@ test("Editor can upload, replace, and delete asset in content mode", async () =>});await measure("content mode delete asset", async () => {- await openAssetDetails({ page, filename: replacementAssetTitle });+ await openAssetSettings({ page, filename: replacementAssetTitle });await deleteSelectedAsset({page,filename: replacementAssetTitle,@@ -291,7 +291,7 @@ test("Editor can replace image source with asset in content mode", async () => {let replacementAssetTitle = "";await measure("content mode replace used image source asset", async () => {await openAssetsPanel({ page });- await openAssetDetails({+ await openAssetSettings({page,filename: uploadedAssetTitle,});diff --git a/fixtures/react-router-cloudflare/.webstudio/data.json b/fixtures/react-router-cloudflare/.webstudio/data.jsonindex ae78057340..6887d5dc34 100644--- a/fixtures/react-router-cloudflare/.webstudio/data.json+++ b/fixtures/react-router-cloudflare/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -496,6 +496,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/react-router-docker/.webstudio/data.json b/fixtures/react-router-docker/.webstudio/data.jsonindex ae78057340..6887d5dc34 100644--- a/fixtures/react-router-docker/.webstudio/data.json+++ b/fixtures/react-router-docker/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -496,6 +496,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/react-router-netlify/.webstudio/data.json b/fixtures/react-router-netlify/.webstudio/data.jsonindex ae78057340..6887d5dc34 100644--- a/fixtures/react-router-netlify/.webstudio/data.json+++ b/fixtures/react-router-netlify/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -496,6 +496,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/react-router-vercel/.webstudio/data.json b/fixtures/react-router-vercel/.webstudio/data.jsonindex ae78057340..6887d5dc34 100644--- a/fixtures/react-router-vercel/.webstudio/data.json+++ b/fixtures/react-router-vercel/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "f565d527-32e7-4731-bc71-aca9e9574587","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -496,6 +496,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/ssg-cloudflare-pages/.webstudio/data.json b/fixtures/ssg-cloudflare-pages/.webstudio/data.jsonindex 766549deda..5cfc72569f 100644--- a/fixtures/ssg-cloudflare-pages/.webstudio/data.json+++ b/fixtures/ssg-cloudflare-pages/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -494,6 +494,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json b/fixtures/ssg-netlify-by-project-id/.webstudio/data.jsonindex f4b42f6af6..0e572d0bb8 100644--- a/fixtures/ssg-netlify-by-project-id/.webstudio/data.json+++ b/fixtures/ssg-netlify-by-project-id/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "8f0fdff2-e76b-4f86-9203-ea7df5f1143c","projectId": "8a7358b1-7de3-459d-b7b1-56dddfb6ce1e",@@ -201,6 +201,7 @@}],"assets": [],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/webstudio-cloudflare-template/.webstudio/data.json b/fixtures/webstudio-cloudflare-template/.webstudio/data.jsonindex 766549deda..5cfc72569f 100644--- a/fixtures/webstudio-cloudflare-template/.webstudio/data.json+++ b/fixtures/webstudio-cloudflare-template/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "a2e8de30-03d5-4514-a3a6-406b3266a3af","projectId": "d845c167-ea07-4875-b08d-83e97c09dcce",@@ -494,6 +494,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/fixtures/webstudio-features/.webstudio/data.json b/fixtures/webstudio-features/.webstudio/data.jsonindex f0a10094eb..ecf38edc86 100644--- a/fixtures/webstudio-features/.webstudio/data.json+++ b/fixtures/webstudio-features/.webstudio/data.json@@ -1,5 +1,5 @@{- "bundleVersion": "bundle-19n82kd",+ "bundleVersion": "bundle-1h06fyv","build": {"id": "1b66ee06-8ea5-4420-9a0e-e0d3a67aca32","projectId": "cddc1d44-af37-4cb6-a430-d300cf6f932d",@@ -7291,6 +7291,7 @@"type": "image"}],+ "assetFolders": [],"user": {"email": "[email protected]"},diff --git a/package.json b/package.jsonindex 24f34e280e..b2b13dc4c4 100644--- a/package.json+++ b/package.json@@ -18,7 +18,7 @@"e2e:builder": "bash ./apps/builder/e2e/run-local.sh","e2e:builder:dev:backend": "E2E_SKIP_CLEANUP=true E2E_RUN_TESTS=false E2E_START_POSTGREST=true E2E_DB_BOOTSTRAP=if-empty E2E_INSTALL_PLAYWRIGHT=false bash ./apps/builder/e2e/run-local.sh","e2e:builder:dev": "E2E_SKIP_CLEANUP=true E2E_DB_BOOTSTRAP=if-empty E2E_INSTALL_PLAYWRIGHT=false E2E_BUILDER_URL=${E2E_BUILDER_URL:-https://127.0.0.1:3000} bash ./apps/builder/e2e/run-local.sh",- "e2e:builder:update-schema": "E2E_DB_BOOTSTRAP=migrations E2E_WRITE_SCHEMA_SNAPSHOT=true E2E_RUN_TESTS=false bash ./apps/builder/e2e/run-local.sh",+ "e2e:builder:refresh-schema-cache": "E2E_DB_BOOTSTRAP=migrations E2E_WRITE_SCHEMA_SNAPSHOT=true E2E_RUN_TESTS=false bash ./apps/builder/e2e/run-local.sh","playwright": "pnpm -r playwright-init","format": "oxfmt","storybook:dev": "storybook dev -p 6006",diff --git a/packages/asset-uploader/src/asset-patch-core.ts b/packages/asset-uploader/src/asset-patch-core.tsindex 4947881fe9..dcdfc2747c 100644--- a/packages/asset-uploader/src/asset-patch-core.ts+++ b/packages/asset-uploader/src/asset-patch-core.ts@@ -1,18 +1,22 @@-import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";import { type Asset, assets } from "@webstudio-is/sdk";import type { Client } from "@webstudio-is/postgrest/index.server";import { formatAsset } from "./utils/format-asset";--// This module applies Immer patches to Maps and can be imported directly,-// so initialize the required Immer plugins next to the production patch use.-enableMapSet();-enablePatches();--const assertPostgrestSuccess = (result: { error: unknown }) => {- if (result.error) {- throw result.error;- }-};+import {+ applyValidatedMapPatches,+ assertPostgrestSuccess,+ diffMaps,+ type Patch,+} from "./patch-utils";++export const createAssetRows = (assets: Iterable<Asset>, projectId: string) =>+ Array.from(assets, (asset) => ({+ id: asset.id,+ projectId,+ name: asset.name,+ filename: asset.filename ?? null,+ description: asset.description ?? null,+ folderId: asset.folderId ?? null,+ }));export const loadAssetsByProjectWithClient = async (projectId: string,@@ -28,6 +32,7 @@ export const loadAssetsByProjectWithClient = async (projectId,filename,description,+ folderId,file:File!inner (*)`)@@ -44,11 +49,19 @@ export const loadAssetsByProjectWithClient = async (projectId,filename,description,+ folderId,file,} of assets.data ?? []) {if (file) {result.push(- formatAsset({ assetId, projectId, filename, description, file })+ formatAsset({+ assetId,+ projectId,+ filename,+ description,+ folderId,+ file,+ }));}}@@ -126,53 +139,51 @@ export const patchAssetsWithClient = async (for (const asset of assetsList) {assetsMap.set(asset.id, asset);}- const patchedAssets = applyPatches(assetsMap, patches);- // Validate assets without recreating objects.- assets.parse(patchedAssets);-- const deletedAssetIds: Asset["id"][] = [];- for (const assetId of assetsMap.keys()) {- if (patchedAssets.has(assetId) === false) {- deletedAssetIds.push(assetId);- }- }+ const patchedAssets = applyValidatedMapPatches(assetsMap, patches, (value) =>+ assets.parse(value)+ );+ const {+ added,+ updated,+ deletedKeys: deletedAssetIds,+ } = diffMaps(+ assetsMap,+ patchedAssets,+ (previous, asset) =>+ previous.filename === asset.filename &&+ previous.description === asset.description &&+ previous.folderId === asset.folderId+ );if (deletedAssetIds.length !== 0) {await deleteAssetsWithClient({ projectId, ids: deletedAssetIds }, client);}- for (const asset of assetsMap.values()) {- const patchedAsset = patchedAssets.get(asset.id);- const metadataChanged =- patchedAsset !== undefined &&- (asset.filename !== patchedAsset.filename ||- asset.description !== patchedAsset.description);- if (metadataChanged) {- const { filename, description } = patchedAsset;- const updatedAsset = await client- .from("Asset")- .update({ filename, description })- .eq("id", asset.id)- .eq("projectId", asset.projectId)- .select("filename, description")- .single();- assertPostgrestSuccess(updatedAsset);- if (- updatedAsset.data?.filename !== (filename ?? null) ||- updatedAsset.data?.description !== (description ?? null)- ) {- throw new Error(- `Asset metadata update was not persisted for ${asset.id}`- );- }+ for (const asset of updated) {+ const { filename, description, folderId } = asset;+ const updatedAsset = await client+ .from("Asset")+ .update({+ filename: filename ?? null,+ description: description ?? null,+ folderId: folderId ?? null,+ })+ .eq("id", asset.id)+ .eq("projectId", asset.projectId)+ .select("filename, description, folderId")+ .single();+ assertPostgrestSuccess(updatedAsset);+ if (+ updatedAsset.data?.filename !== (filename ?? null) ||+ updatedAsset.data?.description !== (description ?? null) ||+ (updatedAsset.data?.folderId ?? null) !== (folderId ?? null)+ ) {+ throw new Error(+ `Asset metadata update was not persisted for ${asset.id}`+ );}}- const addedAssets: Asset[] = [];- for (const [assetId, asset] of patchedAssets) {- if (assetsMap.has(assetId) === false) {- addedAssets.push(asset);- }- }+ const addedAssets: Asset[] = added;if (addedAssets.length !== 0) {const files = await client.from("File")@@ -193,14 +204,12 @@ export const patchAssetsWithClient = async (assertPostgrestSuccess(restoredFiles);const insertedAssets = await client.from("Asset").insert(- addedAssets- // making sure corresponding file exist before creating an asset that references it- .filter((asset) => fileNames.has(asset.name))- .map((asset) => ({- id: asset.id,- projectId,- name: asset.name,- }))+ createAssetRows(+ // Make sure the corresponding file exists before creating an asset+ // that references it.+ addedAssets.filter((asset) => fileNames.has(asset.name)),+ projectId+ ));assertPostgrestSuccess(insertedAssets);}diff --git a/packages/asset-uploader/src/db/load.test.ts b/packages/asset-uploader/src/db/load.test.tsindex 11dd22e1a7..6ef8ac8017 100644--- a/packages/asset-uploader/src/db/load.test.ts+++ b/packages/asset-uploader/src/db/load.test.ts@@ -33,6 +33,7 @@ const assetRow = {projectId: "proj-1",filename: "photo.jpg",description: null,+ folderId: null,file: {name: "photo.jpg",format: "jpg",@@ -53,7 +54,8 @@ describe("loadAssetsByProject (msw)", () => {expect(url.searchParams.get("projectId")).toBe("eq.proj-1");expect(url.searchParams.get("file.status")).toBe("eq.UPLOADED");return json([assetRow]);- })+ }),+ db.get("AssetFolder", () => json([])));const result = await loadAssetsByProject("proj-1", createContext());@@ -69,13 +71,48 @@ describe("loadAssetsByProject (msw)", () => {test("returns empty array when project has no uploaded assets", async () => {server.use(projectOwnershipHandler,- db.get("Asset", () => json([]))+ db.get("Asset", () => json([])),+ db.get("AssetFolder", () => json([])));const result = await loadAssetsByProject("proj-1", createContext());expect(result).toEqual([]);});+ test("places assets with a missing folder in the root", async () => {+ server.use(+ projectOwnershipHandler,+ db.get("Asset", () =>+ json([{ ...assetRow, folderId: "deleted-folder" }])+ ),+ db.get("AssetFolder", () => json([]))+ );++ const [asset] = await loadAssetsByProject("proj-1", createContext());+ expect(asset).not.toHaveProperty("folderId");+ });++ test("preserves references to existing folders", async () => {+ server.use(+ projectOwnershipHandler,+ db.get("Asset", () => json([{ ...assetRow, folderId: "folder-1" }])),+ db.get("AssetFolder", () =>+ json([+ {+ id: "folder-1",+ projectId: "proj-1",+ name: "Images",+ parentId: null,+ createdAt: "2024-01-01T00:00:00.000Z",+ },+ ])+ )+ );++ const [asset] = await loadAssetsByProject("proj-1", createContext());+ expect(asset?.folderId).toBe("folder-1");+ });+test("throws AuthorizationError when caller lacks access", async () => {// Use a project the test user does not own ("proj-denied") so hasProjectPermit// returns false. We cannot reuse "proj-1" here because hasProjectPermit isdiff --git a/packages/asset-uploader/src/db/load.ts b/packages/asset-uploader/src/db/load.tsindex 1545ec05f8..7f1b72a5d5 100644--- a/packages/asset-uploader/src/db/load.ts+++ b/packages/asset-uploader/src/db/load.ts@@ -1,28 +1,72 @@import {authorizeProject,- type AppContext,AuthorizationError,+ type AppContext,} from "@webstudio-is/trpc-interface/index.server";-import type { Asset } from "@webstudio-is/sdk";+import {+ normalizeAssetFolderData,+ type Asset,+ type AssetFolder,+} from "@webstudio-is/sdk";import { loadAssetsByProjectWithClient } from "../asset-patch-core";+import { loadAssetFoldersByProjectWithClient } from "../folder-persistence";-export const loadAssetsByProject = async (+type LoadAssetOptions = { skipPermissionsCheck?: boolean };++const assertAssetReadPermission = async (projectId: string,context: AppContext,- { skipPermissionsCheck = false }: { skipPermissionsCheck?: boolean } = {}-): Promise<Asset[]> => {- const canRead =- skipPermissionsCheck ||+ skipPermissionsCheck: boolean+) => {+ if (+ skipPermissionsCheck === false &&(await authorizeProject.hasProjectPermit({ projectId, permit: "view" },context- ));-- if (canRead === false) {+ )) === false+ ) {throw new AuthorizationError(- "You don't have access to this project assets"+ "You don't have access to this project's assets");}+};++export const loadAssetsByProject = async (+ projectId: string,+ context: AppContext,+ { skipPermissionsCheck = false }: LoadAssetOptions = {}+): Promise<Asset[]> => {+ const { assets } = await loadAssetDataByProject(projectId, context, {+ skipPermissionsCheck,+ });+ return assets;+};++export const loadAssetFoldersByProject = async (+ projectId: string,+ context: AppContext,+ { skipPermissionsCheck = false }: LoadAssetOptions = {}+): Promise<AssetFolder[]> => {+ await assertAssetReadPermission(projectId, context, skipPermissionsCheck);+ return loadAssetFoldersByProjectWithClient(+ projectId,+ context.postgrest.client+ );+};- return loadAssetsByProjectWithClient(projectId, context.postgrest.client);+export const loadAssetDataByProject = async (+ projectId: string,+ context: AppContext,+ { skipPermissionsCheck = false }: LoadAssetOptions = {}+) => {+ await assertAssetReadPermission(projectId, context, skipPermissionsCheck);+ const [assets, assetFolders] = await Promise.all([+ loadAssetsByProjectWithClient(projectId, context.postgrest.client),+ loadAssetFoldersByProjectWithClient(projectId, context.postgrest.client),+ ]);+ const normalized = normalizeAssetFolderData({+ assets,+ folders: assetFolders,+ });+ return { assets: normalized.assets, assetFolders: normalized.folders };};diff --git a/packages/asset-uploader/src/folder-persistence.ts b/packages/asset-uploader/src/folder-persistence.tsnew file mode 100644index 0000000000..bd06d19ada--- /dev/null+++ b/packages/asset-uploader/src/folder-persistence.ts@@ -0,0 +1,124 @@+import {+ assetFolders,+ createAssetFolderHierarchy,+ type AssetFolder,+} from "@webstudio-is/sdk";+import type { Client } from "@webstudio-is/postgrest/index.server";+import {+ applyValidatedMapPatches,+ assertPostgrestSuccess,+ diffMaps,+ type Patch,+} from "./patch-utils";++export const createAssetFolderRows = (+ folders: Iterable<AssetFolder>,+ projectId: string+) => {+ const folderList = Array.from(folders);+ const hierarchy = createAssetFolderHierarchy(+ new Map(folderList.map((folder) => [folder.id, folder]))+ );+ return hierarchy.sortByDepth(folderList).map((folder) => ({+ id: folder.id,+ projectId,+ name: folder.name,+ parentId: folder.parentId ?? null,+ createdAt: folder.createdAt,+ }));+};++export const loadAssetFoldersByProjectWithClient = async (+ projectId: string,+ client: Client+): Promise<AssetFolder[]> => {+ const result = await client+ .from("AssetFolder")+ .select("id, projectId, name, parentId, createdAt")+ .eq("projectId", projectId)+ .order("id");+ assertPostgrestSuccess(result);++ return (result.data ?? []).map((folder) => ({+ id: folder.id,+ projectId: folder.projectId,+ name: folder.name,+ parentId: folder.parentId ?? undefined,+ createdAt: folder.createdAt,+ }));+};++export const patchAssetFoldersWithClient = async (+ { projectId, client }: { projectId: string; client: Client },+ patches: Array<Patch>,+ { deferDeletes = false }: { deferDeletes?: boolean } = {}+): Promise<string[]> => {+ const currentList = await loadAssetFoldersByProjectWithClient(+ projectId,+ client+ );+ const current = new Map(currentList.map((folder) => [folder.id, folder]));+ const validated = applyValidatedMapPatches(current, patches, (value) =>+ assetFolders.parse(value)+ );+ for (const folder of validated.values()) {+ if (folder.projectId !== projectId) {+ throw new Error(`Asset folder ${folder.id} belongs to another project`);+ }+ }++ const { added, updated, deletedKeys } = diffMaps(+ current,+ validated,+ (previous, folder) =>+ previous.name === folder.name && previous.parentId === folder.parentId+ );+ const changed = [...added, ...updated];+ if (changed.length > 0) {+ const result = await client+ .from("AssetFolder")+ .upsert(createAssetFolderRows(changed, projectId), {+ onConflict: "id,projectId",+ })+ .select("id, name, parentId");+ assertPostgrestSuccess(result);+ const persisted = new Map((result.data ?? []).map((row) => [row.id, row]));+ for (const folder of changed) {+ const row = persisted.get(folder.id);+ if (+ row?.name !== folder.name ||+ (row.parentId ?? undefined) !== folder.parentId+ ) {+ throw new Error(+ `Asset folder update was not persisted for ${folder.id}`+ );+ }+ }+ }++ if (deletedKeys.length > 0 && deferDeletes === false) {+ await deleteAssetFoldersWithClient({ projectId, ids: deletedKeys }, client);+ }+ return deletedKeys;+};++export const deleteAssetFoldersWithClient = async (+ { projectId, ids }: { projectId: string; ids: string[] },+ client: Client+) => {+ if (ids.length === 0) {+ return;+ }+ const result = await client+ .from("AssetFolder")+ .delete()+ .in("id", ids)+ .eq("projectId", projectId)+ .select("id");+ assertPostgrestSuccess(result);+ const deletedIds = new Set((result.data ?? []).map(({ id }) => id));+ const missingId = ids.find((id) => deletedIds.has(id) === false);+ if (missingId !== undefined) {+ throw new Error(`Asset folder deletion was not persisted for ${missingId}`);+ }+};diff --git a/packages/asset-uploader/src/index.server.ts b/packages/asset-uploader/src/index.server.tsindex b832609539..35b7127fb0 100644--- a/packages/asset-uploader/src/index.server.ts+++ b/packages/asset-uploader/src/index.server.ts@@ -3,5 +3,6 @@ export * from "./upload";export * from "./delete";export * from "./patch";export * from "./asset-patch-core";+export * from "./folder-persistence";export * from "./clients/fs/fs";export * from "./clients/s3/s3";diff --git a/packages/asset-uploader/src/patch-utils.ts b/packages/asset-uploader/src/patch-utils.tsnew file mode 100644index 0000000000..b84bb341a9--- /dev/null+++ b/packages/asset-uploader/src/patch-utils.ts@@ -0,0 +1,42 @@+import { applyPatches, enableMapSet, enablePatches, type Patch } from "immer";++enableMapSet();+enablePatches();++export type { Patch };++export const assertPostgrestSuccess = (result: { error: unknown }) => {+ if (result.error) {+ throw result.error;+ }+};++export const applyValidatedMapPatches = <Key, Value>(+ current: Map<Key, Value>,+ patches: Patch[],+ parse: (value: unknown) => Map<Key, Value>+) => parse(applyPatches(current, patches));++export const diffMaps = <Key, Value>(+ current: ReadonlyMap<Key, Value>,+ next: ReadonlyMap<Key, Value>,+ isEqual: (current: Value, next: Value) => boolean+) => {+ const added: Value[] = [];+ const updated: Value[] = [];+ for (const [key, value] of next) {+ const previous = current.get(key);+ if (previous === undefined) {+ added.push(value);+ } else if (isEqual(previous, value) === false) {+ updated.push(value);+ }+ }+ return {+ added,+ updated,+ deletedKeys: Array.from(current.keys()).filter(+ (key) => next.has(key) === false+ ),+ };+};diff --git a/packages/asset-uploader/src/patch.test.ts b/packages/asset-uploader/src/patch.test.tsindex ee4ec51e64..88b409b731 100644--- a/packages/asset-uploader/src/patch.test.ts+++ b/packages/asset-uploader/src/patch.test.ts@@ -11,6 +11,10 @@ import {loadAssetsByProjectWithClient,patchAssetsWithClient,} from "./asset-patch-core";+import {+ deleteAssetFoldersWithClient,+ patchAssetFoldersWithClient,+} from "./folder-persistence";import { patchAssets } from "./patch";import type { Patch } from "immer";@@ -34,6 +38,179 @@ const ownershipHandler = db.get("Project", ({ request }) => {return json(null);});+describe("asset folder persistence", () => {+ test("inserts parents before children", async () => {+ const projectId = uid();+ let inserted: Array<{ id: string }> = [];+ server.use(+ db.get("AssetFolder", () => json([])),+ db.post("AssetFolder", async ({ request }) => {+ inserted = (await request.json()) as Array<{ id: string }>;+ return json(inserted);+ })+ );++ await patchAssetFoldersWithClient(+ { projectId, client: testContext.postgrest.client },+ [+ {+ op: "add",+ path: ["child"],+ value: {+ id: "child",+ projectId,+ name: "Child",+ parentId: "parent",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ {+ op: "add",+ path: ["parent"],+ value: {+ id: "parent",+ projectId,+ name: "Parent",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ ]+ );++ expect(inserted.map(({ id }) => id)).toEqual(["parent", "child"]);+ });++ test("can defer folder deletion until assets are moved", async () => {+ const projectId = uid();+ let deleteCount = 0;+ server.use(+ db.get("AssetFolder", () =>+ json([+ {+ id: "folder",+ projectId,+ name: "Folder",+ parentId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ])+ ),+ db.delete("AssetFolder", () => {+ deleteCount += 1;+ return json([{ id: "folder" }]);+ })+ );++ const ids = await patchAssetFoldersWithClient(+ { projectId, client: testContext.postgrest.client },+ [{ op: "remove", path: ["folder"] }],+ { deferDeletes: true }+ );+ expect(ids).toEqual(["folder"]);+ expect(deleteCount).toBe(0);++ await deleteAssetFoldersWithClient(+ { projectId, ids },+ testContext.postgrest.client+ );+ expect(deleteCount).toBe(1);+ });++ test("persists moving a nested folder to root as null", async () => {+ const projectId = uid();+ let updatedParentId: unknown = "not-updated";+ server.use(+ db.get("AssetFolder", () =>+ json([+ {+ id: "parent",+ projectId,+ name: "Parent",+ parentId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ {+ id: "child",+ projectId,+ name: "Child",+ parentId: "parent",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ])+ ),+ db.post("AssetFolder", async ({ request }) => {+ const [update] = (await request.json()) as Array<{+ id: string;+ name: string;+ parentId: unknown;+ }>;+ updatedParentId = update.parentId;+ return json([update]);+ })+ );++ await patchAssetFoldersWithClient(+ { projectId, client: testContext.postgrest.client },+ [{ op: "remove", path: ["child", "parentId"] }]+ );+ expect(updatedParentId).toBeNull();+ });++ test("rejects folders that claim another project", async () => {+ const projectId = uid();+ server.use(db.get("AssetFolder", () => json([])));++ await expect(+ patchAssetFoldersWithClient(+ { projectId, client: testContext.postgrest.client },+ [+ {+ op: "add",+ path: ["folder"],+ value: {+ id: "folder",+ projectId: "another-project",+ name: "Folder",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ ]+ )+ ).rejects.toThrow("belongs to another project");+ });++ test("persists the normalized folder name returned by validation", async () => {+ const projectId = uid();+ let insertedName: string | undefined;+ server.use(+ db.get("AssetFolder", () => json([])),+ db.post("AssetFolder", async ({ request }) => {+ const rows = (await request.json()) as Array<{ name: string }>;+ insertedName = rows[0]?.name;+ return json(rows);+ })+ );++ await patchAssetFoldersWithClient(+ { projectId, client: testContext.postgrest.client },+ [+ {+ op: "add",+ path: ["folder"],+ value: {+ id: "folder",+ projectId,+ name: " Media ",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ ]+ );++ expect(insertedName).toBe("Media");+ });+});+const assetRow = {assetId: "asset-1",projectId: "proj-1",@@ -152,6 +329,32 @@ describe("patchAssets (msw)", () => {]);});+ test("persists moving an asset to root as null", async () => {+ const projectId = uid();+ const localAssetRow = { ...assetRow, projectId, folderId: "folder" };+ let updatedFolderId: unknown = "not-updated";+ server.use(+ ownershipHandler,+ db.get("Asset", () => json([localAssetRow])),+ db.patch("Asset", async ({ request }) => {+ updatedFolderId = ((await request.json()) as { folderId: unknown })+ .folderId;+ return json({+ filename: localAssetRow.filename,+ description: localAssetRow.description,+ folderId: null,+ });+ })+ );++ await patchAssets(+ { projectId },+ [{ op: "remove", path: ["asset-1", "folderId"] }],+ createContext()+ );+ expect(updatedFolderId).toBeNull();+ });+test("does not update metadata when adding an existing asset", async () => {const projectId = uid();const localAssetRow = { ...assetRow, projectId };diff --git a/packages/asset-uploader/src/upload.test.ts b/packages/asset-uploader/src/upload.test.tsindex afba4fe90d..db388bcf82 100644--- a/packages/asset-uploader/src/upload.test.ts+++ b/packages/asset-uploader/src/upload.test.ts@@ -79,6 +79,7 @@ describe("createUploadTicket", () => {id: "asset-1",projectId: "project-1",name: expect.stringMatching(/^photo_.+\.png$/),+ folderId: "campaign",});return empty({ status: 201 });})@@ -89,6 +90,7 @@ describe("createUploadTicket", () => {projectId: "project-1",type: "image/png",filename: "photo.png",+ folderId: "campaign",},createContext(),() => "asset-1"diff --git a/packages/asset-uploader/src/upload.ts b/packages/asset-uploader/src/upload.tsindex 18c8d1752c..d592f7a5c0 100644--- a/packages/asset-uploader/src/upload.ts+++ b/packages/asset-uploader/src/upload.ts@@ -15,6 +15,7 @@ type UploadData = {projectId: string;type: string;filename: string;+ folderId?: string;};export type UploadTicket = {@@ -35,7 +36,7 @@ export const createUploadTicket = async (context: AppContext,createId: () => Asset["id"] = nanoid): Promise<UploadTicket> => {- const { projectId, type, filename } = data;+ const { projectId, type, filename, folderId } = data;const canEdit = await authorizeProject.hasProjectPermit({ projectId, permit: "edit" },context@@ -120,6 +121,7 @@ export const createUploadTicket = async (id: assetId,projectId,name,+ folderId,});if (assetInsert.error) {await context.postgrest.client.from("File").delete().eq("name", name);@@ -191,7 +193,7 @@ export const uploadFile = async (}const asset = await context.postgrest.client.from("Asset")- .select("id, projectId, filename, description")+ .select("id, projectId, filename, description, folderId").eq("name", name).eq("projectId", projectId).single();@@ -206,6 +208,7 @@ export const uploadFile = async (projectId: asset.data.projectId,filename: asset.data.filename,description: asset.data.description,+ folderId: asset.data.folderId,file: file.data,});} catch (error) {diff --git a/packages/asset-uploader/src/utils/format-asset.ts b/packages/asset-uploader/src/utils/format-asset.tsindex bd74c0fb93..7437eaec7b 100644--- a/packages/asset-uploader/src/utils/format-asset.ts+++ b/packages/asset-uploader/src/utils/format-asset.ts@@ -6,12 +6,14 @@ export const formatAsset = ({projectId,filename,description,+ folderId,file,}: {assetId: string;projectId: string;filename: string | null;description: string | null;+ folderId?: string | null;file: {name: string;format: string;@@ -23,17 +25,21 @@ export const formatAsset = ({}): Asset => {const isFont = FONT_FORMATS.has(file.format as FontFormat);const parsedMeta = JSON.parse(file.meta);+ const base = {+ id: assetId,+ name: file.name,+ projectId,+ filename: filename ?? undefined,+ description: description ?? undefined,+ folderId: folderId ?? undefined,+ size: file.size,+ createdAt: file.createdAt,+ };if (isFont) {return {- id: assetId,- name: file.name,- projectId,- filename: filename ?? undefined,- description: description ?? undefined,- size: file.size,+ ...base,type: "font",- createdAt: file.createdAt,format: file.format as FontFormat,meta: fontMeta.parse(parsedMeta),};@@ -52,30 +58,18 @@ export const formatAsset = ({if (isImage) {return {- id: assetId,- name: file.name,- projectId,- filename: filename ?? undefined,- description: description ?? undefined,- size: file.size,+ ...base,type: "image",format: file.format,- createdAt: file.createdAt,meta: imageMeta.parse(parsedMeta),};}// Default to file type for everything else (including videos)return {- id: assetId,- name: file.name,- projectId,- filename: filename ?? undefined,- description: description ?? undefined,- size: file.size,+ ...base,type: "file",format: file.format,- createdAt: file.createdAt,meta: {},};};diff --git a/packages/cli/src/commands/api-command-docs.test.ts b/packages/cli/src/commands/api-command-docs.test.tsindex 5bec1c16af..3472cf9b88 100644--- a/packages/cli/src/commands/api-command-docs.test.ts+++ b/packages/cli/src/commands/api-command-docs.test.ts@@ -51,6 +51,10 @@ const createMetadataOnlyMcpAdapter = () =>throw new Error("MCP metadata reads must not execute operations.");},importProject: async () => ({ imported: true }),+ downloadAsset: async ({ assetId }) => ({+ assetId,+ path: `.webstudio/assets/${assetId}`,+ }),captureScreenshot: async () => ({output: "current.png",browserPath: "/browser",diff --git a/packages/cli/src/commands/api-command-metadata.ts b/packages/cli/src/commands/api-command-metadata.tsindex e2015023f6..a28da6be70 100644--- a/packages/cli/src/commands/api-command-metadata.ts+++ b/packages/cli/src/commands/api-command-metadata.ts@@ -213,6 +213,7 @@ const apiCommandOptionsByCommand: Partial<"delete-domain": apiCommand.deleteDomainCommandOptions,"verify-domain": apiCommand.verifyDomainCommandOptions,"list-assets": apiCommand.assetsCommandOptions,+ "get-asset": apiCommand.assetCommandOptions,"list-fonts": apiCommand.fontsCommandOptions,"upload-asset": apiCommand.uploadAssetCommandOptions,"upload-assets": apiCommand.uploadAssetsCommandOptions,diff --git a/packages/cli/src/commands/api-command.test.ts b/packages/cli/src/commands/api-command.test.tsindex ab6ac13dd0..91647c045b 100644--- a/packages/cli/src/commands/api-command.test.ts+++ b/packages/cli/src/commands/api-command.test.ts@@ -387,6 +387,12 @@ const simpleCommandCases = ["getPageByPath",{ path: "/pricing" },],+ [+ "asset details",+ { command: "get-asset", asset: "asset-1" },+ "getAsset",+ { assetId: "asset-1" },+ ],] satisfies Array<readonly [string,diff --git a/packages/cli/src/commands/api-command.ts b/packages/cli/src/commands/api-command.tsindex fec2be4cec..2b76524aea 100644--- a/packages/cli/src/commands/api-command.ts+++ b/packages/cli/src/commands/api-command.ts@@ -3011,6 +3011,13 @@ const apiCommandHandlers: Partial<Record<ApiCommandName, ApiCommandHandler>> = {dependencies);},+ "get-asset": async (options, connection, dependencies) =>+ runProjectSessionCommand(+ "get-asset",+ { assetId: requireSingleOption(options.asset, "--asset") },+ connection,+ dependencies+ ),"list-fonts": async (options, connection, dependencies) =>runProjectSessionCommand("list-fonts",diff --git a/packages/cli/src/commands/man.ts b/packages/cli/src/commands/man.tsindex df1f5d9cee..6bd92e56de 100644--- a/packages/cli/src/commands/man.ts+++ b/packages/cli/src/commands/man.ts@@ -219,8 +219,16 @@ const taskRecipeUseCases = {],assets: ["List assets",+ "Get asset",+ "List asset folders",+ "Create asset folder",+ "Update asset folder",+ "Duplicate asset folder",+ "Delete asset folder","Upload one asset","Upload asset batch",+ "Duplicate asset",+ "Download asset","Find asset usage","Replace asset references","Delete assets",diff --git a/packages/cli/src/commands/mcp.test.ts b/packages/cli/src/commands/mcp.test.tsindex 710fc96042..01e1e00f90 100644--- a/packages/cli/src/commands/mcp.test.ts+++ b/packages/cli/src/commands/mcp.test.ts@@ -873,13 +873,14 @@ test("adapts MCP upload asset input to public API upload input", () => {name: "image.png",type: "image",format: "png",+ folderId: "campaign",meta: { width: 1200, height: 630 },},assetsDir: ".webstudio/assets",});expect(input).toMatchObject({- asset: { name: "image.png" },+ asset: { name: "image.png", folderId: "campaign" },});expect(input).toHaveProperty("readAssetData", expect.any(Function));});diff --git a/packages/cli/src/commands/mcp.ts b/packages/cli/src/commands/mcp.tsindex a15de09ee6..08fd18fd6d 100644--- a/packages/cli/src/commands/mcp.ts+++ b/packages/cli/src/commands/mcp.ts@@ -48,6 +48,8 @@ import {import {createLocalUploadAssetInput,createLocalUploadAssetsInput,+ downloadAssetFile,+ getLocalAssetPath,} from "../asset-files";import {getVisionVerificationLoop,@@ -939,6 +941,22 @@ const createCliMcpHost = async ({markPreviewStale();return { imported: true as const };},+ async downloadAsset(input) {+ const snapshot = getLoadedProjectSessionSnapshot(session);+ const asset = snapshot.state.assets?.get(input.assetId);+ if (asset === undefined) {+ throw new Error(`Asset not found: ${input.assetId}`);+ }+ await downloadAssetFile({+ asset,+ assetsDirectory: input.assetsDir,+ origin: connection.origin,+ });+ return {+ assetId: asset.id,+ path: getLocalAssetPath(asset.name, input.assetsDir),+ };+ },async startPreview(input, progress) {const resolvedInput =input.port === 0diff --git a/packages/cli/src/docs.generated.ts b/packages/cli/src/docs.generated.tsindex 3a211d7baa..f6757fa7d0 100644--- a/packages/cli/src/docs.generated.ts+++ b/packages/cli/src/docs.generated.ts@@ -2,13 +2,13 @@// Edit markdown files in src/docs instead.export const cliDocs = {"api-use-cases":- '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Upload, replace, delete, and inspect asset usage.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n\nNotes:\n\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',+ '# CLI API Use Cases\n\n## Link/configure one project\n\nCommands:\n\n- webstudio init --link <api-share-link> --json\n\nNotes:\n\n- Writes local project id and global origin/token config.\n\n## Import synced project bundle into another project\n\nCommands:\n\n- webstudio sync\n- webstudio import --to <destination-share-link>\n- MCP tool: import {"to":"<destination-share-link>"}\n\nNotes:\n\n- Imports local `.webstudio/data.json` into the destination project.\n- Destination share link must allow build/import access.\n- Use `--skip-assets` only when asset rows and files should not be imported.\n\n## Identify current token\n\nCommands:\n\n- MCP tool: whoami {}\n\n## Check token permissions\n\nCommands:\n\n- webstudio permissions --json\n\n## Inspect project/build/version\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["pages","instances","styles"]}\n\n## Discover CLI/API capabilities\n\nCommands:\n\n- webstudio schema api\n- webstudio schema mcp\n- webstudio man --json\n- webstudio man llm --json\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"Create a pricing page"}\n- MCP tool: meta.get_more_tools {"brief":"update-styles"}\n- webstudio mcp list-resources\n- webstudio mcp read-resource webstudio://project/guide\n- webstudio mcp read-resource webstudio://project/expressions\n\nNotes:\n\n- Use `webstudio schema mcp` for a compact machine-readable MCP tool overview. Add `--verbose` or use focused `meta.get_more_tools` calls only when exact input schemas are needed.\n- Use focused MCP tools for discovery first: `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get`. Protocol clients can use `resources/list` and `resources/read`; shell agents can use `webstudio mcp list-resources` and `webstudio mcp read-resource <uri>`. Read longer resources such as `webstudio://project/tools` and `webstudio://project/components` only when focused tools are insufficient.\n- `components.summary` returns counts by default; request `{"detail":"components","limit":20}` for paginated entries. Registry list tools return compact metadata, while `components.get` and `templates.get` return focused full details.\n- Read `webstudio://project/expressions` before authoring unfamiliar computed text, prop bindings, resource expressions, actions, or Collection item bindings.\n- From a shell, call one MCP tool with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio components.summary`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n\n## Inspect external shadcn registry items\n\nCommands:\n\n- webstudio registry inspect --source https://example.com/r/registry.json --item button --json\n- webstudio registry inspect --source ./registry.json --item dialog --json\n- webstudio registry inspect --source https://example.com/r/button.json --json\n\nNotes:\n\n- Reads a local or remote registry item without installing files or changing the configured Webstudio project.\n- Returns the item name, description, package and registry dependencies, file paths/targets, available docs, and a read-only compatibility report.\n- The report explicitly says whether installation or editable-component conversion is supported, lists declared requirements and manual steps, and says when arbitrary source code was not analyzed.\n- This is an inspection step only. It does not install files or change the configured project.\n\n## Understand what MCP can do\n\nCommands:\n\n- webstudio man mcp\n- MCP tool: meta.index {}\n- MCP tool: meta.guide {"brief":"What can Webstudio MCP do?"}\n\nMCP lets agents work on one configured Webstudio project. Agents can:\n\n- Inspect the linked project, token permissions, and latest editable build.\n- Read selected project data for audits, migrations, and repair.\n- Search labels, text, props, resource URLs, asset metadata, and styles.\n- Audit accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, and unused or duplicate style data.\n- Create and edit pages, folders, redirects, breakpoints, and page templates.\n- Create pages from reusable templates.\n- Update page metadata, SEO fields, auth settings, and marketplace metadata.\n- Insert components and styled JSX sections.\n- Create data-driven lists, grids, cards, and similar repeated UI from array or object data in one Collection operation.\n- Move, copy, wrap, unwrap, convert, rename, retag, and delete elements.\n- Update text, rich text, props, bindings, and actions.\n- Create and update local styles, design tokens, style sources, and CSS variables.\n- Create static data variables and JSON variables.\n- Create HTTP, GraphQL, and system resources.\n- Use system resources for sitemap, current date, and assets.\n- Bind resources to rendered data or form/action props.\n- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.\n- Publish, unpublish, inspect publish jobs, and manage custom domains.\n- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.\n\n## Inspect and refresh MCP session cache\n\nCommands:\n\n- MCP tool: status {}\n- MCP tool: status {"verbose":true}\n- MCP tool: refresh {"namespaces":["pages","instances","styles"]}\n- MCP tool: reset-session {}\n\nNotes:\n\n- Use status before a task to understand the cached ProjectSession state.\n- Use status with `{"verbose":true}` only when debugging full namespaces, freshness, compatibility, or diagnostics.\n- Use refresh when project data may have changed outside the current MCP session.\n- Use reset-session when local cached state is corrupt or incompatible.\n\n## Visually verify rendered work with AI vision\n\nCommands:\n\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: preview.status {}\n- MCP tool: preview.stop {}\n- MCP tool: screenshot {"path":"/","output":".webstudio/screenshots/home-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/pricing","output":".webstudio/screenshots/pricing-current.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedText":["Pricing","Start free"]}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/home-before.png","currentPath":".webstudio/screenshots/home-current.png","outputDir":".webstudio/screenshots/diff","expectedVisual":{"maxMismatchPercentage":2,"maxChangedRegions":3,"dominantColorChange":{"channel":"luminance","direction":"increase","minMagnitude":10}}}\n- MCP tool: screenshot.diff {"baselinePath":".webstudio/screenshots/pricing-before.png","currentPath":".webstudio/screenshots/pricing-current.png","outputDir":".webstudio/screenshots/diff"}\n- MCP tool: vision.install-ocr {"confirm":true}\n\nNotes:\n\n- Use this after page/content/style mutations and after generated project files are current so a vision-capable AI can see the production-like generated site.\n- For multi-page work, capture every changed page by `path` through the same preview server; no click navigation is required.\n- After MCP mutations, path screenshots regenerate/restart preview as needed before capture; when preview is fresh, repeated path screenshots reuse the running server.\n- Do not call `preview.start` through one-shot `webstudio mcp single-op-call`: it is long-lived. From a shell, use `webstudio mcp run` with preview.start, screenshot, and preview.stop in one shared process, or use a real long-running MCP client.\n- From one-shot shell calls or another process, pass `baseUrl` with `path` to capture an already-running preview/site without generating, building, starting, or restarting preview.\n- Use preview.stop only in the same long-running MCP server or `webstudio mcp run` process that started preview. A separate one-shot `single-op-call` process does not own another process\'s preview controller.\n- Use waitForSelector when the rendered app has a reliable ready marker, waitUntil:"networkidle" for network-heavy pages, and waitForTimeout only for final visual settling.\n- Preview installs generated app dependencies under `.webstudio/preview` and reuses them across regenerations.\n- Do not add generated-preview dependencies to the repository root `package.json` or `pnpm-lock.yaml`.\n- If dependency installation fails, check npm and network configuration, then reinstall or update the Webstudio CLI if the problem persists.\n- When a baseline exists, use screenshot.diff once per baseline/current page or viewport pair to get changed regions, OCR textAnalysis, and diff artifact paths before deciding whether the result matches. Pass expectedText for explicit pass/fail current-screen text assertions with found and missing text. Pass expectedVisual for pass/fail limits on pixel mismatch percentage, changed-region count, or the overall dominant color/brightness direction.\n- If screenshot.diff reports OCR unavailable and the user agrees to install it, call vision.install-ocr {"confirm":true}; otherwise continue with pixel diff and visual inspection.\n- Compare the PNG, OCR text evidence, and diff artifacts against the user\'s intent for layout, typography, colors, spacing, imagery, and responsive framing; then iterate with focused mutations.\n- Root CLI equivalent: `webstudio screenshot --path /pricing --output pricing.png` generates a temporary production preview, captures that route, and stops the server. For repeated captures, keep `webstudio preview` running and pass its absolute URL to `webstudio screenshot`.\n\n## List pages\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n\n## Read page by id\n\nCommands:\n\n- MCP tool: get-page {"pageId":"<pageId>"}\n\n## Read page by path\n\nCommands:\n\n- MCP tool: get-page-by-path {"path":"/pricing"}\n\n## Create page\n\nCommands:\n\n- MCP tool: create-page {"name":"Pricing","path":"/pricing"}\n- MCP tool: create-page {"name":"Pricing","path":"/pricing","title":"Pricing","meta":{"description":"Plans for teams"}}\n\nNotes:\n\n- `name`, `path`, page `title`, and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Update page settings/metadata\n\nCommands:\n\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans","status":"200"}}}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n\nNotes:\n\n- Page `title` and metadata text fields accept plain fixed values.\n- For computed page titles or metadata, send JavaScript expression code such as `pageTitle ?? "Pricing"`.\n\n## Read project settings\n\nCommands:\n\n- MCP tool: get-project-settings {}\n\nNotes:\n\n- Read `meta.agentInstructions` before making project changes. It contains the project\'s own guidance for AI agents.\n- Agent instructions are shared project guidance. Do not store credentials or other secrets there.\n\n## Update project settings\n\nCommands:\n\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n- MCP tool: update-project-settings {"meta":{"agentInstructions":"Use existing design tokens and keep product copy concise."}}\n\n## Read marketplace product\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n\n## Update marketplace product\n\nCommands:\n\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\n## List redirects\n\nCommands:\n\n- MCP tool: list-redirects {}\n\n## Create redirect\n\nCommands:\n\n- MCP tool: create-redirect {"old":"/old","new":"/new","status":301}\n\n## Update redirect\n\nCommands:\n\n- MCP tool: update-redirect {"old":"/old","values":{"new":"/newer","status":302}}\n- MCP tool: update-redirect {"old":"/old","values":{"status":null}}\n\n## Delete redirect\n\nCommands:\n\n- MCP tool: delete-redirect {"old":"/old"}\n\n## Set redirects\n\nCommands:\n\n- MCP tool: set-redirects {"redirects":[{"old":"/old","new":"/new","status":"301"}]}\n\n## List breakpoints\n\nCommands:\n\n- MCP tool: list-breakpoints {}\n\n## Create breakpoint\n\nCommands:\n\n- MCP tool: create-breakpoint {"label":"Tablet","maxWidth":991}\n\n## Update breakpoint\n\nCommands:\n\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"label":"Tablet","maxWidth":1023}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"condition":null,"minWidth":768}}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"minWidth":null,"maxWidth":null,"condition":"(hover: hover)"}}\n\n## Delete breakpoint\n\nCommands:\n\n- MCP tool: delete-breakpoint {"breakpointId":"tablet"}\n\n## Duplicate page\n\nCommands:\n\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Pricing Copy","path":"/pricing-copy"}\n- MCP tool: duplicate-page {"pageId":"<pageId>","name":"Paris","path":"/paris","substitutions":{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}}\n- webstudio duplicate-page --page <pageId> --name Paris --path /paris --substitutions \'{"text":{"London":"Paris"},"variables":{"city":{"type":"string","value":"Paris"}}}\' --json\n\nNotes:\n\n- Text substitutions replace exact fixed text only in the duplicated page\'s text children, string props, title, and metadata.\n- Variable substitutions are keyed by copied source-variable name and use typed variable values. The operation rejects missing or ambiguous names without committing a partial duplicate.\n- Existing expressions and cloned variable/resource references keep their remapped ids.\n\n## List page templates\n\nCommands:\n\n- MCP tool: list-page-templates {}\n\n## Create page template\n\nCommands:\n\n- MCP tool: create-page-template {"name":"Landing Template","title":"Landing"}\n\n## Update page template\n\nCommands:\n\n- MCP tool: update-page-template {"templateId":"<templateId>","values":{"name":"Article Template","meta":{"description":"Reusable article layout"}}}\n\n## Delete page template\n\nCommands:\n\n- MCP tool: delete-page-template {"templateId":"<templateId>"}\n\n## Duplicate page template\n\nCommands:\n\n- MCP tool: duplicate-page-template {"templateId":"<templateId>"}\n\n## Reorder page template\n\nCommands:\n\n- MCP tool: reorder-page-template {"sourceTemplateId":"<sourceTemplateId>","targetTemplateId":"<targetTemplateId>","position":"before"}\n\n## Create page from template\n\nCommands:\n\n- MCP tool: create-page-from-template {"templateId":"<templateId>","name":"Landing","path":"/landing"}\n\n## Delete page\n\nCommands:\n\n- MCP tool: delete-page {"pageId":"<pageId>"}\n\n## List folders\n\nCommands:\n\n- MCP tool: list-folders {}\n- MCP tool: list-pages {}\n\n## Create folder\n\nCommands:\n\n- MCP tool: create-folder {"name":"Blog","slug":"blog"}\n\n## Update folder\n\nCommands:\n\n- MCP tool: update-folder {"folderId":"<folderId>","values":{"name":"Blog","slug":"blog"}}\n\n## Delete folder\n\nCommands:\n\n- MCP tool: delete-folder {"folderId":"<folderId>"}\n\n## List element instances\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/","maxDepth":3}\n\n## Inspect one element instance\n\nCommands:\n\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n\n## Insert authored JSX or one component template\n\nCommands:\n\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px;`}><ws.element ws:tag=\\"h2\\">Product OS</ws.element><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"@webstudio-is/sdk-components-react-radix:Switch"}\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"Form"}\n\nNotes:\n\n- Use MCP `insert-fragment` as the default way to author styled component trees. It converts JSX to a structured fragment before mutation.\n- Use only exact component ids returned by `components.search`, `components.get`, or `templates.get`. Never derive or guess component ids.\n- The `ws:` namespace contains specific Webstudio core components; it is not HTML-tag shorthand. Use `<ws.element ws:tag="div">` for a native `div` and `<ws.element ws:tag="form">` for a native form, never `<ws.div>` or `<ws.form>`.\n- For Webstudio\'s complete form structure, discover the Form component and insert its automatic template with `insert-component` using component `"Form"`.\n- MCP receives JSX as a JSON string because MCP arguments are JSON. The CLI converts it locally before the runtime mutation, so the project session receives structured Webstudio data, not JSX source.\n- In `insert-fragment` JSX, use `ws:style={css\\`...\\`}`for Webstudio-native CSS, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`.\n- Webstudio applies a registered template automatically when using `insert-component`, so composed components such as Switch include required child parts and styles.\n- Use `components.list`, `components.summary`, `components.search`, `components.get`, `templates.list`, and `templates.get` to discover known registry items, component ids, props, templates, insertability, and content model. Read `webstudio://project/components` only when those focused tools are insufficient.\n- Component/template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. They are for Builder/MCP discovery, not a published shadcn install registry yet.\n- Known components with `contentModel.category: "none"` are not standalone-insertable; insert their root component template instead so required providers/parents are included.\n- Unknown custom component ids are a low-level extension mechanism, not a discovery fallback. Agents must not synthesize them.\n\n## Make a region editable in Content mode\n\nCommands:\n\n- MCP tool: insert-component {"parentInstanceId":"<instanceId>","component":"ws:block"}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["children"]}\n\nNotes:\n\n- When a page will be handed to a Content-mode editor, wrap every region they should be able to edit in a Content Block (`ws:block`). Content-mode editors can edit text and supported props only in Content Block descendants. Content outside those blocks remains read-only, even when it looks like ordinary editable text.\n- Put reusable insertable options inside the Content Block\'s `ws:block-template` child. A template is source material, not editor content: editors cannot edit or delete it directly. When an editor inserts a template, its copy becomes a direct child of the Content Block and is editable.\n- Before handing off a page, verify with `inspect-instance` that the intended text, images, and links are inside a Content Block, and that templates include all required styling because Content-mode editors cannot use the Style panel.\n\n## Move elements\n\nCommands:\n\n- MCP tool: move-instance {"moves":"moves.json contents"}\n\nNotes:\n\n- Use `position: "end"` to append an instance. Repeating this for A and then B preserves the final order A, B.\n- A numeric `insertIndex` addresses the target parent\'s children before the moved instance is removed. Use it for exact placement; do not calculate the last index to append.\n- Moves in one `moves` array are applied sequentially in array order.\n\n## Clone element subtree\n\nCommands:\n\n- MCP tool: clone-instance {"sourceInstanceId":"<instanceId>","targetParentInstanceId":"<targetParentId>"}\n\n## Delete element subtree\n\nCommands:\n\n- MCP tool: delete-instance {"instanceIds":["<instanceId>"]}\n\n## List text/expression children\n\nCommands:\n\n- MCP tool: list-texts {"pagePath":"/"}\n\n## Update text child\n\nCommands:\n\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n\n## Replace bounded literal text\n\nCommands:\n\n- MCP tool: replace-text {"find":"Start free","replace":"Get started","match":"exact","pagePath":"/pricing","limit":20}\n\nNotes:\n\n- This changes only literal text children, never expression children. Scope it to pagePath or pageId and set a limit before a broad replacement.\n\n## Replace bounded static prop text\n\nCommands:\n\n- MCP tool: replace-prop-text {"find":"old.example.com","replace":"www.example.com","match":"substring","names":["href","code"],"limit":20}\n\nNotes:\n\n- This changes only static string props such as href, alt, aria-label, title, and HTML embed code. It never changes expressions, resources, actions, assets, or other dynamic bindings. Use names or instanceIds and a limit to narrow the change.\n\n## Replace bounded resource text\n\nCommands:\n\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\nNotes:\n\n- This changes resource names and fixed URL literals only. It skips dynamic URL expressions, headers, search parameters, request bodies, and GraphQL query code.\n\n## Update props\n\nCommands:\n\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: replace-prop-text {"find":"Old label","replace":"New label","names":["aria-label","title"],"limit":20}\n\nNotes:\n\n- Use this for fixed prop values such as `aria-label`, `alt`, `id`, static `href`, and other direct string/number/boolean/json prop values.\n\n## Add JSON-LD structured data\n\nCommands:\n\n- MCP tool: components.get {"component":"JsonLd"}\n- MCP tool: insert-component {"parentInstanceId":"<headSlotInstanceId>","component":"JsonLd"}\n- MCP tool: update-props {"updates":[{"instanceId":"<jsonLdInstanceId>","name":"code","type":"string","value":"{\\"@context\\":\\"https://schema.org\\",\\"@type\\":\\"Organization\\",\\"name\\":\\"Acme\\"}"}]}\n- MCP tool: audit {"scopes":["seo"],"pagePath":"/"}\n\nNotes:\n\n- Prefer placing `JsonLd` inside `HeadSlot`.\n- Store `code` as a JSON object or array encoded as a compact string. The Builder formats it for editing.\n- The semantic prop update rejects malformed JSON and structurally invalid fixed JSON-LD with a precise JSON path.\n- The SEO audit also warns about a missing top-level `@context`, unknown or superseded Schema.org terms, properties unsupported by the supplied type, and incompatible primitive value types.\n- Schema.org vocabulary findings are warnings because custom vocabularies and extensions remain valid. Dynamic JSON-LD is marked as skipped for rendered validation.\n- Do not use bindings just to set static text.\n\n## Delete props\n\nCommands:\n\n- MCP tool: delete-props {"deletions":"props.json contents"}\n\n## Bind props to expressions/resources/actions\n\nCommands:\n\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Use this only when the prop should remain dynamic: expression, resource, action, or an existing scoped runtime context value such as `system`.\n- For a fixed string value, use `update-props` with `type:"string"` and a direct `value` instead.\n\n## Read styles\n\nCommands:\n\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n\n## Update local styles\n\nCommands:\n\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\n## Delete local styles\n\nCommands:\n\n- MCP tool: delete-styles {"deletions":"styles.json contents"}\n\n## Replace matching style values\n\nCommands:\n\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n\n## List design tokens\n\nCommands:\n\n- MCP tool: list-design-tokens {}\n- MCP tool: list-design-tokens {"withUsage":true}\n- MCP tool: list-design-tokens {"verbose":true}\n\nNotes:\n\n- The default response is compact and includes token id, name, declaration count, and optional usage count.\n- Use `verbose:true` only when you need the full inline style declarations.\n\n## Create design tokens\n\nCommands:\n\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n\n## Update design token styles\n\nCommands:\n\n- MCP tool: update-design-token-styles {"designTokenId":"<tokenId>","updates":"styles.json contents"}\n\n## Delete design token styles\n\nCommands:\n\n- MCP tool: delete-design-token-styles {"designTokenId":"<tokenId>","deletions":"styles.json contents"}\n\n## Attach design token to instances\n\nCommands:\n\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Detach design token from instances\n\nCommands:\n\n- MCP tool: detach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n\n## Extract design token from local styles\n\nCommands:\n\n- MCP tool: extract-design-token {"instanceIds":["<instanceId>"],"name":"Brand Primary","removeLocalProps":["color"]}\n\n## List CSS variables\n\nCommands:\n\n- MCP tool: list-css-variables {"withUsage":true}\n\n## Define CSS variables\n\nCommands:\n\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n\n## Delete CSS variables\n\nCommands:\n\n- MCP tool: delete-css-variable {"names":"names.json contents","force":true}\n\n## Rewrite CSS variable references\n\nCommands:\n\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\n## List data variables\n\nCommands:\n\n- MCP tool: list-variables {}\n- MCP tool: list-variables {"scopeInstanceId":"<instanceId>"}\n\nNotes:\n\n- Data variables live in the internal `dataSources` namespace.\n- For raw `snapshot`, request the public `variables` namespace rather than the internal `dataSources` name. Raw patch payloads still use `dataSources` when applying direct changes.\n- Scope variables to the instance where they should become available. Descendants can use them in expressions, and nested variables with the same name mask outer variables.\n\n## Create data variable\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"count","value":{"type":"number","value":3}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"featured","value":{"type":"boolean","value":true}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n\nNotes:\n\n- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`.\n- Parameters are internal scoped runtime values provided by pages, collections, or components. They are not a public authoring surface: do not create, update, or delete parameter records. Use data variables/resources for user-authored data, and reference documented context values such as `system` only where they are already in scope.\n\n## Update data variable\n\nCommands:\n\n- MCP tool: update-variable {"dataSourceId":"<variableId>","values":{"value":{"type":"json","value":{"count":1}}}}\n\n## Delete data variable\n\nCommands:\n\n- MCP tool: delete-variable {"dataSourceId":"<variableId>"}\n\n## List resources\n\nCommands:\n\n- MCP tool: list-resources {}\n- MCP tool: list-resources {"scopeInstanceId":"<instanceId>"}\n\n## Create resource\n\nCommands:\n\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","headers":[]}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"\\"https://api.example.com/posts?tag=\\" + filters.tag","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Filtered Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[{"name":"Authorization","value":"\\"Bearer \\" + auth.token"}]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n\nNotes:\n\n- Resource `url` accepts plain fixed URLs and paths such as `https://api.example.com/posts` and `/$resources/current-date`.\n- Resource `url` can also be a JavaScript expression when it is computed, such as `"https://api.example.com/posts?tag=" + filters.tag`.\n- Header values, search parameter values, and body accept expressions for dynamic values. For fixed text, use `{"type":"literal","value":"application/json"}`; Webstudio stores the required string expression for you.\n- Search parameter values, header values, and body expressions can read scoped variables and documented runtime context values such as `system` when they are available at the resource scope.\n- Add `scopeInstanceId` and `dataSourceName` when the resource result should be exposed as a scoped read data variable. Scoped resources are generated into the page resource `data` map and may be loaded during page rendering. Use this for read-oriented resources such as GET CMS/API data.\n- For submit/write/action resources, create the resource without `scopeInstanceId`, then bind a component prop such as a Form `action` with `bind-props` and `binding.type: "resource"`. Prop-bound resources are generated into the page resource `action` map instead of the read `data` map. Use this for POST, PUT, DELETE, webhooks, GraphQL submissions, and other explicit action flows.\n- Resource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read data, POST for creates/GraphQL/webhooks/form submissions, PUT for full updates or replacements, and DELETE for deletion actions.\n- Optional `control` values are `graphql` and `system`. Use `graphql` for GraphQL-style requests, usually POST with a query body. Use `system` for built-in resources such as `"/$resources/sitemap.xml"`, `"/$resources/current-date"`, and `"/$resources/assets"` and when the resource should use the built-in `system` parameter. System fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`.\n\n## Update resource\n\nCommands:\n\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-resource-text {"find":"api.old.example.com","replace":"api.example.com","fields":["url"],"limit":20}\n\n## Delete resource\n\nCommands:\n\n- MCP tool: delete-resource {"resourceId":"<resourceId>"}\n\n## List assets\n\nCommands:\n\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: list-assets {"verbose":true}\n\nNotes:\n\n- Compact results include each asset\'s folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.\n- Image asset descriptions are the default alt text for asset-backed Image components.\n- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.\n\n## Get asset\n\nCommands:\n\n- MCP tool: get-asset {"assetId":"<assetId>"}\n\n## List asset folders\n\nCommands:\n\n- MCP tool: list-asset-folders {}\n\n## Create asset folder\n\nCommands:\n\n- MCP tool: create-asset-folder {"name":"Marketing"}\n- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}\n\n## Update asset folder\n\nCommands:\n\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}\n- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}\n\nNotes:\n\n- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.\n\n## Duplicate asset folder\n\nCommands:\n\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}\n- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}\n\nNotes:\n\n- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.\n\n## Delete asset folder\n\nCommands:\n\n- MCP tool: delete-asset-folder {"folderId":"<folderId>"}\n\nNotes:\n\n- Deleting a folder recursively deletes its descendant folders and assets.\n\n## Update asset metadata\n\nCommands:\n\n- MCP tool: update-asset {"assetId":"<assetId>","values":{"description":"Team collaborating around a whiteboard"}}\n\nNotes:\n\n- Use an empty description only when the image is intentionally decorative.\n- Updating an image asset description updates the default alt text wherever that asset is used with an asset-backed alt prop.\n\n## Generate missing image descriptions with an agent\n\nCommands:\n\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}\n- MCP tool: audit {"scopes":["accessibility"]}\n\nNotes:\n\n- Start from `missing-image-description` findings. Inspect each image in its rendered page context before writing text.\n- The vision-capable agent generates the wording; the CLI validates and stores it but does not contain its own vision model.\n- Use `decorative:true` only when the image adds no information. This intentionally stores an empty description so later audits do not report it as missing.\n- Re-run the accessibility audit after the update. Asset-backed Image components use the saved asset description as their default alt text.\n\n## Manage fonts\n\nCommands:\n\n- MCP tool: list-fonts {"includeSystem":true}\n- MCP tool: list-assets {"type":"font"}\n- MCP tool: upload-asset {"asset":{"name":"acme-sans.woff2","type":"font","format":"woff2","meta":{"family":"Acme Sans","style":"normal","weight":400}},"assetsDir":".webstudio/assets"}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n\nNotes:\n\n- Use `list-fonts` to discover uploaded families and system stacks. Upload/delete fonts through the existing asset tools, then apply a family with a `font-family` style declaration.\n\n## Upload one asset\n\nCommands:\n\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}\n\n## Upload asset batch\n\nCommands:\n\n- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}\n\n## Duplicate asset\n\nCommands:\n\n- MCP tool: duplicate-asset {"assetId":"<assetId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}\n- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}\n\nNotes:\n\n- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.\n\n## Download asset\n\nCommands:\n\n- MCP tool: download-asset {"assetId":"<assetId>"}\n\n## Find asset usage\n\nCommands:\n\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n\n## Replace asset references\n\nCommands:\n\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n\n## Delete assets\n\nCommands:\n\n- MCP tool: delete-asset {"assetIdsOrPrefixes":["<assetId>"],"force":true}\n\n## Publish project\n\nCommands:\n\n- webstudio publish deploy --target production --json\n\n## List publishes\n\nCommands:\n\n- webstudio publish list --json\n\n## Check publish job\n\nCommands:\n\n- webstudio publish status --job <buildId> --json\n\n## Unpublish\n\nCommands:\n\n- webstudio publish unpublish --target production --confirm --json\n\n## List domains\n\nCommands:\n\n- webstudio domains list --json\n\n## Create domain\n\nCommands:\n\n- webstudio domains create --domain example.com --json\n\n## Update domain\n\nCommands:\n\n- webstudio domains update --domain-id <domainId> --domain www.example.com --json\n\n## Delete domain\n\nCommands:\n\n- webstudio domains delete --domain-id <domainId> --confirm --json\n\n## Verify domain\n\nCommands:\n\n- webstudio domains verify --domain-id <domainId> --json\n\n## Make arbitrary store-level changes\n\nCommands:\n\n- MCP tool: inspect {}\n- MCP tool: snapshot {"include":["<namespace>"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use only when no semantic command exists.\n\n## Manage marketplace metadata\n\nCommands:\n\n- MCP tool: get-marketplace-product {}\n- MCP tool: update-marketplace-product {"category":"pageTemplates","name":"Acme Template","thumbnailAssetId":"asset-id","author":"Acme Studio","email":"[email protected]","website":"https://example.com","issues":"","description":"Reusable template project for Acme landing pages."}\n\nPatch namespaces:\n\n- marketplaceProduct\n\n## Search and inspect safely\n\nCommands:\n\n- MCP tool: search-project {"query":"pricing"}\n- MCP tool: search-project {"query":"api.example.com","scopes":["resources"]}\n- MCP tool: list-instances {"pagePath":"/","maxDepth":5}\n- MCP tool: inspect-instance {"instanceId":"<instanceId>","include":["props","styles","children"]}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: list-assets {"withUsage":true}\n- MCP tool: find-asset-usage {"assetId":"<assetId>"}\n- MCP tool: snapshot {"include":["pages","instances","props","resources","assets"]}\n\nNotes:\n\n- Use `search-project` for query-driven lookup across labels, text, prop values, resource URLs, asset metadata, and styles. Use `audit` for project health findings.\n\n## Audit project quality\n\nCommands:\n\n- webstudio audit --json\n- webstudio audit --scopes accessibility --scopes seo --json\n- webstudio audit --page-path /pricing --json\n- webstudio audit --scopes accessibility --verbose --json\n- webstudio audit --rendered --page-path /pricing --json\n- webstudio audit --rendered --route-example post=/blog/hello --json\n- webstudio audit --rendered --image-domain images.example.com --json\n- MCP tool: audit {}\n- MCP tool: audit {"scopes":["accessibility","security"],"severities":["error","warning"]}\n- MCP tool: audit {"scopes":["accessibility"],"verbose":true}\n- MCP tool: audit {"scopes":["craft"],"verbose":true}\n- MCP tool: audit {"rendered":true,"verbose":true}\n\nNotes:\n\n- With no scopes, `audit` checks accessibility, security, SEO, performance settings, unused assets, ineffective Collection styles, non-GET resources exposed as render-time data, and unused or duplicate style data.\n- Craft is opt-in and read-only. Run `audit` with `scopes:["craft"]` to detect whether the project is not using Craft, partially compatible, or compatible with the versioned Craft 1.2 profile. `profileStatuses` includes the University-doc provenance and the smallest safe next action. The audit never installs Craft or changes a non-Craft project.\n- The `performance` scope reports disabled atomic CSS generation. A rendered audit also measures broken, eager below-fold, and oversized images, browser-marked render-blocking resources, and legacy font formats.\n- Rendered image and resource metrics run only when the selected scopes include `performance`; responsive layout dimensions remain available whenever `rendered:true` is requested.\n- Compact findings include stable ids, severity, message, and location. Use `--verbose` or `{"verbose":true}` for evidence, explanation, suggested remediation, skipped-check details, and manual-check workflows.\n- `summary` counts all findings before severity filtering and pagination.\n- `contractVersion` identifies the audit response contract. Handle a new value before assuming existing fields retain the same meaning.\n- Expression-, resource-, and parameter-backed values that cannot be checked reliably appear in `skippedChecks`; they are not treated as passing or failing.\n- Page filters apply to page-owned accessibility, security, and SEO checks. Asset and style usage remain project-wide to avoid false unused findings.\n- Continue paginated results with `cursor`. Restart the audit if the project version changes.\n- Verbose skipped-check and manual-check details are included on the first findings page only; their total counts remain available on every page.\n- `manualChecks` describes responsive, hierarchy, and contrast checks that require preview screenshots and vision.\n- Focused audits return only manual checks relevant to their selected scopes.\n- In a long-lived MCP session, `{"rendered":true}` reuses preview and screenshot\n tools to capture every static page at mobile, desktop, and Builder breakpoint\n edges. Compact output reports rendered check/issue/failure counts; verbose\n output includes screenshot paths and measured layout dimensions.\n- Dynamic route templates are skipped unless `--route-example <pageId>=<path>`\n (or MCP `routeExamples`) supplies a concrete path. The path must not contain\n unresolved `:` or `*` parameters.\n- Plans above 120 captures return a short-lived confirmation token. Review the\n unchanged plan, then rerun with `--confirm-large-run` and\n `--confirmation-token`.\n- Detailed rendered evidence is stored in a versioned manifest under\n `.webstudio/audits`; compact output includes its path and screenshot count.\n- Rendered checks also report broken images, eager images below the fold, and\n image sources more than 2x their rendered dimensions in both axes, including\n Webstudio instance ids and measured dimensions when available.\n- Rendered checks include sanitized Resource Timing evidence and report\n browser-marked render-blocking resources plus legacy `.ttf`, `.otf`, and\n `.woff` fonts without applying a universal transfer-size threshold.\n- Fix findings through semantic mutation commands, then rerun `audit` to confirm their deterministic finding ids disappeared.\n\n## Verify dynamic bindings\n\nCommands:\n\n- webstudio verify-bindings --json\n- MCP tool: verify-bindings {"pagePath":"/pricing"}\n- MCP tool: verify-bindings {"instanceId":"<instanceId>","limit":50}\n\nNotes:\n\n- Statically checks persisted text expressions, expression/action/resource/parameter props, resource expressions, and page metadata.\n- Findings distinguish invalid syntax, unknown or out-of-scope variables, stale internal data-source ids, and missing resource or parameter references.\n- Page and instance filters can be combined when the instance belongs to the selected page. Continue findings with `cursor`.\n- This operation does not resolve rendered values or execute external resources. Preview representative loading, empty, error, and populated states after static findings are fixed.\n\n## Refactor targeted content\n\nCommands:\n\n- MCP tool: list-instances {"pagePath":"/"}\n- MCP tool: list-texts {"pagePath":"/"}\n- MCP tool: update-text {"instanceId":"<instanceId>","childIndex":0,"text":"Launch faster"}\n- MCP tool: replace-text {"find":"Old headline","replace":"New headline","match":"exact","pagePath":"/pricing","limit":20}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: replace-asset {"fromAssetId":"<oldAssetId>","toAssetId":"<newAssetId>"}\n- MCP tool: replace-styles {"property":"color","fromValue":{"type":"keyword","value":"red"},"toValue":{"type":"keyword","value":"blue"}}\n- MCP tool: rewrite-css-variable-refs {"map":"variables.json contents"}\n\nNotes:\n\n- Use focused reads first, then mutate only matching instances, props, metadata, resource URLs, assets, or style references. Use `replace-text` for bounded literal text changes, `replace-prop-text` for bounded static prop text, `replace-resource-text` for fixed resource names/URLs, and `update-text` for one known child or expressions.\n\n## Optimize existing project\n\nCommands:\n\n- MCP tool: list-pages {}\n- MCP tool: list-folders {}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"title":"Pricing","meta":{"description":"Plans"}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: update-breakpoint {"breakpointId":"tablet","values":{"maxWidth":1023}}\n- MCP tool: get-styles {"instanceIds":["<instanceId>"],"includeTokens":true}\n- MCP tool: update-styles {"updates":"styles.json contents"}\n- MCP tool: attach-design-token {"designTokenId":"<tokenId>","instanceIds":"instances.json contents"}\n- MCP tool: update-project-settings {"meta":{"siteName":"Acme"}}\n\nNotes:\n\n- Use this for SEO metadata, accessibility labels, responsive behavior, token consistency, and project settings.\n\n## Connect external data\n\nCommands:\n\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"title","value":{"type":"string","value":"Hello"}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"tags","value":{"type":"string[]","value":["news","product"]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"filters","value":{"type":"json","value":{"tag":"news"}}}\n- MCP tool: create-resource {"resource":{"name":"Posts","method":"get","url":"https://api.example.com/posts","searchParams":[{"name":"tag","value":"filters.tag"},{"name":"source","value":{"type":"literal","value":"website"}}],"headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"posts"}\n- MCP tool: create-resource {"resource":{"name":"Post GraphQL","control":"graphql","method":"post","url":"https://api.example.com/graphql","headers":[{"name":"Content-Type","value":{"type":"literal","value":"application/json"}}],"body":"{ query: \\"query Post($slug: String!) { post(slug: $slug) { title } }\\", variables: { slug: system.params.slug } }"},"scopeInstanceId":"<instanceId>","dataSourceName":"post"}\n- MCP tool: create-resource {"resource":{"name":"Current Date","control":"system","method":"get","url":"/$resources/current-date","headers":[]},"scopeInstanceId":"<instanceId>","dataSourceName":"currentDate"}\n- MCP tool: update-resource {"resourceId":"<resourceId>","values":{"url":"https://api.example.com/posts"}}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.collection>{/_ collection content _/}</ws.collection>"}\n\nNotes:\n\n- Use this for CMS sections, blog listings, Ghost/headless CMS pages, n8n-style integrations, and API URLs built from variables.\n- For read data, expose GET resources as scoped data variables with `scopeInstanceId`/`dataSourceName` and read the loaded result from the resource result wrapper, usually `.data`.\n- For writes, webhooks, GraphQL submissions, and deletes, prefer unscoped resources bound to Form `action` props so they become action resources instead of auto-loaded read resources.\n- Use direct props for fixed values and prop bindings only when a prop must read a data variable, resource, action, or documented runtime context value such as `system`.\n\n## Render an array or object as repeated content\n\nCommands:\n\n- MCP tool: insert-collection {"parentInstanceId":"<instanceId>","data":{"type":"expression","value":"posts.data.items"},"itemFragment":"<ws.element ws:tag=\\"article\\"><ws.element ws:tag=\\"h2\\">{expression`collectionItem.title`}</ws.element></ws.element>"}\n- MCP tool: inspect-instance {"instanceId":"<collectionId>","include":["props","bindings","children"]}\n\nNotes:\n\n- Use Collection whenever an array or object from a resource or data variable should render a list, grid, cards, table rows, options, tabs, or other repeated UI.\n- Pass `insert-collection` the complete array or object. Do not pass the resource response wrapper or one indexed item. External resource arrays are commonly nested under the scoped resource result\'s `data` field or deeper.\n- Pass one repeated-item Webstudio JSX root. The command creates the Collection, its private current-item/current-key parameters, the iterable binding, and descendant item bindings atomically.\n- Collection renders the item root once for every entry. Use `expression` values such as `collectionItem.title` in descendant text and props. Object iteration also exposes `collectionItemKey`.\n- Wrap multiple repeated sibling instances in one Element inside Collection.\n- For repeated Radix items such as accordion items, tabs, or menu options, bind a stable unique id or slug to every required `value` prop.\n- See the [Collection documentation](https://docs.webstudio.is/university/core-components/collection) for the equivalent Builder workflow.\n\n## Support dynamic runtime behavior\n\nCommands:\n\n- MCP tool: integrate-runtime-ui {"parentInstanceId":"<instanceId>","resources":[{"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]},"dataSourceName":"Seats","exposeAsDataSource":true}],"structure":{"type":"collection","data":{"type":"expression","value":"Seats.data"},"itemFragment":{"children":[{"type":"id","value":"seat"}],"instances":[{"type":"instance","id":"seat","component":"Text","children":[{"type":"expression","value":"collectionItem.label"}]}],"props":[],"dataSources":[],"resources":[],"styleSources":[],"styleSourceSelections":[],"styles":[],"breakpoints":[],"assets":[]}},"retainedBehavior":[{"instanceId":"<scriptInstanceId>","responsibility":"Seat selection behavior"}]}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n- MCP tool: create-resource {"resource":{"name":"Seats","method":"get","url":"https://api.example.com/seats","headers":[]}}\n- MCP tool: snapshot {"include":["instances","props","resources"]}\n- MCP tool: apply-patch {"baseVersion":"<version>","transactions":"patch.json contents"}\n\nNotes:\n\n- Use `integrate-runtime-ui` to create variables/resources, insert one editable fragment or Collection, and add safe data bindings in one transaction.\n- List existing script-owned responsibilities under `retainedBehavior`. The operation preserves those instances and never evaluates or accepts replacement script bodies.\n- `unsupportedConversions` records behavior that cannot be represented safely. Dry-run returns the complete transaction and the same retained/unsupported report without changing the project.\n- New actions and HtmlEmbed scripts are intentionally rejected. Create normal editable components and data bindings; keep opaque runtime behavior in existing script instances.\n\n## Build authenticated pages\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Build a Supabase-authenticated account page"}\n- MCP tool: create-page {"name":"Account","path":"/account"}\n- MCP tool: update-page {"pageId":"<pageId>","values":{"meta":{"auth":{"method":"basic","login":"<login>","password":"<password>"}}}}\n- MCP tool: create-resource {"resource":{"name":"Session","method":"get","url":"https://api.example.com/session","headers":[]}}\n- MCP tool: create-variable {"scopeInstanceId":"<instanceId>","name":"user","value":{"type":"json","value":{}}}\n- MCP tool: update-props {"updates":"props.json contents"}\n- MCP tool: bind-props {"bindings":"bindings.json contents"}\n\nNotes:\n\n- Inspect and reuse the project\'s existing auth convention before authoring. Do\n not add a second provider or session model implicitly.\n- Model signed-out, loading, signed-in, and failed-auth states explicitly.\n- Never store credentials, service-role keys, refresh tokens, private session\n values, or authenticated response bodies in project data, command output,\n screenshots, agent instructions, or error reports. Privileged provider calls\n and authorization enforcement belong server-side.\n- Basic auth is semantic today. Provider-specific Supabase/Firebase setup still\n uses the existing resource, variable, prop, binding, and embed tools; there is\n no provider-specific installer.\n\n## Generate from design input\n\nCommands:\n\n- MCP tool: meta.guide {"brief":"Recreate this Figma design as a responsive page"}\n- MCP tool: create-page {"name":"Landing","path":"/landing"}\n- MCP tool: create-design-token {"tokens":"tokens.json contents"}\n- MCP tool: define-css-variable {"vars":"vars.json contents"}\n- MCP tool: list-breakpoints {}\n- MCP tool: insert-fragment {"parentInstanceId":"<instanceId>","fragment":"<ws.element ws:tag=\\"section\\"><ws.element ws:tag=\\"p\\">Section copy</ws.element></ws.element>"}\n- MCP tool: update-styles {"updates":[{"instanceId":"<instanceId>","breakpointId":"<breakpointId-from-list-breakpoints>","property":"padding-left","value":{"type":"unit","unit":"px","value":24}}]}\n- MCP tool: preview.start {"host":"127.0.0.1","port":5173}\n- MCP tool: screenshot {"path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"path":"/landing","output":"landing-mobile.png","viewport":{"width":390,"height":844},"waitUntil":"load","waitForTimeout":250}\n- MCP tool: screenshot {"baseUrl":"http://127.0.0.1:5177","path":"/landing","output":"landing-desktop.png","viewport":{"width":1440,"height":900},"waitUntil":"load","waitForTimeout":250}\n\nNotes:\n\n- Use this after the agent can inspect the supplied design. There is no direct\n Figma, screenshot, Inception, or `design.md` import command.\n- Inspect and reuse existing variables, tokens, styles, components, assets, and\n page patterns before authoring. Build semantic editable structure rather than\n flattening the design into an image or absolute-positioned approximation.\n- Verify one familiar viewport inside every distinct Builder breakpoint range,\n then run rendered audit and inspect the screenshots before completion.\n\n## Cross-project maintenance\n\nCommands:\n\n- webstudio mcp run .temp/projects.json\n- webstudio mcp run .temp/projects.json --dry-run\n- webstudio mcp run .temp/projects.json --approve-mutations --concurrency 2\n\nNotes:\n\n- Put shared `calls` and a `projects` array of independently linked project roots in the existing `mcp run` manifest. Project roots are relative to the manifest file.\n- Each project uses its own config, authentication, ProjectSession storage, checkpoint, and failure boundary. Confirmed successful calls are checkpointed. Reads can resume automatically; a mutation interrupted after dispatch is reported as ambiguous and is not replayed automatically, preventing silent duplicate writes.\n- Focus the manifest on bounded reads or audits first. Use per-call `dryRun`, global `--dry-run`, or explicitly approve committed mutations with `--approve-mutations` after reviewing the manifest.\n\n# Known CLI Gaps\n\n## Provider-specific authenticated pages\n\nMissing:\nCLI supports page basic auth and generic resources/props/embeds, but not guided Supabase/Firebase auth setup.\n\nCurrent fallback:\nCall `meta.guide` with the provider-authenticated page goal, then create the\npage, resources, variables, props, bindings, and embeds with existing semantic\ntools.\n\nSuggested commands:\n\n- setup-auth-page\n\n## Generate from design input\n\nMissing:\nNo command imports Figma, screenshots, Inception output, or design.md and turns it into pages/tokens/layout.\n\nCurrent fallback:\nCall `meta.guide` with the design-input goal, let the agent inspect the supplied\ndesign, then use semantic page, token, asset, fragment, style, preview,\nscreenshot, and audit tools. Use `apply-patch` only when no semantic operation\nfits.\n\nSuggested commands:\n\n- generate-from-design\n\n## Built-in cross-project maintenance\n\nMissing:\nPublic API and CLI intentionally operate on one configured project at a time; there is no built-in multi-project discovery or loop runner.\n\nCurrent fallback:\nRun the CLI from an external script that reconfigures one project/session at a time.\n\nSuggested commands:\n\n- none\n',"manual-api":'# Webstudio API CLI Manual\n\nThe API commands operate on the single project configured by:\n\n- .webstudio/config.json: projectId\n- global Webstudio config: origin and token\n\n- Pass --json to API/discovery commands that support it. Do not add --json to top-level commands unless their help/schema documents it.\n- Never pass a project id. Commands use configured project only.\n- Read ids before writing. Do not invent ids for existing records.\n- stdout is one JSON object. stderr is diagnostics.\n- Prefer MCP semantic tools for detailed project edits. Use MCP apply-patch only when no semantic tool exists.\n\n## Start\n\n{{start}}\n\n## Read First\n\n{{readFirst}}\n\n## Project Session Cache\n\n- CLI commands use one local ProjectSession snapshot for the configured project.\n- Local-capable reads use cached namespaces when compatible and fetch only missing or stale namespaces.\n- Local-capable mutations build patches from the local snapshot, then commit with the cached build version.\n- Successful mutation commits update the local snapshot only after the remote commit succeeds.\n- Server-only commands run remotely and invalidate/refetch namespaces declared by the operation catalog.\n- Use --refresh on local-capable commands to refresh required namespaces before running.\n- Successful JSON responses include compact meta.session with operationId, buildId, version, source, committed, namespaceCounts, diagnosticCount, non-empty diagnostic summaries, and optional compatibilityVersion.\n\n## CLI Capability Inventory\n\nFor a short end-consumer summary of what MCP can do, see\n`manual mcp` / `webstudio man mcp`. The MCP inventory describes the same\nproject, page, element, style, data, asset, publish, domain, and visual\nverification capabilities without internal command names.\n\n### Top-Level Commands\n\n{{topLevelCapabilityIndex}}\n\n### High-Level API Commands By Area\n\n{{apiCapabilityIndex}}\n\n### MCP Tool Operations\n\nThese are MCP tools. From a shell, call them with the shortcut form `webstudio <tool> \'<json>\'` or with the explicit form `webstudio mcp single-op-call <tool> \'<json>\'`:\n\n{{mcpOnlyCommandIndex}}\n\n## Task Recipes\n\n{{taskRecipeIndex}}\n\n## Use Case Index\n\n{{useCaseIndex}}\n\n## Known CLI Gaps\n\n{{knownCliGapIndex}}\n\n## Input File Shapes\n\n{{inputFileShapeIndex}}\n\n## Raw Patch Fallback\n\napply-patch accepts either BuildPatchTransaction[] or { "transactions": BuildPatchTransaction[] }.\n\nEach transaction has:\n\n{\n"id": "patch-transaction-label",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "replace", "path": ["meta", "siteName"], "value": "New Site" }\n]\n}\n]\n}\n\nThe transaction id is a patch label used for optimistic synchronization. It is\nnot a Builder record id. Do not invent ids for pages, instances, props,\nbreakpoints, resources, variables, folders, assets, or other project records.\n\nPatch paths are JSON-patch-like paths into Builder store data. Map-like namespaces use ids as the first path item.\n\nSupported namespaces:\n\n- pages: redirects, page records, and folders\n- projectSettings: project-wide metadata and compiler settings\n- instances: element instances and children, including text/expression children\n- props: element props, bindings, page references, resource bindings\n- styles: CSS declarations keyed by style declaration key\n- styleSources: local style sources and reusable design tokens\n- styleSourceSelections: instance-to-style-source connections\n- dataSources: data variables, parameters, and resource data sources\n- resources: data resource definitions\n- assets: project asset records handled by the existing asset patch path\n- breakpoints: responsive breakpoints\n- marketplaceProduct: marketplace metadata\n\n## Data Sources\n\n`dataSources` is the internal Builder namespace for variables. Public API, CLI,\nand MCP tools expose it through two user-facing groups:\n\n- data variables: `list-variables`, `create-variable`, `update-variable`, and\n `delete-variable`\n- data resources: `list-resources`, `create-resource`, `update-resource`, and\n `delete-resource`\n\nFor raw `snapshot`, request the public `variables` namespace rather than the\ninternal `dataSources` name. Raw patch payloads still use `dataSources` when\napplying direct changes.\n\nVariables can be scoped to an instance. Expressions under that instance can use\nthe variable by name; nested variables with the same name mask outer variables.\nVariable values support `string`, `number`, `boolean`, `string[]`, and `json`.\nUse `string[]` for lists of strings such as tags or selected categories; use\n`json` for objects, arrays with mixed shapes, or nested API filter state.\nParameters are internal scoped runtime values provided by pages, collections,\nor components. They are not a public authoring surface: do not create, update,\nor delete parameter records. Public tools should preserve existing parameter\nrecords and may reference documented context values such as `system` in\nexpressions where they are already in scope.\n\nResource `url` accepts plain fixed URLs and paths, for example\n`https://api.example.com/posts` or `/$resources/current-date`. Dynamic URLs can\ncombine strings and variables, for example\n`"https://api.example.com/posts?tag=" + filters.tag`. Prefer `searchParams` for\nquery parameters that should be encoded separately:\n`[{ "name": "tag", "value": "filters.tag" }]`. Header values, search parameter\nvalues, and bodies are expressions for dynamic content. For fixed text, use\n`{ "type": "literal", "value": "application/json" }`; Webstudio stores the\nrequired string expression. Headers can still read variables such as\n`"Bearer " + auth.token`, and GraphQL bodies can return objects such as\n`{ query: "...", variables: { slug: system.params.slug } }`.\n\nCreate a GET resource with `scopeInstanceId` when the fetched resource result\nshould be available as a read data variable. Scoped GET resources default to\n`exposeAsDataSource: true`, are generated into the page resource `data` map,\nand may be loaded during page rendering. Use `dataSourceName` to choose the\nvariable name.\n\nFor submit/write/action resources, create the resource without\n`scopeInstanceId`, then bind a component prop such as a Form `action` to the\nresource with `bind-props` and `binding.type: "resource"`. Prop-bound resources\nare generated into the page resource `action` map instead of the read `data`\nmap. Use this shape for POST, PUT, DELETE, webhook, and other resources that\nshould run only from an explicit form/action flow, not merely because the page\nrendered.\n\nPOST, PUT, and DELETE resources default to `exposeAsDataSource: false` even\nwhen a scope is supplied. Set `exposeAsDataSource: true` only when a write-method\nresource intentionally provides render-time data, such as a read-only GraphQL\nPOST query. A scope is required, and the result includes a warning because the\nrequest may execute during page rendering. Set `exposeAsDataSource: false` on\n`update-resource` to detach an existing render-time data source.\n\nResource `method` can be `get`, `post`, `put`, or `delete`. Use GET for read\ndata. Use POST for creates, GraphQL requests, webhooks, and form submissions.\nUse PUT for full updates/replacements. Use DELETE for deletion actions.\nOptional `control` values are `graphql` and `system`: `graphql` marks a\nGraphQL-style resource, usually POST with a query body; `system` marks a\nresource intended to use the built-in `system` parameter or one of the built-in\nlocal resource URLs: `"/$resources/sitemap.xml"`,\n`"/$resources/current-date"`, and `"/$resources/assets"`. The system parameter\nfields are `system.origin`, `system.pathname`, `system.params`, and\n`system.search`.\n\nUse prop bindings for dynamic values that read variables or resources; use\ndirect props for static values.\n\nCommit raw patch:\n\nMCP tool: apply-patch\n\n## Raw Patch Examples\n\nRename the site:\n\n[\n{\n"id": "patch-site-name",\n"payload": [\n{\n"namespace": "projectSettings",\n"patches": [\n{ "op": "add", "path": ["meta", "siteName"], "value": "Acme Studio" }\n]\n}\n]\n}\n]\n\nUpdate page title metadata:\n\n[\n{\n"id": "patch-page-title",\n"payload": [\n{\n"namespace": "pages",\n"patches": [\n{ "op": "replace", "path": ["pages", "page-id", "meta", "title"], "value": "Pricing" }\n]\n}\n]\n}\n]\n\nUpdate a text child on an element:\n\n[\n{\n"id": "patch-text",\n"payload": [\n{\n"namespace": "instances",\n"patches": [\n{ "op": "replace", "path": ["instance-id", "children", 0, "value"], "value": "Launch faster" }\n]\n}\n]\n}\n]\n\nCreate records with semantic operations such as create-variable,\ncreate-resource, create-design-token, create-page, create-folder,\nand create-breakpoint. Raw patch rejects generated record\ncreation, collection replacement, record replacement with a different `id`, and\nrecord id field mutations in id-keyed namespaces because Webstudio must generate\nand preserve record ids.\n\n## Safety Rules\n\n- For MCP apply-patch, read the latest version with MCP snapshot before writing.\n- Reuse ids from MCP snapshot output when updating existing records.\n- Do not create generated records, replace generated record collections, replace records with different ids, or mutate record id fields with raw patch. Use semantic create operations so Webstudio generates ids.\n- If apply-patch reports a version conflict, read the latest build and regenerate the patch.\n- Prefer semantic MCP read tools for discovery, then use MCP snapshot for exact patch paths.\n\n## Command Index\n\n{{commandIndex}}\n',"manual-llm":'# 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## Connect an MCP client\n\nWhen the user asks to connect the current folder to Webstudio, run the command\nfor the agent client you are currently using:\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 the command from the linked project root. If the folder is not linked, ask\nfor an editable Builder share link and run\n`webstudio init --link <share-link> --json`, followed by `webstudio sync`, then\nretry `webstudio connect <client>`. Treat the share link as a credential and do\nnot include it in committed files, logs, screenshots, or issue reports.\n\n`connect` 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 \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe 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 \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor 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, or use React-style object syntax such as`style={{ padding: 24 }}` when that is simpler. Both forms create editable Webstudio style data.\n\nWhen the task says another user will edit a page in Content mode, use a Content Block (`ws:block`) around every editable region. Content-mode users can edit text and supported props only in descendants of that block; content outside it is read-only. Put reusable insertable options in the block\'s `ws:block-template` child. Do not put intended editor content inside that template container: templates are protected source material, while an inserted template copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nDo not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`. JSX fragments are declarative project data; use the built-in Webstudio helpers instead.\n\nUse Webstudio prop names in JSX: `class`, `for`, `aria-label`, and other HTML/Webstudio names. Do not use React-only aliases such as `className` or `htmlFor`; the runtime rejects them with the Webstudio prop name to use.\n\nUse Webstudio actions for event/action props. Do not pass JavaScript functions such as `onClick={() => ...}`; the runtime rejects them because functions cannot be persisted as Webstudio project data.\n\n```tsx\n<ws.element\n ws:tag="button"\n onClick={new ActionValue(["event"], expression`console.log(event)`)}\n>\n Open\n</ws.element>\n```\n\nPlain JSX prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n\nIf a component has a registered template with required parts, JSX must include those parts explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want Webstudio to apply one component template automatically.\n\n## Animation Components\n\nBefore creating animation examples, inspect the exact components with focused discovery:\n\n```sh\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateChildren"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:AnimateText"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:StaggerAnimation"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-animation:VideoAnimation"}\'\n```\n\nUse Animation Group (`AnimateChildren`) as the controller. Put normal instances directly inside it, or put Text Animation, Stagger Animation, or Video Animation directly inside it. Text, Stagger, and Video are helper components with `contentModel.category: "none"` and should not be used as standalone section roots.\n\nDefine timing and CSS changes on the Animation Group `action` prop. Use `type:"view"` for viewport entry/exit progress and `type:"scroll"` for scroll-progress timelines. For in animations, keep the canvas styles as the final state and use `fill:"backwards"` with keyframes that describe the starting state. For out animations, use `fill:"forwards"` with keyframes that describe the ending state.\n\nText Animation settings: `slidingWindow` defaults to `5`, `easing` defaults to `linear`, and `splitBy` defaults to `char`. Use `splitBy:"space"` for word-by-word animation. The parent Animation Group keyframes provide the actual opacity, translate, scale, or other styles.\n\nStagger Animation settings: `slidingWindow` defaults to `1` and `easing` defaults to `linear`. It applies parent Animation Group progress across its direct children. Use `slidingWindow:0` for instant sequential steps, `1` for one child at a time, and values above `1` for overlapping waves.\n\nVideo Animation settings: `timeline` is a boolean. Prefer `insert-component` for Video Animation so the Video child template is inserted, then configure the Video child asset/source. Use short, seek-friendly videos for smooth scroll-linked playback.\n\nUse JSX fragments for authored animation structures when you need styled, editable examples. Put the final visual state in `ws:style` and put the starting or ending animated state in the Animation Group `action` keyframes. Include an explicit `offset` on every keyframe: use `offset: 0` for starting-state keyframes with `fill:"backwards"` and `offset: 1` for ending-state keyframes with `fill:"forwards"`.\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n axis: "block",\n animations: [\n {\n name: "Fade up on entry",\n timing: {\n fill: "backwards",\n rangeStart: ["entry", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["entry", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 24, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n ],\n }}\n>\n <ws.element\n ws:tag="section"\n ws:style={css`\n display: grid;\n gap: 16px;\n padding: 48px;\n border-radius: 24px;\n background: #111827;\n color: white;\n `}\n >\n <ws.element ws:tag="h2">Launch metrics</ws.element>\n <ws.element ws:tag="p">\n A polished card that fades up as it enters the viewport.\n </ws.element>\n </ws.element>\n</animation.AnimateChildren>\n```\n\nFor Text Animation, keep `animation.AnimateText` as the direct child of Animation Group and place the text-containing element inside it:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Parallax In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: 100, unit: "px" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Opacity In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n {\n name: "Scale In",\n timing: {\n fill: "backwards",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 70, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n },\n },\n ],\n },\n {\n name: "Parallax Out",\n timing: {\n fill: "forwards",\n rangeStart: ["cover", { type: "unit", value: 50, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [\n {\n offset: 1,\n styles: {\n translate: {\n type: "tuple",\n value: [\n { type: "unit", value: 0, unit: "number" },\n { type: "unit", value: -100, unit: "px" },\n ],\n },\n scale: {\n type: "tuple",\n value: [\n { type: "unit", value: 5, unit: "number" },\n { type: "unit", value: 5, unit: "number" },\n ],\n },\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n insetStart: { type: "unit", value: 5, unit: "%" },\n insetEnd: { type: "unit", value: 5, unit: "%" },\n isPinned: true,\n }}\n>\n <animation.AnimateText\n splitBy="space"\n slidingWindow={5}\n easing="easeOutQuart"\n >\n <ws.element ws:tag="h2">Animate words with controlled rhythm</ws.element>\n </animation.AnimateText>\n</animation.AnimateChildren>\n```\n\nFor Stagger Animation, put the repeated cards or rows directly inside `animation.StaggerAnimation`:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n timing: {\n fill: "backwards",\n rangeStart: ["contain", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["contain", { type: "unit", value: 30, unit: "%" }],\n },\n keyframes: [\n {\n offset: 0,\n styles: {\n opacity: { type: "unit", value: 0, unit: "number" },\n },\n },\n ],\n },\n ],\n }}\n>\n <animation.StaggerAnimation>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Plan\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Build\n </ws.element>\n <ws.element\n ws:tag="article"\n ws:style={css`\n padding: 20px;\n border: 1px solid #d1d5db;\n border-radius: 16px;\n `}\n >\n Launch\n </ws.element>\n </animation.StaggerAnimation>\n</animation.AnimateChildren>\n```\n\nFor Video Animation, use the registered template via `insert-component` when possible. If you author JSX, include the Video child explicitly:\n\n```tsx\n<animation.AnimateChildren\n action={{\n type: "view",\n animations: [\n {\n name: "Video progress",\n timing: {\n fill: "both",\n rangeStart: ["cover", { type: "unit", value: 0, unit: "%" }],\n rangeEnd: ["cover", { type: "unit", value: 100, unit: "%" }],\n },\n keyframes: [{ offset: 0, styles: {} }],\n },\n ],\n }}\n>\n <animation.VideoAnimation timeline={true}>\n <$.Video\n preload="auto"\n autoPlay={true}\n muted={true}\n playsInline={true}\n crossOrigin="anonymous"\n />\n </animation.VideoAnimation>\n</animation.AnimateChildren>\n```\n\n## Command Surface Boundary\n\n- Use top-level `webstudio ...` shell commands for setup, sync/import/build/preview/screenshot, permissions, publish/domains, schema, registry inspection, man, and starting MCP.\n- Use MCP tools for Builder project data manipulation: pages, instances/components, props, text, styles, tokens, variables, resources, assets, breakpoints, redirects, and raw patches.\n- From a shell, call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio insert-fragment \'<json>\' --dry-run`. The explicit equivalent is `webstudio mcp single-op-call <tool> \'<json>\'`. Use `--input-file` for large payloads.\n- Inside the Webstudio monorepo, call the local CLI as its own command: `node packages/cli/local.js ...`. Do not wrap the CLI call in `pwd && ...`, command substitution, `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`.\n- For experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- For bounded multi-step shell work, run inline JSON with `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For large batches, write `{ "calls": [{ "tool": "..." }] }` to a normal JSON file and run `webstudio mcp run .temp/mcp-calls.json`.\n- Use JSON strings for `brief` fields. Never pass boolean flags such as `{"brief":true}`.\n- Treat `webstudio mcp single-op-call` and `webstudio mcp run` stderr lines as progress checkpoints; stdout remains JSON on both success and failure. On failure, parse stdout for `{ "ok": false, "error": { "code": "...", "message": "..." } }` before deciding what to fix.\n- If a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in Discord `#help` at https://wstd.us/community. Give them a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n- Run one-shot `webstudio mcp single-op-call` commands sequentially against a linked `.webstudio` folder. If a command returns `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- In delegated or non-streaming agent environments, do not batch many MCP calls silently and do not wrap many shortcut or `webstudio mcp single-op-call` commands in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, report that command/result, then wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with `workflow.next {"goal":"design-system-page","phase":"presentation-pass"}`. Coverage 72/72 is necessary but not sufficient: the page must be organized into styled, real-world examples, not raw unstyled component dumps.\n- For design-system or “use every component” tasks, start with compact `webstudio components.coverage-plan`, checkpoint, then request component coverage details with `webstudio components.coverage-plan \'{"detail":"roots","offset":20}\'` or `{"detail":"parts"}` only when needed. Do not pass `detail` to `list-pages`; use `list-pages {}` or `get-page-by-path` for page lookup.\n- MCP tool shortcuts are only for MCP tools. If a shortcut is ambiguous with a real top-level command, the real top-level command wins; use `webstudio mcp single-op-call <tool> \'<json>\'` to force the MCP path.\n\n## LLM Implementation Process\n\nUse this process for user requests that change Webstudio content, layout, styles, assets, pages, redirects, resources, or publishing state:\n\n1. Discover capabilities with `webstudio man --json`, `webstudio schema api`, `webstudio schema mcp`, MCP `meta.index`, `meta.guide`, `meta.get_more_tools`, `components.list`, `components.summary`, `components.coverage-plan`, `components.search`, `components.get`, `templates.list`, and `templates.get`. From a shell, prefer shortcut calls such as `webstudio meta.index` and `webstudio components.search \'{"brief":"button"}\'` for these focused tool calls; use `webstudio mcp single-op-call` when you need the explicit MCP form. Read full resources such as `webstudio://project/tools` and `webstudio://project/components` only when needed. Do not write scripts to parse full MCP discovery JSON for normal lookup.\n2. Inspect current project state with semantic reads such as `get-project-settings`, `list-pages`, `get-page-by-path`, `list-instances`, `inspect-instance`, `get-styles`, `list-assets`, `list-breakpoints`, and `snapshot` only when needed. Before changing a project, read `get-project-settings` and follow any non-empty `meta.agentInstructions`. These are shared project instructions, not a place for secrets.\n3. Mutate the Webstudio project with semantic MCP write tools first. Prefer MCP `insert-fragment` for authored/styled sections, use `insert-component` only for one automatic component template, then `update-text`, `update-props`, `update-styles`, `upload-asset`, `create-page`, and page/project settings tools over raw patches.\n4. Use `apply-patch` only when no semantic tool covers the required change, and only after reading the latest snapshot/version.\n5. For visual/design work, regenerate or preview the generated app, capture a screenshot, inspect it with vision, and iterate before final response.\n6. Report what changed and what verification ran.\n\n## Visual Design Workflow\n\nFor requests involving visible HTML/CSS, layout, typography, colors, imagery, responsive behavior, or screenshots:\n\n1. Read editable Webstudio structure first: pages, instances, props, styles, breakpoints, assets, and relevant text.\n2. Do not use generated route/component files as the source of truth for editable content.\n3. Make edits through Webstudio semantic commands/MCP tools so the result stays editable in Builder and survives the next `webstudio build`.\n4. Keep generated project files current, start preview, and capture the changed page with `screenshot`.\n5. Use `screenshot.diff` when a baseline exists and inspect screenshot/diff artifacts with vision before finishing.\n6. If vision or screenshot tooling is unavailable, state that explicitly and explain what fallback verification was used.\n\n## Responsive Verification Workflow\n\nFor responsive page work, use Builder breakpoints as the source of truth:\n\n1. Read breakpoints with `list-breakpoints` before deciding responsive behavior.\n2. Apply responsive styles with existing Builder breakpoint ids; do not invent CSS media queries or breakpoint names when Webstudio breakpoint data exists.\n3. Pick screenshot viewport widths from the project breakpoints: include a desktop width, each defined max-width or min-width edge, and a narrow mobile width.\n4. Capture each viewport with `screenshot`, for example `{"path":"/","output":"home-375.png","viewport":{"width":375,"height":812}}` and `{"path":"/","output":"home-1440.png","viewport":{"width":1440,"height":900}}`.\n5. Inspect every viewport screenshot with vision before finishing, checking layout, overflow, hidden content, text wrapping, and breakpoint-specific style changes.\n6. If any viewport fails, update styles through semantic Webstudio tools and repeat screenshots for the affected breakpoints.\n\n## Generated Files Guardrails\n\n- Do not edit `app/__generated__`, generated route files, generated page files, generated CSS, or build output for normal Webstudio content/design requests.\n- Do not replace generated page components with handcrafted app code unless the user explicitly asks for code-only export customization.\n- Generated files are build artifacts and may be overwritten by `webstudio build`.\n- If a task truly requires generated app customization, keep it outside `app/__generated__` where possible and explain that it is not editable Webstudio content.\n\n## Values vs Bindings\n\nBefore authoring unfamiliar expressions, read `webstudio://project/expressions` with MCP `resources/read` or `webstudio mcp read-resource webstudio://project/expressions`. It documents the supported expression subset, method allowlist, scope, Collection context, and validation limits.\n\n- Use direct value tools for fixed content. For one visible text child, use `update-text` with plain `text`. For a bounded multi-instance literal replacement, use `replace-text` with `find`, `replace`, `pagePath` or `pageId`, and `limit`; it does not change expression children. Use `replace-prop-text` for bounded changes inside static string props, optionally limited to prop names or instance ids; it never changes dynamic bindings. For static props such as `aria-label`, `alt`, `id`, `class`, `href`, or button labels stored as props, use `update-props` with the prop\'s direct type/value.\n- Use `bind-props` only when the prop must stay dynamic: an expression, resource result, action, or existing scoped runtime context such as `system`. Do not use `bind-props` just to set a fixed string.\n- Direct prop string example: `{"updates":[{"instanceId":"button-id","name":"aria-label","type":"string","value":"Open menu"}]}`.\n- Expression binding example: `{"bindings":[{"instanceId":"link-id","name":"href","binding":{"type":"expression","value":"currentPost.url"}}]}`.\n- Page metadata fields such as `title`, `description`, `language`, `redirect`, `status`, and custom meta content accept plain fixed text. For computed values, pass JavaScript expression code such as `pageTitle ?? "Pricing | Acme"`.\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- Data variable values support `string`, `number`, `boolean`, `string[]`, and `json`. Use `string[]` only for arrays where every item is a string; use `json` for objects, mixed arrays, 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 be expressions such as `"\\"Bearer \\" + auth.token"`. Body can be an object expression, including GraphQL payloads such as `{ query: "...", variables: { slug: system.params.slug } }`.\n- Resource methods are `get`, `post`, `put`, and `delete`. Optional resource controls are `graphql` and `system`. Use `control:"graphql"` for GraphQL POST resources with query bodies. Use `control:"system"` for built-in local resource URLs such as `"/$resources/current-date"` and for resources reading the built-in `system` parameter. The built-in system fields are `system.origin`, `system.pathname`, `system.params`, and `system.search`; do not use `system.path`.\n- Whenever an array or object from a resource or data variable should render repeated UI, call `insert-collection` with the complete iterable and one repeated-item JSX root. The command creates the Collection, private item parameters, iterable binding, and descendant item bindings atomically. Use `collectionItem` and `collectionItemKey` expressions in the item JSX. Wrap multiple repeated siblings in one Element, and give repeated Radix items stable unique `value` bindings.\n- Expressions are single JavaScript expressions, not statements or functions. Functions, arrow functions, classes, `new`, `this`, `await`, imports, arbitrary calls, increment/decrement, and assignment outside actions are unsupported. Prefer optional chaining, nullish coalescing, ternaries, property/index access, operators, and the documented string/array methods.\n\n## Pick Read Command\n\n{{readFirst}}\n\n## Pick Write Command\n\n{{taskRecipeIndex}}\n\n## Raw Patch Only If Needed\n\n1. Use MCP tool: snapshot.\n2. Write BuildPatchTransaction[].\n3. Use MCP tool: apply-patch.\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects, not CLI flags. Use these shapes:\n\n{{mcpArgumentExampleIndex}}\n\n## Rules\n\n- Never guess ids for existing records. Read them first.\n- Never use project ids from user input. Commands use the configured project.\n- Use --refresh before a local-capable command when cached data may be stale.\n- Pass --json only to commands whose help/schema documents it. Do not add --json to top-level commands such as sync unless supported.\n- On VERSION_CONFLICT, read MCP snapshot again, regenerate the patch, then retry.\n- Treat stdout JSON as the API contract and stderr as diagnostics.\n- For visual/design work, verify the rendered result with vision before finishing.\n- Do not edit generated files for normal Webstudio content/design requests.\n- Use direct values for static strings and bindings only for dynamic expressions/resources/actions.\n- Use plain fixed text where documented. Only encode a quoted JavaScript string literal when a field is explicitly documented as an expression-only value.\n- Confirm destructive commands with --confirm only when user requested deletion/unpublish/replacement.\n- Use webstudio schema api for machine-readable top-level command metadata and webstudio schema mcp for MCP tool schemas.\n\n## Known Gaps\n\n{{knownCliGapIndex}}\n',"manual-mcp":- '# Webstudio MCP Manual\n\n`webstudio mcp` starts a stdio MCP server for real MCP clients. Shell users can call MCP tools with the shortcut form `webstudio <tool> \'<json>\'`, for example `webstudio meta.index` or `webstudio insert-fragment \'<json>\' --dry-run`. `webstudio mcp single-op-call` is the explicit equivalent and prints the structured JSON result. `webstudio mcp run` runs multiple MCP tool calls from inline JSON or a normal JSON file in one shared CLI session. Do not manually type or pipe raw JSON-RPC frames into `webstudio mcp` from an interactive shell or PTY.\n\n## Startup\n\nIf you are already working with an agent, ask it to connect the current folder\nto Webstudio. Give the editable Builder share link only when the trusted agent\nasks for it. The agent should perform the steps below, follow any\nclient-specific output from `webstudio connect`, and verify the connection by\nlisting the project pages. Treat the share link as a credential: do not include\nit in committed files, screenshots, logs, or issue reports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Synchronize it with `webstudio sync`.\n3. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview the generated setup.\n4. Check capabilities with `webstudio permissions --json`.\n5. For shell-driven agents, 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.\n6. For MCP clients, start the server with `webstudio mcp`.\n7. 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\nAfter linking and synchronization, run `webstudio connect <client>`, reload or\nrestart the client, then ask the agent to use Webstudio MCP to list the project\npages. The supported client names are `claude`, `codex`, `cursor`, and `vscode`.\nFor Codex, `connect` registers and verifies the server through the Codex CLI;\nthe resulting server appears in Codex settings. Use `--print` to inspect the\nexact registration command without changing configuration or requiring project\naccess. Before changing client configuration, `connect` verifies that the saved\nproject endpoint is reachable and its credential is accepted. If verification\nfails, follow the specific connection, compatibility, or relinking guidance in\nthe error.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\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- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\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, upload, add, update, find usage for, replace, and delete assets.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\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 an agent, ask it to connect the current folder\nto Webstudio. Give the editable Builder share link only when the trusted agent\nasks for it. The agent should perform the steps below, follow any\nclient-specific output from `webstudio connect`, and verify the connection by\nlisting the project pages. Treat the share link as a credential: do not include\nit in committed files, screenshots, logs, or issue reports.\n\n1. Configure a project with `webstudio init --link <api-share-link> --json`.\n2. Synchronize it with `webstudio sync`.\n3. Generate the client configuration with `webstudio connect claude`,\n `webstudio connect codex`, `webstudio connect cursor`, or\n `webstudio connect vscode`. Use `--print` to preview the generated setup.\n4. Check capabilities with `webstudio permissions --json`.\n5. For shell-driven agents, 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.\n6. For MCP clients, start the server with `webstudio mcp`.\n7. 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\nAfter linking and synchronization, run `webstudio connect <client>`, reload or\nrestart the client, then ask the agent to use Webstudio MCP to list the project\npages. The supported client names are `claude`, `codex`, `cursor`, and `vscode`.\nFor Codex, `connect` registers and verifies the server through the Codex CLI;\nthe resulting server appears in Codex settings. Use `--print` to inspect the\nexact registration command without changing configuration or requiring project\naccess. Before changing client configuration, `connect` verifies that the saved\nproject endpoint is reachable and its credential is accepted. If verification\nfails, follow the specific connection, compatibility, or relinking guidance in\nthe error.\n\nStart MCP from the linked Webstudio project root. The lifecycle status line prints that absolute root; create local scripts, screenshots, and temporary artifacts under that root, for example `<project root>/.temp/script.mjs`. If the shell starts in a parent workspace, `cd` into the project root first or use absolute paths.\n\nWhen developing inside the Webstudio monorepo, start the local CLI exactly as `node packages/cli/local.js mcp` from the repo root. Do not use `pnpm exec webstudio`, `pnpm --filter webstudio exec webstudio`, or a global `webstudio`: they can resolve an older binary.\n\nWhile the server is running, stdout is reserved for MCP JSON-RPC messages. Do not print human text from the server process. The server advertises MCP `logging` capability and emits sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`; stderr also mirrors these sparse lifecycle fallback lines prefixed with `[webstudio mcp]`.\n\n## One-Shot Tool Calls\n\nUse the shortcut `webstudio <tool> \'<json>\'` when you are operating from a shell and need one MCP tool result. The explicit form `webstudio mcp single-op-call <tool> \'<json>\'` is equivalent and avoids writing temporary Node.js stdio client scripts.\n\nExamples:\n\n```sh\nwebstudio mcp single-op-call meta.index\nwebstudio mcp single-op-call meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio mcp single-op-call meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio mcp single-op-call components.list \'{"source":"all"}\'\nwebstudio mcp single-op-call components.coverage-plan\nwebstudio mcp single-op-call components.search \'{"brief":"radix select"}\'\nwebstudio mcp single-op-call components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call templates.list\nwebstudio mcp single-op-call templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio mcp single-op-call insert-fragment --input-file .temp/insert-fragment.json\n```\n\nShortcut equivalents:\n\n```sh\nwebstudio meta.index\nwebstudio meta.guide \'{"brief":"Create a design system page using every component"}\'\nwebstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nwebstudio components.list \'{"source":"all"}\'\nwebstudio components.coverage-plan\nwebstudio components.search \'{"brief":"radix select"}\'\nwebstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio templates.list\nwebstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'\nwebstudio insert-fragment --input-file .temp/insert-fragment.json\n```\n\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- Prefer JSX for authored/styled content. Common `insert-fragment` inputs:\n\n```jsonl\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 16px;`}><ws.element ws:tag="h2">Northstar Product OS</ws.element><ws.element ws:tag="p">Reusable patterns for teams.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" style={{ padding: 32, borderRadius: 16 }}><ws.element ws:tag="h2">Operations Console</ws.element><ws.element ws:tag="p">React-style object styles become editable Webstudio styles.</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\" ws:tokens={[token(\\"accent\\", css`color: #0f766e;`)]}><ws.element ws:tag="button" onClick={new ActionValue([\\"event\\"], expression`console.log(event)`)}>Track launch</ws.element></ws.element>"}\n{"parentInstanceId":"root-id","fragment":"<ws.element ws:tag=\\"section\\"><radix.Switch><radix.SwitchThumb /></radix.Switch></ws.element>"}\n```\n\n- Do not access host globals or dynamic code APIs in JSX fragments, including `process`, `globalThis`, `eval`, `Function`, or `constructor`.\n- Use Webstudio prop names such as `class` and `for`; do not use React aliases `className` or `htmlFor`.\n- Use Webstudio actions for event/action props, for example `onClick={new ActionValue(["event"], expression\\`console.log(event)\\`)}`. Do not pass JavaScript functions such as `onClick={() => ...}`.\n- Plain prop values must be JSON-compatible: `null`, strings, booleans, finite numbers, arrays, and plain objects. Do not pass `undefined`, `Symbol`, `BigInt`, `NaN`, `Infinity`, `Date`, `Map`, `Set`, class instances, or circular objects; omit the prop, use plain data, or use `expression`/`ActionValue` when the value is dynamic.\n- Template-backed components used in JSX must include required child/part components explicitly under the same parent structure as the template, for example `<radix.Switch><radix.SwitchThumb /></radix.Switch>`. Use `insert-component` when you want one automatic registered component template.\n- The positional input is JSON and defaults to `{}`.\n- Use `--input-file` for large mutation payloads.\n- Use `--dry-run` with local-capable mutation tools when you need a patch plan without committing. The computed transaction is returned in `meta.session.transaction`, and `meta.session.version` is its base build version. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n- The command prints JSON to stdout for both success and failure. Success uses the same `structuredContent` shape MCP tools return: `{ "ok": true, "data": ..., "meta": ... }`. Failure prints `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` and exits nonzero.\n- The command writes sparse progress to stderr, including start, success/failure, elapsed time, and committed status when the tool returns session metadata.\n- Invalid argument types fail loudly with path-specific messages, for example `meta.guide input.brief must be a string when provided`.\n- Run one-shot shortcut or `mcp single-op-call` commands sequentially against the same linked `.webstudio` folder. If you receive `PROJECT_SESSION_BUSY`, another CLI/MCP process is updating the local session; wait a moment and retry sequentially.\n- To work with another previously linked project without changing the directory\'s default link, start MCP or a shell call with `--project <projectId>`, for example `webstudio mcp --project <projectId>` or `webstudio mcp single-op-call list-pages --project <projectId>`. Selected projects use isolated local session and checkpoint files.\n- If you are a delegated agent and your parent cannot see live stderr/stdout, do not run a long sequence of shortcut or `mcp single-op-call` commands silently and do not wrap many calls in a shell loop. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one `webstudio <tool>` or `webstudio mcp single-op-call` command, report that command/result, then wait before the next MCP command. For all-component design-system pages, checkpoint after discovery, checkpoint after page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase. Coverage alone is not completion; organize examples into styled sections/cards.\n\n## Reporting CLI/MCP Issues\n\nIf a CLI/MCP tool gives a confusing error, crashes, hangs, produces invalid output, requires an undocumented workaround, or makes you inspect source code to understand normal usage, ask the user to report it in the Webstudio Discord `#help` channel: https://wstd.us/community.\n\nGive the user a complete copy-paste report. Include only non-secret values: never include auth tokens, private URLs, cookies, API keys, passwords, or proprietary project data. Redact them as `<redacted>`.\n\nCopy-paste template:\n\n````md\nWebstudio CLI/MCP issue report\n\nWhat I was trying to do:\n<short user goal, for example "Create a resource from an external API and render it in a collection">\n\nWhat I expected:\n<what should have happened>\n\nWhat happened instead:\n<exact error, confusing behavior, hang, missing docs, or workaround required>\n\nCommand/tool used:\n\n```sh\n<exact command or MCP tool call, with tokens/secrets redacted>\n```\n\nStructured output / error:\n\n```json\n<stdout JSON or MCP structuredContent, if available, with secrets redacted>\n```\n\nStderr / lifecycle logs:\n\n```txt\n<stderr lines, timings, checkpoint messages, or stack trace, with secrets redacted>\n```\n\nEnvironment:\n\n- CLI command path: <webstudio / node packages/cli/local.js / other>\n- Webstudio CLI version: <from command output if known>\n- OS: <macOS / Windows / Linux / unknown>\n- Node version: <node -v if known>\n- Project/session state: <linked project, local .webstudio session, preview, MCP server, or unknown>\n\nWorkaround tried:\n<what the agent/user tried next, and whether it worked>\n\nWhy this should be improved:\n<one sentence: better error message, docs, schema, tool behavior, etc.>\n````\n\n## Shared-Session Shell Runs\n\nUse `webstudio mcp run \'[{"tool":"components.find","input":{"brief":"button"}}]\'` when you are operating from a shell and need several MCP tool calls to share one CLI session without hand-writing JSON-RPC. For large batches, pass a normal JSON file path such as `.temp/mcp-calls.json`. Do not use shell process substitution like `<(...)`; use inline JSON or a real file.\n\nUse `mcp run` for long-lived tools such as `preview.start`. A one-shot `mcp single-op-call preview.start` cannot keep ownership of a preview server for a later screenshot or stop call. Put `preview.start`, `screenshot`, and `preview.stop` in one shared `mcp run` process, or use a real long-running MCP client.\n\nInput shape:\n\n```json\n{\n "calls": [\n { "tool": "meta.index" },\n { "tool": "components.find", "input": { "brief": "radix select" } }\n ]\n}\n```\n\nRules:\n\n- The command prints JSON to stdout for both success and failure. It stops at the first failed call and prints partial results in `{ "ok": false, "error": ..., "data": { "completedCalls": ..., "results": [...] }, "meta": ... }`, then exits nonzero.\n- If a call returns `checkpoint.required`, read-only discovery and inspection remain available, but mutations and state-changing session tools return `CHECKPOINT_REQUIRED`. Stop and report the checkpoint to the parent/user. Only after the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}` before continuing mutations.\n- For `mcp single-op-call`, checkpoint requirements persist across later one-shot CLI processes until you call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`.\n- Use this instead of manually sending JSON-RPC frames to `webstudio mcp` from a shell.\n\n### Cross-project batches\n\nAdd `projects` to the same `mcp run` manifest to run focused reads, audits, or dry runs across independently linked project roots:\n\n```json\n{\n "concurrency": 2,\n "calls": [\n { "tool": "status" },\n { "tool": "audit", "input": {} },\n {\n "tool": "update-project-settings",\n "input": { "meta": { "siteName": "Reviewed" } },\n "dryRun": true\n }\n ],\n "projects": [\n { "id": "site-a", "root": "../site-a" },\n { "id": "site-b", "root": "../site-b" }\n ]\n}\n```\n\nProject roots and an optional `progressFile` are resolved relative to the manifest file. Each project may provide its own `calls` instead of using the top-level calls. Each root must already be linked with its own `.webstudio/config.json`; the runner creates an independently authenticated ProjectSession and uses root-scoped session, audit, preview-data, and checkpoint paths without changing the process working directory.\n\nConcurrency defaults to 2, is capped at 16, and can be set in the manifest or overridden with `--concurrency`. A failure is reported for that project while other projects continue. Progress is saved after every successful call; rerunning with the default `--resume` skips completed projects and starts failed projects after their last confirmed successful call. Reads and dry runs may be retried. A committed mutation interrupted after dispatch is marked `AMBIGUOUS_MUTATION_RESULT` and is never replayed automatically; inspect that project before deciding how to continue. Use `--no-resume` only to intentionally start the complete manifest over.\n\nCommitted mutation tools are rejected in a projects batch unless the command includes `--approve-mutations`. Review the complete manifest before granting approval. `--dry-run` applies to every call and does not require mutation approval. The final stdout object is compact: project counts, one status/error record per project, elapsed time, and the progress-file path rather than every tool result.\n\n## Discovery\n\nUse MCP itself after startup, or call the same tools with `webstudio mcp single-op-call`:\n\n- `tools/list`: machine-readable available tools\n- `resources/list`: available overview and full JSON resources\n- `meta.index`: concise capability catalog\n- `meta.guide`: workflow for a user goal; call with a string brief such as `{"brief":"Create a pricing page"}`\n- `meta.get_more_tools`: detailed params, examples, namespaces, and local/server behavior; prefer exact names such as `{"tools":["insert-fragment"]}` when you know them\n- `components.list`: compact registry metadata for visible components and templates; use a focused get tool for complete details\n- `components.summary`: component counts by default; use `{"detail":"components","limit":20}` for paginated entries\n- `components.coverage-plan`: compact paged plan for design-system coverage tasks that need every component; default returns counts plus the first root page, use `{"detail":"roots"}`, `{"detail":"parts"}`, or `{"detail":"full"}` for more\n- `components.coverage-status`: page-specific covered/missing component report with `missingRoots` and `missingParts`\n- `components.search`: focused component/template search by id, namespace, label, category, or content model\n- `components.find`: compatibility alias for focused component search\n- `components.get`: full metadata for one component id\n- `templates.list`: compact metadata for template-backed insertions only\n- `templates.get`: full registry item and payload metadata for one template\n\nComponent and template registry items use a shadcn-compatible top-level shape plus Webstudio-specific superset metadata in `meta`. Use `meta.runtime` for component ids, props, states, content model, and source identity; `meta.authoring` for composition and accessibility guidance; and `meta.builder` for template insertion details and expected project-data namespaces. These items are for Builder/MCP discovery and are not a published shadcn install registry yet.\n\nPrefer the focused `components.*` tools over dumping `webstudio://project/components`. Do not write local scripts to parse full MCP discovery JSON for common component lookup.\nFor “use every component” or design-system pages, start with compact `components.coverage-plan`, checkpoint, then page through roots/parts instead of dumping the full catalog.\n\n## Consumer Capabilities\n\nMCP lets agents work on one configured Webstudio project at a time. In consumer\nterms, agents can:\n\n- Check which project they are connected to.\n- Check what the share link is allowed to do.\n- Inspect project metadata and the latest editable build.\n- Read selected project data for audits and repair.\n- Apply precise project changes against a known version.\n- List, inspect, create, update, delete, duplicate, copy, and reorder pages.\n- Set the home page.\n- Preserve old page paths for redirects or history.\n- Read and update page titles, descriptions, metadata, auth settings, and SEO fields.\n- List, create, update, duplicate, move, and delete page folders.\n- List, create, update, delete, duplicate, reorder, and reuse page templates.\n- Create pages from reusable templates.\n- Read and update project site settings.\n- Read and update marketplace product metadata.\n- List, create, update, delete, and replace redirects.\n- List, create, update, and delete responsive breakpoints.\n- List and inspect page elements.\n- Insert registered components.\n- Insert styled JSX fragments.\n- Move, reparent, clone, duplicate, wrap, unwrap, convert, rename, retag, and delete elements.\n- Fill grid cells.\n- List and update text children.\n- Update plain text and expression text.\n- Update structured rich text.\n- Add, update, delete, and bind element props.\n- Bind props to expressions, resources, actions, and runtime system values.\n- Read, add, update, delete, and replace local styles.\n- Update selected style-source styles.\n- List, create, update, attach, detach, extract, duplicate, rename, lock, unlock, reorder, clear, and delete design tokens and style sources.\n- List, define, rename, delete, and rewrite CSS variables.\n- List, create, update, and delete static data variables.\n- Create string, number, boolean, string list, and JSON variables.\n- Delete unused data variables.\n- List, create, update, upsert, bind, and delete resources.\n- Create HTTP resources.\n- Create GraphQL resources.\n- Create system resources.\n- Use built-in system resources for sitemap, current date, and assets.\n- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.\n- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.\n- Publish to staging or production.\n- Publish to selected domains.\n- List publish builds.\n- Check publish job status.\n- Unpublish staging or production deployments.\n- List, create, update, delete, and verify custom domains.\n- Start and stop preview.\n- Capture screenshots of generated pages.\n- Compare screenshots against baselines.\n- Install OCR support for richer visual checks.\n\nUseful resources:\n\n- `webstudio://project/status`: compact current ProjectSession status\n- `webstudio://project/tools-overview`: small operation overview by capability area\n- `webstudio://project/components-overview`: small component overview with ids, labels, namespaces, and categories\n- `webstudio://project/tools`: full operation catalog; read only when focused metadata is insufficient\n- `webstudio://project/components`: full component catalog with props, states, and content model composition constraints; read only when `components.summary`, `components.find`, and `components.get` are insufficient\n- `webstudio://project/guide`: concise discovery guide\n- `webstudio://project/expressions`: expression syntax, scope, supported methods, bindings, Collection iteration context, and verification\n- `webstudio://project/accessibility-review`: evidence-based LLM accessibility-review workflow using project checks, preview, and screenshots\n\n## MCP SDK Client Imports\n\nWhen writing a local Node.js MCP client script, use the official MCP SDK package and these exact ESM imports:\n\nInside the Webstudio monorepo this package is available at the repo root. In another project, install it first with `pnpm add -D @modelcontextprotocol/sdk`.\n\n```js\nimport { Client } from "@modelcontextprotocol/sdk/client/index.js";\nimport { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";\nimport { LoggingMessageNotificationSchema } from "@modelcontextprotocol/sdk/types.js";\n```\n\nMinimal stdio client for the local Webstudio CLI:\n\n```js\nconst client = new Client({ name: "webstudio-agent", version: "1.0.0" });\n\nclient.setNotificationHandler(\n LoggingMessageNotificationSchema,\n (notification) => {\n console.error(`[mcp] ${notification.params.data}`);\n }\n);\n\nconst transport = new StdioClientTransport({\n command: "node",\n args: ["packages/cli/local.js", "mcp"],\n cwd: process.cwd(),\n stderr: "inherit",\n});\n\nawait client.connect(transport);\n\nconst index = await client.callTool({\n name: "meta.index",\n arguments: {},\n});\nconsole.log(JSON.stringify(index.structuredContent, null, 2));\n\nawait client.close();\n```\n\nUse `node packages/cli/local.js mcp` from the Webstudio monorepo root for local development, or `webstudio mcp` from a linked project where the CLI is installed. Keep stdout for JSON-RPC/structured results and surface MCP logging notifications or stderr lifecycle lines as progress.\n\n## Core Rules\n\n- stdout is reserved for MCP JSON-RPC while the server is running.\n- Operate on the configured project only.\n- Read ids before writing.\n- Prefer semantic tools over `apply-patch`.\n- Use `status` and `refresh` when cached namespaces may be stale. Pass `status {"verbose":true}` only when debugging full namespace arrays, freshness, compatibility, or diagnostic details.\n- A mutation is durable only when `meta.session.committed` is true.\n- For visual/design work, verify the rendered result with vision before finishing.\n\n## Vision Verification Loop\n\nVision-capable AI can use MCP to see what it is building:\n\n{{mcpVisionVerificationLoopMarkdown}}\n\nGenerated app setup:\n\n{{mcpGeneratedAppDependencyNotes}}\n\n## MCP Argument Examples\n\nMCP tools receive JSON argument objects:\n\n{{mcpArgumentExampleIndex}}\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 \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nThe shorter local shortcut form is preferred for simple shell steps:\n\n```sh\nnode packages/cli/local.js meta.index\nnode packages/cli/local.js meta.get_more_tools \'{"tools":["insert-fragment"]}\'\nnode packages/cli/local.js insert-fragment \'{"parentInstanceId":"parent-id","fragment":"<ws.element ws:tag=\\"section\\" ws:style={css`padding: 32px; display: grid; gap: 12px;`}><ws.element ws:tag="h2">Launch Kit</ws.element><ws.element ws:tag="p">A focused section created with Webstudio JSX.</ws.element><ws.element ws:tag="button">Get started</ws.element></ws.element>"}\' --dry-run\n```\n\nFor simple authored/styled sections, run the three commands above. Do not grep source files, dump full MCP resources, or write parser scripts first. Use `list-pages`, `get-page-by-path`, or `list-instances` only when you still need the target `parentInstanceId`.\n\nWhen building for a Content-mode editor, use a Content Block (`ws:block`) around every region that editor must change. Content-mode text and supported props are editable only in Content Block descendants; content outside is read-only. Keep reusable insertable source options in the block\'s `ws:block-template` child. Templates themselves are protected; an editor\'s inserted copy becomes an editable direct child of the Content Block. Verify this structure before handoff.\n\nRun it from the linked Webstudio project root. The startup status line prints that absolute root; use it for local files such as `<project root>/.temp/script.mjs`, screenshots, and generated artifacts.\n\nFor experiments, pass `--dry-run` to local-capable mutation calls. Read the computed transaction from `meta.session.transaction` and its base build version from `meta.session.version`. Copying a `.webstudio` folder is not an isolated project clone; `.webstudio/config.json` still points to the same remote project, so non-dry-run mutations can commit to that project.\n\nStartup marks cached ProjectSession data stale so MCP tools read the current Builder dev build.\n\nAfter startup, use focused discovery tools with concrete JSON. For delegated design-system or “use every component” tasks, start with exactly one command: `webstudio workflow.next \'{"goal":"design-system-page"}\'`; report the returned checkpoint to the parent/user and stop until continued. For other tasks, read `meta.index` first. From a shell, `webstudio mcp list-tools` is a concise alias for the initial tool catalog. Then call shortcuts such as `webstudio meta.guide \'{"brief":"Create a design system page using every component"}\'`, `webstudio workflow.next \'{"goal":"design-system-page"}\'`, `webstudio meta.get_more_tools \'{"tools":["insert-fragment"]}\'`, `webstudio components.list \'{"source":"all"}\'`, `webstudio components.summary`, `webstudio components.search \'{"brief":"radix select"}\'`, `webstudio components.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`, `webstudio templates.list`, and `webstudio templates.get \'{"component":"@webstudio-is/sdk-components-react-radix:Select"}\'`. Use `webstudio mcp single-op-call` when you need the explicit MCP form. Prefer `insert-fragment` for authored/styled sections; use `insert-component` only when inserting one automatic component template. In JSX, use `ws:style={css\\`...\\`}`for styles,`class`/`for`instead of`className`/`htmlFor`, `ActionValue`for actions instead of JavaScript functions such as`onClick={() => ...}`, only JSON-compatible plain prop values, and no host globals or dynamic code APIs. For bounded multi-step shell work, run inline JSON like `webstudio mcp run \'[{"tool":"meta.index"},{"tool":"components.search","input":{"brief":"button"}}]\'`; this reuses one CLI session without raw JSON-RPC. For larger batches, write `{ "calls": [{ "tool": "..." }] }`to`.temp/mcp-calls.json`and run`webstudio mcp run .temp/mcp-calls.json`. If any call returns `checkpoint.required`, `mcp run`stops immediately before later calls; report the checkpoint and call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`before continuing. For design-system or “use every component” tasks, call`workflow.next {"goal":"design-system-page"}`for the next bounded phase, report its checkpoint, wait until the parent/user continues, call`checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, then run only that phase. Start coverage phases with compact`webstudio components.coverage-plan`, checkpoint, then request component coverage details with `components.coverage-plan {"detail":"roots"}`or`components.coverage-plan {"detail":"parts"}`. Do not pass `detail`to`list-pages`; use `list-pages {}`or`get-page-by-path`for page lookup. Read MCP overview resources`webstudio://project/guide`, `webstudio://project/tools-overview`, and `webstudio://project/components-overview`when useful. Read full resources`webstudio://project/tools`and`webstudio://project/components` only when focused tools are insufficient; do not dump or parse full discovery JSON for common lookup.\n\nAfter startup, MCP clients discover capabilities with `tools/list`, `resources/list`, `meta.index`, `meta.guide`, and `meta.get_more_tools`.\n\nstdout is reserved for MCP JSON-RPC messages while the server is running.\n\nThe server advertises MCP `logging` capability and sends sparse `notifications/message` logs for ready state and tool lifecycle checkpoints such as `tool preview.start started`, `tool preview.start still running after 10000ms`, and `tool preview.start succeeded in 1234ms`. It also writes the same sparse lifecycle status lines to stderr, prefixed with `[webstudio mcp]`, including a final ready line. Treat the process as healthy and long-running after either ready signal; surface tool lifecycle logs as progress checkpoints and interact through MCP JSON-RPC on stdin/stdout.\n\n`webstudio mcp single-op-call` also writes sparse lifecycle lines to stderr for each one-shot call. Use those stderr lines as progress checkpoints and parse stdout as JSON on both success and failure. Failed one-shot calls print `{ "ok": false, "error": { "code": "...", "message": "..." }, "meta": ... }` to stdout and exit nonzero. If a one-shot call returns checkpoint.required, read-only discovery remains available, while later mutations fail with `CHECKPOINT_REQUIRED` until you report the checkpoint and call `webstudio mcp single-op-call checkpoint.ack \'{"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}\'`.\n\n`webstudio mcp run` also writes sparse lifecycle lines to stderr and prints one JSON result on success or failure. It stops at the first failed call or checkpoint requirement, including `CHECKPOINT_REQUIRED`, and preserves partial results so delegated agents can report exactly where they stopped.\n\nIf a CLI/MCP tool crashes, hangs, gives a confusing error, needs an undocumented workaround, or forces source-code inspection for normal usage, ask the user to report it in the Webstudio Discord `#help` channel at https://wstd.us/community. Give the user a complete copy-paste report with the goal, expected behavior, actual error, exact command/tool call, stdout JSON, stderr/lifecycle logs, environment, workaround, and secrets redacted.\n\nIf you are running as a delegated or non-streaming agent whose parent cannot see live stderr/stdout, do not batch many MCP calls silently and do not run long shell loops of shortcut or `webstudio mcp single-op-call` commands. Treat each parent-visible checkpoint as the unit of work. If the parent asks for status within 30 seconds, run exactly one shortcut command such as `webstudio meta.index` or one explicit `webstudio mcp single-op-call` command, return a concise checkpoint with that command/result, and wait for the parent to continue. Do not take a broad task such as creating a full design-system page as one execution unit. Call `workflow.next {"goal":"design-system-page"}`, report the returned phase/checkpoint, wait until the parent/user continues, call `checkpoint.ack {"reported":true,"continueAfterReport":true,"summary":"<what you reported>"}`, complete exactly that bounded phase, and return: discovery, page creation, one dry-run JSX section, one committed JSX section, one `components.coverage-insert-next` call, or one presentation pass. Phase commands do not include nextPhase in their own output. After the parent continues, acknowledge the previous checkpoint first, then call `workflow.next` with the next phase. For all-component design-system pages, checkpoint after workflow planning, discovery, page creation, call `components.coverage-insert-next` once before checkpointing again, then finish with the `presentation-pass` workflow phase.\n',"mcp-vision":diff --git a/packages/cli/src/docs/api-use-cases.md b/packages/cli/src/docs/api-use-cases.mdindex 0b6f5569f2..e677cf2251 100644--- a/packages/cli/src/docs/api-use-cases.md+++ b/packages/cli/src/docs/api-use-cases.md@@ -107,7 +107,7 @@ MCP lets agents work on one configured Webstudio project. Agents can:- Create HTTP, GraphQL, and system resources.- Use system resources for sitemap, current date, and assets.- Bind resources to rendered data or form/action props.-- Upload, replace, delete, and inspect asset usage.+- Manage nested asset folders and upload, inspect, move, duplicate, download, replace, delete, and inspect usage for assets.- Publish, unpublish, inspect publish jobs, and manage custom domains.- Start preview, capture screenshots, compare screenshot diffs, and use OCR when installed.@@ -724,12 +724,66 @@ Commands:Commands:- MCP tool: list-assets {"withUsage":true}+- MCP tool: list-assets {"verbose":true}Notes:+- Compact results include each asset's folder id. Use `verbose:true` to include complete records for a page of assets, or `get-asset` to read one complete record including description, folder, creation time, and image/font metadata.- Image asset descriptions are the default alt text for asset-backed Image components.- To generate missing descriptions, inspect the image in its rendered page or asset source, write a concise description of its purpose, and save it on the asset rather than duplicating it on each Image instance.+## Get asset++Commands:++- MCP tool: get-asset {"assetId":"<assetId>"}++## List asset folders++Commands:++- MCP tool: list-asset-folders {}++## Create asset folder++Commands:++- MCP tool: create-asset-folder {"name":"Marketing"}+- MCP tool: create-asset-folder {"name":"Photos","parentId":"<parentFolderId>"}++## Update asset folder++Commands:++- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"name":"Brand"}}+- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":"<parentFolderId>"}}+- MCP tool: update-asset-folder {"folderId":"<folderId>","values":{"parentId":null}}++Notes:++- Updating `parentId` is the folder equivalent of cut and paste. Use `null` to move a folder to Root.++## Duplicate asset folder++Commands:++- MCP tool: duplicate-asset-folder {"folderId":"<folderId>"}+- MCP tool: duplicate-asset-folder {"folderId":"<folderId>","parentId":"<targetFolderId>"}++Notes:++- Duplication recursively copies descendant folders and assets. This is the folder equivalent of copy and paste.++## Delete asset folder++Commands:++- MCP tool: delete-asset-folder {"folderId":"<folderId>"}++Notes:++- Deleting a folder recursively deletes its descendant folders and assets.+## Update asset metadataCommands:@@ -774,6 +828,7 @@ Notes:Commands:- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}+- MCP tool: upload-asset {"asset":{"name":"image.png","type":"image","format":"png","folderId":"<folderId>","meta":{"width":1200,"height":630}},"assetsDir":".webstudio/assets"}## Upload asset batch@@ -781,6 +836,24 @@ Commands:- MCP tool: upload-assets {"assets":[{"name":"image.png","type":"image","format":"png","meta":{"width":1200,"height":630}}],"assetsDir":".webstudio/assets"}+## Duplicate asset++Commands:++- MCP tool: duplicate-asset {"assetId":"<assetId>"}+- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":"<targetFolderId>"}+- MCP tool: duplicate-asset {"assetId":"<assetId>","folderId":null}++Notes:++- Duplication is the asset equivalent of copy and paste. Updating `folderId` is the equivalent of cut and paste; use `null` for Root.++## Download asset++Commands:++- MCP tool: download-asset {"assetId":"<assetId>"}+## Find asset usageCommands:diff --git a/packages/cli/src/docs/manual-mcp.md b/packages/cli/src/docs/manual-mcp.mdindex 19527cea70..65afa96947 100644--- a/packages/cli/src/docs/manual-mcp.md+++ b/packages/cli/src/docs/manual-mcp.md@@ -274,7 +274,8 @@ terms, agents can:- Create GraphQL resources.- Create system resources.- Use built-in system resources for sitemap, current date, and assets.-- List, upload, add, update, find usage for, replace, and delete assets.+- List and inspect complete asset metadata; upload, download, update, move, duplicate, find usage for, replace, and delete assets.+- List, create, rename, move, recursively duplicate, and recursively delete nested asset folders.- Publish to staging or production.- Publish to selected domains.- List publish builds.diff --git a/packages/cli/src/project-session.test.ts b/packages/cli/src/project-session.test.tsindex 00a530ee64..d1a16f14e6 100644--- a/packages/cli/src/project-session.test.ts+++ b/packages/cli/src/project-session.test.ts@@ -327,6 +327,17 @@ test("creates preview bundle from project session snapshot", () => {},],],+ assetFolders: [+ [+ "asset-folder",+ {+ id: "asset-folder",+ projectId: "project",+ name: "Images",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ],});const bundle = createLocalProjectBundleFromSessionSnapshot(@@ -356,6 +367,9 @@ test("creates preview bundle from project session snapshot", () => {"design-system-body",]);expect(bundle.build.marketplaceProduct).toEqual(marketplaceProduct);+ expect(bundle.assetFolders).toEqual([+ expect.objectContaining({ id: "asset-folder", name: "Images" }),+ ]);});describe("cli project session transport", () => {diff --git a/packages/cli/src/project-session.ts b/packages/cli/src/project-session.tsindex 2835848633..6dad02b725 100644--- a/packages/cli/src/project-session.ts+++ b/packages/cli/src/project-session.ts@@ -544,6 +544,7 @@ export const createLocalProjectBundleFromSessionSnapshot = (page: homePage,pages: Array.from(persistedPages.pages.values()),assets: Array.from(snapshot.state.assets?.values() ?? []),+ assetFolders: Array.from(snapshot.state.assetFolders?.values() ?? []),build: {id: snapshot.buildId,projectId: snapshot.projectId,diff --git a/packages/design-system/src/components/popover.tsx b/packages/design-system/src/components/popover.tsxindex 0b6b2aabc8..5c333e5ccd 100644--- a/packages/design-system/src/components/popover.tsx+++ b/packages/design-system/src/components/popover.tsx@@ -16,6 +16,8 @@ export const Popover = Primitive.Root;export const PopoverPortal = Primitive.Portal;+export const PopoverAnchor = Primitive.Anchor;+const contentStyle = css({border: `1px solid ${theme.colors.borderMain}`,boxShadow: `${theme.shadows.menuDropShadow}, inset 0 0 0 1px ${theme.colors.borderMenuInner}`,diff --git a/packages/design-system/src/design-tokens.ts b/packages/design-system/src/design-tokens.tsindex 496115bc85..bec04ccebc 100644--- a/packages/design-system/src/design-tokens.ts+++ b/packages/design-system/src/design-tokens.ts@@ -386,6 +386,7 @@ export const color = {backgroundDestructiveNotification: "#ffe9e9",backgroundSuccessMain: "#00894a",backgroundSuccessNotification: "#e9f9ee",+ backgroundStatusAttention: "#f4c430",backgroundAlertMain: "#f5d90a",backgroundAlertNotification: "#fffbd1",backgroundInfoMain: "#0175dc",diff --git a/packages/http-client/src/index.test.ts b/packages/http-client/src/index.test.tsindex 3ede461b6a..8a5837d99e 100644--- a/packages/http-client/src/index.test.ts+++ b/packages/http-client/src/index.test.ts@@ -16,6 +16,7 @@ import {attachDesignToken,bindProps,cloneInstance,+ createAssetFolder,createBreakpoint,createPageFromTemplate,createDesignTokens,@@ -29,6 +30,7 @@ import {createVariable,deleteDesignTokenStyles,deleteCssVariables,+ deleteAssetFolder,deleteAssets,deleteBreakpoint,deleteDomain,@@ -41,6 +43,8 @@ import {deleteRedirect,deleteVariable,duplicatePage,+ duplicateAsset,+ duplicateAssetFolder,extractDesignToken,findAssetUsage,getPublishJob,@@ -61,6 +65,7 @@ import {importProjectBundle,importProjectBundleWithAssets,listAssets,+ listAssetFolders,listBreakpoints,listDesignTokens,listDomains,@@ -90,6 +95,7 @@ import {replaceStyleValues,rewriteCssVariableRefs,updateDesignTokenStyles,+ updateAssetFolder,updateDomain,updateBreakpoint,updatePage,@@ -787,6 +793,25 @@ test("wraps project api trpc calls in named functions", async () => {...params,domainId: "domain-id",});+ await listAssetFolders(params);+ await createAssetFolder({+ ...params,+ name: "Images",+ });+ await updateAssetFolder({+ ...params,+ folderId: "folder-id",+ values: { name: "Photos", parentId: null },+ });+ await deleteAssetFolder({+ ...params,+ folderId: "folder-id",+ });+ await duplicateAssetFolder({+ ...params,+ folderId: "folder-id",+ parentId: null,+ });await listAssets({...params,type: "image",@@ -806,6 +831,11 @@ test("wraps project api trpc calls in named functions", async () => {assetIdsOrPrefixes: ["asset-id"],force: true,});+ await duplicateAsset({+ ...params,+ assetId: "asset-id",+ folderId: null,+ });await getProjectPermissions(params);await listFolders({...params,@@ -973,6 +1003,14 @@ test("wraps project api trpc calls in named functions", async () => {expectBodyRequest("/trpc/api.domains.update", '"domain":"www.example.com"'),expectBodyRequest("/trpc/api.domains.delete", '"confirm":true'),expectBodyRequest("/trpc/api.domains.verify", '"domainId":"domain-id"'),+ expectRequest("/trpc/api.assetFolders.list"),+ expectBodyRequest("/trpc/api.assetFolders.create", '"name":"Images"'),+ expectBodyRequest("/trpc/api.assetFolders.update", '"parentId":null'),+ expectBodyRequest(+ "/trpc/api.assetFolders.delete",+ '"folderId":"folder-id"'+ ),+ expectBodyRequest("/trpc/api.assetFolders.duplicate", '"parentId":null'),expectRequest("/trpc/api.assets.list"),expectRequest("/trpc/api.assets.findUsage"),expectBodyRequest("/trpc/api.assets.replace", '"confirm":true'),@@ -980,6 +1018,7 @@ test("wraps project api trpc calls in named functions", async () => {"/trpc/api.assets.delete",'"assetIdsOrPrefixes":["asset-id"]'),+ expectBodyRequest("/trpc/api.assets.duplicate", '"folderId":null'),expectRequest("/trpc/api.projects.permissions"),expectRequest("/trpc/api.folders.list"),expectBodyRequest("/trpc/api.build.patch", '"baseVersion":2'),@@ -1086,6 +1125,7 @@ test("uploads assets as binary requests", async () => {type: "image",name: "image.png",filename: "image.png",+ folderId: "campaign",format: "png",size: 3,meta: { width: 10, height: 20 },@@ -1098,7 +1138,7 @@ test("uploads assets as binary requests", async () => {expect(fetch).toHaveBeenCalledOnce();const [url, init] = fetch.mock.calls[0] as [URL, RequestInit];expect(url.href).toBe(- "https://apps.webstudio.is/rest/assets/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&width=10&height=20&format=png"+ "https://apps.webstudio.is/rest/assets/image.png?projectId=090e6e14-ae50-4b2e-bd22-71733cec05bb&type=image&folderId=campaign&width=10&height=20&format=png");expect(init.method).toBe("POST");expect(init.body).toBe(file);@@ -1262,6 +1302,7 @@ test("uploads project asset descriptors with local data readers", async () => {name: "image.png",type: "image",format: "png",+ folderId: "campaign",meta: { width: 10, height: 20 },},readAssetData: async () => new Uint8Array([1, 2, 3]),@@ -1284,6 +1325,9 @@ test("uploads project asset descriptors with local data readers", async () => {).resolves.toEqual({ uploaded: [uploadedAsset] });const calls = fetch.mock.calls as unknown as Array<[URL]>;+ expect(new URL(calls[0][0].toString()).searchParams.get("folderId")).toBe(+ "campaign"+ );for (const [request] of calls) {const url = new URL(request.toString());expect(url.searchParams.has("assetId")).toBe(false);@@ -1293,6 +1337,14 @@ test("uploads project asset descriptors with local data readers", async () => {test("normalizes synced project bundles for local storage", () => {const bundle = createPublishedProjectBundleFixture({bundleVersion: "bundle-old",+ assetFolders: [+ {+ id: "folder-1",+ projectId: "project-1",+ name: "Images",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],});expect(toLocalProjectBundle(bundle)).toMatchObject({@@ -1301,6 +1353,7 @@ test("normalizes synced project bundles for local storage", () => {page: bundle.page,pages: bundle.pages,assets: bundle.assets,+ assetFolders: bundle.assetFolders,user: bundle.user,projectDomain: bundle.projectDomain,projectTitle: bundle.projectTitle,diff --git a/packages/http-client/src/index.ts b/packages/http-client/src/index.tsindex 7acddabbcf..aea1a6bff4 100644--- a/packages/http-client/src/index.ts+++ b/packages/http-client/src/index.ts@@ -334,6 +334,7 @@ type AssetUploadDescriptor = {format?: string;meta?: Record<string, unknown>;description?: string | null;+ folderId?: string;};type AssetUploadResult = { uploadedAssets?: Asset[] };@@ -368,6 +369,9 @@ const getAssetUploadUrl = ({);url.searchParams.set("projectId", projectId);url.searchParams.set("type", asset.type);+ if (asset.folderId !== undefined) {+ url.searchParams.set("folderId", asset.folderId);+ }if (asset.type === "image") {url.searchParams.set("width", String(asset.meta.width));url.searchParams.set("height", String(asset.meta.height));@@ -475,6 +479,7 @@ const toUploadAsset = ({name: descriptor.name,filename: descriptor.name,description: descriptor.description ?? null,+ folderId: descriptor.folderId,size: 0,createdAt: new Date().toISOString(),};@@ -609,6 +614,7 @@ export const toLocalProjectBundle = (project: PublishedProjectBundle) => {const normalizedProject = publishedProjectBundle.parse(project);const {assets,+ assetFolders,build,origin,page,@@ -623,6 +629,7 @@ export const toLocalProjectBundle = (project: PublishedProjectBundle) => {page,pages,assets,+ assetFolders,user,projectDomain,projectTitle,@@ -1529,6 +1536,37 @@ export const verifyDomain = projectMutationInput<AuthProjectParams & { domainId: string }>("verify-domain");+export const listAssetFolders =+ projectQueryInput<AuthProjectParams>("list-asset-folders");++export const createAssetFolder = projectMutationInput<+ AuthProjectParams & {+ name: string;+ parentId?: string;+ }+>("create-asset-folder");++export const updateAssetFolder = projectMutationInput<+ AuthProjectParams & {+ folderId: string;+ values: {+ name?: string;+ parentId?: string | null;+ };+ }+>("update-asset-folder");++export const deleteAssetFolder = projectMutationInput<+ AuthProjectParams & { folderId: string }+>("delete-asset-folder");++export const duplicateAssetFolder = projectMutationInput<+ AuthProjectParams & {+ folderId: string;+ parentId?: string | null;+ }+>("duplicate-asset-folder");+export const listAssets = projectQueryInput<AuthProjectParams &PaginatedQueryInput & {@@ -1538,6 +1576,10 @@ export const listAssets = projectQueryInput<}>("list-assets");+export const getAsset = projectQueryInput<+ AuthProjectParams & { assetId: string }+>("get-asset");+export const findAssetUsage = projectQueryInput<AuthProjectParams &PaginatedQueryInput & {@@ -1559,6 +1601,13 @@ export const deleteAssets = projectConfirmedMutationInput<}>("delete-asset");+export const duplicateAsset = projectMutationInput<+ AuthProjectParams & {+ assetId: string;+ folderId?: string | null;+ }+>("duplicate-asset");+const getUploadIdFromUrl = (uploadUrl: string | null) => {if (uploadUrl === null) {throw new Error("Project bundle upload did not return an upload URL.");diff --git a/packages/icons/generate.ts b/packages/icons/generate.tsindex a9b8ad6fbf..f3337ce608 100644--- a/packages/icons/generate.ts+++ b/packages/icons/generate.ts@@ -50,6 +50,10 @@ type GenerateOptions = {content: string;};+const componentDefaults = new Map<string, { strokeWidth?: number }>([+ ["./icons/folder.svg", { strokeWidth: 1 }],+]);+export const generateStringExport = (options: GenerateOptions) => {const { data: optimized } = optimize(options.content, {path: options.file,@@ -74,6 +78,7 @@ export const generateStringExport = (options: GenerateOptions) => {};const generateComponentExport = (options: GenerateOptions) => {+ const defaults = componentDefaults.get(options.file);const { jsx } = convertSvgToJsx({target: "react-dom",file: options.file,@@ -82,6 +87,9 @@ const generateComponentExport = (options: GenerateOptions) => {width: "{size}",height: "{size}",fill: "{fill}",+ ...(defaults?.strokeWidth === undefined+ ? {}+ : { strokeWidth: "{strokeWidth}" }),"{...props}": null,ref: "{forwardedRef}",},@@ -89,7 +97,7 @@ const generateComponentExport = (options: GenerateOptions) => {});return `export const ${options.exportName}: IconComponent = forwardRef(- ({ fill = "none", size = 16, ...props }, forwardedRef) => {+ ({ fill = "none", size = 16${defaults?.strokeWidth === undefined ? "" : `, strokeWidth = ${defaults.strokeWidth}`}, ...props }, forwardedRef) => {return (${jsx});diff --git a/packages/icons/icons/chevron-right.svg b/packages/icons/icons/chevron-right.svgindex c3cf4492d0..aaea69b5c4 100644--- a/packages/icons/icons/chevron-right.svg+++ b/packages/icons/icons/chevron-right.svg@@ -8,6 +8,7 @@<pathd="M6 12L10 8L6 4"stroke="currentColor"+ vector-effect="non-scaling-stroke"stroke-linecap="round"stroke-linejoin="round"/>diff --git a/packages/icons/icons/folder.svg b/packages/icons/icons/folder.svgindex 1ce82e4114..8908be380a 100644--- a/packages/icons/icons/folder.svg+++ b/packages/icons/icons/folder.svg@@ -6,8 +6,10 @@xmlns="http://www.w3.org/2000/svg"><path- d="M13.3333 13.3333C13.6869 13.3333 14.026 13.1929 14.2761 12.9428C14.5261 12.6928 14.6666 12.3536 14.6666 12V5.33333C14.6666 4.97971 14.5261 4.64057 14.2761 4.39052C14.026 4.14048 13.6869 4 13.3333 4H8.06659C7.84359 4.00219 7.62362 3.94841 7.42679 3.84359C7.22995 3.73877 7.06256 3.58625 6.93992 3.4L6.39992 2.6C6.27851 2.41565 6.11323 2.26432 5.91892 2.1596C5.7246 2.05488 5.50732 2.00004 5.28658 2H2.66659C2.31296 2 1.97382 2.14048 1.72378 2.39052C1.47373 2.64057 1.33325 2.97971 1.33325 3.33333V12C1.33325 12.3536 1.47373 12.6928 1.72378 12.9428C1.97382 13.1929 2.31296 13.3333 2.66659 13.3333H13.3333Z"+ d="M1.5 3.5C1.5 2.95 1.95 2.5 2.5 2.5H5.5L7 4.5H13.5C14.05 4.5 14.5 4.95 14.5 5.5V12.5C14.5 13.05 14.05 13.5 13.5 13.5H2.5C1.95 13.5 1.5 13.05 1.5 12.5V3.5Z"stroke="currentColor"+ stroke-width="1"+ vector-effect="non-scaling-stroke"stroke-linecap="round"stroke-linejoin="round"/>diff --git a/packages/icons/src/__generated__/components.tsx b/packages/icons/src/__generated__/components.tsxindex 3119bb717e..1539cb0e76 100644--- a/packages/icons/src/__generated__/components.tsx+++ b/packages/icons/src/__generated__/components.tsx@@ -1860,6 +1860,7 @@ export const ChevronRightIcon: IconComponent = forwardRef(strokeLinecap="round"strokeLinejoin="round"d="m6 12 4-4-4-4"+ vectorEffect="non-scaling-stroke"/></svg>);@@ -2681,7 +2682,7 @@ export const FacebookIcon: IconComponent = forwardRef(FacebookIcon.displayName = "FacebookIcon";export const FolderIcon: IconComponent = forwardRef(- ({ fill = "none", size = 16, ...props }, forwardedRef) => {+ ({ fill = "none", size = 16, strokeWidth = 1, ...props }, forwardedRef) => {return (<svgxmlns="http://www.w3.org/2000/svg"@@ -2689,6 +2690,7 @@ export const FolderIcon: IconComponent = forwardRef(width={size}height={size}fill={fill}+ strokeWidth={strokeWidth}{...props}ref={forwardedRef}>@@ -2696,7 +2698,8 @@ export const FolderIcon: IconComponent = forwardRef(stroke="currentColor"strokeLinecap="round"strokeLinejoin="round"- d="M13.333 13.333A1.333 1.333 0 0 0 14.667 12V5.333A1.334 1.334 0 0 0 13.333 4H8.067a1.333 1.333 0 0 1-1.127-.6l-.54-.8A1.333 1.333 0 0 0 5.287 2h-2.62a1.333 1.333 0 0 0-1.334 1.333V12a1.333 1.333 0 0 0 1.334 1.333h10.666Z"+ d="M1.5 3.5c0-.55.45-1 1-1h3l1.5 2h6.5c.55 0 1 .45 1 1v7c0 .55-.45 1-1 1h-11c-.55 0-1-.45-1-1v-9Z"+ vectorEffect="non-scaling-stroke"/></svg>);diff --git a/packages/icons/src/__generated__/svg.ts b/packages/icons/src/__generated__/svg.tsindex b585241411..f393f11482 100644--- a/packages/icons/src/__generated__/svg.ts+++ b/packages/icons/src/__generated__/svg.ts@@ -138,7 +138,7 @@ export const ChevronFilledUpIcon = `<svg xmlns="http://www.w3.org/2000/svg" fillexport const ChevronLeftIcon = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" fill="currentColor" width="100%" height="100%" style="display: block;"><g id="c1893fb9d__icon/chevron left"><path id="c1893fb9d__vector" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.3" d="m9.256 4.499-3.512 3.5 3.512 3.502"/></g></svg>`;-export const ChevronRightIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="m6 12 4-4-4-4"/></svg>`;+export const ChevronRightIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="m6 12 4-4-4-4" vector-effect="non-scaling-stroke"/></svg>`;export const ChevronUpIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12 10 8 6l-4 4"/></svg>`;@@ -202,7 +202,7 @@ export const EyedropperIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="nonexport const FacebookIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path fill="currentColor" d="M6.309 14.82v-4.655H4.866v-2.14h1.443v-.921c0-2.383 1.078-3.487 3.417-3.487.234 0 .557.024.856.06.225.023.447.061.666.114v1.94a5.032 5.032 0 0 0-.38-.022 15.632 15.632 0 0 0-.428-.005c-.413 0-.735.056-.978.18a.984.984 0 0 0-.396.363c-.15.245-.218.58-.218 1.022v.757h2.286l-.225 1.226-.167.913H8.848v4.81a7 7 0 1 0-2.54-.155Z"/></svg>`;-export const FolderIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M13.333 13.333A1.333 1.333 0 0 0 14.667 12V5.333A1.334 1.334 0 0 0 13.333 4H8.067a1.333 1.333 0 0 1-1.127-.6l-.54-.8A1.333 1.333 0 0 0 5.287 2h-2.62a1.333 1.333 0 0 0-1.334 1.333V12a1.333 1.333 0 0 0 1.334 1.333h10.666Z"/></svg>`;+export const FolderIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M1.5 3.5c0-.55.45-1 1-1h3l1.5 2h6.5c.55 0 1 .45 1 1v7c0 .55-.45 1-1 1h-11c-.55 0-1-.45-1-1v-9Z" vector-effect="non-scaling-stroke"/></svg>`;export const FooterIcon = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 16 16" width="100%" height="100%" style="display: block;"><path stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" d="M12.667 2H3.333C2.597 2 2 2.597 2 3.333v9.334C2 13.403 2.597 14 3.333 14h9.334c.736 0 1.333-.597 1.333-1.333V3.333C14 2.597 13.403 2 12.667 2ZM4 12h8"/></svg>`;diff --git a/packages/postgrest/src/__generated__/db-types.ts b/packages/postgrest/src/__generated__/db-types.tsindex 7e242e3b8f..574e5f511f 100644--- a/packages/postgrest/src/__generated__/db-types.ts+++ b/packages/postgrest/src/__generated__/db-types.ts@@ -71,6 +71,7 @@ export type Database = {Row: {description: string | null;filename: string | null;+ folderId: string | null;id: string;name: string;projectId: string;@@ -78,6 +79,7 @@ export type Database = {Insert: {description?: string | null;filename?: string | null;+ folderId?: string | null;id: string;name: string;projectId: string;@@ -85,11 +87,19 @@ export type Database = {Update: {description?: string | null;filename?: string | null;+ folderId?: string | null;id?: string;name?: string;projectId?: string;};Relationships: [+ {+ foreignKeyName: "Asset_folderId_projectId_fkey";+ columns: ["folderId", "projectId"];+ isOneToOne: false;+ referencedRelation: "AssetFolder";+ referencedColumns: ["id", "projectId"];+ },{foreignKeyName: "Asset_name_fkey";columns: ["name"];@@ -99,6 +109,52 @@ export type Database = {},];};+ AssetFolder: {+ Row: {+ createdAt: string;+ id: string;+ name: string;+ parentId: string | null;+ projectId: string;+ };+ Insert: {+ createdAt?: string;+ id?: string;+ name: string;+ parentId?: string | null;+ projectId: string;+ };+ Update: {+ createdAt?: string;+ id?: string;+ name?: string;+ parentId?: string | null;+ projectId?: string;+ };+ Relationships: [+ {+ foreignKeyName: "AssetFolder_parentId_projectId_fkey";+ columns: ["parentId", "projectId"];+ isOneToOne: false;+ referencedRelation: "AssetFolder";+ referencedColumns: ["id", "projectId"];+ },+ {+ foreignKeyName: "AssetFolder_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: false;+ referencedRelation: "DashboardProject";+ referencedColumns: ["id"];+ },+ {+ foreignKeyName: "AssetFolder_projectId_fkey";+ columns: ["projectId"];+ isOneToOne: false;+ referencedRelation: "Project";+ referencedColumns: ["id"];+ },+ ];+ };AuthorizationToken: {Row: {canClone: boolean;diff --git a/packages/prisma-client/prisma/migrations/20260716000000_asset_folders/migration.sql b/packages/prisma-client/prisma/migrations/20260716000000_asset_folders/migration.sqlnew file mode 100644index 0000000000..8a722671d9--- /dev/null+++ b/packages/prisma-client/prisma/migrations/20260716000000_asset_folders/migration.sql@@ -0,0 +1,116 @@+CREATE TABLE "AssetFolder" (+ "id" TEXT NOT NULL DEFAULT gen_random_uuid(),+ "projectId" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "parentId" TEXT,+ "createdAt" TIMESTAMPTZ(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "AssetFolder_pkey" PRIMARY KEY ("id", "projectId"),+ CONSTRAINT "AssetFolder_name_not_blank" CHECK (BTRIM("name") <> ''),+ CONSTRAINT "AssetFolder_projectId_fkey"+ FOREIGN KEY ("projectId") REFERENCES "Project"("id")+ ON DELETE CASCADE ON UPDATE CASCADE,+ CONSTRAINT "AssetFolder_parentId_projectId_fkey"+ FOREIGN KEY ("parentId", "projectId") REFERENCES "AssetFolder"("id", "projectId")+ ON DELETE NO ACTION ON UPDATE CASCADE+);++CREATE INDEX "AssetFolder_projectId_parentId_idx"+ ON "AssetFolder"("projectId", "parentId");++CREATE UNIQUE INDEX "AssetFolder_unique_sibling_name"+ ON "AssetFolder"(+ "projectId",+ COALESCE("parentId", ''),+ LOWER(BTRIM("name"))+ );++ALTER TABLE "Asset" ADD COLUMN "folderId" TEXT;++ALTER TABLE "Asset"+ ADD CONSTRAINT "Asset_folderId_projectId_fkey"+ FOREIGN KEY ("folderId", "projectId") REFERENCES "AssetFolder"("id", "projectId")+ ON DELETE NO ACTION ON UPDATE CASCADE;++-- Keep the database-level project clone path aligned with asset folders.+CREATE OR REPLACE FUNCTION clone_project(+ project_id text,+ user_id text,+ title text,+ domain text+) RETURNS "Project" AS $$+DECLARE+ old_project "Project";+ new_project "Project";+BEGIN+ SELECT * FROM "Project" WHERE id = project_id INTO old_project;++ INSERT INTO "Project" (id, "userId", title, domain)+ VALUES (gen_random_uuid(), user_id, title, domain)+ RETURNING * INTO new_project;++ INSERT INTO "AssetFolder" (id, "projectId", name, "parentId", "createdAt")+ SELECT id, new_project.id, name, "parentId", "createdAt"+ FROM "AssetFolder"+ WHERE "projectId" = old_project.id;++ INSERT INTO "Asset" (+ id,+ name,+ "projectId",+ filename,+ description,+ "folderId"+ )+ SELECT+ asset.id,+ asset.name,+ new_project.id,+ asset.filename,+ asset.description,+ asset."folderId"+ FROM "Asset" AS asset, "File" AS file+ WHERE+ asset.name = file.name AND+ file.status = 'UPLOADED' AND+ asset."projectId" = old_project.id;++ UPDATE "Project"+ SET "previewImageAssetId" = old_project."previewImageAssetId"+ WHERE id = new_project.id;++ INSERT INTO "Build" (+ id,+ "projectId",+ pages,+ "styleSources",+ "styleSourceSelections",+ styles,+ breakpoints,+ props,+ instances,+ "dataSources",+ resources,+ "marketplaceProduct",+ "projectSettings"+ )+ SELECT+ gen_random_uuid(),+ new_project.id,+ pages,+ "styleSources",+ "styleSourceSelections",+ styles,+ breakpoints,+ props,+ instances,+ "dataSources",+ resources,+ "marketplaceProduct",+ "projectSettings"+ FROM "Build"+ WHERE "projectId" = old_project.id AND deployment IS NULL;++ RETURN new_project;+END;+$$ LANGUAGE plpgsql;diff --git a/packages/prisma-client/prisma/schema.prisma b/packages/prisma-client/prisma/schema.prismaindex cc7b9579c6..f18ee0f8d0 100644--- a/packages/prisma-client/prisma/schema.prisma+++ b/packages/prisma-client/prisma/schema.prisma@@ -45,12 +45,29 @@ model Asset {name Stringfilename String?description String?+ folderId String?+ folder AssetFolder? @relation(fields: [folderId, projectId], references: [id, projectId], onDelete: NoAction)Project Project[]DashboardProject DashboardProject[]@@id([id, projectId])}+model AssetFolder {+ id String @default(uuid())+ projectId String+ project Project @relation(fields: [projectId], references: [id], onDelete: Cascade)+ name String+ parentId String?+ parent AssetFolder? @relation("AssetFolderChildren", fields: [parentId, projectId], references: [id, projectId], onDelete: NoAction)+ children AssetFolder[] @relation("AssetFolderChildren")+ assets Asset[]+ createdAt DateTime @default(now()) @db.Timestamptz(3)++ @@id([id, projectId])+ @@index([projectId, parentId])+}+model User {id String @id @default(uuid())email String? @unique@@ -149,6 +166,7 @@ model Project {build Build[]isDeleted Boolean @default(false)files File[]+ assetFolders AssetFolder[]projectDomain ProjectDomain[]authorizationToken AuthorizationToken[]previewImageAsset Asset? @relation(fields: [previewImageAssetId, id], references: [id, projectId])diff --git a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.tsindex a95a0b001a..719eecc174 100644--- a/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts+++ b/packages/project-build/src/contracts/__generated__/runtime-operation-contracts.ts@@ -3665,6 +3665,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -3798,6 +3802,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -3856,6 +3864,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -6787,6 +6799,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -6920,6 +6936,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -6978,6 +6998,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -9920,6 +9944,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -10053,6 +10081,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -10111,6 +10143,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -13042,6 +13078,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -13175,6 +13215,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -13233,6 +13277,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -18859,6 +18907,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -19000,6 +19052,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -19058,6 +19114,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -22184,6 +22244,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -22325,6 +22389,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -22383,6 +22451,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -36577,6 +36649,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -36710,6 +36786,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -36768,6 +36848,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -39774,6 +39858,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -39907,6 +39995,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -39965,6 +40057,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -46087,6 +46183,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -46215,6 +46315,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -46273,6 +46377,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -51898,6 +52006,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -52026,6 +52138,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -52084,6 +52200,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -65853,6 +65973,216 @@ export const runtimeOperationContractData = [retryOnConflict: false,requiresConfirm: true,},+ {+ id: "assetFolders.list",+ command: "list-asset-folders",+ client: "listAssetFolders",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {},+ required: [],+ additionalProperties: true,+ },+ outputSchema: {+ type: "object",+ properties: {+ folders: {+ type: "array",+ items: {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ projectId: {+ type: "string",+ },+ name: {+ type: "string",+ },+ parentId: {+ type: "string",+ },+ createdAt: {+ type: "string",+ },+ },+ required: ["id", "projectId", "name", "createdAt"],+ additionalProperties: {},+ },+ },+ },+ required: ["folders"],+ additionalProperties: {},+ },+ readNamespaces: ["assetFolders"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "assetFolders.create",+ command: "create-asset-folder",+ client: "createAssetFolder",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ name: {+ type: "string",+ minLength: 1,+ },+ parentId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["name"],+ },+ outputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ },+ },+ required: ["folderId"],+ additionalProperties: {},+ },+ readNamespaces: ["assetFolders"],+ writeNamespaces: ["assetFolders"],+ invalidatesNamespaces: ["assetFolders"],+ retryOnConflict: true,+ requiresAssets: true,+ },+ {+ id: "assetFolders.update",+ command: "update-asset-folder",+ client: "updateAssetFolder",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ minLength: 1,+ },+ values: {+ type: "object",+ properties: {+ name: {+ type: "string",+ minLength: 1,+ },+ parentId: {+ anyOf: [+ {+ type: "string",+ minLength: 1,+ },+ {+ type: "null",+ },+ ],+ },+ },+ required: [],+ },+ },+ required: ["folderId", "values"],+ },+ outputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ },+ },+ required: ["folderId"],+ additionalProperties: {},+ },+ readNamespaces: ["assetFolders"],+ writeNamespaces: ["assetFolders"],+ invalidatesNamespaces: ["assetFolders"],+ retryOnConflict: false,+ requiresAssets: true,+ },+ {+ id: "assetFolders.delete",+ command: "delete-asset-folder",+ client: "deleteAssetFolder",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["folderId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ },+ },+ required: ["folderId"],+ additionalProperties: {},+ },+ readNamespaces: ["assetFolders", "assets"],+ writeNamespaces: ["assetFolders", "assets"],+ invalidatesNamespaces: ["assetFolders", "assets"],+ retryOnConflict: false,+ requiresAssets: true,+ requiresConfirm: true,+ },+ {+ id: "assetFolders.duplicate",+ command: "duplicate-asset-folder",+ client: "duplicateAssetFolder",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ minLength: 1,+ },+ parentId: {+ anyOf: [+ {+ type: "string",+ minLength: 1,+ },+ {+ type: "null",+ },+ ],+ },+ },+ required: ["folderId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ folderId: {+ type: "string",+ },+ },+ required: ["folderId"],+ additionalProperties: {},+ },+ readNamespaces: ["assetFolders", "assets"],+ writeNamespaces: ["assetFolders", "assets"],+ invalidatesNamespaces: ["assetFolders", "assets"],+ retryOnConflict: true,+ requiresAssets: true,+ },{id: "assets.list",command: "list-assets",@@ -65905,6 +66235,9 @@ export const runtimeOperationContractData = [filename: {type: "string",},+ folderId: {+ type: "string",+ },type: {type: "string",enum: ["font", "image", "file"],@@ -65945,6 +66278,9 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ },type: {type: "string",enum: ["font", "image", "file"],@@ -66037,6 +66373,94 @@ export const runtimeOperationContractData = [retryOnConflict: false,requiresAssets: true,},+ {+ id: "assets.get",+ command: "get-asset",+ client: "getAsset",+ kind: "read",+ inputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ minLength: 1,+ },+ },+ required: ["assetId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ asset: {+ type: "object",+ properties: {+ id: {+ type: "string",+ },+ projectId: {+ type: "string",+ },+ name: {+ type: "string",+ },+ filename: {+ type: "string",+ },+ description: {+ anyOf: [+ {+ type: "string",+ },+ {+ type: "null",+ },+ ],+ },+ folderId: {+ type: "string",+ },+ type: {+ type: "string",+ enum: ["font", "image", "file"],+ },+ size: {+ type: "number",+ },+ format: {+ type: "string",+ },+ createdAt: {+ type: "string",+ },+ meta: {+ type: "object",+ properties: {},+ additionalProperties: {},+ required: [],+ },+ },+ required: [+ "id",+ "projectId",+ "name",+ "type",+ "size",+ "format",+ "createdAt",+ "meta",+ ],+ additionalProperties: {},+ },+ },+ required: ["asset"],+ additionalProperties: {},+ },+ readNamespaces: ["assets"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ requiresAssets: true,+ },{id: "fonts.list",command: "list-fonts",@@ -66351,6 +66775,17 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ anyOf: [+ {+ type: "string",+ minLength: 1,+ },+ {+ type: "null",+ },+ ],+ },},required: [],},@@ -66367,7 +66802,7 @@ export const runtimeOperationContractData = [required: ["assetId"],additionalProperties: {},},- readNamespaces: ["assets"],+ readNamespaces: ["assets", "assetFolders"],writeNamespaces: ["assets"],invalidatesNamespaces: ["assets"],retryOnConflict: false,@@ -66494,6 +66929,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -66622,6 +67061,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -66680,6 +67123,10 @@ export const runtimeOperationContractData = [},],},+ folderId: {+ type: "string",+ minLength: 1,+ },createdAt: {type: "string",},@@ -66722,7 +67169,49 @@ export const runtimeOperationContractData = [required: ["assetId"],additionalProperties: {},},- readNamespaces: ["assets"],+ readNamespaces: ["assets", "assetFolders"],+ writeNamespaces: ["assets"],+ invalidatesNamespaces: ["assets"],+ retryOnConflict: true,+ requiresAssets: true,+ },+ {+ id: "assets.duplicate",+ command: "duplicate-asset",+ client: "duplicateAsset",+ kind: "mutation",+ inputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ minLength: 1,+ },+ folderId: {+ anyOf: [+ {+ type: "string",+ minLength: 1,+ },+ {+ type: "null",+ },+ ],+ },+ },+ required: ["assetId"],+ },+ outputSchema: {+ type: "object",+ properties: {+ assetId: {+ type: "string",+ },+ },+ required: ["assetId"],+ additionalProperties: {},+ },+ readNamespaces: ["assets", "assetFolders"],writeNamespaces: ["assets"],invalidatesNamespaces: ["assets"],retryOnConflict: true,diff --git a/packages/project-build/src/contracts/namespaces.test.ts b/packages/project-build/src/contracts/namespaces.test.tsindex 869601b2de..194ce0bc65 100644--- a/packages/project-build/src/contracts/namespaces.test.ts+++ b/packages/project-build/src/contracts/namespaces.test.ts@@ -1,5 +1,9 @@import { expect, test } from "vitest";-import { builderNamespaces, webstudioDataNamespaces } from "./namespaces";+import {+ builderNamespaces,+ pageCopyNamespaces,+ webstudioDataNamespaces,+} from "./namespaces";test("defines the shared builder namespace catalog", () => {expect(webstudioDataNamespaces).toEqual([@@ -12,6 +16,7 @@ test("defines the shared builder namespace catalog", () => {"dataSources","resources","assets",+ "assetFolders","breakpoints",]);expect(builderNamespaces).toEqual([@@ -24,8 +29,17 @@ test("defines the shared builder namespace catalog", () => {"dataSources","resources","assets",+ "assetFolders","breakpoints","projectSettings","marketplaceProduct",]);+ expect(pageCopyNamespaces).not.toContain("assetFolders");+ expect(new Set(pageCopyNamespaces)).toEqual(+ new Set(+ webstudioDataNamespaces.filter(+ (namespace) => namespace !== "assetFolders"+ )+ )+ );});diff --git a/packages/project-build/src/contracts/namespaces.ts b/packages/project-build/src/contracts/namespaces.tsindex b7df580fea..03fe9b6ca8 100644--- a/packages/project-build/src/contracts/namespaces.ts+++ b/packages/project-build/src/contracts/namespaces.ts@@ -18,11 +18,27 @@ export const webstudioDataNamespaces = ["dataSources","resources","assets",+ "assetFolders","breakpoints",] as const;export type WebstudioDataNamespace = (typeof webstudioDataNamespaces)[number];+// Page-copy operations transfer assets but not the asset-manager folder+// hierarchy. Assets copied across projects are normalized to the root folder.+export const pageCopyNamespaces = [+ "pages",+ "assets",+ "dataSources",+ "resources",+ "instances",+ "props",+ "breakpoints",+ "styles",+ "styleSources",+ "styleSourceSelections",+] as const satisfies readonly WebstudioDataNamespace[];+export const builderNamespaces = [...webstudioDataNamespaces,"projectSettings",diff --git a/packages/project-build/src/contracts/patch.test.ts b/packages/project-build/src/contracts/patch.test.tsindex b4d2d55df2..6c44c2a1ab 100644--- a/packages/project-build/src/contracts/patch.test.ts+++ b/packages/project-build/src/contracts/patch.test.ts@@ -4,6 +4,9 @@ import {builderPatchSchema,builderPatchTransactionSchema,compactBuilderPatchPayload,+ appendOptionalPropertyPatch,+ type BuilderPatch,+ createOptionalPropertyPatch,hasGeneratedRecordWritePatch,restorePointPatchTransactionSchema,} from "./patch";@@ -71,6 +74,58 @@ describe("builder patch contracts", () => {).toBe(false);});+ test("creates patches for optional properties", () => {+ expect(+ createOptionalPropertyPatch({+ path: ["record", "field"],+ previous: undefined,+ next: "value",+ })+ ).toEqual({+ op: "add",+ path: ["record", "field"],+ value: "value",+ });+ expect(+ createOptionalPropertyPatch({+ path: ["record", "field"],+ previous: "value",+ next: "next",+ })+ ).toEqual({+ op: "replace",+ path: ["record", "field"],+ value: "next",+ });+ expect(+ createOptionalPropertyPatch({+ path: ["record", "field"],+ previous: "value",+ next: undefined,+ })+ ).toEqual({ op: "remove", path: ["record", "field"] });+ expect(+ createOptionalPropertyPatch({+ path: ["record", "field"],+ previous: "value",+ next: "value",+ })+ ).toBeUndefined();++ const patches: BuilderPatch[] = [];+ appendOptionalPropertyPatch(patches, {+ path: ["record", "field"],+ previous: undefined,+ next: "value",+ });+ appendOptionalPropertyPatch(patches, {+ path: ["record", "field"],+ previous: "value",+ next: "value",+ });+ expect(patches).toHaveLength(1);+ });+test("requires values for add and replace patches", () => {expect(builderPatchSchema.safeParse({ op: "add", path: ["prop-subtitle"] })diff --git a/packages/project-build/src/contracts/patch.ts b/packages/project-build/src/contracts/patch.tsindex f8c7044c73..084164f7d0 100644--- a/packages/project-build/src/contracts/patch.ts+++ b/packages/project-build/src/contracts/patch.ts@@ -14,6 +14,40 @@ export type BuilderPatch =| { op: "replace"; path: BuilderPatchPath; value: unknown }| { op: "remove"; path: BuilderPatchPath };+type OptionalPropertyPatchInput = {+ path: BuilderPatchPath;+ previous: unknown;+ next: unknown;+};++export const createOptionalPropertyPatch = ({+ path,+ previous,+ next,+}: OptionalPropertyPatchInput): BuilderPatch | undefined => {+ if (Object.is(previous, next)) {+ return;+ }+ if (next === undefined) {+ return { op: "remove", path };+ }+ return {+ op: previous === undefined ? "add" : "replace",+ path,+ value: next,+ };+};++export const appendOptionalPropertyPatch = (+ patches: BuilderPatch[],+ input: OptionalPropertyPatchInput+) => {+ const patch = createOptionalPropertyPatch(input);+ if (patch !== undefined) {+ patches.push(patch);+ }+};+const requireBuilderPatchValue = (patch: { value?: unknown },context: z.RefinementCtxdiff --git a/packages/project-build/src/mcp.test.ts b/packages/project-build/src/mcp.test.tsindex 53b0805019..1c3143e6f9 100644--- a/packages/project-build/src/mcp.test.ts+++ b/packages/project-build/src/mcp.test.ts@@ -772,7 +772,57 @@ describe("project session mcp adapter", () => {"reset-session",]);expect(toolNames).toContain("insert-fragment");+ const assetOperationTools = listProjectSessionMcpTools(+ runtimeOperationContracts+ .filter(+ ({ id }) =>+ id.startsWith("assetFolders.") ||+ id === "assets.get" ||+ id === "assets.duplicate"+ )+ .map((contract) =>+ publicOperation({+ command: contract.command,+ id: contract.id,+ method: contract.kind === "read" ? "query" : "mutation",+ permit: contract.kind === "read" ? "view" : "build",+ description:+ contract.id === "assetFolders.duplicate"+ ? "Recursively duplicate an asset folder"+ : contract.command,+ inputSchema: contract.inputSchema,+ readNamespaces: contract.readNamespaces,+ writeNamespaces: contract.writeNamespaces,+ invalidatesNamespaces: contract.invalidatesNamespaces,+ retryOnConflict: contract.retryOnConflict,+ })+ )+ );+ const assetOperationToolNames = assetOperationTools.map(({ name }) => name);+ expect(assetOperationToolNames).toEqual(+ expect.arrayContaining([+ "list-asset-folders",+ "create-asset-folder",+ "update-asset-folder",+ "duplicate-asset-folder",+ "delete-asset-folder",+ "get-asset",+ "duplicate-asset",+ ])+ );expect(toolNames).not.toContain("copy-page");+ expect(+ assetOperationTools.find(({ name }) => name === "duplicate-asset-folder")+ ).toMatchObject({+ description: expect.stringContaining("Recursively duplicate"),+ inputSchema: expect.objectContaining({ required: ["folderId"] }),+ });+ expect(+ JSON.stringify(+ assetOperationTools.find(({ name }) => name === "update-asset-folder")+ ?.inputSchema+ )+ ).toContain('"type":"null"');for (const operation of publicMcpOperations) {if (hiddenMcpOperationCommands.has(operation.command) ||@@ -810,11 +860,13 @@ describe("project session mcp adapter", () => {});const completeTools = listProjectSessionMcpTools(publicMcpOperations, {includeImport: true,+ includeDownloadAsset: true,includeScreenshot: true,includeScreenshotDiff: true,includeInstallOcr: true,includePreview: true,});+ expect(completeTools.map(({ name }) => name)).toContain("download-asset");for (const tool of completeTools) {expect(tool.inputSchema.additionalProperties,@@ -1110,6 +1162,32 @@ describe("project session mcp adapter", () => {);});+ test("downloads assets through the MCP host", async () => {+ const downloadAsset = vi.fn(async ({ assetId }: { assetId: string }) => ({+ assetId,+ path: `/workspace/.webstudio/assets/${assetId}.png`,+ }));+ const adapter = createProjectSessionMcpCore({+ operations: publicMcpOperations,+ createProjectSession: createSessionFactory(),+ executeOperation: createExecuteOperation(),+ downloadAsset,+ });++ const result = await adapter.callTool({+ name: "download-asset",+ input: { assetId: "hero" },+ });++ expect(downloadAsset).toHaveBeenCalledWith({ assetId: "hero" });+ expect(result.structuredContent).toMatchObject({+ data: {+ assetId: "hero",+ path: "/workspace/.webstudio/assets/hero.png",+ },+ });+ });+test("exposes page expression input descriptions to MCP clients", async () => {const createPageContract = runtimeOperationContracts.find((contract) => contract.id === "pages.create"diff --git a/packages/project-build/src/mcp.ts b/packages/project-build/src/mcp.tsindex 13e4f6c598..9dc7872a48 100644--- a/packages/project-build/src/mcp.ts+++ b/packages/project-build/src/mcp.ts@@ -315,6 +315,20 @@ type ImportProject = (input: ProjectSessionImportInput) => Promise<ProjectSessionImportResult>;+export type ProjectSessionDownloadAssetInput = {+ assetId: string;+ assetsDir?: string;+};++export type ProjectSessionDownloadAssetResult = {+ assetId: string;+ path: string;+};++type DownloadAsset = (+ input: ProjectSessionDownloadAssetInput+) => Promise<ProjectSessionDownloadAssetResult>;+export type ProjectSessionMcpGuidance = {visualVerificationRule: string;getVisionVerificationLoop: (options: {@@ -1437,6 +1451,24 @@ const importInputSchema = {required: ["to"],} as const satisfies ProjectSessionMcpInputSchema;+const downloadAssetInputSchema = {+ ...emptyInputSchema,+ description:+ "Download one project asset to the local filesystem and return its absolute path.",+ properties: {+ assetId: {+ type: "string",+ description: "Existing asset id from list-assets.",+ },+ assetsDir: {+ type: "string",+ description:+ "Optional destination directory. Defaults to .webstudio/assets.",+ },+ },+ required: ["assetId"],+} as const satisfies ProjectSessionMcpInputSchema;+export type ProjectSessionMcpTool = {name: string;description: string;@@ -1527,6 +1559,52 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {to: "https://p-destination-project-id.wstd.dev/?authToken=destination-token",},],+ "download-asset": [{ assetId: "asset-id" }],+ "upload-asset": [+ {+ asset: {+ name: "hero.png",+ type: "image",+ format: "png",+ folderId: "folder-id",+ meta: { width: 1200, height: 630 },+ },+ assetsDir: ".webstudio/assets",+ },+ ],+ "upload-assets": [+ {+ assets: [+ {+ name: "hero.png",+ type: "image",+ format: "png",+ folderId: "folder-id",+ meta: { width: 1200, height: 630 },+ },+ ],+ assetsDir: ".webstudio/assets",+ },+ ],+ "list-asset-folders": [{}],+ "create-asset-folder": [+ { name: "Marketing" },+ { name: "Photos", parentId: "marketing-folder-id" },+ ],+ "update-asset-folder": [+ { folderId: "folder-id", values: { name: "Brand" } },+ { folderId: "folder-id", values: { parentId: null } },+ ],+ "duplicate-asset-folder": [+ { folderId: "folder-id" },+ { folderId: "folder-id", parentId: "target-folder-id" },+ ],+ "delete-asset-folder": [{ folderId: "folder-id" }],+ "get-asset": [{ assetId: "asset-id" }],+ "duplicate-asset": [+ { assetId: "asset-id" },+ { assetId: "asset-id", folderId: "target-folder-id" },+ ],"preview.start": [{ host: "127.0.0.1", port: 5173, source: "session" }],"preview.status": [{}],"preview.stop": [{}],@@ -1770,7 +1848,15 @@ export const mcpArgumentExamples: Record<string, readonly unknown[]> = {assetId: "asset-id",values: { description: "Team collaborating around a whiteboard" },},+ {+ assetId: "asset-id",+ values: { filename: "hero", folderId: "folder-id" },+ },+ { assetId: "asset-id", values: { folderId: null } },],+ "list-assets": [{}, { verbose: true }],+ "replace-asset": [{ fromAssetId: "old-asset-id", toAssetId: "new-asset-id" }],+ "delete-asset": [{ assetIdsOrPrefixes: ["asset-id"] }],"set-image-descriptions": [{updates: [@@ -2546,6 +2632,35 @@ const importTool = createProjectSessionMcpTool({},});+const downloadAssetTool = createProjectSessionMcpTool({+ name: "download-asset",+ description:+ "Download one project asset into .webstudio/assets or a specified directory and return its local path.",+ inputSchema: downloadAssetInputSchema,+ outputSchema: getMcpOutputSchema({+ type: "object",+ properties: {+ assetId: { type: "string" },+ path: { type: "string" },+ },+ required: ["assetId", "path"],+ additionalProperties: false,+ }),+ mcpExamples: getMcpExamples("download-asset"),+ annotations: {+ command: "download-asset",+ operationId: "assets.download",+ method: "session",+ permit: "view",+ localCapable: false,+ serverOnly: true,+ readNamespaces: ["assets"],+ writeNamespaces: [],+ invalidatesNamespaces: [],+ retryOnConflict: false,+ },+});+const previewTools: readonly ProjectSessionMcpTool[] = [createProjectSessionMcpTool({name: "preview.start",@@ -2695,6 +2810,7 @@ export const listProjectSessionMcpTools = (operations: readonly PublicMcpOperation[],options: {includeImport?: boolean;+ includeDownloadAsset?: boolean;includeScreenshot?: boolean;includeScreenshotDiff?: boolean;includeInstallOcr?: boolean;@@ -2749,6 +2865,7 @@ export const listProjectSessionMcpTools = (})),...(options.includeRestorePoints ? restorePointTools : []),...(options.includeImport ? [importTool] : []),+ ...(options.includeDownloadAsset ? [downloadAssetTool] : []),...(options.includeScreenshot ? [screenshotTool] : []),...(options.includeScreenshotDiff ? [screenshotDiffTool] : []),...(options.includeInstallOcr ? [installOcrTool] : []),@@ -2927,13 +3044,21 @@ const capabilityAreas = [},{area: "assets",- goal: "Manage uploaded and system fonts, plus upload, replace, delete, list, and find usage of assets.",+ goal: "Manage asset folders and uploaded assets, including listing, creating, renaming, moving, duplicating, downloading, uploading, replacing, and deleting.",tools: [+ "list-asset-folders",+ "create-asset-folder",+ "update-asset-folder",+ "duplicate-asset-folder",+ "delete-asset-folder","list-assets",+ "get-asset","list-fonts","upload-asset","upload-assets",+ "download-asset","update-asset",+ "duplicate-asset","set-image-descriptions","find-asset-usage","replace-asset",@@ -5900,11 +6025,30 @@ const getImportInput = (input: unknown): ProjectSessionImportInput => {};};+const getDownloadAssetInput = (+ input: unknown+): ProjectSessionDownloadAssetInput => {+ if (isRecord(input) === false) {+ throw new Error("download-asset input must be an object.");+ }+ if (typeof input.assetId !== "string" || input.assetId.length === 0) {+ throw new Error("download-asset requires assetId.");+ }+ return {+ assetId: input.assetId,+ assetsDir:+ typeof input.assetsDir === "string" && input.assetsDir.length > 0+ ? input.assetsDir+ : undefined,+ };+};+type ProjectSessionMcpCoreOptions<Command extends string> = {operations: readonly (PublicMcpOperation & { command: Command })[];createProjectSession: CreateProjectSession;executeOperation: ExecuteMcpOperation<Command>;importProject?: ImportProject;+ downloadAsset?: DownloadAsset;captureScreenshot?: CaptureScreenshot;capturePageScreenshots?: CapturePageScreenshots;diffScreenshots?: DiffScreenshots;@@ -5937,6 +6081,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({createProjectSession,executeOperation,importProject,+ downloadAsset,captureScreenshot,capturePageScreenshots,diffScreenshots,@@ -5964,6 +6109,7 @@ export const createProjectSessionMcpCore = <Command extends string = string>({const listTools = () =>listProjectSessionMcpTools(operations, {includeImport: importProject !== undefined,+ includeDownloadAsset: downloadAsset !== undefined,includeScreenshot: captureScreenshot !== undefined,includeScreenshotDiff: diffScreenshots !== undefined,includeInstallOcr: installOcr !== undefined,@@ -6292,6 +6438,9 @@ export const createProjectSessionMcpCore = <Command extends string = string>({if (name === "import" && importProject !== undefined) {return toMetaResult(await importProject(getImportInput(input)));}+ if (name === "download-asset" && downloadAsset !== undefined) {+ return toMetaResult(await downloadAsset(getDownloadAssetInput(input)));+ }if (name === "screenshot" && captureScreenshot !== undefined) {return toMetaResult(await captureScreenshot(getScreenshotInput(input), {diff --git a/packages/project-build/src/runtime.ts b/packages/project-build/src/runtime.tsindex 1c209efebe..d1861055a7 100644--- a/packages/project-build/src/runtime.ts+++ b/packages/project-build/src/runtime.ts@@ -2,6 +2,7 @@ export * from "./build-integrity";export * from "./shared/graph-utils";export * from "./runtime/assets";export * from "./runtime/binding-verification";+export * from "./runtime/asset-folders";export * from "./runtime/auth";export * from "./runtime/block";export * from "./runtime/breakpoints";diff --git a/packages/project-build/src/runtime/asset-folders.test.ts b/packages/project-build/src/runtime/asset-folders.test.tsnew file mode 100644index 0000000000..9977f5aaec--- /dev/null+++ b/packages/project-build/src/runtime/asset-folders.test.ts@@ -0,0 +1,216 @@+import { describe, expect, test } from "vitest";+import {+ createAssetFolderHierarchy,+ type Asset,+ type AssetFolder,+ type AssetFolders,+} from "@webstudio-is/sdk";+import {+ createAssetFolder,+ deleteAssetFolder,+ duplicateAssetFolder,+ updateAssetFolder,+} from "./asset-folders";++const folder = (id: string, parentId?: string, name = id): AssetFolder => ({+ id,+ projectId: "project",+ name,+ parentId,+ createdAt: "2026-01-01T00:00:00.000Z",+});++const folders = (...values: AssetFolder[]): AssetFolders =>+ new Map(values.map((value) => [value.id, value]));++const asset = (id: string, folderId?: string): Asset => ({+ id,+ projectId: "project",+ name: `${id}.pdf`,+ type: "file",+ size: 1,+ format: "pdf",+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ folderId,+ meta: {},+});++describe("asset folders", () => {+ test("creates a nested folder with a trimmed name", () => {+ const result = createAssetFolder(+ { assetFolders: folders(folder("parent")) },+ { name: " Child ", parentId: "parent" },+ { projectId: "project", createId: () => "child" }+ );++ expect(result.payload).toEqual([+ {+ namespace: "assetFolders",+ patches: [+ {+ op: "add",+ path: ["child"],+ value: expect.objectContaining({+ id: "child",+ name: "Child",+ parentId: "parent",+ projectId: "project",+ }),+ },+ ],+ },+ ]);+ });++ test("rejects duplicate sibling names case-insensitively", () => {+ expect(() =>+ createAssetFolder(+ { assetFolders: folders(folder("existing", undefined, "Media")) },+ { name: "media" },+ { projectId: "project", createId: () => "new" }+ )+ ).toThrow('A folder named "media" already exists');+ });++ test("rejects moving a folder into a descendant", () => {+ expect(() =>+ updateAssetFolder(+ {+ assetFolders: folders(+ folder("parent"),+ folder("child", "parent"),+ folder("grandchild", "child")+ ),+ },+ { folderId: "parent", values: { parentId: "grandchild" } }+ )+ ).toThrow("one of its descendants");+ });++ test("deleting a folder recursively deletes its folders and assets", () => {+ const result = deleteAssetFolder(+ {+ assetFolders: folders(+ folder("grandparent"),+ folder("deleted", "grandparent"),+ folder("child", "deleted"),+ folder("grandchild", "child")+ ),+ assets: new Map([+ ["direct", asset("direct", "deleted")],+ ["nested", asset("nested", "child")],+ ["preserved", asset("preserved", "grandparent")],+ ]),+ },+ { folderId: "deleted" }+ );++ expect(result.payload).toEqual([+ {+ namespace: "assetFolders",+ patches: [+ { op: "remove", path: ["child"] },+ { op: "remove", path: ["grandchild"] },+ { op: "remove", path: ["deleted"] },+ ],+ },+ {+ namespace: "assets",+ patches: [+ { op: "remove", path: ["direct"] },+ { op: "remove", path: ["nested"] },+ ],+ },+ ]);+ });++ test("duplicates a folder subtree and its assets", () => {+ const ids = ["copy", "child-copy", "asset-copy"];+ const result = duplicateAssetFolder(+ {+ assetFolders: folders(+ folder("source", undefined, "Media"),+ folder("existing-copy", undefined, "Media copy"),+ folder("child", "source", "Photos")+ ),+ assets: new Map([["asset", asset("asset", "child")]]),+ },+ { folderId: "source", parentId: null },+ { projectId: "project", createId: () => ids.shift()! }+ );++ expect(result.result).toEqual({ folderId: "copy" });+ expect(result.payload).toEqual([+ {+ namespace: "assetFolders",+ patches: [+ {+ op: "add",+ path: ["copy"],+ value: expect.objectContaining({+ id: "copy",+ name: "Media copy 2",+ parentId: undefined,+ }),+ },+ {+ op: "add",+ path: ["child-copy"],+ value: expect.objectContaining({+ id: "child-copy",+ name: "Photos",+ parentId: "copy",+ }),+ },+ ],+ },+ {+ namespace: "assets",+ patches: [+ {+ op: "add",+ path: ["asset-copy"],+ value: expect.objectContaining({+ id: "asset-copy",+ filename: "asset copy",+ folderId: "child-copy",+ }),+ },+ ],+ },+ ]);+ });++ test("moves a folder to the root without changing its name", () => {+ const result = updateAssetFolder(+ {+ assetFolders: folders(+ folder("parent"),+ folder("child", "parent", "Child")+ ),+ },+ { folderId: "child", values: { parentId: null } }+ );++ expect(result.payload).toEqual([+ {+ namespace: "assetFolders",+ patches: [{ op: "remove", path: ["child", "parentId"] }],+ },+ ]);+ });++ test("collects all descendants", () => {+ expect(+ createAssetFolderHierarchy(+ folders(+ folder("root"),+ folder("child", "root"),+ folder("grandchild", "child"),+ folder("sibling")+ )+ ).getDescendantIds("root")+ ).toEqual(new Set(["child", "grandchild"]));+ });+});diff --git a/packages/project-build/src/runtime/asset-folders.ts b/packages/project-build/src/runtime/asset-folders.tsnew file mode 100644index 0000000000..18a79379cf--- /dev/null+++ b/packages/project-build/src/runtime/asset-folders.ts@@ -0,0 +1,302 @@+import { z } from "zod";+import {+ assetFolderIssue,+ assetFolderName,+ assetFolders,+ createAssetFolderHierarchy,+ type Asset,+ type AssetFolder,+ type AssetFolders,+} from "@webstudio-is/sdk";+import type { BuilderState } from "../state/builder-state";+import {+ appendOptionalPropertyPatch,+ type BuilderPatch,+} from "../contracts/patch";+import type { BuilderRuntimeContext } from "./context";+import { throwBuilderRuntimeError } from "./errors";+import { createRuntimeMutation } from "./mutation";+import { createCopyName } from "./copy-name";+import { getAssetDisplayFilename } from "./assets";++export const assetFolderListInput = z.object({});++export const assetFolderCreateInput = z.object({+ name: assetFolderName,+ parentId: z.string().min(1).optional(),+});++export const assetFolderUpdateInput = z.object({+ folderId: z.string().min(1),+ values: z+ .object({+ name: assetFolderName.optional(),+ parentId: z.string().min(1).nullable().optional(),+ })+ .refine((values) => Object.keys(values).length > 0, {+ message: "At least one folder field is required",+ }),+});++export const assetFolderDeleteInput = z.object({ folderId: z.string().min(1) });++export const assetFolderDuplicateInput = z.object({+ folderId: z.string().min(1),+ parentId: z.string().min(1).nullable().optional(),+});++const getRequiredFolders = (state: Pick<BuilderState, "assetFolders">) => {+ if (state.assetFolders === undefined) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "Asset folders are not loaded"+ );+ }+ return state.assetFolders;+};++const validateFolderMutation = (folders: AssetFolders, name: string) => {+ const result = assetFolders.safeParse(folders);+ if (result.success) {+ return;+ }+ const issue = result.error.issues[0];+ if (issue?.message === assetFolderIssue.duplicateName) {+ return throwBuilderRuntimeError(+ "CONFLICT",+ `A folder named "${name}" already exists in this location`+ );+ }+ if (issue?.message === assetFolderIssue.parentMissing) {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent folder not found");+ }+ if (+ issue?.message === assetFolderIssue.selfParent ||+ issue?.message === assetFolderIssue.cycle+ ) {+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ "A folder can't be moved into itself or one of its descendants"+ );+ }+ return throwBuilderRuntimeError(+ "BAD_REQUEST",+ issue?.message ?? "Invalid asset folder hierarchy"+ );+};++export const listAssetFolders = (+ state: Pick<BuilderState, "assetFolders">,+ _input: z.infer<typeof assetFolderListInput>+) => ({ folders: Array.from(getRequiredFolders(state).values()) });++export const createAssetFolder = (+ state: Pick<BuilderState, "assetFolders">,+ input: z.infer<typeof assetFolderCreateInput>,+ context: BuilderRuntimeContext+) => {+ const folders = getRequiredFolders(state);+ if (context.projectId === undefined) {+ return throwBuilderRuntimeError("BAD_REQUEST", "Project id is required");+ }+ const folder: AssetFolder = {+ id: context.createId(),+ projectId: context.projectId,+ name: input.name.trim(),+ parentId: input.parentId,+ createdAt: new Date().toISOString(),+ };+ const nextFolders = new Map(folders).set(folder.id, folder);+ validateFolderMutation(nextFolders, folder.name);+ return createRuntimeMutation({+ payload: [+ {+ namespace: "assetFolders",+ patches: [{ op: "add", path: [folder.id], value: folder }],+ },+ ],+ result: { folderId: folder.id },+ invalidatesNamespaces: ["assetFolders"],+ });+};++export const updateAssetFolder = (+ state: Pick<BuilderState, "assetFolders">,+ input: z.infer<typeof assetFolderUpdateInput>+) => {+ const folders = getRequiredFolders(state);+ const folder = folders.get(input.folderId);+ if (folder === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Folder not found");+ }+ const nextName = input.values.name?.trim() ?? folder.name;+ const nextParentId =+ input.values.parentId === null+ ? undefined+ : (input.values.parentId ?? folder.parentId);+ const nextFolders = new Map(folders).set(folder.id, {+ ...folder,+ name: nextName,+ parentId: nextParentId,+ });+ validateFolderMutation(nextFolders, nextName);++ const patches: BuilderPatch[] = [];+ if (nextName !== folder.name) {+ patches.push({+ op: "replace",+ path: [folder.id, "name"],+ value: nextName,+ });+ }+ appendOptionalPropertyPatch(patches, {+ path: [folder.id, "parentId"],+ previous: folder.parentId,+ next: nextParentId,+ });+ return createRuntimeMutation({+ payload:+ patches.length === 0 ? [] : [{ namespace: "assetFolders", patches }],+ result: { folderId: folder.id },+ invalidatesNamespaces: patches.length === 0 ? [] : ["assetFolders"],+ });+};++export const duplicateAssetFolder = (+ state: Pick<BuilderState, "assetFolders" | "assets">,+ input: z.infer<typeof assetFolderDuplicateInput>,+ context: BuilderRuntimeContext+) => {+ const folders = getRequiredFolders(state);+ const source = folders.get(input.folderId);+ if (source === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Folder not found");+ }+ const parentId =+ input.parentId === undefined+ ? source.parentId+ : (input.parentId ?? undefined);+ if (parentId !== undefined && folders.has(parentId) === false) {+ return throwBuilderRuntimeError("NOT_FOUND", "Parent folder not found");+ }++ const hierarchy = createAssetFolderHierarchy(folders);+ const sourceFolderIds = hierarchy.getSubtreeIds(source.id);+ const sourceFolders = hierarchy.sortByDepth(+ Array.from(sourceFolderIds, (folderId) => folders.get(folderId)!)+ );+ const duplicatedIds = new Map<string, string>();+ const duplicatedFolders: AssetFolder[] = [];+ const copiedRootName = createCopyName(+ source.name,+ (candidate) =>+ hierarchy.findByName({ name: candidate, parentId }) !== undefined+ );+ const createdAt = new Date().toISOString();+ for (const folder of sourceFolders) {+ const id = context.createId();+ duplicatedIds.set(folder.id, id);+ duplicatedFolders.push({+ ...folder,+ id,+ name: folder.id === source.id ? copiedRootName : folder.name,+ parentId:+ folder.id === source.id+ ? parentId+ : duplicatedIds.get(folder.parentId!),+ createdAt,+ });+ }++ const displayFilenames = new Set(+ Array.from(state.assets?.values() ?? [], getAssetDisplayFilename)+ );+ const duplicatedAssets: Asset[] = [];+ for (const asset of state.assets?.values() ?? []) {+ if (+ asset.folderId === undefined ||+ sourceFolderIds.has(asset.folderId) === false+ ) {+ continue;+ }+ const filename = createCopyName(+ getAssetDisplayFilename(asset),+ (candidate) => displayFilenames.has(candidate)+ );+ displayFilenames.add(filename);+ duplicatedAssets.push({+ ...asset,+ id: context.createId(),+ filename,+ folderId: duplicatedIds.get(asset.folderId),+ });+ }++ const nextFolders = new Map(folders);+ for (const folder of duplicatedFolders) {+ nextFolders.set(folder.id, folder);+ }+ validateFolderMutation(nextFolders, copiedRootName);+ return createRuntimeMutation({+ payload: [+ {+ namespace: "assetFolders",+ patches: duplicatedFolders.map((folder) => ({+ op: "add" as const,+ path: [folder.id],+ value: folder,+ })),+ },+ ...(duplicatedAssets.length === 0+ ? []+ : [+ {+ namespace: "assets" as const,+ patches: duplicatedAssets.map((asset) => ({+ op: "add" as const,+ path: [asset.id],+ value: asset,+ })),+ },+ ]),+ ],+ result: { folderId: duplicatedIds.get(source.id)! },+ invalidatesNamespaces: ["assetFolders", "assets"],+ });+};++export const deleteAssetFolder = (+ state: Pick<BuilderState, "assetFolders" | "assets">,+ input: z.infer<typeof assetFolderDeleteInput>+) => {+ const folders = getRequiredFolders(state);+ const folder = folders.get(input.folderId);+ if (folder === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Folder not found");+ }++ const deletedFolderIds = createAssetFolderHierarchy(folders).getSubtreeIds(+ folder.id+ );+ const folderPatches: BuilderPatch[] = Array.from(deletedFolderIds).map(+ (folderId) => ({ op: "remove", path: [folderId] })+ );++ const assetPatches: BuilderPatch[] = [];+ for (const asset of state.assets?.values() ?? []) {+ if (asset.folderId !== undefined && deletedFolderIds.has(asset.folderId)) {+ assetPatches.push({ op: "remove", path: [asset.id] });+ }+ }++ return createRuntimeMutation({+ payload: [+ { namespace: "assetFolders", patches: folderPatches },+ ...(assetPatches.length === 0+ ? []+ : [{ namespace: "assets" as const, patches: assetPatches }]),+ ],+ result: { folderId: folder.id },+ invalidatesNamespaces: ["assetFolders", "assets"],+ });+};diff --git a/packages/project-build/src/runtime/assets.test.ts b/packages/project-build/src/runtime/assets.test.tsindex af912db4b7..4c45257d7a 100644--- a/packages/project-build/src/runtime/assets.test.ts+++ b/packages/project-build/src/runtime/assets.test.ts@@ -22,8 +22,10 @@ import {createAssetReplacementPayload,createAssetUsageList,deleteAssets,+ duplicateAsset,findAsset,findAssetUsage,+ getAsset,getAssetInfoFallback,getBrowserAssetFormat,imageDescriptionsSetInput,@@ -250,6 +252,47 @@ describe("asset runtime operations", () => {);});+ test("duplicates an asset into a target folder with a unique filename", () => {+ const source = imageAsset("source", "hero.png");+ const existingCopy = imageAsset("existing-copy", "other.png");+ existingCopy.filename = "hero copy";+ const result = duplicateAsset(+ {+ assets: new Map([+ [source.id, source],+ [existingCopy.id, existingCopy],+ ]),+ assetFolders: new Map([+ [+ "target",+ {+ id: "target",+ projectId: "project",+ name: "Target",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: source.id, folderId: "target" },+ { createId: () => "copy", projectId: "project" }+ );++ expect(result.result).toEqual({ assetId: "copy" });+ expect(result.payload[0]?.patches).toEqual([+ {+ op: "add",+ path: ["copy"],+ value: {+ ...source,+ id: "copy",+ filename: "hero copy 2",+ folderId: "target",+ },+ },+ ]);+ });+test("lists assets with usage counts", () => {expect(listAssets(state, { sort: "usage" })).toMatchObject({items: [@@ -261,9 +304,24 @@ describe("asset runtime operations", () => {});});+ test("gets the complete asset record", () => {+ const asset = imageAsset("nested");+ asset.description = "Campaign hero";+ asset.folderId = "campaign";++ expect(+ getAsset({ assets: new Map([[asset.id, asset]]) }, { assetId: asset.id })+ ).toEqual({ asset });+ expect(() =>+ getAsset({ assets: new Map() }, { assetId: "missing" })+ ).toThrow("Asset not found");+ });+test("expands asset descriptions only in verbose output", () => {const asset = imageAsset("described");- asset.description = `Team collaborating around a whiteboard. ${"Detailed visual context. ".repeat(80)}`;+ asset.description = `Team collaborating around a whiteboard. ${"Detailed visual context. ".repeat(+ 80+ )}`;const assetState = { ...state, assets: new Map([[asset.id, asset]]) };const compact = listAssets(assetState);const verbose = listAssets(assetState, { verbose: true });@@ -308,6 +366,15 @@ describe("asset runtime operations", () => {});});+ test("includes folder placement in compact asset lists", () => {+ const asset = imageAsset("nested");+ asset.folderId = "campaign";++ expect(+ listAssets({ ...state, assets: new Map([[asset.id, asset]]) })+ ).toMatchObject({ items: [{ id: "nested", folderId: "campaign" }] });+ });+test("paginates assets and rejects invalid cursors", () => {expect(listAssets(state, { cursor: "1", limit: 1 })).toMatchObject({items: [{ id: "next" }],@@ -962,6 +1029,45 @@ describe("addAsset", () => {)).toThrow("A configured project is required to add an asset");});++ test("adds an asset to an existing folder", () => {+ const result = addAsset(+ {+ assets: new Map(),+ assetFolders: new Map([+ [+ "folder",+ {+ id: "folder",+ projectId: "project",+ name: "Folder",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { asset: { ...assetInput, folderId: "folder" } },+ { projectId: "project" }+ );++ expect(result.payload[0]?.patches).toEqual([+ {+ op: "add",+ path: ["asset-1"],+ value: { ...assetInput, folderId: "folder", projectId: "project" },+ },+ ]);+ });++ test("rejects adding an asset to a missing folder", () => {+ expect(() =>+ addAsset(+ { assets: new Map(), assetFolders: new Map() },+ { asset: { ...assetInput, folderId: "missing" } },+ { projectId: "project" }+ )+ ).toThrow("Asset folder not found");+ });});test("creates asset delete payload", () => {@@ -1055,6 +1161,46 @@ describe("updateAsset", () => {)).toThrow("Filename already used");});++ test("moves an asset into an existing folder", () => {+ const result = updateAsset(+ {+ assets: new Map([["asset-1", imageAsset("asset-1")]]),+ assetFolders: new Map([+ [+ "folder",+ {+ id: "folder",+ projectId: "project",+ name: "Folder",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),+ },+ { assetId: "asset-1", values: { folderId: "folder" } }+ );++ expect(result.payload[0]?.patches).toEqual([+ {+ op: "add",+ path: ["asset-1", "folderId"],+ value: "folder",+ },+ ]);+ });++ test("rejects moving an asset into a missing folder", () => {+ expect(() =>+ updateAsset(+ {+ assets: new Map([["asset-1", imageAsset("asset-1")]]),+ assetFolders: new Map(),+ },+ { assetId: "asset-1", values: { folderId: "missing" } }+ )+ ).toThrow("Asset folder not found");+ });});describe("setImageDescriptions", () => {diff --git a/packages/project-build/src/runtime/assets.ts b/packages/project-build/src/runtime/assets.tsindex 90c3c9cf46..215191e46c 100644--- a/packages/project-build/src/runtime/assets.ts+++ b/packages/project-build/src/runtime/assets.ts@@ -20,7 +20,10 @@ import {fontAsset,imageAsset,} from "@webstudio-is/sdk";-import type { BuilderPatchChange } from "../contracts/patch";+import {+ appendOptionalPropertyPatch,+ type BuilderPatchChange,+} from "../contracts/patch";import {paginateOutput,projectOutput,@@ -35,6 +38,8 @@ import {throwBuilderRuntimeError,} from "./errors";import { createRuntimeMutation } from "./mutation";+import { createCopyName } from "./copy-name";+import type { BuilderRuntimeContext } from "./context";import {collectFontFamiliesFromStyleValue,traverseStyleValue,@@ -75,6 +80,7 @@ export const assetUpdateInput = z.object({).optional(),description: z.union([z.string(), z.null()]).optional(),+ folderId: z.union([z.string().min(1), z.null()]).optional(),}).refine((values) => Object.keys(values).length > 0,@@ -146,6 +152,13 @@ const addableAsset = z.union([export const assetAddInput = z.object({ asset: addableAsset });+export const assetDuplicateInput = z.object({+ assetId: z.string().min(1),+ folderId: z.string().min(1).nullable().optional(),+});++export const assetGetInput = z.object({ assetId: z.string().min(1) });+export const parseAssetType = (value: string | null) => {const result = assetType.safeParse(value);return result.success ? result.data : undefined;@@ -356,6 +369,17 @@ const getRequiredAssets = (state: Pick<BuilderState, "assets">) => {return state.assets;};+export const getAsset = (+ state: Pick<BuilderState, "assets">,+ input: z.infer<typeof assetGetInput>+) => {+ const asset = getRequiredAssets(state).get(input.assetId);+ if (asset === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");+ }+ return { asset };+};+const getRequiredAssetReferenceBuild = (state: Pick<BuilderState,@@ -564,8 +588,17 @@ export const formatAssetName = (asset: Pick<Asset, "name" | "filename">) => {export const getAssetDisplayFilename = (asset: Asset) =>asset.filename ?? asset.name.replace(/\.[^/.]+$/, "");+const assertAssetFolderExists = (+ assetFolders: BuilderState["assetFolders"],+ folderId: string | undefined+) => {+ if (folderId !== undefined && assetFolders?.has(folderId) !== true) {+ return throwBuilderRuntimeError("NOT_FOUND", "Asset folder not found");+ }+};+export const addAsset = (- state: Pick<BuilderState, "assets">,+ state: Pick<BuilderState, "assets" | "assetFolders">,input: z.infer<typeof assetAddInput>,context: { projectId?: string }) => {@@ -579,6 +612,7 @@ export const addAsset = (if (assets.has(input.asset.id)) {return throwBuilderRuntimeError("CONFLICT", "Asset already exists");}+ assertAssetFolderExists(state.assetFolders, input.asset.folderId);const asset: Asset = { ...input.asset, projectId: context.projectId };return createRuntimeMutation({payload: [@@ -592,17 +626,49 @@ export const addAsset = (});};-const createAssetDescriptionPatch = (- asset: Asset,- description: string | null-): BuilderPatchChange["patches"][number] => ({- op: asset.description === undefined ? "add" : "replace",- path: [asset.id, "description"],- value: description,-});+export const duplicateAsset = (+ state: Pick<BuilderState, "assets" | "assetFolders">,+ input: z.infer<typeof assetDuplicateInput>,+ context: BuilderRuntimeContext+) => {+ const assets = getRequiredAssets(state);+ const asset = assets.get(input.assetId);+ if (asset === undefined) {+ return throwBuilderRuntimeError("NOT_FOUND", "Asset not found");+ }+ const folderId =+ input.folderId === undefined+ ? asset.folderId+ : (input.folderId ?? undefined);+ assertAssetFolderExists(state.assetFolders, folderId);++ const displayFilenames = new Set(+ Array.from(assets.values(), getAssetDisplayFilename)+ );+ const duplicatedAsset: Asset = {+ ...asset,+ id: context.createId(),+ filename: createCopyName(getAssetDisplayFilename(asset), (candidate) =>+ displayFilenames.has(candidate)+ ),+ folderId,+ };+ return createRuntimeMutation({+ payload: [+ {+ namespace: "assets",+ patches: [+ { op: "add", path: [duplicatedAsset.id], value: duplicatedAsset },+ ],+ },+ ],+ result: { assetId: duplicatedAsset.id },+ invalidatesNamespaces: ["assets"],+ });+};export const updateAsset = (- state: Pick<BuilderState, "assets">,+ state: Pick<BuilderState, "assets" | "assetFolders">,input: z.infer<typeof assetUpdateInput>) => {const assets = getRequiredAssets(state);@@ -625,10 +691,10 @@ export const updateAsset = (}}if (asset.filename !== input.values.filename) {- patches.push({- op: asset.filename === undefined ? "add" : "replace",+ appendOptionalPropertyPatch(patches, {path: [asset.id, "filename"],- value: input.values.filename,+ previous: asset.filename,+ next: input.values.filename,});}}@@ -636,7 +702,20 @@ export const updateAsset = (input.values.description !== undefined &&asset.description !== input.values.description) {- patches.push(createAssetDescriptionPatch(asset, input.values.description));+ appendOptionalPropertyPatch(patches, {+ path: [asset.id, "description"],+ previous: asset.description,+ next: input.values.description,+ });+ }+ if (input.values.folderId !== undefined) {+ const folderId = input.values.folderId ?? undefined;+ assertAssetFolderExists(state.assetFolders, folderId);+ appendOptionalPropertyPatch(patches, {+ path: [asset.id, "folderId"],+ previous: asset.folderId,+ next: folderId,+ });}return createRuntimeMutation({@@ -670,7 +749,11 @@ export const setImageDescriptions = (}const description = update.decorative === true ? "" : update.description;if (asset.description !== description) {- patches.push(createAssetDescriptionPatch(asset, description));+ appendOptionalPropertyPatch(patches, {+ path: [asset.id, "description"],+ previous: asset.description,+ next: description,+ });updated.push({assetId: asset.id,decorative: update.decorative === true,@@ -759,6 +842,7 @@ const serializeAssetSummary = (asset: Asset) => ({id: asset.id,name: asset.name,filename: asset.filename,+ folderId: asset.folderId,type: asset.type,size: asset.size,contentType: asset.format,diff --git a/packages/project-build/src/runtime/copy-name.ts b/packages/project-build/src/runtime/copy-name.tsnew file mode 100644index 0000000000..d977bdb30f--- /dev/null+++ b/packages/project-build/src/runtime/copy-name.ts@@ -0,0 +1,14 @@+export const createCopyName = (+ name: string,+ isTaken: (candidate: string) => boolean+) => {+ let copyNumber = 1;+ while (true) {+ const suffix = copyNumber === 1 ? " copy" : ` copy ${copyNumber}`;+ const candidate = `${name}${suffix}`;+ if (isTaken(candidate) === false) {+ return candidate;+ }+ copyNumber += 1;+ }+};diff --git a/packages/project-build/src/runtime/cutover.ts b/packages/project-build/src/runtime/cutover.tsindex ee82fd4a76..b11f9b8a67 100644--- a/packages/project-build/src/runtime/cutover.ts+++ b/packages/project-build/src/runtime/cutover.ts@@ -268,14 +268,27 @@ export const builderRuntimeCutoverManifests = [operationIds: ["fonts.list"] as const,callers: ["MCP/CLI font discovery"] as const,},+ {+ family: "asset-folder-operations",+ operationIds: [+ "assetFolders.list",+ "assetFolders.create",+ "assetFolders.update",+ "assetFolders.delete",+ "assetFolders.duplicate",+ ] as const,+ callers: ["appRouter.api.assetFolders", "Builder asset manager"] as const,+ },{family: "asset-reference-operations",operationIds: ["assets.list",+ "assets.get","assets.findUsage","assets.update","assets.setImageDescriptions","assets.add",+ "assets.duplicate","assets.replace","assets.delete",] as const,diff --git a/packages/project-build/src/runtime/data.ts b/packages/project-build/src/runtime/data.tsindex 6508bc9e73..b28a436b6c 100644--- a/packages/project-build/src/runtime/data.ts+++ b/packages/project-build/src/runtime/data.ts@@ -2092,6 +2092,7 @@ export const createWebstudioDataFromBuild = ({}): WebstudioData => ({pages: structuredClone(build.pages),assets: new Map(assets.map(getClonedPair)),+ assetFolders: new Map(),instances: new Map(getBuildItems(build.instances).map(getClonedPair)),props: new Map(getBuildItems(build.props).map(getClonedPair)),dataSources: new Map(getBuildItems(build.dataSources).map(getClonedPair)),diff --git a/packages/project-build/src/runtime/fragment.ts b/packages/project-build/src/runtime/fragment.tsindex 7a5275b0e7..2d4b022cf2 100644--- a/packages/project-build/src/runtime/fragment.ts+++ b/packages/project-build/src/runtime/fragment.ts@@ -485,7 +485,9 @@ const insertFragmentAssetsMutable = ({// asset can be already present if pasting to the same projectif (assets.has(asset.id) === false) {// we use the same asset.id so the references are preserved- assets.set(asset.id, { ...asset, projectId });+ // Fragments do not contain asset-folder hierarchy. New assets therefore+ // land at the target project root instead of retaining a dangling source id.+ assets.set(asset.id, { ...asset, projectId, folderId: undefined });}}};diff --git a/packages/project-build/src/runtime/migrations.test.ts b/packages/project-build/src/runtime/migrations.test.tsindex 6895bd300e..59ed854aea 100644--- a/packages/project-build/src/runtime/migrations.test.ts+++ b/packages/project-build/src/runtime/migrations.test.ts@@ -49,6 +49,7 @@ describe("migrateLoadedData", () => {"dataSources","resources","assets",+ "assetFolders","breakpoints",]);});diff --git a/packages/project-build/src/runtime/output-schemas.ts b/packages/project-build/src/runtime/output-schemas.tsindex 11b54d21a3..dd91abfabe 100644--- a/packages/project-build/src/runtime/output-schemas.ts+++ b/packages/project-build/src/runtime/output-schemas.ts@@ -192,6 +192,7 @@ const asset = looseObject({id,name: z.string(),filename: z.string().optional(),+ folderId: id.optional(),type: assetType,size: z.number(),contentType: z.string(),@@ -203,6 +204,7 @@ const assetRecord = looseObject({name: z.string(),filename: z.string().optional(),description: z.string().nullable().optional(),+ folderId: id.optional(),type: assetType,size: z.number(),format: z.string(),@@ -210,6 +212,13 @@ const assetRecord = looseObject({meta: looseObject({}),});const assetListItem = asset.extend({ record: assetRecord.optional() });+const assetFolder = looseObject({+ id,+ projectId: id,+ name: z.string(),+ parentId: id.optional(),+ createdAt: z.string(),+});const assetUsage = looseObject({namespace: z.enum(["props",@@ -286,6 +295,12 @@ const unsupportedRuntimeConversion = looseObject({});export const runtimeOutputSchemas = {+ "assetFolders.list": looseObject({ folders: z.array(assetFolder) }),+ "assetFolders.create": folderIdResult,+ "assetFolders.update": folderIdResult,+ "assetFolders.delete": folderIdResult,+ "assetFolders.duplicate": folderIdResult,+ "assets.get": looseObject({ asset: assetRecord }),"pages.list": looseObject({pages: z.array(pageSummary),...outputPage,@@ -602,6 +617,7 @@ export const runtimeOutputSchemas = {updated: z.array(looseObject({ assetId: id, decorative: z.boolean() })),}),"assets.add": assetIdResult,+ "assets.duplicate": assetIdResult,"assets.replace": looseObject({ fromAssetId: id, toAssetId: id }),"assets.delete": looseObject({ assetIds: stringArray }),"system.migrateLoadedData": looseObject({ didBreakCycles: z.boolean() }),diff --git a/packages/project-build/src/runtime/page-copy.ts b/packages/project-build/src/runtime/page-copy.tsindex 539c546656..546a6c52ee 100644--- a/packages/project-build/src/runtime/page-copy.ts+++ b/packages/project-build/src/runtime/page-copy.ts@@ -35,7 +35,7 @@ import {import type { ConflictResolution } from "./style-copy";import type { BuilderState } from "../state/builder-state";import { paginateOutput, type PaginatedOutputInput } from "./output";-import { webstudioDataNamespaces } from "../contracts/namespaces";+import { pageCopyNamespaces } from "../contracts/namespaces";import { throwBuilderRuntimeError } from "./errors";import { createRuntimeMutation } from "./mutation";import { getStaticStringLiteral } from "./text-replacement";@@ -90,7 +90,7 @@ const isHydratedWebstudioData = (value: unknown): value is WebstudioData => {return false;}const data = value as Partial<WebstudioData>;- return webstudioDataNamespaces.every((namespace) => {+ return pageCopyNamespaces.every((namespace) => {if (namespace === "pages") {return (data.pages?.pages instanceof Map && data.pages.folders instanceof Map@@ -175,7 +175,7 @@ const contentModePageMetaFields = new Set([]);const getRequiredWebstudioData = (state: BuilderState): WebstudioData => {- for (const namespace of webstudioDataNamespaces) {+ for (const namespace of pageCopyNamespaces) {if (state[namespace] === undefined) {return throwBuilderRuntimeError("BAD_REQUEST",@@ -186,8 +186,6 @@ const getRequiredWebstudioData = (state: BuilderState): WebstudioData => {return state as WebstudioData;};-const pageCopyInvalidatesNamespaces = webstudioDataNamespaces;-const parseCopyNumberSuffix = (value: string) => {const { name = value, copyNumber = "0" } =value.match(/^(?<name>.+) \((?<copyNumber>\d+)\)$/)?.groups ?? {};@@ -854,7 +852,7 @@ export const duplicatePage = (return createRuntimeMutation({payload: duplicate.payload,result: { pageId: duplicate.pageId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -888,7 +886,7 @@ export const copyPage = (return createRuntimeMutation({payload,result: { pageId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -938,7 +936,7 @@ export const duplicateFolder = (return createRuntimeMutation({payload,result: { folderId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -982,7 +980,7 @@ export const createPageTemplate = (return createRuntimeMutation({payload,result: { templateId, rootInstanceId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -1030,7 +1028,7 @@ export const updatePageTemplate = (return createRuntimeMutation({payload,result: { templateId: input.templateId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -1061,7 +1059,7 @@ export const deletePageTemplate = (}),],result: { templateId: input.templateId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -1105,7 +1103,7 @@ export const duplicatePageTemplate = (return createRuntimeMutation({payload,result: { templateId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -1268,7 +1266,7 @@ export const createPageFromTemplate = (return createRuntimeMutation({payload,result: { pageId },- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};@@ -1581,7 +1579,7 @@ export const insertPageTransferItem = (type: input.item.type,didReachBreakpointLimit,},- invalidatesNamespaces: pageCopyInvalidatesNamespaces,+ invalidatesNamespaces: pageCopyNamespaces,});};diff --git a/packages/project-build/src/runtime/registry.test.ts b/packages/project-build/src/runtime/registry.test.tsindex 3d745b7e1c..115c0845ea 100644--- a/packages/project-build/src/runtime/registry.test.ts+++ b/packages/project-build/src/runtime/registry.test.ts@@ -1941,7 +1941,9 @@ describe("builder runtime registry", () => {for (const operation of builderRuntimeOperations) {expect(operation.requiresAssets).toBe(operation.readNamespaces.includes("assets") ||- operation.writeNamespaces.includes("assets")+ operation.writeNamespaces.includes("assets") ||+ operation.readNamespaces.includes("assetFolders") ||+ operation.writeNamespaces.includes("assetFolders"));}for (const operation of builderRuntimeOperations.filter((operation) =>@@ -2153,9 +2155,14 @@ describe("builder runtime registry", () => {["resources.upsert", {}],["resources.upsertProp", {}],["resources.delete", {}],+ ["assetFolders.create", {}],+ ["assetFolders.update", {}],+ ["assetFolders.delete", {}],+ ["assetFolders.duplicate", {}],["assets.update", {}],["assets.setImageDescriptions", {}],["assets.add", {}],+ ["assets.duplicate", {}],["assets.replace", {}],["assets.delete", { assetIdsOrPrefixes: "asset" }],]);@@ -2425,6 +2432,10 @@ describe("builder runtime registry", () => {},],["resources.delete", { resourceId: "resource", force: true }],+ [+ "assetFolders.update",+ { folderId: "asset-folder", values: { name: "Updated Media" } },+ ],["assets.update",{diff --git a/packages/project-build/src/runtime/registry.ts b/packages/project-build/src/runtime/registry.tsindex a5e3cf3644..ba04c3e5a3 100644--- a/packages/project-build/src/runtime/registry.ts+++ b/packages/project-build/src/runtime/registry.ts@@ -10,10 +10,12 @@ import {isHiddenPublicApiInputField,} from "../contracts/input-schema";import { instanceFilterInput, type InputJsonSchema } from "@webstudio-is/sdk";+import { pageCopyNamespaces } from "../contracts/namespaces";import { builderRuntimeContext, type BuilderRuntimeContext } from "./context";import { z } from "zod";import * as assets from "./assets";import * as bindingVerification from "./binding-verification";+import * as assetFolders from "./asset-folders";import * as components from "./components";import * as collection from "./collection";import * as data from "./data";@@ -324,19 +326,6 @@ const assetUsageNamespaces = ["resources","dataSources",] as const;-const pageCopyNamespaces = [- "pages",- "assets",- "dataSources",- "resources",- "instances",- "props",- "breakpoints",- "styles",- "styleSources",- "styleSourceSelections",-] as const;-const emptyInput = z.object({});const pageListInput = z.object({...paginatedOutputInputSchema.shape,@@ -1821,6 +1810,61 @@ export const builderRuntimeOperations = [data.resourceDeleteInput,({ state, input }) => data.deleteResource(state, input)),+ runtimeOperation(+ "assetFolders.list",+ api("list-asset-folders", "listAssetFolders"),+ readContract(["assetFolders"], { requiresAssets: true }),+ assetFolders.assetFolderListInput,+ ({ state, input }) => assetFolders.listAssetFolders(state, input)+ ),+ runtimeOperation(+ "assetFolders.create",+ api("create-asset-folder", "createAssetFolder"),+ mutationContract({+ readNamespaces: ["assetFolders"],+ writeNamespaces: ["assetFolders"],+ retryOnConflict: true,+ requiresAssets: true,+ }),+ assetFolders.assetFolderCreateInput,+ ({ state, input, context }) =>+ assetFolders.createAssetFolder(state, input, context)+ ),+ runtimeOperation(+ "assetFolders.update",+ api("update-asset-folder", "updateAssetFolder"),+ mutationContract({+ readNamespaces: ["assetFolders"],+ writeNamespaces: ["assetFolders"],+ requiresAssets: true,+ }),+ assetFolders.assetFolderUpdateInput,+ ({ state, input }) => assetFolders.updateAssetFolder(state, input)+ ),+ runtimeOperation(+ "assetFolders.delete",+ api("delete-asset-folder", "deleteAssetFolder"),+ mutationContract({+ readNamespaces: ["assetFolders", "assets"],+ writeNamespaces: ["assetFolders", "assets"],+ requiresAssets: true,+ }),+ assetFolders.assetFolderDeleteInput,+ ({ state, input }) => assetFolders.deleteAssetFolder(state, input)+ ),+ runtimeOperation(+ "assetFolders.duplicate",+ api("duplicate-asset-folder", "duplicateAssetFolder"),+ mutationContract({+ readNamespaces: ["assetFolders", "assets"],+ writeNamespaces: ["assetFolders", "assets"],+ retryOnConflict: true,+ requiresAssets: true,+ }),+ assetFolders.assetFolderDuplicateInput,+ ({ state, input, context }) =>+ assetFolders.duplicateAssetFolder(state, input, context)+ ),runtimeOperation("assets.list",api("list-assets", "listAssets"),@@ -1828,6 +1872,13 @@ export const builderRuntimeOperations = [assetListInput,({ state, input }) => assets.listAssets(state, input)),+ runtimeOperation(+ "assets.get",+ api("get-asset", "getAsset"),+ readContract(["assets"], { requiresAssets: true }),+ assets.assetGetInput,+ ({ state, input }) => assets.getAsset(state, input)+ ),runtimeOperation("fonts.list",api("list-fonts", "listFonts"),@@ -1846,7 +1897,7 @@ export const builderRuntimeOperations = ["assets.update",api("update-asset", "updateAsset"),mutationContract({- readNamespaces: ["assets"],+ readNamespaces: ["assets", "assetFolders"],writeNamespaces: ["assets"],requiresAssets: true,}),@@ -1868,13 +1919,26 @@ export const builderRuntimeOperations = ["assets.add",api("add-asset", "addAsset"),mutationContract({- readNamespaces: ["assets"],+ readNamespaces: ["assets", "assetFolders"],writeNamespaces: ["assets"],retryOnConflict: true,+ requiresAssets: true,}),assets.assetAddInput,({ state, input, context }) => assets.addAsset(state, input, context)),+ runtimeOperation(+ "assets.duplicate",+ api("duplicate-asset", "duplicateAsset"),+ mutationContract({+ readNamespaces: ["assets", "assetFolders"],+ writeNamespaces: ["assets"],+ retryOnConflict: true,+ requiresAssets: true,+ }),+ assets.assetDuplicateInput,+ ({ state, input, context }) => assets.duplicateAsset(state, input, context)+ ),runtimeOperation("assets.replace",api("replace-asset", "replaceAsset"),diff --git a/packages/project-build/src/runtime/runtime.test-fixtures.ts b/packages/project-build/src/runtime/runtime.test-fixtures.tsindex 9fbf5e84f0..590117dd4f 100644--- a/packages/project-build/src/runtime/runtime.test-fixtures.ts+++ b/packages/project-build/src/runtime/runtime.test-fixtures.ts@@ -252,6 +252,17 @@ export const state = {},],]),+ assetFolders: new Map([+ [+ "asset-folder",+ {+ id: "asset-folder",+ projectId: "project",+ name: "Media",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ],+ ]),breakpoints: new Map([["base", { id: "base", label: "Base" }],["desktop", { id: "desktop", label: "Desktop", minWidth: 1024 }],diff --git a/packages/project-build/src/state/adapters.ts b/packages/project-build/src/state/adapters.tsindex 16511fc7c0..6569b58b68 100644--- a/packages/project-build/src/state/adapters.ts+++ b/packages/project-build/src/state/adapters.ts@@ -13,6 +13,7 @@ import {import {getStyleDeclKey,type Asset,+ type AssetFolder,type Breakpoint,type DataSource,type Instance,@@ -57,6 +58,7 @@ export type BuilderBuildDataSnapshot = Partial<{dataSources: DataSource[];resources: Resource[];assets: Asset[];+ assetFolders: AssetFolder[];breakpoints: Breakpoint[];marketplaceProduct: MarketplaceProduct;projectSettings: ProjectSettings;@@ -76,6 +78,7 @@ export type BuilderCompactBuildDataSnapshot = Pick<| "marketplaceProduct"> & {assets?: Asset[];+ assetFolders?: AssetFolder[];projectSettings?: ProjectSettings;};@@ -111,7 +114,7 @@ const normalizeProjectSettings = (state: BuilderState) => {const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>(state: BuilderState,namespace: Namespace,- value: BuilderStateValueByNamespace[Namespace]+ value: BuilderStateValueByNamespace[Namespace] | SnapshotValue<Namespace>) => {if (namespace === "pages") {state.pages = migratePages(serializePages(value as Pages));@@ -121,27 +124,10 @@ const setClonedBuilderStateValue = <Namespace extends BuilderNamespace>((state as Record<string, unknown>)[namespace] = structuredClone(value);return;}- (state as Record<string, unknown>)[namespace] = cloneMap(- value as Map<unknown, unknown>- );-};--const setClonedBuilderStateSnapshotValue = <Namespace extends BuilderNamespace>(- state: BuilderState,- namespace: Namespace,- value: SnapshotValue<Namespace>-) => {- if (namespace === "pages") {- state.pages = migratePages(serializePages(value as Pages));- return;- }- if (namespace === "marketplaceProduct" || namespace === "projectSettings") {- (state as Record<string, unknown>)[namespace] = structuredClone(value);- return;- }- (state as Record<string, unknown>)[namespace] = cloneMapEntries(- value as readonly (readonly [unknown, unknown])[]- );+ (state as Record<string, unknown>)[namespace] =+ value instanceof Map+ ? cloneMap(value as Map<unknown, unknown>)+ : cloneMapEntries(value as readonly (readonly [unknown, unknown])[]);};export const createBuilderStateFromStores = (@@ -170,7 +156,7 @@ export const createBuilderStateFromSnapshot = (for (const namespace of builderNamespaces) {const value = build[namespace];if (value !== undefined) {- setClonedBuilderStateSnapshotValue(+ setClonedBuilderStateValue(state,namespace,value as SnapshotValue<typeof namespace>@@ -234,6 +220,9 @@ export const createBuilderStateFromBuildData = (if (build.assets !== undefined) {snapshot.assets = mapEntriesById(build.assets);}+ if (build.assetFolders !== undefined) {+ snapshot.assetFolders = mapEntriesById(build.assetFolders);+ }if (build.breakpoints !== undefined) {snapshot.breakpoints = mapEntriesById(build.breakpoints);}@@ -261,6 +250,7 @@ export const createBuilderStateFromCompactBuild = (resources: build.resources,instances: build.instances,assets: build.assets,+ assetFolders: build.assetFolders,marketplaceProduct: build.marketplaceProduct,projectSettings:build.projectSettings ?? createProjectSettingsFromPages(build.pages),diff --git a/packages/project-build/src/state/builder-state.ts b/packages/project-build/src/state/builder-state.tsindex c6f3436c9f..9d4fa2ce51 100644--- a/packages/project-build/src/state/builder-state.ts+++ b/packages/project-build/src/state/builder-state.ts@@ -1,5 +1,6 @@import type {Assets,+ AssetFolders,Breakpoints,DataSources,Instances,@@ -27,6 +28,7 @@ export type BuilderStateValueByNamespace = {dataSources: DataSources;resources: Resources;assets: Assets;+ assetFolders: AssetFolders;breakpoints: Breakpoints;projectSettings: ProjectSettings;marketplaceProduct: MarketplaceProduct;diff --git a/packages/project/src/db/build-patch-core.ts b/packages/project/src/db/build-patch-core.tsindex b617d9b25f..88e84588ba 100644--- a/packages/project/src/db/build-patch-core.ts+++ b/packages/project/src/db/build-patch-core.ts@@ -131,6 +131,7 @@ export type BuildPatchUpdateResult =update?: Database["public"]["Tables"]["Build"]["Update"];nextVersion: number;assetPatches: Patch[][];+ assetFolderPatches: Patch[][];previewImageAssetId?: string | null;}| { status: "version_mismatched"; errors: string }@@ -165,7 +166,12 @@ export const createBuildPatchUpdate = async ({const serverVersion = build.version;if (clientVersion !== serverVersion) {if (lastTransactionId === build.lastTransactionId) {- return { status: "ok", assetPatches: [], nextVersion: serverVersion };+ return {+ status: "ok",+ assetPatches: [],+ assetFolderPatches: [],+ nextVersion: serverVersion,+ };}return singlePlayerVersionMismatchResult;@@ -195,6 +201,7 @@ export const createBuildPatchUpdate = async ({const touchedStyleSources = createTouchedKeys();const touchedStyleSourceSelections = createTouchedKeys();const assetPatches: Patch[][] = [];+ const assetFolderPatches: Patch[][] = [];for (const transaction of transactions) {for (const change of transaction.payload) {@@ -268,6 +275,11 @@ export const createBuildPatchUpdate = async ({continue;}+ if (namespace === "assetFolders") {+ assetFolderPatches.push(patches);+ continue;+ }+if (namespace === "styleSourceSelections") {addTouchedPatchKeys(touchedStyleSourceSelections, patches);const styleSourceSelections =@@ -442,6 +454,7 @@ export const createBuildPatchUpdate = async ({return {status: "ok",assetPatches,+ assetFolderPatches,update,nextVersion: clientVersion + 1,previewImageAssetId,diff --git a/packages/project/src/db/build-patch.test.ts b/packages/project/src/db/build-patch.test.tsindex eb4746edac..535c43f6d6 100644--- a/packages/project/src/db/build-patch.test.ts+++ b/packages/project/src/db/build-patch.test.ts@@ -133,6 +133,152 @@ describe("patchBuild", () => {expect(didLoadBuild).toBe(false);});+ test("persists asset-folder namespace changes before accepting the build transaction", async () => {+ let insertedFolders: unknown;+ server.use(+ db.get("AssetFolder", () => json([])),+ db.post("AssetFolder", async ({ request }) => {+ insertedFolders = await request.json();+ return json(insertedFolders as never);+ }),+ db.patch("Build", () => empty({ headers: { "Content-Range": "*/1" } }))+ );++ const result = await patchLoadedBuild(+ {+ build: buildRow,+ buildId: "build-1",+ projectId: "project-1",+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "assetFolders",+ patches: [+ {+ op: "add",+ path: ["folder-1"],+ value: {+ id: "folder-1",+ projectId: "project-1",+ name: "Images",+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ },+ ],+ },+ ],+ }),+ ],+ },+ createContext()+ );++ expect(result.status).toBe("ok");+ expect(insertedFolders).toEqual([+ {+ id: "folder-1",+ projectId: "project-1",+ name: "Images",+ parentId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ]);+ });++ test("deletes folder assets before deleting the folder", async () => {+ const calls: string[] = [];+ const assetRow = {+ assetId: "asset-1",+ projectId: "project-1",+ filename: null,+ description: null,+ folderId: "folder-1",+ file: {+ name: "asset.pdf",+ format: "pdf",+ description: null,+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ meta: "{}",+ status: "UPLOADED",+ },+ };+ server.use(+ ownershipHandler,+ db.get("AssetFolder", () =>+ json([+ {+ id: "folder-1",+ projectId: "project-1",+ name: "Folder",+ parentId: null,+ createdAt: "2026-01-01T00:00:00.000Z",+ },+ ])+ ),+ db.get("Asset", ({ request }) => {+ const url = new URL(request.url);+ if (url.searchParams.has("name")) {+ return json([]);+ }+ if (url.searchParams.has("id")) {+ return json([+ {+ id: "asset-1",+ projectId: "project-1",+ name: "asset.pdf",+ file: assetRow.file,+ },+ ]);+ }+ return json([assetRow]);+ }),+ db.patch("Project", () => empty({ status: 204 })),+ db.delete("Asset", () => {+ calls.push("asset-delete");+ return empty({ status: 204 });+ }),+ db.patch("File", () => empty({ status: 204 })),+ db.delete("AssetFolder", () => {+ calls.push("folder-delete");+ return json([{ id: "folder-1" }]);+ }),+ db.patch("Build", () => {+ calls.push("build-update");+ return empty({ headers: { "Content-Range": "*/1" } });+ })+ );++ const result = await patchLoadedBuild(+ {+ build: buildRow,+ buildId: "build-1",+ projectId: "project-1",+ clientVersion: 3,+ transactions: [+ transaction({+ payload: [+ {+ namespace: "assetFolders",+ patches: [{ op: "remove", path: ["folder-1"] }],+ },+ {+ namespace: "assets",+ patches: [{ op: "remove", path: ["asset-1"] }],+ },+ ],+ }),+ ],+ },+ createContext()+ );++ expect(result.status).toBe("ok");+ expect(calls).toEqual(["asset-delete", "folder-delete", "build-update"]);+ });+test("applies transactions, validates data, and updates build with optimistic version guard", async () => {let updatedBuild: unknown;server.use(diff --git a/packages/project/src/db/build-patch.ts b/packages/project/src/db/build-patch.tsindex 5b0273495e..37812bad3b 100644--- a/packages/project/src/db/build-patch.ts+++ b/packages/project/src/db/build-patch.ts@@ -1,4 +1,8 @@-import { patchAssets } from "@webstudio-is/asset-uploader/index.server";+import {+ deleteAssetFoldersWithClient,+ patchAssetFoldersWithClient,+ patchAssets,+} from "@webstudio-is/asset-uploader/index.server";import type { Build } from "@webstudio-is/project-build";import { loadRawBuildById } from "@webstudio-is/project-build/server";import type { Database } from "@webstudio-is/postgrest/index.server";@@ -63,9 +67,21 @@ export const patchLoadedBuild = async (// Apply app-side asset mutations before marking the Build with// lastTransactionId so a failed asset mutation is not later treated as an// already-saved retry.- for (const patches of result.assetPatches) {- await patchAssets({ projectId }, patches, context);+ const deletedAssetFolderIds =+ result.assetFolderPatches.length === 0+ ? []+ : await patchAssetFoldersWithClient(+ { projectId, client: context.postgrest.client },+ result.assetFolderPatches.flat(),+ { deferDeletes: true }+ );+ if (result.assetPatches.length > 0) {+ await patchAssets({ projectId }, result.assetPatches.flat(), context);}+ await deleteAssetFoldersWithClient(+ { projectId, ids: deletedAssetFolderIds },+ context.postgrest.client+ );const update = await context.postgrest.client.from("Build")diff --git a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.tsindex 8348e1348c..24817de9a8 100644--- a/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts+++ b/packages/protocol/src/builder-api/__generated__/server-only-router-operation-metadata.ts@@ -76,6 +76,7 @@ export const serverOnlyRouterOperationMetadata = {"variables","resources","assets",+ "assetFolders","breakpoints","projectSettings","marketplaceProduct",@@ -108,6 +109,7 @@ export const serverOnlyRouterOperationMetadata = {"dataSources","resources","assets",+ "assetFolders","breakpoints","projectSettings","marketplaceProduct",@@ -147,6 +149,7 @@ export const serverOnlyRouterOperationMetadata = {"dataSources","resources","assets",+ "assetFolders","breakpoints","projectSettings","marketplaceProduct",diff --git a/packages/protocol/src/builder-api/local-operation-inputs.ts b/packages/protocol/src/builder-api/local-operation-inputs.tsindex 644adf0cf1..845949c09b 100644--- a/packages/protocol/src/builder-api/local-operation-inputs.ts+++ b/packages/protocol/src/builder-api/local-operation-inputs.ts@@ -8,6 +8,7 @@ const assetUploadDescriptor = z.object({type: z.enum(["image", "font", "file"]),format: z.string().optional(),description: z.string().optional(),+ folderId: z.string().min(1).optional(),meta: z.record(z.string(), z.unknown()).optional(),});diff --git a/packages/protocol/src/builder-api/operation-docs.ts b/packages/protocol/src/builder-api/operation-docs.tsindex ecc8f2f07d..e198d01605 100644--- a/packages/protocol/src/builder-api/operation-docs.ts+++ b/packages/protocol/src/builder-api/operation-docs.ts@@ -677,11 +677,53 @@ const curatedPublicApiOperationDocumentation = [requiredOptions: ["domain-id", "json"],examples: ["webstudio verify-domain --domain-id domain-id --json"],},+ {+ command: "list-asset-folders",+ description: "List the complete Asset Manager folder hierarchy",+ examples: ["MCP/API: list-asset-folders {}"],+ },+ {+ command: "create-asset-folder",+ description: "Create a root or nested Asset Manager folder",+ examples: [+ 'MCP/API: create-asset-folder {"name":"Marketing","parentId":"parent-folder-id"}',+ ],+ },+ {+ command: "update-asset-folder",+ description:+ "Rename an Asset Manager folder or move it under another folder; use parentId:null for Root",+ examples: [+ 'MCP/API: update-asset-folder {"folderId":"folder-id","values":{"name":"Brand","parentId":null}}',+ ],+ },+ {+ command: "duplicate-asset-folder",+ description:+ "Recursively duplicate a folder, nested folders, and contained assets; optionally choose a target parent",+ examples: [+ 'MCP/API: duplicate-asset-folder {"folderId":"folder-id","parentId":"target-folder-id"}',+ ],+ },+ {+ command: "delete-asset-folder",+ description:+ "Delete a folder recursively, including nested folders and contained assets",+ examples: ['MCP/API: delete-asset-folder {"folderId":"folder-id"}'],+ },{command: "list-assets",- description: "List project assets",+ description:+ "List project assets with folder ids; use verbose output for complete records",examples: ["webstudio list-assets --type image --with-usage --json"],},+ {+ command: "get-asset",+ description:+ "Get one complete asset record, including description, folder, creation time, and type-specific metadata",+ requiredOptions: ["asset", "json"],+ examples: ["webstudio get-asset --asset asset-id --json"],+ },{command: "list-fonts",description:@@ -690,7 +732,8 @@ const curatedPublicApiOperationDocumentation = [},{command: "upload-asset",- description: "Upload one local asset file from an asset descriptor",+ description:+ "Upload one local asset file from a descriptor, optionally into an Asset Manager folder",requiredOptions: ["input", "json"],examples: ["webstudio upload-asset --input asset.json --assets-dir .webstudio/assets --json",@@ -698,7 +741,8 @@ const curatedPublicApiOperationDocumentation = [},{command: "upload-assets",- description: "Upload local asset files from asset descriptors",+ description:+ "Upload local asset files from descriptors, optionally into Asset Manager folders",requiredOptions: ["input", "json"],examples: ["webstudio upload-assets --input assets.json --assets-dir .webstudio/assets --json",@@ -718,6 +762,30 @@ const curatedPublicApiOperationDocumentation = ['MCP/API: set-image-descriptions {"updates":[{"assetId":"hero-id","description":"Team collaborating around a whiteboard"},{"assetId":"texture-id","decorative":true}]}',],},+ {+ command: "update-asset",+ description:+ "Rename an asset, update its description, or move it to another folder; use folderId:null for Root",+ examples: [+ 'MCP/API: update-asset {"assetId":"asset-id","values":{"filename":"hero","folderId":"folder-id"}}',+ ],+ },+ {+ command: "add-asset",+ description:+ "Add an already-uploaded asset record, optionally inside an Asset Manager folder",+ examples: [+ 'MCP/API: add-asset {"asset":{"id":"asset-id","name":"hero_hash.png","type":"image","size":1200,"format":"png","createdAt":"2026-01-01T00:00:00.000Z","meta":{"width":1200,"height":800},"folderId":"folder-id"}}',+ ],+ },+ {+ command: "duplicate-asset",+ description:+ "Duplicate an asset record while reusing its uploaded file; optionally choose a target folder",+ examples: [+ 'MCP/API: duplicate-asset {"assetId":"asset-id","folderId":"target-folder-id"}',+ ],+ },{command: "replace-asset",description: "Replace asset references and delete the old asset",diff --git a/packages/protocol/src/builder-api/operations.test.ts b/packages/protocol/src/builder-api/operations.test.tsindex a329de759f..f19f95b36c 100644--- a/packages/protocol/src/builder-api/operations.test.ts+++ b/packages/protocol/src/builder-api/operations.test.ts@@ -288,6 +288,14 @@ describe("public api operation catalog", () => {).toEqual(["assets"]);});+ test("allows MCP uploads to target asset folders", () => {+ const upload = getPublicApiOperation("upload-asset");+ const uploadMany = getPublicApiOperation("upload-assets");++ expect(JSON.stringify(upload.inputSchema)).toContain('"folderId"');+ expect(JSON.stringify(uploadMany.inputSchema)).toContain('"folderId"');+ });+test("keeps operation lookup and tRPC path lookup strict", () => {expect(getPublicApiOperation("list-pages").id).toBe("pages.list");expect(getPublicApiOperationPath("list-pages")).toBe("api.pages.list");diff --git a/packages/protocol/src/schema.ts b/packages/protocol/src/schema.tsindex b4c2f37e06..25ced03a48 100644--- a/packages/protocol/src/schema.ts+++ b/packages/protocol/src/schema.ts@@ -1,4 +1,4 @@-import { asset, page } from "@webstudio-is/sdk/schema";+import { asset, assetFolder, page } from "@webstudio-is/sdk/schema";import { builderNamespaces } from "@webstudio-is/project-build/contracts";import {builderPatchSchema as internalBuilderPatchSchema,@@ -63,6 +63,7 @@ export const projectBundle = z.object({pages: z.array(page),build: serializedBuild,assets: z.array(asset),+ assetFolders: z.array(assetFolder).optional(),origin: z.string().optional(),});export type ProjectBundle = z.infer<typeof projectBundle>;diff --git a/packages/sdk/package.json b/packages/sdk/package.jsonindex a66b3d8d86..f4c07ca762 100644--- a/packages/sdk/package.json+++ b/packages/sdk/package.json@@ -45,6 +45,9 @@},"./router-path-test-data": {"webstudio": "./src/router-path-test-data.ts"+ },+ "./testing": {+ "webstudio": "./src/testing.ts"}},"files": [diff --git a/packages/sdk/src/asset-folder-hierarchy.ts b/packages/sdk/src/asset-folder-hierarchy.tsnew file mode 100644index 0000000000..9c04808514--- /dev/null+++ b/packages/sdk/src/asset-folder-hierarchy.ts@@ -0,0 +1,135 @@+import type { Asset } from "./schema/assets";+import type { AssetFolder, AssetFolders } from "./schema/asset-folders";++export const normalizeAssetFolderName = (name: string) =>+ name.trim().toLowerCase();++export const getAssetFolderSiblingKey = (+ parentId: string | undefined,+ name: string+) => JSON.stringify([parentId ?? null, normalizeAssetFolderName(name)]);++type AssetFolderTraversal = { path: AssetFolder[]; hasCycle: boolean };++const traverseAssetFolderAncestors = (+ folders: AssetFolders,+ folderId: string+): AssetFolderTraversal => {+ const path: AssetFolder[] = [];+ const visited = new Set<string>();+ let currentId: string | undefined = folderId;+ while (currentId !== undefined) {+ if (visited.has(currentId)) {+ return { path, hasCycle: true };+ }+ visited.add(currentId);+ const folder = folders.get(currentId);+ if (folder === undefined) {+ break;+ }+ path.unshift(folder);+ currentId = folder.parentId;+ }+ return { path, hasCycle: false };+};++export const createAssetFolderHierarchy = (folders: AssetFolders) => {+ const childrenByParentId = new Map<string | undefined, AssetFolder[]>();+ const traversalByFolderId = new Map<string, AssetFolderTraversal>();+ for (const folder of folders.values()) {+ const children = childrenByParentId.get(folder.parentId) ?? [];+ children.push(folder);+ childrenByParentId.set(folder.parentId, children);+ }++ const getTraversal = (folderId: string) => {+ const cached = traversalByFolderId.get(folderId);+ if (cached !== undefined) {+ return cached;+ }+ const traversal = traverseAssetFolderAncestors(folders, folderId);+ traversalByFolderId.set(folderId, traversal);+ return traversal;+ };++ const getChildren = (parentId: string | undefined): readonly AssetFolder[] =>+ childrenByParentId.get(parentId) ?? [];++ const resolveFolderId = (folderId: string | undefined) =>+ folderId !== undefined && folders.has(folderId) ? folderId : undefined;++ const getDescendantIds = (folderId: string | undefined) => {+ const descendants = new Set<string>();+ const pending: Array<string | undefined> = [folderId];+ while (pending.length > 0) {+ for (const child of getChildren(pending.pop())) {+ if (descendants.has(child.id) === false) {+ descendants.add(child.id);+ pending.push(child.id);+ }+ }+ }+ return descendants;+ };++ const getSubtreeIds = (folderId: string) =>+ getDescendantIds(folderId).add(folderId);++ const sortByDepth = (items: Iterable<AssetFolder>) =>+ Array.from(items).toSorted(+ (left, right) =>+ getTraversal(left.id).path.length - getTraversal(right.id).path.length+ );++ return {+ getChildren,+ getDescendantIds,+ getSubtreeIds,+ resolveFolderId,+ getPath: (folderId: string | undefined) =>+ folderId === undefined ? [] : getTraversal(folderId).path,+ hasCycle: (folderId: string) => getTraversal(folderId).hasCycle,+ sortByDepth,+ getAggregateAssetSizes: (assets: Iterable<Asset>) => {+ const sizes = new Map<string, number>();+ for (const asset of assets) {+ const folderId = resolveFolderId(asset.folderId);+ if (folderId !== undefined) {+ sizes.set(folderId, (sizes.get(folderId) ?? 0) + asset.size);+ }+ }+ for (const folder of sortByDepth(folders.values()).reverse()) {+ if (folder.parentId !== undefined) {+ sizes.set(+ folder.parentId,+ (sizes.get(folder.parentId) ?? 0) + (sizes.get(folder.id) ?? 0)+ );+ }+ }+ return sizes;+ },+ findByName: ({+ name,+ parentId,+ excludeIds = new Set(),+ }: {+ name: string;+ parentId: string | undefined;+ excludeIds?: ReadonlySet<string>;+ }) => {+ const siblingKey = getAssetFolderSiblingKey(parentId, name);+ for (const folder of folders.values()) {+ if (+ excludeIds.has(folder.id) === false &&+ getAssetFolderSiblingKey(folder.parentId, folder.name) === siblingKey+ ) {+ return folder;+ }+ }+ },+ };+};++export type AssetFolderHierarchy = ReturnType<+ typeof createAssetFolderHierarchy+>;diff --git a/packages/sdk/src/asset-folder-normalization.ts b/packages/sdk/src/asset-folder-normalization.tsnew file mode 100644index 0000000000..2eedb7dd22--- /dev/null+++ b/packages/sdk/src/asset-folder-normalization.ts@@ -0,0 +1,25 @@+import type { Asset } from "./schema/assets";+import type { AssetFolder } from "./schema/asset-folders";+import { createAssetFolderHierarchy } from "./asset-folder-hierarchy";++export const normalizeAssetFolderData = ({+ assets,+ folders,+}: {+ assets: readonly Asset[];+ folders: readonly AssetFolder[];+}) => {+ const hierarchy = createAssetFolderHierarchy(+ new Map(folders.map((folder) => [folder.id, folder]))+ );+ return {+ assets: assets.map((asset): Asset => {+ if (hierarchy.resolveFolderId(asset.folderId) === asset.folderId) {+ return asset;+ }+ const { folderId: _orphanedFolderId, ...rootAsset } = asset;+ return rootAsset;+ }),+ folders: Array.from(folders),+ };+};diff --git a/packages/sdk/src/asset-folder-utils.test.ts b/packages/sdk/src/asset-folder-utils.test.tsnew file mode 100644index 0000000000..e8e98aa2f5--- /dev/null+++ b/packages/sdk/src/asset-folder-utils.test.ts@@ -0,0 +1,90 @@+import { describe, expect, test } from "vitest";+import { createAssetFolderHierarchy } from "./asset-folder-hierarchy";+import { normalizeAssetFolderData } from "./asset-folder-normalization";+import {+ createAssetFolderFixture as folder,+ createAssetFoldersFixture as createFolders,+} from "./asset-folder.test-fixtures";++describe("asset folder utilities", () => {+ const root = folder({ id: "root" });+ const child = folder({ id: "child", parentId: "root" });+ const grandchild = folder({ id: "grandchild", parentId: "child" });+ const folders = createFolders(grandchild, child, root);+ const hierarchy = createAssetFolderHierarchy(folders);++ test("traverses descendants and ancestors", () => {+ expect(hierarchy.getDescendantIds("root")).toEqual(+ new Set(["child", "grandchild"])+ );+ expect(hierarchy.getSubtreeIds("root")).toEqual(+ new Set(["root", "child", "grandchild"])+ );+ expect(hierarchy.getPath("grandchild")).toEqual([root, child, grandchild]);+ });++ test("sorts parents before descendants", () => {+ expect(hierarchy.sortByDepth(folders.values())).toEqual([+ root,+ child,+ grandchild,+ ]);+ });++ test("handles cyclic hierarchy traversal without looping", () => {+ const cyclic = createFolders(+ folder({ id: "left", parentId: "right" }),+ folder({ id: "right", parentId: "left" })+ );++ const cyclicHierarchy = createAssetFolderHierarchy(cyclic);+ expect(cyclicHierarchy.getPath("left")).toHaveLength(2);+ expect(cyclicHierarchy.hasCycle("left")).toBe(true);+ expect(cyclicHierarchy.sortByDepth(cyclic.values())).toHaveLength(2);+ });++ test("finds sibling names case-insensitively and respects exclusions", () => {+ const photos = folder({ id: "photos", name: "Photos" });+ const folders = createFolders(+ photos,+ folder({ id: "nested", parentId: "photos", name: "Photos" })+ );++ expect(+ createAssetFolderHierarchy(folders).findByName({+ name: " photos ",+ parentId: undefined,+ })+ ).toBe(photos);+ expect(+ createAssetFolderHierarchy(folders).findByName({+ name: "photos",+ parentId: undefined,+ excludeIds: new Set([photos.id]),+ })+ ).toBeUndefined();+ });++ test("treats orphaned asset folder references as root", () => {+ const asset = {+ id: "asset",+ projectId: "project",+ name: "asset.pdf",+ type: "file" as const,+ format: "pdf",+ size: 1,+ createdAt: "2026-01-01T00:00:00.000Z",+ description: null,+ folderId: "missing",+ meta: {},+ };++ expect(hierarchy.resolveFolderId(asset.folderId)).toBeUndefined();+ expect(+ normalizeAssetFolderData({+ assets: [asset],+ folders: [...folders.values()],+ }).assets[0]+ ).not.toHaveProperty("folderId");+ });+});diff --git a/packages/sdk/src/asset-folder.test-fixtures.ts b/packages/sdk/src/asset-folder.test-fixtures.tsnew file mode 100644index 0000000000..82fb89091a--- /dev/null+++ b/packages/sdk/src/asset-folder.test-fixtures.ts@@ -0,0 +1,17 @@+import type { AssetFolder, AssetFolders } from "./schema/asset-folders";++export const createAssetFolderFixture = ({+ id,+ parentId,+ name = id,+ createdAt = "2026-01-01T00:00:00.000Z",+}: {+ id: string;+ parentId?: string;+ name?: string;+ createdAt?: string;+}): AssetFolder => ({ id, projectId: "project", name, parentId, createdAt });++export const createAssetFoldersFixture = (+ ...folders: AssetFolder[]+): AssetFolders => new Map(folders.map((folder) => [folder.id, folder]));diff --git a/packages/sdk/src/index.ts b/packages/sdk/src/index.tsindex a5afd97d5f..f502ca499e 100644--- a/packages/sdk/src/index.ts+++ b/packages/sdk/src/index.ts@@ -1,4 +1,5 @@export * from "./schema/assets";+export * from "./schema/asset-folders";export * from "./schema/pages";export * from "./schema/instances";export * from "./schema/data-sources";@@ -14,6 +15,8 @@ export * from "./schema/prop-meta";export * from "./schema/component-meta";export * from "./assets";+export * from "./asset-folder-hierarchy";+export * from "./asset-folder-normalization";export * from "./core-metas";export * from "./instances-utils";export * from "./page-utils";diff --git a/packages/sdk/src/schema.ts b/packages/sdk/src/schema.tsindex 24b2e3ac93..2cd612b327 100644--- a/packages/sdk/src/schema.ts+++ b/packages/sdk/src/schema.ts@@ -2,6 +2,7 @@// API contracts should import domain models from this file instead of the// package root so they do not pull SDK runtime helpers into API consumers.export * from "./schema/assets";+export * from "./schema/asset-folders";export * from "./schema/breakpoints";export * from "./schema/data-sources";export * from "./schema/deployment";diff --git a/packages/sdk/src/schema/asset-folders.test.ts b/packages/sdk/src/schema/asset-folders.test.tsnew file mode 100644index 0000000000..58a4c80836--- /dev/null+++ b/packages/sdk/src/schema/asset-folders.test.ts@@ -0,0 +1,54 @@+import { describe, expect, test } from "vitest";+import { assetFolders } from "./asset-folders";+import { createAssetFolderFixture as folder } from "../asset-folder.test-fixtures";++describe("assetFolders", () => {+ test("accepts nested folders", () => {+ expect(() =>+ assetFolders.parse(+ new Map([+ ["parent", folder({ id: "parent" })],+ ["child", folder({ id: "child", parentId: "parent" })],+ ])+ )+ ).not.toThrow();+ });++ test("rejects missing parents, cycles, and duplicate sibling names", () => {+ expect(() =>+ assetFolders.parse(+ new Map([["child", folder({ id: "child", parentId: "missing" })]])+ )+ ).toThrow("Parent folder must exist");+ expect(() =>+ assetFolders.parse(+ new Map([+ ["left", folder({ id: "left", parentId: "right" })],+ ["right", folder({ id: "right", parentId: "left" })],+ ])+ )+ ).toThrow("Folders can't contain cycles");+ expect(() =>+ assetFolders.parse(+ new Map([+ ["one", folder({ id: "one", name: "Media" })],+ ["two", folder({ id: "two", name: "media" })],+ ])+ )+ ).toThrow("Folder name must be unique");+ });++ test("rejects empty ids and folders from mixed projects", () => {+ expect(() =>+ assetFolders.parse(new Map([["", folder({ id: "" })]]))+ ).toThrow();+ expect(() =>+ assetFolders.parse(+ new Map([+ ["one", folder({ id: "one" })],+ ["two", { ...folder({ id: "two" }), projectId: "another-project" }],+ ])+ )+ ).toThrow("All folders must belong to the same project");+ });+});diff --git a/packages/sdk/src/schema/asset-folders.ts b/packages/sdk/src/schema/asset-folders.tsnew file mode 100644index 0000000000..1daa687560--- /dev/null+++ b/packages/sdk/src/schema/asset-folders.ts@@ -0,0 +1,95 @@+import { z } from "zod";+import {+ createAssetFolderHierarchy,+ getAssetFolderSiblingKey,+} from "../asset-folder-hierarchy";++export const assetFolderId = z.string().min(1);++export const assetFolderName = z+ .string()+ .trim()+ .min(1, "Folder name can't be empty");++export const assetFolderIssue = {+ idMismatch: "Folder id must match its record key",+ selfParent: "Folder can't be its own parent",+ parentMissing: "Parent folder must exist",+ duplicateName: "Folder name must be unique within its parent",+ projectMismatch: "All folders must belong to the same project",+ cycle: "Folders can't contain cycles",+} as const;++export const assetFolder = z.object({+ id: assetFolderId,+ projectId: z.string().min(1),+ name: assetFolderName,+ parentId: assetFolderId.optional(),+ createdAt: z.string(),+});++export type AssetFolder = z.infer<typeof assetFolder>;++export const assetFolders = z+ .map(assetFolderId, assetFolder)+ .superRefine((folders, context) => {+ const siblingKeys = new Set<string>();+ const projectIds = new Set<string>();++ for (const [folderId, folder] of folders) {+ projectIds.add(folder.projectId);+ if (folder.id !== folderId) {+ context.addIssue({+ code: "custom",+ path: [folderId, "id"],+ message: assetFolderIssue.idMismatch,+ });+ }+ if (folder.parentId === folder.id) {+ context.addIssue({+ code: "custom",+ path: [folderId, "parentId"],+ message: assetFolderIssue.selfParent,+ });+ } else if (+ folder.parentId !== undefined &&+ folders.has(folder.parentId) === false+ ) {+ context.addIssue({+ code: "custom",+ path: [folderId, "parentId"],+ message: assetFolderIssue.parentMissing,+ });+ }++ const siblingKey = getAssetFolderSiblingKey(folder.parentId, folder.name);+ if (siblingKeys.has(siblingKey)) {+ context.addIssue({+ code: "custom",+ path: [folderId, "name"],+ message: assetFolderIssue.duplicateName,+ });+ }+ siblingKeys.add(siblingKey);+ }++ if (projectIds.size > 1) {+ context.addIssue({+ code: "custom",+ message: assetFolderIssue.projectMismatch,+ });+ }++ const hierarchy = createAssetFolderHierarchy(folders);+ for (const folderId of folders.keys()) {+ if (hierarchy.hasCycle(folderId)) {+ context.addIssue({+ code: "custom",+ path: [folderId, "parentId"],+ message: assetFolderIssue.cycle,+ });+ }+ }+ });++export type AssetFolders = z.infer<typeof assetFolders>;diff --git a/packages/sdk/src/schema/assets.ts b/packages/sdk/src/schema/assets.tsindex 1f2c8afc22..34e28006ef 100644--- a/packages/sdk/src/schema/assets.ts+++ b/packages/sdk/src/schema/assets.ts@@ -1,4 +1,5 @@import { z } from "zod";+import { assetFolderId } from "./asset-folders";import { fontFormat, fontMeta } from "@webstudio-is/fonts";const assetId = z.string();@@ -10,6 +11,7 @@ const baseAsset = {name: z.string(),filename: z.string().optional(),description: z.union([z.string().optional(), z.null()]),+ folderId: assetFolderId.optional(),createdAt: z.string(),};diff --git a/packages/sdk/src/schema/webstudio.ts b/packages/sdk/src/schema/webstudio.tsindex 3107071d44..887aa1c72c 100644--- a/packages/sdk/src/schema/webstudio.ts+++ b/packages/sdk/src/schema/webstudio.ts@@ -1,5 +1,6 @@import { z } from "zod";import { asset, type Assets } from "./assets";+import type { AssetFolders } from "./asset-folders";import { dataSource, type DataSources } from "./data-sources";import { resource, type Resources } from "./resources";import { instance, instanceChild, type Instances } from "./instances";@@ -40,6 +41,7 @@ export type WebstudioFragment = z.infer<typeof webstudioFragment>;export type WebstudioData = {pages: Pages;assets: Assets;+ assetFolders?: AssetFolders;dataSources: DataSources;resources: Resources;instances: Instances;diff --git a/packages/sdk/src/testing.ts b/packages/sdk/src/testing.tsnew file mode 100644index 0000000000..7352fda2c7--- /dev/null+++ b/packages/sdk/src/testing.ts@@ -0,0 +1,4 @@+export {+ createAssetFolderFixture,+ createAssetFoldersFixture,+} from "./asset-folder.test-fixtures";