Files
webstudio/apps/builder/e2e/flows/generated-app.ts
T
Oleg Isonen 23c81d64c9 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
on de2f4ed. 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.
2026-11-15 17:10:10 +01:00

432 lines
13 KiB
TypeScript

import { execFile, spawn, type ChildProcess } from "node:child_process";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createServer } from "node:net";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import type { Page as PlaywrightPage } from "@playwright/test";
import { bundleVersion } from "@webstudio-is/protocol";
import { getStyleDeclKey, type Page } from "@webstudio-is/sdk";
import type { ProjectSettings } from "@webstudio-is/project-build";
import { loadDevBuild } from "../db";
import { stopChildProcess } from "../process";
const execFileAsync = promisify(execFile);
const cliLocalPath = fileURLToPath(
new URL("../../../../packages/cli/local.js", import.meta.url)
);
type BuildRow = Awaited<ReturnType<typeof loadDevBuild>>;
export const getAvailablePort = async () => {
const server = createServer();
server.unref();
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => resolve());
});
const address = server.address();
if (address === null || typeof address === "string") {
await new Promise<void>((resolve) => server.close(() => resolve()));
throw new Error("Expected a numeric port for generated-app preview.");
}
await new Promise<void>((resolve) => server.close(() => resolve()));
return address.port;
};
export const waitForGeneratedPreview = async ({
process,
url,
output,
}: {
process: ChildProcess;
url: string;
output: () => string;
}) => {
// Preview also compiles the production app while other E2E workers are active.
const deadline = Date.now() + 120_000;
while (Date.now() < deadline) {
if (process.exitCode !== null || process.signalCode !== null) {
throw new Error(
`Generated preview exited before it became ready at ${url}. Output:\n${output()}`
);
}
try {
const response = await fetch(url, {
signal: AbortSignal.timeout(2_000),
});
if (response.ok) {
return await response.text();
}
} catch {
// The generated production server is still starting.
}
await new Promise<void>((resolve) => setTimeout(resolve, 250));
}
throw new Error(
`Generated preview did not become ready at ${url}. Output:\n${output()}`
);
};
const parseBuildField = <Value>(build: BuildRow, field: keyof BuildRow) =>
JSON.parse(String(build[field])) as Value;
const parseBuildEntriesById = <Value extends { id: string }>(
build: BuildRow,
field: keyof BuildRow
) => {
return parseBuildField<Value[]>(build, field).map((value) => [
value.id,
value,
]);
};
const parseBuildStyleEntries = (build: BuildRow) => {
return parseBuildField<Parameters<typeof getStyleDeclKey>[0][]>(
build,
"styles"
).map((style) => [getStyleDeclKey(style), style]);
};
const parseBuildStyleSourceSelectionEntries = (build: BuildRow) => {
return parseBuildField<Array<{ instanceId: string }>>(
build,
"styleSourceSelections"
).map((selection) => [selection.instanceId, selection]);
};
export const createLocalBundleFromDevBuild = (build: BuildRow) => {
const pages = parseBuildField<{
homePageId: string;
pages: Page[];
}>(build, "pages");
const homePage = pages.pages.find((page) => page.id === pages.homePageId);
if (homePage === undefined) {
throw new Error("Expected dev build to have a home page");
}
return {
bundleVersion,
origin: "https://assets.example",
projectDomain: "generated-e2e.example",
projectTitle: pages.pages[0]?.name ?? "Generated E2E",
page: homePage,
pages: pages.pages,
assets: [],
build: {
id: build.id,
projectId: build.projectId,
version: build.version,
createdAt: build.createdAt,
updatedAt: build.updatedAt,
pages,
breakpoints: parseBuildEntriesById(build, "breakpoints"),
styles: parseBuildStyleEntries(build),
styleSources: parseBuildEntriesById(build, "styleSources"),
styleSourceSelections: parseBuildStyleSourceSelectionEntries(build),
props: parseBuildEntriesById(build, "props"),
instances: parseBuildEntriesById(build, "instances"),
dataSources: parseBuildEntriesById(build, "dataSources"),
resources: parseBuildEntriesById(build, "resources"),
projectSettings: parseBuildField<ProjectSettings>(
build,
"projectSettings"
),
},
};
};
export const expectGeneratedAppBuild = async ({
projectId,
expectedText,
}: {
projectId: string;
expectedText?: string;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
await execFileAsync(
process.execPath,
[cliLocalPath, "build", "--assets", "false", "--template", "defaults"],
{
cwd: tempDir,
env: { ...process.env, PWD: tempDir },
maxBuffer: 1024 * 1024 * 10,
}
);
if (expectedText !== undefined) {
const generatedHome = await readFile(
join(tempDir, "app", "__generated__", "_index.tsx"),
"utf8"
);
if (generatedHome.includes(expectedText) === false) {
throw new Error(
`Expected generated home route to include "${expectedText}".`
);
}
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};
export const withGeneratedPreview = async <Result>({
projectId,
callback,
evaluationReceiverPort,
}: {
projectId: string;
callback: ({ url, html }: { url: string; html: string }) => Promise<Result>;
evaluationReceiverPort?: string;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
let preview: ChildProcess | undefined;
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
const port = await getAvailablePort();
const output: string[] = [];
preview = spawn(
process.execPath,
[
cliLocalPath,
"preview",
"--assets",
"false",
"--template",
"defaults",
"--template",
"react-router",
"--host",
"127.0.0.1",
"--port",
String(port),
],
{
cwd: tempDir,
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
env: {
...process.env,
PWD: tempDir,
...(evaluationReceiverPort === undefined
? {}
: {
WEBSTUDIO_FORM_EVALUATION_RECEIVER_PORT: evaluationReceiverPort,
}),
},
}
);
const appendOutput = (chunk: unknown) => {
output.push(String(chunk));
while (output.join("").length > 8_000) {
output.shift();
}
};
preview.stdout?.on("data", appendOutput);
preview.stderr?.on("data", appendOutput);
const url = `http://127.0.0.1:${port}/`;
const html = await waitForGeneratedPreview({
process: preview,
url,
output: () => output.join(""),
});
return await callback({ url, html });
} finally {
if (preview !== undefined) {
// The CLI starts npm and the generated server below it.
await stopChildProcess(preview, { killGroup: true });
}
await rm(tempDir, { recursive: true, force: true });
}
};
export const expectGeneratedAppToRender = async ({
projectId,
expectedText,
path = "/",
}: {
projectId: string;
expectedText: string;
path?: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url, html }) => {
const response =
path === "/"
? undefined
: await fetch(new URL(path, url), { redirect: "manual" });
const routeHtml = response === undefined ? html : await response.text();
if (
(response !== undefined && response.ok === false) ||
routeHtml.includes(expectedText) === false
) {
throw new Error(
`Expected generated preview route ${JSON.stringify(path)} at ${url} to render ${JSON.stringify(expectedText)}.`
);
}
},
});
};
export const expectGeneratedAppRedirect = async ({
projectId,
path,
status,
location,
}: {
projectId: string;
path: string;
status: number;
location: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url }) => {
const response = await fetch(new URL(path, url), {
redirect: "manual",
});
const actualLocation = response.headers.get("location");
if (response.status !== status || actualLocation !== location) {
throw new Error(
`Expected generated preview redirect ${JSON.stringify(path)} to return ${status} with location ${JSON.stringify(location)}. Received ${response.status} with location ${JSON.stringify(actualLocation)}.`
);
}
},
});
};
export const expectGeneratedAppNavigation = async ({
projectId,
page,
linkText,
targetPath,
expectedRenderedText,
renderPath,
}: {
projectId: string;
page: PlaywrightPage;
linkText: string;
targetPath: string;
expectedRenderedText?: string;
renderPath?: string;
}) => {
await withGeneratedPreview({
projectId,
callback: async ({ url }) => {
if (expectedRenderedText !== undefined) {
const path = renderPath ?? "/";
const response = await fetch(new URL(path, url), {
redirect: "manual",
});
const html = await response.text();
if (
response.ok === false ||
html.includes(expectedRenderedText) === false
) {
throw new Error(
`Expected generated preview route ${JSON.stringify(path)} at ${url} to render ${JSON.stringify(expectedRenderedText)}.`
);
}
}
const targetUrl = new URL(targetPath, url).toString();
await page.goto(url);
await page.getByRole("link", { name: linkText, exact: true }).click();
await page.waitForURL(targetUrl);
const activeLink = page.getByRole("link", {
name: linkText,
exact: true,
});
try {
await activeLink.waitFor({ state: "visible" });
await page.waitForFunction(
({ linkText }) =>
Array.from(document.querySelectorAll("a")).some(
(link) =>
link.textContent?.trim() === linkText &&
link.getAttribute("aria-current") === "page"
),
{ linkText },
{ timeout: 10_000 }
);
} catch {
const ariaCurrent = await activeLink.getAttribute("aria-current");
throw new Error(
`Expected generated preview link ${JSON.stringify(linkText)} to be active after navigating to ${JSON.stringify(targetPath)}. Received aria-current=${JSON.stringify(ariaCurrent)}.`
);
}
},
});
};
export const expectGeneratedRedirects = async ({
projectId,
expectedRedirects,
}: {
projectId: string;
expectedRedirects: Array<{ old: string; new: string; status?: string }>;
}) => {
const tempDir = await mkdtemp(join(tmpdir(), "webstudio-e2e-generated-"));
try {
const build = await loadDevBuild({ projectId });
await mkdir(join(tempDir, ".webstudio"), { recursive: true });
await writeFile(
join(tempDir, ".webstudio", "data.json"),
`${JSON.stringify(createLocalBundleFromDevBuild(build), undefined, 2)}\n`
);
await execFileAsync(
process.execPath,
[cliLocalPath, "build", "--assets", "false", "--template", "defaults"],
{
cwd: tempDir,
env: { ...process.env, PWD: tempDir },
maxBuffer: 1024 * 1024 * 10,
}
);
const redirectsModule = await readFile(
join(tempDir, "app", "__generated__", "$resources.redirects.ts"),
"utf8"
);
const redirectsExport = redirectsModule.trim();
const prefix = "export const redirects = ";
const suffix = ";";
if (
redirectsExport.startsWith(prefix) === false ||
redirectsExport.endsWith(suffix) === false
) {
throw new Error(
`Expected generated redirects module to export redirects. Received ${redirectsModule}`
);
}
const redirectsJson = redirectsExport.slice(prefix.length, -suffix.length);
const redirects = JSON.parse(redirectsJson);
if (JSON.stringify(redirects) !== JSON.stringify(expectedRedirects)) {
throw new Error(
`Expected generated redirects ${JSON.stringify(
expectedRedirects
)}, received ${JSON.stringify(redirects)}.`
);
}
} finally {
await rm(tempDir, { recursive: true, force: true });
}
};