fix: improve screenshot diagnostics and CSS validation (#6696)

## What changed

- Report a safe generated script path and line number, plus the saved
screenshot artifact, when a page exception makes screenshot capture
fail. Private routes and non-script files are omitted.
- Generate parenthesized `all` media conditions without extra wrapping
so publish validation accepts single and compound conditions.

## Verification

- CSS engine tests: 12 passed
- Publish validation tests: 54 passed
- Screenshot CDP tests: 62 passed
- MCP preview tests: 50 passed
- Typechecks, lint, and formatting passed

Fixes #6671
Fixes #6691
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-15 14:58:05 +01:00
1 parent 35e77d845f
commit cdca13c755
7 files changed
+197 -21

No files matched your search

@@ -1445,6 +1445,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(
+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 }),
},
],
});
@@ -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 {
@@ -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);
}
@@ -461,7 +464,9 @@ class FakeWebSocket {
this.runtimeErrorScenario === "exception-error"
? executionContextId
: 1,
url: "https://example.com/assets/exception.js?token=private",
url:
this.exceptionUrl ??
"https://user:pass@example.com/assets/exception.js?token=private#fragment",
lineNumber: 6,
},
}
@@ -2429,7 +2434,7 @@ test("does not treat console.error as an uncaught page exception", async () => {
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",
@@ -2455,7 +2460,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 () => {
@@ -2496,6 +2543,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();
});
@@ -2537,6 +2587,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();
});
+48 -2
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) => {
@@ -1847,6 +1887,7 @@ const capturePageWithBrowserRuntime = async (
activeExecutionContextIds
);
javascriptErrorPresent = false;
javascriptErrorLocation = undefined;
navigationExecutionContextFrames = new Map();
navigationErrorsByContextId.clear();
activeExecutionContextIds = new Set();
@@ -1890,6 +1931,8 @@ const capturePageWithBrowserRuntime = async (
for (const executionContextId of activeExecutionContextIds) {
if (navigationErrorsByContextId.has(executionContextId)) {
javascriptErrorPresent = true;
javascriptErrorLocation ??=
navigationErrorsByContextId.get(executionContextId);
}
}
navigationExecutionContextFrames = undefined;
@@ -2113,6 +2156,9 @@ const capturePageWithBrowserRuntime = async (
redirects,
...readiness,
...(javascriptErrorPresent ? { javascriptErrorPresent: true } : {}),
...(javascriptErrorPresent && javascriptErrorLocation !== undefined
? { javascriptErrorLocation }
: {}),
};
if (images === undefined) {
delete layout.images;