perf: Cut Builder E2E shard startup and repeated work (#6705)

The five-worker A/B run (`3d464ec2`, run 43985693015) passed all 61 E2E
cases and every Main check. Full shard jobs took **197, 201, 218, 226,
and 233 seconds** with a warm Builder build cache. Browser phases were
**154, 147, 169, 184, and 186 seconds**, totaling about 18 seconds more
than the four-worker warm run (`6f87754c`, run 43983946199). Five
workers raised CPU scheduling pressure from 72–74% to 77–84%. Four
workers are restored; all five jobs still need to finish under 180
seconds.

The merged-main run (`dfa0fc97`, run 43981570428) passed all **61 E2E
tests** and every Main workflow check. Its cold build cache made each
shard wait about 35–41 seconds for the shared Builder artifact. Full job
times were **285, 246, 227, 202, and 228 seconds**; browser phases were
**196, 154, 138, 116, and 140 seconds**. CPU scheduling pressure was
68–71%, with no memory pressure. A same-SHA rerun hit the Builder build
cache on shard 1: the full job fell to 215 seconds and browser work took
155.9 seconds. Warm setup is cheaper, but shard 1 still misses 180
seconds. The other four jobs have not been rerun warm.

The warm-cache full run on commit `3c0a936d` passed all 60 browser cases
across five fixed shards with three workers. Full jobs took 184, 191,
124, 161, and 190 seconds. Shards 1, 2, and 5 remain 4–11 seconds over
the 180-second target.

Browser phases took 137.5, 140.3, 77.0, 117.4, and 134.0 seconds. Setup
and cleanup added 44–56 seconds. All caches hit, and source checkout
took about 1–2 seconds.

The latest warm-cache run on `8a8f04b4` passed all 60 cases, but browser
phases were 85.9, 129.8, 193.2, 169.9, and 138.4 seconds. Shard 3's
Email binding test alone took 96.8 seconds in this run, versus 50.5 and
59.2 seconds in two earlier runs. This shows the current fixed
assignment is still too uneven and timings vary by run. The third
assignment moved Data variables from shard 1 to 3, Style panel from
shard 2 to 4, and Animation runtime from shard 2 to 5. All 60 cases
passed, but browser phases were 93.7, 150.2, 156.7, 110.6, and 167.2
seconds. Shards 2, 3, and 5 remain above the target once setup is
included. Test times varied sharply from prior runs. Read-only
inspection found no safe material reduction in the 93-second redirect
test or 56-second Asset folder clone test; both use serial state changes
and persistence checks. A separate select-asset-folders test now uses a
direct page reload for its final persistence check, removing an
unnecessary canvas wait. Its focused full-run time changed from 19.9 to
18.8 seconds, but this small result is not a speedup for the slow Asset
folder clone test. The six-move assignment passed all 60 cases on run
43969666884, but browser phases were 166.8, 106.5, 151.5, 183.3, and
123.1 seconds. Only shards 2 and 5 finished under 180 seconds including
setup. The total measured test work was about 1,805 seconds across 15
workers, a 120-second ideal average before scheduling overhead. The
latest run on `b71669bf` passed all 60 cases, with browser phases of
88.4, 123.5, 138.8, 151.4, and 157.1 seconds. Setup added 43–65 seconds.
Only shard 1 finished under 180 seconds for the complete job. The
four-file rebalance reduced the worst complete-job time from about 238
to 209 seconds. Run `66163599` passed all 60 cases; full jobs took about
155, 212, 152, 168, and 173 seconds. Run `1853aef1` also passed all 60,
but jobs were about 180, 157, 203, 166, and 156 seconds; browser phases
were 129, 90, 136, 106, and 103 seconds. Setup and cleanup added 51, 67,
67, 60, and 53 seconds. Shards 1 and 3 missed the 180-second target. CPU
scheduling pressure was 48–62%, with no memory pressure.

Recent changes reduce repeated work and keep the same assertions:
- The variable test uses one saved pre-edit Preview snapshot while
Builder edits and reloads the project on a separate page.
- The two-generation Email test starts from a blank project because it
creates the routes and forms it checks. Both saved production
generations are still built and checked.
- Email delivery forms are authored inside the existing Preview process,
removing a separate Node process start.
- Two shard-3 form tests share one project and production Preview. Their
success/failure results, redirects, browser feedback, scroll behavior,
retry behavior, and saved project redirect checks remain.
- Marketplace settings save both fields in one cycle and keep checks for
each value before and after reload.
- Content-mode rich-text tests save both link edits together while
keeping stored href and link-removal checks.
- MCP form delivery uses a smaller fixture with the same email plan and
Builder permissions; it removes five unused inserts. Warm local timings
were nearly the same.
- The two longest shard-5 cases and the 64-second shard-3 Pages bridge
file moved to lower-load fixed shards. All 60 cases remain assigned
once.
- The shard-3 form-delivery file now sorts earlier so its Preview work
overlaps earlier cases. A local three-worker comparison reduced shard-3
Playwright time from 71.2 to 64.7 seconds.
- The shard-5 callbacks test uses a blank project with its existing
page. It keeps its production Preview and all assertions, removes eight
unrelated database operations, and measured 13.8% faster in focused
local comparisons.
- The shard action starts PostgreSQL and PostgREST image pulls while
pnpm installs dependencies. Both operations still occur; setup and
cleanup still add about 45 seconds.

The latest run (`43990503162`) passed all 61 browser cases, but GitHub
reported full shard jobs of **228/200/176/152/218 seconds**; shards 1,
2, and 5 missed the 180-second target. Hook-aware logs show per-file
work sums of **587/458/358/349/551 seconds**. These are work totals, not
CI wall times, and the two parallel suites on shard 1 made a simple
work-sum rebalance misleading. The current setup change starts and
readies the snapshot database/PostgREST while dependencies install, with
Prisma and Chromium work remaining after installation; its CI saving is
not measured yet.

Run `44008044890` passed all 61 browser cases and five setup tests on
the same fixed assignments after backend setup began overlapping
dependency installation. Browser phases were
**202.5/176.4/81.2/106.7/110.8 seconds**; the full jobs still missed the
180-second goal on the slower shards. Image pulls finished in
4/6/21/8/23 seconds, and only shards 3 and 5 waited after installation
(9 and 14 seconds). The nine-file tag assignment passed all 61 browser
cases and five setup tests in run `44008945736`. Complete shard jobs
took **174.4/125/223.7/161.6/166.2 seconds**; only shard 3 missed 180
seconds. Three more measured file retags move slow serial work from
shard 3 to shards 2 and 4. All twelve tag changes are exact file
renames, so test cases and assertions remain. The final full run on
commit `b9bc8b4` (run `44050045632`) passed all 61 browser tests and
five setup tests. Complete shard jobs, including setup and cleanup, took
**151/132/136/162/144 seconds**; all five finished under three minutes.
The Node/pnpm, Playwright browser, and Builder build caches hit, so no
E2E build artifact polling or download was needed. Each shard still
installs workspace dependencies, starts and readies its local database
services, prepares E2E, runs its assigned tests, and tears services
down. CPU scheduling pressure was 60–68%; memory pressure was 0%. All
workflow checks passed.

### Checklist

- [x] Keep five fixed shards and preserve every test while measuring
worker counts.
- [x] Add timings for generated Preview phases and preserve the logs in
CI.
- [x] Reduce repeated form, variable, and Preview setup without dropping
assertions.
- [x] Compare worker counts and restore three workers after the
two-worker trial increased total test time.
- [x] Manually rebalance fixed shard tags from measured test durations;
discovery confirms all 60 cases run once.
- [x] Review Builder documentation impact; the E2E README describes
fixed, manually measured shard tags.
- [x] Run all five shards on the latest assignment; all 60 browser cases
and all workflow checks passed.
- [x] Check whether slow source checkouts recur; this run's five fetches
took 1–2 seconds, and source caching remains unjustified.
- [x] Optimize shard-5 setup without removing its Preview or assertions.
- [x] Rebalance heavy tests onto lower-load fixed shards, based on
measured durations.
- [x] Overlap image pulls with the dependency install shared by the five
shards.
- [x] Run the full suite on these combined changes; all 60 cases and
workflow checks passed.
- [x] Re-run shard 5 with the Builder build cache warm; it passed in 173
seconds.
- [x] Rebalance measured files across the five shards and verify all 60
cases run once.
- [x] Run all five shards with the Builder build cache warm; four
finished under 180 seconds.
- [x] Move the 61-second data-variable Preview case from shard 1 to
shard 5; all 60 cases remain assigned once.
- [x] Run all five shards on the latest assignments; all 60 cases
passed, but shards 3 (183s) and 5 (212s) remain over 180 seconds.
- [x] Share one generated Preview between shard-5 callback and
legacy-route scenarios; local full-shard A/B improved by 6 seconds with
all assertions preserved.
- [x] Move the data-variable and Form inspector tests from shard 5 to
shard 4, Preview links from shard 5 to shard 1, and content-mode pages
from shard 3 to shard 1.
- [x] Run all five shards on the new assignments; all 60 cases passed,
but shard 4 took 235 seconds.
- [x] Move the 61-second data-variable and 46-second redirect tests from
shard 4 to shard 1, the 79-second Email binding test to shard 5, and the
21-second Slot keyboard test from shard 5 to shard 2.
- [x] Rebalance the four longest test files from the latest CI
measurements while keeping five fixed shards and all 60 cases.
- [x] Run all five shards on that assignment; all 60 browser cases and
workflow checks passed, but full jobs were approximately 144, 188, 247,
212, and 180 seconds. Shards 2–5 remained at or above the 180-second
goal.
- [x] Rebalance measured test files again and verify all 60 cases run
once; full workflow run 43965687329 passed all cases, but several shards
remained over 180 seconds.
- [x] Use four-run medians to rebalance Data variables, Style panel, and
Animation runtime while keeping five shards and three workers.
- [x] Run all five shards on the latest assignment; all 60 cases passed,
but browser phases were 93.7, 150.2, 156.7, 110.6, and 167.2 seconds.
- [x] Replace the unnecessary Builder canvas readiness wait with a
direct reload in the select-and-drag asset folder persistence test;
preserve the post-reload folder assertions. Focused full runs were 19.9s
and 18.8s, including setup; independent review found no coverage or
readiness issue.
- [x] Inspect the slow redirect and Asset folder clone tests; keep their
serial writes and persistence checks because no safe material reduction
was found.
- [x] Rebalance six files against recent and median timings; all 60
browser cases passed on run 43969666884, with full jobs approximately
212, 156, 208, 238, and 176 seconds. Shards 1, 3, and 4 remained over
180 seconds.
- [x] Rebalance Data variables, Content mode assets, Navigator, and Form
redirect files using the latest run. All 60 cases passed on run
43971617077; complete jobs were approximately 149, 191, 191, 209, and
202 seconds.
- [x] Move Navigator (shard 4→1), Form redirect matrix (5→1), and Editor
fragment (2→4). The 66163599 run passed all 60 cases; four full jobs
took 149–171 seconds and shard 2 took 208 seconds.
- [x] Move Share links from shard 2→3 and Author props from shard 2→1.
All 60 cases passed in run `1853aef1`, but shards 1 and 3 remained over
180 seconds.
- [x] Move Email binding from shard 1→2, Browser form preview from shard
3→1, and Share links from shard 3→5. All 60 cases passed, but the latest
run’s browser phases were 184, 145, 129, 89, and 182 seconds. Only shard
4’s full job was under 180 seconds.
- [x] Start DB/PostgREST image pulls before Node/pnpm cache restoration
and installation, preserving timeouts, error propagation, and cleanup.
The next run reported 5–17 seconds total pull time and zero wait after
install on all five shards; setup still varied and the 3-minute goal was
not met.
- [x] Compare three and four Playwright workers on the same five fixed
shards and assignments. Four workers lowered total browser-phase time by
about 13% and lowered the worst full job from 252s to 234s; all tests
passed. Keep four workers for the next balanced run.
- [x] Trial five Playwright workers on the same five fixed shards and 61
cases. Run 43985693015 passed every check with warm-cache full jobs of
197/201/218/226/233s; browser phases were 154/147/169/184/186s. Against
the four-worker run 43983946199 (198/180/224/230/246s full;
147/135/168/182/190s browser), aggregate browser work rose about 18s and
CPU pressure rose to 77–84%. Restore four workers; neither setting met
the 180s target.
- [x] Use run 43986730815's 61 case timings to rebalance whole test
files across the same five fixed shards with four workers. Discovery
found all 61 unique cases once; run 43988555497 passed all five shards
with full jobs of 158/162/224/220/177s. Shards 3 and 4 still miss 180s.
- [x] Overlap snapshot DB/PostgREST preparation with dependency
installation; preserve readiness, errors, and cleanup. Run 44008044890
passed all five shards; only two image pulls required waiting after
installation.
- [x] Add hook-aware timings and rebalance fixed shard tags using runs
43990503162 and 44008044890. All nine file changes are exact renames;
the 180-second whole-job target remains unverified on the new tags.
- [x] Rebalance the five fixed shards from all 61 current case timings
without weakening assertions; run `44050045632` passed all 61 browser
cases and five setup tests, with full jobs at 151/132/136/162/144
seconds and all checks green.
- [x] Validate seeded E2E pages, instances, props, and breakpoints with
existing schemas; preserve the historical Form identity marker and cover
its JSON round-trip. Builder typecheck, focused Vitest, lint,
formatting, and diff checks passed. Reviewed Builder docs; no
documentation changes are needed.
- [ ] Rebalance any shard still above three minutes using the latest
full-run timings while keeping five fixed shards and all tests.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-17 11:03:04 +01:00
1 parent c4b26b4173
commit 9a86222afd
152 files changed
+11794 -14662

No files matched your search

+7 -4
View File
@@ -20,8 +20,6 @@ runs:
submodules-ssh-key: ${{ inputs.submodules-ssh-key }}
- uses: ./.github/actions/ci-setup
with:
run-scripts: "true"
- name: Discover shards
id: shards
@@ -30,7 +28,7 @@ runs:
shards=$(pnpm --dir apps/builder exec tsx ./e2e/print-shards.ts)
SHARDS="$shards" node -e '
const shards = JSON.parse(process.env.SHARDS);
if (shards.length !== 10 || shards.some(({ shard, partition }, index) =>
if (shards.length !== 5 || shards.some(({ shard, partition }, index) =>
shard !== `shard-${index + 1}` || partition !== "")) {
throw new Error("Builder E2E shard matrix changed; update the workflow matrix before running CI.");
}
@@ -41,7 +39,8 @@ runs:
id: build-key
shell: bash
run: |
echo "hash=$(git ls-files -s -- . ':!apps/builder/e2e/**' | sha256sum | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
hash=$(bash .github/actions/builder-e2e-build/build-input-hash.sh)
echo "hash=$hash" >> "$GITHUB_OUTPUT"
- name: Cache Builder build
id: build-cache
@@ -65,10 +64,13 @@ runs:
- name: Check Builder build
shell: bash
env:
BUILD_INPUT_HASH: ${{ steps.build-key.outputs.hash }}
run: |
test -d apps/builder/build/server
test -d apps/builder/build/client/assets
test -f packages/sdk-components-react-router/lib/components.js
printf '%s\n' "$BUILD_INPUT_HASH" > apps/builder/build/e2e-build-input-hash
- name: Identify schema snapshot
id: schema
@@ -92,6 +94,7 @@ runs:
name: builder-e2e-build
retention-days: 7
path: |
apps/builder/build/e2e-build-input-hash
apps/builder/build/server
apps/builder/build/client/assets
packages/*/lib
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -euo pipefail
{
# Keep test exclusions scoped so Remix routes and public assets are still hashed.
git ls-files -s -- . ':!apps/builder/e2e/**' \
':(exclude,glob).github/actions/builder-e2e-shard/**' \
':(exclude,glob)apps/builder/app/'{builder,canvas,dashboard,services,shared}'/**/*.'{test,spec}.{ts,tsx} \
':(exclude,glob)apps/builder/backend/**/*.'{test,spec}.{ts,tsx} \
':(exclude,glob)packages/*/'{src,scripts,evaluations,migrations-cli}'/**/*.'{test,spec}.{ts,tsx} \
':(exclude,glob)scripts/visual-regression/**/*.'{test,spec}.{ts,tsx}
# CI can check out a submodule branch newer than the recorded gitlink.
git submodule foreach --quiet --recursive 'head=$(git rev-parse HEAD) && printf "%s %s\n" "$displaypath" "$head"'
} | sha256sum | cut -d' ' -f1
+117 -12
View File
@@ -20,9 +20,88 @@ runs:
with:
submodules-ssh-key: ${{ inputs.submodules-ssh-key }}
- name: Start E2E image pull
shell: bash
run: |
# Elapsed pull time includes tool setup, pnpm cache restoration, and install.
pull_dir="$RUNNER_TEMP/builder-e2e-image-pull"
mkdir -p "$pull_dir"
rm -f "$pull_dir/status"
date +%s > "$pull_dir/started"
setsid bash -c '
timeout --kill-after=10s "${E2E_DOCKER_PULL_TIMEOUT_SECONDS:-300}s" \
bash apps/builder/backend/run.sh snapshot pull --policy missing db postgrest \
> "$1" 2>&1 &
pull=$!
trap '\''kill "$pull" 2>/dev/null || true; wait "$pull" 2>/dev/null || true; exit 143'\'' TERM INT
wait "$pull"
result=$?
printf "%s %s\n" "$result" "$(date +%s)" > "$2.tmp"
mv "$2.tmp" "$2"
' bash "$pull_dir/log" "$pull_dir/status" </dev/null >/dev/null 2>&1 &
echo "$!" > "$pull_dir/pid"
- uses: ./.github/actions/ci-setup
with:
run-scripts: "true"
install-dependencies: "false"
- name: Install dependencies and prepare E2E backend
shell: bash
run: |
pnpm install --frozen-lockfile &
install=$!
pull_dir="$RUNNER_TEMP/builder-e2e-image-pull"
cleanup() {
status=$?
trap - EXIT
if [ "$status" -ne 0 ]; then
kill "$install" 2>/dev/null || true
fi
wait "$install" 2>/dev/null || true
exit "$status"
}
trap cleanup EXIT
trap 'exit 143' TERM INT
pull=$(cat "$pull_dir/pid")
wait_started=$SECONDS
while [ ! -f "$pull_dir/status" ]; do
if ! kill -0 "$pull" 2>/dev/null && [ ! -f "$pull_dir/status" ]; then
cat "$pull_dir/log"
echo "E2E image pull stopped without a result" >&2
exit 1
fi
sleep 1
done
read -r pull_status pull_finished < "$pull_dir/status"
printf 'E2E image pull: total=%ss wait-after-starting-install=%ss\n' \
"$(( pull_finished - $(cat "$pull_dir/started") ))" "$(( SECONDS - wait_started ))"
cat "$pull_dir/log"
if [ "$pull_status" != 0 ]; then
exit 1
fi
TIMEFORMAT='[e2e:backend] elapsed=%3Rs'
time bash apps/builder/e2e/run.sh ci-shard-backend
wait "$install"
trap - EXIT TERM INT
- name: Stop unfinished E2E image pull
if: always()
shell: bash
run: |
pull_dir="$RUNNER_TEMP/builder-e2e-image-pull"
if [ -f "$pull_dir/status" ] || [ ! -f "$pull_dir/pid" ]; then
exit 0
fi
pull=$(cat "$pull_dir/pid")
kill "$pull" 2>/dev/null || true
for attempt in {1..12}; do
if ! kill -0 "$pull" 2>/dev/null; then
exit 0
fi
sleep 1
done
kill -KILL "$pull" 2>/dev/null || true
- name: Cache Playwright Chromium
uses: actions/cache@v5
@@ -37,7 +116,8 @@ runs:
id: build-key
shell: bash
run: |
echo "hash=$(git ls-files -s -- . ':!apps/builder/e2e/**' | sha256sum | cut -d' ' -f1)" >> "$GITHUB_OUTPUT"
hash=$(bash .github/actions/builder-e2e-build/build-input-hash.sh)
echo "hash=$hash" >> "$GITHUB_OUTPUT"
- name: Restore Builder build
id: build-cache
@@ -49,18 +129,33 @@ runs:
packages/*/lib
key: builder-e2e-build-v1-${{ runner.os }}-${{ runner.arch }}-${{ steps.build-key.outputs.hash }}
- name: Prepare Builder E2E
shell: bash
run: |
# Dependencies are installed, so Prisma and Playwright can run safely.
TIMEFORMAT='[e2e:prepare] elapsed=%3Rs'
time bash apps/builder/e2e/run.sh ci-shard-prepare
- name: Wait for Builder E2E build
if: steps.build-cache.outputs.cache-hit != 'true'
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
for attempt in {1..84}; do
count=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts?name=builder-e2e-build" --jq '.total_count')
if [ "$count" -gt 0 ]; then
wait_started_at=$SECONDS
deadline=$((wait_started_at + 7 * 60))
while (( SECONDS < deadline )); do
available=$(gh api "repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/artifacts?name=builder-e2e-build" --jq '.artifacts | max_by(.id) | .expired == false')
if [ "$available" = true ]; then
exit 0
fi
sleep 5
# Check more often during normal builds without increasing the
# maximum number of requests if the build never uploads.
if (( SECONDS - wait_started_at < 40 )); then
sleep 2
else
sleep 6
fi
done
echo "Builder E2E build artifact was not uploaded within 7 minutes" >&2
exit 1
@@ -71,6 +166,19 @@ runs:
with:
name: builder-e2e-build
path: .
# Use the same REST artifact lookup as the wait step.
github-token: ${{ github.token }}
- name: Verify Builder E2E build inputs
if: steps.build-cache.outputs.cache-hit != 'true'
shell: bash
env:
BUILD_INPUT_HASH: ${{ steps.build-key.outputs.hash }}
run: |
if ! cmp -s <(printf '%s\n' "$BUILD_INPUT_HASH") apps/builder/build/e2e-build-input-hash; then
echo "Builder E2E build artifact does not match this shard's build inputs." >&2
exit 1
fi
- name: Check Builder build
shell: bash
@@ -85,16 +193,13 @@ runs:
E2E_TEST_SHARD: ${{ inputs.shard }}
E2E_TEST_PARTITION: ${{ inputs.partition }}
run: |
workers=3
if [ "$E2E_TEST_SHARD" = "shard-5" ]; then
workers=2
fi
args=(--workers="$workers")
# Select only the E2E test files. Playwright runs setup as a dependency.
args=(--workers=4 'e2e/tests/')
if [ -n "$E2E_TEST_PARTITION" ]; then
args+=(--shard="$E2E_TEST_PARTITION")
fi
bash apps/builder/e2e/measure-resources.sh \
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
bash apps/builder/e2e/run.sh ci-shard-test "${args[@]}"
- name: Upload report
if: failure()
+4
View File
@@ -4,6 +4,9 @@ description: |
Sets up the CI environment for the project.
inputs:
install-dependencies:
description: Install workspace dependencies after setting up the tools and cache.
default: "true"
run-scripts:
description: Run dependency lifecycle scripts during installation.
default: "false"
@@ -23,4 +26,5 @@ runs:
install_args+=(--ignore-scripts)
fi
pnpm install "${install_args[@]}"
if: inputs.install-dependencies == 'true'
shell: bash
@@ -5,6 +5,7 @@ on:
types: [labeled]
permissions:
actions: read
contents: read
deployments: write
pull-requests: write
-5
View File
@@ -211,11 +211,6 @@ jobs:
- shard-3
- shard-4
- shard-5
- shard-6
- shard-7
- shard-8
- shard-9
- shard-10
permissions:
contents: read
@@ -0,0 +1,143 @@
import { page, userEvent } from "@vitest/browser/context";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { afterEach, beforeEach, expect, test } from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { createDefaultPages } from "@webstudio-is/project-build";
import { coreMetas, elementComponent, type Instance } from "@webstudio-is/sdk";
import { subscribeCommands } from "~/builder/shared/commands";
import {
$registeredComponentMetas,
$selectedPageId,
clearInstanceSelection,
selectInstance,
} from "~/shared/nano-states";
import { expectSlotsShareFragment } from "~/shared/slot-test-utils";
import { $instances, $pages, $project } from "~/shared/sync/data-stores";
import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
import { NavigatorTree } from "./navigator-tree";
const instance = (
id: string,
component: string,
label: string,
...children: string[]
): [string, Instance] => [
id,
{
type: "instance",
id,
component,
label,
children: children.map((value) => ({ type: "id", value })),
},
];
let container: HTMLDivElement;
let root: Root;
let unsubscribeCommands: () => void;
(
globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;
registerContainers();
beforeEach(() => {
$registeredComponentMetas.set(new Map(Object.entries(coreMetas)));
$pages.set(
createDefaultPages({ rootInstanceId: "body", homePageId: "home" })
);
$selectedPageId.set("home");
$project.set({ id: "slot-keyboard" } as Project);
$instances.set(
new Map([
instance("body", elementComponent, "Body", "slot-a", "slot-b"),
instance("slot-a", "Slot", "Slot A", "fragment"),
instance("slot-b", "Slot", "Slot B", "fragment"),
instance("fragment", "Fragment", "Shared fragment", "box", "heading"),
instance("box", elementComponent, "Drop Div"),
instance("heading", elementComponent, "Slot Heading"),
])
);
selectInstance(["box", "fragment", "slot-a", "body"]);
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root.render(
<TooltipProvider>
<NavigatorTree />
</TooltipProvider>
)
);
unsubscribeCommands = subscribeCommands();
});
afterEach(() => {
unsubscribeCommands();
act(() => root.unmount());
container.remove();
clearInstanceSelection();
$selectedPageId.set(undefined);
$pages.set(undefined);
$instances.set(new Map());
$project.set(undefined);
$registeredComponentMetas.set(new Map());
serverSyncStore.transactionManager.currentStack = [];
serverSyncStore.transactionManager.undoneStack = [];
serverSyncStore.popAll();
});
const selectedRows = () =>
Array.from(
container.querySelectorAll("[data-tree-button][aria-selected='true']"),
(button) => button.textContent?.trim()
);
test("Shift+ArrowDown selects exactly one additional row in the shared Slot", async () => {
await act(async () =>
page.getByRole("button", { name: "Drop Div", exact: true }).click()
);
expect(selectedRows()).toEqual(["Drop Div"]);
await act(async () => userEvent.keyboard("{Shift>}{ArrowDown}{/Shift}"));
expect(selectedRows()).toEqual(["Drop Div", "Slot Heading"]);
await expect
.element(page.getByRole("button", { name: "Slot Heading", exact: true }))
.toHaveFocus();
});
test.each([
{
label: "Drop Div",
key: "ArrowUp",
remaining: "heading",
order: ["box", "slot-a", "slot-b"],
},
{
label: "Slot Heading",
key: "ArrowDown",
remaining: "box",
order: ["slot-a", "heading", "slot-b"],
},
])(
"Ctrl+$key moves $label out of both Slot occurrences from Navigator focus",
async ({ label, key, remaining, order }) => {
await act(async () => {
await page.getByRole("button", { name: label, exact: true }).click();
await userEvent.keyboard(`{Control>}{${key}}{/Control}`);
});
const instances = $instances.get();
expectSlotsShareFragment(instances, ["slot-a", "slot-b"]);
expect(instances.get("body")?.children).toEqual(
order.map((value) => ({ type: "id", value }))
);
expect(instances.get("fragment")?.children).toEqual([
{ type: "id", value: remaining },
]);
}
);
@@ -926,6 +926,7 @@ const NavigatorRow = memo(
},
}}
buttonProps={{
"data-navigator-instance-id": item.instance.id,
onPointerDown: (event) => onPointerDown(item.selector, event),
onMouseEnter: () => {
$hoveredInstanceSelector.set(item.selector);
@@ -0,0 +1,188 @@
import { page, userEvent } from "@vitest/browser/context";
import { act } from "react-dom/test-utils";
import { afterEach, beforeEach, expect, test } from "vitest";
import { TooltipProvider } from "@webstudio-is/design-system";
import "@webstudio-is/design-system/global.css";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { Project } from "@webstudio-is/project";
import type { Asset } from "@webstudio-is/sdk";
import {
createAssetFolderFixture,
createAssetFoldersFixture,
} from "@webstudio-is/sdk/testing";
import { $authPermit } from "~/shared/nano-states";
import {
$assetFolders,
$assets,
$pages,
$project,
} from "~/shared/sync/data-stores";
import { registerContainers, serverSyncStore } from "~/shared/sync/sync-stores";
import { AssetManager } from "./asset-manager";
import { createAssetManagerTestRenderer } from "./test-utils";
const renderer = createAssetManagerTestRenderer();
registerContainers();
const asset = (id: string): Asset => ({
id,
projectId: "asset-folders",
name: `${id}.txt`,
format: "txt",
type: "file",
size: 1,
createdAt: "2026-01-01T00:00:00.000Z",
meta: {},
});
beforeEach(() => {
$authPermit.set("build");
$pages.set(createDefaultPages({ rootInstanceId: "body" }));
$project.set({ id: "asset-folders" } as Project);
$assetFolders.set(
createAssetFoldersFixture(
createAssetFolderFixture({ id: "parent", name: "Parent" }),
createAssetFolderFixture({
id: "child",
name: "Child",
parentId: "parent",
})
)
);
$assets.set(
new Map([
["first", asset("first")],
["second", asset("second")],
])
);
renderer.render(
<TooltipProvider>
<div style={{ width: 400, height: 500, display: "flex" }}>
<AssetManager canManageFolders />
</div>
</TooltipProvider>
);
});
afterEach(() => {
renderer.cleanup();
$assetFolders.set(new Map());
$assets.set(new Map());
$pages.set(undefined);
$project.set(undefined);
serverSyncStore.transactionManager.currentStack = [];
serverSyncStore.transactionManager.undoneStack = [];
serverSyncStore.popAll();
});
test("dragging a selected asset into a folder moves the entire selection", async () => {
const first = page.getByTitle("first.txt");
const second = page.getByTitle("second.txt");
const folder = page.getByRole("button", {
name: "Folder Parent",
exact: true,
});
await act(async () => first.click());
await act(async () => second.click({ modifiers: ["ControlOrMeta"] }));
expect(page.getByRole("option", { selected: true }).elements()).toHaveLength(
2
);
await act(async () => userEvent.dragAndDrop(second, folder));
await expect.element(first).not.toBeInTheDocument();
await expect.element(second).not.toBeInTheDocument();
await act(async () => folder.dblClick());
await expect.element(first).toBeVisible();
await expect.element(second).toBeVisible();
});
test("asset settings move to the selected subfolder only after leaving the folder selector", async () => {
const first = page.getByTitle("first.txt");
await act(async () => {
await first.hover();
await page.getByRole("button", { name: "Actions for first.txt" }).click();
await page.getByRole("menuitem", { name: "Settings" }).click();
});
const settings = page.getByText("Asset settings", { exact: true });
const selectFolder = async (label: string, name: string) => {
await act(async () => {
await page.getByRole("combobox", { name: label, exact: true }).click();
await page.getByRole("option", { name, exact: true }).click();
});
await expect.element(settings).toBeVisible();
expect($assets.get().get("first")?.folderId).toBeUndefined();
};
await selectFolder("Folder", "Parent");
await selectFolder("Asset subfolder level 1", "Child");
await act(async () => page.getByRole("textbox", { name: "Name" }).click());
await expect.element(settings).not.toBeInTheDocument();
expect($assets.get().get("first")?.folderId).toBe("child");
await act(async () =>
page.getByRole("button", { name: "Folder Parent" }).dblClick()
);
await act(async () =>
page.getByRole("button", { name: "Folder Child" }).dblClick()
);
await expect.element(first).toBeVisible();
});
test("dragging a selected folder into a folder moves the entire selection", async () => {
act(() => {
$assetFolders.set(
createAssetFoldersFixture(
createAssetFolderFixture({ id: "parent", name: "Parent" }),
createAssetFolderFixture({ id: "alpha", name: "Alpha" }),
createAssetFolderFixture({ id: "bravo", name: "Bravo" })
)
);
});
const alpha = page.getByRole("button", { name: "Folder Alpha", exact: true });
const bravo = page.getByRole("button", { name: "Folder Bravo", exact: true });
const parent = page.getByRole("button", {
name: "Folder Parent",
exact: true,
});
await act(async () => alpha.click());
await act(async () => bravo.click({ modifiers: ["ControlOrMeta"] }));
expect(page.getByRole("option", { selected: true }).elements()).toHaveLength(
2
);
await act(async () => userEvent.dragAndDrop(bravo, parent));
await expect.element(alpha).not.toBeInTheDocument();
await expect.element(bravo).not.toBeInTheDocument();
await act(async () => parent.dblClick());
await expect.element(alpha).toBeVisible();
await expect.element(bravo).toBeVisible();
});
test("the context menu moves all selected assets into the chosen folder", async () => {
const first = page.getByTitle("first.txt");
const second = page.getByTitle("second.txt");
await act(async () => first.click());
await act(async () => second.click({ modifiers: ["ControlOrMeta"] }));
await act(async () => second.click({ button: "right" }));
await act(async () =>
page.getByRole("menuitem", { name: "Move", exact: true }).click()
);
const dialog = page.getByRole("dialog", { name: "Move items" });
await act(async () =>
dialog.getByRole("combobox", { name: "Folder", exact: true }).click()
);
await act(async () =>
page.getByRole("option", { name: "Parent", exact: true }).click()
);
await act(async () =>
dialog.getByRole("button", { name: "Move", exact: true }).click()
);
await expect.element(first).not.toBeInTheDocument();
await expect.element(second).not.toBeInTheDocument();
await act(async () =>
page.getByRole("button", { name: "Folder Parent", exact: true }).dblClick()
);
await expect.element(first).toBeVisible();
await expect.element(second).toBeVisible();
});
+1 -1
View File
@@ -186,7 +186,7 @@ builder_backend_write_schema_snapshot() {
# Dump only the application-owned public schema so the snapshot can be
# restored without replacing database-owned schemas.
if builder_compose exec -T db \
sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --schema=public --schema-only --clean --if-exists --no-owner --no-privileges --restrict-key=webstudioE2ESchema' \
sh -c 'PGPASSWORD="$POSTGRES_PASSWORD" pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --schema=public --schema-only --clean --if-exists --no-owner --no-privileges' \
>"$temporary_snapshot"; then
mv "$temporary_snapshot" "$SCHEMA_SNAPSHOT"
else
+7 -9
View File
@@ -17,7 +17,7 @@ used by Preview tests.
In CI, the build job caches those compiled files. A later E2E-only change can
restore them after dependency setup; changes outside `apps/builder/e2e` still
compile Builder before the ten shards download the build artifact.
compile Builder before the five shards download the build artifact.
The schema snapshot is generated from the regular migration pipeline and
committed at `e2e/schema/schema-<fingerprint>.sql`. When a migration or backend
@@ -95,19 +95,17 @@ each invocation.
- Keep tests in a file independent even though Playwright runs them in
declaration order by default.
CI discovers isolated Playwright shards from filename tags. Each shard uses
three workers, except shard 5 uses two to avoid overlapping MCP browser launches.
Files are assigned by measured CI duration to keep the slowest job short:
CI runs five isolated Playwright shards with four workers each. Files have a
fixed assignment based on measured CI duration to keep the slowest job short:
```txt
pages-actions.[shard-3].e2e.ts
```
Every E2E filename must contain at least one unique shard tag. CI derives its
matrix from those tags, so adding or removing a shard does not require editing
the workflow. Files with multiple tags are partitioned across those shards. All
files selected by a shard must use the same set of tags. Rebalance by changing
filename tags when measured job durations drift.
Every E2E filename in CI must contain one shard tag. The build job checks that
the tags match the five shards in the workflow. Rebalance by changing filename
tags when measured job durations drift.
Suites may opt into parallel mode only when every worker creates uniquely named
setup data and the tests do not depend on each other's mutations.
+8
View File
@@ -107,6 +107,14 @@ export const insertAsset = async (row: Tables["Asset"]["Insert"]) => {
);
};
export const insertAssetFolders = async (
rows: Tables["AssetFolder"]["Insert"][]
) => {
return throwIfError(
await postgrest.from("AssetFolder").insert(rows).select()
);
};
export const loadDevBuild = async ({
projectId,
}: {
@@ -1 +1,7 @@
# Valid MDX sibling
<MissingE2ETemplate />
Valid content after the missing template.
<LifecycleCard>Authored lifecycle card</LifecycleCard>
@@ -1,5 +0,0 @@
# Valid MDX sibling
<MissingE2ETemplate />
Valid content after the missing template.
@@ -0,0 +1,98 @@
import { randomUUID } from "node:crypto";
import type { BrowserContext, Page } from "@playwright/test";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import type { Instance } from "@webstudio-is/sdk";
import { createSeededBuilderProject } from "./builder-project";
export const pageTemplateName = "Content Page Template";
export const pageTemplateText = "Content page template heading";
export const createBuilderEditingProject = ({
context,
page,
name,
devPlan,
includePageTemplate = false,
}: {
context: BrowserContext;
page?: Page;
name: string;
devPlan?: string;
includePageTemplate?: boolean;
}) =>
createSeededBuilderProject({
context,
page,
email: `${name}@webstudio.test`,
title: name,
devPlan,
builderToken: `${name}-${randomUUID()}-builder-token`,
createBuildUpdate: (build) => {
const pages = migratePages(JSON.parse(build.pages));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected the fixture home page");
}
home.rootInstanceId = "body";
const instances: Instance[] = [
{
type: "instance",
id: "body",
component: "ws:element",
tag: "body",
children: [{ type: "id", value: "initial-content" }],
},
{
type: "instance",
id: "initial-content",
component: "ws:element",
tag: "p",
children: [{ type: "text", value: "Initial content" }],
},
];
if (includePageTemplate) {
const rootInstanceId = "page-template-body";
pages.pageTemplates = new Map([
[
"content-page-template",
{
id: "content-page-template",
rootInstanceId,
name: pageTemplateName,
title: JSON.stringify(pageTemplateName),
meta: {},
},
],
]);
instances.push(
{
type: "instance",
id: rootInstanceId,
component: "ws:element",
tag: "body",
children: [{ type: "id", value: "page-template-heading" }],
},
{
type: "instance",
id: "page-template-heading",
component: "ws:element",
tag: "h1",
children: [{ type: "text", value: pageTemplateText }],
}
);
}
return {
pages: JSON.stringify(serializePages(pages)),
instances: JSON.stringify(instances),
dataSources: "[]",
props: "[]",
resources: "[]",
styleSources: "[]",
styleSourceSelections: "[]",
styles: "[]",
};
},
});
+12 -2
View File
@@ -1,4 +1,4 @@
import type { BrowserContext } from "@playwright/test";
import type { BrowserContext, Page } from "@playwright/test";
import { insertAuthorizationToken, loadDevBuild, updateBuild } from "../db";
import { createProjectThroughApi } from "./create-project";
@@ -7,18 +7,28 @@ type BuildUpdate = Omit<Parameters<typeof updateBuild>[1], "version">;
export const createSeededBuilderProject = async ({
context,
page,
email,
title,
devPlan,
builderToken,
createBuildUpdate,
}: {
context: BrowserContext;
page?: Page;
email: string;
title: string;
devPlan?: string;
builderToken: string;
createBuildUpdate: (build: Build) => BuildUpdate | Promise<BuildUpdate>;
}) => {
const projectId = await createProjectThroughApi({ context, email, title });
const projectId = await createProjectThroughApi({
context,
page,
email,
title,
devPlan,
});
const build = await loadDevBuild({ projectId });
await updateBuild(build.id, {
...(await createBuildUpdate(build)),
@@ -1,4 +1,7 @@
import { serializedPages } from "@webstudio-is/project-migrations/pages";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import { breakpoint } from "@webstudio-is/sdk/schema";
import { z } from "zod";
import {
insertAsset,
insertAuthorizationToken,
@@ -108,11 +111,7 @@ const pageTemplateFontSize = "38px";
const inlineImageHeadingText = "Heading with protected image";
const getBaseBreakpointId = (breakpoints: string) => {
const parsedBreakpoints = JSON.parse(breakpoints) as Array<{
id: string;
minWidth?: number;
maxWidth?: number;
}>;
const parsedBreakpoints = z.array(breakpoint).parse(JSON.parse(breakpoints));
return (
parsedBreakpoints.find(
(breakpoint) =>
@@ -800,17 +799,9 @@ const createContentModeBuildData = ({
},
];
const nextPages = JSON.parse(pages) as {
homePageId: string;
formComponentIdentityVersion?: number;
pages: Array<{ id: string; rootInstanceId: string }>;
pageTemplates?: Array<{
id: string;
name: string;
title: string;
rootInstanceId: string;
meta: Record<string, unknown>;
}>;
const nextPages = {
...serializedPages.parse(JSON.parse(pages)),
formComponentIdentityVersion: 1,
};
const homePage = nextPages.pages.find(
(page) => page.id === nextPages.homePageId
@@ -821,9 +812,12 @@ const createContentModeBuildData = ({
homePage.rootInstanceId = rootInstanceId;
// Tests insert canonical managed Forms later. The seeded resource examples
// remain WebhookForms because their action props use the legacy format.
nextPages.formComponentIdentityVersion = 1;
const pageTemplates = nextPages.pageTemplates ?? [];
if (!Array.isArray(pageTemplates)) {
throw new Error("Expected page templates to be an array");
}
nextPages.pageTemplates = [
...(nextPages.pageTemplates ?? []),
...pageTemplates,
{
id: pageTemplateId,
name: pageTemplateName,
@@ -1,10 +1,11 @@
import type { BrowserContext } from "@playwright/test";
import type { BrowserContext, Page } from "@playwright/test";
import { measure } from "../perf";
import { prepareExistingContentModeProject } from "./content-mode-project";
import { createProjectThroughApi } from "./create-project";
type ContentModeProjectOptions = {
context: BrowserContext;
page?: Page;
email?: string;
title?: string;
devPlan?: string;
@@ -16,6 +17,7 @@ type ContentModeProjectOptions = {
export const createContentModeProject = async ({
context,
page,
email = "content-mode-e2e@webstudio.test",
title = "Content Mode E2E",
devPlan,
@@ -26,7 +28,7 @@ export const createContentModeProject = async ({
}: ContentModeProjectOptions) => {
const projectId = await measure(
"content mode fixture login/create project",
() => createProjectThroughApi({ context, email, title, devPlan })
() => createProjectThroughApi({ context, page, email, title, devPlan })
);
return await measure("content mode fixture prepare project", async () => {
+22 -7
View File
@@ -1,20 +1,30 @@
import type { BrowserContext, Page } from "@playwright/test";
import type { BrowserContext, Page, Route } from "@playwright/test";
import env from "../../app/env/env.server";
import { getWorkerEmail } from "../flows/dashboard";
import { dashboardUrl } from "../test";
const openApiOrigin = async (page: Page, keepRoute: boolean) => {
const originUrl = `${dashboardUrl}/__e2e_origin`;
const fulfillOrigin = (route: Route) =>
route.fulfill({ contentType: "text/html", body: "<!doctype html>" });
await page.route(originUrl, fulfillOrigin);
try {
await page.goto(originUrl);
} finally {
if (keepRoute === false) {
await page.unroute(originUrl, fulfillOrigin);
}
}
};
const apiPages = new WeakMap<BrowserContext, Promise<Page>>();
const getApiPage = (context: BrowserContext) => {
let page = apiPages.get(context);
if (page === undefined) {
page = (async () => {
const page = await context.newPage();
const originUrl = `${dashboardUrl}/__e2e_origin`;
try {
await page.route(originUrl, (route) =>
route.fulfill({ contentType: "text/html", body: "<!doctype html>" })
);
await page.goto(originUrl);
await openApiOrigin(page, true);
return page;
} catch (error) {
await page.close();
@@ -28,11 +38,13 @@ const getApiPage = (context: BrowserContext) => {
export const createProjectThroughApi = async ({
context,
page: workflowPage,
email,
title,
devPlan,
}: {
context: BrowserContext;
page?: Page;
email: string;
title: string;
devPlan?: string;
@@ -43,7 +55,10 @@ export const createProjectThroughApi = async ({
if (devPlan !== undefined) {
await context.clearCookies();
}
const page = await getApiPage(context);
const page = workflowPage ?? (await getApiPage(context));
if (workflowPage !== undefined) {
await openApiOrigin(workflowPage, false);
}
await page.evaluate(
async ({ email, devPlan, secret }) => {
const loginPage = await fetch("/login");
+13 -9
View File
@@ -1,6 +1,9 @@
import { randomUUID } from "node:crypto";
import type { SerializedPages } from "@webstudio-is/project-migrations/pages";
import type { Instance, Prop } from "@webstudio-is/sdk";
import type { BrowserContext, Page } from "@playwright/test";
import { serializedPages } from "@webstudio-is/project-migrations/pages";
import type { Instance } from "@webstudio-is/sdk";
import { instance, prop } from "@webstudio-is/sdk/schema";
import { z } from "zod";
import { loadDevBuild } from "../db";
import { createSeededBuilderProject } from "./builder-project";
@@ -29,8 +32,8 @@ const element = (
children,
});
const seedBuild = (serializedPages: string) => {
const pages = JSON.parse(serializedPages) as SerializedPages;
const seedBuild = (pagesJson: string) => {
const pages = serializedPages.parse(JSON.parse(pagesJson));
const home = pages.pages.find(({ id }) => id === pages.homePageId);
const root = pages.folders.find(({ id }) => id === pages.rootFolderId);
if (home === undefined || root === undefined) {
@@ -111,10 +114,12 @@ const seedBuild = (serializedPages: string) => {
export const createDragProject = async (
context: BrowserContext,
name: string
name: string,
page?: Page
) => {
return await createSeededBuilderProject({
context,
page,
email: `drag-${name}@webstudio.test`,
title: `Drag ${name}`,
builderToken: `drag-${name}-${randomUUID()}-builder-token`,
@@ -125,8 +130,8 @@ export const createDragProject = async (
export const loadDragProjectData = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
return {
instances: JSON.parse(build.instances) as Instance[],
props: JSON.parse(build.props) as Prop[],
instances: z.array(instance).parse(JSON.parse(build.instances)),
props: z.array(prop).parse(JSON.parse(build.props)),
};
};
@@ -144,6 +149,5 @@ export const loadChildIds = async (projectId: string, parentId: string) =>
export const loadPages = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
return JSON.parse(build.pages) as SerializedPages;
return serializedPages.parse(JSON.parse(build.pages));
};
import type { BrowserContext } from "@playwright/test";
@@ -1,5 +1,6 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { measure } from "../perf";
// Load the CLI in this isolated runner; Builder's tsconfig does not include
// the CLI's import-attribute module setting.
@@ -24,18 +25,30 @@ if (!Number.isInteger(port) || !Number.isInteger(receiverPort)) {
throw new Error("Expected Preview and receiver ports");
}
const project = await preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
});
await writeFile(
join(
project.cwd,
"app/__generated__/$resources.managed-form-fetch.server.ts"
),
`import { getDeniedResourceHostnames } from "@webstudio-is/sdk/protected-resource-fetch";
const [, , , , prepareModuleUrl, projectId, ...prepareArgs] = process.argv;
if (prepareModuleUrl !== undefined && projectId !== undefined) {
const { preparePreviewBundle } = await import(prepareModuleUrl);
const prepared = await preparePreviewBundle(projectId, ...prepareArgs);
await writeFile("preview-prepared.json", JSON.stringify(prepared));
}
const project = await measure<{ cwd: string }>(
"generated Form Preview project preparation",
() =>
preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
})
);
await measure("generated Form Preview test adapter setup", () =>
writeFile(
join(
project.cwd,
"app/__generated__/$resources.managed-form-fetch.server.ts"
),
`import { getDeniedResourceHostnames } from "@webstudio-is/sdk/protected-resource-fetch";
import { createNodeProtectedResourceFetch } from "@webstudio-is/sdk/protected-resource-fetch-node";
export const createManagedFormEmailSender = () => undefined;
@@ -63,11 +76,18 @@ export const createManagedFormResourceFetch = ({ request, projectDomain }: { req
});
};
`
)
);
await measure("generated Form Preview production build", () =>
buildPreparedPreview(project)
);
const preview = await measure(
"generated Form Preview server process start",
async () =>
startPreviewServer({
host: "127.0.0.1",
port,
cwd: project.cwd,
})
);
await buildPreparedPreview(project);
const preview = startPreviewServer({
host: "127.0.0.1",
port,
cwd: project.cwd,
});
await waitForPreviewExit(preview.process);
@@ -1,6 +1,7 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import {
migratePages,
serializePages,
@@ -24,10 +25,17 @@ import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { mkdir, writeFile } from "node:fs/promises";
import { loadDevBuild, updateBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
const commands = new Set([
"create-page",
"insert-component",
"insert-fragment",
"create-resource",
"update-resource",
"update-props",
"list-instances",
"inspect-instance",
"list-resources",
@@ -53,11 +61,7 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
const author = async (projectId: string) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -236,7 +240,7 @@ const author = async () => {
return payload.data;
};
try {
const authorDefaultContact = async () => {
const inserted = await call("insert-component", {
parentInstanceId: home.rootInstanceId,
component: "form",
@@ -278,17 +282,179 @@ const author = async () => {
expect.objectContaining({ name: "action", value: actions }),
])
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
ownerResourceId: owner.id,
visitorResourceId: visitor.id,
})}\n`
return { formId, ownerResourceId: owner.id, visitorResourceId: visitor.id };
};
const authorReadableFormData = async () => {
const inserted = await call("insert-component", {
parentInstanceId: home.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
if (formId === undefined) {
throw new Error("Expected the inserted Form ID");
}
await call("refresh");
const form = { id: formId };
await call("insert-fragment", {
parentInstanceId: form.id,
fragment:
'<Input name="profile.city" /><Input name="tag" /><Input name="tag" /><Input name="password" type="password" /><Input name="upload" type="file" />',
});
const resources = await call("list-resources", {
scopeInstanceId: form.id,
});
const emails = resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>;
const owner = emails.find(({ name }) => name === "Email to owner");
const visitor = emails.find(({ name }) => name === "Email to visitor");
if (owner === undefined || visitor === undefined) {
throw new Error("Expected both default Form Email Resources");
}
const inspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
const formDataId = (
inspection.props as Array<{ name: string; value: unknown }>
).find(({ name }) => name === "formData")?.value;
if (typeof formDataId !== "string") {
throw new Error("Expected Form data parameter");
}
const expression = `${encodeDataSourceVariable(formDataId)}.toString()`;
await call("update-resource", {
resourceId: owner.id,
values: { email: { body: expression } },
});
await call("update-props", {
updates: [
{
instanceId: form.id,
name: "action",
type: "json",
value: [{ dataSourceId: owner.dataSourceId }],
},
],
});
const actions = [{ dataSourceId: owner.dataSourceId }];
const updatedInspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
expect(updatedInspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "action", value: actions }),
])
);
return { formId, ownerResourceId: owner.id, expression };
};
const authorFormContext = async () => {
await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
fragment:
'<Link href="/contact/autumn?private=omit">Open contact Form</Link>',
});
const page = await call("create-page", {
name: "Form context",
path: "/contact/:slug",
});
const inserted = await call("insert-component", {
parentInstanceId: page.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
if (formId === undefined) {
throw new Error("Expected the inserted Form ID");
}
await call("refresh");
const formInspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
const formProps = formInspection.props as Array<{
name: string;
value: unknown;
}>;
const variable = (name: string) => {
const id = formProps.find((prop) => prop.name === name)?.value;
if (typeof id !== "string") {
throw new Error(`Expected the ${name} Form parameter`);
}
return encodeDataSourceVariable(id);
};
const formData = variable("formData");
const browserInfo = variable("browserInfo");
const resource = await call("create-resource", {
resource: {
name: "Context receiver",
method: "post",
url: "https://mcp-delivery.example/submit",
headers: [],
},
scopeInstanceId: formId,
dataSourceName: "Context receiver",
exposeAsDataSource: true,
});
await call("update-resource", {
resourceId: resource.resourceId,
scopeInstanceId: formId,
exposeAsDataSource: true,
values: {
bodyFormat: "json",
body: `{ name: ${formData}.name, email: ${formData}.email, slug: system.params.slug, browser: { ip: ${browserInfo}.ip ?? null, userAgent: ${browserInfo}.userAgent ?? null, language: ${browserInfo}.language ?? null, referrer: ${browserInfo}.referrer ?? null } }`,
headers: [
{ name: "X-Form-Language", value: `${browserInfo}.language ?? ""` },
],
},
});
await call("update-props", {
updates: [
{
instanceId: formId,
name: "action",
type: "json",
value: [{ dataSourceId: resource.dataSourceId }],
},
],
});
await call("refresh");
const inspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
expect(inspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "action",
type: "json",
}),
])
);
return { formId };
};
try {
const formData = await authorReadableFormData();
const contact = await authorDefaultContact();
const context = await authorFormContext();
return { formData, contact, context };
} finally {
await client.close();
await server.close();
}
};
await author();
export const preparePreviewBundle = async (projectId: string) => {
const authored = await author(projectId);
const build = await loadDevBuild({ projectId });
await mkdir(".webstudio", { recursive: true });
await writeFile(
".webstudio/data.json",
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
return authored;
};
@@ -26,23 +26,23 @@ import {
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
import { authorFormQueries } from "./mcp-form-query-author";
import { authorManagedForm } from "./mcp-managed-form-author";
const projectId = process.argv[2];
const mode = process.argv[3];
const formId = process.argv[4];
if (
projectId === undefined ||
(mode !== "bind" &&
mode !== "reset" &&
mode !== "partial" &&
mode !== "empty") ||
formId === undefined
) {
throw new Error(
"Expected a project ID, bind, reset, partial, or empty mode, and Form ID"
);
if (projectId === undefined) {
throw new Error("Expected a project ID");
}
const { formId: boundFormId } = await authorManagedForm(projectId, {
mode: "email",
});
const { formId: partialFormId } = await authorManagedForm(projectId, {
mode: "email",
});
expect(boundFormId).not.toBe(partialFormId);
const commands = new Set([
"list-instances",
"list-resources",
@@ -71,211 +71,267 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
let build = await loadDevBuild({ projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
let remote: ProjectSessionRemoteSnapshot = {
projectId,
buildId: build.id,
version: build.version,
state: createBuilderStateFromBuildData({
pages: migratePages(parse("pages")),
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
projectSettings: parse("projectSettings"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
}),
};
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
projectSettings: JSON.stringify(snapshot.projectSettings),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId,
compatibilityVersion: "mcp-email-binding-e2e-v1",
runtimeContext: { createId: () => `mcp-email-binding-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions).state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
const configureBinding = async (
mode: "bind" | "partial" | "reset" | "empty",
formId: string
) => {
let build = await loadDevBuild({ projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
let remote: ProjectSessionRemoteSnapshot = {
projectId,
buildId: build.id,
version: build.version,
state: createBuilderStateFromBuildData({
pages: migratePages(parse("pages")),
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
projectSettings: parse("projectSettings"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
}),
getCompatibility: async () => ({
sessionVersion: "mcp-email-binding-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-email-binding-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-email-binding-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = { ...(input as object), projectId };
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
const client = new Client({ name: "mcp-email-binding-e2e", version: "1.0.0" });
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
const form = { id: formId };
const resources = await call("list-resources", {
scopeInstanceId: form.id,
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
projectSettings: JSON.stringify(snapshot.projectSettings),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId,
compatibilityVersion: "mcp-email-binding-e2e-v1",
runtimeContext: { createId: () => `mcp-email-binding-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions)
.state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
}),
getCompatibility: async () => ({
sessionVersion: "mcp-email-binding-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-email-binding-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-email-binding-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const projectEmail = (
resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>
).find(({ name }) => name === "Email to owner");
if (projectEmail === undefined) {
throw new Error("Expected the contact Form Project Email Resource");
}
if (mode === "partial" || mode === "empty") {
const visitorEmail = (
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = { ...(input as object), projectId };
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({
name: "mcp-email-binding-e2e",
version: "1.0.0",
});
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
const form = { id: formId };
const resources = await call("list-resources", {
scopeInstanceId: form.id,
});
const projectEmail = (
resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>
).find(({ name }) => name === "Email to visitor");
if (visitorEmail === undefined) {
throw new Error("Expected the contact Form visitor Email Resource");
).find(({ name }) => name === "Email to owner");
if (projectEmail === undefined) {
throw new Error("Expected the contact Form Project Email Resource");
}
const settings = {
recipientMode: "visitor",
visitorEmailField: "email",
senderExpression: '"Contact Team <team@example.test>"',
includeAttachments: false,
subject: '"Thanks for writing"',
body: '"Initial confirmation"',
};
if (mode === "partial") {
if (mode === "partial" || mode === "empty") {
const visitorEmail = (
resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>
).find(({ name }) => name === "Email to visitor");
if (visitorEmail === undefined) {
throw new Error("Expected the contact Form visitor Email Resource");
}
const settings = {
recipientMode: "visitor",
visitorEmailField: "email",
senderExpression: '"Contact Team <team@example.test>"',
includeAttachments: false,
subject: '"Thanks for writing"',
body: '"Initial confirmation"',
};
if (mode === "partial") {
await call("update-resource", {
resourceId: visitorEmail.id,
values: { email: settings },
});
await call("update-props", {
updates: [
{
instanceId: form.id,
name: "action",
type: "json",
value: [{ dataSourceId: visitorEmail.dataSourceId }],
},
],
});
}
const body = mode === "partial" ? '"Custom confirmation"' : '""';
await call("update-resource", {
resourceId: visitorEmail.id,
values: { email: settings },
values: { email: { body } },
});
await call("refresh");
const persistedResources = JSON.parse(
(await loadDevBuild({ projectId })).resources
) as Array<{ id: string; email?: Record<string, unknown> }>;
expect(
persistedResources.find(({ id }) => id === visitorEmail.id)?.email
).toMatchObject({ ...settings, body });
} else if (mode === "bind") {
const inspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
const formDataId = (
inspection.props as Array<{ name: string; value: unknown }>
).find(({ name }) => name === "formData")?.value;
if (typeof formDataId !== "string") {
throw new Error("Expected the Form data parameter");
}
const formData = encodeDataSourceVariable(formDataId);
await call("update-resource", {
resourceId: projectEmail.id,
values: {
email: {
recipientMode: "custom",
recipientsExpression: `${formData}.email`,
senderExpression: `${formData}.email`,
subject: `\`Bound: \${${formData}.subject}\``,
body: `\`Message from \${${formData}.name}: \${${formData}.message}\``,
},
},
});
await call("update-props", {
updates: [
@@ -283,119 +339,87 @@ try {
instanceId: form.id,
name: "action",
type: "json",
value: [{ dataSourceId: visitorEmail.dataSourceId }],
value: [{ dataSourceId: projectEmail.dataSourceId }],
},
],
});
} else {
const savedResource = (
JSON.parse((await loadDevBuild({ projectId })).resources) as Array<{
id: string;
name: string;
control?: string;
method: string;
url: string;
headers: Array<{ name: string; value: string }>;
}>
).find(({ id }) => id === projectEmail.id);
if (savedResource === undefined) {
throw new Error("Expected the saved Project Email Resource");
}
const { id: _id, ...resource } = savedResource;
await call("upsert-resource", {
resourceId: projectEmail.id,
dataSourceId: projectEmail.dataSourceId,
scopeInstanceId: form.id,
resource: { ...resource, email: { recipientMode: "project" } },
});
await call("update-project-settings", {
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
}
const body = mode === "partial" ? '"Custom confirmation"' : '""';
await call("update-resource", {
resourceId: visitorEmail.id,
values: { email: { body } },
});
await call("refresh");
const persistedResources = JSON.parse(
(await loadDevBuild({ projectId })).resources
) as Array<{ id: string; email?: Record<string, unknown> }>;
expect(
persistedResources.find(({ id }) => id === visitorEmail.id)?.email
).toMatchObject({ ...settings, body });
} else if (mode === "bind") {
const inspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
const formDataId = (
inspection.props as Array<{ name: string; value: unknown }>
).find(({ name }) => name === "formData")?.value;
if (typeof formDataId !== "string") {
throw new Error("Expected the Form data parameter");
const persistedSettings = persistedResources.find(
({ id }) => id === projectEmail.id
)?.email;
if (mode === "partial" || mode === "empty") {
const visitorEmail = (
resources.resources as Array<{ id: string; name: string }>
).find(({ name }) => name === "Email to visitor");
expect(
persistedResources.find(({ id }) => id === visitorEmail?.id)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
senderExpression: '"Contact Team <team@example.test>"',
includeAttachments: false,
subject: '"Thanks for writing"',
body: mode === "partial" ? '"Custom confirmation"' : '""',
});
} else if (mode === "reset") {
expect(persistedSettings).toEqual({ recipientMode: "project" });
} else {
expect(persistedSettings).toMatchObject({
recipientMode: "custom",
recipientsExpression: expect.any(String),
senderExpression: expect.any(String),
subject: expect.any(String),
body: expect.any(String),
});
}
const formData = encodeDataSourceVariable(formDataId);
await call("update-resource", {
resourceId: projectEmail.id,
values: {
email: {
recipientMode: "custom",
recipientsExpression: `${formData}.email`,
senderExpression: `${formData}.email`,
subject: `\`Bound: \${${formData}.subject}\``,
body: `\`Message from \${${formData}.name}: \${${formData}.message}\``,
},
},
});
await call("update-props", {
updates: [
{
instanceId: form.id,
name: "action",
type: "json",
value: [{ dataSourceId: projectEmail.dataSourceId }],
},
],
});
} else {
const savedResource = (
JSON.parse((await loadDevBuild({ projectId })).resources) as Array<{
id: string;
name: string;
control?: string;
method: string;
url: string;
headers: Array<{ name: string; value: string }>;
}>
).find(({ id }) => id === projectEmail.id);
if (savedResource === undefined) {
throw new Error("Expected the saved Project Email Resource");
}
const { id: _id, ...resource } = savedResource;
await call("upsert-resource", {
resourceId: projectEmail.id,
dataSourceId: projectEmail.dataSourceId,
scopeInstanceId: form.id,
resource: { ...resource, email: { recipientMode: "project" } },
});
await call("update-project-settings", {
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
} finally {
await client.close();
await server.close();
}
await call("refresh");
const persistedResources = JSON.parse(
(await loadDevBuild({ projectId })).resources
) as Array<{ id: string; email?: Record<string, unknown> }>;
const persistedSettings = persistedResources.find(
({ id }) => id === projectEmail.id
)?.email;
if (mode === "partial" || mode === "empty") {
const visitorEmail = (
resources.resources as Array<{ id: string; name: string }>
).find(({ name }) => name === "Email to visitor");
expect(
persistedResources.find(({ id }) => id === visitorEmail?.id)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
senderExpression: '"Contact Team <team@example.test>"',
includeAttachments: false,
subject: '"Thanks for writing"',
body: mode === "partial" ? '"Custom confirmation"' : '""',
});
} else if (mode === "reset") {
expect(persistedSettings).toEqual({ recipientMode: "project" });
} else {
expect(persistedSettings).toMatchObject({
recipientMode: "custom",
recipientsExpression: expect.any(String),
senderExpression: expect.any(String),
subject: expect.any(String),
body: expect.any(String),
});
}
process.stdout.write(`${JSON.stringify({ formId: form.id })}\n`);
} finally {
await client.close();
await server.close();
}
};
await configureBinding("bind", boundFormId);
await configureBinding("partial", partialFormId);
const query = await authorFormQueries(projectId);
const readPreviewBundle = async () =>
JSON.stringify(
createLocalBundleFromDevBuild(await loadDevBuild({ projectId }))
);
const initialBundle = await readPreviewBundle();
await configureBinding("reset", boundFormId);
await configureBinding("empty", partialFormId);
const updatedBundle = await readPreviewBundle();
process.stdout.write(
`${JSON.stringify({ boundFormId, partialFormId, query, initialBundle, updatedBundle })}\n`
);
@@ -0,0 +1,21 @@
import { mkdir, writeFile } from "node:fs/promises";
import { loadDevBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
import { authorManagedForm } from "./mcp-managed-form-author";
export const preparePreviewBundle = async (projectId: string) => {
const standard = await authorManagedForm(projectId, { mode: "email" });
const isolated = await authorManagedForm(projectId, {
mode: "email-isolation",
});
const combined = await authorManagedForm(projectId, {
mode: "email-http-combination",
});
const build = await loadDevBuild({ projectId });
await mkdir(".webstudio", { recursive: true });
await writeFile(
".webstudio/data.json",
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
return { standard, isolated, combined };
};
@@ -1,328 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts";
import {
createProjectSessionMcpServer,
type PublicMcpOperation,
} from "@webstudio-is/project-build/mcp";
import {
createProjectSession,
type ProjectSessionPersistedSnapshot,
type ProjectSessionRemoteSnapshot,
} from "@webstudio-is/project-build/project-session";
import {
applyBuilderPatchTransactions,
createBuilderBuildDataSnapshotFromState,
createBuilderStateFromBuildData,
} from "@webstudio-is/project-build/state";
import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
const commands = new Set([
"insert-component",
"insert-fragment",
"list-instances",
"inspect-instance",
"list-resources",
"list-variables",
"create-resource",
"update-resource",
"update-props",
"get-project-settings",
"update-project-settings",
]);
const operations: PublicMcpOperation[] = runtimeOperationContracts
.filter(({ command }) => commands.has(command))
.map((contract) => ({
command: contract.command,
id: contract.id,
method: contract.kind === "mutation" ? "mutation" : "query",
permit: contract.permit ?? "view",
description: contract.command,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
localCapable: true,
serverOnly: false,
readNamespaces: contract.readNamespaces,
writeNamespaces: contract.writeNamespaces,
invalidatesNamespaces: contract.invalidatesNamespaces,
retryOnConflict: contract.retryOnConflict,
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
const pages = migratePages(parse("pages"));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected a home page in the E2E fixture");
}
const initialState = createBuilderStateFromBuildData({
pages,
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
projectSettings: parse("projectSettings"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
});
let remote: ProjectSessionRemoteSnapshot = {
projectId: projectId,
buildId: build.id,
version: build.version,
state: initialState,
};
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
projectSettings: JSON.stringify(snapshot.projectSettings),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId: projectId,
compatibilityVersion: "mcp-preview-form-e2e-v1",
runtimeContext: { createId: () => `mcp-preview-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions)
.state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
}),
getCompatibility: async () => ({
sessionVersion: "mcp-preview-form-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-preview-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-preview-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = {
...(input as object),
projectId: projectId,
};
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({ name: "mcp-preview-form-e2e", version: "1.0.0" });
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
const inserted = await call("insert-component", {
parentInstanceId: home.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
if (formId === undefined) {
throw new Error("Expected the inserted Form ID");
}
await call("refresh");
const form = { id: formId };
await call("update-project-settings", {
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
const resources = await call("list-resources", {
scopeInstanceId: form.id,
});
const email = (
resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>
).find(({ name }) => name === "Email to owner");
if (email === undefined) {
throw new Error("Expected the Form's Email to owner Email Action");
}
await call("update-resource", {
resourceId: email.id,
values: {
email: {
recipientMode: "custom",
recipients: "combined@mcp.test",
subject: JSON.stringify("Combined action subject"),
body: JSON.stringify("Combined action exact body."),
},
},
});
const http = await call("create-resource", {
resource: {
name: "Combined HTTP action",
method: "post",
url: "https://mcp-delivery.example/submit",
headers: [],
},
scopeInstanceId: form.id,
dataSourceName: "Combined HTTP action",
exposeAsDataSource: true,
});
const actions = [
{ dataSourceId: email.dataSourceId },
{ dataSourceId: http.dataSourceId },
];
await call("update-props", {
updates: [
{ instanceId: form.id, name: "action", type: "json", value: actions },
],
});
await call("refresh");
const inspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
expect(inspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "action", value: actions }),
])
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
emailResourceId: email.id,
httpResourceId: http.resourceId,
})}\n`
);
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -1,5 +1,6 @@
import { writeFile } from "node:fs/promises";
import { rename, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { measure } from "../perf";
// Load the CLI in this isolated runner; Builder's tsconfig does not include
// the CLI's import-attribute module setting.
@@ -29,20 +30,39 @@ if (
throw new Error("Expected Preview, email receiver, and HTTP receiver ports");
}
const project = await preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
});
await writeFile(
join(
project.cwd,
"app/__generated__/$resources.managed-form-fetch.server.ts"
),
`import { createCloudflareManagedFormEmailSender, validateCloudflareManagedFormEmail } from "@webstudio-is/sdk/runtime";
const prepareModule = process.argv[5];
const authorProjectId = process.argv[6];
if (prepareModule !== undefined && authorProjectId !== undefined) {
const { preparePreviewBundle } = await import(prepareModule);
const prepared = await preparePreviewBundle(authorProjectId);
await writeFile("preview-prepared.json", JSON.stringify(prepared));
}
const project = await measure<{ cwd: string }>(
"MCP email HTTP Preview project preparation",
() =>
preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
})
);
const adapterPath = join(
project.cwd,
"app/__generated__/$resources.managed-form-fetch.server.ts"
);
await measure("MCP email HTTP Preview test adapter setup", async () => {
await rename(
adapterPath,
join(project.cwd, "app/__generated__/production-form-fetch.server.ts")
);
await writeFile(
adapterPath,
`import { createCloudflareManagedFormEmailSender, validateCloudflareManagedFormEmail } from "@webstudio-is/sdk/runtime";
import { getDeniedResourceHostnames } from "@webstudio-is/sdk/protected-resource-fetch";
import { createNodeProtectedResourceFetch } from "@webstudio-is/sdk/protected-resource-fetch-node";
import { createManagedFormResourceFetch as createProductionFormFetch } from "./production-form-fetch.server";
// This test-only RPC binding records payloads through the loopback capture server.
export const createManagedFormEmailSender = ({ formData, projectId }: { context: unknown; formData: FormData; projectId: string }) => createCloudflareManagedFormEmailSender({
@@ -63,29 +83,47 @@ export const createManagedFormEmailSender = ({ formData, projectId }: { context:
}, formData, projectId);
export const validateManagedFormEmail = validateCloudflareManagedFormEmail;
export const createManagedFormResourceFetch = ({ request, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
export const createManagedFormResourceFetch = ({ request, context, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
const previewHostname = new URL(request.url).hostname;
const productionFetch = createProductionFormFetch({ request, context, projectDomain });
const protectedFetch = createNodeProtectedResourceFetch({
deniedHostnames: getDeniedResourceHostnames([new URL(request.url).hostname, projectDomain]),
deniedHostnames: getDeniedResourceHostnames([previewHostname, projectDomain]),
});
const testFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const outgoing = new Request(input, init);
const destination = new URL(outgoing.url);
if (destination.hostname === previewHostname) {
return productionFetch(outgoing);
}
protectedFetch.validateDestination(destination);
if (destination.href !== "https://mcp-delivery.example/submit") {
if (
destination.href !== "https://mcp-delivery.example/submit" &&
destination.href !== "https://mcp-delivery.example/reject"
) {
throw new Error("Unexpected E2E HTTP destination");
}
return fetch(new Request("http://127.0.0.1:${httpPort}/submit", outgoing));
const receiver = new URL(destination.pathname, "http://127.0.0.1:${httpPort}");
return fetch(new Request(receiver, outgoing));
};
return Object.assign(testFetch, {
validateDestination: (url: URL) => protectedFetch.validateDestination(url),
validateDestination: (url: URL) => url.hostname === previewHostname
? productionFetch.validateDestination(url)
: protectedFetch.validateDestination(url),
});
};
`
);
await buildPreparedPreview(project);
const preview = startPreviewServer({
host: "127.0.0.1",
port,
cwd: project.cwd,
);
});
await measure("MCP email HTTP Preview production build", () =>
buildPreparedPreview(project)
);
const preview = await measure(
"MCP email HTTP Preview server process start",
async () =>
startPreviewServer({
host: "127.0.0.1",
port,
cwd: project.cwd,
})
);
await waitForPreviewExit(preview.process);
+60 -10
View File
@@ -1,5 +1,7 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { waitForGeneratedPreview } from "../flows/generated-app";
import { measure } from "../perf";
// Load the CLI in this isolated runner; Builder's tsconfig does not include
// the CLI's import-attribute module setting.
@@ -20,16 +22,26 @@ const { startPreviewServer, waitForPreviewExit } = await import(
const port = Number(process.argv[2]);
const emailPort = Number(process.argv[3]);
if (!Number.isInteger(port) || !Number.isInteger(emailPort)) {
const queryPort =
process.argv[4] === undefined ? undefined : Number(process.argv[4]);
if (
!Number.isInteger(port) ||
!Number.isInteger(emailPort) ||
(queryPort !== undefined && !Number.isInteger(queryPort))
) {
throw new Error("Expected Preview and local email receiver ports");
}
const project = await preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
});
const project = await measure<{ cwd: string }>(
"generated Email preview project preparation",
() =>
preparePreviewProject({
assets: false,
template: ["defaults", "react-router"],
generate: true,
source: "local",
})
);
await writeFile(
join(
project.cwd,
@@ -59,16 +71,54 @@ export const createManagedFormEmailSender = ({ formData, projectId }: { context:
export const validateManagedFormEmail = validateCloudflareManagedFormEmail;
export const createManagedFormResourceFetch = ({ request, projectDomain }: { request: Request; context: unknown; projectDomain?: string }) => {
return createNodeProtectedResourceFetch({
const protectedFetch = createNodeProtectedResourceFetch({
deniedHostnames: getDeniedResourceHostnames([new URL(request.url).hostname, projectDomain]),
});
${
queryPort === undefined
? "return protectedFetch;"
: `
const validateDestination = (url: URL) => {
if (
url.origin !== "https://mcp-delivery.example" ||
url.pathname !== "/submit" ||
[...url.searchParams.keys()].some((key) => key !== "tag") ||
url.hash !== ""
) {
throw new Error("Unexpected E2E Form query destination");
}
protectedFetch.validateDestination(url);
};
const captureQueryDelivery = async (input: RequestInfo | URL, init?: RequestInit) => {
const outgoing = new Request(input, init);
const destination = new URL(outgoing.url);
validateDestination(destination);
if (outgoing.method !== "POST") {
throw new Error("Expected an E2E Form query POST");
}
const target = new URL(destination.pathname + destination.search, "http://127.0.0.1:${queryPort}");
return fetch(new Request(target, outgoing));
};
return Object.assign(captureQueryDelivery, { validateDestination });`
}
};
`
);
await buildPreparedPreview(project);
await measure("generated Email preview production build", () =>
buildPreparedPreview(project)
);
const preview = startPreviewServer({
host: "127.0.0.1",
port,
cwd: project.cwd,
});
await waitForPreviewExit(preview.process);
await Promise.all([
waitForPreviewExit(preview.process),
measure("generated Email preview server readiness", () =>
waitForGeneratedPreview({
process: preview.process,
url: `http://127.0.0.1:${port}/`,
output: () => "",
})
),
]);
@@ -1,3 +1,4 @@
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
@@ -59,11 +60,11 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
export const authorFormActionCombination = async (
projectId: string,
mode?: string,
deliveryPath = "/submit"
) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -283,7 +284,7 @@ const author = async () => {
dataSourceName: name,
exposeAsDataSource: true,
});
if (process.argv[3] === "ten-actions") {
if (mode === "ten-actions") {
const created = [];
for (let index = 0; index < 11; index++) {
created.push(
@@ -330,23 +331,20 @@ const author = async () => {
expect.objectContaining({ name: "action", value: actions }),
])
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
resourceIds: created.slice(0, 10).map(({ resourceId }) => resourceId),
rejectedResourceId: created[10].resourceId,
})}\n`
);
return;
return {
formId: form.id,
resourceIds: created.slice(0, 10).map(({ resourceId }) => resourceId),
rejectedResourceId: created[10].resourceId,
};
}
const graphql = await createAction(
"First GraphQL action",
"/submit",
deliveryPath,
"graphql",
`{ query: "mutation Record($name: String!) { record(name: $name) }", variables: { name: ${formData}.name } }`
);
const middle = await createAction("Middle HTTP action", "/submit");
const http = await createAction("Last HTTP action", "/submit");
const middle = await createAction("Middle HTTP action", deliveryPath);
const http = await createAction("Last HTTP action", deliveryPath);
const actions = [
{ dataSourceId: graphql.dataSourceId },
{ dataSourceId: middle.dataSourceId },
@@ -367,18 +365,23 @@ const author = async () => {
expect.objectContaining({ name: "action", value: actions }),
])
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
graphqlResourceId: graphql.resourceId,
middleResourceId: middle.resourceId,
httpResourceId: http.resourceId,
})}\n`
);
return {
formId: form.id,
graphqlResourceId: graphql.resourceId,
middleResourceId: middle.resourceId,
httpResourceId: http.resourceId,
};
} finally {
await client.close();
await server.close();
}
};
await author();
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [, , projectId, mode] = process.argv;
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const result = await authorFormActionCombination(projectId, mode);
process.stdout.write(`${JSON.stringify(result)}\n`);
}
@@ -0,0 +1,32 @@
import { authorFormActionCombination } from "./mcp-form-action-combination-author";
import { authorFormCallbacks } from "./mcp-form-callbacks-author";
import { authorLegacyFormRoute } from "./mcp-legacy-form-route-author";
import { authorQuerySearch } from "./mcp-query-search-author";
const [, , projectId, managedPath, concurrencyPath] = process.argv;
if (
projectId === undefined ||
managedPath === undefined ||
concurrencyPath === undefined
) {
throw new Error(
"Expected a project ID and managed callback and concurrency paths"
);
}
const receiverUrl = "https://mcp-delivery.example/submit";
await authorFormCallbacks({ projectId, mode: "legacy", receiverUrl });
await authorFormCallbacks({
projectId,
mode: "managed",
receiverUrl,
path: managedPath,
});
await authorQuerySearch(projectId);
await authorLegacyFormRoute(projectId, receiverUrl);
const actions = await authorFormActionCombination(
projectId,
undefined,
concurrencyPath
);
process.stdout.write(`${JSON.stringify(actions)}\n`);
@@ -1,3 +1,4 @@
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
@@ -26,9 +27,11 @@ import {
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { authorQuerySearch } from "./mcp-query-search-author";
import { seedSavedLegacyForm } from "./saved-legacy-form";
const commands = new Set([
"create-page",
"insert-fragment",
"set-text-content",
"create-variable",
@@ -55,19 +58,19 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const mode = process.argv[3];
const receiverUrl = process.argv[4];
const verifyFieldChange = process.argv[5] === "field-change";
if ((mode !== "legacy" && mode !== "managed") || receiverUrl === undefined) {
throw new Error("Expected legacy/managed mode and a local receiver URL");
}
const author = async () => {
export const authorFormCallbacks = async ({
projectId,
mode,
receiverUrl,
path,
verifyFieldChange = false,
}: {
projectId: string;
mode: "legacy" | "managed";
receiverUrl: string;
path?: string;
verifyFieldChange?: boolean;
}) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -98,6 +101,7 @@ const author = async () => {
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const idPrefix = `mcp-callback-${mode}`;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
@@ -116,7 +120,7 @@ const author = async () => {
const session = createProjectSession({
projectId: projectId,
compatibilityVersion: "mcp-form-callbacks-e2e-v1",
runtimeContext: { createId: () => `mcp-callback-${nextId++}` },
runtimeContext: { createId: () => `${idPrefix}-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
@@ -170,7 +174,7 @@ const author = async () => {
state: remote.state,
input,
context: {
createId: () => `mcp-callback-server-${nextId++}`,
createId: () => `${idPrefix}-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
@@ -181,7 +185,7 @@ const author = async () => {
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-callback-transaction-${nextId++}`,
id: `${idPrefix}-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
@@ -248,29 +252,38 @@ const author = async () => {
};
try {
const rootInstanceId =
path === undefined
? home.rootInstanceId
: ((
await call("create-page", {
name: "Managed Form callbacks",
path,
})
).rootInstanceId as string);
const state = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: rootInstanceId,
name: "callbackState",
value: { type: "string", value: "initial" },
});
const history = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: rootInstanceId,
name: "callbackHistory",
value: { type: "string", value: "" },
});
const results = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: rootInstanceId,
name: "callbackResults",
value: { type: "json", value: [] },
});
const errors = await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: rootInstanceId,
name: "callbackErrors",
value: { type: "json", value: [] },
});
const changeCount = verifyFieldChange
? await call("create-variable", {
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: rootInstanceId,
name: "fieldChangeCount",
value: { type: "number", value: 0 },
})
@@ -283,7 +296,7 @@ const author = async () => {
if (mode === "legacy") {
await expect(
call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
parentInstanceId: rootInstanceId,
fragment: "<WebhookForm />",
})
).rejects.toThrow("Webhook Form is deprecated");
@@ -293,7 +306,7 @@ const author = async () => {
version: remote.version + 1,
state: seedSavedLegacyForm({
state: remote.state,
rootInstanceId: home.rootInstanceId,
rootInstanceId: rootInstanceId,
formId,
}),
};
@@ -315,14 +328,14 @@ const author = async () => {
'<Input name="outcome" /><Button type="submit">Submit callback form</Button>',
});
const fragment = await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
parentInstanceId: rootInstanceId,
fragment:
'<Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',
});
[auditId, errorId] = fragment.rootInstanceIds as string[];
} else {
const fragment = await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
parentInstanceId: rootInstanceId,
fragment: verifyFieldChange
? '<ResourceForm id="callback-form" /><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>'
: '<ResourceForm id="callback-form"><Input name="outcome" /><Button type="submit">Submit callback form</Button></ResourceForm><Text id="callback-audit">Pending callbacks</Text><Text id="callback-error">Pending errors</Text>',
@@ -471,13 +484,49 @@ const author = async () => {
}),
])
);
process.stdout.write(
`${JSON.stringify({ formId, resourceId: resource.resourceId })}\n`
);
return { formId, resourceId: resource.resourceId };
} finally {
await client.close();
await server.close();
}
};
await author();
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [, , projectId, mode, receiverUrl, option] = process.argv;
if (
projectId === undefined ||
(mode !== "legacy" &&
mode !== "managed" &&
mode !== "legacy-and-managed") ||
receiverUrl === undefined
) {
throw new Error("Expected a project ID, callback mode and receiver URL");
}
if (mode === "legacy-and-managed") {
if (option === undefined) {
throw new Error("Expected the managed callback page path");
}
const legacy = await authorFormCallbacks({
projectId,
mode: "legacy",
receiverUrl,
});
process.stdout.write(`${JSON.stringify(legacy)}\n`);
const managed = await authorFormCallbacks({
projectId,
mode: "managed",
receiverUrl,
path: option,
});
process.stdout.write(`${JSON.stringify(managed)}\n`);
await authorQuerySearch(projectId);
} else {
const result = await authorFormCallbacks({
projectId,
mode,
receiverUrl,
verifyFieldChange: option === "field-change",
});
process.stdout.write(`${JSON.stringify(result)}\n`);
}
}
@@ -1,336 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts";
import {
createProjectSessionMcpServer,
type PublicMcpOperation,
} from "@webstudio-is/project-build/mcp";
import {
createProjectSession,
type ProjectSessionPersistedSnapshot,
type ProjectSessionRemoteSnapshot,
} from "@webstudio-is/project-build/project-session";
import {
applyBuilderPatchTransactions,
createBuilderBuildDataSnapshotFromState,
createBuilderStateFromBuildData,
} from "@webstudio-is/project-build/state";
import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
const commands = new Set([
"create-page",
"insert-fragment",
"insert-component",
"list-instances",
"list-variables",
"create-resource",
"update-resource",
"update-props",
"inspect-instance",
]);
const operations: PublicMcpOperation[] = runtimeOperationContracts
.filter(({ command }) => commands.has(command))
.map((contract) => ({
command: contract.command,
id: contract.id,
method: contract.kind === "mutation" ? "mutation" : "query",
permit: contract.permit ?? "view",
description: contract.command,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
localCapable: true,
serverOnly: false,
readNamespaces: contract.readNamespaces,
writeNamespaces: contract.writeNamespaces,
invalidatesNamespaces: contract.invalidatesNamespaces,
retryOnConflict: contract.retryOnConflict,
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
const pages = migratePages(parse("pages"));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected a home page in the E2E fixture");
}
const initialState = createBuilderStateFromBuildData({
pages,
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
});
let remote: ProjectSessionRemoteSnapshot = {
projectId: projectId,
buildId: build.id,
version: build.version,
state: initialState,
};
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId: projectId,
compatibilityVersion: "mcp-form-context-e2e-v1",
runtimeContext: { createId: () => `mcp-context-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions)
.state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
}),
getCompatibility: async () => ({
sessionVersion: "mcp-form-context-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-context-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-context-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = {
...(input as object),
projectId: projectId,
};
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({
name: "mcp-form-context-e2e",
version: "1.0.0",
});
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
fragment:
'<Link href="/contact/autumn?private=omit">Open contact Form</Link>',
});
const page = await call("create-page", {
name: "Form context",
path: "/contact/:slug",
});
const inserted = await call("insert-component", {
parentInstanceId: page.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
if (formId === undefined) {
throw new Error("Expected the inserted Form ID");
}
await call("refresh");
const formInspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
const formProps = formInspection.props as Array<{
name: string;
value: unknown;
}>;
const variable = (name: string) => {
const id = formProps.find((prop) => prop.name === name)?.value;
if (typeof id !== "string") {
throw new Error(`Expected the ${name} Form parameter`);
}
return encodeDataSourceVariable(id);
};
const formData = variable("formData");
const browserInfo = variable("browserInfo");
const resource = await call("create-resource", {
resource: {
name: "Context receiver",
method: "post",
url: "https://mcp-delivery.example/submit",
headers: [],
},
scopeInstanceId: formId,
dataSourceName: "Context receiver",
exposeAsDataSource: true,
});
await call("update-resource", {
resourceId: resource.resourceId,
scopeInstanceId: formId,
exposeAsDataSource: true,
values: {
bodyFormat: "json",
body: `{ name: ${formData}.name, email: ${formData}.email, slug: system.params.slug, browser: { ip: ${browserInfo}.ip ?? null, userAgent: ${browserInfo}.userAgent ?? null, language: ${browserInfo}.language ?? null, referrer: ${browserInfo}.referrer ?? null } }`,
headers: [
{ name: "X-Form-Language", value: `${browserInfo}.language ?? ""` },
],
},
});
await call("update-props", {
updates: [
{
instanceId: formId,
name: "action",
type: "json",
value: [{ dataSourceId: resource.dataSourceId }],
},
],
});
await call("refresh");
const inspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
expect(inspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: "action",
type: "json",
}),
])
);
process.stdout.write(
`${JSON.stringify({ formId, resourceId: resource.resourceId })}\n`
);
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -1,326 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import {
migratePages,
serializePages,
} from "@webstudio-is/project-migrations/pages";
import { runtimeOperationContracts } from "@webstudio-is/project-build/contracts";
import {
createProjectSessionMcpServer,
type PublicMcpOperation,
} from "@webstudio-is/project-build/mcp";
import {
createProjectSession,
type ProjectSessionPersistedSnapshot,
type ProjectSessionRemoteSnapshot,
} from "@webstudio-is/project-build/project-session";
import {
applyBuilderPatchTransactions,
createBuilderBuildDataSnapshotFromState,
createBuilderStateFromBuildData,
} from "@webstudio-is/project-build/state";
import {
executeBuilderRuntimeOperation,
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
const commands = new Set([
"insert-component",
"insert-fragment",
"update-resource",
"update-props",
"list-instances",
"inspect-instance",
"list-resources",
"get-project-settings",
"update-project-settings",
]);
const operations: PublicMcpOperation[] = runtimeOperationContracts
.filter(({ command }) => commands.has(command))
.map((contract) => ({
command: contract.command,
id: contract.id,
method: contract.kind === "mutation" ? "mutation" : "query",
permit: contract.permit ?? "view",
description: contract.command,
inputSchema: contract.inputSchema,
outputSchema: contract.outputSchema,
localCapable: true,
serverOnly: false,
readNamespaces: contract.readNamespaces,
writeNamespaces: contract.writeNamespaces,
invalidatesNamespaces: contract.invalidatesNamespaces,
retryOnConflict: contract.retryOnConflict,
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
const pages = migratePages(parse("pages"));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected a home page in the E2E fixture");
}
const initialState = createBuilderStateFromBuildData({
pages,
instances: parse("instances"),
props: parse("props"),
styles: parse("styles"),
styleSources: parse("styleSources"),
styleSourceSelections: parse("styleSourceSelections"),
dataSources: parse("dataSources"),
projectSettings: parse("projectSettings"),
resources: parse("resources"),
breakpoints: parse("breakpoints"),
assets: [],
assetFolders: [],
});
let remote: ProjectSessionRemoteSnapshot = {
projectId: projectId,
buildId: build.id,
version: build.version,
state: initialState,
};
let stored: ProjectSessionPersistedSnapshot | undefined;
let revision = 0;
let nextId = 0;
const persist = async () => {
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
build = await updateBuild(build.id, {
version: remote.version,
pages: JSON.stringify(serializePages(snapshot.pages!)),
instances: JSON.stringify(snapshot.instances),
props: JSON.stringify(snapshot.props),
styles: JSON.stringify(snapshot.styles),
styleSources: JSON.stringify(snapshot.styleSources),
styleSourceSelections: JSON.stringify(snapshot.styleSourceSelections),
dataSources: JSON.stringify(snapshot.dataSources),
projectSettings: JSON.stringify(snapshot.projectSettings),
resources: JSON.stringify(snapshot.resources),
breakpoints: JSON.stringify(snapshot.breakpoints),
});
};
const session = createProjectSession({
projectId: projectId,
compatibilityVersion: "mcp-preview-form-e2e-v1",
runtimeContext: { createId: () => `mcp-form-data-${nextId++}` },
storage: {
load: async () => stored,
save: async (snapshot, options) => {
expect(options.expectedRevision).toBe(stored?.revision);
stored = { ...snapshot, revision: `revision-${++revision}` };
return { revision: stored.revision };
},
clear: async () => {
stored = undefined;
},
},
transport: {
fetchNamespaces: async () => remote,
commitPatch: async ({ baseVersion, transactions }) => {
expect(baseVersion).toBe(remote.version);
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, transactions)
.state,
};
await persist();
return { version: remote.version };
},
commitRestorePoint: async () => {
throw new Error("Restore points are outside this E2E fixture");
},
getPermissions: async () => ({
canView: true,
canEdit: true,
canBuild: true,
canAdmin: false,
canUseApi: true,
}),
getCompatibility: async () => ({
sessionVersion: "mcp-preview-form-e2e-v1",
runtimeContractVersion: "test-runtime-contracts",
projectSchemaVersion: "test-project-schema",
apiCompatibilityVersion: "test-api",
}),
executeServerOperation: async <Result>({
operationId,
input,
}: {
operationId: string;
input: unknown;
}): Promise<Result> => {
const mutation =
await executeBuilderRuntimeOperation<BuilderRuntimeMutation>({
id: operationId,
state: remote.state,
input,
context: {
createId: () => `mcp-form-data-server-${nextId++}`,
projectId: remote.projectId,
projectVersion: remote.version,
},
});
expect(mutation.kind).toBe("mutation");
remote = {
...remote,
version: remote.version + 1,
state: applyBuilderPatchTransactions(remote.state, [
{
id: `mcp-form-data-transaction-${nextId++}`,
payload: mutation.payload,
},
]).state,
};
await persist();
return mutation.result as Result;
},
},
});
const server = await createProjectSessionMcpServer({
operations,
createProjectSession: () => session,
executeOperation: async ({ command, input, dryRun }) => {
const operation = operations.find(
(candidate) => candidate.command === command
);
const contract = runtimeOperationContracts.find(
({ id }) => id === operation?.id
);
if (operation === undefined || contract === undefined) {
throw new Error(`Unexpected MCP operation: ${command}`);
}
const scopedInput = {
...(input as object),
projectId: projectId,
};
const result =
operation.method === "mutation"
? await session.mutate(contract.id, scopedInput, {
permit: operation.permit,
dryRun,
})
: await session.read(contract.id, scopedInput, {
permit: operation.permit,
});
const failure = result.diagnostics.find(({ level }) => level === "error");
if (failure) {
throw new Error(failure.message);
}
return result;
},
});
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
const client = new Client({ name: "mcp-preview-form-e2e", version: "1.0.0" });
await Promise.all([
server.connect(serverTransport),
client.connect(clientTransport),
]);
const call = async (name: string, args: Record<string, unknown> = {}) => {
const response = await client.callTool({ name, arguments: args });
if (response.isError) {
throw new Error(`${name}: ${JSON.stringify(response.structuredContent)}`);
}
const payload = response.structuredContent as {
ok: boolean;
data: Record<string, unknown>;
};
expect(payload.ok, name).toBe(true);
return payload.data;
};
try {
const inserted = await call("insert-component", {
parentInstanceId: home.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
if (formId === undefined) {
throw new Error("Expected the inserted Form ID");
}
await call("refresh");
const form = { id: formId };
await call("insert-fragment", {
parentInstanceId: form.id,
fragment:
'<Input name="profile.city" /><Input name="tag" /><Input name="tag" /><Input name="password" type="password" /><Input name="upload" type="file" />',
});
await call("update-project-settings", {
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
const resources = await call("list-resources", {
scopeInstanceId: form.id,
});
const emails = resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>;
const owner = emails.find(({ name }) => name === "Email to owner");
const visitor = emails.find(({ name }) => name === "Email to visitor");
if (owner === undefined || visitor === undefined) {
throw new Error("Expected both default Form Email Resources");
}
const inspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
const formDataId = (
inspection.props as Array<{ name: string; value: unknown }>
).find(({ name }) => name === "formData")?.value;
if (typeof formDataId !== "string") {
throw new Error("Expected Form data parameter");
}
const expression = `${encodeDataSourceVariable(formDataId)}.toString()`;
await call("update-resource", {
resourceId: owner.id,
values: { email: { body: expression } },
});
await call("update-props", {
updates: [
{
instanceId: form.id,
name: "action",
type: "json",
value: [{ dataSourceId: owner.dataSourceId }],
},
],
});
const actions = [{ dataSourceId: owner.dataSourceId }];
const updatedInspection = await call("inspect-instance", {
instanceId: form.id,
include: ["props"],
});
expect(updatedInspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "action", value: actions }),
])
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
ownerResourceId: owner.id,
expression,
})}\n`
);
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -26,6 +26,7 @@ import {
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { authorManagedFormQuery } from "./mcp-managed-form-query-author";
import { seedSavedLegacyForm } from "./saved-legacy-form";
const commands = new Set([
@@ -62,13 +63,8 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
const receiverUrl = process.argv[3];
if (projectId === undefined || receiverUrl === undefined) {
throw new Error("Expected the disposable E2E project ID and receiver URL");
}
const author = async () => {
const authorLegacyFormQuery = async (projectId: string) => {
const receiverUrl = "https://mcp-delivery.example/submit";
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -382,11 +378,13 @@ const author = async () => {
}),
])
);
process.stdout.write(`${JSON.stringify({ formId, outputInstanceId })}\n`);
} finally {
await client.close();
await server.close();
}
};
await author();
export const authorFormQueries = async (projectId: string) => {
await authorLegacyFormQuery(projectId);
return await authorManagedFormQuery(projectId);
};
@@ -0,0 +1,23 @@
import { mkdir, writeFile } from "node:fs/promises";
import { loadDevBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
import { authorManagedForm } from "./mcp-managed-form-author";
export const preparePreviewBundle = async (
projectId: string,
...scenarios: string[]
) => {
const formIds: string[] = [];
// Each author reads the build persisted by the previous one.
for (const scenario of scenarios) {
const { formId } = await authorManagedForm(projectId, JSON.parse(scenario));
formIds.push(formId);
}
const build = await loadDevBuild({ projectId });
await mkdir(".webstudio", { recursive: true });
await writeFile(
".webstudio/data.json",
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
return formIds;
};
@@ -62,13 +62,10 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
const receiverUrl = process.argv[3];
if (projectId === undefined || receiverUrl === undefined) {
throw new Error("Expected the disposable E2E project ID and receiver URL");
}
const author = async () => {
export const authorLegacyFormRoute = async (
projectId: string,
receiverUrl: string
) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -380,11 +377,8 @@ const author = async () => {
}),
])
);
process.stdout.write(`${JSON.stringify({ formId, outputInstanceId })}\n`);
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -1,4 +1,5 @@
import { randomUUID } from "node:crypto";
import { fileURLToPath } from "node:url";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
@@ -60,38 +61,33 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const authorOptions = (() => {
const argument = process.argv[3];
if (argument === undefined || argument.startsWith("{") === false) {
return { mode: argument ?? "default" };
}
return JSON.parse(argument) as {
mode: string;
successRedirect?: string;
fail?: boolean;
actionUrl?: string;
};
})();
const deliveryMode = ["delivery", "multipart", "redirect"].includes(
authorOptions.mode
);
const emailAttachmentsMode = authorOptions.mode === "email-attachments";
const emailMode = authorOptions.mode === "email" || emailAttachmentsMode;
const emailIsolationMode = authorOptions.mode === "email-isolation";
const redirectMode = authorOptions.mode === "redirect";
const emptyActionMode = authorOptions.mode === "empty-action";
const formatMode = ["format-json", "format-multipart", "format-text"].includes(
authorOptions.mode
);
const httpFailureUrl = deliveryMode
? "https://mcp-delivery.example/reject"
: "http://127.0.0.1/preview-e2e-must-not-run";
type AuthorOptions = {
mode: string;
successRedirect?: string;
fail?: boolean;
actionUrl?: string;
};
const author = async () => {
export const authorManagedForm = async (
projectId: string,
authorOptions: AuthorOptions
) => {
const deliveryMode = ["delivery", "multipart", "redirect"].includes(
authorOptions.mode
);
const emailAttachmentsMode = authorOptions.mode === "email-attachments";
const emailMode = authorOptions.mode === "email" || emailAttachmentsMode;
const emailIsolationMode = authorOptions.mode === "email-isolation";
const redirectMode = authorOptions.mode === "redirect";
const emptyActionMode = authorOptions.mode === "empty-action";
const formatMode = [
"format-json",
"format-multipart",
"format-text",
].includes(authorOptions.mode);
const httpFailureUrl = deliveryMode
? "https://mcp-delivery.example/reject"
: "http://127.0.0.1/preview-e2e-must-not-run";
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -289,6 +285,73 @@ const author = async () => {
secondFormId = (insertedSecondForm.rootInstanceIds as string[])[0];
}
await call("refresh");
if (authorOptions.mode === "email-http-combination") {
await call("update-project-settings", {
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
const resources = await call("list-resources", {
scopeInstanceId: formId,
});
const email = (
resources.resources as Array<{
id: string;
dataSourceId: string;
name: string;
}>
).find(({ name }) => name === "Email to owner");
if (email === undefined) {
throw new Error("Expected the Form's Email to owner Email Action");
}
await call("update-resource", {
resourceId: email.id,
values: {
email: {
recipientMode: "custom",
recipients: "combined@mcp.test",
subject: JSON.stringify("Combined action subject"),
body: JSON.stringify("Combined action exact body."),
},
},
});
const http = await call("create-resource", {
resource: {
name: "Combined HTTP action",
method: "post",
url: "https://mcp-delivery.example/submit",
headers: [],
},
scopeInstanceId: formId,
dataSourceName: "Combined HTTP action",
exposeAsDataSource: true,
});
const actions = [
{ dataSourceId: email.dataSourceId },
{ dataSourceId: http.dataSourceId },
];
await call("update-props", {
updates: [
{ instanceId: formId, name: "action", type: "json", value: actions },
],
});
await call("refresh");
const inspection = await call("inspect-instance", {
instanceId: formId,
include: ["props"],
});
expect(inspection.props).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "action", value: actions }),
])
);
return {
formId,
emailResourceId: email.id,
httpResourceId: http.resourceId,
};
}
if (emailIsolationMode && secondFormId === undefined) {
throw new Error("Expected the second inserted Form ID");
}
@@ -693,26 +756,36 @@ const author = async () => {
expect(resultCallback?.value[0]?.code).toContain(
`${variableId("errors")} = result.errors`
);
process.stdout.write(
`${JSON.stringify({
formId: form.id,
secondFormId: secondForm?.id,
resourceId: http.resourceId,
successfulResourceId: successfulHttp?.resourceId,
emailResourceIds: emailMode
? emails
.filter(({ name }) =>
["Email to owner", "Email to visitor"].includes(name)
)
.map(({ id }) => id)
: undefined,
emailResourceIdsByForm,
})}\n`
);
return {
formId: form.id,
secondFormId: secondForm?.id,
resourceId: http.resourceId,
successfulResourceId: successfulHttp?.resourceId,
emailResourceIds: emailMode
? emails
.filter(({ name }) =>
["Email to owner", "Email to visitor"].includes(name)
)
.map(({ id }) => id)
: undefined,
emailResourceIdsByForm,
};
} finally {
await client.close();
await server.close();
}
};
await author();
if (process.argv[1] === fileURLToPath(import.meta.url)) {
const [, , projectId, ...args] = process.argv;
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
for (const argument of args.length === 0 ? ["default"] : args) {
const options: AuthorOptions = argument.startsWith("{")
? JSON.parse(argument)
: { mode: argument };
const result = await authorManagedForm(projectId, options);
process.stdout.write(`${JSON.stringify(result)}\n`);
}
}
@@ -56,12 +56,7 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
export const authorManagedFormQuery = async (projectId: string) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -309,13 +304,9 @@ const author = async () => {
}),
])
);
process.stdout.write(
`${JSON.stringify({ formId, resourceId: resource.resourceId })}\n`
);
return { formId, resourceId: resource.resourceId };
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -25,6 +25,9 @@ import {
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { authorFormActionCombination } from "./mcp-form-action-combination-author";
import { authorFormCallbacks } from "./mcp-form-callbacks-author";
import { authorManagedForm } from "./mcp-managed-form-author";
const commands = new Set([
"insert-fragment",
@@ -284,11 +287,40 @@ const author = async () => {
}),
])
);
process.stdout.write(`${JSON.stringify({ formInstanceId })}\n`);
return formInstanceId;
} finally {
await client.close();
await server.close();
}
};
await author();
const callbackForm = await authorFormCallbacks({
projectId,
mode: "managed",
receiverUrl: "https://mcp-delivery.example/submit",
verifyFieldChange: true,
});
const actionForm = await authorFormActionCombination(projectId, "ten-actions");
const blockedForm = await authorManagedForm(projectId, { mode: "default" });
const emailForm = await authorManagedForm(projectId, {
mode: "email-attachments",
});
const nativeFormId = await author();
const successRedirect = "?mcp-e2e=success";
const successful = await authorManagedForm(projectId, {
mode: "redirect",
successRedirect,
fail: false,
});
const failed = await authorManagedForm(projectId, {
mode: "redirect",
successRedirect,
fail: true,
});
const feedback = await authorManagedForm(projectId, {
mode: "redirect",
fail: false,
});
process.stdout.write(
`${JSON.stringify({ callbackForm, actionForm, blockedForm, emailForm, nativeFormId, outcomes: { successful, failed, feedback } })}\n`
);
@@ -1,3 +1,4 @@
import { mkdir, writeFile } from "node:fs/promises";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { expect } from "@playwright/test";
@@ -25,8 +26,11 @@ import {
type BuilderRuntimeMutation,
} from "@webstudio-is/project-build/runtime";
import { loadDevBuild, updateBuild } from "../db";
import { createLocalBundleFromDevBuild } from "../flows/generated-app";
import { authorManagedForm } from "./mcp-managed-form-author";
const commands = new Set([
"create-page",
"set-text-content",
"insert-fragment",
"insert-component",
@@ -56,21 +60,11 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
const receiverUrl = process.argv[3];
if (projectId === undefined || receiverUrl === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
const author = async (projectId: string, receiverUrl: string) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
const pages = migratePages(parse("pages"));
const home = pages.pages.get(pages.homePageId);
if (home === undefined) {
throw new Error("Expected a home page in the E2E fixture");
}
const initialState = createBuilderStateFromBuildData({
pages,
instances: parse("instances"),
@@ -243,10 +237,14 @@ const author = async () => {
};
try {
const navigationPage = await call("create-page", {
name: "Form navigation",
path: "/search",
});
// Inserting the public Form template creates connected Email Resources.
// Removing every Action through MCP must switch that same Form to navigation.
const inserted = await call("insert-component", {
parentInstanceId: home.rootInstanceId,
parentInstanceId: navigationPage.rootInstanceId,
component: "form",
});
const formId = (inserted.rootInstanceIds as string[])[0];
@@ -283,13 +281,13 @@ const author = async () => {
url: receiverUrl,
headers: [],
},
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: navigationPage.rootInstanceId,
dataSourceName: "searchResults",
exposeAsDataSource: true,
});
await call("update-resource", {
resourceId: resource.resourceId,
scopeInstanceId: home.rootInstanceId,
scopeInstanceId: navigationPage.rootInstanceId,
exposeAsDataSource: true,
values: {
searchParams: [
@@ -302,7 +300,7 @@ const author = async () => {
},
});
const output = await call("insert-fragment", {
parentInstanceId: home.rootInstanceId,
parentInstanceId: navigationPage.rootInstanceId,
fragment: '<Text id="navigation-search-results">Waiting</Text>',
});
const [outputInstanceId] = output.rootInstanceIds as string[];
@@ -322,11 +320,29 @@ const author = async () => {
expect.objectContaining({ name: "action", type: "json", value: [] }),
])
);
process.stdout.write(`${JSON.stringify({ formId })}\n`);
return formId;
} finally {
await client.close();
await server.close();
}
};
await author();
export const preparePreviewBundle = async (
projectId: string,
receiverUrl: string,
...formatModes: string[]
) => {
const formatForms = [];
for (const mode of formatModes) {
const { formId } = await authorManagedForm(projectId, { mode });
formatForms.push({ mode, formId });
}
const navigationFormId = await author(projectId, receiverUrl);
const build = await loadDevBuild({ projectId });
await mkdir(".webstudio", { recursive: true });
await writeFile(
".webstudio/data.json",
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
return { formatForms, navigationFormId };
};
@@ -0,0 +1,26 @@
import { expect, test } from "vitest";
import { getMcpPreviewBrowserOptions } from "./mcp-preview-browser-options";
test("passes Playwright's Linux sandbox setting to the MCP browser launch", () => {
const options = { browserPath: "/playwright/headless_shell", timeout: 3000 };
expect(
getMcpPreviewBrowserOptions(options, {
platform: "linux",
playwrightBrowserPath: options.browserPath,
})
).toEqual({ ...options, disableSandbox: true });
expect(
getMcpPreviewBrowserOptions(options, {
platform: "darwin",
playwrightBrowserPath: options.browserPath,
})
).toBe(options);
expect(
getMcpPreviewBrowserOptions(options, {
platform: "linux",
playwrightBrowserPath: "/different-browser",
})
).toBe(options);
});
@@ -0,0 +1,15 @@
export const getMcpPreviewBrowserOptions = <
Options extends { browserPath: string },
>(
options: Options,
{
platform = process.platform,
playwrightBrowserPath = process.env.WEBSTUDIO_BROWSER_PATH,
} = {}
) => {
if (platform === "linux" && options.browserPath === playwrightBrowserPath) {
// Match Playwright's sandbox setting for its Chromium binary on Linux.
return { ...options, disableSandbox: true };
}
return options;
};
@@ -2,6 +2,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
import { createProjectSessionMcpServer } from "@webstudio-is/project-build/mcp";
import { createInterface } from "node:readline";
import { getMcpPreviewBrowserOptions } from "./mcp-preview-browser-options";
const previewModuleUrl = new URL(
"../../../../packages/cli/src/commands/mcp-preview.ts",
@@ -12,7 +13,8 @@ const screenshotModuleUrl = new URL(
import.meta.url
).href;
const { createMcpPreviewHandlers } = await import(previewModuleUrl);
const { createScreenshotCaptureSession } = await import(screenshotModuleUrl);
const { createScreenshotCaptureSession, defaultScreenshotDependencies } =
await import(screenshotModuleUrl);
let url = "";
@@ -26,7 +28,18 @@ const previewHandlers = createMcpPreviewHandlers({
stop: async () => ({ running: false, url, mode: "iterative" as const }),
},
isStale: () => false,
createCaptureSession: createScreenshotCaptureSession,
createCaptureSession: () =>
createScreenshotCaptureSession({
...defaultScreenshotDependencies,
createBrowserScreenshotSession: (
options: { browserPath: string },
dependencies: unknown
) =>
defaultScreenshotDependencies.createBrowserScreenshotSession(
getMcpPreviewBrowserOptions(options),
dependencies
),
}),
});
const server = await createProjectSessionMcpServer({
operations: [],
@@ -51,12 +51,7 @@ const operations: PublicMcpOperation[] = runtimeOperationContracts
requiresConfirm: contract.requiresConfirm,
}));
const projectId = process.argv[2];
if (projectId === undefined) {
throw new Error("Expected the disposable E2E project ID");
}
const author = async () => {
export const authorQuerySearch = async (projectId: string) => {
let build = await loadDevBuild({ projectId: projectId });
const parse = <Value>(field: keyof typeof build) =>
JSON.parse(String(build[field])) as Value;
@@ -265,11 +260,8 @@ const author = async () => {
verbose: true,
});
expect(JSON.stringify(inspection)).toContain(".search.tag");
process.stdout.write(`${JSON.stringify({ outputInstanceId })}\n`);
} finally {
await client.close();
await server.close();
}
};
await author();
@@ -1,5 +1,10 @@
import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises";
import type { BrowserContext } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import { loadDevBuild, updateBuild } from "../db";
import { getAssetUploadApiUrl } from "@webstudio-is/sdk/runtime";
import { insertAuthorizationToken, loadDevBuild, updateBuild } from "../db";
import { builderUrl } from "../test";
type InstanceData = {
type: "instance";
@@ -29,6 +34,7 @@ type DataSourceData = {
const blockId = "content-block";
const templateId = "content-block-template";
export const lifecycleTemplateId = "lifecycle-card-template";
const getBuildData = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
@@ -55,33 +61,12 @@ export const configureRepresentableContentBlockBody = async (
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
export const configureEmptyHeadingTemplate = async (projectId: string) => {
const { build, instances } = await getBuildData(projectId);
const templates = instances.find((instance) => instance.id === templateId);
if (templates === undefined) {
throw new Error("Expected the Content Block templates fixture instance");
}
const emptyHeadingId = "empty-heading-template";
templates.children.push({ type: "id", value: emptyHeadingId });
instances.push({
type: "instance",
id: emptyHeadingId,
component: "ws:element",
tag: "h1",
name: "EmptyHeadingTemplate",
label: "Empty Heading Template",
children: [],
});
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
export const configureNamedTemplateLifecycle = async (projectId: string) => {
const { build, instances } = await getBuildData(projectId);
const templates = instances.find((instance) => instance.id === templateId);
if (templates === undefined) {
throw new Error("Expected the Content Block templates fixture instance");
}
const lifecycleTemplateId = "lifecycle-card-template";
templates.children.push({ type: "id", value: lifecycleTemplateId });
instances.push({
type: "instance",
@@ -95,70 +80,104 @@ export const configureNamedTemplateLifecycle = async (projectId: string) => {
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
export const configureNestedHeadingTemplates = async (projectId: string) => {
const { build, instances } = await getBuildData(projectId);
const templates = instances.find((instance) => instance.id === templateId);
if (templates === undefined) {
throw new Error("Expected the Content Block templates fixture instance");
}
const nestedTemplates = [
{ id: "service-card-template", name: "ServiceCard", tag: "a" },
{ id: "card-shell-template", name: "CardShell", tag: "div" },
{ id: "card-text-template", name: "CardText", tag: "div" },
];
templates.children.push(
...nestedTemplates.map(({ id }) => ({ type: "id", value: id }))
);
instances.push(
...nestedTemplates.map(({ id, name, tag }) => ({
type: "instance" as const,
id,
component: "ws:element",
tag,
name,
children: [{ type: "text", value: "Template default" }],
}))
);
await updateBuild(build.id, { instances: JSON.stringify(instances) });
export const mdxEditorPageNames = {
detail: "Dynamic MDX detail",
repeated: "Repeated MDX content",
};
const configureSourceBlock = ({
instances,
props,
expression,
export const prepareMdxEditorPages = async ({
context,
projectId,
sourceFilename,
alternateFilename,
emptyFilename,
}: {
instances: InstanceData[];
props: PropData[];
expression: string;
context: BrowserContext;
projectId: string;
sourceFilename: string;
alternateFilename: string;
emptyFilename: string;
}) => {
const block = instances.find((instance) => instance.id === blockId);
if (block === undefined) {
throw new Error("Expected the Content Block fixture instance");
const token = randomUUID();
await insertAuthorizationToken({
token,
projectId,
name: "MDX fixture setup",
relation: "builders",
canUseApi: true,
});
const upload = async (filename: string, uploadedFilename = filename) => {
const url = new URL(getAssetUploadApiUrl(uploadedFilename), builderUrl);
url.searchParams.set("projectId", projectId);
url.searchParams.set("type", "file");
url.searchParams.set("format", "mdx");
if (uploadedFilename !== filename) {
url.searchParams.set("force", "true");
}
const response = await context.request.post(url.href, {
headers: {
"x-auth-token": token,
"content-type": "application/octet-stream",
},
data: await readFile(new URL(`./assets/${filename}`, import.meta.url)),
});
if (response.ok() === false) {
throw new Error(
`MDX fixture upload failed for ${filename}: ${response.status()}`
);
}
const { uploadedAssets } = (await response.json()) as {
uploadedAssets: Array<{ id: string }>;
};
const [asset] = uploadedAssets;
if (asset === undefined) {
throw new Error(`Expected an asset ID for ${filename}`);
}
return asset.id;
};
const [
{ build, instances, props, dataSources },
sourceAssetId,
alternateAssetId,
emptyAssetId,
detailSourceAssetId,
detailAlternateAssetId,
] = await Promise.all([
getBuildData(projectId),
upload(sourceFilename),
upload(alternateFilename),
upload(emptyFilename),
upload(sourceFilename, `detail-${sourceFilename}`),
upload(alternateFilename, `detail-${alternateFilename}`),
]);
const homeBlock = instances.find((instance) => instance.id === blockId);
const homeTemplates = instances.find(
(instance) => instance.id === templateId
);
if (homeBlock === undefined || homeTemplates === undefined) {
throw new Error("Expected the Content Block fixture instances");
}
block.children = [{ type: "id", value: templateId }];
const emptyHeadingId = "empty-heading-template";
homeTemplates.children.push({ type: "id", value: emptyHeadingId });
instances.push({
type: "instance",
id: emptyHeadingId,
component: "ws:element",
tag: "h1",
name: "EmptyHeadingTemplate",
label: "Empty Heading Template",
children: [],
});
homeBlock.children = [{ type: "id", value: templateId }];
props.push({
id: "content-block-source",
instanceId: blockId,
name: "src",
type: "expression",
value: expression,
type: "asset",
value: emptyAssetId,
});
};
export const configureDynamicDetailContentBlock = async ({
projectId,
initialAssetId,
}: {
projectId: string;
initialAssetId: string;
}) => {
const { build, instances, props, dataSources } =
await getBuildData(projectId);
configureSourceBlock({
instances,
props,
expression: "$ws$system.params.assetid",
});
const pages = JSON.parse(build.pages) as {
homePageId: string;
rootFolderId: string;
@@ -172,80 +191,99 @@ export const configureDynamicDetailContentBlock = async ({
}>;
folders: Array<{ id: string; children: string[] }>;
};
const homePage = pages.pages.find((page) => page.id === pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected the Content Block fixture home page");
}
const dynamicPageId = homePage.id;
const homeRootId = "mdx-detail-home-root";
const body = instances.find(
(instance) => instance.id === homePage.rootInstanceId
);
if (body === undefined) {
throw new Error("Expected the Content Block fixture page root");
}
instances.push({ ...body, id: homeRootId, children: [] });
pages.pages.push({
...homePage,
id: "mdx-detail-home-page",
name: "MDX detail home",
title: JSON.stringify("MDX detail home"),
path: "",
history: [],
rootInstanceId: homeRootId,
});
pages.homePageId = "mdx-detail-home-page";
const home = pages.pages.find((page) => page.id === pages.homePageId);
const rootFolder = pages.folders.find(
(folder) => folder.id === pages.rootFolderId
);
if (rootFolder === undefined) {
throw new Error("Expected the Content Block fixture root folder");
if (home === undefined || rootFolder === undefined) {
throw new Error(
"Expected the Content Block fixture home page and root folder"
);
}
rootFolder.children = [
pages.homePageId,
dynamicPageId,
...rootFolder.children.filter((id) => id !== dynamicPageId),
];
homePage.name = "Dynamic MDX detail";
homePage.title = JSON.stringify("Dynamic MDX detail");
homePage.path = "/:assetid";
homePage.history = [`/${initialAssetId}`];
await updateBuild(build.id, {
instances: JSON.stringify(instances),
props: JSON.stringify(props),
dataSources: JSON.stringify(dataSources),
pages: JSON.stringify(pages),
});
return dynamicPageId;
};
export const configureRepeatedContentBlock = async ({
projectId,
assetIds,
}: {
projectId: string;
assetIds: [string, string];
}) => {
const { build, instances, props, dataSources } =
await getBuildData(projectId);
const addSourcePage = ({
id,
name,
path,
history,
expression,
collectionId,
}: {
id: string;
name: string;
path: string;
history?: string[];
expression: string;
collectionId?: string;
}) => {
const rootInstanceId = `${id}-root`;
const blockInstanceId = `${id}-block`;
const blockTemplateId = `${id}-templates`;
pages.pages.push({
...home,
id,
name,
title: JSON.stringify(name),
path,
history,
rootInstanceId,
});
rootFolder.children.push(id);
instances.push(
{
type: "instance",
id: rootInstanceId,
component: "ws:element",
tag: "body",
children: [{ type: "id", value: collectionId ?? blockInstanceId }],
},
{
type: "instance",
id: blockInstanceId,
component: "ws:block",
children: [{ type: "id", value: blockTemplateId }],
},
{
type: "instance",
id: blockTemplateId,
component: "ws:block-template",
children: [],
}
);
props.push({
id: `${id}-source`,
instanceId: blockInstanceId,
name: "src",
type: "expression",
value: expression,
});
return blockInstanceId;
};
addSourcePage({
id: "mdx-detail-page",
name: mdxEditorPageNames.detail,
path: "/:assetid",
history: [`/${detailSourceAssetId}`],
expression: "$ws$system.params.assetid",
});
const collectionId = "mdx-content-collection";
const itemParameterId = "mdx-content-collection-item";
const itemKeyParameterId = "mdx-content-collection-item-key";
configureSourceBlock({
instances,
props,
expression: `${encodeDataSourceVariable(itemParameterId)}?.assetId`,
const repeatedPageId = "mdx-repeated-page";
const repeatedBlockId = addSourcePage({
id: repeatedPageId,
name: mdxEditorPageNames.repeated,
path: "/repeated",
expression: `${encodeDataSourceVariable(itemParameterId)}.assetId`,
collectionId,
});
const body = instances.find((instance) => instance.id === "body");
if (body === undefined) {
throw new Error("Expected the Content Block fixture body");
}
body.children = [{ type: "id", value: collectionId }];
instances.push({
type: "instance",
id: collectionId,
component: "ws:collection",
children: [{ type: "id", value: blockId }],
children: [{ type: "id", value: repeatedBlockId }],
});
props.push(
{
@@ -253,7 +291,7 @@ export const configureRepeatedContentBlock = async ({
instanceId: collectionId,
name: "data",
type: "json",
value: assetIds.map((assetId) => ({ assetId })),
value: [sourceAssetId, alternateAssetId].map((assetId) => ({ assetId })),
},
{
id: "mdx-content-collection-item-prop",
@@ -288,5 +326,39 @@ export const configureRepeatedContentBlock = async ({
instances: JSON.stringify(instances),
props: JSON.stringify(props),
dataSources: JSON.stringify(dataSources),
pages: JSON.stringify(pages),
});
return {
homePageName: home.name,
repeatedPageId,
detailSourceAssetId,
detailAlternateAssetId,
};
};
export const configureNestedHeadingTemplates = async (projectId: string) => {
const { build, instances } = await getBuildData(projectId);
const templates = instances.find((instance) => instance.id === templateId);
if (templates === undefined) {
throw new Error("Expected the Content Block templates fixture instance");
}
const nestedTemplates = [
{ id: "service-card-template", name: "ServiceCard", tag: "a" },
{ id: "card-shell-template", name: "CardShell", tag: "div" },
{ id: "card-text-template", name: "CardText", tag: "div" },
];
templates.children.push(
...nestedTemplates.map(({ id }) => ({ type: "id", value: id }))
);
instances.push(
...nestedTemplates.map(({ id, name, tag }) => ({
type: "instance" as const,
id,
component: "ws:element",
tag,
name,
children: [{ type: "text", value: "Template default" }],
}))
);
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
@@ -0,0 +1,27 @@
import { expect, test } from "vitest";
import { parsePreviewLinksPages } from "./preview-links-pages";
test("preserves the historical Form marker through a pages round-trip", () => {
const pages = {
homePageId: "home",
rootFolderId: "root",
pages: [
{
id: "home",
name: "Home",
title: '"Home"',
path: "",
rootInstanceId: "body",
meta: {},
},
],
folders: [{ id: "root", name: "Root", slug: "", children: ["home"] }],
formComponentIdentityVersion: 1,
};
expect(
JSON.parse(
JSON.stringify(parsePreviewLinksPages(JSON.parse(JSON.stringify(pages))))
)
).toEqual(pages);
});
@@ -0,0 +1,12 @@
import {
hasHistoricalFormComponentIdentityVersion,
serializedPages,
} from "@webstudio-is/project-migrations/pages";
import { z } from "zod";
export const parsePreviewLinksPages = (value: unknown) => ({
...serializedPages.parse(value),
...(hasHistoricalFormComponentIdentityVersion(value)
? z.object({ formComponentIdentityVersion: z.number().int() }).parse(value)
: {}),
});
@@ -0,0 +1,192 @@
import type { Instance, Prop } from "@webstudio-is/sdk";
import { instance, prop } from "@webstudio-is/sdk/schema";
import { z } from "zod";
import { loadDevBuild, updateBuild } from "../db";
import { parsePreviewLinksPages } from "./preview-links-pages";
export const previewLinkText = {
homeLink: "Preview home link",
pageLink: "Preview page link",
richTextLink: "Preview rich text link",
pageAnchor: "Preview page anchor",
pageQueryLink: "Preview page query link",
hashLink: "Preview hash link",
} as const;
export const previewPageId = "preview-links-page";
type PreviewLink = {
key: string;
text: string;
href: string;
component?: string;
tag?: string;
};
const previewLinks: PreviewLink[] = [
{ key: "home-link", text: previewLinkText.homeLink, href: "/" },
{ key: "page-link", text: previewLinkText.pageLink, href: "/my-page" },
{
key: "rich-text-link",
text: previewLinkText.richTextLink,
href: "/my-page",
component: "RichTextLink",
},
{
key: "page-anchor",
text: previewLinkText.pageAnchor,
href: "/my-page",
component: "ws:element",
tag: "a",
},
{
key: "page-query-link",
text: previewLinkText.pageQueryLink,
href: "/my-page?tab=details",
},
{ key: "hash-link", text: previewLinkText.hashLink, href: "#section" },
] as const;
const appendChild = (
instances: Instance[],
parentId: string,
childId: string
) => {
const parent = instances.find((instance) => instance.id === parentId);
if (parent === undefined) {
throw new Error(`Expected instance "${parentId}"`);
}
parent.children.push({ type: "id", value: childId });
};
const addTextLink = ({
instances,
props,
id,
component = "Link",
tag,
text,
href,
}: {
instances: Instance[];
props: Prop[];
id: string;
component?: string;
tag?: string;
text: string;
href: string;
}) => {
instances.push({
type: "instance",
id,
component,
tag,
label: text,
children: [{ type: "text", value: text }],
});
props.push({
id: `${id}-href`,
instanceId: id,
name: "href",
type: "string",
value: href,
});
};
const addPreviewLinks = ({
instances,
props,
parentId,
prefix,
}: {
instances: Instance[];
props: Prop[];
parentId: string;
prefix: string;
}) => {
for (const link of previewLinks) {
const id = `${prefix}-${link.key}`;
addTextLink({
instances,
props,
id,
text: link.text,
href: link.href,
component: link.component,
tag: link.tag,
});
appendChild(instances, parentId, id);
}
};
export const preparePreviewLinksProject = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
const pages = parsePreviewLinksPages(JSON.parse(build.pages));
const instances = z.array(instance).parse(JSON.parse(build.instances));
const props = z.array(prop).parse(JSON.parse(build.props));
const homePage = pages.pages.find((page) => page.id === pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected home page");
}
const homeRoot = instances.find(
(instance) => instance.id === homePage.rootInstanceId
);
const homeContentId = homeRoot?.children.find(
(child) => child.type === "id"
)?.value;
if (homeContentId === undefined) {
throw new Error("Expected home page content instance");
}
const pageRootId = "preview-links-page-root";
const pageContentId = "preview-links-page-content";
pages.pages.push({
id: previewPageId,
name: "Preview Links Page",
title: JSON.stringify("Preview Links Page"),
rootInstanceId: pageRootId,
path: "/my-page",
meta: { description: JSON.stringify("") },
});
pages.folders
.find((folder) => folder.id === pages.rootFolderId)
?.children.push(previewPageId);
instances.push(
{
type: "instance",
id: pageRootId,
component: "ws:element",
tag: "body",
children: [{ type: "id", value: pageContentId }],
},
{
type: "instance",
id: pageContentId,
component: "ws:element",
tag: "main",
label: "Preview Links Page Content",
children: [],
}
);
addPreviewLinks({
instances,
props,
parentId: homeContentId,
prefix: "preview-home",
});
addPreviewLinks({
instances,
props,
parentId: pageContentId,
prefix: "preview-page",
});
await updateBuild(build.id, {
pages: JSON.stringify(pages),
instances: JSON.stringify(instances),
props: JSON.stringify(props),
});
};
@@ -1,4 +1,7 @@
import type { BrowserContext } from "@playwright/test";
import type { BrowserContext, Page } from "@playwright/test";
import { serializedPages } from "@webstudio-is/project-migrations/pages";
import { breakpoint } from "@webstudio-is/sdk/schema";
import { z } from "zod";
import { createSeededBuilderProject } from "./builder-project";
export type SeededSlotKeyboardProject = {
@@ -7,11 +10,7 @@ export type SeededSlotKeyboardProject = {
};
const getBaseBreakpointId = (breakpoints: string) => {
const parsedBreakpoints = JSON.parse(breakpoints) as Array<{
id: string;
minWidth?: number;
maxWidth?: number;
}>;
const parsedBreakpoints = z.array(breakpoint).parse(JSON.parse(breakpoints));
return (
parsedBreakpoints.find(
(breakpoint) =>
@@ -25,26 +24,18 @@ const getBaseBreakpointId = (breakpoints: string) => {
const createSlotKeyboardBuildData = ({
pages,
breakpoints,
additionalPairSuffixes,
}: {
pages: string;
breakpoints: string;
additionalPairSuffixes: string[];
}) => {
const rootInstanceId = "slot-keyboard-body";
const wrapperId = "slot-keyboard-wrapper";
const slotAId = "slot-keyboard-slot-a";
const slotBId = "slot-keyboard-slot-b";
const fragmentId = "slot-keyboard-fragment";
const divId = "slot-keyboard-div";
const headingId = "slot-keyboard-heading";
const baseBreakpointId = getBaseBreakpointId(breakpoints);
const wrapperStyleSourceId = "slot-keyboard-wrapper-style";
const divStyleSourceId = "slot-keyboard-div-style";
const headingStyleSourceId = "slot-keyboard-heading-style";
const nextPages = JSON.parse(pages) as {
homePageId: string;
pages: Array<{ id: string; rootInstanceId: string }>;
};
const nextPages = serializedPages.parse(JSON.parse(pages));
const homePage = nextPages.pages.find(
(page) => page.id === nextPages.homePageId
);
@@ -53,6 +44,91 @@ const createSlotKeyboardBuildData = ({
}
homePage.rootInstanceId = rootInstanceId;
const slotPairs = ["", ...additionalPairSuffixes].map((suffix) => {
const slotAId = `slot-keyboard-slot-a${suffix}`;
const slotBId = `slot-keyboard-slot-b${suffix}`;
const fragmentId = `slot-keyboard-fragment${suffix}`;
const divId = `slot-keyboard-div${suffix}`;
const headingId = `slot-keyboard-heading${suffix}`;
const divStyleSourceId = `slot-keyboard-div-style${suffix}`;
const headingStyleSourceId = `slot-keyboard-heading-style${suffix}`;
return {
children: [
{ type: "id", value: slotAId },
{ type: "id", value: slotBId },
],
instances: [
{
type: "instance",
id: slotAId,
component: "Slot",
label: "Slot A",
children: [{ type: "id", value: fragmentId }],
},
{
type: "instance",
id: slotBId,
component: "Slot",
label: "Slot B",
children: [{ type: "id", value: fragmentId }],
},
{
type: "instance",
id: fragmentId,
component: "Fragment",
children: [
{ type: "id", value: divId },
{ type: "id", value: headingId },
],
},
{
type: "instance",
id: divId,
component: "ws:element",
tag: "div",
label: "Drop Div",
children: [{ type: "text", value: "Drop zone" }],
},
{
type: "instance",
id: headingId,
component: "ws:element",
tag: "h1",
label: "Slot Heading",
children: [{ type: "text", value: "Slot heading" }],
},
],
styleSources: [
{ type: "local", id: divStyleSourceId },
{ type: "local", id: headingStyleSourceId },
],
styleSourceSelections: [
{ instanceId: divId, values: [divStyleSourceId] },
{ instanceId: headingId, values: [headingStyleSourceId] },
],
styles: [
{
styleSourceId: divStyleSourceId,
breakpointId: baseBreakpointId,
property: "minHeight",
value: { type: "unit", unit: "px", value: 36 },
},
{
styleSourceId: divStyleSourceId,
breakpointId: baseBreakpointId,
property: "padding",
value: { type: "unit", unit: "px", value: 8 },
},
{
styleSourceId: headingStyleSourceId,
breakpointId: baseBreakpointId,
property: "marginTop",
value: { type: "unit", unit: "px", value: 8 },
},
],
};
});
return {
pages: JSON.stringify(nextPages),
instances: JSON.stringify([
@@ -69,61 +145,18 @@ const createSlotKeyboardBuildData = ({
component: "ws:element",
tag: "main",
label: "Slot Keyboard Wrapper",
children: [
{ type: "id", value: slotAId },
{ type: "id", value: slotBId },
],
},
{
type: "instance",
id: slotAId,
component: "Slot",
label: "Slot A",
children: [{ type: "id", value: fragmentId }],
},
{
type: "instance",
id: slotBId,
component: "Slot",
label: "Slot B",
children: [{ type: "id", value: fragmentId }],
},
{
type: "instance",
id: fragmentId,
component: "Fragment",
children: [
{ type: "id", value: divId },
{ type: "id", value: headingId },
],
},
{
type: "instance",
id: divId,
component: "ws:element",
tag: "div",
label: "Drop Div",
children: [{ type: "text", value: "Drop zone" }],
},
{
type: "instance",
id: headingId,
component: "ws:element",
tag: "h1",
label: "Slot Heading",
children: [{ type: "text", value: "Slot heading" }],
children: slotPairs.flatMap((pair) => pair.children),
},
...slotPairs.flatMap((pair) => pair.instances),
]),
props: JSON.stringify([]),
styleSources: JSON.stringify([
{ type: "local", id: wrapperStyleSourceId },
{ type: "local", id: divStyleSourceId },
{ type: "local", id: headingStyleSourceId },
...slotPairs.flatMap((pair) => pair.styleSources),
]),
styleSourceSelections: JSON.stringify([
{ instanceId: wrapperId, values: [wrapperStyleSourceId] },
{ instanceId: divId, values: [divStyleSourceId] },
{ instanceId: headingId, values: [headingStyleSourceId] },
...slotPairs.flatMap((pair) => pair.styleSourceSelections),
]),
styles: JSON.stringify([
{
@@ -136,26 +169,9 @@ const createSlotKeyboardBuildData = ({
styleSourceId: wrapperStyleSourceId,
breakpointId: baseBreakpointId,
property: "gap",
value: { type: "unit", unit: "px", value: 32 },
},
{
styleSourceId: divStyleSourceId,
breakpointId: baseBreakpointId,
property: "minHeight",
value: { type: "unit", unit: "px", value: 120 },
},
{
styleSourceId: divStyleSourceId,
breakpointId: baseBreakpointId,
property: "padding",
value: { type: "unit", unit: "px", value: 24 },
},
{
styleSourceId: headingStyleSourceId,
breakpointId: baseBreakpointId,
property: "marginTop",
value: { type: "unit", unit: "px", value: 24 },
value: { type: "unit", unit: "px", value: 8 },
},
...slotPairs.flatMap((pair) => pair.styles),
]),
dataSources: JSON.stringify([]),
resources: JSON.stringify([]),
@@ -165,17 +181,22 @@ const createSlotKeyboardBuildData = ({
export const createSlotKeyboardProject = async ({
context,
page,
email = "slot-keyboard-e2e@webstudio.test",
title = "Slot Keyboard E2E",
builderToken = "slot-keyboard-e2e-builder-token",
additionalPairSuffixes = [],
}: {
context: BrowserContext;
page: Page;
email?: string;
title?: string;
builderToken?: string;
additionalPairSuffixes?: string[];
}): Promise<SeededSlotKeyboardProject> => {
return await createSeededBuilderProject({
context,
page,
email,
title,
builderToken,
@@ -183,6 +204,7 @@ export const createSlotKeyboardProject = async ({
createSlotKeyboardBuildData({
pages: build.pages,
breakpoints: build.breakpoints,
additionalPairSuffixes,
}),
});
};
+19 -7
View File
@@ -1,6 +1,6 @@
import path from "node:path";
import type { Page } from "@playwright/test";
import { waitForChangeToBeSaved } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
import { dragPointer } from "./drag";
const assetFixturePath = (filename: string) =>
@@ -93,24 +93,36 @@ export const dragAssetToFolder = async ({
await asset.waitFor({ state: "hidden" });
};
export const uploadAsset = async ({
export const uploadAssets = async ({
page,
filename,
filenames,
}: {
page: Page;
filename: string;
filenames: [string, ...string[]];
}) => {
const fileChooserPromise = page.waitForEvent("filechooser");
await openAddAssetMenu(page);
await page.getByRole("menuitem", { name: "Upload", exact: true }).click();
const fileChooser = await fileChooserPromise;
const save = waitForChangeToBeSaved({ page });
await fileChooser.setFiles(assetFixturePath(filename));
const title = await waitForAsset({ page, filename });
await fileChooser.setFiles(filenames.map(assetFixturePath));
const titles = await Promise.all(
filenames.map((filename) => waitForAsset({ page, filename }))
);
await save;
return title;
// A slow upload can enqueue another save after the first one completes.
await waitForSyncComplete({ page });
return titles;
};
export const uploadAsset = async ({
page,
filename,
}: {
page: Page;
filename: string;
}) => (await uploadAssets({ page, filenames: [filename] }))[0]!;
export const openAssetSettings = async ({
page,
filename,
-28
View File
@@ -1,28 +0,0 @@
import type { Page } from "@playwright/test";
import { waitForCanvasFrame } from "./builder";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
export const deleteContentBlockChildAfterCanvasText = async ({
page,
text,
}: {
page: Page;
text: string;
}) => {
const canvas = await waitForCanvasFrame({ page });
await waitForSyncStatus({ page, status: "idle" });
await page.keyboard.down("Alt");
try {
await canvas.getByText(text, { exact: true }).hover();
const deleteButton = page
.getByRole("button", { name: "Delete block" })
.last();
await deleteButton.waitFor({ state: "visible" });
const save = waitForChangeToBeSaved({ page });
await deleteButton.click();
await save;
} finally {
await page.keyboard.up("Alt");
}
};
+46 -9
View File
@@ -1,4 +1,4 @@
import type { Frame, Page } from "@playwright/test";
import type { Frame, Page, Request, Response } from "@playwright/test";
import { getProjectBuilderUrl } from "../test";
import { measure } from "../perf";
@@ -108,14 +108,51 @@ export const waitForCanvasTextHidden = async ({
};
const openBuilderPage = async (page: Page, url: string): Promise<Frame> => {
await measure("builder page navigation", () => page.goto(url));
const canvas = await measure("builder canvas ready", () =>
waitForCanvasFrame({ page })
);
await measure("builder loading indicator hidden", () =>
page.getByRole("progressbar").waitFor({ state: "hidden", timeout: 30_000 })
);
return canvas;
const startedAt = Date.now();
let dataRequestAt: number | undefined;
let dataResponseAt: number | undefined;
let dataFinishedAt: number | undefined;
const isDataRequest = (request: Request) =>
new URL(request.url()).pathname.includes("build.loadData");
const onRequest = (request: Request) => {
if (isDataRequest(request)) {
dataRequestAt ??= Date.now();
}
};
const onResponse = (response: Response) => {
if (isDataRequest(response.request())) {
dataResponseAt ??= Date.now();
}
};
const onRequestFinished = (request: Request) => {
if (isDataRequest(request)) {
dataFinishedAt = Date.now();
}
};
page.on("request", onRequest);
page.on("response", onResponse);
page.on("requestfinished", onRequestFinished);
try {
await measure("builder page navigation", () => page.goto(url));
const navigationEndedAt = Date.now();
const canvas = await measure("builder canvas iframe attached", () =>
waitForCanvasFrame({ page })
);
const iframeAttachedAt = Date.now();
console.info(
`[e2e:load] navigation=${navigationEndedAt - startedAt}ms data_request=${dataRequestAt === undefined ? "none" : dataRequestAt - startedAt + "ms"} data_response=${dataResponseAt === undefined ? "none" : dataResponseAt - startedAt + "ms"} data_finished=${dataFinishedAt === undefined ? "none" : dataFinishedAt - startedAt + "ms"} iframe_attached=${iframeAttachedAt - startedAt}ms`
);
await measure("builder loading indicator hidden", () =>
page
.getByRole("progressbar")
.waitFor({ state: "hidden", timeout: 30_000 })
);
return canvas;
} finally {
page.off("request", onRequest);
page.off("response", onResponse);
page.off("requestfinished", onRequestFinished);
}
};
export const openProjectBuilder = async ({
+1 -2
View File
@@ -1,5 +1,5 @@
import type { Page } from "@playwright/test";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved } from "./sync-status";
export const addCssDeclaration = async ({
page,
@@ -18,5 +18,4 @@ export const addCssDeclaration = async ({
const save = waitForChangeToBeSaved({ page });
await editor.press("ControlOrMeta+Enter");
await save;
await waitForSyncStatus({ page, status: "idle" });
};
+37 -11
View File
@@ -1,7 +1,7 @@
import { createServer } from "node:http";
import type { Page } from "@playwright/test";
import { selectCanvasTextInstance } from "./canvas-selection";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved } from "./sync-status";
const getVariableForm = (page: Page) =>
page
@@ -9,14 +9,20 @@ const getVariableForm = (page: Page) =>
.filter({ has: page.locator('input[name="name"]') })
.last();
const closeVariablePanelAndWaitForSave = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page });
const closeNewVariablePanel = async ({
page,
name,
}: {
page: Page;
name: string;
}) => {
await page.getByRole("button", { name: "Close" }).last().click();
await save;
await page
.getByText("New variable", { exact: true })
.waitFor({ state: "hidden" });
await waitForSyncStatus({ page, status: "idle" });
await page
.getByRole("button", { name: `Variable ${name}`, exact: true })
.waitFor({ state: "visible" });
};
const openNewVariablePanel = async ({ page }: { page: Page }) => {
@@ -50,8 +56,14 @@ const fillVariableName = async ({
await getVariableForm(page).locator('input[name="name"]').fill(name);
};
export const selectContentInstance = async ({ page }: { page: Page }) => {
await selectCanvasTextInstance({ page, text: "Initial content" });
export const selectContentInstance = async ({
page,
text = "Initial content",
}: {
page: Page;
text?: string;
}) => {
await selectCanvasTextInstance({ page, text });
await page
.getByText("No instance selected", { exact: true })
.waitFor({ state: "hidden" });
@@ -95,10 +107,24 @@ export const bindSelectedTextContentToExpression = async ({
{ cause: error }
);
}
await waitForSyncStatus({ page, status: "idle" });
await page.keyboard.press("Escape");
};
export const createStringVariable = async ({
page,
name,
value,
}: {
page: Page;
name: string;
value: string;
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await page.getByLabel("Value").last().fill(value);
await closeNewVariablePanel({ page, name });
};
export const createHttpResourceVariable = async ({
page,
name,
@@ -112,7 +138,7 @@ export const createHttpResourceVariable = async ({
await fillVariableName({ page, name });
await selectVariableType({ page, next: "REST resource" });
await page.getByRole("textbox", { name: "URL" }).fill(url);
await closeVariablePanelAndWaitForSave({ page });
await closeNewVariablePanel({ page, name });
};
export const createGraphqlResourceVariable = async ({
@@ -131,7 +157,7 @@ export const createGraphqlResourceVariable = async ({
await selectVariableType({ page, next: "GraphQL resource" });
await page.getByRole("textbox", { name: "URL" }).fill(url);
await page.getByRole("textbox", { name: "Query" }).fill(query);
await closeVariablePanelAndWaitForSave({ page });
await closeNewVariablePanel({ page, name });
};
export const createSystemResourceVariable = async ({
@@ -146,7 +172,7 @@ export const createSystemResourceVariable = async ({
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await selectVariableType({ page, next: resource });
await closeVariablePanelAndWaitForSave({ page });
await closeNewVariablePanel({ page, name });
};
export const startJsonResourceServer = async ({ title }: { title: string }) => {
@@ -1,19 +1,84 @@
import { createServer } from "node:http";
import { createServer, type ServerResponse } from "node:http";
export const concurrencyPath = "/submit?tag=concurrency";
export const startFormCallbackReceiver = async () => {
const deliveries: Array<Record<string, unknown>> = [];
const server = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
const body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
deliveries.push(body);
const success = body.outcome !== "failure";
const actionDeliveries: string[] = [];
const legacyRouteDeliveries: Array<{
method: string;
slug: string | null;
routeHeader: string | null;
body: Record<string, unknown>;
}> = [];
const pending: ServerResponse[] = [];
let requestCount = 0;
let barrierReached = false;
let timeout: ReturnType<typeof setTimeout> | undefined;
const respond = (response: ServerResponse, success: boolean) => {
response.writeHead(success ? 200 : 503, {
"content-type": "application/json",
});
response.end(JSON.stringify({ delivered: success }));
};
const server = createServer(async (request, response) => {
requestCount += 1;
const url = new URL(request.url ?? "/", "http://receiver.local");
if (request.method !== "POST" || url.pathname !== "/submit") {
response.writeHead(404).end();
return;
}
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
const body = Buffer.concat(chunks).toString("utf8");
if (request.url === "/submit") {
const callback = JSON.parse(body);
deliveries.push(callback);
respond(response, callback.outcome !== "failure");
return;
}
if (url.searchParams.has("slug")) {
legacyRouteDeliveries.push({
method: request.method,
slug: url.searchParams.get("slug"),
routeHeader: request.headers["x-route-slug"]?.toString() ?? null,
body: JSON.parse(body),
});
respond(response, true);
return;
}
if (request.url !== concurrencyPath) {
response.writeHead(404).end();
return;
}
actionDeliveries.push(body);
if (actionDeliveries.length > 3) {
response.writeHead(409).end();
return;
}
if (barrierReached) {
respond(response, true);
return;
}
pending.push(response);
if (pending.length === 1) {
// A serial dispatcher can never get the second response before the first.
timeout = setTimeout(() => {
for (const waiting of pending.splice(0)) {
waiting.writeHead(504).end("Second Action did not arrive");
}
}, 10_000);
} else {
barrierReached = true;
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
respond(waiting, true);
}
}
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
@@ -24,9 +89,22 @@ export const startFormCallbackReceiver = async () => {
throw new Error("Expected local Form receiver port");
}
return {
url: `http://127.0.0.1:${address.port}/submit`,
port: address.port,
deliveries,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
actionDeliveries,
legacyRouteDeliveries,
get requestCount() {
return requestCount;
},
get barrierReached() {
return barrierReached;
},
close: async () => {
clearTimeout(timeout);
for (const waiting of pending.splice(0)) {
waiting.writeHead(503).end();
}
await new Promise<void>((resolve) => server.close(() => resolve()));
},
};
};
@@ -1,9 +1,12 @@
import { createServer } from "node:http";
export const startLegacyFormQueryReceiver = async () => {
export const startFormQueryReceiver = async () => {
const deliveries: Array<{
method: string;
pathname: string;
search: string;
tag: string | null;
contentType: string;
body: Record<string, unknown>;
}> = [];
const server = createServer(async (request, response) => {
@@ -11,14 +14,20 @@ export const startLegacyFormQueryReceiver = async () => {
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
deliveries.push({
method: request.method ?? "",
tag: new URL(
request.url ?? "/",
"http://receiver.local"
).searchParams.get("tag"),
body: JSON.parse(Buffer.concat(chunks).toString("utf8")),
});
const url = new URL(request.url ?? "/", "http://receiver.local");
try {
deliveries.push({
method: request.method ?? "",
pathname: url.pathname,
search: url.search,
tag: url.searchParams.get("tag"),
contentType: request.headers["content-type"] ?? "",
body: JSON.parse(Buffer.concat(chunks).toString("utf8")),
});
} catch {
response.writeHead(400).end();
return;
}
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ delivered: true }));
});
@@ -28,10 +37,10 @@ export const startLegacyFormQueryReceiver = async () => {
});
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("Expected local legacy Form receiver port");
throw new Error("Expected local Form query receiver port");
}
return {
url: `http://127.0.0.1:${address.port}/submit`,
port: address.port,
deliveries,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
+170
View File
@@ -0,0 +1,170 @@
import { expect, type Page } from "@playwright/test";
import { test } from "../test";
import type { startFormQueryReceiver } from "./form-query-receiver";
import { submitPreviewFormViaMcp } from "./mcp-preview-submit";
export const expectFormQueryDelivery = async ({
page,
url,
receiver,
formId,
resourceId,
}: {
page: Page;
url: string;
receiver: Awaited<ReturnType<typeof startFormQueryReceiver>>;
formId: string;
resourceId: string;
}) => {
await page.route("**/*", (route) =>
new URL(route.request().url()).hostname === "127.0.0.1"
? route.continue()
: route.abort()
);
await test.step("saved deprecated Webhook Form", async () => {
await page.goto(url);
const documentMarker = await page.evaluate(() => {
const marker = crypto.randomUUID();
(
window as Window & { __legacyFormQueryMarker?: string }
).__legacyFormQueryMarker = marker;
return marker;
});
const form = page.locator("#legacy-query-form");
const output = page.locator("#legacy-query-output");
for (const scenario of [
{
link: "Open legacy single query",
path: "/legacy-query?tag=solo",
text: "string:solo",
tag: "solo",
message: "Single query submission",
},
{
link: "Open legacy repeated query",
path: "/legacy-query?tag=second&tag=first&tag=second",
text: "object:second|first|second",
tag: "second|first|second",
message: "Repeated query submission",
},
]) {
await page.getByRole("link", { name: scenario.link }).click();
await expect(page).toHaveURL(new URL(scenario.path, url).href);
await expect(output).toHaveText(scenario.text);
await expect(form).toBeVisible();
await expect
.poll(() =>
page.evaluate(
() =>
(window as Window & { __legacyFormQueryMarker?: string })
.__legacyFormQueryMarker
)
)
.toBe(documentMarker);
const submission = await submitPreviewFormViaMcp({
url,
input: {
path: scenario.path,
selector: "#legacy-query-form",
values: [{ name: "message", value: scenario.message }],
submitter: 'button[type="submit"]',
timeout: 30_000,
},
});
expect(submission.ok).toBe(true);
expect(submission.data).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.data.exchanges).toEqual(
expect.arrayContaining([expect.objectContaining({ status: 200 })])
);
expect(receiver.deliveries.at(-1)).toMatchObject({
method: "POST",
tag: scenario.tag,
body: { message: scenario.message },
});
}
expect(receiver.deliveries).toHaveLength(2);
});
await test.step("managed Form Resource", async () => {
await page.goto(url);
const managedDocumentMarker = await page.evaluate(() => {
const marker = crypto.randomUUID();
(
window as Window & { __managedFormQueryMarker?: string }
).__managedFormQueryMarker = marker;
return marker;
});
const form = page.locator(`[data-ws-managed-form-id="${formId}"]`);
for (const scenario of [
{
link: "Open single Form query",
path: "/form-query?tag=solo",
tag: "solo",
},
{
link: "Open repeated Form query",
path: "/form-query?tag=second&tag=first&tag=second",
tag: ["second", "first", "second"],
},
]) {
await page.getByRole("link", { name: scenario.link }).click();
await expect(page).toHaveURL(new URL(scenario.path, url).href);
await expect(form).toBeVisible();
await expect
.poll(() =>
page.evaluate(
() =>
(window as Window & { __managedFormQueryMarker?: string })
.__managedFormQueryMarker
)
)
.toBe(managedDocumentMarker);
const submission = (
await submitPreviewFormViaMcp({
url,
input: {
path: scenario.path,
selector: `[data-ws-managed-form-id="${formId}"]`,
values: [
{ name: "name", value: "Ada" },
{ name: "email", value: "ada@example.com" },
{ name: "subject", value: "Query shape" },
{ name: "message", value: "Hello" },
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(submission).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.pageUrl).toBe(new URL("/form-query", url).href);
expect(submission.results).toEqual([
expect.objectContaining({ resourceId, status: 200 }),
]);
expect(submission.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: 200,
url: expect.stringContaining("/__ws-form"),
}),
])
);
const delivery = receiver.deliveries.at(-1);
expect(delivery).toMatchObject({
pathname: "/submit",
search: "",
method: "POST",
contentType: expect.stringContaining("application/json"),
});
expect(delivery?.body).toEqual({ tag: scenario.tag });
}
expect(receiver.deliveries).toHaveLength(4);
});
};
+49 -115
View File
@@ -5,7 +5,6 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import type { Page as PlaywrightPage } from "@playwright/test";
import { bundleVersion } from "@webstudio-is/protocol";
import { getStyleDeclKey, type Page } from "@webstudio-is/sdk";
import type { ProjectSettings } from "@webstudio-is/project-build";
@@ -40,13 +39,15 @@ export const waitForGeneratedPreview = async ({
process,
url,
output,
timeout = 120_000,
}: {
process: ChildProcess;
url: string;
output: () => string;
timeout?: number;
}) => {
// Preview also compiles the production app while other E2E workers are active.
const deadline = Date.now() + 120_000;
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
if (process.exitCode !== null || process.signalCode !== null) {
throw new Error(
@@ -138,16 +139,18 @@ export const createLocalBundleFromDevBuild = (build: BuildRow) => {
};
};
export const expectGeneratedAppBuild = async ({
projectId,
expectedText,
}: {
projectId: string;
expectedText?: string;
}) => {
export const expectGeneratedAppBuild = async (
input: ({ projectId: string } | { build: BuildRow }) & {
expectedText?: string;
}
) => {
const { expectedText } = input;
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
const build = await loadDevBuild({ projectId });
const build =
"build" in input
? input.build
: await loadDevBuild({ projectId: input.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
@@ -182,19 +185,29 @@ export const expectGeneratedAppBuild = async ({
}
};
export const withGeneratedPreview = async <Result>({
projectId,
callback,
evaluationReceiverPort,
}: {
projectId: string;
callback: ({ url, html }: { url: string; html: string }) => Promise<Result>;
evaluationReceiverPort?: string;
}) => {
export const startGeneratedPreview = async (
input: ({ projectId: string } | { build: BuildRow }) & {
evaluationReceiverPort?: string;
}
) => {
const { evaluationReceiverPort } = input;
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
let preview: ChildProcess | undefined;
const close = async () => {
try {
if (preview !== undefined) {
// The CLI starts npm and the generated server below it.
await stopChildProcess(preview, { killGroup: true });
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};
try {
const build = await loadDevBuild({ projectId });
const build =
"build" in input
? input.build
: await loadDevBuild({ projectId: input.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
@@ -252,15 +265,26 @@ export const withGeneratedPreview = async <Result>({
output: () => output.join(""),
})
);
return { url, html, close };
} catch (error) {
await close();
throw error;
}
};
export const withGeneratedPreview = async <Result>({
callback,
...input
}: Parameters<typeof startGeneratedPreview>[0] & {
callback: (preview: { url: string; html: string }) => Promise<Result>;
}) => {
const { url, html, close } = await startGeneratedPreview(input);
try {
return await measure("generated app preview callback", () =>
callback({ url, html })
);
} finally {
if (preview !== undefined) {
// The CLI starts npm and the generated server below it.
await stopChildProcess(preview, { killGroup: true });
}
await rm(tempDir, { recursive: true, force: true });
await close();
}
};
@@ -293,96 +317,6 @@ export const expectGeneratedAppToRender = async ({
});
};
export const expectGeneratedAppRedirect = async ({
projectId,
path,
status,
location,
}: {
projectId: string;
path: string;
status: number;
location: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url }) => {
const response = await fetch(new URL(path, url), {
redirect: "manual",
});
const actualLocation = response.headers.get("location");
if (response.status !== status || actualLocation !== location) {
throw new Error(
`Expected generated preview redirect ${JSON.stringify(path)} to return ${status} with location ${JSON.stringify(location)}. Received ${response.status} with location ${JSON.stringify(actualLocation)}.`
);
}
},
});
};
export const expectGeneratedAppNavigation = async ({
projectId,
page,
linkText,
targetPath,
expectedRenderedText,
renderPath,
}: {
projectId: string;
page: PlaywrightPage;
linkText: string;
targetPath: string;
expectedRenderedText?: string;
renderPath?: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url }) => {
if (expectedRenderedText !== undefined) {
const path = renderPath ?? "/";
const response = await fetch(new URL(path, url), {
redirect: "manual",
});
const html = await response.text();
if (
response.ok === false ||
html.includes(expectedRenderedText) === false
) {
throw new Error(
`Expected generated preview route ${JSON.stringify(path)} at ${url} to render ${JSON.stringify(expectedRenderedText)}.`
);
}
}
const targetUrl = new URL(targetPath, url).toString();
await page.goto(url);
await page.getByRole("link", { name: linkText, exact: true }).click();
await page.waitForURL(targetUrl);
const activeLink = page.getByRole("link", {
name: linkText,
exact: true,
});
try {
await activeLink.waitFor({ state: "visible" });
await page.waitForFunction(
({ linkText }) =>
Array.from(document.querySelectorAll("a")).some(
(link) =>
link.textContent?.trim() === linkText &&
link.getAttribute("aria-current") === "page"
),
{ linkText },
{ timeout: 10_000 }
);
} catch {
const ariaCurrent = await activeLink.getAttribute("aria-current");
throw new Error(
`Expected generated preview link ${JSON.stringify(linkText)} to be active after navigating to ${JSON.stringify(targetPath)}. Received aria-current=${JSON.stringify(ariaCurrent)}.`
);
}
},
});
};
export const expectGeneratedRedirects = async ({
projectId,
expectedRedirects,
@@ -1,5 +1,5 @@
import { spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -24,24 +24,31 @@ const cliTsconfigPath = fileURLToPath(
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
);
type PreparePreview = { moduleUrl: string; args: string[] };
export const startGeneratedFormDeliveryPreview = async ({
projectId,
receiverPort,
prepare,
}: {
projectId: string;
receiverPort: number;
prepare?: PreparePreview;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-form-delivery-"));
let preview: ChildProcess | undefined;
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
if (prepare === undefined) {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
}
const port = await getAvailablePort();
const output: string[] = [];
let outputLineBuffer = "";
preview = spawn(
process.execPath,
[
@@ -53,6 +60,9 @@ export const startGeneratedFormDeliveryPreview = async ({
runnerPath,
String(port),
String(receiverPort),
...(prepare === undefined
? []
: [prepare.moduleUrl, projectId, ...prepare.args]),
],
{
cwd: tempDir,
@@ -66,7 +76,18 @@ export const startGeneratedFormDeliveryPreview = async ({
}
);
const appendOutput = (chunk: unknown) => {
output.push(String(chunk));
const value = String(chunk);
output.push(value);
outputLineBuffer += value;
let newlineIndex = outputLineBuffer.indexOf("\n");
while (newlineIndex !== -1) {
const line = outputLineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
outputLineBuffer = outputLineBuffer.slice(newlineIndex + 1);
if (line.startsWith("[e2e:perf]")) {
console.info(line);
}
newlineIndex = outputLineBuffer.indexOf("\n");
}
while (output.join("").length > 8_000) {
output.shift();
}
@@ -80,10 +101,18 @@ export const startGeneratedFormDeliveryPreview = async ({
process: runningPreview,
url,
output: () => output.join(""),
// A combined process includes the former 60-second authoring budget.
timeout: prepare === undefined ? undefined : 180_000,
})
);
return {
url,
prepared:
prepare === undefined
? undefined
: (JSON.parse(
await readFile(join(tempDir, "preview-prepared.json"), "utf8")
) as unknown),
close: async () => {
try {
await stopChildProcess(runningPreview, { killGroup: true });
@@ -107,18 +136,21 @@ export const withGeneratedFormDeliveryPreview = async <Result>({
projectId,
receiverPort,
callback,
prepare,
}: {
projectId: string;
receiverPort: number;
callback: ({ url }: { url: string }) => Promise<Result>;
callback: (preview: { url: string; prepared?: unknown }) => Promise<Result>;
prepare?: PreparePreview;
}) => {
const preview = await startGeneratedFormDeliveryPreview({
projectId,
receiverPort,
prepare,
});
try {
return await measure("generated form preview callback", () =>
callback({ url: preview.url })
callback({ url: preview.url, prepared: preview.prepared })
);
} finally {
await preview.close();
@@ -1,40 +0,0 @@
import { createServer } from "node:http";
export const startLegacyFormRouteReceiver = async () => {
const deliveries: Array<{
method: string;
slug: string | null;
routeHeader: string | null;
body: Record<string, unknown>;
}> = [];
const server = createServer(async (request, response) => {
const chunks: Buffer[] = [];
for await (const chunk of request) {
chunks.push(Buffer.from(chunk));
}
deliveries.push({
method: request.method ?? "",
slug: new URL(
request.url ?? "/",
"http://receiver.local"
).searchParams.get("slug"),
routeHeader: request.headers["x-route-slug"]?.toString() ?? null,
body: JSON.parse(Buffer.concat(chunks).toString("utf8")),
});
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ delivered: true }));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("Expected local legacy Form receiver port");
}
return {
url: `http://127.0.0.1:${address.port}/submit`,
deliveries,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
};
@@ -1,9 +1,10 @@
import { spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { loadDevBuild } from "../db";
import { measure } from "../perf";
import { stopChildProcess } from "../process";
import {
createLocalBundleFromDevBuild,
@@ -23,29 +24,41 @@ const cliTsconfigPath = fileURLToPath(
);
export const withMcpEmailHttpPreview = async <Result>({
projectId,
emailPort,
httpPort,
callback,
...source
}: {
projectId: string;
emailPort: number;
httpPort: number;
callback: ({ url }: { url: string }) => Promise<Result>;
}) => {
callback: (preview: { url: string; prepared?: unknown }) => Promise<Result>;
} & (
| { projectId: string; prepareModule?: string }
| { build: Awaited<ReturnType<typeof loadDevBuild>> }
)) => {
const tempDir = await mkdtemp(
join(tmpdir(), "webstudio-e2e-mcp-email-http-")
);
let preview: ChildProcess | undefined;
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
const prepareArgs =
"projectId" in source && source.prepareModule !== undefined
? [source.prepareModule, source.projectId]
: [];
if (prepareArgs.length === 0) {
const build =
"build" in source
? source.build
: await loadDevBuild({ projectId: source.projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
}
const port = await getAvailablePort();
const output: string[] = [];
let outputLineBuffer = "";
preview = spawn(
process.execPath,
[
@@ -58,6 +71,7 @@ export const withMcpEmailHttpPreview = async <Result>({
String(port),
String(emailPort),
String(httpPort),
...prepareArgs,
],
{
cwd: tempDir,
@@ -71,7 +85,18 @@ export const withMcpEmailHttpPreview = async <Result>({
}
);
const appendOutput = (chunk: unknown) => {
output.push(String(chunk));
const value = String(chunk);
output.push(value);
outputLineBuffer += value;
let newlineIndex = outputLineBuffer.indexOf("\n");
while (newlineIndex !== -1) {
const line = outputLineBuffer.slice(0, newlineIndex).replace(/\r$/, "");
outputLineBuffer = outputLineBuffer.slice(newlineIndex + 1);
if (line.startsWith("[e2e:perf]")) {
console.info(line);
}
newlineIndex = outputLineBuffer.indexOf("\n");
}
while (output.join("").length > 8_000) {
output.shift();
}
@@ -83,8 +108,20 @@ export const withMcpEmailHttpPreview = async <Result>({
process: preview,
url,
output: () => output.join(""),
// Allow time for the author as well as the Preview build when combined.
timeout: prepareArgs.length === 0 ? undefined : 180_000,
});
return await callback({ url });
if (prepareArgs.length === 0) {
return await measure("MCP email HTTP Preview callback", () =>
callback({ url })
);
}
const prepared = JSON.parse(
await readFile(join(tempDir, "preview-prepared.json"), "utf8")
) as unknown;
return await measure("MCP email HTTP Preview callback", () =>
callback({ url, prepared })
);
} finally {
if (preview !== undefined) {
await stopChildProcess(preview, { killGroup: true });
+46 -20
View File
@@ -3,14 +3,11 @@ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { loadDevBuild } from "../db";
import { measure } from "../perf";
import { stopChildProcess } from "../process";
import {
createLocalBundleFromDevBuild,
getAvailablePort,
waitForGeneratedPreview,
} from "./generated-app";
import { getAvailablePort, waitForGeneratedPreview } from "./generated-app";
const runnerPath = fileURLToPath(
new URL("../fixtures/mcp-email-preview.ts", import.meta.url)
@@ -79,23 +76,37 @@ export const startLocalEmailReceiver = async () => {
};
export const withMcpEmailPreview = async <Result>({
projectId,
bundle,
emailPort,
queryPort,
callback,
}: {
projectId: string;
bundle: string;
emailPort: number;
queryPort?: number;
callback: ({ url }: { url: string }) => Promise<Result>;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-mcp-email-"));
const tempDir = await measure(
"generated Email preview source preparation",
async () => {
const directory = await mkdtemp(
join(tmpdir(), "webstudio-e2e-mcp-email-")
);
try {
await mkdir(join(directory, ".webstudio"), { recursive: true });
await writeFile(
join(directory, ".webstudio", "data.json"),
`${bundle}\n`
);
return directory;
} catch (error) {
await rm(directory, { recursive: true, force: true });
throw error;
}
}
);
let preview: ChildProcess | undefined;
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build))}\n`
);
const port = await getAvailablePort();
const output: string[] = [];
preview = spawn(
@@ -109,6 +120,7 @@ export const withMcpEmailPreview = async <Result>({
runnerPath,
String(port),
String(emailPort),
...(queryPort === undefined ? [] : [String(queryPort)]),
],
{
cwd: tempDir,
@@ -129,12 +141,26 @@ export const withMcpEmailPreview = async <Result>({
};
preview.stdout?.on("data", appendOutput);
preview.stderr?.on("data", appendOutput);
if (preview.stdout !== null) {
createInterface({ input: preview.stdout }).on("line", (line) => {
if (
/^\[e2e:perf\] phase="generated Email preview (project preparation|production build|server readiness)" duration=\d+ms$/.test(
line
)
) {
console.info(line);
}
});
}
const url = `http://127.0.0.1:${port}/`;
await waitForGeneratedPreview({
process: preview,
url,
output: () => output.join(""),
});
const runningPreview = preview;
await measure("generated Email preview startup", () =>
waitForGeneratedPreview({
process: runningPreview,
url,
output: () => output.join(""),
})
);
return await callback({ url });
} finally {
if (preview !== undefined) {
+34
View File
@@ -0,0 +1,34 @@
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
const execFileAsync = promisify(execFile);
const reactGlobalPath = fileURLToPath(
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
);
const cliTsconfigPath = fileURLToPath(
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
);
export const runFormAuthor = (
author: string,
projectId: string,
...args: string[]
) =>
execFileAsync(
process.execPath,
[
"--import",
"tsx",
"--import",
reactGlobalPath,
"--conditions=webstudio",
fileURLToPath(new URL(`../fixtures/${author}.ts`, import.meta.url)),
projectId,
...args,
],
{
timeout: 60_000,
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
}
);
+277
View File
@@ -0,0 +1,277 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { test } from "../test";
import { submitPreviewFormViaMcp } from "./mcp-preview-submit";
const scrollCallsKey = "mcp-form-feedback-scroll-calls";
type RedirectForm = {
formId: string;
resourceId: string;
successfulResourceId?: string;
};
export type FormOutcomes = {
successful: RedirectForm;
failed: RedirectForm;
feedback: RedirectForm;
};
const fillContactForm = async (form: Locator) => {
await form.locator('input[name="name"]').fill("Ada");
await form.locator('input[name="email"]').fill("ada@example.com");
await form.locator('input[name="subject"]').fill("Redirect test");
await form
.locator('textarea[name="message"]')
.fill("MCP-authored redirect scenario");
};
const installFeedbackScrollRecorder = async (page: Page) => {
await page.addInitScript((key) => {
if (sessionStorage.getItem(key) === null) {
sessionStorage.setItem(key, "[]");
}
const original = Element.prototype.scrollIntoView;
Element.prototype.scrollIntoView = function (options) {
const calls = JSON.parse(sessionStorage.getItem(key) ?? "[]") as Array<{
text: string;
behavior?: ScrollBehavior;
}>;
calls.push({
text: this.textContent ?? "",
behavior:
typeof options === "object" && options !== null
? options.behavior
: undefined,
});
sessionStorage.setItem(key, JSON.stringify(calls));
original.call(this, options);
};
}, scrollCallsKey);
};
const moveFeedbackBelowViewport = async (page: Page, text: string) => {
await page.evaluate((messageText) => {
const moveFeedback = () => {
const feedback = Array.from(
document.querySelectorAll<HTMLElement>("body *")
).find((element) => element.textContent?.trim() === messageText);
if (feedback === undefined) {
return false;
}
const spacer = document.createElement("div");
spacer.style.height = "1600px";
feedback.parentNode?.insertBefore(spacer, feedback);
(
window as Window & { __mcpFeedbackPositioned?: boolean }
).__mcpFeedbackPositioned = true;
return true;
};
if (moveFeedback()) {
return;
}
const observer = new MutationObserver(() => {
if (moveFeedback()) {
observer.disconnect();
}
});
observer.observe(document.body, { childList: true, subtree: true });
}, text);
};
const getScrollCalls = async (page: Page) =>
await page.evaluate(
(key) =>
JSON.parse(sessionStorage.getItem(key) ?? "[]") as Array<{
text: string;
behavior?: ScrollBehavior;
}>,
scrollCallsKey
);
const expectFeedbackInViewport = async (page: Page, text: string) => {
const feedback = page.getByText(text, { exact: true });
await expect(feedback).toBeVisible();
const getFeedbackState = () =>
feedback.evaluate((element) => {
const bounds = element.getBoundingClientRect();
const calls = JSON.parse(
sessionStorage.getItem("mcp-form-feedback-scroll-calls") ?? "[]"
) as unknown[];
return {
visible:
bounds.width > 0 &&
bounds.height > 0 &&
bounds.top >= 0 &&
bounds.bottom <= window.innerHeight,
tagName: element.tagName,
display: window.getComputedStyle(element).display,
top: bounds.top,
bottom: bounds.bottom,
viewportHeight: window.innerHeight,
scrollY: window.scrollY,
positioned: Boolean(
(window as Window & { __mcpFeedbackPositioned?: boolean })
.__mcpFeedbackPositioned
),
calls,
};
});
try {
await expect.poll(getFeedbackState).toMatchObject({ visible: true });
} catch (cause) {
throw new Error(
`Feedback did not enter viewport: ${JSON.stringify(await getFeedbackState())}`,
{ cause }
);
}
};
export const verifyFormOutcomes = async ({
page,
url,
outcomes: { successful, failed, feedback },
deliveries,
}: {
page: Page;
url: string;
outcomes: FormOutcomes;
deliveries: Array<{ pathname: string; method: string }>;
}) => {
for (const [name, form, fail] of [
["successful", successful, false],
["failed", failed, true],
] as const) {
await test.step("MCP " + name + " Action redirect outcome", async () => {
const submission = (
await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${form.formId}"]`,
values: [
{ name: "name", value: "Ada" },
{ name: "email", value: "ada@example.com" },
{ name: "subject", value: "Redirect test" },
{
name: "message",
value: "MCP-authored redirect scenario",
},
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(submission.status).toBe("submitted");
expect(submission.results).toEqual([
expect.objectContaining({
resourceId: fail ? form.resourceId : form.successfulResourceId,
status: fail ? 503 : 200,
}),
]);
expect(submission.errors).toHaveLength(fail ? 1 : 0);
expect(submission.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: fail ? 502 : 200,
url: expect.stringContaining("/__ws-form"),
}),
])
);
expect(submission.redirect).toBe(
fail ? undefined : new URL(url).origin + "/"
);
expect(deliveries.map(({ pathname }) => pathname)).toEqual(
fail ? ["/reject"] : ["/submit"]
);
deliveries.splice(0);
});
}
await test.step("browser follows success redirect without scrolling feedback", async () => {
await installFeedbackScrollRecorder(page);
await page.goto(url);
const form = page.locator(
'[data-ws-managed-form-id="' + successful.formId + '"]'
);
await moveFeedbackBelowViewport(
page,
"Thanks for contacting us. Your message has been sent."
);
await fillContactForm(form);
const redirected = page.waitForURL(
(target) => target.searchParams.get("mcp-e2e") === "success"
);
await form.getByRole("button", { name: "Submit" }).click();
await redirected;
expect(await getScrollCalls(page)).toEqual([]);
expect(deliveries).toHaveLength(1);
expect(deliveries[0]).toMatchObject({ method: "POST" });
deliveries.splice(0);
});
await test.step("successful Form scrolls off-screen feedback into view", async () => {
await page.emulateMedia({ reducedMotion: "reduce" });
await page.goto(url);
await page.evaluate(
(key) => sessionStorage.setItem(key, "[]"),
scrollCallsKey
);
const form = page.locator(
'[data-ws-managed-form-id="' + feedback.formId + '"]'
);
const message = "Thanks for contacting us. Your message has been sent.";
await moveFeedbackBelowViewport(page, message);
await fillContactForm(form);
await form.getByRole("button", { name: "Submit" }).click();
await expect(form).toHaveAttribute("data-state", "success");
await expectFeedbackInViewport(page, message);
expect(await getScrollCalls(page)).toEqual([
expect.objectContaining({
text: expect.stringContaining(message),
behavior: "instant",
}),
]);
expect(deliveries).toHaveLength(1);
deliveries.splice(0);
});
await test.step("failed Form stays put and remains retryable", async () => {
await page.goto(url);
await page.evaluate(
(key) => sessionStorage.setItem(key, "[]"),
scrollCallsKey
);
const form = page.locator(
'[data-ws-managed-form-id="' + failed.formId + '"]'
);
const message = "We could not send your message. Please try again.";
await moveFeedbackBelowViewport(page, message);
await fillContactForm(form);
await form.getByRole("button", { name: "Submit" }).click();
await expect(form).toHaveAttribute("data-state", "error");
await expect(form.getByText(message, { exact: true })).toBeVisible();
await expectFeedbackInViewport(page, message);
expect(await getScrollCalls(page)).toEqual([
expect.objectContaining({
text: expect.stringContaining(message),
behavior: "instant",
}),
]);
expect(new URL(page.url()).searchParams.has("mcp-e2e")).toBe(false);
await expect
.poll(() => deliveries.map(({ pathname }) => pathname))
.toEqual(["/reject"]);
await form.evaluate((element: HTMLFormElement) => element.requestSubmit());
await expect.poll(() => deliveries.length).toBe(2);
await expect(form).toHaveAttribute("data-state", "error");
await expectFeedbackInViewport(page, message);
expect(new URL(page.url()).searchParams.has("mcp-e2e")).toBe(false);
expect(deliveries.map(({ pathname }) => pathname)).toEqual([
"/reject",
"/reject",
]);
await expectFeedbackInViewport(page, message);
});
};
@@ -1,4 +1,5 @@
import { spawn } from "node:child_process";
import { once } from "node:events";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { createInterface } from "node:readline";
@@ -87,6 +88,13 @@ const startClient = () => {
let client: ReturnType<typeof startClient> | undefined;
let queue = Promise.resolve();
export const startPreviewFormMcpClient = async () => {
if (client === undefined) {
client = startClient();
await once(client.child, "spawn");
}
};
export const closePreviewFormMcpClient = async () => {
await queue;
const activeClient = client;
+39 -45
View File
@@ -1,7 +1,7 @@
import type { Locator, Page } from "@playwright/test";
import { expectLocatorHidden, expectTextHidden } from "./assertions";
import { waitForCanvasText } from "./builder";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
const getPageSettingsControl = ({
page,
@@ -41,11 +41,9 @@ export const fillAllowedPageSettings = async ({
content: string;
};
}) => {
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
await waitForSyncComplete({ page, timeout: 3_000 }).catch(() => undefined);
let save = waitForChangeToBeSaved({ page });
const save = waitForChangeToBeSaved({ page });
for (const field of [
{ label: "Page name", value: name },
{ label: "Path", value: path },
@@ -64,41 +62,9 @@ export const fillAllowedPageSettings = async ({
const socialImageInput = page.getByPlaceholder("https://www.url.com").first();
await socialImageInput.fill(socialImage);
await socialImageInput.blur();
await fillMetadataInputs({ page, ...metadata });
await save;
await waitForSyncStatus({ page, status: "idle" });
await fillCustomMetadata({ page, metadata });
};
export const fillCustomMetadata = async ({
page,
metadata,
}: {
page: Page;
metadata: {
property: string;
content: string;
};
}) => {
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
const metadataGroup = getCustomMetadataGroup(page);
let save = waitForChangeToBeSaved({ page });
await metadataGroup
.getByLabel("Content", { exact: true })
.first()
.fill(metadata.content);
await save;
await waitForSyncStatus({ page, status: "idle" });
save = waitForChangeToBeSaved({ page });
await metadataGroup
.getByLabel("Property", { exact: true })
.first()
.fill(metadata.property);
await save;
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await expectCustomMetadataValue({
page,
@@ -107,6 +73,38 @@ export const fillCustomMetadata = async ({
});
};
const fillMetadataInputs = async ({
page,
property,
content,
}: {
page: Page;
property: string;
content: string;
}) => {
const metadataGroup = getCustomMetadataGroup(page);
await metadataGroup
.getByLabel("Content", { exact: true })
.first()
.fill(content);
await metadataGroup
.getByLabel("Property", { exact: true })
.first()
.fill(property);
};
export const fillCustomMetadata = async (
values: Parameters<typeof fillMetadataInputs>[0]
) => {
const { page } = values;
await waitForSyncComplete({ page });
const save = waitForChangeToBeSaved({ page });
await fillMetadataInputs(values);
await save;
await waitForSyncComplete({ page });
await expectCustomMetadataValue(values);
};
export const openPagesPanel = async ({ page }: { page: Page }) => {
const tab = page.getByRole("tab", { name: "Pages" });
if ((await tab.getAttribute("aria-selected")) !== "true") {
@@ -206,7 +204,7 @@ export const openPage = async ({
await openPagesPanel({ page });
await page.getByText(pageName, { exact: true }).first().click();
await waitForCanvasText({ page, text: canvasText });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
};
export const createFolder = async ({
@@ -229,7 +227,6 @@ export const createFolder = async ({
await page
.getByRole("group", { name: `Folder ${folderName}`, exact: true })
.waitFor();
await waitForSyncStatus({ page, status: "idle" });
};
export const createPageFromTemplate = async ({
@@ -256,7 +253,6 @@ export const createPageFromTemplate = async ({
await save;
await waitForCanvasText({ page, text: canvasText });
await waitForSyncStatus({ page, status: "idle" });
};
export const choosePageSettingsSocialImageAsset = async ({
@@ -268,9 +264,7 @@ export const choosePageSettingsSocialImageAsset = async ({
filename: string;
label?: string;
}) => {
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
await waitForSyncComplete({ page, timeout: 3_000 }).catch(() => undefined);
await page.getByRole("button", { name: "Choose image from assets" }).click();
const save = waitForChangeToBeSaved({ page });
await page.getByAltText(label, { exact: true }).click();
@@ -0,0 +1,322 @@
import type { Page as PlaywrightPage } from "@playwright/test";
import type { Page as WebstudioPage } from "@webstudio-is/sdk";
import { loadDevBuild } from "../db";
import { measure } from "../perf";
import { test } from "../test";
import { openProjectBuilder, waitForCanvasText } from "./builder";
import { expectGeneratedRedirects } from "./generated-app";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
type PersistedPages = {
redirects?: Array<{
old: string;
new: string;
status?: string;
}>;
pages: WebstudioPage[];
};
type PersistedProjectSettings = {
compiler: { atomicStyles?: boolean };
meta: {
auth?: string | null;
siteName?: string;
contactEmail?: string;
emailSender?: string;
};
};
export const getPersistedPages = async ({
projectId,
}: {
projectId: string;
}) => {
const build = await loadDevBuild({ projectId });
return JSON.parse(build.pages) as PersistedPages;
};
export const getPersistedProjectSettings = async ({
projectId,
}: {
projectId: string;
}) => {
const build = await loadDevBuild({ projectId });
return JSON.parse(build.projectSettings) as PersistedProjectSettings;
};
export const openProjectSettings = async ({
page,
}: {
page: PlaywrightPage;
}) => {
await page.getByRole("button", { name: "Menu", exact: true }).click();
await page.getByRole("menuitem", { name: "Project settings" }).click();
await page.getByRole("dialog", { name: "Project settings" }).waitFor();
};
const setAtomicStyles = async ({
page,
checked,
}: {
page: PlaywrightPage;
checked: boolean;
}) => {
await page.getByRole("option", { name: "Publish" }).click();
const checkbox = page.getByRole("checkbox", {
name: "Generate atomic CSS when publishing",
});
if ((await checkbox.isChecked()) === checked) {
await checkbox.click();
}
await checkbox.click();
};
const addRedirect = async ({
page,
from,
to,
}: {
page: PlaywrightPage;
from: string;
to: string;
}) => {
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByPlaceholder("/old-path or /old/*").waitFor();
await page.getByPlaceholder("/old-path or /old/*").fill(from);
await page.getByPlaceholder("/to-path or URL").fill(to);
await page.keyboard.press("Escape");
await page
.getByPlaceholder("/to-path or URL")
.locator("xpath=following::button[2]")
.click();
await page.getByText(from, { exact: true }).waitFor();
};
const deleteRedirect = async ({
page,
from,
}: {
page: PlaywrightPage;
from: string;
}) => {
await page.getByText(from, { exact: true }).hover();
const save = waitForChangeToBeSaved({ page });
await page
.getByRole("button", { name: `Delete redirect from ${from}` })
.click();
await save;
};
const expectPersistedProjectSettings = ({
build,
siteName,
redirect,
}: {
build: Awaited<ReturnType<typeof loadDevBuild>>;
siteName: string;
redirect?: { from: string; to: string; status?: string };
}) => {
const pages = JSON.parse(build.pages) as PersistedPages;
const settings = JSON.parse(
build.projectSettings
) as PersistedProjectSettings;
if (settings.meta.siteName !== siteName) {
throw new Error(
`Expected siteName "${siteName}", received ${JSON.stringify(settings.meta)}.`
);
}
const redirects = pages.redirects ?? [];
if (redirect === undefined) {
if (redirects.length !== 0) {
throw new Error(
`Expected no redirects, received ${JSON.stringify(redirects)}.`
);
}
return;
}
if (
redirects.some(
(entry) =>
entry.old === redirect.from &&
entry.new === redirect.to &&
(entry.status ?? "301") === (redirect.status ?? "301")
) === false
) {
throw new Error(
`Expected redirect ${JSON.stringify(redirect)}, received ${JSON.stringify(redirects)}.`
);
}
};
export const withSavedProjectRedirect = async ({
page,
fixture,
verifyPreview,
}: {
page: PlaywrightPage;
fixture: { projectId: string; builderToken: string };
verifyPreview: (options: {
redirect: { from: string; to: string };
build: Awaited<ReturnType<typeof loadDevBuild>>;
}) => Promise<void>;
}) => {
const siteName = "Runtime Settings Site";
const redirect = {
from: "/e2e-old-route",
to: "/",
};
const recipients = '"Team, West" <team@mcp.test>, Owner <owner@mcp.test>';
const sender = "Project Team <sender@example.com>";
await measure("project settings runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
});
await measure("project settings runtime update settings", async () => {
await openProjectSettings({ page });
await page
.getByRole("textbox", { name: "Site name", exact: true })
.fill(siteName);
await setAtomicStyles({ page, checked: false });
await addRedirect({
page,
from: redirect.from,
to: redirect.to,
});
});
await test.step("Save named email recipients and Reply to", async () => {
await page.getByRole("option", { name: "Emails" }).click();
await page.getByRole("textbox", { name: "Recipients" }).fill(recipients);
await page.getByRole("textbox", { name: "Reply to" }).fill(sender);
await waitForSyncComplete({ page });
});
const savedBuild = await loadDevBuild({ projectId: fixture.projectId });
expectPersistedProjectSettings({ build: savedBuild, siteName, redirect });
const settings = JSON.parse(
savedBuild.projectSettings
) as PersistedProjectSettings;
if (settings.compiler.atomicStyles !== false) {
throw new Error("Expected atomic CSS setting to persist as disabled.");
}
if (
settings.meta.contactEmail !== recipients ||
settings.meta.emailSender !== sender
) {
throw new Error(
`Expected saved Project Emails settings, received ${JSON.stringify(settings.meta)}.`
);
}
// Preview uses this saved version while Builder verifies and deletes the
// redirect. The export after deletion still reads a fresh build from storage.
const checks = await Promise.allSettled([
measure("project settings runtime production Preview", () =>
verifyPreview({ redirect, build: savedBuild })
),
test.step("Verify saved settings and delete redirect in Builder", async () => {
await measure(
"project settings runtime reload with redirect",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
}
);
await openProjectSettings({ page });
await page
.getByRole("textbox", { name: "Site name", exact: true })
.waitFor();
const persistedSiteName = await page
.getByRole("textbox", { name: "Site name", exact: true })
.inputValue();
if (persistedSiteName !== siteName) {
throw new Error(
`Expected project settings site name "${siteName}", received "${persistedSiteName}".`
);
}
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor();
await page.getByRole("option", { name: "Publish" }).click();
if (
await page
.getByRole("checkbox", {
name: "Generate atomic CSS when publishing",
})
.isChecked()
) {
throw new Error(
"Expected atomic CSS setting to remain disabled after reload."
);
}
await test.step("Verify email settings after reload", async () => {
await page.getByRole("option", { name: "Emails" }).click();
if (
(await page
.getByRole("textbox", { name: "Recipients" })
.inputValue()) !== recipients ||
(await page
.getByRole("textbox", { name: "Reply to" })
.inputValue()) !== sender
) {
throw new Error(
"Expected Project Emails settings to survive reload."
);
}
});
await page.getByRole("option", { name: "Redirects" }).click();
await measure("project settings runtime delete redirect", async () => {
await deleteRedirect({ page, from: redirect.from });
});
expectPersistedProjectSettings({
build: await loadDevBuild({ projectId: fixture.projectId }),
siteName,
});
await Promise.all([
measure(
"project settings runtime generated redirects after delete",
() =>
expectGeneratedRedirects({
projectId: fixture.projectId,
expectedRedirects: [],
})
),
measure(
"project settings runtime reload after redirect delete",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
}
),
]);
await openProjectSettings({ page });
await page.getByRole("option", { name: "Redirects" }).click();
await page.getByText(redirect.from, { exact: true }).waitFor({
state: "hidden",
});
}),
]);
for (const check of checks) {
if (check.status === "rejected") {
throw check.reason;
}
}
};
+3 -7
View File
@@ -1,6 +1,6 @@
import type { Page } from "@playwright/test";
import { chooseAssetByFilename } from "./assets-panel";
import { waitForChangeToBeSaved, waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
const getPropertyLabel = ({ page, label }: { page: Page; label: string }) =>
page.getByText(label, { exact: true }).first();
@@ -26,9 +26,7 @@ export const fillSelectedStringProperty = async ({
const input = getPropertyInput({ page, control });
await input.waitFor({ state: "visible", timeout: 10_000 });
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
await waitForSyncComplete({ page, timeout: 3_000 }).catch(() => undefined);
const save = waitForProjectSync
? waitForChangeToBeSaved({ page })
: Promise.resolve();
@@ -75,9 +73,7 @@ export const chooseSelectedAssetProperty = async ({
timeout: 10_000,
});
await waitForSyncStatus({ page, status: "idle", timeout: 3_000 }).catch(
() => undefined
);
await waitForSyncComplete({ page });
await page.getByRole("button", { name: triggerName }).click();
const save = waitForChangeToBeSaved({ page });
if (assetFilename !== undefined) {
+1 -12
View File
@@ -124,6 +124,7 @@ export const createShareLink = async ({
});
const nameInput = customLinkOptions.getByLabel("Name");
await nameInput.fill(name);
await selectRole({ options: customLinkOptions, role });
await saveShareLinkOptions({
page,
closeOptions: () =>
@@ -145,18 +146,6 @@ export const createShareLink = async ({
{ cause: error }
);
}
await renamedLink.getByRole("button", { name: "Options menu" }).click();
const renamedLinkOptions = getShareLinkOptions({ page, name });
const roleChanged = await selectRole({ options: renamedLinkOptions, role });
if (roleChanged) {
await saveShareLinkOptions({
page,
closeOptions: () =>
renamedLink.getByRole("button", { name: "Options menu" }).click(),
});
} else {
await renamedLink.getByRole("button", { name: "Options menu" }).click();
}
await waitForShareLinksReady({ page });
};
+12
View File
@@ -39,6 +39,18 @@ export const waitForSyncStatus = async ({
await getSyncStatusDotByStatus({ page, status }).waitFor({ timeout });
};
export const waitForSyncComplete = async ({
page,
timeout = 10_000,
}: {
page: Page;
timeout?: number;
}) => {
await getSyncStatusDotByStatus({ page, status: "idle" })
.or(getSyncStatusDotByStatus({ page, status: "saved" }))
.waitFor({ timeout });
};
const waitForChangeToBeSavedUnmeasured = async ({
page,
timeout = 10_000,
+10 -3
View File
@@ -1,6 +1,6 @@
import type { Page } from "@playwright/test";
import { waitForCanvasFrame } from "./builder";
import { waitForSyncStatus } from "./sync-status";
import { waitForChangeToBeSaved, waitForSyncComplete } from "./sync-status";
const getVisibleInsertBlockButton = async ({
page,
@@ -36,14 +36,21 @@ export const insertTemplateAfterCanvasText = async ({
page,
anchorText,
templateName,
waitForProjectSync = true,
}: {
page: Page;
anchorText: string;
templateName: string;
waitForProjectSync?: boolean;
}) => {
const insertButton = await getVisibleInsertBlockButton({ page, anchorText });
await insertButton.click();
const template = page.getByRole("menuitemradio", { name: templateName });
if (waitForProjectSync === false) {
await template.click();
return;
}
await page.getByRole("menuitemradio", { name: templateName }).click();
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await Promise.all([waitForChangeToBeSaved({ page }), template.click()]);
};
@@ -0,0 +1,353 @@
import type { Page } from "@playwright/test";
import {
createId,
encodeDataSourceVariable,
type Instance,
} from "@webstudio-is/sdk";
import { loadDevBuild, updateBuild } from "../db";
import { measure } from "../perf";
import { openProjectBuilder, waitForCanvasText } from "./builder";
import { selectNavigatorItem } from "./navigator";
import { waitForChangeToBeSaved } from "./sync-status";
const seedSavedWebhookForm = async (projectId: string) => {
const build = await loadDevBuild({ projectId });
const instances = JSON.parse(build.instances) as Instance[];
const body = instances.find((instance) => instance.id === "body");
if (body === undefined) {
throw new Error("Expected the fixture's body instance");
}
const id = () => createId("nano");
const formId = id();
const stateId = id();
const contentId = id();
const nameLabelId = id();
const nameInputId = id();
const emailLabelId = id();
const emailInputId = id();
const buttonId = id();
const successId = id();
const errorId = id();
const formState = encodeDataSourceVariable(stateId);
const nameStyleId = `${nameLabelId}:ws:style`;
const nameInputStyleId = `${nameInputId}:ws:style`;
const emailStyleId = `${emailLabelId}:ws:style`;
const emailInputStyleId = `${emailInputId}:ws:style`;
const breakpoints = JSON.parse(build.breakpoints) as Array<{
id: string;
label?: string;
minWidth?: number;
maxWidth?: number;
}>;
const baseBreakpoint = breakpoints.find(
({ minWidth, maxWidth }) => minWidth === undefined && maxWidth === undefined
);
const breakpointId = baseBreakpoint?.id ?? "base";
if (baseBreakpoint === undefined) {
breakpoints.push({ id: breakpointId, label: "" });
}
const instancesToAdd: Instance[] = [
{
type: "instance",
id: formId,
component: "WebhookForm",
children: [contentId, successId, errorId].map((value) => ({
type: "id",
value,
})),
},
{
type: "instance",
id: contentId,
component: "ws:element",
tag: "div",
label: "Form Content",
children: [
nameLabelId,
nameInputId,
emailLabelId,
emailInputId,
buttonId,
].map((value) => ({
type: "id",
value,
})),
},
{
type: "instance",
id: nameLabelId,
component: "ws:element",
tag: "label",
children: [{ type: "text", value: "Name", placeholder: true }],
},
{
type: "instance",
id: nameInputId,
component: "ws:element",
tag: "input",
children: [],
},
{
type: "instance",
id: emailLabelId,
component: "ws:element",
tag: "label",
children: [{ type: "text", value: "Email", placeholder: true }],
},
{
type: "instance",
id: emailInputId,
component: "ws:element",
tag: "input",
children: [],
},
{
type: "instance",
id: buttonId,
component: "ws:element",
tag: "button",
children: [{ type: "text", value: "Submit", placeholder: true }],
},
{
type: "instance",
id: successId,
component: "ws:element",
tag: "div",
label: "Success Message",
children: [
{
type: "text",
value: "Thank you for getting in touch!",
placeholder: true,
},
],
},
{
type: "instance",
id: errorId,
component: "ws:element",
tag: "div",
label: "Error Message",
children: [
{
type: "text",
value: "Sorry, something went wrong.",
placeholder: true,
},
],
},
];
body.children.push({ type: "id", value: formId });
const makePropId = (instanceId: string, name: string) =>
`${instanceId}:${name}`;
const expressionProp = (instanceId: string, name: string, value: string) => ({
id: makePropId(instanceId, name),
instanceId,
name,
type: "expression" as const,
value,
mode: "read" as const,
});
const dataSources = JSON.parse(build.dataSources) as unknown[];
const props = JSON.parse(build.props) as unknown[];
const styleSources = JSON.parse(build.styleSources) as unknown[];
const styleSourceSelections = JSON.parse(
build.styleSourceSelections
) as unknown[];
const styles = JSON.parse(build.styles) as unknown[];
await updateBuild(build.id, {
instances: JSON.stringify([...instances, ...instancesToAdd]),
breakpoints: JSON.stringify(breakpoints),
dataSources: JSON.stringify([
...dataSources,
{
type: "variable",
id: stateId,
scopeInstanceId: formId,
name: "formState",
value: { type: "string", value: "initial" },
},
]),
props: JSON.stringify([
...props,
expressionProp(formId, "state", formState),
{
id: makePropId(formId, "onStateChange"),
instanceId: formId,
name: "onStateChange",
type: "action",
value: [
{
type: "execute",
args: ["state"],
code: `${formState} = state`,
},
],
},
expressionProp(
contentId,
"data-ws-show",
`${formState} === 'initial' || ${formState} === 'error'`
),
expressionProp(successId, "data-ws-show", `${formState} === 'success'`),
expressionProp(errorId, "data-ws-show", `${formState} === 'error'`),
{
id: makePropId(nameInputId, "name"),
instanceId: nameInputId,
name: "name",
type: "string",
value: "name",
},
{
id: makePropId(emailInputId, "name"),
instanceId: emailInputId,
name: "name",
type: "string",
value: "email",
},
]),
styleSources: JSON.stringify([
...styleSources,
{ type: "local", id: nameStyleId },
{ type: "local", id: nameInputStyleId },
{ type: "local", id: emailStyleId },
{ type: "local", id: emailInputStyleId },
]),
styleSourceSelections: JSON.stringify([
...styleSourceSelections,
{ instanceId: nameLabelId, values: [nameStyleId] },
{ instanceId: nameInputId, values: [nameInputStyleId] },
{ instanceId: emailLabelId, values: [emailStyleId] },
{ instanceId: emailInputId, values: [emailInputStyleId] },
]),
styles: JSON.stringify([
...styles,
...[nameStyleId, nameInputStyleId, emailStyleId, emailInputStyleId].map(
(styleSourceId) => ({
styleSourceId,
breakpointId,
property: "display",
value: { type: "keyword", value: "block" },
})
),
]),
});
};
const updateResourceActionUrl = async ({
page,
url,
}: {
page: Page;
url: string;
}) => {
await page.getByRole("tab", { name: "Settings" }).click();
await page.getByText("Action", { exact: true }).first().waitFor({
state: "visible",
timeout: 10_000,
});
const input = page.locator("input:not([placeholder])").last();
await input.waitFor({ state: "visible", timeout: 10_000 });
await input.fill(url);
const save = waitForChangeToBeSaved({ page });
await input.press("Enter");
await save;
};
const expectPersistedActionResource = async ({
projectId,
url,
}: {
projectId: string;
url: string;
}) => {
const build = await loadDevBuild({ projectId });
const props = JSON.parse(build.props) as Array<{
name: string;
type: string;
value?: string;
}>;
const resources = JSON.parse(build.resources) as Array<{
id: string;
name: string;
method: string;
url: string;
}>;
const dataSources = JSON.parse(build.dataSources) as Array<{
type: string;
resourceId?: string;
}>;
const resource = resources.find(
(resource) =>
resource.name === "action" &&
resource.method === "post" &&
resource.url === JSON.stringify(url)
);
const actionProp = props.find(
(prop) =>
prop.name === "action" &&
prop.type === "resource" &&
prop.value === resource?.id
);
if (actionProp === undefined || resource === undefined) {
throw new Error(
`Expected Webhook Form action prop to persist resource "${url}". Props: ${JSON.stringify(props)} Resources: ${JSON.stringify(resources)}`
);
}
if (
dataSources.some(
(dataSource) =>
dataSource.type === "resource" && dataSource.resourceId === resource.id
)
) {
throw new Error(
`Expected Webhook Form action resource "${url}" not to load during rendering. Data sources: ${JSON.stringify(dataSources)}`
);
}
};
export const configureSavedWebhookForm = async ({
page,
fixture,
}: {
page: Page;
fixture: { projectId: string; builderToken: string };
}) => {
const text = "Initial content";
const actionUrl = "https://mcp-delivery.example/submit";
await seedSavedWebhookForm(fixture.projectId);
await measure("props runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
features: ["resourceProp"],
});
});
await waitForCanvasText({ page, text });
await selectNavigatorItem({ page, name: "Webhook Form" });
await measure("props runtime update resource action", async () => {
await updateResourceActionUrl({ page, url: actionUrl });
});
await expectPersistedActionResource({
projectId: fixture.projectId,
url: actionUrl,
});
await measure("props runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
features: ["resourceProp"],
});
});
await waitForCanvasText({ page, text });
await expectPersistedActionResource({
projectId: fixture.projectId,
url: actionUrl,
});
};
+58 -26
View File
@@ -34,7 +34,7 @@ case "$mode" in
export E2E_DB_BOOTSTRAP=migrations
export E2E_RUN_TESTS=false
;;
ci-shard)
ci-shard|ci-shard-backend|ci-shard-prepare|ci-shard-test)
export E2E_BACKEND_MODE=snapshot
export E2E_BUILD_DATABASE_IMAGE=false
export E2E_SKIP_BUILDER_BUILD=true
@@ -48,6 +48,13 @@ case "$mode" in
;;
esac
if [ "$mode" = "ci-shard-backend" ]; then
export E2E_DB_BOOTSTRAP=schema
export E2E_GENERATE_PRISMA=false
export E2E_START_POSTGREST=true
export E2E_RUN_TESTS=false
fi
PLAYWRIGHT_ARGS=("$@")
if [ "${PLAYWRIGHT_ARGS[0]:-}" = "--" ]; then
PLAYWRIGHT_ARGS=("${PLAYWRIGHT_ARGS[@]:1}")
@@ -66,7 +73,6 @@ export E2E_BACKEND_MODE="${E2E_BACKEND_MODE:-test}"
source "$ROOT_DIR/apps/builder/backend/lib.sh"
source "$ROOT_DIR/apps/builder/e2e/run-step.sh"
builder_backend_init "$E2E_BACKEND_MODE"
builder_backend_init_schema_snapshot
export E2E_DB_BOOTSTRAP="${E2E_DB_BOOTSTRAP:-auto}"
export E2E_BUILD_DATABASE_IMAGE="${E2E_BUILD_DATABASE_IMAGE:-true}"
@@ -183,37 +189,56 @@ prepare_e2e_database_image() {
builder_backend_pull_db
}
if [ "$E2E_RUN_TESTS" = "true" ]; then
configure_database_urls() {
local db_port="$PGPORT"
if [ "$db_port" = 0 ]; then
db_port="$(builder_compose port db 5432)"
db_port="${db_port##*:}"
fi
export DATABASE_URL="${E2E_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${db_port}/${POSTGRES_DB}?pgbouncer=true}"
export DIRECT_URL="${E2E_DIRECT_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${db_port}/${POSTGRES_DB}}"
}
if [ "$E2E_RUN_TESTS" = "true" ] && [[ "$mode" != ci-shard-* ]]; then
run_step "validate builder e2e test selection" \
"$E2E_TEST_SELECTION_TIMEOUT_SECONDS" validate_builder_e2e_selection
fi
run_step "prepare e2e database image" "$E2E_DOCKER_PULL_TIMEOUT_SECONDS" \
prepare_e2e_database_image
run_step "start e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_start_db
db_port="$PGPORT"
if [ "$db_port" = 0 ]; then
db_port="$(builder_compose port db 5432)"
db_port="${db_port##*:}"
if [ "$mode" = "ci-shard-prepare" ]; then
run_step "generate prisma client" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \
builder_generate_prisma_client "$E2E_GENERATE_PRISMA"
run_step "install playwright chromium" "$E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS" \
install_playwright_chromium
exit 0
fi
export DATABASE_URL="${E2E_DATABASE_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${db_port}/${POSTGRES_DB}?pgbouncer=true}"
export DIRECT_URL="${E2E_DIRECT_URL:-postgresql://${POSTGRES_USER}:${POSTGRES_PASSWORD}@localhost:${db_port}/${POSTGRES_DB}}"
run_step "generate prisma client" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \
builder_generate_prisma_client "$E2E_GENERATE_PRISMA"
if [ "$mode" = "ci-shard-test" ]; then
# The preparation step left these services running on Compose-assigned ports.
configure_database_urls
else
builder_backend_init_schema_snapshot
run_step "prepare e2e database image" "$E2E_DOCKER_PULL_TIMEOUT_SECONDS" \
prepare_e2e_database_image
run_step "wait for e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_wait_for_db "$E2E_DOCKER_TIMEOUT_SECONDS"
run_step "start e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_start_db
configure_database_urls
run_step "bootstrap database schema" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \
bootstrap_database
if [ "$mode" != "ci-shard-backend" ]; then
run_step "generate prisma client" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \
builder_generate_prisma_client "$E2E_GENERATE_PRISMA"
fi
if [ "$E2E_START_POSTGREST" = "true" ]; then
run_step "start e2e postgrest" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_start_postgrest
run_step "wait for e2e database" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_wait_for_db "$E2E_DOCKER_TIMEOUT_SECONDS"
run_step "bootstrap database schema" "$E2E_MIGRATIONS_TIMEOUT_SECONDS" \
bootstrap_database
if [ "$E2E_START_POSTGREST" = "true" ]; then
run_step "start e2e postgrest" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_start_postgrest
fi
fi
postgrest_port="$POSTGREST_PORT"
if [ "$E2E_START_POSTGREST" = "true" ] && [ "$postgrest_port" = 0 ]; then
@@ -222,9 +247,16 @@ if [ "$E2E_START_POSTGREST" = "true" ] && [ "$postgrest_port" = 0 ]; then
fi
export POSTGREST_URL="${E2E_POSTGREST_URL:-http://localhost:${postgrest_port}}"
if [ "$mode" = "ci-shard-backend" ]; then
run_step "wait for e2e postgrest" "$E2E_DOCKER_TIMEOUT_SECONDS" \
builder_backend_wait_for_postgrest "$E2E_DOCKER_TIMEOUT_SECONDS"
fi
if [ "$E2E_RUN_TESTS" = "true" ]; then
run_step "install playwright chromium" "$E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS" \
install_playwright_chromium
if [ "$mode" != "ci-shard-test" ]; then
run_step "install playwright chromium" "$E2E_PLAYWRIGHT_INSTALL_TIMEOUT_SECONDS" \
install_playwright_chromium
fi
if [ "${E2E_BUILDER_URL:-}" = "" ]; then
if [ "${E2E_SKIP_BUILDER_BUILD:-false}" = "true" ]; then
@@ -2,10 +2,8 @@
-- PostgreSQL database dump
--
\restrict webstudioE2ESchema
-- Dumped from database version 15.19 (Debian 15.19-1.pgdg12+2)
-- Dumped by pg_dump version 15.19 (Debian 15.19-1.pgdg12+2)
-- Dumped from database version 15.8
-- Dumped by pg_dump version 15.8
SET statement_timeout = 0;
SET lock_timeout = 0;
@@ -120,6 +118,7 @@ DROP TABLE IF EXISTS public."domainsVirtual";
DROP FUNCTION IF EXISTS public.delete_stale_asset_file_metadata(p_project_id text, p_asset_ids text[]);
DROP FUNCTION IF EXISTS public.delete_asset_file_metadata_if_matches(p_project_id text, p_asset_id text, p_revision text, p_document jsonb);
DROP FUNCTION IF EXISTS public.database_cleanup(from_date timestamp without time zone, to_date timestamp without time zone);
DROP FUNCTION IF EXISTS public.create_production_build_expected(project_id text, deployment text, expected_version integer);
DROP FUNCTION IF EXISTS public.create_production_build(project_id text, deployment text);
DROP FUNCTION IF EXISTS public.clone_project(project_id text, user_id text, title text, domain text);
DROP TABLE IF EXISTS public."Project";
@@ -362,6 +361,38 @@ END;
$$;
--
-- Name: create_production_build_expected(text, text, integer); Type: FUNCTION; Schema: public; Owner: -
--
CREATE FUNCTION public.create_production_build_expected(project_id text, deployment text, expected_version integer) 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(), create_production_build_expected.deployment
FROM "Build"
WHERE "projectId" = project_id
AND "Build".deployment IS NULL
AND version = expected_version
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: -
--
@@ -1877,5 +1908,3 @@ ALTER TABLE ONLY public."latestBuildVirtual"
-- PostgreSQL database dump complete
--
\unrestrict webstudioE2ESchema
@@ -4,11 +4,8 @@ import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import { expectGeneratedAppBuild } from "../flows/generated-app";
import { openNavigatorPanel } from "../flows/navigator";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { waitForSyncComplete } from "../flows/sync-status";
import { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { test } from "../test";
import { measure } from "../perf";
@@ -52,10 +49,7 @@ const wrapSelectedInstance = async ({
);
await optionInput.waitFor();
await optionInput.fill(option);
const save = waitForChangeToBeSaved({ page });
await selectCommandPanelItem({ page, text: option });
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const selectNavigatorItem = async ({
@@ -87,7 +81,7 @@ const addAnimationPreset = async ({
await animationsTitle.waitFor();
await page.getByRole("button", { name: "Add animation" }).click();
await page.getByRole("menuitem", { name: presetName }).click();
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await page.getByText(presetName, { exact: true }).waitFor();
};
@@ -150,14 +144,10 @@ test("Builder animation UI creates supported animation props that persist and bu
// Includes two Builder loads and a generated app build on shared CI CPUs.
test.setTimeout(180_000);
const email = "animation-runtime@webstudio.test";
const fixture = await createContentModeProject({
context: context,
email,
title: "Animation Runtime",
assetNamePrefix: "animation-runtime-",
editorToken: "animation-runtime-editor-token",
builderToken: "animation-runtime-builder-token",
const fixture = await createBuilderEditingProject({
context,
page,
name: "animation-runtime",
});
const text = "Initial content";
const wrapperName = "Animation Group";
@@ -186,23 +176,29 @@ test("Builder animation UI creates supported animation props that persist and bu
presetName,
});
await measure("animation runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text });
await expectPersistedAnimation({
projectId: fixture.projectId,
presetName,
});
await measure("animation runtime generated app build", async () => {
await expectGeneratedAppBuild({
projectId: fixture.projectId,
expectedText: text,
});
});
const results = await Promise.allSettled([
measure("animation runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text });
await expectPersistedAnimation({
projectId: fixture.projectId,
presetName,
});
}),
measure("animation runtime generated app build", () =>
expectGeneratedAppBuild({
projectId: fixture.projectId,
expectedText: text,
})
),
]);
for (const result of results) {
if (result.status === "rejected") {
throw result.reason;
}
}
});
@@ -0,0 +1,156 @@
import { randomUUID } from "node:crypto";
import {
createAssetFolder,
dragAssetToFolder,
openAssetsPanel,
uploadAsset,
} from "../flows/assets-panel";
import { openProjectBuilder } from "../flows/builder";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { insertAssetFolders, insertAuthorizationToken } from "../db";
import { createProjectThroughApi } from "../fixtures/create-project";
import { dashboardUrl, test } from "../test";
test("Asset folder moves survive Builder reload and project cloning", async ({
page,
context,
}) => {
const cloneTitle = "Asset Folder Clone Result";
const projectId = await createProjectThroughApi({
context,
page,
email: "asset-folder-clone-e2e@webstudio.test",
title: "Asset Folder Clone Source",
});
const builderToken = randomUUID();
const parentId = randomUUID();
const childId = randomUUID();
const createdAt = new Date().toISOString();
// This hierarchy is the starting point for the drag and clone checks.
await Promise.all([
insertAuthorizationToken({
token: builderToken,
projectId,
name: "E2E asset folder builder",
relation: "builders",
}),
insertAssetFolders(
[
{ id: parentId, name: "Parent", parentId: null },
{ id: childId, name: "Child", parentId },
].map((folder) => ({ ...folder, projectId, createdAt }))
),
]);
const openSource = () =>
openProjectBuilder({ page, projectId, authToken: builderToken });
await openSource();
await waitForSyncStatus({ page, status: "idle" });
await openAssetsPanel({ page });
const child = page.getByRole("button", { name: "Folder Child", exact: true });
await page
.getByRole("button", { name: "Folder Parent", exact: true })
.dblclick();
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 asset.waitFor();
await child.waitFor();
await dragAssetToFolder({ page, assetTitle, folderName: "Child" });
await child.dblclick();
await asset.waitFor();
await openSource();
await openAssetsPanel({ page });
// Reopening Assets restores Child rather than returning to the root.
await page.getByRole("button", { name: "Back", exact: true }).waitFor();
await asset.waitFor();
await waitForSyncStatus({ page, status: "idle" });
const cloneUrl = new URL("/dashboard", dashboardUrl);
cloneUrl.searchParams.set("projectToCloneAuthToken", 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 Parent", exact: true })
.press("Enter");
await page
.getByRole("button", { name: "Folder Child", exact: true })
.press("Enter");
await page.getByTitle(assetTitle).waitFor();
});
@@ -1,317 +0,0 @@
import {
createAssetFolder,
dragAssetToFolder,
openAssetsPanel,
openAssetSettings,
uploadAsset,
} from "../flows/assets-panel";
import { openProjectBuilder } from "../flows/builder";
import { loginWithSecret } from "../flows/dashboard";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { dashboardUrl, test } from "../test";
test.describe.configure({ mode: "parallel" });
test("Cloning a project preserves nested asset folders", async ({
context,
}) => {
const email = "asset-folder-clone-e2e@webstudio.test";
const sourceTitle = "Asset Folder Clone Source";
const cloneTitle = "Asset Folder Clone Result";
const fixture = await createContentModeProject({
context: context,
email,
title: sourceTitle,
builderToken: "asset-folder-clone-e2e-builder-token",
});
const page = await context.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 ({ page, context }) => {
const fixture = await createContentModeProject({
context: context,
email: "asset-folder-drag-e2e@webstudio.test",
title: "Asset Folder Drag E2E",
builderToken: "asset-folder-drag-e2e-builder-token",
});
const filename = "upload-image.svg";
const folderName = "Images";
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 });
// Reopening Assets restores Images rather than returning to the root.
await page.getByRole("button", { name: "Back", exact: true }).waitFor();
await page.getByTitle(assetTitle).waitFor();
await waitForSyncStatus({ page, status: "idle" });
});
test("Dragging over Back navigates to parent folders before dropping", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context: context,
email: "asset-folder-back-drag-e2e@webstudio.test",
title: "Asset Folder Back Drag E2E",
builderToken: "asset-folder-back-drag-e2e-builder-token",
});
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();
});
test("Asset folder changes wait until the nested selector loses focus", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context: context,
email: "asset-folder-selector-e2e@webstudio.test",
title: "Asset Folder Selector E2E",
builderToken: "asset-folder-selector-e2e-builder-token",
});
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();
});
test("Multiselected assets can be dragged into a folder", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context: context,
email: "asset-folder-multidrag-e2e@webstudio.test",
title: "Asset Folder Multidrag E2E",
builderToken: "asset-folder-multidrag-e2e-builder-token",
});
const folderName = "Selected assets";
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();
});
@@ -0,0 +1,414 @@
import type { Page } from "@playwright/test";
import { loadDevBuild } from "../db";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { openNavigatorPanel } from "../flows/navigator";
import {
resetSelectedProperty,
setSelectedBooleanProperty,
waitForSelectedBooleanPropertyValue,
} from "../flows/props-panel";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { test } from "../test";
import { measure } from "../perf";
const openComponentsPanel = async ({ page }: { page: Page }) => {
await page.getByRole("tab", { name: "Components" }).click();
await page.getByPlaceholder("Find components").waitFor();
};
const insertComponentPanelOption = async ({
page,
name,
component,
}: {
page: Page;
name: string;
component?: string;
}) => {
const search = page.getByPlaceholder("Find components");
await search.fill(name);
const option =
component === undefined
? page.getByRole("option", { name, exact: true })
: page.locator(`[data-drag-component="${component}"]`);
const save = waitForChangeToBeSaved({ page });
await option.click();
await save;
};
const selectNavigatorItem = async ({
page,
itemName,
}: {
page: Page;
itemName: string;
}) => {
await openNavigatorPanel({ page });
const item = page
.locator("[data-navigator-tree] [data-tree-button]")
.filter({ hasText: itemName })
.last();
await item.waitFor({ state: "visible" });
await item.click();
await item.click();
};
const selectFirstNavigatorChild = async ({
page,
parentLabel,
}: {
page: Page;
parentLabel: string;
}) => {
await openNavigatorPanel({ page });
const parent = page
.locator("[data-navigator-tree] [data-tree-button]")
.filter({ hasText: parentLabel })
.first();
await parent.waitFor({ state: "visible" });
await parent.press("ArrowRight");
const child = parent.locator("xpath=following::button[@data-tree-button][1]");
await child.waitFor({ state: "visible" });
await child.click();
await child.click();
};
const pastePlainTextFromClipboardShortcut = async ({
page,
text,
}: {
page: Page;
text: string;
}) => {
const save = waitForChangeToBeSaved({ page });
await page.evaluate((text) => {
const clipboardData = new DataTransfer();
clipboardData.setData("text/plain", text);
document.dispatchEvent(
new ClipboardEvent("paste", {
bubbles: true,
cancelable: true,
clipboardData,
})
);
}, text);
await save;
};
const bindSelectedPropertyToExpression = async ({
page,
label,
expression,
}: {
page: Page;
label: string;
expression: string;
}) => {
await page.getByRole("tab", { name: "Settings" }).click();
await page.getByText(label, { exact: true }).waitFor({
state: "visible",
timeout: 10_000,
});
await page.getByText(label, { exact: true }).hover();
await page
.getByText(label, { exact: true })
.locator("xpath=following::button[@data-variant][1]")
.click();
const bindingDialog = page.getByRole("dialog", { name: "Binding" });
await bindingDialog.waitFor();
const expressionEditor = bindingDialog.locator(".cm-content").last();
await expressionEditor.click();
await page.keyboard.press("ControlOrMeta+A");
await page.keyboard.type(expression);
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+Enter");
await save;
await page.keyboard.press("Escape");
};
const expectPersistedExpressionProp = async ({
projectId,
tag,
text,
name,
expression,
}: {
projectId: string;
tag: string;
text: string;
name: string;
expression: string;
}) => {
const build = await loadDevBuild({ projectId });
const instances = JSON.parse(build.instances) as Array<{
id: string;
component: string;
tag?: string;
children?: Array<{ type: string; value?: string }>;
}>;
const props = JSON.parse(build.props) as Array<{
instanceId: string;
name: string;
type: string;
value?: string;
}>;
const instancesById = new Map(
instances.map((instance) => [instance.id, instance])
);
const instanceContainsText = (instanceId: string): boolean => {
const instance = instancesById.get(instanceId);
if (instance === undefined) {
return false;
}
return (
instance.children?.some((child) => {
if (child.type === "text") {
return child.value?.includes(text);
}
if (child.type === "id" && child.value !== undefined) {
return instanceContainsText(child.value);
}
return false;
}) ?? false
);
};
const instance = instances.find(
(instance) =>
instance.component === "ws:element" &&
instance.tag === tag &&
instanceContainsText(instance.id)
);
const prop = props.find(
(prop) =>
prop.instanceId === instance?.id &&
prop.name === name &&
prop.type === "expression" &&
prop.value === expression
);
if (instance === undefined || prop === undefined) {
throw new Error(
`Expected ${tag} "${text}" to persist expression prop ${name}=${expression}. Props: ${JSON.stringify(props)} Instances: ${JSON.stringify(instances)}`
);
}
};
const expectPersistedBooleanProp = async ({
projectId,
component,
name,
value,
}: {
projectId: string;
component: string;
name: string;
value: boolean;
}) => {
const build = await loadDevBuild({ projectId });
const instances = JSON.parse(build.instances) as Array<{
id: string;
component: string;
}>;
const props = JSON.parse(build.props) as Array<{
instanceId: string;
name: string;
type: string;
value?: unknown;
}>;
const instanceIds = new Set(
instances
.filter((instance) => instance.component === component)
.map((instance) => instance.id)
);
const prop = props.find(
(prop) =>
instanceIds.has(prop.instanceId) &&
prop.name === name &&
prop.type === "boolean" &&
prop.value === value
);
if (prop === undefined) {
throw new Error(
`Expected ${component} ${name}=${value} to persist. Props: ${JSON.stringify(props)}`
);
}
};
const expectBooleanPropDeleted = async ({
projectId,
component,
name,
}: {
projectId: string;
component: string;
name: string;
}) => {
const build = await loadDevBuild({ projectId });
const instances = JSON.parse(build.instances) as Array<{
id: string;
component: string;
}>;
const props = JSON.parse(build.props) as Array<{
instanceId: string;
name: string;
}>;
const instanceIds = new Set(
instances
.filter((instance) => instance.component === component)
.map((instance) => instance.id)
);
if (
props.some((prop) => instanceIds.has(prop.instanceId) && prop.name === name)
) {
throw new Error(
`Expected ${component} ${name} prop to be deleted. Props: ${JSON.stringify(props)}`
);
}
};
test("Props panel expression bindings and checkbox state persist after reload", async ({
page,
context,
}) => {
const fixture = await createBuilderEditingProject({
context,
page,
name: "props-runtime",
});
const anchorText = "Expression-bound link";
const expression = '"/props-expression-link"';
await measure("props expression runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text: "Initial content" });
await measure("props expression runtime paste anchor", async () => {
await openNavigatorPanel({ page });
await selectNavigatorItem({ page, itemName: "Body" });
await pastePlainTextFromClipboardShortcut({
page,
text: `<a href="/initial-props-link">${anchorText}</a>`,
});
});
await waitForCanvasText({ page, text: anchorText });
await measure("props expression runtime bind href", async () => {
await selectNavigatorItem({ page, itemName: "a" });
await bindSelectedPropertyToExpression({
page,
label: "Href",
expression,
});
});
await expectPersistedExpressionProp({
projectId: fixture.projectId,
tag: "a",
text: anchorText,
name: "href",
expression,
});
await selectNavigatorItem({ page, itemName: "Body" });
await measure("props boolean runtime insert checkbox", async () => {
await openComponentsPanel({ page });
await insertComponentPanelOption({
page,
name: "Checkbox",
component: "@webstudio-is/sdk-components-react-radix:Checkbox",
});
});
await selectFirstNavigatorChild({
page,
parentLabel: "Checkbox Field",
});
await page.getByRole("tab", { name: "Settings" }).click();
await measure("props boolean runtime set checked", async () => {
await setSelectedBooleanProperty({
page,
label: "Checked",
checked: true,
});
});
await expectPersistedBooleanProp({
projectId: fixture.projectId,
component: "@webstudio-is/sdk-components-react-radix:Checkbox",
name: "checked",
value: true,
});
await measure("props runtime reload expression and boolean", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text: anchorText });
await expectPersistedExpressionProp({
projectId: fixture.projectId,
tag: "a",
text: anchorText,
name: "href",
expression,
});
await selectFirstNavigatorChild({
page,
parentLabel: "Checkbox Field",
});
await page.getByRole("tab", { name: "Settings" }).click();
await waitForSelectedBooleanPropertyValue({
page,
label: "Checked",
checked: true,
});
await expectPersistedBooleanProp({
projectId: fixture.projectId,
component: "@webstudio-is/sdk-components-react-radix:Checkbox",
name: "checked",
value: true,
});
await measure("props boolean runtime reset checked", async () => {
await resetSelectedProperty({ page, label: "Checked" });
});
await expectBooleanPropDeleted({
projectId: fixture.projectId,
component: "@webstudio-is/sdk-components-react-radix:Checkbox",
name: "checked",
});
await measure("props boolean runtime reload after reset", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await selectFirstNavigatorChild({
page,
parentLabel: "Checkbox Field",
});
await page.getByRole("tab", { name: "Settings" }).click();
await waitForSelectedBooleanPropertyValue({
page,
label: "Checked",
checked: false,
});
await expectBooleanPropDeleted({
projectId: fixture.projectId,
component: "@webstudio-is/sdk-components-react-radix:Checkbox",
name: "checked",
});
});
@@ -0,0 +1,255 @@
import { createServer } from "node:http";
import { expect } from "@playwright/test";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { preparePreviewBundle } from "../fixtures/mcp-navigation-form-author";
import {
startFormDeliveryReceiver,
startGeneratedFormDeliveryPreview,
} from "../flows/generated-form-delivery";
import {
startPreviewFormMcpClient,
submitPreviewFormViaMcp,
} from "../flows/mcp-preview-submit";
import { test, withBrowserContext } from "../test";
test.describe.configure({ mode: "default" });
const formats = [
["format-json", "application/json"],
["format-multipart", "multipart/form-data"],
["format-text", "text/plain"],
] as const;
const startSearchReceiver = async () => {
const tags: Array<string | null> = [];
const server = createServer((request, response) => {
const url = new URL(request.url ?? "/", "http://receiver.local");
const tag = url.searchParams.get("tag");
tags.push(tag);
response.writeHead(200, { "content-type": "application/json" });
response.end(JSON.stringify({ query: JSON.stringify({ tag }) }));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("Expected local search receiver port");
}
return {
url: `http://127.0.0.1:${address.port}/search`,
tags,
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
};
const formIds = new Map<string, string>();
let navigationFormId: string;
let searchReceiver: Awaited<ReturnType<typeof startSearchReceiver>> | undefined;
let receiver: Awaited<ReturnType<typeof startFormDeliveryReceiver>> | undefined;
let preview:
| Awaited<ReturnType<typeof startGeneratedFormDeliveryPreview>>
| undefined;
test.beforeAll(async ({ browser }) => {
await startPreviewFormMcpClient();
const projectId = await withBrowserContext(browser, async (context) => {
const fixture = await createContentModeProject({
context,
email: "mcp-http-formats@webstudio.test",
title: "MCP HTTP body formats",
assetNamePrefix: "mcp-http-formats-",
builderToken: "mcp-http-formats-builder-token",
});
return fixture.projectId;
});
searchReceiver = await startSearchReceiver();
receiver = await startFormDeliveryReceiver();
try {
preview = await startGeneratedFormDeliveryPreview({
projectId,
receiverPort: receiver.port,
prepare: {
moduleUrl: new URL(
"../fixtures/mcp-navigation-form-author.ts",
import.meta.url
).href,
args: [searchReceiver.url, ...formats.map(([mode]) => mode)],
},
});
} catch (error) {
await receiver.close();
receiver = undefined;
throw error;
}
const authored = preview.prepared as Awaited<
ReturnType<typeof preparePreviewBundle>
>;
expect(authored.formatForms).toHaveLength(formats.length);
for (const { mode, formId } of authored.formatForms) {
formIds.set(mode, formId);
}
navigationFormId = authored.navigationFormId;
});
test.afterAll(async () => {
try {
await preview?.close();
} finally {
await Promise.all([receiver?.close(), searchReceiver?.close()]);
}
});
for (const [mode, contentType] of formats) {
test(`MCP-authored Form sends HTTP body with ${mode}`, async () => {
const formId = formIds.get(mode);
const activeReceiver = receiver;
const activePreview = preview;
if (
formId === undefined ||
activeReceiver === undefined ||
activePreview === undefined
) {
throw new Error(`Expected ${mode} Preview fixture`);
}
const deliveryCount = activeReceiver.deliveries.length;
const submission = (
await submitPreviewFormViaMcp({
url: activePreview.url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${formId}"]`,
values: [
{ name: "name", value: "Ada" },
{ name: "email", value: "ada@example.com" },
{ name: "subject", value: "Format test" },
{ name: "message", value: "Exact body text" },
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(submission).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: 200,
url: expect.stringContaining("/__ws-form"),
}),
])
);
expect(submission.results).toEqual([
expect.objectContaining({ status: 200 }),
]);
await expect
.poll(() => activeReceiver.deliveries.length)
.toBe(deliveryCount + 1);
const delivery = activeReceiver.deliveries[deliveryCount];
expect(delivery).toBeDefined();
if (delivery === undefined) {
throw new Error("Expected the formatted HTTP delivery");
}
expect(delivery.pathname).toBe("/submit");
expect(delivery.method).toBe("POST");
expect(delivery.contentType).toContain(contentType);
if (mode === "format-json") {
expect(delivery.contentType).toBe("application/json");
expect(JSON.parse(delivery.body)).toEqual({
sender: "ada@example.com",
message: "Exact body text",
});
} else if (mode === "format-text") {
expect(delivery.contentType).toBe("text/plain");
expect(delivery.body).toBe("Exact body text");
} else {
expect(delivery.contentType).toMatch(/^multipart\/form-data; boundary=/);
const multipart = await new Request("http://127.0.0.1/submit", {
method: "POST",
headers: { "content-type": delivery.contentType },
body: Uint8Array.from(delivery.bodyBytes),
}).formData();
expect(Array.from(multipart.keys()).sort()).toEqual([
"message",
"sender",
]);
expect(multipart.get("message")).toBe("Exact body text");
expect(multipart.get("sender")).toBe("ada@example.com");
}
});
}
test.describe("Navigation without Form Actions", () => {
test("MCP removes Form Actions to enable client-side query navigation and refresh filtered page Resources", async ({
page,
}) => {
const activePreview = preview;
const activeSearchReceiver = searchReceiver;
if (activePreview === undefined || activeSearchReceiver === undefined) {
throw new Error("Expected the navigation Preview fixture");
}
await page.route("**/*", (route) =>
new URL(route.request().url()).hostname === "127.0.0.1"
? route.continue()
: route.abort()
);
await page.goto(new URL("/search", activePreview.url).href);
const marker = await page.evaluate(() => {
const value = crypto.randomUUID();
(
window as Window & { navigationFormMarker?: string }
).navigationFormMarker = value;
return value;
});
const form = page.locator(
`[data-ws-managed-form-id="${navigationFormId}"]`
);
await expect(form).toHaveAttribute("action", "?__webstudio__=navigate");
let resourceSubmissions = 0;
page.on("request", (request) => {
if (
new URL(request.url()).pathname.startsWith("/__ws-form") &&
request.method() === "POST"
) {
resourceSubmissions += 1;
}
});
for (const tags of [["second", "first"], ["first"]]) {
await form.locator('input[name="name"]').fill("Ada");
await form.locator('input[name="email"]').fill("ada@example.com");
await form.locator('input[name="subject"]').fill("Search");
await form.locator('textarea[name="message"]').fill("Filter results");
await form.locator('select[name="tag"]').selectOption(tags);
await form.getByRole("button", { name: "Submit" }).click();
await expect
.poll(() => new URL(page.url()).searchParams.getAll("tag"))
.toEqual(tags);
expect(new URL(page.url()).searchParams.has("__webstudio__")).toBe(false);
await expect
.poll(() =>
page.evaluate(
() =>
(window as Window & { navigationFormMarker?: string })
.navigationFormMarker
)
)
.toBe(marker);
const expectedTag = tags.join("|");
await expect
.poll(() => activeSearchReceiver.tags.at(-1))
.toEqual(expectedTag);
await expect(page.locator("#navigation-search-results")).toContainText(
JSON.stringify(expectedTag)
);
await expect(form).toHaveAttribute("action", "?__webstudio__=navigate");
}
expect(resourceSubmissions).toBe(0);
});
});
@@ -0,0 +1,307 @@
import { expectLocatorHidden, expectTextHidden } from "../flows/assertions";
import {
openBuilderUrl,
openProjectBuilder,
waitForCanvasText,
} from "../flows/builder";
import {
selectCanvasTextInstance,
selectCanvasTextInstanceForProps,
} from "../flows/canvas-selection";
import { replaceCanvasText } from "../flows/content-editing";
import {
copyShareLink,
createShareLink,
expectShareUnavailable,
openShareDialog,
updateShareLinkRole,
} from "../flows/share-dialog";
import { waitForSyncComplete } from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { newIsolatedPage, test } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
const ownerEmail = "share-link-e2e@webstudio.test";
const baselineText = "Initial content";
const expectLinkMode = ({
link,
mode,
}: {
link: string;
mode: "preview" | "content" | "design";
}) => {
const actualMode = new URL(link).searchParams.get("mode");
if (actualMode !== mode) {
throw new Error(`Expected share link mode ${mode}, received ${actualMode}`);
}
};
const expectCurrentMode = ({
pageUrl,
mode,
}: {
pageUrl: string;
mode: "preview" | "content" | "design";
}) => {
const actualMode = new URL(pageUrl).searchParams.get("mode");
if (mode === "design") {
if (actualMode !== null) {
throw new Error(`Expected current mode design, received ${actualMode}`);
}
return;
}
if (actualMode !== mode) {
throw new Error(`Expected current mode ${mode}, received ${actualMode}`);
}
};
test("Share links enforce viewer, editor, builder, admin, and owner permissions", async ({
browser,
context,
page: ownerPage,
}) => {
const fixture = await createContentModeProject({
context,
page: ownerPage,
email: ownerEmail,
title: "Share Link E2E",
devPlan: e2ePaidPlanName,
assetNamePrefix: "share-link-",
editorToken: "share-link-e2e-editor-token",
builderToken: "share-link-e2e-builder-token",
});
await measure("share link open owner project", async () => {
await openProjectBuilder({
page: ownerPage,
projectId: fixture.projectId,
});
});
await waitForCanvasText({ page: ownerPage, text: baselineText });
const { viewerUrl, editorUrl, builderUrl, adminUrl } = await measure(
"share link create links",
async () => {
await openShareDialog({ page: ownerPage });
await createShareLink({
page: ownerPage,
name: "E2E Viewer link",
role: "Viewer",
});
const viewerUrl = await copyShareLink({
page: ownerPage,
name: "E2E Viewer link",
});
await createShareLink({
page: ownerPage,
name: "E2E Editor link",
role: "Editor",
});
const editorUrl = await copyShareLink({
page: ownerPage,
name: "E2E Editor link",
});
await createShareLink({
page: ownerPage,
name: "E2E Builder link",
role: "Builder",
});
const builderUrl = await copyShareLink({
page: ownerPage,
name: "E2E Builder link",
});
await createShareLink({
page: ownerPage,
name: "E2E Admin link",
role: "Admin",
});
const adminUrl = await copyShareLink({
page: ownerPage,
name: "E2E Admin link",
});
return { viewerUrl, editorUrl, builderUrl, adminUrl };
}
);
const editedText = "Share-link editor text";
const collaborativeText = "Collaborative editor text";
expectLinkMode({ link: viewerUrl, mode: "preview" });
expectLinkMode({ link: editorUrl, mode: "content" });
expectLinkMode({ link: builderUrl, mode: "design" });
expectLinkMode({ link: adminUrl, mode: "design" });
await Promise.all([
(async () => {
// Check Viewer and Admin one at a time while the Editor workflow runs.
await test.step("Viewer can view and gains design controls after the owner changes the same link", async () => {
const viewer = await newIsolatedPage(browser);
try {
await openBuilderUrl({ page: viewer.page, url: viewerUrl });
await waitForCanvasText({ page: viewer.page, text: baselineText });
await expectShareUnavailable({ page: viewer.page });
await expectTextHidden({
page: viewer.page,
text: "No instance selected",
});
await expectLocatorHidden({
locator: viewer.page.getByRole("tab", { name: "Style" }),
message: "Expected Style tab to be unavailable for viewer link",
});
await updateShareLinkRole({
page: ownerPage,
name: "E2E Viewer link",
role: "Builder",
});
const updatedBuilderUrl = await copyShareLink({
page: ownerPage,
name: "E2E Viewer link",
});
expectLinkMode({ link: updatedBuilderUrl, mode: "design" });
await ownerPage.close();
await openBuilderUrl({ page: viewer.page, url: updatedBuilderUrl });
await waitForCanvasText({ page: viewer.page, text: baselineText });
await expectShareUnavailable({ page: viewer.page });
await selectCanvasTextInstance({
page: viewer.page,
text: baselineText,
});
await viewer.page
.getByRole("tab", { name: "Style" })
.waitFor({ state: "visible", timeout: 10_000 });
} finally {
await viewer.close();
}
});
await test.step("Admin may publish", async () => {
const admin = await newIsolatedPage(browser);
try {
await openBuilderUrl({ page: admin.page, url: adminUrl });
await waitForCanvasText({ page: admin.page, text: baselineText });
await waitForSyncComplete({ page: admin.page });
await expectShareUnavailable({ page: admin.page });
const publishButton = admin.page.getByRole("button", {
name: "Publish",
});
await publishButton.waitFor({ state: "visible", timeout: 10_000 });
if (await publishButton.isDisabled()) {
throw new Error("Expected admin share link to allow publishing");
}
} finally {
await admin.close();
}
});
})(),
test.step("Editor can save content and collaborate with a Builder", async () => {
const editor = await newIsolatedPage(browser);
const builderPage = await newIsolatedPage(browser);
try {
await openBuilderUrl({ page: editor.page, url: editorUrl });
await waitForCanvasText({ page: editor.page, text: baselineText });
await waitForSyncComplete({ page: editor.page });
expectCurrentMode({ pageUrl: editor.page.url(), mode: "content" });
await insertTemplateAfterCanvasText({
page: editor.page,
anchorText: baselineText,
templateName: fixture.collaborationTemplateName,
});
await waitForCanvasText({
page: editor.page,
text: fixture.collaborationTemplateText,
});
await openBuilderUrl({ page: builderPage.page, url: builderUrl });
await waitForCanvasText({
page: builderPage.page,
text: baselineText,
});
await waitForSyncComplete({ page: builderPage.page });
await expectShareUnavailable({ page: builderPage.page });
await selectCanvasTextInstance({
page: builderPage.page,
text: baselineText,
});
await builderPage.page
.getByRole("tab", { name: "Style" })
.waitFor({ state: "visible", timeout: 10_000 });
await waitForCanvasText({
page: builderPage.page,
text: fixture.collaborationTemplateText,
});
await waitForCanvasText({
page: editor.page,
text: fixture.shareLinkEditableText,
});
await replaceCanvasText({
page: editor.page,
currentText: fixture.shareLinkEditableText,
text: editedText,
waitForProjectSync: false,
});
await replaceCanvasText({
page: editor.page,
currentText: fixture.collaborationTemplateText,
text: collaborativeText,
});
await selectCanvasTextInstance({
page: editor.page,
text: collaborativeText,
});
await expectLocatorHidden({
locator: editor.page.getByRole("tab", { name: "Style" }),
message:
"Expected edit-only collaborator to be blocked from design controls",
});
await Promise.all([
(async () => {
await openBuilderUrl({ page: editor.page, url: editorUrl });
await waitForCanvasText({ page: editor.page, text: editedText });
await waitForCanvasText({
page: editor.page,
text: collaborativeText,
});
await waitForSyncComplete({ page: editor.page });
await expectShareUnavailable({ page: editor.page });
await selectCanvasTextInstanceForProps({
page: editor.page,
text: "Initial link",
propertyLabel: "Href",
});
await expectLocatorHidden({
locator: editor.page.getByRole("tab", { name: "Style" }),
message: "Expected Style tab to be unavailable for editor link",
});
})(),
(async () => {
await openBuilderUrl({ page: builderPage.page, url: builderUrl });
await waitForCanvasText({
page: builderPage.page,
text: collaborativeText,
});
await selectCanvasTextInstance({
page: builderPage.page,
text: collaborativeText,
});
await builderPage.page
.getByRole("tab", { name: "Style" })
.waitFor({ state: "visible" });
await waitForSyncComplete({ page: builderPage.page });
})(),
]);
} finally {
await Promise.all([editor.close(), builderPage.close()]);
}
}),
]);
});
@@ -1,56 +1,23 @@
import { execFile } from "node:child_process";
import { createServer } from "node:http";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect } from "@playwright/test";
import { encodeDataSourceVariable } from "@webstudio-is/sdk";
import { formDataParameterName } from "@webstudio-is/sdk/runtime";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { createProjectThroughApi } from "../fixtures/create-project";
import { loadDevBuild } from "../db";
import {
withMcpEmailPreview,
type CapturedEmail,
} from "../flows/mcp-email-preview";
import type { CapturedEmail } from "../flows/mcp-email-preview";
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
import { startFormContextReceiver } from "../flows/form-context-receiver";
import type { preparePreviewBundle } from "../fixtures/mcp-default-contact-email-author";
import { test } from "../test";
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
import {
startPreviewFormMcpClient,
submitPreviewFormViaMcp,
} from "../flows/mcp-preview-submit";
const execFileAsync = promisify(execFile);
const authorPath = fileURLToPath(
new URL("../fixtures/mcp-default-contact-email-author.ts", import.meta.url)
);
const formDataAuthorPath = fileURLToPath(
new URL("../fixtures/mcp-form-data-string-author.ts", import.meta.url)
);
const reactGlobalPath = fileURLToPath(
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
);
const cliTsconfigPath = fileURLToPath(
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
);
const authorDefaultContactForm = async (projectId: string) => {
const { stdout } = await execFileAsync(
process.execPath,
[
"--import",
"tsx",
"--import",
reactGlobalPath,
"--conditions=webstudio",
authorPath,
projectId,
],
{
timeout: 60_000,
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
}
);
return JSON.parse(stdout) as {
formId: string;
ownerResourceId: string;
visitorResourceId: string;
};
};
const prepareModule = new URL(
"../fixtures/mcp-default-contact-email-author.ts",
import.meta.url
).href;
const submitContactForm = async (url: string, formId: string) =>
await submitPreviewFormViaMcp({
@@ -79,84 +46,19 @@ const submitContactForm = async (url: string, formId: string) =>
},
});
test("MCP Forms deliver readable data and default owner and visitor emails in one Preview", async ({
test("Generated Preview delivers MCP-authored forms with readable email and browser context", async ({
context,
}) => {
const fixture = await createContentModeProject({
await startPreviewFormMcpClient();
const setupPage = await context.newPage();
const projectId = await createProjectThroughApi({
context,
page: setupPage,
email: "mcp-default-contact@webstudio.test",
title: "MCP default contact Form",
assetNamePrefix: "mcp-default-contact-",
builderToken: "mcp-default-contact-builder-token",
});
const { stdout: formDataAuthorOutput } = await execFileAsync(
process.execPath,
[
"--import",
"tsx",
"--import",
reactGlobalPath,
"--conditions=webstudio",
formDataAuthorPath,
fixture.projectId,
],
{
timeout: 60_000,
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
}
);
const {
formId: formDataFormId,
ownerResourceId: formDataResourceId,
expression: formDataExpression,
} = JSON.parse(formDataAuthorOutput) as {
formId: string;
ownerResourceId: string;
expression: string;
};
expect(formDataExpression).toContain(".toString()");
const { formId, ownerResourceId, visitorResourceId } =
await authorDefaultContactForm(fixture.projectId);
const build = await loadDevBuild({ projectId: fixture.projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
email?: Record<string, unknown>;
}>;
expect(
resources.find(({ id }) => id === formDataResourceId)?.email?.body
).toBe(formDataExpression);
const dataSources = JSON.parse(build.dataSources) as Array<{
id: string;
name: string;
scopeInstanceId?: string;
}>;
const formData = dataSources.find(
({ name, scopeInstanceId }) =>
name === formDataParameterName && scopeInstanceId === formId
);
expect(formData).toBeDefined();
expect(
resources.find(({ id }) => id === ownerResourceId)?.email
).toMatchObject({
recipientMode: "project",
body: expect.stringContaining(encodeDataSourceVariable(formData!.id)),
});
expect(
resources.find(({ id }) => id === visitorResourceId)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
subject: expect.stringContaining(".subject"),
body: JSON.stringify(
"Thank you for your message.\n\nWe received it and will respond as soon as possible."
),
});
expect(JSON.parse(build.projectSettings)).toMatchObject({
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
await setupPage.close();
const messages: CapturedEmail[] = [];
let rejectVisitor = false;
const server = createServer(async (request, response) => {
@@ -199,11 +101,65 @@ test("MCP Forms deliver readable data and default owner and visitor emails in on
if (address === null || typeof address === "string") {
throw new Error("Expected a local Email receiver port");
}
const receiver = await startFormContextReceiver();
try {
await withMcpEmailPreview({
projectId: fixture.projectId,
await withMcpEmailHttpPreview({
projectId,
prepareModule,
emailPort: address.port,
callback: async ({ url }) => {
httpPort: receiver.port,
callback: async ({ url, prepared }) => {
const {
formData: {
formId: formDataFormId,
ownerResourceId: formDataResourceId,
expression: formDataExpression,
},
contact: { formId, ownerResourceId, visitorResourceId },
context: { formId: contextFormId },
} = prepared as Awaited<ReturnType<typeof preparePreviewBundle>>;
expect(formDataExpression).toContain(".toString()");
const build = await loadDevBuild({ projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
email?: Record<string, unknown>;
}>;
expect(
resources.find(({ id }) => id === formDataResourceId)?.email?.body
).toBe(formDataExpression);
const dataSources = JSON.parse(build.dataSources) as Array<{
id: string;
name: string;
scopeInstanceId?: string;
}>;
const formData = dataSources.find(
({ name, scopeInstanceId }) =>
name === formDataParameterName && scopeInstanceId === formId
);
expect(formData).toBeDefined();
expect(
resources.find(({ id }) => id === ownerResourceId)?.email
).toMatchObject({
recipientMode: "project",
body: expect.stringContaining(encodeDataSourceVariable(formData!.id)),
});
expect(
resources.find(({ id }) => id === visitorResourceId)?.email
).toMatchObject({
recipientMode: "visitor",
visitorEmailField: "email",
subject: expect.stringContaining(".subject"),
body: JSON.stringify(
"Thank you for your message.\n\nWe received it and will respond as soon as possible."
),
});
expect(JSON.parse(build.projectSettings)).toMatchObject({
meta: {
contactEmail: "owner@mcp.test",
emailSender: "Contact Form <forms@mcp.test>",
},
});
await test.step("Form data email has readable fields and no private values", async () => {
const formDataSubmission = (
await submitPreviewFormViaMcp({
@@ -358,9 +314,95 @@ test("MCP Forms deliver readable data and default owner and visitor emails in on
)
).toBe(true);
});
await test.step("dynamic route form delivers scoped submission and browser values", async () => {
const page = await context.newPage();
await page.route("**/*", (route) =>
new URL(route.request().url()).hostname === "127.0.0.1"
? route.continue()
: route.abort()
);
await context.setExtraHTTPHeaders({
"accept-language": "pt-PT",
"user-agent": "McpFormContextE2E/1.0",
});
await page.goto(url);
await page.getByRole("link", { name: "Open contact Form" }).click();
await expect(page).toHaveURL(
new URL("/contact/autumn?private=omit", url).href
);
const form = page.locator(
`[data-ws-managed-form-id="${contextFormId}"]`
);
await form.locator('input[name="name"]').fill("Ada");
await form.locator('input[name="email"]').fill("ada@example.com");
await form.locator('input[name="subject"]').fill("Context test");
await form.locator('textarea[name="message"]').fill("Hello");
const postRequests: string[] = [];
page.on("request", (request) => {
if (request.method() === "POST") {
postRequests.push(request.url());
}
});
const responsePromise = page.waitForResponse(
(response) =>
new URL(response.url()).pathname.startsWith("/__ws-form") &&
response.request().method() === "POST",
{ timeout: 5_000 }
);
await form.getByRole("button", { name: "Submit" }).click();
const response = await responsePromise.catch(
async (error: unknown) => {
const validity = await form.evaluate(
(element: HTMLFormElement) => ({
valid: element.checkValidity(),
disabled: element.querySelector("button")?.disabled,
invalid: Array.from(element.elements)
.filter(
(control) =>
control instanceof HTMLInputElement ||
control instanceof HTMLTextAreaElement
)
.filter((control) => !control.checkValidity())
.map((control) => ({
name: control.name,
value: control.value,
})),
})
);
throw new Error(
`${String(error)}; Form state=${await form.getAttribute("data-state")}; ` +
`text=${await form.innerText()}; POSTs=${JSON.stringify(postRequests)}; ` +
`validity=${JSON.stringify(validity)}`
);
}
);
expect(response.status()).toBe(200);
expect(await response.json()).toMatchObject({ success: true });
await expect(form).toHaveAttribute("data-state", "success");
expect(receiver.deliveries).toHaveLength(1);
expect(receiver.deliveries[0]).toMatchObject({
method: "POST",
languageHeader: "pt-PT",
body: {
name: "Ada",
email: "ada@example.com",
slug: "autumn",
browser: {
// Local generated Preview has no trusted platform IP header.
ip: null,
userAgent: "McpFormContextE2E/1.0",
language: "pt-PT",
referrer: new URL("/contact/autumn", url).href,
},
},
});
});
},
});
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
await Promise.all([
receiver.close(),
new Promise<void>((resolve) => server.close(() => resolve())),
]);
}
});
@@ -11,6 +11,10 @@ import { waitForChangeToBeSaved } from "../flows/sync-status";
import { measure } from "../perf";
import { test } from "../test";
// Playwright's trace snapshots traverse all 2,000 rows after each action.
// Video and failure screenshots still capture this full Builder workflow.
test.use({ trace: "off" });
test("large-page Navigator selection, repeated reorder, drag, and reload", async ({
page,
context,
@@ -88,7 +92,7 @@ test("large-page Navigator selection, repeated reorder, drag, and reload", async
await openNavigatorPanel({ page });
const tree = page.locator("[data-navigator-tree]");
const row = (index: number) =>
tree.getByRole("button", { name: `Row ${index}`, exact: true });
tree.locator(`[data-navigator-instance-id="row-${index}"]`);
const order = () =>
tree
.locator("[data-tree-button]")
@@ -96,6 +100,7 @@ test("large-page Navigator selection, repeated reorder, drag, and reload", async
buttons.slice(2, 5).map((button) => button.textContent)
);
await measure("large Navigator select row", async () => {
await expect(row(1)).toHaveText("Row 1");
await row(1).click();
await expect(row(1)).toHaveAttribute("aria-selected", "true");
});
@@ -0,0 +1,442 @@
import { createServer } from "node:http";
import { expect } from "@playwright/test";
import { loadDevBuild } from "../db";
import { createBuilderEditingProject } from "../fixtures/builder-editing-project";
import { startFormDeliveryReceiver } from "../flows/generated-form-delivery";
import { withMcpEmailHttpPreview } from "../flows/mcp-email-http-preview";
import { startLocalEmailReceiver } from "../flows/mcp-email-preview";
import {
verifyFormOutcomes,
type FormOutcomes,
} from "../flows/mcp-form-outcomes";
import { runFormAuthor } from "../flows/mcp-form-author";
import {
startPreviewFormMcpClient,
submitPreviewFormViaMcp,
} from "../flows/mcp-preview-submit";
import { withSavedProjectRedirect } from "../flows/project-settings-runtime";
import { e2eEmailPlanName } from "../plans";
import { test } from "../test";
test("Project redirects and MCP-authored Forms run in the same generated production Preview", async ({
page,
context,
}) => {
test.setTimeout(240_000);
await startPreviewFormMcpClient();
const fixture = await createBuilderEditingProject({
context,
name: "mcp-email-attachments",
devPlan: e2eEmailPlanName,
});
const requests: Array<{ method: string; url: string }> = [];
const server = createServer((request, response) => {
if (new URL(request.url ?? "", "http://127.0.0.1").pathname === "/search") {
requests.push({ method: request.method ?? "", url: request.url ?? "" });
}
response.writeHead(200, { "content-type": "text/html" });
response.end('<!doctype html><p id="received">Received</p>');
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", resolve);
});
try {
const address = server.address();
if (address === null || typeof address === "string") {
throw new Error("Expected local receiver port");
}
const receiverUrl = `http://127.0.0.1:${address.port}/search`;
const { stdout } = await runFormAuthor(
"mcp-managed-native-form-author",
fixture.projectId,
receiverUrl
);
const {
callbackForm,
actionForm,
blockedForm,
emailForm,
nativeFormId,
outcomes,
} = JSON.parse(stdout) as {
callbackForm: { formId: string };
actionForm: {
formId: string;
resourceIds: string[];
rejectedResourceId: string;
};
blockedForm: { formId: string; resourceId: string };
emailForm: { formId: string; emailResourceIds: string[] };
nativeFormId: string;
outcomes: FormOutcomes;
};
const { formId: blockedFormId } = blockedForm;
const { formId: emailFormId, emailResourceIds } = emailForm;
expect(emailResourceIds).toHaveLength(2);
const { formId: callbackFormId } = callbackForm;
const { formId, resourceIds, rejectedResourceId } = actionForm;
expect(resourceIds).toHaveLength(10);
expect(new Set([...resourceIds, rejectedResourceId]).size).toBe(11);
const build = await loadDevBuild({ projectId: fixture.projectId });
const formIds = [
blockedFormId,
emailFormId,
formId,
callbackFormId,
nativeFormId,
outcomes.successful.formId,
outcomes.failed.formId,
outcomes.feedback.formId,
];
expect(new Set(formIds).size).toBe(formIds.length);
expect(
(JSON.parse(build.instances) as Array<{ id: string }>).map(({ id }) => id)
).toEqual(expect.arrayContaining(formIds));
const resources = JSON.parse(build.resources) as Array<{
id: string;
name: string;
url?: string;
email?: { includeAttachments?: boolean };
}>;
expect(resources.find(({ id }) => id === blockedForm.resourceId)?.url).toBe(
JSON.stringify("http://127.0.0.1/preview-e2e-must-not-run")
);
const ownerResource = resources.find(
({ id, name }) =>
emailResourceIds.includes(id) && name === "Email to owner"
);
const visitorResource = resources.find(
({ id, name }) =>
emailResourceIds.includes(id) && name === "Email to visitor"
);
expect(ownerResource?.email?.includeAttachments).toBe(true);
expect(visitorResource?.email?.includeAttachments).toBe(false);
const files = [
{
name: "café-notes.txt",
mimeType: "text/plain",
buffer: Buffer.from("First attachment: café\n", "utf8"),
},
{
name: "sample.bin",
mimeType: "application/octet-stream",
buffer: Buffer.from([0, 1, 127, 128, 254, 255]),
},
];
const emailReceiver = await startLocalEmailReceiver();
try {
const receiver = await startFormDeliveryReceiver();
try {
const verifyPreview: Parameters<
typeof withSavedProjectRedirect
>[0]["verifyPreview"] = ({ redirect, build }) =>
withMcpEmailHttpPreview({
build,
emailPort: emailReceiver.port,
httpPort: receiver.port,
callback: async ({ url }) => {
await test.step("Builder redirect returns 301 in generated production Preview", async () => {
const response = await fetch(new URL(redirect.from, url), {
redirect: "manual",
});
expect(response.status).toBe(301);
expect(response.headers.get("location")).toBe(redirect.to);
});
const previewPage = await context.newPage();
await previewPage.route("**/*", (route) =>
new URL(route.request().url()).hostname === "127.0.0.1"
? route.continue()
: route.abort()
);
await previewPage.goto(url);
await test.step("Managed Form requires fields and reports a blocked HTTP action", async () => {
const rendered = previewPage.locator(
`[data-ws-managed-form-id="${blockedFormId}"]`
);
await rendered.getByRole("button", { name: "Submit" }).click();
expect(
await rendered
.locator('input[name="name"]')
.evaluate(
(input: HTMLInputElement) => input.validity.valueMissing
)
).toBe(true);
const bytes = Buffer.from([0, 1, 127, 128, 255]);
const submission = (
await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${blockedFormId}"]`,
values: [
{ name: "name", value: "Ada" },
{ name: "email", value: "ada@example.com" },
{ name: "subject", value: "MCP Preview" },
{ name: "message", value: "Hello from MCP" },
{ name: "tag", value: "first tag" },
{ name: "tag", value: "second tag" },
{
name: "upload",
file: {
name: "sample.bin",
type: "application/octet-stream",
base64: bytes.toString("base64"),
},
},
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(submission).toMatchObject({
status: "submitted",
formState: "error",
results: [],
});
expect(submission.errors).toEqual([
expect.objectContaining({ status: 400 }),
]);
expect(submission.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: 400,
url: expect.stringContaining("/__ws-form"),
}),
])
);
expect(receiver.deliveries).toHaveLength(0);
});
await test.step("Native GET form submits repeated fields to a local receiver", async () => {
const form = previewPage.locator("#native-get-form");
await expect(form).toHaveAttribute("method", "get");
await expect(form).toHaveAttribute("action", receiverUrl);
const invalid = await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: "#native-get-form",
values: [],
submitter: 'button[type="submit"]',
timeout: 30_000,
},
});
expect(invalid.ok).toBe(true);
expect(invalid.data).toMatchObject({
status: "validation_failed",
formState: "invalid",
results: [],
exchanges: [],
});
await expect(previewPage).toHaveURL(url);
expect(requests).toHaveLength(0);
const submitted = await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: "#native-get-form",
values: [
{ name: "tag", value: "second" },
{ name: "tag", value: "first" },
],
submitter: 'button[type="submit"]',
timeout: 30_000,
},
});
expect(submitted.ok).toBe(true);
expect(submitted.data).toMatchObject({
status: "submitted",
results: [],
errors: [],
redirect: receiverUrl,
});
expect(submitted.data.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({ status: 200 }),
])
);
expect(submitted.data.pageUrl).toBe(receiverUrl);
expect(requests).toHaveLength(1);
expect(requests[0].method).toBe("GET");
expect(
new URL(requests[0].url, receiverUrl).searchParams.getAll(
"tag"
)
).toEqual(["second", "first"]);
});
await test.step("authored field-change effect runs before submission", async () => {
const callbackSubmission = (
await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: "#callback-form",
values: [{ name: "outcome", value: "success" }],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(callbackSubmission).toMatchObject({
status: "submitted",
formState: "success",
});
expect(
receiver.deliveries.map(({ body }) => JSON.parse(body))
).toEqual([{ outcome: "success", changeCount: "1" }]);
});
receiver.deliveries.length = 0;
await test.step("ten Actions run in order and an eleventh is rejected", async () => {
const submission = (
await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${formId}"]`,
values: [
{ name: "name", value: "Ada" },
{ name: "email", value: "ada@example.com" },
{ name: "subject", value: "Ten actions" },
{ name: "message", value: "All actions" },
],
submitter: "button[type=submit]",
timeout: 30_000,
},
})
).data;
expect(submission).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.exchanges).toEqual(
expect.arrayContaining([
expect.objectContaining({
status: 200,
url: expect.stringContaining("/__ws-form"),
}),
])
);
expect(submission.results).toEqual(
resourceIds.map((resourceId, index) =>
expect.objectContaining({
resourceId,
resourceName: `HTTP action ${index + 1}`,
status: 200,
})
)
);
expect(JSON.stringify(submission)).not.toContain(
rejectedResourceId
);
expect(receiver.deliveries).toHaveLength(10);
expect(
receiver.deliveries
.map(
({ body }) =>
JSON.parse(body) as { index: number; name: string }
)
.sort((left, right) => left.index - right.index)
).toEqual(
Array.from({ length: 10 }, (_, index) => ({
index: index + 1,
name: "Ada",
}))
);
});
await test.step("email Resources deliver multiple files and honor attachment opt-out", async () => {
const submission = await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${emailFormId}"]`,
values: [
{ name: "name", value: "Ada Lovelace" },
{ name: "email", value: "ada@example.test" },
{ name: "subject", value: "Attachment opt-out test" },
{
name: "message",
value: "Checking separate file delivery settings.",
},
...files.map((file) => ({
name: "upload",
file: {
name: file.name,
type: file.mimeType,
base64: file.buffer.toString("base64"),
},
})),
],
submitter: "button[type=submit]",
timeout: 30_000,
},
});
expect(submission.data).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.data.results).toEqual([
expect.objectContaining({
resourceId: emailResourceIds[0],
status: 200,
}),
expect.objectContaining({
resourceId: emailResourceIds[1],
status: 200,
}),
]);
expect(emailReceiver.messages).toHaveLength(2);
const owner = emailReceiver.messages.find((message) =>
message.to.some(({ address }) => address === "owner@mcp.test")
);
const visitor = emailReceiver.messages.find((message) =>
message.to.some(
({ address }) => address === "ada@example.test"
)
);
expect(owner).toBeDefined();
expect(visitor).toBeDefined();
expect(owner?.attachments).toHaveLength(files.length);
for (const [index, file] of files.entries()) {
const attachment = owner?.attachments?.[index];
expect(attachment?.filename).toBe(file.name);
expect(attachment?.contentType).toBe(file.mimeType);
expect(
Buffer.from(attachment?.contentBase64 ?? "", "base64")
).toEqual(file.buffer);
}
expect(visitor?.attachments).toBeUndefined();
});
receiver.deliveries.length = 0;
await test.step("MCP-authored Forms redirect and show feedback in generated Preview", () =>
verifyFormOutcomes({
page: previewPage,
url,
outcomes,
deliveries: receiver.deliveries,
}));
},
});
await withSavedProjectRedirect({ page, fixture, verifyPreview });
} finally {
await receiver.close();
}
} finally {
await emailReceiver.close();
}
} finally {
await new Promise<void>((resolve) => server.close(() => resolve()));
}
});
@@ -0,0 +1,406 @@
import { expect, type Page } from "@playwright/test";
import type {
StyleDecl,
StyleSource,
StyleSourceSelection,
} from "@webstudio-is/sdk";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import {
waitForCanvasTextStyle,
waitForHoveredCanvasTextStyle,
} from "../flows/canvas-style";
import { openNavigatorPanel } from "../flows/navigator";
import { addCssDeclaration } from "../flows/css-declaration";
import { waitForChangeToBeSaved } from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test } from "../test";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
const setCssValue = async ({
page,
property,
value,
verifyCanvas,
}: {
page: Page;
property: string;
value: string;
verifyCanvas?: () => Promise<void>;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
await input.fill(value);
const save = verifyCanvas && waitForChangeToBeSaved({ page });
await Promise.all([save, input.press("Enter").then(verifyCanvas)]);
};
const resetCssValue = async ({
page,
property,
}: {
page: Page;
property: string;
}) => {
const input = page.getByLabel(property, { exact: true }).first();
const labelText = `${property.slice(0, 1).toUpperCase()}${property.slice(1)}`;
const control = input.locator(
`xpath=ancestor::*[.//*[normalize-space()=${JSON.stringify(labelText)}]][1]`
);
const label = control.getByText(labelText, { exact: true });
await label.waitFor({ state: "visible", timeout: 10_000 });
await label.click({ modifiers: ["Alt"] });
};
const selectStyleSourceState = async ({
page,
state,
}: {
page: Page;
state: string;
}) => {
await page
.getByLabel("Style source menu Local", { exact: true })
.click({ force: true });
await page.getByRole("menuitem", { name: state, exact: true }).click();
};
const selectNavigatorItem = async ({
page,
itemName,
}: {
page: Page;
itemName: string;
}) => {
await openNavigatorPanel({ page });
const item = page
.locator("[data-navigator-tree] [data-tree-button]")
.filter({ hasText: itemName })
.last();
await item.waitFor({ state: "visible" });
await item.click();
await item.click();
};
const readBuildStylesText = async (fixture: SeededContentModeProject) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
return JSON.stringify(JSON.parse(build.styles));
};
const getInstanceChildCount = async ({
fixture,
instanceId,
}: {
fixture: SeededContentModeProject;
instanceId: string;
}) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const instances = JSON.parse(build.instances) as Array<{
id: string;
children?: Array<{ type: string }>;
}>;
return (
instances
.find((instance) => instance.id === instanceId)
?.children?.filter((child) => child.type === "id").length ?? 0
);
};
test("Builder style properties, grid, tokens, and custom breakpoints persist", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context,
page,
email: "style-panel-e2e@webstudio.test",
title: "Style Panel E2E",
assetNamePrefix: "style-panel-e2e-",
});
const bodyInstanceId = "body";
const styledText = "Initial content";
const tokenText = fixture.shareLinkEditableText;
const tokenInstanceId = "share-link-editable-content";
const breakpointName = "E2E Tablet";
const updatedBreakpointName = "E2E Tablet Updated";
const tokenName = "E2E Brand Token";
const openStyleProject = () =>
openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
const expectSavedToken = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const sources: StyleSource[] = JSON.parse(build.styleSources);
const selections: StyleSourceSelection[] = JSON.parse(
build.styleSourceSelections
);
const token = sources.find(
(source) => source.type === "token" && source.name === tokenName
);
expect(token).toBeDefined();
const selection = selections.find(
({ instanceId }) => instanceId === tokenInstanceId
);
expect(selection?.values).toContain(token?.id);
};
const representativeStyles = [
{ property: "font-size", value: "44px", computed: "44px" },
{ property: "line-height", value: "1.25", computed: "55px" },
{ property: "letter-spacing", value: "2px", computed: "2px" },
{ property: "color", value: "#2255ff", computed: "rgb(34, 85, 255)" },
];
const expectRepresentativeCanvasStyles = async () => {
for (const { property, computed } of representativeStyles) {
await waitForCanvasTextStyle({
page,
text: styledText,
property,
value: computed,
});
}
};
const expectHoverCanvasStyle = () =>
waitForHoveredCanvasTextStyle({
page,
text: styledText,
property: "color",
value: "rgb(202, 18, 107)",
});
const readSavedInstanceStyles = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const styles: StyleDecl[] = JSON.parse(build.styles);
const selections: StyleSourceSelection[] = JSON.parse(
build.styleSourceSelections
);
const selection = selections.find(
({ instanceId }) => instanceId === fixture.listItemInstanceId
);
return styles.filter(({ styleSourceId }) =>
selection?.values.includes(styleSourceId)
);
};
const hoverColor = expect.objectContaining({
state: ":hover",
property: "color",
});
const width = expect.objectContaining({ property: "width" });
await openStyleProject();
await waitForCanvasText({ page, text: styledText });
const initialBodyChildCount = await getInstanceChildCount({
fixture,
instanceId: bodyInstanceId,
});
const expectedBodyChildCount = Math.max(initialBodyChildCount, 4);
await test.step("save styles on a design token", async () => {
await selectCanvasTextInstance({ page, text: tokenText });
await page.getByRole("tab", { name: "Style" }).click();
const styleSourceInput = page.getByLabel("New style source input");
await styleSourceInput.fill(tokenName);
await page.getByText(`Create ${tokenName}`, { exact: false }).click();
await page.getByText(tokenName, { exact: true }).waitFor();
await setCssValue({
page,
property: "color",
value: "#b4234c",
verifyCanvas: () =>
waitForCanvasTextStyle({
page,
text: tokenText,
property: "color",
value: "rgb(180, 35, 76)",
}),
});
await expectSavedToken();
});
await test.step("edit and reset representative style properties", async () => {
await selectCanvasTextInstance({ page, text: styledText });
await page.getByRole("tab", { name: "Style" }).click();
for (const { property, value } of representativeStyles) {
await setCssValue({ page, property, value });
}
await setCssValue({
page,
property: "width",
value: "420px",
});
await selectStyleSourceState({ page, state: ":hover" });
await setCssValue({ page, property: "color", value: "#ca126b" });
await selectStyleSourceState({ page, state: ":hover" });
await expectRepresentativeCanvasStyles();
await waitForCanvasTextStyle({
page,
text: styledText,
property: "width",
value: "420px",
});
await expectHoverCanvasStyle();
await expect
.poll(readSavedInstanceStyles)
.toEqual(expect.arrayContaining([hoverColor, width]));
await page.getByRole("tab", { name: "Style" }).click();
await resetCssValue({ page, property: "width" });
});
await test.step("fill the selected grid", async () => {
await selectNavigatorItem({ page, itemName: "Body" });
await page.getByRole("tab", { name: "Style" }).click();
const gridLayout = page.getByRole("button", { name: /Grid layout:/ });
await expect(gridLayout).toBeHidden();
await Promise.all([
measure("style panel runtime enable body grid", () =>
addCssDeclaration({ page, property: "display", value: "grid" })
),
measure("style panel runtime fill body grid", async () => {
await gridLayout.click();
await page.getByRole("button", { name: "Fill grid" }).click();
// The display declaration may save before the new children.
await expect
.poll(
() =>
getInstanceChildCount({
fixture,
instanceId: bodyInstanceId,
}),
{ message: "Fill grid saves the new Body children" }
)
.toBe(expectedBodyChildCount);
await page.keyboard.press("Escape");
}),
]);
const styles = await readBuildStylesText(fixture);
expect(styles).toContain('"display"');
expect(styles).toContain('"grid"');
expect(styles).toContain('"flexDirection"');
expect(styles).toContain('"column"');
// The saved grid changes also cover the width reset on the previous instance.
expect(await readSavedInstanceStyles()).not.toContainEqual(width);
});
await test.step("create, rename, and style a custom breakpoint", async () => {
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
await page.getByRole("button", { name: "Edit breakpoints" }).click();
await page.getByRole("button", { name: "Add breakpoint" }).click();
const nameInput = page.getByPlaceholder("Breakpoint name").first();
const nameSave = waitForChangeToBeSaved({ page });
await nameInput.fill(breakpointName);
await nameInput.blur();
await nameSave;
await nameInput.fill(updatedBreakpointName);
await nameInput.blur();
await page.keyboard.press("Escape");
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
await page.getByText(updatedBreakpointName, { exact: true }).click();
await selectCanvasTextInstance({ page, text: styledText });
await page.getByRole("tab", { name: "Style" }).click();
await setCssValue({
page,
property: "font-size",
value: "31px",
verifyCanvas: () =>
waitForCanvasTextStyle({
page,
text: styledText,
property: "font-size",
value: "31px",
}),
});
});
await openStyleProject();
await waitForCanvasText({ page, text: styledText });
await test.step("verify the reloaded design token and grid", async () => {
await selectCanvasTextInstance({ page, text: tokenText });
await page.getByRole("tab", { name: "Style" }).click();
await page.getByText(tokenName, { exact: true }).waitFor();
await waitForCanvasTextStyle({
page,
text: tokenText,
property: "color",
value: "rgb(180, 35, 76)",
});
await expectSavedToken();
await selectNavigatorItem({ page, itemName: "Body" });
await page.getByRole("tab", { name: "Style" }).click();
await page.getByRole("button", { name: /Grid layout:/ }).waitFor();
const reloadedBodyChildCount = await getInstanceChildCount({
fixture,
instanceId: bodyInstanceId,
});
if (reloadedBodyChildCount !== expectedBodyChildCount) {
throw new Error(
`Expected reloaded Fill grid result to keep ${expectedBodyChildCount} Body children. Got ${reloadedBodyChildCount}`
);
}
});
await test.step("verify and remove the reloaded breakpoint", async () => {
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
await page.getByText(updatedBreakpointName, { exact: true }).click();
await waitForCanvasTextStyle({
page,
text: styledText,
property: "font-size",
value: "31px",
});
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
await page.getByRole("button", { name: "Edit breakpoints" }).click();
await page.locator("[data-breakpoint-delete]").first().click({
force: true,
});
const deleteSave = waitForChangeToBeSaved({ page });
await page.getByRole("button", { name: "Delete" }).click();
await deleteSave;
});
await openStyleProject();
await page
.getByRole("button", { name: "Breakpoints with custom conditions" })
.click();
await page.getByRole("button", { name: "Edit breakpoints" }).waitFor();
await page.getByText(updatedBreakpointName, { exact: true }).waitFor({
state: "hidden",
});
await page.keyboard.press("Escape");
// The new breakpoint has a minimum width of 0. Check the base font size
// once its override has been removed.
await test.step("verify the reloaded style properties", async () => {
await expectRepresentativeCanvasStyles();
await expectHoverCanvasStyle();
await page.mouse.move(0, 0);
const styles = await readSavedInstanceStyles();
expect(styles).toContainEqual(hoverColor);
expect(styles).not.toContainEqual(width);
});
});
@@ -0,0 +1,404 @@
import { expect } from "@playwright/test";
import { randomUUID } from "node:crypto";
import { loadDevBuild } from "../db";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
createAssetFolder,
deleteSelectedAsset,
openAssetSettings,
openAssetsPanel,
replaceSelectedAsset,
uploadAsset,
waitForAsset,
} from "../flows/assets-panel";
import {
openProjectBuilder,
waitForCanvasFrame,
waitForCanvasText,
} from "../flows/builder";
import {
selectCanvasImage,
waitForCanvasImage,
waitForCanvasImageCount,
waitForCanvasImageSourceName,
waitForCanvasVideoSource,
} from "../flows/canvas-media";
import {
waitForCanvasTextStyle,
waitForCanvasTextStyleCount,
} from "../flows/canvas-style";
import { chooseSelectedAssetProperty } from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
import { test } from "../test";
test("Content templates, assets, and collection entries persist across Builder modes", async ({
context,
page,
}) => {
const fixture = await createContentModeProject({
context,
page,
devPlan: e2ePaidPlanName,
email: `content-mode-assets-${randomUUID()}@webstudio.test`,
});
const getImageAssetReferenceCount = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const props = JSON.parse(build.props) as Array<{
name: string;
type: string;
value: string;
}>;
const references = props.filter(
(prop) =>
prop.name === "src" &&
prop.type === "asset" &&
prop.value === fixture.assetTemplateImageAssetId
);
return references.length;
};
const uploadFilename = "large-image.svg";
const replacementFilename = "replacement-image.svg";
const collectionName = "Content collection entries";
const folderName = "Editor ordinary assets";
const entryTitle = "Content collection entry";
const entryFilename = "content-collection-entry.mdx";
const assetsPanel = page.getByRole("tabpanel", { name: "Assets" });
const browseRoot = () =>
assetsPanel.getByRole("button", { name: "Root", exact: true }).click();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
const collection = await createAssetFolder({
page,
name: collectionName,
useAsContentCollection: true,
});
await collection.dblclick();
await page.getByRole("button", { name: "Collection settings" }).waitFor();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForSyncComplete({ page });
await openAssetsPanel({ page });
// The last folder is remembered for this project, including across modes.
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByRole("button", { name: "Add asset" }).click();
await page.getByRole("menuitem", { name: "New entry" }).click();
const dialog = page.getByRole("dialog", { name: "New entry" });
await dialog.getByLabel("Title *").fill(entryTitle);
await Promise.all([
waitForChangeToBeSaved({ page }),
dialog.getByRole("button", { name: "Create entry" }).click(),
]);
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.imageReplacementTemplateName,
waitForProjectSync: false,
});
await waitForCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
let uploadedAssetTitle = "";
await measure("content mode upload image source asset", async () => {
await openAssetsPanel({ page });
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
await selectCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
await measure("content mode choose image source asset", async () => {
await chooseSelectedAssetProperty({
page,
label: "Source",
assetFilename: uploadFilename,
});
});
await waitForCanvasImageSourceName({ page, sourceName: "large-image_" });
const canvas = await waitForCanvasFrame({ page });
const uploadedImage = canvas.locator('img[src*="large-image_"]');
await expect(uploadedImage).toHaveAttribute("width", "240");
await expect(uploadedImage).toHaveAttribute("height", "160");
let replacementAssetTitle = "";
await measure("content mode replace used image source asset", async () => {
await openAssetsPanel({ page });
await openAssetSettings({
page,
filename: uploadedAssetTitle,
});
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await waitForSyncComplete({ page });
const folder = await createAssetFolder({ page, name: folderName });
await folder.dblclick();
const deletedAsset =
await test.step("Upload, replace and delete an unused asset in the ordinary folder", async () => {
const uploadFilename = "upload-image.svg";
const replacementFilename = "large-image.svg";
let uploadedAssetTitle = "";
await measure("content mode upload asset", async () => {
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
let replacementAssetTitle = "";
await measure("content mode replace asset", async () => {
await openAssetSettings({ page, filename: uploadedAssetTitle });
const assetId = await page.locator("#asset-manager-id").inputValue();
if (assetId.length === 0) {
throw new Error(
"Expected Asset settings to expose the uploaded asset id"
);
}
await page.getByText("0 uses", { exact: true }).waitFor();
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await measure("content mode delete asset", async () => {
await openAssetSettings({ page, filename: replacementAssetTitle });
await deleteSelectedAsset({
page,
filename: replacementAssetTitle,
});
});
return { uploadedAssetTitle, replacementAssetTitle };
});
await browseRoot();
await collection.dblclick();
const initialAssetReferenceCount = await getImageAssetReferenceCount();
await test.step("Editor can insert templates with styles and assets", async () => {
await waitForCanvasText({ page, text: "Initial content" });
// Check each insertion on the canvas, then wait for the final save before
// opening the project as Builder and checking persistence across reloads.
await measure("content mode insert asset template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.assetTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await waitForCanvasVideoSource({
page,
sourceName: fixture.assetTemplateVideoName,
});
await measure("content mode insert heading template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.styledHeadingTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
page,
text: fixture.styledHeadingTemplateText,
});
await waitForCanvasTextStyle({
page,
text: fixture.styledHeadingTemplateText,
property: "font-size",
value: fixture.styledHeadingTemplateFontSize,
});
await measure("content mode insert token template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.tokenTemplateLabel,
waitForProjectSync: false,
});
});
await waitForCanvasText({
page,
text: fixture.tokenTemplateVisibleText,
});
await waitForCanvasTextStyle({
page,
text: fixture.tokenTemplateVisibleText,
property: "font-size",
value: fixture.tokenTemplateFontSize,
});
await measure("content mode insert local style templates", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.isolatedLocalTemplateName,
waitForProjectSync: false,
});
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.isolatedLocalTemplateName,
});
});
await waitForCanvasTextStyleCount({
page,
text: fixture.isolatedLocalTemplateText,
property: "font-size",
value: fixture.isolatedLocalTemplateFontSize,
count: 2,
});
});
await test.step("Builder can copy and paste the inserted image and save its asset references", async () => {
await measure("asset copy open build mode", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await selectCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await page.keyboard.press("ControlOrMeta+C");
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+V");
await save;
await waitForSyncComplete({ page });
await waitForCanvasImageCount({
page,
alt: fixture.assetTemplateImageAlt,
count: 2,
});
if (
(await getImageAssetReferenceCount()) !==
initialAssetReferenceCount + 2
) {
throw new Error(
"Expected insertion and paste to add two asset references."
);
}
});
await test.step("Reload content mode and check copied templates, assets, folders, and entries", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForCanvasVideoSource({
page,
sourceName: fixture.assetTemplateVideoName,
});
await waitForCanvasTextStyle({
page,
text: fixture.styledHeadingTemplateText,
property: "font-size",
value: fixture.styledHeadingTemplateFontSize,
});
await waitForCanvasTextStyle({
page,
text: fixture.tokenTemplateVisibleText,
property: "font-size",
value: fixture.tokenTemplateFontSize,
});
await waitForCanvasTextStyleCount({
page,
text: fixture.isolatedLocalTemplateText,
property: "font-size",
value: fixture.isolatedLocalTemplateFontSize,
count: 2,
});
await waitForSyncComplete({ page });
await waitForCanvasImageCount({
page,
alt: fixture.assetTemplateImageAlt,
count: 2,
});
if (
(await getImageAssetReferenceCount()) !==
initialAssetReferenceCount + 2
) {
throw new Error("Expected reload to preserve copied asset references.");
}
await openAssetsPanel({ page });
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await browseRoot();
const expectDeletedAssetAbsent = async () => {
await expect(
assetsPanel.getByTitle(deletedAsset.uploadedAssetTitle)
).toHaveCount(0);
await expect(
assetsPanel.getByTitle(deletedAsset.replacementAssetTitle)
).toHaveCount(0);
};
await expectDeletedAssetAbsent();
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await page.getByTitle(replacementAssetTitle).waitFor();
await waitForSyncComplete({ page });
const reloadedCanvas = await waitForCanvasFrame({ page });
const replacementImage = reloadedCanvas.locator(
'img[src*="replacement-image_"]'
);
await expect(replacementImage).toHaveAttribute("width", "120");
await expect(replacementImage).toHaveAttribute("height", "80");
await folder.dblclick();
await expectDeletedAssetAbsent();
});
});
@@ -1,515 +0,0 @@
import { expect } from "@playwright/test";
import { randomUUID } from "node:crypto";
import {
createAssetFolder,
deleteSelectedAsset,
openAssetSettings,
openAssetsPanel,
replaceSelectedAsset,
uploadAsset,
waitForAsset,
} from "../flows/assets-panel";
import {
openProjectBuilder,
waitForCanvasFrame,
waitForCanvasText,
} from "../flows/builder";
import {
selectCanvasImage,
waitForCanvasImage,
waitForCanvasImageCount,
waitForCanvasImageSourceName,
waitForCanvasVideoSource,
} from "../flows/canvas-media";
import {
waitForCanvasTextStyle,
waitForCanvasTextStyleCount,
} from "../flows/canvas-style";
import { chooseSelectedAssetProperty } from "../flows/props-panel";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
import { loadDevBuild } from "../db";
let fixture: SeededContentModeProject;
test.describe.configure({ mode: "parallel" });
test.beforeEach(async ({ context }) => {
fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: `content-mode-assets-${randomUUID()}@webstudio.test`,
});
});
test("Editor can insert content templates with assets and styles", async ({
page,
}) => {
await measure("content mode open editor for asset template", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: "Initial content" });
await waitForSyncStatus({ page, status: "idle" });
await measure("content mode insert asset template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.assetTemplateName,
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await waitForCanvasVideoSource({
page,
sourceName: fixture.assetTemplateVideoName,
});
await measure("content mode insert heading template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.styledHeadingTemplateName,
});
});
await waitForCanvasText({
page,
text: fixture.styledHeadingTemplateText,
});
await waitForCanvasTextStyle({
page,
text: fixture.styledHeadingTemplateText,
property: "font-size",
value: fixture.styledHeadingTemplateFontSize,
});
await measure("content mode insert token template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.tokenTemplateLabel,
});
});
await waitForCanvasText({
page,
text: fixture.tokenTemplateVisibleText,
});
await waitForCanvasTextStyle({
page,
text: fixture.tokenTemplateVisibleText,
property: "font-size",
value: fixture.tokenTemplateFontSize,
});
await measure("content mode insert local style templates", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.isolatedLocalTemplateName,
});
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.isolatedLocalTemplateName,
});
});
await waitForCanvasTextStyleCount({
page,
text: fixture.isolatedLocalTemplateText,
property: "font-size",
value: fixture.isolatedLocalTemplateFontSize,
count: 2,
});
await measure("content mode reload editor for asset template", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await waitForCanvasVideoSource({
page,
sourceName: fixture.assetTemplateVideoName,
});
await waitForCanvasTextStyle({
page,
text: fixture.styledHeadingTemplateText,
property: "font-size",
value: fixture.styledHeadingTemplateFontSize,
});
await waitForCanvasTextStyle({
page,
text: fixture.tokenTemplateVisibleText,
property: "font-size",
value: fixture.tokenTemplateFontSize,
});
await waitForCanvasTextStyleCount({
page,
text: fixture.isolatedLocalTemplateText,
property: "font-size",
value: fixture.isolatedLocalTemplateFontSize,
count: 2,
});
await waitForSyncStatus({ page, status: "idle" });
});
test("Editor can upload, replace, and delete asset in content mode", async ({
page,
}) => {
const uploadFilename = "upload-image.svg";
const replacementFilename = "replacement-image.svg";
await measure("content mode open editor for asset workflows", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: "Initial content" });
await waitForSyncStatus({ page, status: "idle" });
let uploadedAssetTitle = "";
await measure("content mode upload asset", async () => {
await openAssetsPanel({ page });
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
let replacementAssetTitle = "";
await measure("content mode replace asset", async () => {
await openAssetSettings({ page, filename: uploadedAssetTitle });
const assetId = await page.locator("#asset-manager-id").inputValue();
if (assetId.length === 0) {
throw new Error(
"Expected Asset settings to expose the uploaded asset id"
);
}
await page.getByText("0 uses", { exact: true }).waitFor();
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await measure("content mode delete asset", async () => {
await openAssetSettings({ page, filename: replacementAssetTitle });
await deleteSelectedAsset({
page,
filename: replacementAssetTitle,
});
});
await measure("content mode reload editor for asset workflows", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await openAssetsPanel({ page });
await page.getByTitle(uploadedAssetTitle).waitFor({ state: "hidden" });
await page.getByTitle(replacementAssetTitle).waitFor({ state: "hidden" });
await waitForSyncStatus({ page, status: "idle" });
});
test("Editor can create and reload an ordinary asset folder", async ({
page,
}) => {
const folderName = "Editor ordinary assets";
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForSyncStatus({ page, status: "idle" });
await openAssetsPanel({ page });
await createAssetFolder({ page, name: folderName });
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openAssetsPanel({ page });
await page
.getByRole("button", { name: `Folder ${folderName}`, exact: true })
.waitFor();
});
test("Editor can create and reload a content collection entry", async ({
page,
}) => {
const folderName = "Content collection entries";
const entryTitle = "Content collection entry";
const entryFilename = "content-collection-entry.mdx";
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForSyncStatus({ page, status: "idle" });
await openAssetsPanel({ page });
const folder = await createAssetFolder({
page,
name: folderName,
useAsContentCollection: true,
});
await folder.dblclick();
await page.getByRole("button", { name: "Collection settings" }).waitFor();
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForSyncStatus({ page, status: "idle" });
await openAssetsPanel({ page });
// The last folder is remembered for this project, including across modes.
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByRole("button", { name: "Add asset" }).click();
await page.getByRole("menuitem", { name: "New entry" }).click();
const dialog = page.getByRole("dialog", { name: "New entry" });
await dialog.getByLabel("Title *").fill(entryTitle);
await Promise.all([
waitForChangeToBeSaved({ page }),
dialog.getByRole("button", { name: "Create entry" }).click(),
]);
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openAssetsPanel({ page });
await waitForAsset({ page, filename: entryFilename });
await page.getByTitle("collection.json").waitFor({ state: "visible" });
await page.getByTitle("template.mdx").waitFor({ state: "visible" });
});
test("Editor can replace image source with asset in content mode", async ({
page,
}) => {
const uploadFilename = "large-image.svg";
const replacementFilename = "replacement-image.svg";
await measure(
"content mode open editor for image source asset replacement",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasText({ page, text: "Initial content" });
await waitForSyncStatus({ page, status: "idle" });
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.imageReplacementTemplateName,
});
await waitForCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
let uploadedAssetTitle = "";
await measure("content mode upload image source asset", async () => {
await openAssetsPanel({ page });
uploadedAssetTitle = await uploadAsset({
page,
filename: uploadFilename,
});
});
await selectCanvasImage({
page,
alt: fixture.imageReplacementTemplateImageAlt,
});
await measure("content mode choose image source asset", async () => {
await chooseSelectedAssetProperty({
page,
label: "Source",
assetFilename: uploadFilename,
});
});
await waitForCanvasImageSourceName({ page, sourceName: "large-image_" });
const canvas = await waitForCanvasFrame({ page });
const uploadedImage = canvas.locator('img[src*="large-image_"]');
await expect(uploadedImage).toHaveAttribute("width", "240");
await expect(uploadedImage).toHaveAttribute("height", "160");
let replacementAssetTitle = "";
await measure("content mode replace used image source asset", async () => {
await openAssetsPanel({ page });
await openAssetSettings({
page,
filename: uploadedAssetTitle,
});
replacementAssetTitle = await replaceSelectedAsset({
page,
filename: replacementFilename,
});
});
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await waitForSyncStatus({ page, status: "idle" });
await measure(
"content mode reload editor for image source asset replacement",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasImageSourceName({
page,
sourceName: "replacement-image_",
});
await openAssetsPanel({ page });
await page.getByTitle(replacementAssetTitle).waitFor();
await waitForSyncStatus({ page, status: "idle" });
const reloadedCanvas = await waitForCanvasFrame({ page });
const replacementImage = reloadedCanvas.locator(
'img[src*="replacement-image_"]'
);
await expect(replacementImage).toHaveAttribute("width", "120");
await expect(replacementImage).toHaveAttribute("height", "80");
});
test("Builder copy/paste preserves image asset references after reload", async ({
page,
}) => {
const getImageAssetReferenceCount = async () => {
const build = await loadDevBuild({ projectId: fixture.projectId });
const props = JSON.parse(build.props) as Array<{
name: string;
type: string;
value: string;
}>;
const references = props.filter(
(prop) =>
prop.name === "src" &&
prop.type === "asset" &&
prop.value === fixture.assetTemplateImageAssetId
);
return references.length;
};
await measure("asset copy open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: "Initial content" });
const initialAssetReferenceCount = await getImageAssetReferenceCount();
await measure("asset copy insert template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.assetTemplateName,
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await measure("asset copy open build mode", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await selectCanvasImage({
page,
alt: fixture.assetTemplateImageAlt,
});
await page.keyboard.press("ControlOrMeta+C");
const save = waitForChangeToBeSaved({ page });
await page.keyboard.press("ControlOrMeta+V");
await save;
await waitForSyncStatus({ page, status: "idle" });
await waitForCanvasImageCount({
page,
alt: fixture.assetTemplateImageAlt,
count: 2,
});
if (
(await getImageAssetReferenceCount()) !==
initialAssetReferenceCount + 2
) {
throw new Error(
"Expected insertion and paste to add two asset references."
);
}
await measure("asset copy reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasImageCount({
page,
alt: fixture.assetTemplateImageAlt,
count: 2,
});
if (
(await getImageAssetReferenceCount()) !==
initialAssetReferenceCount + 2
) {
throw new Error("Expected reload to preserve copied asset references.");
}
});
@@ -1,5 +1,5 @@
import { expect, type Page } from "@playwright/test";
import { deleteContentBlockChildAfterCanvasText } from "../flows/block-outline";
import { expect } from "@playwright/test";
import type { Instance, Prop } from "@webstudio-is/sdk";
import {
openProjectBuilder,
waitForCanvasFrame,
@@ -20,23 +20,20 @@ import {
replaceCanvasText,
replaceCanvasTextAndApplyInlineFormats,
} from "../flows/content-editing";
import {
fillSelectedStringProperty,
waitForSelectedStringPropertyValue,
} from "../flows/props-panel";
import { waitForSelectedStringPropertyValue } from "../flows/props-panel";
import {
expectContentModeTemplateActionsUnavailable,
openPagesPanel,
} from "../flows/pages-panel";
import { selectNavigatorItem } from "../flows/navigator";
import { waitForSyncStatus } from "../flows/sync-status";
import { waitForSyncComplete } from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test, withBrowserContext } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
import { loadDevBuild } from "../db";
import { loadDevBuild, updateBuild } from "../db";
const getElementTagWithTextCount = async ({
projectId,
@@ -141,45 +138,82 @@ const getElementHrefWithText = async ({
return href.value;
};
const undoShortcut = async ({ page }: { page: Page }) => {
await page.keyboard.press("ControlOrMeta+Z");
await waitForSyncStatus({ page, status: "idle" });
};
const redoShortcut = async ({ page }: { page: Page }) => {
await page.keyboard.press("ControlOrMeta+Shift+Z");
await waitForSyncStatus({ page, status: "idle" });
};
let fixture: SeededContentModeProject;
test.beforeAll(async ({ browser }) => {
test.describe.configure({ mode: "parallel" });
test.beforeEach(async ({ browser }) => {
fixture = await withBrowserContext(browser, (context) =>
createContentModeProject({ context, devPlan: e2ePaidPlanName })
);
});
test("Editor can delete direct children but not protected containers", async ({
test("Editor can paste, format and delete text while protected content remains", async ({
page,
}) => {
await measure(
"content mode open editor for direct child delete",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
const formattedText = "Rich editor formatted copy";
const editedHref = "/rich-text-editor-link";
const existingLinkText = "Preexisting inline link";
const build = await loadDevBuild({ projectId: fixture.projectId });
const instances: Instance[] = JSON.parse(build.instances);
const props: Prop[] = JSON.parse(build.props);
const contentBlock = instances.find(({ id }) => id === "content-block");
if (contentBlock === undefined) {
throw new Error("Expected the fixture Content Block");
}
// Keep a second link so adding and removing links can share one reload.
contentBlock.children.push({ type: "id", value: "existing-link-paragraph" });
instances.push(
{
type: "instance",
id: "existing-link-paragraph",
component: "ws:element",
tag: "p",
children: [{ type: "id", value: "existing-inline-link" }],
},
{
type: "instance",
id: "existing-inline-link",
component: "ws:element",
tag: "a",
children: [{ type: "id", value: "existing-inline-link-text" }],
},
{
type: "instance",
id: "existing-inline-link-text",
component: "ws:element",
tag: "b",
children: [{ type: "text", value: existingLinkText }],
}
);
await waitForCanvasText({ page, text: "Initial content" });
await waitForSyncStatus({ page, status: "idle" });
props.push({
id: "existing-inline-link-href",
instanceId: "existing-inline-link",
name: "href",
type: "string",
value: "/existing-inline-link",
});
await updateBuild(build.id, {
instances: JSON.stringify(instances),
props: JSON.stringify(props),
});
await measure("content mode open editor for text changes", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: fixture.shareLinkEditableText });
await waitForSyncComplete({ page });
await measure("content mode insert deletable template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.deletableTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
@@ -187,47 +221,190 @@ test("Editor can delete direct children but not protected containers", async ({
text: fixture.deletableTemplateText,
});
await measure("content mode delete direct child", async () => {
await deleteContentBlockChildAfterCanvasText({
const pastedContent = "Pasted editable content";
await measure("content mode native paste text", async () => {
await pasteCanvasText({
page,
text: fixture.deletableTemplateText,
currentText: fixture.deletableTemplateText,
text: pastedContent,
});
});
await measure("content mode delete direct child", async () => {
const canvas = await waitForCanvasFrame({ page });
await page.keyboard.down("Alt");
try {
await canvas.getByText(pastedContent, { exact: true }).hover();
await page.getByRole("button", { name: "Delete block" }).last().click();
} finally {
await page.keyboard.up("Alt");
}
});
await waitForCanvasTextHidden({
page,
text: fixture.deletableTemplateText,
text: pastedContent,
});
await measure(
"content mode reload editor for direct child delete",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await measure("content mode apply rich text formatting", async () => {
await replaceCanvasTextAndApplyInlineFormats({
page,
currentText: fixture.shareLinkEditableText,
text: formattedText,
formats: ["Bold", "Italic", "Inline link"],
});
});
await waitForCanvasText({ page, text: formattedText });
// The preceding deletion can finish while the formatting is being applied.
await waitForSyncComplete({ page });
const boldCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "b",
text: formattedText,
});
const italicCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "i",
text: formattedText,
});
const linkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (boldCount !== 1 || italicCount !== 1 || linkCount !== 1) {
throw new Error(
`Expected rich text editor to persist one bold, italic, and inline link subtree. bold=${boldCount}, italic=${italicCount}, link=${linkCount}`
);
}
await measure("content mode undo rich text formatting", async () => {
await page.keyboard.press("ControlOrMeta+Z");
await waitForCanvasTextHidden({ page, text: formattedText });
await waitForCanvasText({ page, text: fixture.shareLinkEditableText });
});
await measure("content mode redo rich text formatting", async () => {
await page.keyboard.press("ControlOrMeta+Shift+Z");
await waitForCanvasText({ page, text: formattedText });
});
await selectCanvasTextInstanceForProps({
page,
text: formattedText,
propertyLabel: "Href",
});
const urlInput = page.getByPlaceholder("https://www.url.com").first();
await urlInput.fill(editedHref);
await urlInput.blur();
const canvas = await waitForCanvasFrame({ page });
await expect(
canvas.getByRole("link", { name: existingLinkText })
).toBeVisible();
// Save both link edits before checking the stored build and reloading.
await removeCanvasInlineLink({ page, text: existingLinkText });
await waitForSyncComplete({ page });
const savedHref = await getElementHrefWithText({
projectId: fixture.projectId,
text: formattedText,
});
if (savedHref !== editedHref) {
throw new Error(
`Expected rich-text link href to be saved as "${editedHref}", received "${savedHref}"`
);
}
const removedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: existingLinkText,
});
expect(removedLinkCount).toBe(0);
await measure("content mode reload text changes", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: formattedText });
await waitForCanvasText({ page, text: "Initial content" });
await waitForCanvasTextHidden({
page,
text: pastedContent,
});
await waitForCanvasTextHidden({
page,
text: fixture.deletableTemplateText,
});
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const reloadedHref = await getElementHrefWithText({
projectId: fixture.projectId,
text: formattedText,
});
if (reloadedHref !== editedHref) {
throw new Error(
`Expected reloaded rich-text link href to be "${editedHref}", received "${reloadedHref}"`
);
}
const reloadedBoldCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "b",
text: formattedText,
});
const reloadedItalicCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "i",
text: formattedText,
});
const reloadedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (
reloadedBoldCount !== 1 ||
reloadedItalicCount !== 1 ||
reloadedLinkCount !== 1
) {
throw new Error(
`Expected reloaded rich text formatting to persist. bold=${reloadedBoldCount}, italic=${reloadedItalicCount}, link=${reloadedLinkCount}`
);
}
const reloadedCanvas = await waitForCanvasFrame({ page });
await expect(
reloadedCanvas.getByRole("link", { name: formattedText })
).toHaveAttribute("href", editedHref);
await expect(reloadedCanvas.getByText(existingLinkText)).toBeVisible();
await expect(
reloadedCanvas.getByRole("link", { name: existingLinkText })
).toHaveCount(0);
const reloadedRemovedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: existingLinkText,
});
expect(reloadedRemovedLinkCount).toBe(0);
await measure("content mode insert nested template", async () => {
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.nestedTemplateName,
waitForProjectSync: false,
});
});
await waitForCanvasText({
page,
text: fixture.nestedTemplateText,
});
await waitForSyncStatus({ page, status: "idle" });
await measure("content mode try nested delete", async () => {
const canvas = await waitForCanvasFrame({ page });
await page.keyboard.down("Alt");
@@ -244,7 +421,7 @@ test("Editor can delete direct children but not protected containers", async ({
page,
text: fixture.nestedTemplateText,
});
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await openPagesPanel({ page });
await expectContentModeTemplateActionsUnavailable({
@@ -255,7 +432,7 @@ test("Editor can delete direct children but not protected containers", async ({
await page.getByRole("tab", { name: "Navigator" }).click();
await expectTextHidden({ page, text: "Global Root" });
await expectTextHidden({ page, text: fixture.pageTemplateName });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
});
test("Editor can edit text and content props but not design props", async ({
@@ -277,13 +454,14 @@ test("Editor can edit text and content props but not design props", async ({
});
});
await waitForCanvasText({ page, text: "Initial link" });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const canvas = await waitForCanvasFrame({ page });
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.styledHeadingTemplateName,
waitForProjectSync: false,
});
const styledTemplateHeading = canvas
.locator("h2")
@@ -314,13 +492,13 @@ test("Editor can edit text and content props but not design props", async ({
});
await page.keyboard.press("Enter");
await expect(canvas.locator("[contenteditable]")).toHaveCount(0);
await waitForSyncStatus({ page, status: "idle" });
await expect(protectedImage).toBeVisible();
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.editableTextTemplateName,
waitForProjectSync: false,
});
await waitForCanvasText({
page,
@@ -331,6 +509,7 @@ test("Editor can edit text and content props but not design props", async ({
page,
anchorText: fixture.editableTextTemplateText,
templateName: fixture.contentPropsTemplateName,
waitForProjectSync: false,
});
await waitForCanvasText({
page,
@@ -353,6 +532,7 @@ test("Editor can edit text and content props but not design props", async ({
page,
currentText: fixture.editableTextTemplateText,
text: editedContent,
waitForProjectSync: false,
});
});
@@ -380,41 +560,33 @@ test("Editor can edit text and content props but not design props", async ({
text: fixture.contentPropsTemplateLinkText,
propertyLabel: "Href",
});
await fillSelectedStringProperty({
page,
label: "Href",
control: "url",
value: editedHref,
});
const urlInput = page.getByPlaceholder("https://www.url.com").first();
await urlInput.fill(editedHref);
await urlInput.blur();
await selectCanvasImage({
page,
alt: fixture.contentPropsTemplateImageAlt,
});
await fillSelectedStringProperty({
page,
label: "Source",
control: "url",
value: editedImageSrc,
});
await fillSelectedStringProperty({
page,
label: "Alt",
control: "text",
value: editedImageAlt,
});
await expect(page.getByText("Source", { exact: true }).first()).toBeVisible();
await urlInput.fill(editedImageSrc);
await urlInput.blur();
await expect(page.getByText("Alt", { exact: true }).first()).toBeVisible();
const altInput = page.locator("textarea").first();
await altInput.fill(editedImageAlt);
await altInput.blur();
await expectTextHidden({ page, text: "Width" });
await selectCanvasVideoSource({
page,
sourceName: fixture.contentPropsTemplateVideoName,
});
await fillSelectedStringProperty({
page,
label: "Source",
control: "url",
value: editedVideoSrc,
});
await expect(page.getByText("Source", { exact: true }).first()).toBeVisible();
await urlInput.fill(editedVideoSrc);
await urlInput.blur();
// Verify each edit after a single save barrier and reload.
await waitForSyncComplete({ page });
await measure("content mode reload editor for props", async () => {
await openProjectBuilder({
@@ -429,7 +601,7 @@ test("Editor can edit text and content props but not design props", async ({
text: fixture.contentPropsTemplateLinkText,
});
await waitForCanvasText({ page, text: editedContent });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const reloadedCanvas = await waitForCanvasFrame({ page });
const reloadedHeading = reloadedCanvas
.locator("h2")
@@ -498,194 +670,3 @@ test("Editor can edit text and content props but not design props", async ({
});
await waitForCanvasText({ page, text: editedContent });
});
test("Editor can paste text while editing canvas content", async ({ page }) => {
const pastedContent = "Pasted editable content";
await measure("content mode open editor for text paste", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: "Initial content" });
await waitForSyncStatus({ page, status: "idle" });
await insertTemplateAfterCanvasText({
page,
anchorText: "Initial content",
templateName: fixture.editableTextTemplateName,
});
await waitForCanvasText({
page,
text: fixture.editableTextTemplateText,
});
await measure("content mode native paste text", async () => {
await pasteCanvasText({
page,
currentText: fixture.editableTextTemplateText,
text: pastedContent,
});
});
await waitForCanvasText({ page, text: pastedContent });
});
test("Editor rich text formatting persists after reload", async ({ page }) => {
const formattedText = "Rich editor formatted copy";
const editedHref = "/rich-text-editor-link";
await measure(
"content mode open editor for rich text formatting",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasText({ page, text: fixture.shareLinkEditableText });
await waitForSyncStatus({ page, status: "idle" });
await measure("content mode apply rich text formatting", async () => {
await replaceCanvasTextAndApplyInlineFormats({
page,
currentText: fixture.shareLinkEditableText,
text: formattedText,
formats: ["Bold", "Italic", "Inline link"],
});
});
await waitForCanvasText({ page, text: formattedText });
const boldCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "b",
text: formattedText,
});
const italicCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "i",
text: formattedText,
});
const linkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (boldCount !== 1 || italicCount !== 1 || linkCount !== 1) {
throw new Error(
`Expected rich text editor to persist one bold, italic, and inline link subtree. bold=${boldCount}, italic=${italicCount}, link=${linkCount}`
);
}
await measure("content mode undo rich text formatting", async () => {
await undoShortcut({ page });
});
await waitForCanvasTextHidden({ page, text: formattedText });
await measure("content mode redo rich text formatting", async () => {
await redoShortcut({ page });
});
await waitForCanvasText({ page, text: formattedText });
await selectCanvasTextInstanceForProps({
page,
text: formattedText,
propertyLabel: "Href",
});
await fillSelectedStringProperty({
page,
label: "Href",
control: "url",
value: editedHref,
});
const savedHref = await getElementHrefWithText({
projectId: fixture.projectId,
text: formattedText,
});
if (savedHref !== editedHref) {
throw new Error(
`Expected rich-text link href to be saved as "${editedHref}", received "${savedHref}"`
);
}
await measure("content mode reload rich text formatting", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: formattedText });
const reloadedHref = await getElementHrefWithText({
projectId: fixture.projectId,
text: formattedText,
});
if (reloadedHref !== editedHref) {
throw new Error(
`Expected reloaded rich-text link href to be "${editedHref}", received "${reloadedHref}"`
);
}
const reloadedBoldCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "b",
text: formattedText,
});
const reloadedItalicCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "i",
text: formattedText,
});
const reloadedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (
reloadedBoldCount !== 1 ||
reloadedItalicCount !== 1 ||
reloadedLinkCount !== 1
) {
throw new Error(
`Expected reloaded rich text formatting to persist. bold=${reloadedBoldCount}, italic=${reloadedItalicCount}, link=${reloadedLinkCount}`
);
}
await removeCanvasInlineLink({ page, text: formattedText });
const removedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (removedLinkCount !== 0) {
throw new Error(
`Expected rich-text link removal to delete the inline link subtree, received ${removedLinkCount} link instances`
);
}
await measure("content mode reload rich text link removal", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: formattedText });
const reloadedRemovedLinkCount = await getElementTagWithTextCount({
projectId: fixture.projectId,
tag: "a",
text: formattedText,
});
if (reloadedRemovedLinkCount !== 0) {
throw new Error(
`Expected rich-text link removal to persist after reload, received ${reloadedRemovedLinkCount} link instances`
);
}
});
@@ -1,3 +1,4 @@
import { createReadStream } from "node:fs";
import { expect } from "@playwright/test";
import {
blockBodyComponent,
@@ -11,29 +12,27 @@ import type {
StyleSource,
StyleSourceSelection,
} from "@webstudio-is/sdk";
import { loadDevBuild, updateBuild } from "../db";
import { createAssetClient } from "../../app/shared/asset-client";
import { insertAsset, insertFile, loadDevBuild, updateBuild } from "../db";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
openProjectBuilder,
waitForCanvasFrame,
waitForCanvasText,
} from "../flows/builder";
import {
getAssetIdByFilename,
openAssetsPanel,
uploadAsset,
} from "../flows/assets-panel";
import { selectCanvasImage } from "../flows/canvas-media";
import { replaceCanvasText } from "../flows/content-editing";
import { fillSelectedStringProperty } from "../flows/props-panel";
import { selectNavigatorItem } from "../flows/navigator";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
waitForSyncComplete,
} from "../flows/sync-status";
import { e2ePaidPlanName } from "../plans";
import { test, withBrowserContext } from "../test";
test.describe.configure({ mode: "parallel" });
test("Editor can open and save legacy content before a Builder migrates the project", async ({
page,
browser,
@@ -139,33 +138,21 @@ test("Editor can open and save legacy content before a Builder migrates the proj
mode: "content",
});
await waitForCanvasText({ page, text: fixture.shareLinkEditableText });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
await waitForCanvasText({ page, text: code });
expect((await loadDevBuild({ projectId: fixture.projectId })).version).toBe(
0
);
const editedText = "Saved legacy Editor content";
const textSave = waitForChangeToBeSaved({ page });
textSave.catch(() => undefined);
await replaceCanvasText({
page,
currentText: fixture.shareLinkEditableText,
text: editedText,
waitForProjectSync: false,
});
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForCanvasText({ page, text: editedText });
await waitForCanvasText({ page, text: code });
await waitForSyncStatus({ page, status: "idle" });
const editedBuild = await loadDevBuild({ projectId: fixture.projectId });
expect(JSON.parse(editedBuild.styles)).toEqual(styles);
expect(JSON.parse(editedBuild.styleSources)).toEqual(styleSources);
expect(JSON.parse(editedBuild.styleSourceSelections)).toEqual(selections);
expect(JSON.parse(editedBuild.props)).toEqual(props);
expect(unexpectedDialogs).toEqual([]);
const canvas = await waitForCanvasFrame({ page });
await canvas.getByText(readOnlyCode, { exact: true }).click();
@@ -175,6 +162,15 @@ test("Editor can open and save legacy content before a Builder migrates the proj
await selectNavigatorItem({ page, name: "Legacy literal code" });
await expect(textContent).toHaveText(code);
await expect(textContent).toHaveAttribute("contenteditable", "true");
await textSave;
const editedBuild = await loadDevBuild({ projectId: fixture.projectId });
expect(JSON.parse(editedBuild.styles)).toEqual(styles);
expect(JSON.parse(editedBuild.styleSources)).toEqual(styleSources);
expect(JSON.parse(editedBuild.styleSourceSelections)).toEqual(selections);
expect(JSON.parse(editedBuild.props)).toEqual(props);
expect(unexpectedDialogs).toEqual([]);
const editedCode = "const savedAnswer = 43;";
const codeSave = waitForChangeToBeSaved({ page });
codeSave.catch(() => undefined);
@@ -187,22 +183,22 @@ test("Editor can open and save legacy content before a Builder migrates the proj
authToken: fixture.editorToken,
mode: "content",
});
await waitForCanvasText({ page, text: editedText });
await waitForCanvasText({ page, text: editedCode });
await waitForCanvasText({ page, text: readOnlyCode });
await waitForSyncComplete({ page });
expect(unexpectedDialogs).toEqual([]);
// Actual build permission still permits migration while using Content mode.
await withBrowserContext(browser, async (context) => {
const builderPage = await context.newPage();
await openProjectBuilder({
page: builderPage,
projectId: fixture.projectId,
authToken: fixture.builderToken,
mode: "content",
});
await waitForCanvasText({ page: builderPage, text: editedText });
await waitForCanvasText({ page: builderPage, text: editedCode });
await waitForSyncStatus({ page: builderPage, status: "idle" });
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
mode: "content",
});
await waitForCanvasText({ page, text: editedText });
await waitForCanvasText({ page, text: editedCode });
await waitForSyncComplete({ page });
const migratedBuild = await loadDevBuild({ projectId: fixture.projectId });
expect(
JSON.parse(migratedBuild.styleSources) as StyleSource[]
@@ -226,7 +222,7 @@ test("Editor can open and save legacy content before a Builder migrates the proj
await waitForCanvasText({ page, text: editedText });
await waitForCanvasText({ page, text: editedCode });
await waitForCanvasText({ page, text: readOnlyCode });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
expect(unexpectedDialogs).toEqual([]);
});
@@ -235,31 +231,40 @@ test("Editor can edit legacy document bindings before a Builder visits", async (
browser,
}) => {
const filename = "content-source.mdx";
const { fixture, assetId } = await withBrowserContext(
browser,
async (context) => {
const fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: "legacy-bindings@webstudio.test",
title: "Legacy document bindings",
});
const setupPage = await context.newPage();
await openProjectBuilder({
page: setupPage,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await openAssetsPanel({ page: setupPage });
await uploadAsset({ page: setupPage, filename });
return {
fixture,
assetId: await getAssetIdByFilename({ page: setupPage, filename }),
};
}
const fixture = await withBrowserContext(browser, (context) =>
createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: "legacy-bindings@webstudio.test",
title: "Legacy document bindings",
})
);
// Seed the old representation only after the setup browser has closed.
const build = await loadDevBuild({ projectId: fixture.projectId });
// Seed the document before opening Builder so the Editor is its first reader.
const name = `${fixture.projectId}-${filename}`;
const [assetData, build] = await Promise.all([
createAssetClient().uploadFile(
name,
"file",
createReadStream(
new URL(`../fixtures/assets/${filename}`, import.meta.url)
),
undefined
),
loadDevBuild({ projectId: fixture.projectId }),
]);
await insertFile({
name,
...assetData,
meta: JSON.stringify(assetData.meta),
status: "UPLOADED",
uploaderProjectId: fixture.projectId,
});
const { id: assetId } = await insertAsset({
id: `${fixture.projectId}-legacy-document`,
projectId: fixture.projectId,
name,
filename,
});
const instances: Instance[] = JSON.parse(build.instances);
const props: Prop[] = JSON.parse(build.props);
const dataSources: DataSource[] = JSON.parse(build.dataSources);
@@ -356,7 +361,7 @@ test("Editor can edit legacy document bindings before a Builder visits", async (
mode: "content",
});
await waitForCanvasText({ page, text: "Content source fixture" });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const editedTitle = "Edited legacy document title";
const titleWrite = page.waitForResponse(
(response) =>
@@ -398,7 +403,7 @@ test("Editor can edit legacy document bindings before a Builder visits", async (
});
await waitForCanvasText({ page, text: editedAlt });
await waitForCanvasText({ page, text: "MDX source heading" });
await waitForSyncStatus({ page, status: "idle" });
await waitForSyncComplete({ page });
const savedBuild = await loadDevBuild({ projectId: fixture.projectId });
expect(JSON.parse(savedBuild.instances)).toEqual(instances);
expect(JSON.parse(savedBuild.props)).toEqual(props);
@@ -0,0 +1,183 @@
import { randomUUID } from "node:crypto";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { waitForCanvasTextStyle } from "../flows/canvas-style";
import {
choosePageSettingsSocialImageAsset,
createPageFromTemplate,
expectContentModePagePathError,
expectContentModePageSettingsRestrictions,
expectCustomMetadataValue,
fillAllowedPageSettings,
fillCustomMetadata,
getPageSettingsPathInput,
openPage,
openPageSettings,
} from "../flows/pages-panel";
import { waitForSyncComplete } from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { test } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
let fixture: SeededContentModeProject;
test.beforeEach(async ({ context, page }) => {
fixture = await createContentModeProject({
context,
page,
devPlan: e2ePaidPlanName,
email: `content-mode-pages-${randomUUID()}@webstudio.test`,
});
});
test("Editor can create a styled page, edit allowed settings, and reload it in content mode", async ({
page,
}) => {
const pageName = "Created content page";
const invalidPaths = ["/posts/:slug", "/docs/*", "https://x.com"];
const editedName = "Edited settings content page";
const editedPath = "/edited-settings-content-page";
const editedTitle = "Edited settings title";
const editedDescription = "Edited settings description";
const editedLanguage = "en-US";
const editedSocialImage = "https://example.com/content-mode-social.png";
const metadata = {
property: "content-mode",
content: "edited metadata",
};
const expectTemplatedCanvas = async () => {
await waitForCanvasTextStyle({
page,
text: fixture.pageTemplateText,
property: "font-size",
value: fixture.pageTemplateFontSize,
});
await waitForCanvasText({
page,
text: fixture.dataResourceStaticVariableVisibleValue,
});
await waitForCanvasText({
page,
text: "HTTP resource variable configured",
});
await waitForCanvasText({
page,
text: "GraphQL resource variable configured",
});
await waitForCanvasText({
page,
text: "2026",
});
};
await measure(
"content mode open editor for page template creation",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasText({ page, text: "Initial link" });
await waitForSyncComplete({ page });
await measure("content mode create page from template", async () => {
await createPageFromTemplate({
page,
templateName: fixture.pageTemplateName,
pageName,
canvasText: fixture.pageTemplateText,
});
});
await expectTemplatedCanvas();
await openPageSettings({ page, pageName });
await test.step("Invalid paths and restricted settings are blocked", async () => {
for (const path of invalidPaths) {
const pathInput = getPageSettingsPathInput({ page });
await pathInput.fill(path);
await pathInput.blur();
await expectContentModePagePathError({ page });
await waitForSyncComplete({ page });
}
await expectContentModePageSettingsRestrictions({ page });
await waitForSyncComplete({ page });
});
await test.step("Allowed settings can be saved", async () => {
await fillAllowedPageSettings({
page,
name: editedName,
path: editedPath,
title: editedTitle,
description: editedDescription,
language: editedLanguage,
socialImage: editedSocialImage,
metadata,
});
await choosePageSettingsSocialImageAsset({
page,
filename: fixture.assetTemplateImageName,
label: fixture.assetTemplateImageAlt,
});
await fillCustomMetadata({ page, ...metadata });
});
await measure("content mode reload created page and settings", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openPage({
page,
pageName: editedName,
canvasText: fixture.pageTemplateText,
});
});
await expectTemplatedCanvas();
await openPageSettings({ page, pageName: editedName });
await page.getByLabel("Page name").waitFor();
if ((await page.getByLabel("Page name").inputValue()) !== editedName) {
throw new Error("Expected edited page name to persist");
}
if ((await getPageSettingsPathInput({ page }).inputValue()) !== editedPath) {
throw new Error("Expected edited page path to persist");
}
if ((await page.getByLabel("Title").inputValue()) !== editedTitle) {
throw new Error("Expected edited page title to persist");
}
if (
(await page.getByLabel("Description").inputValue()) !== editedDescription
) {
throw new Error("Expected edited page description to persist");
}
if (
(await page
.getByLabel("Exclude this page from search results")
.isChecked()) === false
) {
throw new Error("Expected edited search visibility to persist");
}
if ((await page.getByLabel("Language").inputValue()) !== editedLanguage) {
throw new Error("Expected edited page language to persist");
}
const socialPreviewImage = page.getByRole("img", {
name: "Social sharing preview image",
});
await socialPreviewImage.waitFor();
const socialPreviewImageSrc = await socialPreviewImage.getAttribute("src");
if (
socialPreviewImageSrc?.includes(fixture.assetTemplateImageName) !== true
) {
throw new Error(
`Expected social image preview to render ${fixture.assetTemplateImageName}, received ${socialPreviewImageSrc}`
);
}
await expectCustomMetadataValue({ page, ...metadata });
await waitForSyncComplete({ page });
});
@@ -1,358 +0,0 @@
import { randomUUID } from "node:crypto";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import { selectCanvasTextInstance } from "../flows/canvas-selection";
import { expectLocatorHidden } from "../flows/assertions";
import { waitForCanvasTextStyle } from "../flows/canvas-style";
import { replaceCanvasText } from "../flows/content-editing";
import {
choosePageSettingsSocialImageAsset,
createPageFromTemplate,
expectContentModePagePathError,
expectContentModePageSettingsRestrictions,
expectCustomMetadataValue,
fillAllowedPageSettings,
fillCustomMetadata,
getPageSettingsPathInput,
openPage,
openPageSettings,
} from "../flows/pages-panel";
import { waitForSyncStatus } from "../flows/sync-status";
import { insertTemplateAfterCanvasText } from "../flows/template-insertion";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import type { SeededContentModeProject } from "../fixtures/content-mode-project";
import { newIsolatedPage, test } from "../test";
import { measure } from "../perf";
import { e2ePaidPlanName } from "../plans";
let fixture: SeededContentModeProject;
test.describe.configure({ mode: "parallel" });
test.beforeEach(async ({ context }) => {
fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: `content-mode-pages-${randomUUID()}@webstudio.test`,
});
});
test("Editor can create styled page from template in content mode", async ({
page,
}) => {
const pageName = "Created content page";
await measure(
"content mode open editor for page template creation",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasText({ page, text: "Initial link" });
await waitForSyncStatus({ page, status: "idle" });
await measure("content mode create page from template", async () => {
await createPageFromTemplate({
page,
templateName: fixture.pageTemplateName,
pageName,
canvasText: fixture.pageTemplateText,
});
});
await waitForCanvasTextStyle({
page,
text: fixture.pageTemplateText,
property: "font-size",
value: fixture.pageTemplateFontSize,
});
await waitForCanvasText({
page,
text: fixture.dataResourceStaticVariableVisibleValue,
});
await waitForCanvasText({
page,
text: "HTTP resource variable configured",
});
await waitForCanvasText({
page,
text: "GraphQL resource variable configured",
});
await waitForCanvasText({
page,
text: "2026",
});
await measure("content mode reload created page from template", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openPage({
page,
pageName,
canvasText: fixture.pageTemplateText,
});
});
await waitForCanvasText({
page,
text: fixture.dataResourceStaticVariableVisibleValue,
});
await waitForCanvasText({
page,
text: "HTTP resource variable configured",
});
await waitForCanvasText({
page,
text: "GraphQL resource variable configured",
});
await waitForCanvasText({
page,
text: "2026",
});
await waitForSyncStatus({ page, status: "idle" });
});
test("Editor can edit allowed page settings", async ({ page }) => {
const pageName = "Settings content page";
const editedName = "Edited settings content page";
const editedPath = "/edited-settings-content-page";
const editedTitle = "Edited settings title";
const editedDescription = "Edited settings description";
const editedLanguage = "en-US";
const editedSocialImage = "https://example.com/content-mode-social.png";
await measure(
"content mode open editor for allowed page settings",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await waitForCanvasText({ page, text: "Initial link" });
await waitForSyncStatus({ page, status: "idle" });
await createPageFromTemplate({
page,
templateName: fixture.pageTemplateName,
pageName,
canvasText: fixture.pageTemplateText,
});
await openPageSettings({ page, pageName });
await fillAllowedPageSettings({
page,
name: editedName,
path: editedPath,
title: editedTitle,
description: editedDescription,
language: editedLanguage,
socialImage: editedSocialImage,
metadata: {
property: "content-mode",
content: "edited metadata",
},
});
await choosePageSettingsSocialImageAsset({
page,
filename: fixture.assetTemplateImageName,
label: fixture.assetTemplateImageAlt,
});
await fillCustomMetadata({
page,
metadata: {
property: "content-mode",
content: "edited metadata",
},
});
await measure(
"content mode reload editor for allowed page settings",
async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
}
);
await openPageSettings({ page, pageName: editedName });
await page.getByLabel("Page name").waitFor();
if ((await page.getByLabel("Page name").inputValue()) !== editedName) {
throw new Error("Expected edited page name to persist");
}
if ((await getPageSettingsPathInput({ page }).inputValue()) !== editedPath) {
throw new Error("Expected edited page path to persist");
}
if ((await page.getByLabel("Title").inputValue()) !== editedTitle) {
throw new Error("Expected edited page title to persist");
}
if (
(await page.getByLabel("Description").inputValue()) !== editedDescription
) {
throw new Error("Expected edited page description to persist");
}
if (
(await page
.getByLabel("Exclude this page from search results")
.isChecked()) === false
) {
throw new Error("Expected edited search visibility to persist");
}
if ((await page.getByLabel("Language").inputValue()) !== editedLanguage) {
throw new Error("Expected edited page language to persist");
}
const socialPreviewImage = page.getByRole("img", {
name: "Social sharing preview image",
});
await socialPreviewImage.waitFor();
const socialPreviewImageSrc = await socialPreviewImage.getAttribute("src");
if (
socialPreviewImageSrc?.includes(fixture.assetTemplateImageName) !== true
) {
throw new Error(
`Expected social image preview to render ${fixture.assetTemplateImageName}, received ${socialPreviewImageSrc}`
);
}
await expectCustomMetadataValue({
page,
property: "content-mode",
content: "edited metadata",
});
await waitForSyncStatus({ page, status: "idle" });
});
test("Editor is blocked from invalid paths and restricted page settings", async ({
page,
}) => {
const pageName = "Blocked settings content page";
const invalidPaths = ["/posts/:slug", "/docs/*", "https://x.com"];
await measure("content mode open editor for blocked page paths", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
});
await waitForCanvasText({ page, text: "Initial link" });
await waitForSyncStatus({ page, status: "idle" });
await createPageFromTemplate({
page,
templateName: fixture.pageTemplateName,
pageName,
canvasText: fixture.pageTemplateText,
});
await openPageSettings({ page, pageName });
for (const path of invalidPaths) {
const pathInput = getPageSettingsPathInput({ page });
await pathInput.fill(path);
await pathInput.blur();
await expectContentModePagePathError({ page });
await waitForSyncStatus({ page, status: "idle" });
}
await expectContentModePageSettingsRestrictions({ page });
await waitForSyncStatus({ page, status: "idle" });
});
test("Edit-only and build-capable users can collaborate in content mode", async ({
browser,
}) => {
const editor = await newIsolatedPage(browser);
const builder = await newIsolatedPage(browser);
try {
await measure("open editor and builder sessions", async () => {
await Promise.all([
openProjectBuilder({
page: editor.page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
}),
openProjectBuilder({
page: builder.page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
}),
]);
});
await waitForCanvasText({ page: editor.page, text: "Initial content" });
await waitForCanvasText({ page: builder.page, text: "Initial content" });
await waitForSyncStatus({ page: editor.page, status: "idle" });
await waitForSyncStatus({ page: builder.page, status: "idle" });
await insertTemplateAfterCanvasText({
page: editor.page,
anchorText: "Initial content",
templateName: fixture.collaborationTemplateName,
});
await waitForCanvasText({
page: editor.page,
text: fixture.collaborationTemplateText,
});
await waitForSyncStatus({ page: editor.page, status: "idle" });
await openProjectBuilder({
page: builder.page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({
page: builder.page,
text: fixture.collaborationTemplateText,
});
await replaceCanvasText({
page: editor.page,
currentText: fixture.collaborationTemplateText,
text: "Collaborative editor text",
});
await waitForSyncStatus({ page: editor.page, status: "idle" });
await selectCanvasTextInstance({
page: editor.page,
text: "Collaborative editor text",
});
await expectLocatorHidden({
locator: editor.page.getByRole("tab", { name: "Style" }),
message:
"Expected edit-only collaborator to be blocked from design controls",
});
await openProjectBuilder({
page: builder.page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({
page: builder.page,
text: "Collaborative editor text",
});
await selectCanvasTextInstance({
page: builder.page,
text: "Collaborative editor text",
});
await builder.page
.getByRole("tab", { name: "Style" })
.waitFor({ state: "visible" });
await waitForSyncStatus({ page: editor.page, status: "idle" });
await waitForSyncStatus({ page: builder.page, status: "idle" });
} finally {
await editor.close();
await builder.close();
}
});
@@ -1,107 +0,0 @@
import { expect } from "@playwright/test";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import {
bindSelectedTextContentToExpression,
createGraphqlResourceVariable,
createHttpResourceVariable,
createSystemResourceVariable,
selectContentInstance,
startGraphqlResourceServer,
startJsonResourceServer,
} from "../flows/data-variables";
import { loginWithSecret } from "../flows/dashboard";
import { withGeneratedPreview } from "../flows/generated-app";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { test } from "../test";
import { measure } from "../perf";
test("Generated app renders Builder-created HTTP, GraphQL, and system resources", async ({
page,
context,
}) => {
const http = await startJsonResourceServer({
title: "Rendered from local HTTP resource",
});
const graphql = await startGraphqlResourceServer({
title: "Rendered from local GraphQL resource",
});
try {
const fixture = await createContentModeProject({
context,
email: "generated-resources@webstudio.test",
title: "Generated resources",
assetNamePrefix: "generated-resources-",
editorToken: "generated-resources-editor-token",
builderToken: "generated-resources-builder-token",
});
await loginWithSecret({
page,
email: "generated-resources@webstudio.test",
});
await measure("generated resources open Builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
});
await selectContentInstance({ page });
await test.step("create HTTP resource through Builder", async () => {
await createHttpResourceVariable({
page,
name: "e2eGeneratedPosts",
url: http.url,
});
});
await test.step("create GraphQL resource through Builder", async () => {
await createGraphqlResourceVariable({
page,
name: "e2eGeneratedPost",
url: graphql.url,
query: "query Post { post { title } }",
});
});
await test.step("create system resource through Builder", async () => {
await createSystemResourceVariable({
page,
name: "e2eGeneratedCurrentDate",
resource: "Current date resource",
});
});
await measure("generated resources reload Builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
await selectContentInstance({ page });
});
const expectedYear = String(new Date().getUTCFullYear());
const expectedText = `Rendered from local HTTP resource | Rendered from local GraphQL resource | ${expectedYear}`;
await bindSelectedTextContentToExpression({
page,
expression:
'e2eGeneratedPosts.data.title + " | " + e2eGeneratedPost.data.data.post.title + " | " + e2eGeneratedCurrentDate.data.year',
});
await waitForCanvasText({
page,
text: expectedText,
});
await test.step("render all three resources in one generated Preview", async () => {
await withGeneratedPreview({
projectId: fixture.projectId,
callback: async ({ html }) => {
expect(html).toContain(expectedText);
},
});
});
} finally {
await Promise.all([http.close(), graphql.close()]);
}
});
@@ -0,0 +1,619 @@
import { expect, type Page } from "@playwright/test";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import {
bindSelectedTextContentToExpression,
createGraphqlResourceVariable,
createHttpResourceVariable,
createStringVariable,
createSystemResourceVariable,
selectContentInstance,
startGraphqlResourceServer,
startJsonResourceServer,
} from "../flows/data-variables";
import { withGeneratedPreview } from "../flows/generated-app";
import {
waitForChangeToBeSaved,
waitForSyncComplete,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
preparePreviewLinksProject,
previewLinkText,
} from "../fixtures/preview-links-project";
import { test } from "../test";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
type DataSourceRecord =
| {
id: string;
type: "variable";
name: string;
value: { type: string; value: unknown };
}
| {
id: string;
type: "resource";
name: string;
resourceId: string;
};
type ResourceRecord = {
id: string;
name: string;
url: string;
method: string;
control?: "graphql" | "system";
body?: string;
searchParams?: Array<{ name: string; value: string }>;
headers?: Array<{ name: string; value: string }>;
};
const getDataVariableRuntimeState = async (fixture: { projectId: string }) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
return {
dataSources: JSON.parse(build.dataSources) as DataSourceRecord[],
resources: JSON.parse(build.resources) as ResourceRecord[],
};
};
const getVariableForm = (page: Page) =>
page
.locator("form")
.filter({ has: page.locator('input[name="name"]') })
.last();
const getVariableIdByName = async ({
fixture,
name,
}: {
fixture: { projectId: string };
name: string;
}) => {
const { dataSources } = await getDataVariableRuntimeState(fixture);
const dataSource = dataSources.find((dataSource) => dataSource.name === name);
if (dataSource === undefined) {
throw new Error(`Expected data variable "${name}" to exist.`);
}
return dataSource.id;
};
const closeVariablePanelAndWaitForSave = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page });
await page.getByRole("button", { name: "Close" }).last().click();
await save;
await page
.getByText("New variable", { exact: true })
.waitFor({ state: "hidden" });
};
const editStringVariable = async ({
page,
fixture,
name,
value,
}: {
page: Page;
fixture: { projectId: string };
name: string;
value: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
await page.locator(`button[data-id="${id}"]`).click();
await getVariableForm(page).locator('input[name="name"]').waitFor();
await page.getByLabel("Value").last().fill(value);
await closeVariablePanelAndWaitForSave({ page });
};
const deleteVariable = async ({
page,
fixture,
name,
}: {
page: Page;
fixture: { projectId: string };
name: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
const row = page.locator(`button[data-id="${id}"]`).locator("xpath=..");
await row.hover();
await row.getByRole("button", { name: "Open variable menu" }).click();
await page.getByRole("menuitem", { name: /^Delete/ }).click();
const save = waitForChangeToBeSaved({ page });
await page
.getByRole("dialog", { name: "Delete confirmation" })
.getByRole("button", { name: "Delete" })
.click();
await save;
};
const editHttpResourceVariableWithCurl = async ({
page,
fixture,
name,
curl,
}: {
page: Page;
fixture: { projectId: string };
name: string;
curl: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
await page.locator(`button[data-id="${id}"]`).click();
await getVariableForm(page).locator('input[name="name"]').waitFor();
await page.getByRole("textbox", { name: "URL" }).fill(curl);
await closeVariablePanelAndWaitForSave({ page });
};
const expectVariableListItem = async ({
page,
name,
badge,
}: {
page: Page;
name: string;
badge: "Static variable" | "Dynamic variable";
}) => {
const itemButton = page
.getByText(name, { exact: true })
.locator("xpath=ancestor::button[@data-id][1]");
await itemButton.waitFor({ state: "visible" });
await itemButton
.locator("xpath=parent::*")
.getByLabel(badge)
.waitFor({ state: "attached" });
};
const expectPersistedDataVariables = async ({
fixture,
staticName,
staticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
currentDateName,
deletedName,
}: {
fixture: { projectId: string };
staticName: string;
staticValue: string;
httpName: string;
httpUrl: string;
httpCurlUrl?: string;
httpSearchParamName?: string;
httpSearchParamValue?: string;
httpHeaderName?: string;
httpHeaderValue?: string;
httpBodyValue?: string;
graphqlName: string;
graphqlUrl: string;
graphqlQuery: string;
systemName: string;
currentDateName: string;
deletedName?: string;
}) => {
const { dataSources, resources } = await getDataVariableRuntimeState(fixture);
const staticVariable = dataSources.find(
(dataSource) => dataSource.name === staticName
);
if (
staticVariable?.type !== "variable" ||
staticVariable.value.type !== "string" ||
staticVariable.value.value !== staticValue
) {
throw new Error(
`Expected static variable "${staticName}" to persist with string value. Received: ${JSON.stringify(staticVariable)}. All data sources: ${JSON.stringify(dataSources)}`
);
}
const httpVariable = dataSources.find(
(dataSource) => dataSource.name === httpName
);
const httpResource = resources.find(
(resource) =>
httpVariable?.type === "resource" &&
resource.id === httpVariable.resourceId
);
if (
httpVariable?.type !== "resource" ||
httpResource === undefined ||
httpResource?.control !== undefined ||
httpResource.url !== JSON.stringify(httpCurlUrl ?? httpUrl) ||
httpResource.method !== (httpCurlUrl === undefined ? "get" : "post")
) {
throw new Error(`Expected HTTP resource variable "${httpName}".`);
}
if (
httpSearchParamName !== undefined &&
httpResource.searchParams?.some(
(searchParam) =>
searchParam.name === httpSearchParamName &&
searchParam.value === JSON.stringify(httpSearchParamValue)
) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist search param "${httpSearchParamName}". Received: ${JSON.stringify(httpResource)}`
);
}
if (
httpHeaderName !== undefined &&
httpResource.headers?.some(
(header) =>
header.name === httpHeaderName &&
header.value === JSON.stringify(httpHeaderValue)
) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist header "${httpHeaderName}". Received: ${JSON.stringify(httpResource)}`
);
}
if (
httpBodyValue !== undefined &&
httpResource.body?.includes(httpBodyValue) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist body value "${httpBodyValue}". Received: ${JSON.stringify(httpResource)}`
);
}
if (deletedName !== graphqlName) {
const graphqlVariable = dataSources.find(
(dataSource) => dataSource.name === graphqlName
);
const graphqlResource = resources.find(
(resource) =>
graphqlVariable?.type === "resource" &&
resource.id === graphqlVariable.resourceId
);
if (
graphqlVariable?.type !== "resource" ||
graphqlResource?.control !== "graphql" ||
graphqlResource.url !== JSON.stringify(graphqlUrl) ||
graphqlResource.method !== "post" ||
graphqlResource.body?.includes(graphqlQuery) !== true
) {
throw new Error(`Expected GraphQL resource variable "${graphqlName}".`);
}
}
const systemVariable = dataSources.find(
(dataSource) => dataSource.name === systemName
);
const systemResource = resources.find(
(resource) =>
systemVariable?.type === "resource" &&
resource.id === systemVariable.resourceId
);
if (
systemVariable?.type !== "resource" ||
systemResource?.control !== "system" ||
systemResource.method !== "get"
) {
throw new Error(`Expected system resource variable "${systemName}".`);
}
const currentDateVariable = dataSources.find(
(dataSource) => dataSource.name === currentDateName
);
const currentDateResource = resources.find(
(resource) =>
currentDateVariable?.type === "resource" &&
resource.id === currentDateVariable.resourceId
);
if (
currentDateVariable?.type !== "resource" ||
currentDateResource?.control !== "system" ||
currentDateResource.method !== "get"
) {
throw new Error(`Expected system resource variable "${currentDateName}".`);
}
if (
deletedName !== undefined &&
dataSources.some((dataSource) => dataSource.name === deletedName)
) {
throw new Error(`Expected deleted variable "${deletedName}" to be absent.`);
}
};
test("Builder variables render in generated Preview and persist after reload", async ({
page,
context,
}) => {
const http = await startJsonResourceServer({
title: "Rendered from local HTTP resource",
});
const graphql = await startGraphqlResourceServer({
title: "Rendered from local GraphQL resource",
});
try {
const email = "data-variables-runtime@webstudio.test";
const fixture = await createContentModeProject({
context: context,
email,
title: "Data Variables Runtime",
assetNamePrefix: "data-variables-runtime-",
editorToken: "data-variables-runtime-editor-token",
builderToken: "data-variables-runtime-builder-token",
});
const staticName = "e2eStaticLabel";
const staticValue = "Rendered from local static variable";
const editedStaticValue = "Edited from Builder UI";
const httpName = "e2ePosts";
const httpUrl = http.url;
const httpCurlUrl = new URL("/api/posts", http.url).href;
const httpSearchParamName = "status";
const httpSearchParamValue = "published";
const httpHeaderName = "X-Test";
const httpHeaderValue = "resource-panel";
const httpBodyValue = "featured";
const graphqlName = "e2eGraphqlPosts";
const graphqlUrl = graphql.url;
const graphqlQuery = "query Post { post { title } }";
const systemName = "e2eSitemap";
const currentDateName = "e2eCurrentDate";
const expectedYear = String(new Date().getUTCFullYear());
const expectedText = `${staticValue} | Rendered from local HTTP resource | Rendered from local GraphQL resource | ${expectedYear}`;
await preparePreviewLinksProject(fixture.projectId);
await measure("data variables runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
});
await selectContentInstance({ page });
await measure(
"data variables runtime create variables through UI",
async () => {
await createStringVariable({
page,
name: staticName,
value: staticValue,
});
await createHttpResourceVariable({
page,
name: httpName,
url: httpUrl,
});
await createGraphqlResourceVariable({
page,
name: graphqlName,
url: graphqlUrl,
query: graphqlQuery,
});
await createSystemResourceVariable({ page, name: systemName });
await createSystemResourceVariable({
page,
name: currentDateName,
resource: "Current date resource",
});
await waitForSyncComplete({ page });
}
);
await test.step("Bind Text Content to all rendered variable types", async () => {
await bindSelectedTextContentToExpression({
page,
expression:
'e2eStaticLabel + " | " + e2ePosts.data.title + " | " + e2eGraphqlPosts.data.data.post.title + " | " + e2eCurrentDate.data.year',
});
await waitForCanvasText({ page, text: expectedText });
await waitForSyncComplete({ page });
});
// Preview uses the saved project before the Builder edits below.
const previewBuild = await loadDevBuild({ projectId: fixture.projectId });
const verifyPreview = () =>
test.step("Generated Preview renders variables and navigates linked routes", async () => {
await withGeneratedPreview({
build: previewBuild,
callback: async ({ url, html }) => {
expect(html).toContain(expectedText);
const target = new URL("/my-page", url).href;
const response = await fetch(target, { redirect: "manual" });
expect(response.ok).toBe(true);
expect(await response.text()).toContain(previewLinkText.pageLink);
const previewPage = await context.newPage();
try {
await previewPage.goto(url);
const link = previewPage.getByRole("link", {
name: previewLinkText.pageLink,
exact: true,
});
await link.click();
await expect(previewPage).toHaveURL(target);
await expect(link).toBeVisible();
await expect(link).toHaveAttribute("aria-current", "page");
} finally {
await previewPage.close();
}
},
});
});
const verifyPersistence = () =>
test.step("Builder edits persist after reload", async () => {
await measure(
"data variables runtime edit resources and variables",
async () => {
await editStringVariable({
page,
fixture,
name: staticName,
value: editedStaticValue,
});
await editHttpResourceVariableWithCurl({
page,
fixture,
name: httpName,
curl: `curl '${httpCurlUrl}?${httpSearchParamName}=${httpSearchParamValue}' --request POST --header '${httpHeaderName}: ${httpHeaderValue}' --header 'Content-Type: application/json' --data '{"${httpBodyValue}":true}'`,
});
}
);
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
currentDateName,
deletedName: undefined,
});
await expectVariableListItem({
page,
name: staticName,
badge: "Static variable",
});
await expectVariableListItem({
page,
name: httpName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: graphqlName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: systemName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: currentDateName,
badge: "Dynamic variable",
});
await measure("data variables runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
const editedText = expectedText.replace(staticValue, editedStaticValue);
await waitForCanvasText({ page, text: editedText });
await selectContentInstance({ page, text: editedText });
await expectVariableListItem({
page,
name: staticName,
badge: "Static variable",
});
await expectVariableListItem({
page,
name: httpName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: graphqlName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: systemName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: currentDateName,
badge: "Dynamic variable",
});
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
currentDateName,
deletedName: undefined,
});
await measure(
"data variables runtime delete graphql variable",
async () => {
await deleteVariable({
page,
fixture,
name: graphqlName,
});
}
);
await page.getByText(graphqlName, { exact: true }).waitFor({
state: "hidden",
});
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
currentDateName,
deletedName: graphqlName,
});
});
const results = await Promise.allSettled([
verifyPreview(),
verifyPersistence(),
]);
for (const result of results) {
if (result.status === "rejected") {
throw result.reason;
}
}
} finally {
await Promise.all([http.close(), graphql.close()]);
}
});
@@ -1,600 +0,0 @@
import type { Page } from "@playwright/test";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
import {
bindSelectedTextContentToExpression,
createGraphqlResourceVariable,
createHttpResourceVariable,
createSystemResourceVariable,
selectContentInstance,
} from "../flows/data-variables";
import {
waitForChangeToBeSaved,
waitForSyncStatus,
} from "../flows/sync-status";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { loginWithSecret } from "../flows/dashboard";
import { expectGeneratedAppToRender } from "../flows/generated-app";
import { test } from "../test";
import { measure } from "../perf";
import { loadDevBuild } from "../db";
test.describe.configure({ mode: "parallel" });
type DataSourceRecord =
| {
id: string;
type: "variable";
name: string;
value: { type: string; value: unknown };
}
| {
id: string;
type: "resource";
name: string;
resourceId: string;
};
type ResourceRecord = {
id: string;
name: string;
url: string;
method: string;
control?: "graphql" | "system";
body?: string;
searchParams?: Array<{ name: string; value: string }>;
headers?: Array<{ name: string; value: string }>;
};
const getDataVariableRuntimeState = async (fixture: { projectId: string }) => {
const build = await loadDevBuild({ projectId: fixture.projectId });
return {
dataSources: JSON.parse(build.dataSources) as DataSourceRecord[],
resources: JSON.parse(build.resources) as ResourceRecord[],
};
};
const getVariableForm = (page: Page) =>
page
.locator("form")
.filter({ has: page.locator('input[name="name"]') })
.last();
const fillVariableName = async ({
page,
name,
}: {
page: Page;
name: string;
}) => {
await getVariableForm(page).locator('input[name="name"]').fill(name);
};
const getVariableIdByName = async ({
fixture,
name,
}: {
fixture: { projectId: string };
name: string;
}) => {
const { dataSources } = await getDataVariableRuntimeState(fixture);
const dataSource = dataSources.find((dataSource) => dataSource.name === name);
if (dataSource === undefined) {
throw new Error(`Expected data variable "${name}" to exist.`);
}
return dataSource.id;
};
const closeVariablePanelAndWaitForSave = async ({ page }: { page: Page }) => {
const save = waitForChangeToBeSaved({ page });
await page.getByRole("button", { name: "Close" }).last().click();
await save;
await page
.getByText("New variable", { exact: true })
.waitFor({ state: "hidden" });
await waitForSyncStatus({ page, status: "idle" });
};
const openNewVariablePanel = async ({ page }: { page: Page }) => {
await page.getByRole("tab", { name: "Settings" }).click();
await page.getByRole("button", { name: "Add variable" }).click();
await page.getByText("New variable", { exact: true }).waitFor();
};
const createStringVariable = async ({
page,
name,
value,
}: {
page: Page;
name: string;
value: string;
}) => {
await openNewVariablePanel({ page });
await fillVariableName({ page, name });
await page.getByLabel("Value").last().fill(value);
await closeVariablePanelAndWaitForSave({ page });
};
const editStringVariable = async ({
page,
fixture,
name,
value,
}: {
page: Page;
fixture: { projectId: string };
name: string;
value: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
await page.locator(`button[data-id="${id}"]`).click();
await getVariableForm(page).locator('input[name="name"]').waitFor();
await page.getByLabel("Value").last().fill(value);
await closeVariablePanelAndWaitForSave({ page });
};
const deleteVariable = async ({
page,
fixture,
name,
}: {
page: Page;
fixture: { projectId: string };
name: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
const row = page.locator(`button[data-id="${id}"]`).locator("xpath=..");
await row.hover();
await row.getByRole("button", { name: "Open variable menu" }).click();
await page.getByRole("menuitem", { name: /^Delete/ }).click();
const save = waitForChangeToBeSaved({ page });
await page
.getByRole("dialog", { name: "Delete confirmation" })
.getByRole("button", { name: "Delete" })
.click();
await save;
await waitForSyncStatus({ page, status: "idle" });
};
const editHttpResourceVariableWithCurl = async ({
page,
fixture,
name,
curl,
}: {
page: Page;
fixture: { projectId: string };
name: string;
curl: string;
}) => {
const id = await getVariableIdByName({ fixture, name });
await page.locator(`button[data-id="${id}"]`).click();
await getVariableForm(page).locator('input[name="name"]').waitFor();
await page.getByRole("textbox", { name: "URL" }).fill(curl);
await closeVariablePanelAndWaitForSave({ page });
};
const expectVariableListItem = async ({
page,
name,
badge,
}: {
page: Page;
name: string;
badge: "Static variable" | "Dynamic variable";
}) => {
const itemButton = page
.getByText(name, { exact: true })
.locator("xpath=ancestor::button[@data-id][1]");
await itemButton.waitFor({ state: "visible" });
await itemButton
.locator("xpath=parent::*")
.getByLabel(badge)
.waitFor({ state: "attached" });
};
const expectPersistedDataVariables = async ({
fixture,
staticName,
staticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
deletedName,
}: {
fixture: { projectId: string };
staticName: string;
staticValue: string;
httpName: string;
httpUrl: string;
httpCurlUrl?: string;
httpSearchParamName?: string;
httpSearchParamValue?: string;
httpHeaderName?: string;
httpHeaderValue?: string;
httpBodyValue?: string;
graphqlName: string;
graphqlUrl: string;
graphqlQuery: string;
systemName: string;
deletedName?: string;
}) => {
const { dataSources, resources } = await getDataVariableRuntimeState(fixture);
const staticVariable = dataSources.find(
(dataSource) => dataSource.name === staticName
);
if (
staticVariable?.type !== "variable" ||
staticVariable.value.type !== "string" ||
staticVariable.value.value !== staticValue
) {
throw new Error(
`Expected static variable "${staticName}" to persist with string value. Received: ${JSON.stringify(staticVariable)}. All data sources: ${JSON.stringify(dataSources)}`
);
}
const httpVariable = dataSources.find(
(dataSource) => dataSource.name === httpName
);
const httpResource = resources.find(
(resource) =>
httpVariable?.type === "resource" &&
resource.id === httpVariable.resourceId
);
if (
httpVariable?.type !== "resource" ||
httpResource === undefined ||
httpResource?.control !== undefined ||
httpResource.url !== JSON.stringify(httpCurlUrl ?? httpUrl) ||
httpResource.method !== (httpCurlUrl === undefined ? "get" : "post")
) {
throw new Error(`Expected HTTP resource variable "${httpName}".`);
}
if (
httpSearchParamName !== undefined &&
httpResource.searchParams?.some(
(searchParam) =>
searchParam.name === httpSearchParamName &&
searchParam.value === JSON.stringify(httpSearchParamValue)
) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist search param "${httpSearchParamName}". Received: ${JSON.stringify(httpResource)}`
);
}
if (
httpHeaderName !== undefined &&
httpResource.headers?.some(
(header) =>
header.name === httpHeaderName &&
header.value === JSON.stringify(httpHeaderValue)
) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist header "${httpHeaderName}". Received: ${JSON.stringify(httpResource)}`
);
}
if (
httpBodyValue !== undefined &&
httpResource.body?.includes(httpBodyValue) !== true
) {
throw new Error(
`Expected HTTP resource "${httpName}" to persist body value "${httpBodyValue}". Received: ${JSON.stringify(httpResource)}`
);
}
if (deletedName !== graphqlName) {
const graphqlVariable = dataSources.find(
(dataSource) => dataSource.name === graphqlName
);
const graphqlResource = resources.find(
(resource) =>
graphqlVariable?.type === "resource" &&
resource.id === graphqlVariable.resourceId
);
if (
graphqlVariable?.type !== "resource" ||
graphqlResource?.control !== "graphql" ||
graphqlResource.url !== JSON.stringify(graphqlUrl) ||
graphqlResource.method !== "post" ||
graphqlResource.body?.includes(graphqlQuery) !== true
) {
throw new Error(`Expected GraphQL resource variable "${graphqlName}".`);
}
}
const systemVariable = dataSources.find(
(dataSource) => dataSource.name === systemName
);
const systemResource = resources.find(
(resource) =>
systemVariable?.type === "resource" &&
resource.id === systemVariable.resourceId
);
if (
systemVariable?.type !== "resource" ||
systemResource?.control !== "system" ||
systemResource.method !== "get"
) {
throw new Error(`Expected system resource variable "${systemName}".`);
}
if (
deletedName !== undefined &&
dataSources.some((dataSource) => dataSource.name === deletedName)
) {
throw new Error(`Expected deleted variable "${deletedName}" to be absent.`);
}
};
test("Builder-created data variables and resources persist after reload", async ({
page,
context,
}) => {
const email = "data-variables-runtime@webstudio.test";
const fixture = await createContentModeProject({
context: context,
email,
title: "Data Variables Runtime",
assetNamePrefix: "data-variables-runtime-",
editorToken: "data-variables-runtime-editor-token",
builderToken: "data-variables-runtime-builder-token",
});
const staticName = "e2eStaticLabel";
const staticValue = "Created from Builder UI";
const editedStaticValue = "Edited from Builder UI";
const httpName = "e2ePosts";
const httpUrl = "https://example.com/posts.json";
const httpCurlUrl = "https://example.com/api/posts";
const httpSearchParamName = "status";
const httpSearchParamValue = "published";
const httpHeaderName = "X-Test";
const httpHeaderValue = "resource-panel";
const httpBodyValue = "featured";
const graphqlName = "e2eGraphqlPosts";
const graphqlUrl = "https://example.com/graphql";
const graphqlQuery = "query Posts { posts { id title } }";
const systemName = "e2eSitemap";
await loginWithSecret({ page, email });
await measure("data variables runtime open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
});
await selectContentInstance({ page });
await measure(
"data variables runtime create variables through UI",
async () => {
await createStringVariable({
page,
name: staticName,
value: staticValue,
});
await createHttpResourceVariable({
page,
name: httpName,
url: httpUrl,
});
await createGraphqlResourceVariable({
page,
name: graphqlName,
url: graphqlUrl,
query: graphqlQuery,
});
await createSystemResourceVariable({ page, name: systemName });
}
);
await measure(
"data variables runtime edit resources and variables",
async () => {
await editStringVariable({
page,
fixture,
name: staticName,
value: editedStaticValue,
});
await editHttpResourceVariableWithCurl({
page,
fixture,
name: httpName,
curl: `curl '${httpCurlUrl}?${httpSearchParamName}=${httpSearchParamValue}' --request POST --header '${httpHeaderName}: ${httpHeaderValue}' --header 'Content-Type: application/json' --data '{"${httpBodyValue}":true}'`,
});
}
);
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
deletedName: undefined,
});
await expectVariableListItem({
page,
name: staticName,
badge: "Static variable",
});
await expectVariableListItem({
page,
name: httpName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: graphqlName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: systemName,
badge: "Dynamic variable",
});
await measure("data variables runtime reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text: "Initial content" });
await selectContentInstance({ page });
await expectVariableListItem({
page,
name: staticName,
badge: "Static variable",
});
await expectVariableListItem({
page,
name: httpName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: graphqlName,
badge: "Dynamic variable",
});
await expectVariableListItem({
page,
name: systemName,
badge: "Dynamic variable",
});
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
deletedName: undefined,
});
await measure("data variables runtime delete graphql variable", async () => {
await deleteVariable({
page,
fixture,
name: graphqlName,
});
});
await page.getByText(graphqlName, { exact: true }).waitFor({
state: "hidden",
});
await expectPersistedDataVariables({
fixture,
staticName,
staticValue: editedStaticValue,
httpName,
httpUrl,
httpCurlUrl,
httpSearchParamName,
httpSearchParamValue,
httpHeaderName,
httpHeaderValue,
httpBodyValue,
graphqlName,
graphqlUrl,
graphqlQuery,
systemName,
deletedName: graphqlName,
});
});
test("Text Content can bind to a Builder-created variable and persist after reload", async ({
page,
context,
}) => {
const email = "text-content-binding@webstudio.test";
const fixture = await createContentModeProject({
context: context,
email,
title: "Text Content Binding",
assetNamePrefix: "text-content-binding-",
editorToken: "text-content-binding-editor-token",
builderToken: "text-content-binding-builder-token",
});
const staticName = "e2eTextBindingLabel";
const staticValue = "Bound Text Content";
await loginWithSecret({ page, email });
await measure("text content binding open builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await waitForCanvasText({ page, text: "Initial content" });
});
await selectContentInstance({ page });
await measure("text content binding create variable", async () => {
await createStringVariable({
page,
name: staticName,
value: staticValue,
});
});
await measure("text content binding bind expression", async () => {
await bindSelectedTextContentToExpression({
page,
expression: staticName,
});
await waitForCanvasText({ page, text: staticValue });
});
await measure("text content binding reload builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
});
await waitForCanvasText({ page, text: staticValue });
await measure("text content binding generated app renders", async () => {
await expectGeneratedAppToRender({
projectId: fixture.projectId,
expectedText: staticValue,
});
});
});
@@ -1,9 +1,9 @@
import { execFile } from "node:child_process";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { expect } from "@playwright/test";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
@@ -11,7 +11,6 @@ import { loadDevBuild } from "../db";
import { e2ePaidPlanName } from "../plans";
import { dashboardUrl, test } from "../test";
const execFileAsync = promisify(execFile);
const cliPath = fileURLToPath(
new URL("../../../../packages/cli/local.js", import.meta.url)
);
@@ -30,30 +29,13 @@ test("Editor MCP fragment insertion persists inside Content Block and rejects it
const directory = await mkdtemp(join(tmpdir(), "webstudio-mcp-editor-"));
const insertedText = "Editor MCP round-trip content";
const deniedText = "Protected template must stay unchanged";
const call = async (tool: string, input: object) => {
const args = [
cliPath,
"mcp",
"single-op-call",
tool,
JSON.stringify(input),
"--project",
fixture.projectId,
];
try {
const { stdout } = await execFileAsync(process.execPath, args, {
cwd: directory,
timeout: 60_000,
env: { ...process.env, WEBSTUDIO_CONFIG_DIR: directory },
});
return JSON.parse(stdout);
} catch (error) {
const stdout = (error as Error & { stdout?: string }).stdout;
if (stdout === undefined) {
throw error;
}
return JSON.parse(stdout);
}
const client = new Client({
name: "mcp-editor-fragment-e2e",
version: "1.0.0",
});
const call = async (name: string, args: Record<string, unknown>) => {
const result = await client.callTool({ name, arguments: args });
return JSON.parse(JSON.stringify(result.structuredContent));
};
try {
@@ -68,6 +50,19 @@ test("Editor MCP fragment insertion persists inside Content Block and rejects it
{ mode: 0o600 }
);
await client.connect(
new StdioClientTransport({
command: process.execPath,
args: [cliPath, "mcp", "--project", fixture.projectId],
cwd: directory,
env: {
...process.env,
WEBSTUDIO_CONFIG_DIR: directory,
} as Record<string, string>,
stderr: "inherit",
})
);
const inserted = await call("insert-fragment", {
parentInstanceId: "content-block",
fragment: `<p>${insertedText}</p>`,
@@ -76,6 +71,7 @@ test("Editor MCP fragment insertion persists inside Content Block and rejects it
expect(inserted.ok, inserted.error?.code).toBe(true);
expect(inserted.meta.session.commitStatus).toBe("committed");
expect((await call("refresh", {})).ok).toBe(true);
const reloaded = await call("list-texts", { contains: insertedText });
expect(reloaded.ok).toBe(true);
expect(reloaded.data.texts).toEqual(
@@ -105,6 +101,10 @@ test("Editor MCP fragment insertion persists inside Content Block and rejects it
expect(afterDenied.version).toBe(beforeDenied.version);
expect(afterDenied.instances).toEqual(beforeDenied.instances);
} finally {
await rm(directory, { recursive: true, force: true });
try {
await client.close();
} finally {
await rm(directory, { recursive: true, force: true });
}
}
});
@@ -24,6 +24,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
test.setTimeout(240_000);
const fixture = await createContentModeProject({
context,
page,
email: "mcp-editor-pages@webstudio.test",
title: "MCP Editor pages",
devPlan: e2ePaidPlanName,
@@ -43,10 +44,11 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
const builderToken = `${fixture.projectId}-mcp-builder-token`;
const directories = {
editor: directory,
editorRead: freshDirectory,
viewer: viewerDirectory,
builder: builderDirectory,
};
const clients = new Map<keyof typeof directories, Client>();
const clients = new Map<keyof typeof directories, Promise<Client>>();
const connect = async (cwd: string, configDirectory: string) => {
const client = new Client({
name: "mcp-editor-pages-e2e",
@@ -70,32 +72,27 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
}
return client;
};
const call = async (
tool: string,
input: object,
{
fresh = false,
role = "editor",
}: { fresh?: boolean; role?: keyof typeof directories } = {}
) => {
const client = fresh
? await connect(freshDirectory, directories[role])
: (clients.get(role) ??
(await connect(directories[role], directories[role])));
if (fresh === false) {
const getClient = (role: keyof typeof directories) => {
let client = clients.get(role);
if (client === undefined) {
client = connect(
directories[role],
role === "editorRead" ? directories.editor : directories[role]
);
// A prestarted connection can fail before its first tool call is ready.
client.catch(() => undefined);
clients.set(role, client);
}
try {
const result = await client.callTool({
name: tool,
arguments: input as Record<string, unknown>,
});
return JSON.parse(JSON.stringify(result.structuredContent));
} finally {
if (fresh) {
await client.close();
}
}
return client;
};
const call = async (
tool: string,
input: Record<string, unknown>,
role: keyof typeof directories = "editor"
) => {
const client = await getClient(role);
const result = await client.callTool({ name: tool, arguments: input });
return JSON.parse(JSON.stringify(result.structuredContent));
};
try {
@@ -155,7 +152,11 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
expect(updated.ok, updated.error?.message).toBe(true);
expect(updated.meta.session.commitStatus).toBe("committed");
const reloaded = await call("get-page", { pageId }, { fresh: true });
// The remaining CLI processes have separate session directories. Start
// the role checks' connections while the fresh editor reads this commit.
getClient("viewer");
getClient("builder");
const reloaded = await call("get-page", { pageId }, "editorRead");
expect(reloaded.ok).toBe(true);
expect(reloaded.data).toMatchObject({
id: pageId,
@@ -165,20 +166,6 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
meta: { description: '"Edited MCP description"' },
});
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openPage({
page,
pageName: "Edited MCP content page",
canvasText: fixture.pageTemplateText,
});
await openPageSettings({ page, pageName: "Edited MCP content page" });
await expect(page.getByLabel("Title")).toHaveValue("Edited MCP title");
const beforeDenied = await loadDevBuild({ projectId: fixture.projectId });
const denied = await call("update-page-settings", {
pageId,
@@ -207,13 +194,20 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
expect(uploaded.meta.session.commitStatus).toBe("committed");
const assetId = uploaded.data.uploaded[0].id;
const asset = await call("get-asset", { assetId }, { fresh: true });
const refreshed = await call(
"refresh",
{ namespaces: ["assets", "assetFolders"] },
"editorRead"
);
expect(refreshed.ok, refreshed.error?.message).toBe(true);
const asset = await call("get-asset", { assetId }, "editorRead");
expect(asset.ok).toBe(true);
expect(asset.data.asset).toMatchObject({
id: assetId,
folderId,
});
const folders = await call("list-asset-folders", {}, { fresh: true });
const folders = await call("list-asset-folders", {}, "editorRead");
expect(folders.ok).toBe(true);
expect(folders.data.folders).toEqual(
expect.arrayContaining([
@@ -221,58 +215,82 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
])
);
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openAssetsPanel({ page });
await page
.getByRole("button", { name: "Folder Editor MCP assets" })
.dblclick();
await waitForAsset({ page, filename });
// Verify both read paths before the Builder role changes the saved page.
const readResults = await Promise.allSettled([
test.step("verify saved MCP edits in Builder", async () => {
await openProjectBuilder({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await openPage({
page,
pageName: "Edited MCP content page",
canvasText: fixture.pageTemplateText,
});
await openPageSettings({ page, pageName: "Edited MCP content page" });
await expect(page.getByLabel("Title")).toHaveValue("Edited MCP title");
const beforeViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect((await call("list-pages", {}, { role: "viewer" })).ok).toBe(true);
for (const [tool, input] of [
[
"create-page-from-template",
{ templateId: template.id, name: "Denied", path: "/denied" },
],
["create-asset-folder", { name: "Denied folder" }],
[
"upload-asset",
{
asset: { name: filename, type: "file", format: "txt" },
assetsDir: directory,
},
],
] as const) {
const denied = await call(tool, input, { role: "viewer" });
expect(denied.ok, tool).toBe(false);
expect(denied.error.code, `${tool}: ${denied.error.message}`).toBe(
"FORBIDDEN"
);
await openAssetsPanel({ page });
await page
.getByRole("button", { name: "Folder Editor MCP assets" })
.dblclick();
await waitForAsset({ page, filename });
}),
test.step("verify the MCP viewer cannot write", async () => {
const beforeViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect((await call("list-pages", {}, "viewer")).ok).toBe(true);
for (const [tool, input] of [
[
"create-page-from-template",
{ templateId: template.id, name: "Denied", path: "/denied" },
],
["create-asset-folder", { name: "Denied folder" }],
[
"upload-asset",
{
asset: { name: filename, type: "file", format: "txt" },
assetsDir: directory,
},
],
] as const) {
const denied = await call(tool, input, "viewer");
expect(denied.ok, tool).toBe(false);
expect(denied.error.code, `${tool}: ${denied.error.message}`).toBe(
"FORBIDDEN"
);
}
const afterViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect(afterViewerWrites.version).toBe(beforeViewerWrites.version);
expect(afterViewerWrites.pages).toEqual(beforeViewerWrites.pages);
}),
]);
for (const result of readResults) {
if (result.status === "rejected") {
throw result.reason;
}
}
const afterViewerWrites = await loadDevBuild({
projectId: fixture.projectId,
});
expect(afterViewerWrites.version).toBe(beforeViewerWrites.version);
expect(afterViewerWrites.pages).toEqual(beforeViewerWrites.pages);
const builderWrite = await call(
"update-page-settings",
{ pageId, values: { status: "302" } },
{ role: "builder" }
"builder"
);
expect(builderWrite.ok, builderWrite.error?.message).toBe(true);
const builderPage = await call("get-page", { pageId }, { role: "builder" });
const builderPage = await call("get-page", { pageId }, "builder");
expect(builderPage.data.meta.status).toBe("302");
} finally {
await Promise.all(Array.from(clients.values(), (client) => client.close()));
const connections = await Promise.allSettled(clients.values());
await Promise.all(
connections.flatMap((connection) =>
connection.status === "fulfilled" ? [connection.value.close()] : []
)
);
await Promise.all([
rm(directory, { recursive: true, force: true }),
rm(freshDirectory, { recursive: true, force: true }),
@@ -1,157 +0,0 @@
import { execFile } from "node:child_process";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { expect } from "@playwright/test";
import { loadDevBuild } from "../db";
import { createContentModeProject } from "../fixtures/content-mode-suite";
import {
startLocalEmailReceiver,
withMcpEmailPreview,
} from "../flows/mcp-email-preview";
import { test } from "../test";
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
const execFileAsync = promisify(execFile);
const authorPath = fileURLToPath(
new URL("../fixtures/mcp-managed-form-author.ts", import.meta.url)
);
const reactGlobalPath = fileURLToPath(
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
);
const cliTsconfigPath = fileURLToPath(
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
);
test("MCP-authored Email Resources deliver multiple files and honor attachment opt-out", async ({
context,
}) => {
const fixture = await createContentModeProject({
context,
email: "mcp-email-attachments@webstudio.test",
title: "MCP Email attachments",
assetNamePrefix: "mcp-email-attachments-",
builderToken: "mcp-email-attachments-builder-token",
});
const { stdout } = await execFileAsync(
process.execPath,
[
"--import",
"tsx",
"--import",
reactGlobalPath,
"--conditions=webstudio",
authorPath,
fixture.projectId,
"email-attachments",
],
{
timeout: 60_000,
env: { ...process.env, TSX_TSCONFIG_PATH: cliTsconfigPath },
}
);
const { formId, emailResourceIds } = JSON.parse(stdout) as {
formId: string;
emailResourceIds: string[];
};
expect(emailResourceIds).toHaveLength(2);
const build = await loadDevBuild({ projectId: fixture.projectId });
const resources = JSON.parse(build.resources) as Array<{
id: string;
name: string;
email?: { includeAttachments?: boolean };
}>;
const ownerResource = resources.find(
({ id, name }) => emailResourceIds.includes(id) && name === "Email to owner"
);
const visitorResource = resources.find(
({ id, name }) =>
emailResourceIds.includes(id) && name === "Email to visitor"
);
expect(ownerResource?.email?.includeAttachments).toBe(true);
expect(visitorResource?.email?.includeAttachments).toBe(false);
const files = [
{
name: "café-notes.txt",
mimeType: "text/plain",
buffer: Buffer.from("First attachment: café\n", "utf8"),
},
{
name: "sample.bin",
mimeType: "application/octet-stream",
buffer: Buffer.from([0, 1, 127, 128, 254, 255]),
},
];
const receiver = await startLocalEmailReceiver();
try {
await withMcpEmailPreview({
projectId: fixture.projectId,
emailPort: receiver.port,
callback: async ({ url }) => {
const submission = await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: `[data-ws-managed-form-id="${formId}"]`,
values: [
{ name: "name", value: "Ada Lovelace" },
{ name: "email", value: "ada@example.test" },
{ name: "subject", value: "Attachment opt-out test" },
{
name: "message",
value: "Checking separate file delivery settings.",
},
...files.map((file) => ({
name: "upload",
file: {
name: file.name,
type: file.mimeType,
base64: file.buffer.toString("base64"),
},
})),
],
submitter: "button[type=submit]",
timeout: 30_000,
},
});
expect(submission.data).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.data.results).toEqual([
expect.objectContaining({
resourceId: emailResourceIds[0],
status: 200,
}),
expect.objectContaining({
resourceId: emailResourceIds[1],
status: 200,
}),
]);
expect(receiver.messages).toHaveLength(2);
const owner = receiver.messages.find((message) =>
message.to.some(({ address }) => address === "owner@mcp.test")
);
const visitor = receiver.messages.find((message) =>
message.to.some(({ address }) => address === "ada@example.test")
);
expect(owner).toBeDefined();
expect(visitor).toBeDefined();
expect(owner?.attachments).toHaveLength(files.length);
for (const [index, file] of files.entries()) {
const attachment = owner?.attachments?.[index];
expect(attachment?.filename).toBe(file.name);
expect(attachment?.contentType).toBe(file.mimeType);
expect(
Buffer.from(attachment?.contentBase64 ?? "", "base64")
).toEqual(file.buffer);
}
expect(visitor?.attachments).toBeUndefined();
},
});
} finally {
await receiver.close();
}
});
@@ -0,0 +1,171 @@
import { expect } from "@playwright/test";
import { createProjectThroughApi } from "../fixtures/create-project";
import { expectFormQueryDelivery } from "../flows/form-query";
import { startFormQueryReceiver } from "../flows/form-query-receiver";
import { runFormAuthor } from "../flows/mcp-form-author";
import {
startLocalEmailReceiver,
withMcpEmailPreview,
} from "../flows/mcp-email-preview";
import { test } from "../test";
import {
startPreviewFormMcpClient,
submitPreviewFormViaMcp,
} from "../flows/mcp-preview-submit";
const twoPhaseTimeout = 240_000;
test("MCP form query delivery and Email binding changes across two production Previews", async ({
context,
page,
}) => {
test.setTimeout(twoPhaseTimeout);
await startPreviewFormMcpClient();
const projectId = await createProjectThroughApi({
context,
email: "mcp-email-binding-scenarios@webstudio.test",
title: "MCP Email binding scenarios",
});
const { stdout } = await runFormAuthor("mcp-email-binding-author", projectId);
const { boundFormId, partialFormId, query, initialBundle, updatedBundle } =
JSON.parse(stdout) as {
boundFormId: string;
partialFormId: string;
query: { formId: string; resourceId: string };
initialBundle: string;
updatedBundle: string;
};
const submit = async (url: string, formId: string, withUpload: boolean) => {
const submission = await submitPreviewFormViaMcp({
url,
input: {
path: "/",
selector: '[data-ws-managed-form-id="' + formId + '"]',
values: [
{ name: "name", value: "Ada Lovelace" },
{ name: "email", value: "ada@example.test" },
{ name: "subject", value: "Account question" },
{
name: "message",
value: withUpload ? "Hello" : "Please send the project details.",
},
...(withUpload
? [
{
name: "upload",
file: {
name: "private-note.txt",
type: "text/plain",
base64: Buffer.from("Do not attach this file").toString(
"base64"
),
},
},
]
: []),
],
submitter: "button[type=submit]",
timeout: 30_000,
},
});
expect(submission.data).toMatchObject({
status: "submitted",
formState: "success",
errors: [],
});
expect(submission.data.results).toEqual([
expect.objectContaining({ status: 200 }),
]);
};
const receiver = await startLocalEmailReceiver();
try {
const queryReceiver = await startFormQueryReceiver();
const checkInitialDelivery = async (url: string) => {
await test.step("bound values and recipients", async () => {
await submit(url, boundFormId, false);
await expect.poll(() => receiver.messages.length).toBe(1);
expect(receiver.messages[0]).toMatchObject({
to: [{ address: "ada@example.test" }],
subject: expect.stringContaining("Bound: Account question"),
text: "Message from Ada Lovelace: Please send the project details.",
replyTo: { address: "ada@example.test" },
});
});
await test.step("partial body update keeps sender and attachment settings", async () => {
await submit(url, partialFormId, true);
await expect.poll(() => receiver.messages.length).toBe(2);
expect(receiver.messages[1]).toMatchObject({
to: [{ address: "ada@example.test" }],
text: "Custom confirmation",
replyTo: { address: "team@example.test", name: "Contact Team" },
fromName: "Contact Team",
});
expect(receiver.messages[1]?.attachments ?? []).toEqual([]);
});
await expectFormQueryDelivery({
page,
url,
receiver: queryReceiver,
...query,
});
};
const checkUpdatedDelivery = async (url: string) => {
await test.step("full reset restores project recipient and reply-to", async () => {
await submit(url, boundFormId, false);
await expect.poll(() => receiver.messages.length).toBe(3);
expect(receiver.messages[2]).toMatchObject({
to: [{ address: "owner@mcp.test" }],
subject: expect.stringContaining("New form submission"),
text: expect.stringContaining("Form data:"),
replyTo: { address: "forms@mcp.test", name: "Contact Form" },
});
});
await test.step("empty body keeps recipient and sender settings", async () => {
await submit(url, partialFormId, true);
await expect.poll(() => receiver.messages.length).toBe(4);
expect(receiver.messages[3]).toMatchObject({
to: [{ address: "ada@example.test" }],
text: "",
replyTo: { address: "team@example.test", name: "Contact Team" },
fromName: "Contact Team",
});
expect(receiver.messages[3]?.attachments ?? []).toEqual([]);
});
};
try {
await withMcpEmailPreview({
bundle: initialBundle,
emailPort: receiver.port,
queryPort: queryReceiver.port,
callback: async ({ url }) => {
// The initial app is already compiled. Build the updated saved
// snapshot while the browser checks the initial deliveries.
const initialDelivery = checkInitialDelivery(url);
const results = await Promise.allSettled([
initialDelivery,
withMcpEmailPreview({
bundle: updatedBundle,
emailPort: receiver.port,
callback: async ({ url }) => {
await initialDelivery;
await checkUpdatedDelivery(url);
},
}),
]);
for (const result of results) {
if (result.status === "rejected") {
throw result.reason;
}
}
},
});
} finally {
await queryReceiver.close();
}
} finally {
await receiver.close();
}
});
Loaded 100 of 152 files, more files were not shown because too many files have changed in this diff. Show more