fix: Address E2E cache, cleanup, and browser routing review findings

This commit is contained in:
Oleg Isonen committed 2026-11-15 15:39:04 +00:00
1 parent 393e51c783
commit ec40adda07
10 files changed
+228 -62

No files matched your search

+13
View File
@@ -67,6 +67,19 @@ 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",
+1
View File
@@ -36,6 +36,7 @@ builder_backend_schema_fingerprint() {
find packages/prisma-client/prisma/migrations \
-mindepth 1 -maxdepth 1 -type d -print
find packages/prisma-client/prisma/migrations \
-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
+73 -56
View File
@@ -1,4 +1,4 @@
import type { BrowserContext } from "@playwright/test";
import type { BrowserContext, Page } from "@playwright/test";
import env from "../../app/env/env.server";
import { getWorkerEmail } from "../flows/dashboard";
import { measure } from "../perf";
@@ -16,6 +16,29 @@ 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,
@@ -33,71 +56,65 @@ const createProjectThroughApi = async ({
if (devPlan !== undefined) {
await context.clearCookies();
}
const loginPage = await context.request.get(`${dashboardUrl}/login`, {
headers: {
"sec-fetch-mode": "navigate",
"sec-fetch-dest": "document",
"sec-fetch-site": "same-origin",
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}`);
}
}
},
maxRedirects: 0,
});
if (loginPage.status() === 200) {
const login = await context.request.post(`${dashboardUrl}/auth/dev`, {
form: {
secret: env.AUTH_SECRET,
email: getWorkerEmail(email),
devPlan: devPlan ?? "",
},
headers: { "sec-fetch-site": "same-origin" },
maxRedirects: 0,
});
if (login.status() !== 302) {
throw new Error(`E2E dev login failed with HTTP ${login.status()}`);
}
} else if (loginPage.status() !== 302) {
throw new Error(`E2E login check failed with HTTP ${loginPage.status()}`);
}
const csrf = await context.request.get(
`${dashboardUrl}/dashboard?_data=routes/_ui`,
{
headers: {
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
},
email: getWorkerEmail(email),
devPlan: devPlan ?? "",
secret: env.AUTH_SECRET,
}
);
if (csrf.ok() === false) {
throw new Error(`E2E CSRF setup failed with HTTP ${csrf.status()}`);
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");
}
const project = await context.request.post(
`${dashboardUrl}/trpc/dashboardProject.create?batch=1`,
{
data: { 0: { title } },
headers: {
"sec-fetch-site": "same-origin",
"x-csrf-token": csrfToken,
},
}
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 }
);
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;
};
export const createContentModeProject = async ({
@@ -8,6 +8,7 @@ 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)
@@ -85,6 +86,15 @@ const startClient = () => {
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;
@@ -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 });
}
};
+10 -1
View File
@@ -5,6 +5,7 @@ import {
type BrowserContextOptions,
} from "@playwright/test";
import env from "../app/env/env.server";
import { closePreviewFormMcpClient } from "./flows/mcp-preview-submit";
const builderPort = process.env.PORT ?? "3000";
@@ -54,7 +55,15 @@ export const withBrowserContext = async <Result>(
}
};
export const test = base;
export const test = base.extend<{}, { mcpClientCleanup: void }>({
mcpClientCleanup: [
async ({}, use) => {
await use();
await closePreviewFormMcpClient();
},
{ scope: "worker", auto: true },
],
});
export const newIsolatedPage = async (browser: Browser) => {
const context = await newBrowserContext(browser);
@@ -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 });
}
});
@@ -955,6 +955,7 @@ const createManagedFormSocket = ({
unreadable = false,
navigationGap = false,
fastRedirect = false,
interceptedBodyUnreadable = false,
unrelated,
}: {
body?: string;
@@ -963,6 +964,7 @@ const createManagedFormSocket = ({
unreadable?: boolean;
navigationGap?: boolean | "stalled";
fastRedirect?: boolean;
interceptedBodyUnreadable?: boolean;
unrelated?: { method: string; url: string; frameId: string };
} = {}) => {
const url = "http://127.0.0.1:5173/contact";
@@ -1014,7 +1016,9 @@ const createManagedFormSocket = ({
socket.emit("message", {
data: JSON.stringify({
id: message.id,
result: { body, base64Encoded },
...(interceptedBodyUnreadable
? { error: { code: -32000, message: "Body unavailable" } }
: { result: { body, base64Encoded } }),
}),
}),
0
@@ -1207,6 +1211,31 @@ test("captures managed Form results before a fast redirect discards the network
}
});
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);
@@ -2582,9 +2582,9 @@ const submitFormWithBrowserRuntime = async (
interceptedManagedResponseBody = send<{
body?: string;
base64Encoded?: boolean;
}>("Fetch.getResponseBody", { requestId }).finally(() =>
send("Fetch.continueResponse", { requestId })
);
}>("Fetch.getResponseBody", { requestId })
.finally(() => send("Fetch.continueResponse", { requestId }))
.catch(() => undefined);
return;
}
}