mirror of
https://github.com/webstudio-is/webstudio.git
synced 2026-12-01 21:05:42 +09:00
perf: Speed up Builder E2E tests (#6689)
Builder E2E still takes too long. The goal is all 145 cases under 3 minutes end to end, with exactly ten shards and the same UI, MCP, and generated Preview checks. This PR has not met that goal. ### Measured results - Initial green CI run: 9m43s from build start to the last shard; slowest test step 439s. - Best green run after replacing repeated UI project setup: about 5m35s; slowest test step 250s. - Best green run (393e51c): about 4m59s; slowest test step 201s. The two-file rebalance reduced the prior green run by about 50s. The 3-minute goal remains unmet. - Latest green run (de2f4ed): about 5m56s; slowest test step 257s. All ten shards and required workflows passed. The preceding green run took about 6m09s, showing substantial run-to-run variation. - The 119 content-mode project setup calls fell from 599s to 23.5s of aggregate worker time by using the app's dev login and project creation API. The sum of shard test steps fell from 2,178s to 1,721s in the first run with this change. Per-shard wall time still varies substantially between runs. - The shared build takes about 85s, including roughly 30s of setup and 51s of Builder compilation. During tests, the four-CPU shard runners showed 27–52% CPU scheduling pressure and 0% memory pressure; peak memory was unavailable. ### Changes - Cache the test schema and share one Builder build artifact across ten shards. Shard setup overlaps the build; each shard still starts an isolated database. - Keep real MCP and browser sessions alive for repeated Preview submissions, and reuse generated Previews where checks can share one. - Give independent cases separate projects and run them within the existing shard workers. Keep exactly ten shards. - Create content-mode fixture projects through the app's normal login and project API, using its CSRF token. Dedicated UI project creation remains in the Builder project fixture. - Capture managed Form responses before fast redirects discard their bodies. Fix drag targeting and unique drag fixture IDs. - Report CPU and memory pressure for every shard. Allow the MCP browser startup enough time under CI load. An earlier shard rebalance worsened the run and was reverted; a measured two-file rebalance improved the slowest shard without changing test logic. ### Verification and remaining work Focused local runs passed for a single project, three projects sharing one session, a paid-plan MCP project, and the MCP Preview form case. Builder and Vision typechecks, lint, formatting, the ten-shard matrix check, and Vision regression tests passed. All required workflows passed onde2f4ed. The latest review fix also passed all 63 Vision tests, Vision typecheck, lint, and formatting locally. - [x] Profile the full suite and measure complete ten-shard CI runs. - [x] Remove repeated UI project setup from the shared fixture. - [x] Measure CPU and memory pressure in CI. - [ ] Reduce Builder interactions, generated Preview work, and build time enough to finish under 3 minutes. - [x] Resolve five review threads and verify the affected paths. - [x] Check authoritative Builder documentation; these test harness and capture fixes do not change user-facing behavior or documentation. CI still checks out and installs dependencies, builds Builder, uploads and downloads its artifact, starts a database for each shard, and runs real browsers and generated production Previews. Warm caches remove downloads and schema generation, but do not remove setup, compilation, browser work, or cache transfers. No product behavior or authoritative documentation changed.
This commit is contained in:
1 parent
207686a0d9
commit
23c81d64c9
47 files changed
+1101
-364
No files matched your search
@@ -28,6 +28,13 @@ runs:
|
||||
shell: bash
|
||||
run: |
|
||||
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) =>
|
||||
shard !== `shard-${index + 1}` || partition !== "")) {
|
||||
throw new Error("Builder E2E shard matrix changed; update the workflow matrix before running CI.");
|
||||
}
|
||||
'
|
||||
echo "value=$shards" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Build Builder
|
||||
@@ -38,10 +45,37 @@ runs:
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/sdk-components-react-router build
|
||||
|
||||
- name: Identify schema snapshot
|
||||
id: schema
|
||||
shell: bash
|
||||
run: |
|
||||
ROOT_DIR="$PWD"
|
||||
source apps/builder/backend/lib.sh
|
||||
echo "fingerprint=$(builder_backend_schema_fingerprint)" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- name: Restore schema snapshot
|
||||
id: schema-cache
|
||||
uses: actions/cache/restore@v5
|
||||
with:
|
||||
path: .cache/builder-e2e/schema-${{ steps.schema.outputs.fingerprint }}.sql
|
||||
key: builder-e2e-schema-v1-${{ runner.os }}-${{ steps.schema.outputs.fingerprint }}
|
||||
|
||||
- name: Generate schema snapshot
|
||||
if: steps.schema-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: pnpm --filter @webstudio-is/builder e2e:schema-cache
|
||||
|
||||
- name: Check schema snapshot
|
||||
shell: bash
|
||||
run: test -s ".cache/builder-e2e/schema-${{ steps.schema.outputs.fingerprint }}.sql"
|
||||
|
||||
- name: Save schema snapshot
|
||||
if: steps.schema-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/save@v5
|
||||
with:
|
||||
path: .cache/builder-e2e/schema-${{ steps.schema.outputs.fingerprint }}.sql
|
||||
key: builder-e2e-schema-v1-${{ runner.os }}-${{ steps.schema.outputs.fingerprint }}
|
||||
|
||||
- name: Upload prerequisites
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
|
||||
@@ -33,6 +33,21 @@ runs:
|
||||
~/.cache/ms-playwright/ffmpeg-*
|
||||
key: playwright-chromium-${{ runner.os }}-${{ hashFiles('pnpm-lock.yaml') }}
|
||||
|
||||
- name: Wait for Builder E2E build
|
||||
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
|
||||
exit 0
|
||||
fi
|
||||
sleep 5
|
||||
done
|
||||
echo "Builder E2E build artifact was not uploaded within 7 minutes" >&2
|
||||
exit 1
|
||||
|
||||
- name: Download Builder E2E build
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
@@ -45,11 +60,16 @@ runs:
|
||||
E2E_TEST_SHARD: ${{ inputs.shard }}
|
||||
E2E_TEST_PARTITION: ${{ inputs.partition }}
|
||||
run: |
|
||||
args=(--workers=2)
|
||||
workers=3
|
||||
if [ "$E2E_TEST_SHARD" = "shard-5" ]; then
|
||||
workers=2
|
||||
fi
|
||||
args=(--workers="$workers")
|
||||
if [ -n "$E2E_TEST_PARTITION" ]; then
|
||||
args+=(--shard="$E2E_TEST_PARTITION")
|
||||
fi
|
||||
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
|
||||
bash apps/builder/e2e/measure-resources.sh \
|
||||
pnpm --filter @webstudio-is/builder e2e:ci:shard -- "${args[@]}"
|
||||
|
||||
- name: Upload report
|
||||
if: failure()
|
||||
|
||||
@@ -201,13 +201,25 @@ jobs:
|
||||
name: builder-e2e (${{ matrix.shard }})
|
||||
timeout-minutes: 12
|
||||
|
||||
needs: builder-e2e-build
|
||||
|
||||
runs-on: ubuntu-24.04
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include: ${{ fromJSON(needs.builder-e2e-build.outputs.shards) }}
|
||||
shard:
|
||||
- shard-1
|
||||
- shard-2
|
||||
- shard-3
|
||||
- shard-4
|
||||
- shard-5
|
||||
- shard-6
|
||||
- shard-7
|
||||
- shard-8
|
||||
- shard-9
|
||||
- shard-10
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
|
||||
environment:
|
||||
name: development
|
||||
@@ -222,4 +234,3 @@ jobs:
|
||||
with:
|
||||
submodules-ssh-key: ${{ secrets.PRIVATE_GITHUB_DEPLOY_TOKEN }}
|
||||
shard: ${{ matrix.shard }}
|
||||
partition: ${{ matrix.partition }}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { dirname, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
import { afterEach, expect, test } from "vitest";
|
||||
|
||||
@@ -67,6 +67,37 @@ test("schema fingerprint includes new backend files", async () => {
|
||||
expect(await readSchemaFingerprint(root)).not.toBe(before);
|
||||
});
|
||||
|
||||
test("schema fingerprint ignores generated migration clients", async () => {
|
||||
const root = await createRepositoryFixture();
|
||||
const before = await readSchemaFingerprint(root);
|
||||
const client = join(
|
||||
root,
|
||||
"packages/prisma-client/prisma/migrations/initial/client"
|
||||
);
|
||||
await mkdir(client, { recursive: true });
|
||||
await writeFile(join(client, "schema.prisma"), "generated");
|
||||
|
||||
expect(await readSchemaFingerprint(root)).toBe(before);
|
||||
});
|
||||
|
||||
test.each([
|
||||
"packages/prisma-client/prisma/migrations/initial/schema.prisma",
|
||||
"packages/prisma-client/prisma/schema.prisma",
|
||||
"packages/prisma-client/migrations-cli/commands.ts",
|
||||
"packages/prisma-client/src/prisma.ts",
|
||||
"packages/prisma-client/package.json",
|
||||
"pnpm-lock.yaml",
|
||||
])("schema fingerprint includes %s", async (file) => {
|
||||
const root = await createRepositoryFixture();
|
||||
const path = join(root, file);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, "before");
|
||||
const before = await readSchemaFingerprint(root);
|
||||
await writeFile(path, "after");
|
||||
|
||||
expect(await readSchemaFingerprint(root)).not.toBe(before);
|
||||
});
|
||||
|
||||
test("backend modes select safe Compose projects", async () => {
|
||||
const root = await createRepositoryFixture();
|
||||
const readProjectName = async (mode: "development" | "test") => {
|
||||
|
||||
@@ -36,8 +36,16 @@ builder_backend_schema_fingerprint() {
|
||||
find packages/prisma-client/prisma/migrations \
|
||||
-mindepth 1 -maxdepth 1 -type d -print
|
||||
find packages/prisma-client/prisma/migrations \
|
||||
-type f \( -name migration.sql -o -name migration.ts \) -print
|
||||
-type d -name client -prune -o \
|
||||
-type f \( -name migration.sql -o -name migration.ts -o -name schema.prisma -o -name migration_lock.toml -o -name template.txt \) -print
|
||||
find packages/prisma-client/migrations-cli \
|
||||
-type f -name '*.ts' ! -name '*.test.ts' -print
|
||||
find apps/builder/backend -type f ! -name '*.test.*' -print
|
||||
printf '%s\n' \
|
||||
packages/prisma-client/prisma/schema.prisma \
|
||||
packages/prisma-client/src/prisma.ts \
|
||||
packages/prisma-client/package.json \
|
||||
pnpm-lock.yaml
|
||||
} | LC_ALL=C sort | while IFS= read -r file; do
|
||||
if [ -f "$file" ]; then
|
||||
printf '%s ' "$file"
|
||||
|
||||
@@ -12,6 +12,9 @@ Use the full command for CI-like validation:
|
||||
pnpm e2e:builder
|
||||
```
|
||||
|
||||
The local command builds Builder and the generated React Router components
|
||||
used by Preview tests.
|
||||
|
||||
The first run after migrations change applies the regular migration pipeline
|
||||
and writes an ignored schema cache under `.cache/builder-e2e`. Refresh it
|
||||
explicitly with:
|
||||
@@ -89,8 +92,8 @@ each invocation.
|
||||
declaration order by default.
|
||||
|
||||
CI discovers isolated Playwright shards from filename tags. Each shard uses
|
||||
four workers, and files are assigned by measured CI duration to keep jobs near
|
||||
three to four minutes:
|
||||
two workers, except shard 5 uses one to avoid overlapping MCP browser launches.
|
||||
Files are assigned by measured CI duration to keep the slowest job short:
|
||||
|
||||
```txt
|
||||
pages-actions.[shard-3].e2e.ts
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import type { BrowserContext } from "@playwright/test";
|
||||
import { loginAndCreateBlankProject } from "../flows/dashboard";
|
||||
import type { BrowserContext, Page } from "@playwright/test";
|
||||
import env from "../../app/env/env.server";
|
||||
import { getWorkerEmail } from "../flows/dashboard";
|
||||
import { measure } from "../perf";
|
||||
import { dashboardUrl } from "../test";
|
||||
import { prepareExistingContentModeProject } from "./content-mode-project";
|
||||
|
||||
type ContentModeProjectOptions = {
|
||||
@@ -14,6 +16,107 @@ type ContentModeProjectOptions = {
|
||||
builderToken?: string;
|
||||
};
|
||||
|
||||
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);
|
||||
return page;
|
||||
} catch (error) {
|
||||
await page.close();
|
||||
throw error;
|
||||
}
|
||||
})();
|
||||
apiPages.set(context, page);
|
||||
}
|
||||
return page;
|
||||
};
|
||||
|
||||
const createProjectThroughApi = async ({
|
||||
context,
|
||||
email,
|
||||
title,
|
||||
devPlan,
|
||||
}: {
|
||||
context: BrowserContext;
|
||||
email: string;
|
||||
title: string;
|
||||
devPlan?: string;
|
||||
}) => {
|
||||
if (env.AUTH_SECRET === undefined) {
|
||||
throw new Error("AUTH_SECRET must be set for e2e dev login");
|
||||
}
|
||||
if (devPlan !== undefined) {
|
||||
await context.clearCookies();
|
||||
}
|
||||
const page = await getApiPage(context);
|
||||
await page.evaluate(
|
||||
async ({ email, devPlan, secret }) => {
|
||||
const loginPage = await fetch("/login");
|
||||
if (loginPage.ok === false) {
|
||||
throw new Error(`E2E login check failed with HTTP ${loginPage.status}`);
|
||||
}
|
||||
if (new URL(loginPage.url).pathname === "/login") {
|
||||
const login = await fetch("/auth/dev", {
|
||||
method: "POST",
|
||||
body: new URLSearchParams({ secret, email, devPlan }),
|
||||
});
|
||||
if (login.ok === false) {
|
||||
throw new Error(`E2E dev login failed with HTTP ${login.status}`);
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
email: getWorkerEmail(email),
|
||||
devPlan: devPlan ?? "",
|
||||
secret: env.AUTH_SECRET,
|
||||
}
|
||||
);
|
||||
const csrf = await page.goto(`${dashboardUrl}/dashboard?_data=routes/_ui`, {
|
||||
waitUntil: "commit",
|
||||
});
|
||||
if (csrf === null || csrf.ok() === false) {
|
||||
throw new Error(`E2E CSRF setup failed with HTTP ${csrf?.status()}`);
|
||||
}
|
||||
const { csrfToken } = (await csrf.json()) as { csrfToken?: string };
|
||||
if (csrfToken === undefined || csrfToken === "") {
|
||||
throw new Error("E2E CSRF setup did not return a token");
|
||||
}
|
||||
return await page.evaluate(
|
||||
async ({ title, csrfToken }) => {
|
||||
const project = await fetch("/trpc/dashboardProject.create?batch=1", {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"content-type": "application/json",
|
||||
"x-csrf-token": csrfToken,
|
||||
},
|
||||
body: JSON.stringify({ 0: { title } }),
|
||||
});
|
||||
if (project.ok === false) {
|
||||
throw new Error(
|
||||
`E2E project creation failed with HTTP ${project.status}`
|
||||
);
|
||||
}
|
||||
const result = (await project.json()) as Array<{
|
||||
result?: { data?: { id?: string } };
|
||||
}>;
|
||||
const projectId = result[0]?.result?.data?.id;
|
||||
if (projectId === undefined) {
|
||||
throw new Error("E2E project creation did not return a project ID");
|
||||
}
|
||||
return projectId;
|
||||
},
|
||||
{ title, csrfToken }
|
||||
);
|
||||
};
|
||||
|
||||
export const createContentModeProject = async ({
|
||||
context,
|
||||
email = "content-mode-e2e@webstudio.test",
|
||||
@@ -24,30 +127,18 @@ export const createContentModeProject = async ({
|
||||
editorCanUseApi,
|
||||
builderToken,
|
||||
}: ContentModeProjectOptions) => {
|
||||
const ownerPage = await context.newPage();
|
||||
const projectId = await measure(
|
||||
"content mode fixture login/create project",
|
||||
() => createProjectThroughApi({ context, email, title, devPlan })
|
||||
);
|
||||
|
||||
try {
|
||||
const projectId = await measure(
|
||||
"content mode fixture login/create project",
|
||||
async () =>
|
||||
await loginAndCreateBlankProject({
|
||||
page: ownerPage,
|
||||
email,
|
||||
title,
|
||||
devPlan,
|
||||
})
|
||||
);
|
||||
|
||||
return await measure("content mode fixture prepare project", async () => {
|
||||
return await prepareExistingContentModeProject({
|
||||
projectId,
|
||||
assetNamePrefix,
|
||||
editorToken,
|
||||
editorCanUseApi,
|
||||
builderToken,
|
||||
});
|
||||
return await measure("content mode fixture prepare project", async () => {
|
||||
return await prepareExistingContentModeProject({
|
||||
projectId,
|
||||
assetNamePrefix,
|
||||
editorToken,
|
||||
editorCanUseApi,
|
||||
builderToken,
|
||||
});
|
||||
} finally {
|
||||
await ownerPage.close();
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { SerializedPages } from "@webstudio-is/project-migrations/pages";
|
||||
import type { Instance, Prop } from "@webstudio-is/sdk";
|
||||
import { loadDevBuild } from "../db";
|
||||
@@ -116,7 +117,7 @@ export const createDragProject = async (
|
||||
context,
|
||||
email: `drag-${name}@webstudio.test`,
|
||||
title: `Drag ${name}`,
|
||||
builderToken: `drag-${name}-builder-token`,
|
||||
builderToken: `drag-${name}-${randomUUID()}-builder-token`,
|
||||
createBuildUpdate: (build) => seedBuild(build.pages),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
|
||||
import { expect } from "@playwright/test";
|
||||
@@ -122,6 +123,7 @@ const author = async () => {
|
||||
let stored: ProjectSessionPersistedSnapshot | undefined;
|
||||
let revision = 0;
|
||||
let nextId = 0;
|
||||
const idPrefix = randomUUID();
|
||||
const persist = async () => {
|
||||
const snapshot = createBuilderBuildDataSnapshotFromState(remote.state);
|
||||
build = await updateBuild(build.id, {
|
||||
@@ -141,7 +143,7 @@ const author = async () => {
|
||||
const session = createProjectSession({
|
||||
projectId: projectId,
|
||||
compatibilityVersion: "mcp-preview-form-e2e-v1",
|
||||
runtimeContext: { createId: () => `mcp-preview-${nextId++}` },
|
||||
runtimeContext: { createId: () => `mcp-preview-${idPrefix}-${nextId++}` },
|
||||
storage: {
|
||||
load: async () => stored,
|
||||
save: async (snapshot, options) => {
|
||||
@@ -195,7 +197,7 @@ const author = async () => {
|
||||
state: remote.state,
|
||||
input,
|
||||
context: {
|
||||
createId: () => `mcp-preview-server-${nextId++}`,
|
||||
createId: () => `mcp-preview-server-${idPrefix}-${nextId++}`,
|
||||
projectId: remote.projectId,
|
||||
projectVersion: remote.version,
|
||||
},
|
||||
@@ -206,7 +208,7 @@ const author = async () => {
|
||||
version: remote.version + 1,
|
||||
state: applyBuilderPatchTransactions(remote.state, [
|
||||
{
|
||||
id: `mcp-preview-transaction-${nextId++}`,
|
||||
id: `mcp-preview-transaction-${idPrefix}-${nextId++}`,
|
||||
payload: mutation.payload,
|
||||
},
|
||||
]).state,
|
||||
|
||||
@@ -1,6 +1,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";
|
||||
|
||||
const previewModuleUrl = new URL(
|
||||
"../../../../packages/cli/src/commands/mcp-preview.ts",
|
||||
@@ -13,27 +14,7 @@ const screenshotModuleUrl = new URL(
|
||||
const { createMcpPreviewHandlers } = await import(previewModuleUrl);
|
||||
const { createScreenshotCaptureSession } = await import(screenshotModuleUrl);
|
||||
|
||||
let payload = "";
|
||||
for await (const chunk of process.stdin) {
|
||||
payload += String(chunk);
|
||||
if (payload.length > 8_000_000) {
|
||||
throw new Error("MCP Preview submit fixture input is too large.");
|
||||
}
|
||||
}
|
||||
const request = JSON.parse(payload) as {
|
||||
url: string;
|
||||
input: Record<string, unknown>;
|
||||
};
|
||||
if (
|
||||
typeof request.url !== "string" ||
|
||||
typeof request.input !== "object" ||
|
||||
request.input === null
|
||||
) {
|
||||
throw new Error(
|
||||
"Expected one JSON payload with Preview url and submit input."
|
||||
);
|
||||
}
|
||||
const { url, input } = request;
|
||||
let url = "";
|
||||
|
||||
const previewHandlers = createMcpPreviewHandlers({
|
||||
preview: {
|
||||
@@ -74,16 +55,33 @@ try {
|
||||
server.connect(serverTransport),
|
||||
client.connect(clientTransport),
|
||||
]);
|
||||
const result = await client.callTool({
|
||||
name: "preview.submit-form",
|
||||
arguments: input,
|
||||
});
|
||||
if (result.isError) {
|
||||
throw new Error(
|
||||
`MCP submit failed: ${JSON.stringify(result.structuredContent)}`
|
||||
);
|
||||
for await (const line of createInterface({ input: process.stdin })) {
|
||||
if (line.length > 8_000_000) {
|
||||
throw new Error("MCP Preview submit fixture input is too large.");
|
||||
}
|
||||
const request = JSON.parse(line) as {
|
||||
url: string;
|
||||
input: Record<string, unknown>;
|
||||
};
|
||||
if (
|
||||
typeof request.url !== "string" ||
|
||||
typeof request.input !== "object" ||
|
||||
request.input === null
|
||||
) {
|
||||
throw new Error("Expected Preview url and submit input.");
|
||||
}
|
||||
url = request.url;
|
||||
const result = await client.callTool({
|
||||
name: "preview.submit-form",
|
||||
arguments: request.input,
|
||||
});
|
||||
if (result.isError) {
|
||||
throw new Error(
|
||||
`MCP submit failed: ${JSON.stringify(result.structuredContent)}`
|
||||
);
|
||||
}
|
||||
process.stdout.write(`${JSON.stringify(result.structuredContent)}\n`);
|
||||
}
|
||||
process.stdout.write(`${JSON.stringify(result.structuredContent)}\n`);
|
||||
} finally {
|
||||
await Promise.all([
|
||||
client.close(),
|
||||
|
||||
@@ -110,18 +110,6 @@ export const waitForCanvasTextHidden = async ({
|
||||
});
|
||||
};
|
||||
|
||||
export const dismissBlockingAlerts = async ({ page }: { page: Page }) => {
|
||||
const startedAt = Date.now();
|
||||
while (Date.now() - startedAt < 3_000) {
|
||||
const dismissButton = page.getByRole("button", { name: "Dismiss" });
|
||||
if (await dismissButton.isVisible({ timeout: 500 }).catch(() => false)) {
|
||||
await dismissButton.click();
|
||||
return;
|
||||
}
|
||||
await delay(100);
|
||||
}
|
||||
};
|
||||
|
||||
export const openProjectBuilder = async ({
|
||||
page,
|
||||
projectId,
|
||||
@@ -148,7 +136,9 @@ export const openProjectBuilder = async ({
|
||||
.waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout })
|
||||
.catch(() => undefined);
|
||||
const canvas = await waitForCanvasFrame({ page });
|
||||
await dismissBlockingAlerts({ page });
|
||||
await page
|
||||
.getByRole("progressbar")
|
||||
.waitFor({ state: "hidden", timeout: 30_000 });
|
||||
return canvas;
|
||||
};
|
||||
|
||||
@@ -164,6 +154,8 @@ export const openBuilderUrl = async ({
|
||||
.waitForLoadState("networkidle", { timeout: builderNetworkIdleTimeout })
|
||||
.catch(() => undefined);
|
||||
const canvas = await waitForCanvasFrame({ page });
|
||||
await dismissBlockingAlerts({ page });
|
||||
await page
|
||||
.getByRole("progressbar")
|
||||
.waitFor({ state: "hidden", timeout: 30_000 });
|
||||
return canvas;
|
||||
};
|
||||
@@ -18,7 +18,9 @@ export const dragPointer = async ({
|
||||
page: Page;
|
||||
source: Locator;
|
||||
target: Locator;
|
||||
targetPoint?: (bounds: Bounds) => { x: number; y: number };
|
||||
targetPoint?: (
|
||||
bounds: Bounds
|
||||
) => Promise<{ x: number; y: number }> | { x: number; y: number };
|
||||
ready: () => Promise<boolean>;
|
||||
attempts?: number;
|
||||
beforeAttempt?: () => Promise<void>;
|
||||
@@ -45,7 +47,7 @@ export const dragPointer = async ({
|
||||
if (before === null) {
|
||||
throw new Error("Expected visible drag target");
|
||||
}
|
||||
const to = targetPoint(before);
|
||||
const to = await targetPoint(before);
|
||||
jiggle = jiggle === 0 ? 1 : 0;
|
||||
await page.mouse.move(to.x + jiggle, to.y, { steps: 3 });
|
||||
await page.waitForTimeout(120);
|
||||
@@ -90,10 +92,17 @@ export const dragTreeRow = async (
|
||||
page,
|
||||
source,
|
||||
target,
|
||||
targetPoint: ({ x, y, width, height }) => ({
|
||||
x: x + width / 2,
|
||||
y: y + height * (position === "above" ? 0.1 : 0.5),
|
||||
}),
|
||||
targetPoint: async (bounds) => {
|
||||
const button = await target
|
||||
.locator("[data-tree-button]")
|
||||
.first()
|
||||
.boundingBox();
|
||||
const { x, y, width, height } = button ?? bounds;
|
||||
return {
|
||||
x: x + width / 2,
|
||||
y: y + height * (position === "above" ? 0.1 : 0.5),
|
||||
};
|
||||
},
|
||||
ready: async () =>
|
||||
(await target.getAttribute("data-is-drop-over")) === "true" &&
|
||||
(position === "inside" ||
|
||||
|
||||
@@ -317,15 +317,34 @@ export const expectGeneratedAppNavigation = async ({
|
||||
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();
|
||||
|
||||
@@ -23,14 +23,12 @@ const cliTsconfigPath = fileURLToPath(
|
||||
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
|
||||
);
|
||||
|
||||
export const withGeneratedFormDeliveryPreview = async <Result>({
|
||||
export const startGeneratedFormDeliveryPreview = async ({
|
||||
projectId,
|
||||
receiverPort,
|
||||
callback,
|
||||
}: {
|
||||
projectId: string;
|
||||
receiverPort: number;
|
||||
callback: ({ url }: { url: string }) => Promise<Result>;
|
||||
}) => {
|
||||
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-form-delivery-"));
|
||||
let preview: ChildProcess | undefined;
|
||||
@@ -80,12 +78,45 @@ export const withGeneratedFormDeliveryPreview = async <Result>({
|
||||
url,
|
||||
output: () => output.join(""),
|
||||
});
|
||||
return await callback({ url });
|
||||
} finally {
|
||||
const runningPreview = preview;
|
||||
return {
|
||||
url,
|
||||
close: async () => {
|
||||
try {
|
||||
await stopChildProcess(runningPreview, { killGroup: true });
|
||||
} finally {
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
if (preview !== undefined) {
|
||||
await stopChildProcess(preview, { killGroup: true });
|
||||
await stopChildProcess(preview, { killGroup: true }).catch(
|
||||
() => undefined
|
||||
);
|
||||
}
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
export const withGeneratedFormDeliveryPreview = async <Result>({
|
||||
projectId,
|
||||
receiverPort,
|
||||
callback,
|
||||
}: {
|
||||
projectId: string;
|
||||
receiverPort: number;
|
||||
callback: ({ url }: { url: string }) => Promise<Result>;
|
||||
}) => {
|
||||
const preview = await startGeneratedFormDeliveryPreview({
|
||||
projectId,
|
||||
receiverPort,
|
||||
});
|
||||
try {
|
||||
return await callback({ url: preview.url });
|
||||
} finally {
|
||||
await preview.close();
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,10 +1,14 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { existsSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { createInterface } from "node:readline";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { chromium } from "@playwright/test";
|
||||
import type {
|
||||
ProjectSessionPreviewSubmitFormInput,
|
||||
ProjectSessionPreviewSubmitFormResult,
|
||||
} from "@webstudio-is/project-build/mcp";
|
||||
import { closeChildProcessInput } from "../process";
|
||||
|
||||
const runnerPath = fileURLToPath(
|
||||
new URL("../fixtures/mcp-preview-submit-client.ts", import.meta.url)
|
||||
@@ -17,14 +21,32 @@ const cliTsconfigPath = fileURLToPath(
|
||||
new URL("../../../../packages/cli/tsconfig.local.json", import.meta.url)
|
||||
);
|
||||
|
||||
/** One JSON payload goes over stdin so base64 files are not limited by argv size. */
|
||||
export const submitPreviewFormViaMcp = async ({
|
||||
url,
|
||||
input,
|
||||
}: {
|
||||
const getMcpBrowserPath = () => {
|
||||
const chromiumPath = chromium.executablePath();
|
||||
const match = chromiumPath.match(/^(.*)[\\/]chromium-(\d+)[\\/]/);
|
||||
if (match === null) {
|
||||
return chromiumPath;
|
||||
}
|
||||
const [, cacheDir, revision] = match;
|
||||
const shellPath = join(
|
||||
cacheDir,
|
||||
`chromium_headless_shell-${revision}`,
|
||||
process.platform === "darwin"
|
||||
? "chrome-mac"
|
||||
: process.platform === "win32"
|
||||
? "chrome-win"
|
||||
: "chrome-linux",
|
||||
process.platform === "win32" ? "headless_shell.exe" : "headless_shell"
|
||||
);
|
||||
return existsSync(shellPath) ? shellPath : chromiumPath;
|
||||
};
|
||||
|
||||
type SubmitRequest = {
|
||||
url: string;
|
||||
input: ProjectSessionPreviewSubmitFormInput;
|
||||
}): Promise<{ ok: true; data: ProjectSessionPreviewSubmitFormResult }> => {
|
||||
};
|
||||
|
||||
const startClient = () => {
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
@@ -40,48 +62,103 @@ export const submitPreviewFormViaMcp = async ({
|
||||
env: {
|
||||
...process.env,
|
||||
TSX_TSCONFIG_PATH: cliTsconfigPath,
|
||||
WEBSTUDIO_BROWSER_PATH: chromium.executablePath(),
|
||||
WEBSTUDIO_BROWSER_PATH: getMcpBrowserPath(),
|
||||
},
|
||||
}
|
||||
);
|
||||
let stdout = "";
|
||||
const lines = createInterface({ input: child.stdout });
|
||||
let stderr = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
stderr += chunk;
|
||||
stderr = (stderr + chunk).slice(-4000);
|
||||
});
|
||||
const timeout = setTimeout(() => child.kill("SIGTERM"), 90_000);
|
||||
const stopOnParentExit = () => child.kill("SIGTERM");
|
||||
process.once("exit", stopOnParentExit);
|
||||
child.once("close", () => {
|
||||
process.off("exit", stopOnParentExit);
|
||||
if (client?.child === child) {
|
||||
client = undefined;
|
||||
}
|
||||
});
|
||||
return { child, lines, stderr: () => stderr };
|
||||
};
|
||||
|
||||
let client: ReturnType<typeof startClient> | undefined;
|
||||
let queue = Promise.resolve();
|
||||
|
||||
export const closePreviewFormMcpClient = async () => {
|
||||
await queue;
|
||||
const activeClient = client;
|
||||
if (activeClient !== undefined) {
|
||||
await closeChildProcessInput(activeClient.child);
|
||||
client = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const submit = async ({ url, input }: SubmitRequest) => {
|
||||
const activeClient = (client ??= startClient());
|
||||
const { child, lines } = activeClient;
|
||||
let timeout: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
child.stdin.end(JSON.stringify({ url, input }));
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("close", (code) => {
|
||||
if (code === 0) {
|
||||
resolve();
|
||||
} else {
|
||||
reject(
|
||||
new Error(
|
||||
`MCP Preview submit fixture exited ${code}: ${stderr.slice(-4000)}`
|
||||
)
|
||||
);
|
||||
const stdout = await new Promise<string>((resolve, reject) => {
|
||||
const onLine = (line: string) => {
|
||||
cleanup();
|
||||
resolve(line);
|
||||
};
|
||||
const onClose = (code: number | null) => {
|
||||
cleanup();
|
||||
reject(
|
||||
new Error(
|
||||
`MCP Preview submit fixture exited ${code}: ${activeClient.stderr()}`
|
||||
)
|
||||
);
|
||||
};
|
||||
const onError = (error: Error) => {
|
||||
cleanup();
|
||||
reject(error);
|
||||
};
|
||||
const cleanup = () => {
|
||||
lines.off("line", onLine);
|
||||
child.off("close", onClose);
|
||||
child.off("error", onError);
|
||||
};
|
||||
lines.once("line", onLine);
|
||||
child.once("close", onClose);
|
||||
child.once("error", onError);
|
||||
timeout = setTimeout(() => {
|
||||
child.kill("SIGTERM");
|
||||
}, 90_000);
|
||||
child.stdin.write(`${JSON.stringify({ url, input })}\n`, (error) => {
|
||||
if (error !== null && error !== undefined) {
|
||||
onError(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
const result = JSON.parse(stdout) as {
|
||||
ok?: boolean;
|
||||
data?: ProjectSessionPreviewSubmitFormResult;
|
||||
};
|
||||
if (result.ok !== true || result.data === undefined) {
|
||||
throw new Error(
|
||||
`MCP Preview submit returned an invalid result: ${stdout.slice(-4000)}`
|
||||
);
|
||||
}
|
||||
return { ok: true as const, data: result.data };
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
if (timeout !== undefined) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
const result = JSON.parse(stdout) as {
|
||||
ok?: boolean;
|
||||
data?: ProjectSessionPreviewSubmitFormResult;
|
||||
};
|
||||
if (result.ok !== true || result.data === undefined) {
|
||||
throw new Error(
|
||||
`MCP Preview submit returned an invalid result: ${stdout.slice(-4000)}`
|
||||
);
|
||||
}
|
||||
return { ok: true, data: result.data };
|
||||
};
|
||||
|
||||
/** Keep the real MCP server and browser session across submissions in one worker. */
|
||||
export const submitPreviewFormViaMcp = (
|
||||
request: SubmitRequest
|
||||
): Promise<{ ok: true; data: ProjectSessionPreviewSubmitFormResult }> => {
|
||||
const result = queue.then(() => submit(request));
|
||||
queue = result.then(
|
||||
() => undefined,
|
||||
() => undefined
|
||||
);
|
||||
return result;
|
||||
};
|
||||
@@ -0,0 +1,89 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
samples="$(mktemp)"
|
||||
trap 'rm -f "$samples"' EXIT
|
||||
|
||||
read_metric() {
|
||||
local file="$1"
|
||||
local key="$2"
|
||||
if [ -r "$file" ]; then
|
||||
awk -v key="$key" '$1 == key { print $2; exit }' "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
read_pressure() {
|
||||
local file="$1"
|
||||
if [ -r "$file" ]; then
|
||||
awk '$1 == "some" { for (i = 2; i <= NF; i++) if ($i ~ /^total=/) { sub(/^total=/, "", $i); print $i; exit } }' "$file"
|
||||
fi
|
||||
}
|
||||
|
||||
sample() {
|
||||
local cpu_usage cpu_pressure memory_usage memory_pressure oom
|
||||
cpu_usage="$(read_metric /sys/fs/cgroup/cpu.stat usage_usec)"
|
||||
cpu_pressure="$(read_pressure /sys/fs/cgroup/cpu.pressure)"
|
||||
memory_usage="$(cat /sys/fs/cgroup/memory.current 2>/dev/null || true)"
|
||||
memory_pressure="$(read_pressure /sys/fs/cgroup/memory.pressure)"
|
||||
oom="$(read_metric /sys/fs/cgroup/memory.events oom)"
|
||||
printf '%s\t%s\t%s\t%s\t%s\t%s\n' \
|
||||
"$(date +%s%N)" "$cpu_usage" "$cpu_pressure" \
|
||||
"$memory_usage" "$memory_pressure" "$oom" >> "$samples"
|
||||
}
|
||||
|
||||
printf '[e2e:resources] logical_cpus=%s cpu_quota=%s memory_limit=%s\n' \
|
||||
"$(nproc 2>/dev/null || true)" \
|
||||
"$(cat /sys/fs/cgroup/cpu.max 2>/dev/null || true)" \
|
||||
"$(cat /sys/fs/cgroup/memory.max 2>/dev/null || true)"
|
||||
|
||||
sample
|
||||
(
|
||||
while true; do
|
||||
sleep 2
|
||||
sample
|
||||
done
|
||||
) &
|
||||
sampler_pid=$!
|
||||
|
||||
if "$@"; then
|
||||
result=0
|
||||
else
|
||||
result=$?
|
||||
fi
|
||||
|
||||
kill "$sampler_pid" 2>/dev/null || true
|
||||
wait "$sampler_pid" 2>/dev/null || true
|
||||
sample
|
||||
|
||||
python3 - "$samples" <<'PY'
|
||||
import sys
|
||||
|
||||
rows = []
|
||||
for line in open(sys.argv[1]):
|
||||
values = line.rstrip("\n").split("\t")
|
||||
if len(values) != 6:
|
||||
continue
|
||||
rows.append([int(value) if value.isdigit() else None for value in values])
|
||||
|
||||
if len(rows) >= 2:
|
||||
elapsed = (rows[-1][0] - rows[0][0]) / 1_000_000_000
|
||||
def delta(index):
|
||||
first, last = rows[0][index], rows[-1][index]
|
||||
return None if first is None or last is None else last - first
|
||||
def pressure(index):
|
||||
change = delta(index)
|
||||
return "unavailable" if change is None else f"{change / 10_000 / elapsed:.1f}%"
|
||||
cpu = delta(1)
|
||||
memory = [row[3] for row in rows if row[3] is not None]
|
||||
print(
|
||||
"[e2e:resources] "
|
||||
f"elapsed={elapsed:.1f}s "
|
||||
f"cpu_cores_avg={'unavailable' if cpu is None else f'{cpu / 1_000_000 / elapsed:.2f}'} "
|
||||
f"cpu_pressure={pressure(2)} "
|
||||
f"memory_peak_gib={'unavailable' if not memory else f'{max(memory) / 2**30:.2f}'} "
|
||||
f"memory_pressure={pressure(4)} "
|
||||
f"oom_events={delta(5)}"
|
||||
)
|
||||
PY
|
||||
|
||||
exit "$result"
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import { stopChildProcess } from "./process";
|
||||
import { closeChildProcessInput, stopChildProcess } from "./process";
|
||||
|
||||
const createChild = () => {
|
||||
const child = new EventEmitter() as ChildProcess;
|
||||
@@ -30,6 +30,41 @@ test("stops a child gracefully without escalating", async () => {
|
||||
expect(child.kill).toHaveBeenCalledWith("SIGTERM");
|
||||
});
|
||||
|
||||
test("closes child input and waits for cleanup", async () => {
|
||||
const child = createChild();
|
||||
const end = vi.fn(() => {
|
||||
queueMicrotask(() => {
|
||||
Object.defineProperty(child, "exitCode", { value: 0, writable: true });
|
||||
child.emit("close", 0, null);
|
||||
});
|
||||
});
|
||||
Object.defineProperty(child, "stdin", { value: { end } });
|
||||
|
||||
await closeChildProcessInput(child, 10);
|
||||
|
||||
expect(end).toHaveBeenCalledOnce();
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("forces a child to stop if closing input stalls", async () => {
|
||||
const child = createChild();
|
||||
const end = vi.fn();
|
||||
Object.defineProperty(child, "stdin", { value: { end } });
|
||||
vi.mocked(child.kill).mockImplementation((signal) => {
|
||||
Object.defineProperty(child, "signalCode", {
|
||||
value: signal,
|
||||
writable: true,
|
||||
});
|
||||
child.emit("close", null, signal);
|
||||
return true;
|
||||
});
|
||||
|
||||
await closeChildProcessInput(child, 1);
|
||||
|
||||
expect(end).toHaveBeenCalledOnce();
|
||||
expect(child.kill).toHaveBeenCalledWith("SIGTERM");
|
||||
});
|
||||
|
||||
test("escalates a child that ignores SIGTERM", async () => {
|
||||
const child = createChild();
|
||||
vi.mocked(child.kill).mockImplementation((signal) => {
|
||||
@@ -72,3 +72,31 @@ export const stopChildProcess = async (
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const closeChildProcessInput = async (
|
||||
child: ChildProcess,
|
||||
timeoutMs = 5_000
|
||||
) => {
|
||||
if (hasExited(child)) {
|
||||
return;
|
||||
}
|
||||
const stdin = child.stdin;
|
||||
if (stdin === null) {
|
||||
throw new Error("Child process stdin is unavailable");
|
||||
}
|
||||
const closed = new Promise<boolean>((resolve) => {
|
||||
const onClose = () => {
|
||||
clearTimeout(timer);
|
||||
resolve(true);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
child.off("close", onClose);
|
||||
resolve(false);
|
||||
}, timeoutMs);
|
||||
child.once("close", onClose);
|
||||
});
|
||||
stdin.end();
|
||||
if ((await closed) === false) {
|
||||
await stopChildProcess(child, { timeoutMs: 1_000 });
|
||||
}
|
||||
};
|
||||
@@ -137,13 +137,15 @@ install_playwright_chromium() {
|
||||
|
||||
build_e2e_apps() {
|
||||
pnpm --dir "$ROOT_DIR" e2e:builder:build
|
||||
pnpm --dir "$ROOT_DIR" --filter=@webstudio-is/sdk-components-react-router build
|
||||
}
|
||||
|
||||
verify_e2e_apps_built() {
|
||||
local builder_server="$ROOT_DIR/apps/builder/build/server"
|
||||
local builder_assets="$ROOT_DIR/apps/builder/build/client/assets"
|
||||
local router_components="$ROOT_DIR/packages/sdk-components-react-router/lib/components.js"
|
||||
|
||||
if [ ! -d "$builder_server" ] || [ ! -d "$builder_assets" ]; then
|
||||
if [ ! -d "$builder_server" ] || [ ! -d "$builder_assets" ] || [ ! -f "$router_components" ]; then
|
||||
echo "E2E_SKIP_BUILDER_BUILD requires prebuilt Builder artifacts" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
@@ -54,7 +54,17 @@ export const withBrowserContext = async <Result>(
|
||||
}
|
||||
};
|
||||
|
||||
export const test = base;
|
||||
export const test = base.extend<{}, { mcpClientCleanup: void }>({
|
||||
mcpClientCleanup: [
|
||||
async ({}, use) => {
|
||||
await use();
|
||||
const { closePreviewFormMcpClient } =
|
||||
await import("./flows/mcp-preview-submit");
|
||||
await closePreviewFormMcpClient();
|
||||
},
|
||||
{ scope: "worker", auto: true },
|
||||
],
|
||||
});
|
||||
|
||||
export const newIsolatedPage = async (browser: Browser) => {
|
||||
const context = await newBrowserContext(browser);
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
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,
|
||||
}) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
createAssetFolder,
|
||||
deleteSelectedAsset,
|
||||
@@ -32,17 +33,21 @@ import {
|
||||
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 { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
import { e2ePaidPlanName } from "../plans";
|
||||
import { loadDevBuild } from "../db";
|
||||
|
||||
let fixture: SeededContentModeProject;
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
fixture = await withBrowserContext(browser, (context) =>
|
||||
createContentModeProject({ context, devPlan: e2ePaidPlanName })
|
||||
);
|
||||
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,
|
||||
@@ -416,18 +421,7 @@ test("Editor can replace image source with asset in content mode", async ({
|
||||
|
||||
test("Builder copy/paste preserves image asset references after reload", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
const fixture = await createContentModeProject({
|
||||
context: context,
|
||||
devPlan: e2ePaidPlanName,
|
||||
email: "asset-copy-e2e@webstudio.test",
|
||||
title: "Asset Copy E2E",
|
||||
assetNamePrefix: "asset-copy-",
|
||||
editorToken: "asset-copy-e2e-editor-token",
|
||||
builderToken: "asset-copy-e2e-builder-token",
|
||||
});
|
||||
|
||||
const getImageAssetReferenceCount = async () => {
|
||||
const build = await loadDevBuild({ projectId: fixture.projectId });
|
||||
const props = JSON.parse(build.props) as Array<{
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { test } from "../test";
|
||||
|
||||
test("content-mode project setup works without Node-side dashboard requests", async ({
|
||||
context,
|
||||
}) => {
|
||||
const request = context.request;
|
||||
const get = request.get;
|
||||
Object.defineProperty(request, "get", {
|
||||
configurable: true,
|
||||
value: () => {
|
||||
throw new Error("Node-side dashboard request is unavailable");
|
||||
},
|
||||
});
|
||||
try {
|
||||
const first = await createContentModeProject({ context });
|
||||
const second = await createContentModeProject({ context });
|
||||
expect(first.projectId).toBeTruthy();
|
||||
expect(second.projectId).not.toBe(first.projectId);
|
||||
} finally {
|
||||
Object.defineProperty(request, "get", { value: get });
|
||||
}
|
||||
});
|
||||
+10
-5
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { openProjectBuilder, waitForCanvasText } from "../flows/builder";
|
||||
import { selectCanvasTextInstance } from "../flows/canvas-selection";
|
||||
import { expectLocatorHidden } from "../flows/assertions";
|
||||
@@ -19,16 +20,20 @@ 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, withBrowserContext } from "../test";
|
||||
import { newIsolatedPage, test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
import { e2ePaidPlanName } from "../plans";
|
||||
|
||||
let fixture: SeededContentModeProject;
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
fixture = await withBrowserContext(browser, (context) =>
|
||||
createContentModeProject({ context, devPlan: e2ePaidPlanName })
|
||||
);
|
||||
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,
|
||||
File renamed without changes.
@@ -18,6 +18,8 @@ import { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
import { loadDevBuild } from "../db";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
type DataSourceRecord =
|
||||
| {
|
||||
id: string;
|
||||
|
||||
+41
-22
@@ -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 } from "../flows/builder";
|
||||
@@ -13,7 +13,6 @@ import { insertAuthorizationToken, 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)
|
||||
);
|
||||
@@ -47,6 +46,30 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
viewer: viewerDirectory,
|
||||
builder: builderDirectory,
|
||||
};
|
||||
const clients = new Map<keyof typeof directories, Client>();
|
||||
const connect = async (cwd: string, configDirectory: string) => {
|
||||
const client = new Client({
|
||||
name: "mcp-editor-pages-e2e",
|
||||
version: "1.0.0",
|
||||
});
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [cliPath, "mcp", "--project", fixture.projectId],
|
||||
cwd,
|
||||
env: {
|
||||
...process.env,
|
||||
WEBSTUDIO_CONFIG_DIR: configDirectory,
|
||||
} as Record<string, string>,
|
||||
stderr: "inherit",
|
||||
});
|
||||
try {
|
||||
await client.connect(transport);
|
||||
} catch (error) {
|
||||
await client.close().catch(() => undefined);
|
||||
throw error;
|
||||
}
|
||||
return client;
|
||||
};
|
||||
const call = async (
|
||||
tool: string,
|
||||
input: object,
|
||||
@@ -55,28 +78,23 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
role = "editor",
|
||||
}: { fresh?: boolean; role?: keyof typeof directories } = {}
|
||||
) => {
|
||||
const args = [
|
||||
cliPath,
|
||||
"mcp",
|
||||
"single-op-call",
|
||||
tool,
|
||||
JSON.stringify(input),
|
||||
"--project",
|
||||
fixture.projectId,
|
||||
];
|
||||
const client = fresh
|
||||
? await connect(freshDirectory, directories[role])
|
||||
: (clients.get(role) ??
|
||||
(await connect(directories[role], directories[role])));
|
||||
if (fresh === false) {
|
||||
clients.set(role, client);
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execFileAsync(process.execPath, args, {
|
||||
cwd: fresh ? freshDirectory : directories[role],
|
||||
timeout: 60_000,
|
||||
env: { ...process.env, WEBSTUDIO_CONFIG_DIR: directories[role] },
|
||||
const result = await client.callTool({
|
||||
name: tool,
|
||||
arguments: input as Record<string, unknown>,
|
||||
});
|
||||
return JSON.parse(stdout);
|
||||
} catch (error) {
|
||||
const stdout = (error as Error & { stdout?: string }).stdout;
|
||||
if (stdout === undefined) {
|
||||
throw error;
|
||||
return JSON.parse(JSON.stringify(result.structuredContent));
|
||||
} finally {
|
||||
if (fresh) {
|
||||
await client.close();
|
||||
}
|
||||
return JSON.parse(stdout);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -254,6 +272,7 @@ test("Editor MCP saves permitted pages, folders, and assets", async ({
|
||||
const builderPage = await call("get-page", { pageId }, { role: "builder" });
|
||||
expect(builderPage.data.meta.status).toBe("302");
|
||||
} finally {
|
||||
await Promise.all(Array.from(clients.values(), (client) => client.close()));
|
||||
await Promise.all([
|
||||
rm(directory, { recursive: true, force: true }),
|
||||
rm(freshDirectory, { recursive: true, force: true }),
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -5,10 +5,12 @@ import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import {
|
||||
startFormDeliveryReceiver,
|
||||
withGeneratedFormDeliveryPreview,
|
||||
startGeneratedFormDeliveryPreview,
|
||||
} from "../flows/generated-form-delivery";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
import { test, withBrowserContext } from "../test";
|
||||
|
||||
test.describe.configure({ mode: "default" });
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const authorPath = fileURLToPath(
|
||||
@@ -26,17 +28,25 @@ const formats = [
|
||||
["format-text", "text/plain"],
|
||||
] as const;
|
||||
|
||||
for (const [mode, contentType] of formats) {
|
||||
test(`MCP-authored Form sends HTTP body with ${mode}`, async ({
|
||||
context,
|
||||
}) => {
|
||||
const formIds = new Map<(typeof formats)[number][0], string>();
|
||||
let receiver: Awaited<ReturnType<typeof startFormDeliveryReceiver>> | undefined;
|
||||
let preview:
|
||||
| Awaited<ReturnType<typeof startGeneratedFormDeliveryPreview>>
|
||||
| undefined;
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
const projectId = await withBrowserContext(browser, async (context) => {
|
||||
const fixture = await createContentModeProject({
|
||||
context,
|
||||
email: `mcp-${mode}@webstudio.test`,
|
||||
title: `MCP HTTP ${mode}`,
|
||||
assetNamePrefix: `mcp-${mode}-`,
|
||||
builderToken: `mcp-${mode}-builder-token`,
|
||||
email: "mcp-http-formats@webstudio.test",
|
||||
title: "MCP HTTP body formats",
|
||||
assetNamePrefix: "mcp-http-formats-",
|
||||
builderToken: "mcp-http-formats-builder-token",
|
||||
});
|
||||
return fixture.projectId;
|
||||
});
|
||||
|
||||
for (const [mode] of formats) {
|
||||
const { stdout } = await execFileAsync(
|
||||
process.execPath,
|
||||
[
|
||||
@@ -46,7 +56,7 @@ for (const [mode, contentType] of formats) {
|
||||
reactGlobalPath,
|
||||
"--conditions=webstudio",
|
||||
authorPath,
|
||||
fixture.projectId,
|
||||
projectId,
|
||||
mode,
|
||||
],
|
||||
{
|
||||
@@ -55,83 +65,109 @@ for (const [mode, contentType] of formats) {
|
||||
}
|
||||
);
|
||||
const { formId } = JSON.parse(stdout) as { formId: string };
|
||||
const receiver = await startFormDeliveryReceiver();
|
||||
try {
|
||||
await withGeneratedFormDeliveryPreview({
|
||||
projectId: fixture.projectId,
|
||||
receiverPort: receiver.port,
|
||||
callback: async ({ url }) => {
|
||||
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: "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 }),
|
||||
]);
|
||||
expect(receiver.deliveries).toHaveLength(1);
|
||||
const delivery = receiver.deliveries[0];
|
||||
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");
|
||||
}
|
||||
formIds.set(mode, formId);
|
||||
}
|
||||
|
||||
receiver = await startFormDeliveryReceiver();
|
||||
try {
|
||||
preview = await startGeneratedFormDeliveryPreview({
|
||||
projectId,
|
||||
receiverPort: receiver.port,
|
||||
});
|
||||
} catch (error) {
|
||||
await receiver.close();
|
||||
receiver = undefined;
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
await preview?.close();
|
||||
} finally {
|
||||
await receiver?.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",
|
||||
});
|
||||
} finally {
|
||||
await receiver.close();
|
||||
} 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");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -101,7 +101,7 @@ test("MCP-edited saved deprecated Webhook Form action uses current dynamic route
|
||||
selector: "#legacy-route-form",
|
||||
values: [{ name: "message", value: "Current route" }],
|
||||
submitter: 'button[type="submit"]',
|
||||
timeout: 10_000,
|
||||
timeout: 30_000,
|
||||
},
|
||||
});
|
||||
expect(submission.ok).toBe(true);
|
||||
|
||||
@@ -19,6 +19,8 @@ const reactGlobalPath = fileURLToPath(
|
||||
new URL("../../../../scripts/register-react-global.ts", import.meta.url)
|
||||
);
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
test("MCP-authored Form uses query navigation when no Actions are connected", async ({
|
||||
page,
|
||||
context,
|
||||
|
||||
File renamed without changes.
+9
-2
@@ -5,7 +5,10 @@ import { promisify } from "node:util";
|
||||
import { expect } from "@playwright/test";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { withGeneratedPreview } from "../flows/generated-app";
|
||||
import { submitPreviewFormViaMcp } from "../flows/mcp-preview-submit";
|
||||
import {
|
||||
closePreviewFormMcpClient,
|
||||
submitPreviewFormViaMcp,
|
||||
} from "../flows/mcp-preview-submit";
|
||||
import { test } from "../test";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
@@ -138,6 +141,10 @@ test("MCP-authored native GET form submits repeated fields to a local receiver",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
try {
|
||||
await closePreviewFormMcpClient();
|
||||
} finally {
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
}
|
||||
});
|
||||
File renamed without changes.
+4
-10
@@ -4,10 +4,7 @@ import {
|
||||
openBuilderUrl,
|
||||
waitForCanvasFrame,
|
||||
} from "../flows/builder";
|
||||
import {
|
||||
expectGeneratedAppNavigation,
|
||||
expectGeneratedAppToRender,
|
||||
} from "../flows/generated-app";
|
||||
import { expectGeneratedAppNavigation } from "../flows/generated-app";
|
||||
import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { insertAuthorizationToken, loadDevBuild, updateBuild } from "../db";
|
||||
import { getProjectBuilderUrl, test, withBrowserContext } from "../test";
|
||||
@@ -417,18 +414,15 @@ test("Preview links expose current page state for components and element anchors
|
||||
test("Generated preview renders and navigates linked routes", async ({
|
||||
page,
|
||||
}) => {
|
||||
// Each assertion starts and compiles a separate production preview.
|
||||
// Preview compilation is part of this test's production route coverage.
|
||||
test.setTimeout(300_000);
|
||||
|
||||
await expectGeneratedAppToRender({
|
||||
projectId: fixture.projectId,
|
||||
path: "/my-page",
|
||||
expectedText: previewLinkText.pageLink,
|
||||
});
|
||||
await expectGeneratedAppNavigation({
|
||||
projectId: fixture.projectId,
|
||||
page,
|
||||
linkText: previewLinkText.pageLink,
|
||||
targetPath: "/my-page",
|
||||
renderPath: "/my-page",
|
||||
expectedRenderedText: previewLinkText.pageLink,
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import { createContentModeProject } from "../fixtures/content-mode-suite";
|
||||
import { getCanvasFrame, waitForCanvasFrame } from "../flows/builder";
|
||||
import { getProjectBuilderUrl, test } from "../test";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
test("Preview Form posts to the authenticated Builder and sets error state without publishing", async ({
|
||||
page,
|
||||
context,
|
||||
|
||||
@@ -22,6 +22,8 @@ import { e2eEmailPlanName } from "../plans";
|
||||
import { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
type PersistedPages = {
|
||||
redirects?: Array<{
|
||||
old: string;
|
||||
|
||||
File renamed without changes.
+28
-78
@@ -1,3 +1,4 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import type { Frame, Page } from "@playwright/test";
|
||||
import {
|
||||
getCanvasInstance,
|
||||
@@ -10,18 +11,12 @@ import {
|
||||
createSlotKeyboardProject,
|
||||
type SeededSlotKeyboardProject,
|
||||
} from "../fixtures/slot-keyboard-project";
|
||||
import { test, withBrowserContext } from "../test";
|
||||
import { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
let fixture: SeededSlotKeyboardProject;
|
||||
let detachFixture: SeededSlotKeyboardProject;
|
||||
let navigatorFixture: SeededSlotKeyboardProject;
|
||||
let navigatorOutdentFixture: SeededSlotKeyboardProject;
|
||||
let topChildFixture: SeededSlotKeyboardProject;
|
||||
let bottomChildFixture: SeededSlotKeyboardProject;
|
||||
let navigatorTopChildFixture: SeededSlotKeyboardProject;
|
||||
let navigatorBottomChildFixture: SeededSlotKeyboardProject;
|
||||
let multiSelectFixture: SeededSlotKeyboardProject;
|
||||
|
||||
const slotASelector = getCanvasInstanceSelector([
|
||||
"slot-keyboard-slot-a",
|
||||
@@ -42,57 +37,12 @@ const expectCanvasInstanceVisible = async ({
|
||||
});
|
||||
};
|
||||
|
||||
test.beforeAll(async ({ browser }) => {
|
||||
await withBrowserContext(browser, async (context) => {
|
||||
fixture = await createSlotKeyboardProject({ context });
|
||||
detachFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-detach-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Detach E2E",
|
||||
builderToken: "slot-keyboard-detach-e2e-builder-token",
|
||||
});
|
||||
navigatorFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-navigator-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Navigator E2E",
|
||||
builderToken: "slot-keyboard-navigator-e2e-builder-token",
|
||||
});
|
||||
navigatorOutdentFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-navigator-outdent-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Navigator Outdent E2E",
|
||||
builderToken: "slot-keyboard-navigator-outdent-e2e-builder-token",
|
||||
});
|
||||
topChildFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-top-child-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Top Child E2E",
|
||||
builderToken: "slot-keyboard-top-child-e2e-builder-token",
|
||||
});
|
||||
bottomChildFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-bottom-child-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Bottom Child E2E",
|
||||
builderToken: "slot-keyboard-bottom-child-e2e-builder-token",
|
||||
});
|
||||
navigatorTopChildFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-navigator-top-child-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Navigator Top Child E2E",
|
||||
builderToken: "slot-keyboard-navigator-top-child-e2e-builder-token",
|
||||
});
|
||||
navigatorBottomChildFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-navigator-bottom-child-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Navigator Bottom Child E2E",
|
||||
builderToken: "slot-keyboard-navigator-bottom-child-e2e-builder-token",
|
||||
});
|
||||
multiSelectFixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: "slot-keyboard-navigator-multi-select-e2e@webstudio.test",
|
||||
title: "Slot Keyboard Multi Select E2E",
|
||||
builderToken: "slot-keyboard-navigator-multi-select-e2e-builder-token",
|
||||
});
|
||||
test.beforeEach(async ({ context }) => {
|
||||
const id = randomUUID();
|
||||
fixture = await createSlotKeyboardProject({
|
||||
context,
|
||||
email: `slot-keyboard-${id}@webstudio.test`,
|
||||
builderToken: `slot-keyboard-${id}-builder-token`,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -238,8 +188,8 @@ test("Keyboard shortcut keeps Navigator arrows working after outdenting a row",
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: navigatorOutdentFixture.projectId,
|
||||
authToken: navigatorOutdentFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -288,8 +238,8 @@ test("Shift+ArrowDown in Navigator selects exactly one additional row", async ({
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: multiSelectFixture.projectId,
|
||||
authToken: multiSelectFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -334,8 +284,8 @@ test("Control/Command+A after canvas selection selects sibling rows", async ({
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: multiSelectFixture.projectId,
|
||||
authToken: multiSelectFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -376,8 +326,8 @@ test("Keyboard shortcut moves a direct shared slot child out of all slot occurre
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: detachFixture.projectId,
|
||||
authToken: detachFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -434,8 +384,8 @@ test("Keyboard shortcut moves the first shared slot child above all slot occurre
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: navigatorTopChildFixture.projectId,
|
||||
authToken: navigatorTopChildFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -509,8 +459,8 @@ test("Keyboard shortcut moves the last shared slot child below all slot occurren
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: navigatorBottomChildFixture.projectId,
|
||||
authToken: navigatorBottomChildFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -584,8 +534,8 @@ test("Keyboard shortcut reorders a shared slot child from navigator focus", asyn
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: navigatorFixture.projectId,
|
||||
authToken: navigatorFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -648,8 +598,8 @@ test("Keyboard shortcut moves the first shared slot child above all slot occurre
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: topChildFixture.projectId,
|
||||
authToken: topChildFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -721,8 +671,8 @@ test("Keyboard shortcut moves the last shared slot child below all slot occurren
|
||||
async () => {
|
||||
return await openProjectBuilder({
|
||||
page,
|
||||
projectId: bottomChildFixture.projectId,
|
||||
authToken: bottomChildFixture.builderToken,
|
||||
projectId: fixture.projectId,
|
||||
authToken: fixture.builderToken,
|
||||
});
|
||||
}
|
||||
);
|
||||
@@ -14,6 +14,8 @@ import { test } from "../test";
|
||||
import { measure } from "../perf";
|
||||
import { loadDevBuild } from "../db";
|
||||
|
||||
test.describe.configure({ mode: "parallel" });
|
||||
|
||||
const createStylePanelRuntimeProject = async (
|
||||
context: BrowserContext,
|
||||
name: string
|
||||
|
||||
@@ -47,7 +47,7 @@ export default defineConfig({
|
||||
url: builderUrl,
|
||||
reuseExistingServer: false,
|
||||
ignoreHTTPSErrors: true,
|
||||
timeout: 60_000,
|
||||
timeout: 120_000,
|
||||
stdout: "pipe",
|
||||
stderr: "pipe",
|
||||
}
|
||||
|
||||
@@ -947,6 +947,9 @@ const createManagedFormSocket = ({
|
||||
bodyDelay = 0,
|
||||
unreadable = false,
|
||||
navigationGap = false,
|
||||
fastRedirect = false,
|
||||
interceptedBodyUnreadable = false,
|
||||
interceptedChild = false,
|
||||
unrelated,
|
||||
}: {
|
||||
body?: string;
|
||||
@@ -954,6 +957,9 @@ const createManagedFormSocket = ({
|
||||
bodyDelay?: number;
|
||||
unreadable?: boolean;
|
||||
navigationGap?: boolean | "stalled";
|
||||
fastRedirect?: boolean;
|
||||
interceptedBodyUnreadable?: boolean;
|
||||
interceptedChild?: boolean;
|
||||
unrelated?: { method: string; url: string; frameId: string };
|
||||
} = {}) => {
|
||||
const url = "http://127.0.0.1:5173/contact";
|
||||
@@ -967,6 +973,8 @@ const createManagedFormSocket = ({
|
||||
reads: [] as string[],
|
||||
lateReads: 0,
|
||||
gaps: 0,
|
||||
interceptedReads: 0,
|
||||
continuedResponses: 0,
|
||||
};
|
||||
const emit = (method: string, params: unknown) =>
|
||||
socket.emit("message", { data: JSON.stringify({ method, params }) });
|
||||
@@ -996,6 +1004,41 @@ const createManagedFormSocket = ({
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message.method === "Fetch.getResponseBody") {
|
||||
counters.interceptedReads += 1;
|
||||
setTimeout(
|
||||
() =>
|
||||
socket.emit("message", {
|
||||
data: JSON.stringify({
|
||||
id: message.id,
|
||||
...(interceptedBodyUnreadable
|
||||
? { error: { code: -32000, message: "Body unavailable" } }
|
||||
: {
|
||||
result: {
|
||||
body:
|
||||
message.params?.requestId === "intercepted-child"
|
||||
? JSON.stringify({ results: [{ status: 418 }] })
|
||||
: body,
|
||||
base64Encoded,
|
||||
},
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
0
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (message.method === "Fetch.continueResponse") {
|
||||
counters.continuedResponses += 1;
|
||||
send(data);
|
||||
setTimeout(() => {
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
}, 0);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
navigationGap &&
|
||||
message.method === "Runtime.evaluate" &&
|
||||
@@ -1069,11 +1112,44 @@ const createManagedFormSocket = ({
|
||||
});
|
||||
emit("Network.loadingFinished", { requestId: "unrelated" });
|
||||
}
|
||||
emit("Network.loadingFinished", { requestId: "managed" });
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
if (fastRedirect) {
|
||||
emit("Fetch.requestPaused", {
|
||||
requestId: "intercepted-managed",
|
||||
networkId: "managed",
|
||||
frameId: "main",
|
||||
responseStatusCode: 200,
|
||||
request: {
|
||||
method: "POST",
|
||||
url: "http://127.0.0.1:5173/__ws-form/contact",
|
||||
},
|
||||
});
|
||||
if (interceptedChild) {
|
||||
emit("Network.requestWillBeSent", {
|
||||
requestId: "child",
|
||||
frameId: "child",
|
||||
request: {
|
||||
method: "POST",
|
||||
url: "http://127.0.0.1:5173/__ws-form/contact",
|
||||
},
|
||||
});
|
||||
emit("Fetch.requestPaused", {
|
||||
requestId: "intercepted-child",
|
||||
networkId: "child",
|
||||
frameId: "child",
|
||||
responseStatusCode: 200,
|
||||
request: {
|
||||
method: "POST",
|
||||
url: "http://127.0.0.1:5173/__ws-form/contact",
|
||||
},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
emit("Network.loadingFinished", { requestId: "managed" });
|
||||
navigated = true;
|
||||
emit("Page.frameNavigated", {
|
||||
frame: { id: "main", url: "http://127.0.0.1:5173/thanks" },
|
||||
});
|
||||
}
|
||||
}, 5);
|
||||
}
|
||||
};
|
||||
@@ -1135,6 +1211,77 @@ test.each([false, true])(
|
||||
}
|
||||
);
|
||||
|
||||
test("captures managed Form results before a fast redirect discards the network body", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({ fastRedirect: true });
|
||||
const session = await createFormBrowserSession(socket);
|
||||
try {
|
||||
const result = await session.submitForm!({
|
||||
url: "http://127.0.0.1:5173/contact",
|
||||
selector: "form",
|
||||
values: [],
|
||||
timeout: 1000,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: "submitted",
|
||||
results: [{ status: 201, resourceId: "action" }],
|
||||
});
|
||||
expect(counters).toMatchObject({
|
||||
submissions: 1,
|
||||
interceptedReads: 1,
|
||||
continuedResponses: 1,
|
||||
reads: [],
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("ignores an intercepted child-frame Form response", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({
|
||||
fastRedirect: true,
|
||||
interceptedChild: true,
|
||||
});
|
||||
const session = await createFormBrowserSession(socket);
|
||||
try {
|
||||
const result = await session.submitForm!({
|
||||
url: "http://127.0.0.1:5173/contact",
|
||||
selector: "form",
|
||||
values: [],
|
||||
timeout: 1000,
|
||||
});
|
||||
expect(result.results).toEqual([{ status: 201, resourceId: "action" }]);
|
||||
expect(counters.interceptedReads).toBe(1);
|
||||
expect(counters.continuedResponses).toBe(2);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("continues a fast redirect when its intercepted response body cannot be read", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({
|
||||
fastRedirect: true,
|
||||
interceptedBodyUnreadable: true,
|
||||
});
|
||||
const session = await createFormBrowserSession(socket);
|
||||
try {
|
||||
const result = await session.submitForm!({
|
||||
url: "http://127.0.0.1:5173/contact",
|
||||
selector: "form",
|
||||
values: [],
|
||||
timeout: 1000,
|
||||
});
|
||||
expect(result.status).toBe("submitted");
|
||||
expect(result.results).toEqual([]);
|
||||
expect(counters).toMatchObject({
|
||||
submissions: 1,
|
||||
interceptedReads: 1,
|
||||
continuedResponses: 1,
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("continues observing across a navigation execution-context gap without replaying the Form", async () => {
|
||||
const { socket, counters } = createManagedFormSocket({ navigationGap: true });
|
||||
const session = await createFormBrowserSession(socket);
|
||||
|
||||
@@ -2436,6 +2436,9 @@ const submitFormWithBrowserRuntime = async (
|
||||
let managedResponseBody:
|
||||
| Promise<{ body?: string; base64Encoded?: boolean } | undefined>
|
||||
| undefined;
|
||||
let interceptedManagedResponseBody:
|
||||
| Promise<{ body?: string; base64Encoded?: boolean } | undefined>
|
||||
| undefined;
|
||||
const submissionRequestIds = new Set<string>();
|
||||
const completedRequestIds = new Set<string>();
|
||||
let navigationObserved = false;
|
||||
@@ -2583,6 +2586,53 @@ const submitFormWithBrowserRuntime = async (
|
||||
}
|
||||
}
|
||||
});
|
||||
cdp.on("Fetch.requestPaused", (params) => {
|
||||
if (
|
||||
typeof params !== "object" ||
|
||||
params === null ||
|
||||
!("requestId" in params) ||
|
||||
typeof params.requestId !== "string"
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const requestId = params.requestId;
|
||||
if (
|
||||
dispatchStarted &&
|
||||
mainFrameId !== undefined &&
|
||||
"frameId" in params &&
|
||||
params.frameId === mainFrameId &&
|
||||
"networkId" in params &&
|
||||
typeof params.networkId === "string" &&
|
||||
submissionRequestIds.has(params.networkId) &&
|
||||
"responseStatusCode" in params &&
|
||||
typeof params.responseStatusCode === "number" &&
|
||||
"request" in params &&
|
||||
typeof params.request === "object" &&
|
||||
params.request !== null &&
|
||||
"url" in params.request &&
|
||||
typeof params.request.url === "string" &&
|
||||
"method" in params.request &&
|
||||
params.request.method === "POST"
|
||||
) {
|
||||
const responseUrl = new URL(params.request.url);
|
||||
const initialUrl = new URL(initialPageUrl);
|
||||
if (
|
||||
responseUrl.origin === initialUrl.origin &&
|
||||
responseUrl.pathname ===
|
||||
`/__ws-form${initialUrl.pathname === "/" ? "" : initialUrl.pathname}`
|
||||
) {
|
||||
// Read before releasing the response so a fast redirect cannot discard it.
|
||||
interceptedManagedResponseBody = send<{
|
||||
body?: string;
|
||||
base64Encoded?: boolean;
|
||||
}>("Fetch.getResponseBody", { requestId })
|
||||
.finally(() => send("Fetch.continueResponse", { requestId }))
|
||||
.catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
}
|
||||
void send("Fetch.continueResponse", { requestId }).catch(() => undefined);
|
||||
});
|
||||
await Promise.all([
|
||||
send("Page.enable"),
|
||||
send("Runtime.enable"),
|
||||
@@ -2591,6 +2641,9 @@ const submitFormWithBrowserRuntime = async (
|
||||
maxTotalBufferSize: 4_000_000,
|
||||
maxResourceBufferSize: 1_000_000,
|
||||
}),
|
||||
send("Fetch.enable", {
|
||||
patterns: [{ urlPattern: "*__ws-form*", requestStage: "Response" }],
|
||||
}),
|
||||
send("Page.setLifecycleEventsEnabled", { enabled: true }),
|
||||
]);
|
||||
const navigation = await navigateAndWaitForLifecycle(
|
||||
@@ -2716,8 +2769,13 @@ const submitFormWithBrowserRuntime = async (
|
||||
resourceName?: string;
|
||||
}[] = [];
|
||||
const errors: { status?: number; name?: string; message: string }[] = [];
|
||||
if (managedResponseBody !== undefined) {
|
||||
const body = await managedResponseBody;
|
||||
if (
|
||||
interceptedManagedResponseBody !== undefined ||
|
||||
managedResponseBody !== undefined
|
||||
) {
|
||||
const body =
|
||||
(await interceptedManagedResponseBody?.catch(() => undefined)) ??
|
||||
(await managedResponseBody);
|
||||
if (body?.body !== undefined && body.body.length < 1_000_000) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(
|
||||
|
||||
Reference in new issue
Block a user