fix: Keep publish audit warnings linked to instances (#6715)

Fixes #6714

Validate and Publish now use the same audit formatter, location details,
and instance links. This keeps messages consistent and preserves the
link from publisher findings. Free-plan location redaction remains
unchanged.

## Checklist

- [x] Use one shared mapper for local and publisher audit findings,
excluding info findings.
- [x] Add a Builder browser regression test for a published warning and
its **Show element** link.
- [x] Update publish-test fixtures to use the structured audit response
shape and SDK instance type.
- [x] Remove redundant Publish-dialog startup and repeated close/reopen
work from the session tests.
- [x] Allow the static integration test’s module setup extra time under
the full browser suite without changing global test timeouts.
- [x] Give only the three browser tests that exceeded the 15-second
shard limit a 30-second limit.
- [x] Review Builder publishing documentation; the existing paid-plan
element-link guidance already covers this behavior, so no documentation
change is needed.
- [x] Run Builder typecheck and lint.
- [x] Run Publish tests: 203 passed; focused changed files also pass 13
tests after the test-timeout changes.
- [ ] Confirm the Builder-core CI jobs pass after the repeated-publish
helper cleanup.
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-18 09:28:23 +01:00
1 parent 02f62eeaf2
commit 0fc5744719
8 files changed
+205 -100

No files matched your search

@@ -11,9 +11,13 @@ import {
} from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { createDefaultPages } from "@webstudio-is/project-build";
import type { Instance } from "@webstudio-is/sdk";
import {
createPublishAuditFinding,
createTrpcInterceptor,
selectStaticDestination,
selectTab,
} from "./publish-test-utils";
const reactEnvironment = globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean };
@@ -263,7 +267,7 @@ test("a rejected publish replaces an older success notice with its findings", as
publishResponse = {
success: false,
auditFindings: [{ severity: "error", message: "new audit failure" }],
auditFindings: [createPublishAuditFinding("new audit failure")],
};
const publishAgain = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
@@ -394,6 +398,8 @@ afterEach(() => {
act(() => {
root?.unmount();
stores.$project.set(undefined);
stores.$pages.set(undefined);
stores.$instances.set(new Map());
builderStates.$publishDialog.set("none");
});
root = undefined;
@@ -479,6 +485,96 @@ test("keeps Diagnostics visible but disabled before there is anything to show",
).toHaveLength(1);
});
test("publish audit warnings keep their instance links in Diagnostics", async () => {
const instanceId = "publish-warning-instance";
const pageId = "publish-warning-page";
stores.$pages.set(
createDefaultPages({ rootInstanceId: instanceId, homePageId: pageId })
);
stores.$instances.set(
new Map([
[
instanceId,
{
type: "instance",
id: instanceId,
component: "Box",
children: [],
} satisfies Instance,
],
])
);
nanoStates.$planFeatures.set({
...nanoStates.$planFeatures.get(),
allowPublishLogs: true,
});
jobStatus = "success";
publishResponse = {
success: true,
buildId: "build-1",
findings: [
{
ruleId: "html-content-model",
severity: "warning",
message: "A child does not match the element's content model.",
location: {
pageId,
pageName: "Home",
pagePath: "/",
instanceId,
instanceSelector: [instanceId],
},
},
],
};
await mount();
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
)!;
if (domain.checked === false) {
await act(async () =>
document.body.querySelector<HTMLElement>('[role="checkbox"]')?.click()
);
}
const publish = Array.from(
document.body.querySelectorAll<HTMLButtonElement>("button")
)
.filter((button) => button.textContent?.trim() === "Publish")
.at(-1)!;
await act(async () => publish.click());
await waitFor(() =>
expect(document.body.textContent).toContain("Published successfully.")
);
await act(async () =>
document.body
.querySelector<HTMLButtonElement>('button[aria-label="Publish options"]')
?.dispatchEvent(
new PointerEvent("pointerdown", {
bubbles: true,
pointerType: "mouse",
})
)
);
await act(async () =>
Array.from(document.body.querySelectorAll<HTMLElement>("[role=menuitem]"))
.find((item) => item.textContent?.trim() === "Diagnostics")
?.click()
);
await waitFor(() =>
expect(document.body.querySelector('[role="dialog"]')).not.toBeNull()
);
await selectTab("Warnings");
const link = document.body.querySelector<HTMLAnchorElement>(
'a[href*="instance=publish-warning-instance"]'
);
expect(link?.textContent).toBe("Show element");
expect(document.body.textContent).toContain(
`Publish warning for "Home" (/): A child does not match the element's content model.`
);
});
test.each([
["Validate", "Errors", false],
["Publish", "Errors", false],
@@ -15,6 +15,7 @@ import { createAssetContentSession } from "@webstudio-is/content-engine/asset-co
import type { Project } from "@webstudio-is/project";
import type { Pages } from "@webstudio-is/sdk";
import {
createPublishAuditFinding,
createTrpcInterceptor,
deferred,
selectTab,
@@ -308,7 +309,7 @@ test.each([
await act(async () => {
dispatch.resolve({
success: false,
auditFindings: [{ severity: "error", message: "server rejection" }],
auditFindings: [createPublishAuditFinding("server rejection")],
});
await dispatch.promise;
});
@@ -339,7 +340,7 @@ test("static audit rejection notifies after Export closes", async () => {
await act(async () => {
dispatch.resolve({
success: false,
auditFindings: [{ severity: "error", message: "server rejection" }],
auditFindings: [createPublishAuditFinding("server rejection")],
});
await dispatch.promise;
});
@@ -600,7 +601,7 @@ test("static check failure stays in the Export alert without a toast", async ()
await act(async () => {
dispatch.resolve({
success: false,
auditFindings: [{ severity: "error", message: "server rejection" }],
auditFindings: [createPublishAuditFinding("server rejection")],
});
await dispatch.promise;
});
@@ -770,7 +771,7 @@ test.each([
failure === "audit"
? {
success: false,
auditFindings: [{ severity: "error", message }],
auditFindings: [createPublishAuditFinding(message)],
}
: { success: false, error: message }
);
@@ -14,6 +14,7 @@ import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import { createAssetContentSession } from "@webstudio-is/content-engine/asset-content-session";
import {
createPublishAuditFinding,
createTrpcInterceptor,
deferred,
selectTab,
@@ -769,7 +770,7 @@ test.each(["site", "static"] as const)(
let target: "site" | "static" = first;
publish = async () => ({
success: false,
auditFindings: [{ severity: "error", message: `${target} diagnostic` }],
auditFindings: [createPublishAuditFinding(`${target} diagnostic`)],
});
await mount();
if (first === "static") {
@@ -179,7 +179,7 @@ beforeEach(() => {
allowPublishLogs: true,
});
stores.$project.set(project("project-1"));
publishDialog.set("publish");
publishDialog.set("none");
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
@@ -233,9 +233,11 @@ const setPaid = async (allowPublishLogs: boolean) => {
})
);
};
const publish = async () => {
await act(async () => publishDialog.set("none"));
await act(async () => publishDialog.set("publish"));
const publish = async (timeout = 10_000) => {
if (document.body.querySelector('input[name="domainToPublish[]"]') === null) {
await act(async () => publishDialog.set("none"));
await act(async () => publishDialog.set("publish"));
}
const domain = document.body.querySelector<HTMLInputElement>(
'input[name="domainToPublish[]"]'
);
@@ -252,14 +254,17 @@ const publish = async () => {
?.closest("form")
?.querySelectorAll<HTMLButtonElement>("button") ?? []
).at(-1);
await waitFor(() => expect(getButton()?.disabled).toBe(false));
await waitFor(() => expect(getButton()?.disabled).toBe(false), timeout);
const previousRequests = publishRequests;
await act(async () => {
const button = getButton();
expect(button).toBeDefined();
button?.click();
});
await waitFor(() => expect(publishRequests).toBe(previousRequests + 1));
await waitFor(
() => expect(publishRequests).toBe(previousRequests + 1),
timeout
);
};
const openReport = async () => {
await act(async () =>
@@ -338,7 +343,7 @@ test("retries pending and failed log reads before giving up on the session", asy
undefined,
1,
]);
});
}, 30_000);
test("Free does not fetch logs; upgrading reads UTF-8 from byte zero and preserves issue severity", async () => {
await setPaid(false);
@@ -366,7 +371,7 @@ test("Free does not fetch logs; upgrading reads UTF-8 from byte zero and preserv
expect(panel().textContent).not.toContain("Late error");
expect(panel().textContent).not.toContain("Early warning");
expect(document.body.querySelector("pre")).toBeNull();
});
}, 30_000);
test("an accepted publish without a log handle is retained without retrying dispatch or reading logs", async () => {
withHandle = false;
@@ -382,32 +387,33 @@ test("a paid response after downgrade cannot restore logs; upgrading restarts fr
holdLog = { cursor: 1, response: deferred<void>() };
await render();
await publish();
await waitFor(() => expect(logRequests).toHaveLength(2));
await waitFor(() => expect(logRequests).toHaveLength(2), 20_000);
await openReport();
await setPaid(false);
await act(async () => holdLog?.response.resolve());
expect(panel().querySelector("pre")).toBeNull();
await setPaid(true);
await waitFor(() =>
expect(panel().querySelector("pre")?.textContent).toBe("€")
await waitFor(
() => expect(panel().querySelector("pre")?.textContent).toBe("€"),
20_000
);
expect(logRequests.slice(2).map(({ cursor }) => cursor)).toEqual([
undefined,
1,
]);
});
}, 60_000);
test("a log response from the previous project cannot populate the new project's report", async () => {
holdLog = { response: deferred<void>() };
await render();
await publish();
await waitFor(() => expect(logRequests).toHaveLength(1));
await waitFor(() => expect(logRequests).toHaveLength(1), 20_000);
await changeProject("project-2");
await act(async () => holdLog?.response.resolve());
await openReport();
expect(entries()).toHaveLength(0);
expect(logRequests).toHaveLength(1);
});
}, 45_000);
test("a dispatch accepted after leaving and returning to its project cannot restore the old session", async () => {
heldPublish = deferred<unknown>();
@@ -426,7 +432,7 @@ test("a dispatch accepted after leaving and returning to its project cannot rest
await openReport();
expect(entries()).toHaveLength(0);
expect(logRequests).toHaveLength(0);
});
}, 30_000);
test("keeping ten publishes evicts an older in-flight reader before its next page", async () => {
holdLog = { response: deferred<void>() };
@@ -435,7 +441,7 @@ test("keeping ten publishes evicts an older in-flight reader before its next pag
await waitFor(() => expect(logRequests).toHaveLength(1));
for (let index = 0; index < 10; index++) {
buildId = `new-build-${index}`;
await publish();
await publish(20_000);
}
await act(async () => holdLog?.response.resolve());
await openReport();
@@ -444,4 +450,4 @@ test("keeping ten publishes evicts an older in-flight reader before its next pag
expect(
logRequests.filter((request) => request.buildId === "build-1")
).toHaveLength(1);
}, 30_000);
}, 60_000);
@@ -4,6 +4,7 @@ import { afterAll, afterEach, beforeAll, expect, test, vi } from "vitest";
import { TooltipProvider, toast } from "@webstudio-is/design-system";
import type { Project } from "@webstudio-is/project";
import {
createPublishAuditFinding,
createTrpcInterceptor,
selectStaticDestination,
} from "./publish-test-utils";
@@ -80,7 +81,7 @@ beforeAll(async () => {
projectStore = (await import("~/shared/sync/data-stores")).$project;
const { updateCsrfToken } = await import("~/shared/csrf.client");
updateCsrfToken("test-token");
});
}, 60_000);
afterEach(async () => {
await act(async () => root?.unmount());
@@ -121,13 +122,13 @@ const staticButton = () =>
(button) => button.textContent?.startsWith("Build and download static site")
);
const waitFor = <T,>(assertion: () => T | Promise<T>) =>
const waitFor = <T,>(assertion: () => T | Promise<T>, timeout = 10_000) =>
vi.waitFor(
async () => {
await act(async () => {});
await assertion();
},
{ timeout: 10_000 }
{ timeout }
);
const render = async (open: boolean, projectId = "project-a") => {
@@ -162,7 +163,6 @@ test("reopening an active static publish keeps one status owner and one download
buildStatus = "PENDING";
projectStore.set(createProject());
await render(true);
vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"] });
const button = staticButton();
expect(button).toBeDefined();
await act(async () => button?.click());
@@ -179,11 +179,10 @@ test("reopening an active static publish keeps one status owner and one download
)
).toBeNull();
getJobStatus = "success";
await act(async () => vi.advanceTimersByTimeAsync(15_000));
await waitFor(async () => {
await act(async () => {});
expect(downloads).toHaveBeenCalledOnce();
});
}, 30_000);
expect(downloads).toHaveBeenCalledExactlyOnceWith("/cgi/static/ssg/site.zip");
expect(staticButton()?.dataset.state).not.toBe("pending");
expect(staticButton()?.disabled).toBe(false);
@@ -191,7 +190,7 @@ test("reopening an active static publish keeps one status owner and one download
expect(document.body.textContent).toContain("Downloaded");
expect(publishRequests).toBe(1);
expect(jobRequests).toBe(2);
}, 30_000);
}, 60_000);
test("a persisted static failure remains visible without session diagnostics", async () => {
projectStore.set({
@@ -234,7 +233,7 @@ test("project navigation suppresses an old static download and error toast", asy
await act(async () => vi.advanceTimersByTimeAsync(1_000));
expect(downloads).not.toHaveBeenCalled();
expect(errorToast).not.toHaveBeenCalled();
});
}, 30_000);
test("a failed static runner clears progress without starting a download", async () => {
const errorToast = vi.spyOn(toast, "error").mockImplementation(() => "");
@@ -311,7 +310,7 @@ test("the static failure alert opens an audit rejection instead of an older succ
});
staticResponse = {
success: false,
auditFindings: [{ severity: "error", message: "audit-rejection" }],
auditFindings: [createPublishAuditFinding("audit-rejection")],
};
await act(async () => staticButton()?.click());
await waitFor(() => expect(publishRequests).toBe(2));
@@ -2,6 +2,16 @@ import { FetchInterceptor } from "@mswjs/interceptors/fetch";
import { act } from "react-dom/test-utils";
import { expect, vi } from "vitest";
export const createPublishAuditFinding = (
message: string,
severity: "error" | "warning" = "error"
) => ({
ruleId: "test-rule",
severity,
message,
location: {},
});
export const selectTab = async (name: string) => {
const tab = Array.from(
document.body.querySelectorAll<HTMLElement>('[role="tab"]')
@@ -5,6 +5,7 @@ import {
findPageAndSelectorByInstanceId,
formatPrePublishAuditFinding,
runPrePublishAudit,
type PrePublishAuditFinding,
} from "@webstudio-is/project-build/runtime";
import {
$registeredComponentMetas,
@@ -92,54 +93,64 @@ const PrePublishInstanceLink = ({
);
};
const getPrePublishAuditFindings = (): DiagnosticFinding[] => {
const findings = runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
props: $props.get(),
dataSources: $dataSources.get(),
resources: $resources.get(),
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
});
return findings.flatMap((finding) => {
if (finding.severity !== "error" && finding.severity !== "warning") {
return [];
}
const context = Object.entries(finding.location)
.filter(
([key, value]) => key !== "instanceSelector" && value !== undefined
)
.map(([key, value]) => `${key}: ${value}`);
const reportText = [
`${finding.severity.toUpperCase()}: ${formatPrePublishAuditFinding(
finding
)}`,
type DiagnosticPrePublishAuditFinding = PrePublishAuditFinding & {
severity: "error" | "warning";
};
const toPrePublishDiagnosticFinding = (
finding: DiagnosticPrePublishAuditFinding
): DiagnosticFinding => {
const title = formatPrePublishAuditFinding(finding);
const context = Object.entries(finding.location)
.filter(([key, value]) => key !== "instanceSelector" && value !== undefined)
.map(([key, value]) => `${key}: ${value}`);
return {
severity: finding.severity,
source: "audit",
title,
summary: title.slice(0, 160),
link:
finding.location.instanceId === undefined ? undefined : (
<PrePublishInstanceLink
instanceId={finding.location.instanceId}
pageId={finding.location.pageId}
instanceSelector={finding.location.instanceSelector}
>
Show element
</PrePublishInstanceLink>
),
details: context.length === 0 ? undefined : context.join(" · "),
reportText: [
`${finding.severity.toUpperCase()}: ${title}`,
`Rule: ${finding.ruleId}`,
...context,
].join("\n");
return [
{
severity: finding.severity,
title: formatPrePublishAuditFinding(finding),
summary: formatPrePublishAuditFinding(finding).slice(0, 160),
link:
finding.location.instanceId === undefined ? undefined : (
<PrePublishInstanceLink
instanceId={finding.location.instanceId}
pageId={finding.location.pageId}
instanceSelector={finding.location.instanceSelector}
>
Show element
</PrePublishInstanceLink>
),
details: context.length === 0 ? undefined : context.join(" · "),
reportText,
},
];
});
].join("\n"),
};
};
export const getPublishAuditFindings = (
findings: readonly PrePublishAuditFinding[]
): DiagnosticFinding[] =>
findings
.filter(
(finding): finding is DiagnosticPrePublishAuditFinding =>
finding.severity === "error" || finding.severity === "warning"
)
.map(toPrePublishDiagnosticFinding);
const getPrePublishAuditFindings = (): DiagnosticFinding[] =>
getPublishAuditFindings(
runPrePublishAudit({
pages: $pages.get(),
instances: $instances.get(),
props: $props.get(),
dataSources: $dataSources.get(),
resources: $resources.get(),
assets: $assets.get(),
metas: $registeredComponentMetas.get(),
})
);
export const runPublishDiagnostics = async (
projectId: Project["id"],
domains?: string[]
@@ -240,22 +251,3 @@ export const reportPublishValidationFailure = (
},
]);
};
export const getServerPublishFindings = (
findings: readonly {
severity: "error" | "warning" | "info";
message: string;
}[]
): DiagnosticFinding[] =>
findings.flatMap((finding) =>
finding.severity === "info"
? []
: [
{
severity: finding.severity,
title: finding.message,
summary: finding.message,
reportText: `${finding.severity.toUpperCase()}: ${finding.message}`,
},
]
);
@@ -53,7 +53,7 @@ import {
runPublishDiagnostics,
runPublishValidation,
reportPublishValidationFailure,
getServerPublishFindings,
getPublishAuditFindings,
} from "./publish-validation";
import { runPublishAfterBestEffortChecks } from "./publish-preflight";
import { getPublishStatusDisplay } from "./publish-status";
@@ -958,7 +958,7 @@ export const PublishButton = ({ projectId }: PublishProps) => {
if ("auditFindings" in publishResult) {
diagnostics.finish((findings) => [
...findings,
...getServerPublishFindings(publishResult.auditFindings),
...getPublishAuditFindings(publishResult.auditFindings),
]);
return;
}
@@ -1011,7 +1011,7 @@ export const PublishButton = ({ projectId }: PublishProps) => {
logHandle: publishResult.logHandle,
target: "site",
domains,
findings: getServerPublishFindings(publishResult.findings),
findings: getPublishAuditFindings(publishResult.findings),
});
const outcome = await waitForCompletion(accepted, previousBuildId);
reportPublishResult({
@@ -1064,7 +1064,7 @@ export const PublishButton = ({ projectId }: PublishProps) => {
if ("auditFindings" in publishResult) {
diagnostics.finish((findings) => [
...findings,
...getServerPublishFindings(publishResult.auditFindings),
...getPublishAuditFindings(publishResult.auditFindings),
]);
if ($publishDialog.get() !== "export") {
toast.error(
@@ -1089,7 +1089,7 @@ export const PublishButton = ({ projectId }: PublishProps) => {
logHandle: publishResult.logHandle,
target: "static",
domains: [],
findings: getServerPublishFindings(publishResult.findings),
findings: getPublishAuditFindings(publishResult.findings),
staticName: "name" in publishResult ? publishResult.name : undefined,
});
if (accepted?.staticName == null) {