Merge branch 'main' into pub.staging

This commit is contained in:
Oleg Isonen committed 2026-11-15 16:14:42 +00:00
commit d206589a7b
62 files changed
+1633 -435

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:
+22 -2
View File
@@ -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()
+15 -4
View File
@@ -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 }}
@@ -1572,6 +1572,26 @@ describe("api router permits", () => {
target: "staging",
})
).resolves.toMatchObject({ valid: true, cssValid: true });
build.styles[0].value = { type: "keyword", value: "red" };
build.breakpoints[0].condition = "(prefers-reduced-motion: reduce)";
await expect(
createCaller(createContext(true)).publish.validate({
projectId: "project-1",
target: "staging",
})
).resolves.toMatchObject({ valid: true, cssValid: true });
for (const condition of [
"(orientation: portrait) or (hover: hover)",
"(orientation: portrait) and (hover: hover)",
]) {
build.breakpoints[0].condition = condition;
await expect(
createCaller(createContext(true)).publish.validate({
projectId: "project-1",
target: "staging",
})
).resolves.toMatchObject({ valid: true, cssValid: true });
}
});
test.each(
+32 -1
View File
@@ -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") => {
+9 -1
View File
@@ -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"
+5 -2
View 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
+117 -26
View File
@@ -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();
}
});
};
+2 -1
View File
@@ -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(),
+6 -14
View File
@@ -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;
};
+15 -6
View File
@@ -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" ||
+19
View File
@@ -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();
}
};
+114 -37
View File
@@ -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;
};
+89
View File
@@ -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) => {
+28
View File
@@ -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 });
}
};
+3 -1
View File
@@ -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
+11 -1
View File
@@ -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 });
}
});
@@ -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,
@@ -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;
@@ -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 }),
@@ -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,
@@ -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()));
}
}
});
@@ -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;
@@ -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
+1 -1
View File
@@ -47,7 +47,7 @@ export default defineConfig({
url: builderUrl,
reuseExistingServer: false,
ignoreHTTPSErrors: true,
timeout: 60_000,
timeout: 120_000,
stdout: "pipe",
stderr: "pipe",
}
+1 -1
View File
@@ -20,7 +20,7 @@ The Head Slot provides a visual interface for controlling your website's `<head>
## Key information
- Even though the Head Slot is visually in the Body instance, the contents of Head Slot are added to the `<head>`. This hierarchy enables [data variables](../foundations/variables.md) defined on the Body to be used in the head.
- If Head Slot and Page Settings define the same data, such as meta title, Head Slot will take priority. Similarly, a default canonical is output on every page and references the current path. By specifying a canonical in Head Slot, the default canonical will not be displayed on the page.
- If Head Slot and Page Settings define the same data, such as meta title, Head Slot will take priority. A default canonical references the current path unless the page returns 404. By specifying a canonical in Head Slot, the default canonical will not be displayed on the page.
- Head Slot comes with an instance for Title, Link, and Meta. These can be duplicated. If you remove them and later need to add them back, you can copy them from a new Head Slot instance.
## Supported components
@@ -0,0 +1,33 @@
import type { AppLoadContext, EntryContext } from "@remix-run/cloudflare";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToReadableStream } from "react-dom/server";
export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
_loadContext: AppLoadContext
) {
const body = await renderToReadableStream(
<RemixServer context={remixContext} url={request.url} />,
{
onError(error: unknown) {
console.error(error);
responseStatusCode = 500;
},
}
);
const userAgent = request.headers.get("user-agent");
if (userAgent && isbot(userAgent)) {
await body.allReady;
}
responseHeaders.set("Content-Type", "text/html");
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
});
}
@@ -412,7 +412,7 @@ const Outlet = () => {
assetBaseUrl={constants.assetBaseUrl}
/>
<PageSettingsTitle>{pageMeta.title}</PageSettingsTitle>
<PageSettingsCanonicalLink href={url} />
{pageMeta.status !== 404 && <PageSettingsCanonicalLink href={url} />}
</ReactSdkContext.Provider>
);
};
@@ -412,7 +412,7 @@ const Outlet = () => {
assetBaseUrl={constants.assetBaseUrl}
/>
<PageSettingsTitle>{pageMeta.title}</PageSettingsTitle>
<PageSettingsCanonicalLink href={url} />
{pageMeta.status !== 404 && <PageSettingsCanonicalLink href={url} />}
</ReactSdkContext.Provider>
);
};
+29 -12
View File
@@ -15,6 +15,7 @@ import {
resolveMcpScreenshotInput,
startMcpPreview,
} from "./mcp-preview";
import { __testing__ as mcpTesting } from "./mcp";
test("browser failure before Form dispatch is reported instead of an unknown submission", async () => {
const submitForm = vi.fn(async () => {
@@ -1939,15 +1940,15 @@ test("reports an interior route HTTP failure instead of a wrong-site error", asy
});
});
test("does not expose a page script URL in responsive capture errors", async () => {
test("reports a safe script location and saved PNG through MCP error serialization", async () => {
const capturePage = vi.fn().mockResolvedValueOnce([
{
output: "builder.png",
output: "/tmp/builder.png",
navigation: {
generatedSiteRootPresent: true,
javascriptErrorPresent: true,
javascriptErrorLocation: {
pathname: "/private/customer-123.js",
pathname: "/assets/app.js",
line: 42,
},
},
@@ -1978,14 +1979,30 @@ test("does not expose a page script URL in responsive capture errors", async ()
viewport: { width: 1280, height: 720 },
},
];
await expect(handlers.capturePageScreenshots(input)).rejects.toMatchObject({
code: "SCREENSHOT_JAVASCRIPT_ERROR",
message: "The page reported a JavaScript error during screenshot capture.",
issues: [
{
code: "screenshot_javascript_error",
constraint: "javascript_runtime_error",
},
],
const error = await handlers
.capturePageScreenshots(input)
.catch((error) => error);
const serialized = mcpTesting.createMcpSingleOpCallErrorPayload({
error,
elapsedMs: 1,
});
expect(
serialized.error.message.startsWith(
"The page reported a JavaScript error during screenshot capture at /assets/app.js:42."
)
).toBe(true);
expect(serialized).toMatchObject({
error: {
code: "SCREENSHOT_JAVASCRIPT_ERROR",
issues: [
{
code: "screenshot_javascript_error",
file: "/assets/app.js",
line: 42,
reference: "/tmp/builder.png",
constraint: "javascript_runtime_error",
},
],
},
});
});
+10 -2
View File
@@ -564,8 +564,10 @@ export const createMcpPreviewHandlers = ({
});
}
if (result.navigation?.javascriptErrorPresent === true) {
const message =
"The page reported a JavaScript error during screenshot capture.";
const location = result.navigation.javascriptErrorLocation;
const message = location
? `The page reported a JavaScript error during screenshot capture at ${location.pathname}:${location.line}.`
: "The page reported a JavaScript error during screenshot capture.";
throw Object.assign(new Error(message), {
code: "SCREENSHOT_JAVASCRIPT_ERROR",
issues: [
@@ -574,6 +576,12 @@ export const createMcpPreviewHandlers = ({
path: [],
message,
constraint: "javascript_runtime_error",
...(location === undefined
? {}
: { file: location.pathname, line: location.line }),
...(result.output === undefined
? {}
: { reference: result.output }),
},
],
});
+96
View File
@@ -2965,6 +2965,102 @@ sitemap.map((page) => page.path);`
await expectGeneratedRedirectFallback("app/routes/$.tsx");
});
test("omits the default canonical from a 404 response", async () => {
await writeSiteData(
createSiteData({
pages: [
{
id: "home",
name: "Home",
title: "Home",
path: "",
rootInstanceId: "root",
meta: {},
},
{
id: "post",
name: "Post",
title: "Post",
path: "/blog/:slug",
rootInstanceId: "root",
meta: { status: "404" },
},
{
id: "not-found",
name: "Not found",
title: "Not found",
path: "/*",
rootInstanceId: "root",
meta: { status: "404" },
},
],
})
);
await prebuild({ assets: false, template: ["defaults"] });
await symlink(join(originalCwd, "node_modules"), "node_modules", "dir");
const viteConfig = await readFile("vite.config.ts", "utf8");
await writeFile(
"vite.config.ts",
viteConfig
.replaceAll(
'conditions: ["browser", "development|production"]',
'conditions: ["webstudio", "browser", "development|production"]'
)
.replaceAll(
'conditions: ["node", "development|production"]',
'conditions: ["webstudio", "node", "development|production"]'
)
);
await runGeneratedCommand("remix", ["vite:build"]);
const serverEntry = pathToFileURL(
join(tempDir, "build/server/index.js")
).href;
const runner = `
import { createRequestHandler } from "@remix-run/server-runtime";
const serverBuild = await import(${JSON.stringify(serverEntry)});
const handleRequest = createRequestHandler(serverBuild, "production");
const responses = [];
for (const path of ["/", "/blog/missing", "/missing"]) {
const response = await handleRequest(new Request(
new URL(path, "https://example.com"),
{ headers: { host: "example.com" } }
));
responses.push({ status: response.status, html: await response.text() });
}
process.stdout.write(JSON.stringify(responses));
`;
const { stdout } = await execFileAsync(
process.execPath,
[
"--import",
pathToFileURL(
join(originalCwd, "../../node_modules/tsx/dist/loader.mjs")
).href,
"--input-type=module",
"-e",
runner,
],
{
cwd: tempDir,
env: { ...process.env, NODE_OPTIONS: "--conditions=webstudio" },
}
);
const responses = JSON.parse(stdout) as {
status: number;
html: string;
}[];
const canonicals = responses.map(({ html }) =>
findElementsByTagName(parseHtml(html), "link").filter((link) =>
link.attrs.some(
({ name, value }) => name === "rel" && value === "canonical"
)
)
);
expect(responses.map(({ status }) => status)).toEqual([200, 404, 404]);
expect(canonicals.map((links) => links.length)).toEqual([1, 0, 0]);
}, 60_000);
test("builds a generated dynamic route with the packaged React Router SDK", async () => {
await writeSiteData(
createSiteData({
@@ -0,0 +1,33 @@
import type { AppLoadContext, EntryContext } from "@remix-run/cloudflare";
import { RemixServer } from "@remix-run/react";
import { isbot } from "isbot";
import { renderToReadableStream } from "react-dom/server";
export default async function handleRequest(
request: Request,
responseStatusCode: number,
responseHeaders: Headers,
remixContext: EntryContext,
_loadContext: AppLoadContext
) {
const body = await renderToReadableStream(
<RemixServer context={remixContext} url={request.url} />,
{
onError(error: unknown) {
console.error(error);
responseStatusCode = 500;
},
}
);
const userAgent = request.headers.get("user-agent");
if (userAgent && isbot(userAgent)) {
await body.allReady;
}
responseHeaders.set("Content-Type", "text/html");
return new Response(body, {
headers: responseHeaders,
status: responseStatusCode,
});
}
@@ -412,7 +412,7 @@ const Outlet = () => {
assetBaseUrl={constants.assetBaseUrl}
/>
<PageSettingsTitle>{pageMeta.title}</PageSettingsTitle>
<PageSettingsCanonicalLink href={url} />
{pageMeta.status !== 404 && <PageSettingsCanonicalLink href={url} />}
</ReactSdkContext.Provider>
);
};
@@ -2,6 +2,36 @@ import { describe, expect, test } from "vitest";
import { MediaRule, PlaintextRule } from "./rules";
describe("MediaRule with custom conditions", () => {
test.each([
[
"(prefers-reduced-motion: reduce)",
"@media (prefers-reduced-motion: reduce)",
],
[
"(orientation: portrait) or (hover: hover)",
"@media (orientation: portrait) or (hover: hover)",
],
[
"(orientation: portrait) and (hover: hover)",
"@media (orientation: portrait) and (hover: hover)",
],
])("groups media condition %s", (condition, expected) => {
const mediaRule = new MediaRule("breakpoint", { condition });
mediaRule.insertRule(new PlaintextRule(" .test { color: red; }"));
expect(mediaRule.cssText).toContain(expected);
});
test("keeps a negated condition grouped for screen media", () => {
const mediaRule = new MediaRule("breakpoint", {
mediaType: "screen",
condition: "not (prefers-reduced-motion: reduce)",
});
mediaRule.insertRule(new PlaintextRule(" .test { color: red; }"));
expect(mediaRule.cssText).toContain(
"@media screen and (not (prefers-reduced-motion: reduce))"
);
});
test("generates media query with custom condition only", () => {
const mediaRule = new MediaRule("breakpoint1", {
condition: "orientation:portrait",
+2 -1
View File
@@ -365,7 +365,8 @@ export class MediaRule {
// If condition is set, use it exclusively (minWidth/maxWidth must be undefined)
if (condition !== undefined) {
query =
mediaType === "all" && condition.startsWith("not (")
mediaType === "all" &&
(condition.trimStart().startsWith("(") || condition.startsWith("not ("))
? condition
: `${mediaType} and (${condition})`;
} else {
@@ -1,3 +1,4 @@
import { page } from "@vitest/browser/context";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { afterEach, expect, test } from "vitest";
@@ -52,3 +53,28 @@ test("consent checkboxes keep their size beside wrapped labels", () => {
expect(top).toBe(rowTop);
}
});
test("checkbox keeps its size on hover", async () => {
const container = document.createElement("div");
container.style.padding = "20px";
document.body.append(container);
root = createRoot(container);
act(() => {
root?.render(<Checkbox aria-label="Selection" />);
});
const checkbox = container.querySelector<HTMLButtonElement>("button")!;
const restRect = checkbox.getBoundingClientRect();
expect({ width: restRect.width, height: restRect.height }).toEqual({
width: 14,
height: 14,
});
await page.elementLocator(checkbox).hover();
const hoverRect = checkbox.getBoundingClientRect();
expect({ width: hoverRect.width, height: hoverRect.height }).toEqual({
width: restRect.width,
height: restRect.height,
});
});
@@ -22,20 +22,20 @@ const checkboxStyle = css({
position: "relative",
borderRadius: theme.borderRadius[3],
color: cssVar("--foreground-primary"),
background: cssVar("--background-secondary"),
background: `light-dark(${cssVar("--background-secondary")}, ${cssVar(
"--foreground-disabled"
)})`,
border: "1px solid transparent",
"&:hover": {
borderColor: cssVar("--border-default"),
},
"&:focus-visible": {
borderColor: cssVar("--border-focus"),
},
// [data-state] is needed to make selector specificity higher
"&[data-state]:disabled": {
color: cssVar("--foreground-disabled"),
color: `light-dark(${cssVar("--foreground-disabled")}, ${cssVar(
"--foreground-on-inverse"
)})`,
},
});
@@ -1,3 +1,4 @@
import { page, userEvent } from "@vitest/browser/context";
import { createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
@@ -42,7 +43,47 @@ const readTokenColor = (name: string) => {
return color;
};
test("compact form controls use their intended resting treatment", () => {
const luminance = (color: number[]) => {
const linearize = (channel: number) => {
const value = channel / 255;
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
};
return (
0.2126 * linearize(color[0]) +
0.7152 * linearize(color[1]) +
0.0722 * linearize(color[2])
);
};
const contrast = (first: number[], second: number[]) => {
const firstLuminance = luminance(first);
const secondLuminance = luminance(second);
return (
(Math.max(firstLuminance, secondLuminance) + 0.05) /
(Math.min(firstLuminance, secondLuminance) + 0.05)
);
};
const expectCheckboxBackground = (
checkbox: Element,
mode: string,
state: string
) => {
const style = getComputedStyle(checkbox);
const background = readColor(style.backgroundColor);
if (mode === "light") {
expect(background, `${state} light background`).toEqual(
readTokenColor("--background-secondary")
);
return;
}
expect(
contrast(background, readTokenColor("--background-floating-raised")),
`${state} dark background contrast`
).toBeGreaterThanOrEqual(3);
};
test("compact form controls keep their intended contrast", async () => {
const container = document.createElement("div");
document.body.append(container);
root = createRoot(container);
@@ -59,6 +100,24 @@ test("compact form controls use their intended resting treatment", () => {
{ "data-control": "checkbox" },
createElement(Checkbox, { "aria-label": "Checkbox" })
),
createElement(Checkbox, {
"aria-label": "Checked checkbox",
checked: true,
}),
createElement(Checkbox, {
"aria-label": "Disabled checkbox",
disabled: true,
}),
createElement(Checkbox, {
"aria-label": "Disabled checked checkbox",
checked: true,
disabled: true,
}),
createElement(Checkbox, {
"aria-label": "Disabled indeterminate checkbox",
checked: "indeterminate",
disabled: true,
}),
createElement(
"div",
{ "data-switch": true },
@@ -89,14 +148,74 @@ test("compact form controls use their intended resting treatment", () => {
);
});
const checkbox = container.querySelector("[data-control] > button");
const checkbox = container.querySelector<HTMLButtonElement>(
"[data-control] > button"
);
if (checkbox === null) {
throw new Error("Expected a checkbox");
}
act(() => checkbox.blur());
await page.getByText("Neutral").hover();
expect(checkbox.matches(":hover, :focus-visible")).toBe(false);
expectCheckboxBackground(checkbox, mode, "resting checkbox");
const restingBorderColor = readColor(
getComputedStyle(checkbox).borderColor
);
expect(restingBorderColor[3]).toBe(0);
const checkedCheckbox = container.querySelector<HTMLButtonElement>(
'[aria-label="Checked checkbox"]'
);
const disabledCheckbox = container.querySelector<HTMLButtonElement>(
'[aria-label="Disabled checkbox"]'
);
if (checkedCheckbox === null || disabledCheckbox === null) {
throw new Error("Expected checked and disabled checkboxes");
}
expectCheckboxBackground(checkedCheckbox, mode, "checked checkbox");
expect(
readColor(getComputedStyle(checkbox).borderColor)[3],
`${mode} checkbox resting border`
).toBe(0);
contrast(
readColor(getComputedStyle(checkedCheckbox).color),
readColor(getComputedStyle(checkedCheckbox).backgroundColor)
),
`${mode} checked icon contrast`
).toBeGreaterThanOrEqual(3);
expectCheckboxBackground(disabledCheckbox, mode, "disabled checkbox");
for (const label of [
"Disabled checked checkbox",
"Disabled indeterminate checkbox",
]) {
const disabledMarked = container.querySelector<HTMLButtonElement>(
`[aria-label="${label}"]`
);
if (disabledMarked === null) {
throw new Error(`Expected ${label}`);
}
expectCheckboxBackground(disabledMarked, mode, label);
const style = getComputedStyle(disabledMarked);
if (mode === "light") {
expect(readColor(style.color)).toEqual(
readTokenColor("--foreground-disabled")
);
} else {
expect(
contrast(readColor(style.color), readColor(style.backgroundColor)),
`${label} dark mark contrast`
).toBeGreaterThanOrEqual(3);
}
}
await page.elementLocator(checkbox).hover();
expect(checkbox.matches(":hover")).toBe(true);
expectCheckboxBackground(checkbox, mode, "hovered checkbox");
expect(readColor(getComputedStyle(checkbox).borderColor)).toEqual(
restingBorderColor
);
act(() => checkedCheckbox.focus());
await act(async () => userEvent.keyboard("{Shift>}{Tab}{/Shift}"));
expect(checkbox.matches(":focus-visible")).toBe(true);
expect(readColor(getComputedStyle(checkbox).borderColor)).toEqual(
readTokenColor("--border-focus")
);
expectCheckboxBackground(checkbox, mode, "focused checkbox");
const switchControl = container.querySelector("[data-switch] > button");
if (switchControl === null) {
@@ -66,6 +66,7 @@ class FakeWebSocket {
| "exception-error"
| "stale-outgoing-error"
| "hash-navigation-error";
readonly exceptionUrl?: string;
private navigationCount = 0;
imageInspectionFinished = false;
screenshotStartedBeforeImageInspectionFinished = false;
@@ -78,7 +79,8 @@ class FakeWebSocket {
readinessWidths?: number[],
lifecycleFrames = ["main"],
pendingFonts = false,
runtimeErrorScenario?: FakeWebSocket["runtimeErrorScenario"]
runtimeErrorScenario?: FakeWebSocket["runtimeErrorScenario"],
exceptionUrl?: string
) {
this.status = status;
this.finalUrl = finalUrl;
@@ -87,6 +89,7 @@ class FakeWebSocket {
this.lifecycleFrames = lifecycleFrames;
this.pendingFonts = pendingFonts;
this.runtimeErrorScenario = runtimeErrorScenario;
this.exceptionUrl = exceptionUrl;
setTimeout(() => this.emit("open"), 0);
}
@@ -448,36 +451,26 @@ class FakeWebSocket {
sameDocumentNavigation) &&
navigationNumber === 2);
if (shouldLogError) {
const isException = this.runtimeErrorScenario !== "console-error";
this.emit("message", {
data: JSON.stringify({
method:
this.runtimeErrorScenario === "exception-error"
? "Runtime.exceptionThrown"
: "Runtime.consoleAPICalled",
params:
this.runtimeErrorScenario === "exception-error"
? {
exceptionDetails: {
executionContextId,
url: "https://example.com/assets/exception.js?token=private",
lineNumber: 6,
},
}
: {
type: "error",
method: isException
? "Runtime.exceptionThrown"
: "Runtime.consoleAPICalled",
params: isException
? {
exceptionDetails: {
executionContextId:
this.runtimeErrorScenario === "console-error"
this.runtimeErrorScenario === "exception-error"
? executionContextId
: 1,
stackTrace: {
callFrames: [
{
url: "https://example.com/assets/app.js?token=private",
lineNumber: 41,
},
],
},
url:
this.exceptionUrl ??
"https://user:pass@example.com/assets/exception.js?token=private#fragment",
lineNumber: 6,
},
}
: { type: "error", executionContextId },
}),
});
}
@@ -954,6 +947,9 @@ const createManagedFormSocket = ({
bodyDelay = 0,
unreadable = false,
navigationGap = false,
fastRedirect = false,
interceptedBodyUnreadable = false,
interceptedChild = false,
unrelated,
}: {
body?: string;
@@ -961,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";
@@ -974,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 }) });
@@ -1003,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" &&
@@ -1076,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);
}
};
@@ -1142,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);
@@ -2412,7 +2552,7 @@ test("returns final URL, redirects, and HTTP error status", async () => {
});
});
test("reports React error boundary errors logged by the page", async () => {
test("does not treat console.error as an uncaught page exception", async () => {
const layout = await captureBrowserScreenshot(
{
url: "https://example.com",
@@ -2437,11 +2577,11 @@ test("reports React error boundary errors logged by the page", async () => {
})
);
expect(layout.navigation?.javascriptErrorPresent).toBe(true);
expect(layout.navigation?.javascriptErrorPresent).toBeUndefined();
expect(layout.navigation).not.toHaveProperty("javascriptErrorLocation");
});
test("does not expose a page exception URL", async () => {
test("reports a page exception script path and one-based line without its URL query", async () => {
const layout = await captureBrowserScreenshot(
{
url: "https://example.com",
@@ -2467,7 +2607,49 @@ test("does not expose a page exception URL", async () => {
);
expect(layout.navigation?.javascriptErrorPresent).toBe(true);
expect(layout.navigation).not.toHaveProperty("javascriptErrorLocation");
expect(layout.navigation?.javascriptErrorLocation).toEqual({
pathname: "/assets/exception.js",
line: 7,
});
expect(JSON.stringify(layout.navigation)).not.toContain("token=private");
expect(JSON.stringify(layout.navigation)).not.toContain("user:pass");
expect(JSON.stringify(layout.navigation)).not.toContain("fragment");
});
test.each([
"https://example.com/private/customer-123.js?token=private",
"https://example.com/assets/data.json",
])("omits a non-script path from page exception results: %s", async (url) => {
const layout = await captureBrowserScreenshot(
{
url: "https://example.com",
output: "/tmp/private-exception.png",
width: 800,
height: 600,
browserPath: "/usr/bin/chromium",
waitUntil: "networkidle",
waitForTimeout: 0,
timeout: 1000,
},
createDependencies({
socket: new FakeWebSocket(
200,
undefined,
undefined,
undefined,
["main"],
false,
"exception-error",
url
),
})
);
expect(layout.navigation?.javascriptErrorPresent).toBe(true);
expect(layout.navigation?.javascriptErrorLocation).toBeUndefined();
expect(JSON.stringify(layout.navigation)).not.toContain(
new URL(url).pathname
);
});
test("does not attribute an outgoing page error to the next route", async () => {
@@ -2508,6 +2690,9 @@ test("does not attribute an outgoing page error to the next route", async () =>
expect(
layouts.map(({ navigation }) => navigation?.javascriptErrorPresent)
).toEqual([undefined, undefined]);
expect(
layouts.map(({ navigation }) => navigation?.javascriptErrorLocation)
).toEqual([undefined, undefined]);
await session.close();
});
@@ -2549,6 +2734,10 @@ test("keeps tracking the document context across hash navigations", async () =>
expect(
layouts.map(({ navigation }) => navigation?.javascriptErrorPresent)
).toEqual([undefined, true]);
expect(layouts[1]?.navigation?.javascriptErrorLocation).toEqual({
pathname: "/assets/exception.js",
line: 7,
});
await session.close();
});
+108 -14
View File
@@ -442,6 +442,36 @@ const getExecutionContextId = (params: unknown) =>
? params.executionContextId
: undefined;
const isGeneratedStaticScriptPath = (pathname: string) =>
/^\/assets\/[^/?#]+\.(?:js|mjs)$/.test(pathname);
const getJavascriptErrorLocation = (params: unknown) => {
if (typeof params !== "object" || params === null) {
return;
}
const { url, lineNumber } = params as Record<string, unknown>;
if (
typeof url !== "string" ||
typeof lineNumber !== "number" ||
Number.isSafeInteger(lineNumber) === false ||
lineNumber < 0 ||
lineNumber === Number.MAX_SAFE_INTEGER
) {
return;
}
try {
const scriptUrl = new URL(url);
if (
(scriptUrl.protocol === "http:" || scriptUrl.protocol === "https:") &&
isGeneratedStaticScriptPath(scriptUrl.pathname)
) {
return { pathname: scriptUrl.pathname, line: lineNumber + 1 };
}
} catch {
return;
}
};
const navigateAndWaitForLifecycle = async (
cdp: CdpSession,
waitUntil: ScreenshotWaitUntil,
@@ -791,6 +821,7 @@ export type BrowserScreenshotNavigation = {
redirects: string[];
documentReadyState: string;
javascriptErrorPresent?: boolean;
javascriptErrorLocation?: { pathname: string; line: number };
pageMetadata?: BrowserScreenshotPageMetadata;
layoutStable: boolean;
};
@@ -1720,19 +1751,28 @@ const capturePageWithBrowserRuntime = async (
}
>();
let javascriptErrorPresent = false;
let javascriptErrorLocation: BrowserScreenshotNavigation["javascriptErrorLocation"];
let navigationFrameId: string | undefined;
let navigationExecutionContextFrames: Map<number, string> | undefined;
const navigationErrorsByContextId = new Set<number>();
const navigationErrorsByContextId = new Map<
number,
BrowserScreenshotNavigation["javascriptErrorLocation"]
>();
let activeExecutionContextIds = new Set<number>();
const recordJavascriptError = (params: unknown) => {
const executionContextId = getExecutionContextId(params);
if (executionContextId === undefined) {
return;
}
const location = getJavascriptErrorLocation(params);
if (navigationExecutionContextFrames !== undefined) {
navigationErrorsByContextId.add(executionContextId);
navigationErrorsByContextId.set(
executionContextId,
navigationErrorsByContextId.get(executionContextId) ?? location
);
} else if (activeExecutionContextIds.has(executionContextId)) {
javascriptErrorPresent = true;
javascriptErrorLocation ??= location;
}
};
cdp.on("Runtime.executionContextCreated", (params) => {
@@ -1767,16 +1807,6 @@ const capturePageWithBrowserRuntime = async (
recordJavascriptError(params.exceptionDetails);
}
});
cdp.on("Runtime.consoleAPICalled", (params) => {
if (
typeof params === "object" &&
params !== null &&
"type" in params &&
params.type === "error"
) {
recordJavascriptError(params);
}
});
cdp.on("Network.requestWillBeSent", (params) => {
if (
typeof params !== "object" ||
@@ -1857,6 +1887,7 @@ const capturePageWithBrowserRuntime = async (
activeExecutionContextIds
);
javascriptErrorPresent = false;
javascriptErrorLocation = undefined;
navigationExecutionContextFrames = new Map();
navigationErrorsByContextId.clear();
activeExecutionContextIds = new Set();
@@ -1900,6 +1931,8 @@ const capturePageWithBrowserRuntime = async (
for (const executionContextId of activeExecutionContextIds) {
if (navigationErrorsByContextId.has(executionContextId)) {
javascriptErrorPresent = true;
javascriptErrorLocation ??=
navigationErrorsByContextId.get(executionContextId);
}
}
navigationExecutionContextFrames = undefined;
@@ -2123,6 +2156,9 @@ const capturePageWithBrowserRuntime = async (
redirects,
...readiness,
...(javascriptErrorPresent ? { javascriptErrorPresent: true } : {}),
...(javascriptErrorPresent && javascriptErrorLocation !== undefined
? { javascriptErrorLocation }
: {}),
};
if (images === undefined) {
delete layout.images;
@@ -2400,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;
@@ -2547,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"),
@@ -2555,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(
@@ -2680,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(