fix: Persist nested MDX heading edits after refresh (#6707)

Nested headings inside MDX templates should save and remain after
refresh. PR #6692 did not fix that persistence failure.

The staging repro showed the MDX serializer rejecting an unchanged Asset
record. The live record and saved record can have different JavaScript
prototypes while representing the same JSON data, so the raw deep
comparison rejected a valid edit. Reconciliation now compares normalized
JSON data.

Known authored Asset props and path-mapped template assets remain
supported. Unmapped, unreferenced template Asset records are still
rejected; the staging repro did not need a broader provenance-based
exception.

The save status remains pending until the MDX Asset write completes,
even if the last Content Block root unmounts. Failed or conflicting
writes remain visible as errors and keep the unload guard active.

## Checklist
- [x] Add a Builder E2E regression test for nested heading persistence
through the MDX Asset.
- [x] Track Asset saves independently of mounted Content Block roots.
- [x] Keep failed/conflicting Asset writes visible and guarded.
- [x] Preserve authored Asset props and path-mapped template assets
during MDX text edits.
- [x] Add regression tests for omitted asset records and continue
rejecting unknown or modified assets.
- [x] Confirm the asset comparison regression test fails with the
previous comparator and passes with the fix.
- [x] Review Content Block docs; no documentation changes are needed.
- [x] Run the focused MDX suite (62 passed), project-build typecheck,
oxlint, formatter, and diff checks.
- [x] Add the generated Builder E2E schema snapshot required by CI.
- [x] Remove temporary diagnostics and the unneeded broader provenance
exception.
- [x] Verify nested heading persistence on staging after the latest
deployment.
- [x] Verify required CI checks for this staging branch; all passed.

Replaces #6706
Ref #6306
This commit is contained in:
Oleg Isonen authored and GitHub committed 2026-11-17 00:30:11 +01:00
1 parent baeaab904f
commit c4b26b4173
13 files changed
+2332 -13

No files matched your search

@@ -3,6 +3,11 @@ import { createRoot, type Root } from "react-dom/client";
import { act } from "react-dom/test-utils";
import { afterEach, describe, expect, test, vi } from "vitest";
import { $syncStatus } from "@webstudio-is/sync-client";
import {
$externalContentRoots,
$externalContentAssetStatuses,
} from "~/shared/external-content-mutations";
import { usePreventUnload } from "~/shared/sync/project-queue";
import { SyncStatusDot } from "./sync-status";
(
@@ -38,6 +43,8 @@ afterEach(() => {
root = undefined;
document.body.innerHTML = "";
$syncStatus.set({ status: "idle" });
$externalContentRoots.set(new Map());
$externalContentAssetStatuses.set(new Map());
vi.useRealTimers();
});
@@ -62,6 +69,59 @@ describe("SyncStatusDot", () => {
);
});
test("keeps pending status until an MDX Asset save completes", () => {
const { getDot } = renderSyncStatusDot();
act(() => {
$externalContentAssetStatuses.set(new Map([["asset", "pending"]]));
});
expect(getDot().getAttribute("data-sync-status")).toBe("pending");
act(() => {
$externalContentAssetStatuses.set(new Map([["asset", "saving"]]));
});
expect(getDot().getAttribute("data-sync-status")).toBe("pending");
act(() => {
$externalContentAssetStatuses.set(new Map());
});
expect(getDot().getAttribute("data-sync-status")).toBe("saved");
});
test("keeps pending status when the last MDX root unmounts", () => {
const { getDot } = renderSyncStatusDot();
act(() => {
$externalContentRoots.set(
new Map([
[
"block",
{
blockInstanceId: "block",
instanceIds: new Set<string>(),
mutationRevision: 1,
savedMutationRevision: 0,
},
],
])
);
$externalContentAssetStatuses.set(new Map([["asset", "pending"]]));
});
act(() => {
$externalContentRoots.set(new Map());
});
expect(getDot().getAttribute("data-sync-status")).toBe("pending");
});
test.each(["failed", "conflicting"] as const)(
"renders an MDX Asset %s status as an error",
(assetContentStatus) => {
const { getDot } = renderSyncStatusDot();
act(() => {
$externalContentAssetStatuses.set(
new Map([["asset", assetContentStatus]])
);
});
expect(getDot().getAttribute("data-sync-status")).toBe("error");
}
);
test("renders saved status briefly after pending changes become idle", () => {
vi.useFakeTimers();
const { getDot } = renderSyncStatusDot();
@@ -103,3 +163,24 @@ describe("SyncStatusDot", () => {
);
});
});
test("warns before unloading while an MDX Asset save is pending", () => {
const Guard = () => {
usePreventUnload();
return null;
};
root = createRoot(document.createElement("div"));
act(() => root?.render(createElement(Guard)));
act(() => {
$externalContentAssetStatuses.set(new Map([["asset", "pending"]]));
});
const event = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(event);
expect(event.defaultPrevented).toBe(true);
act(() => {
$externalContentAssetStatuses.set(new Map([["asset", "failed"]]));
});
const failedEvent = new Event("beforeunload", { cancelable: true });
window.dispatchEvent(failedEvent);
expect(failedEvent.defaultPrevented).toBe(true);
});
@@ -12,6 +12,7 @@ import {
} from "@webstudio-is/design-system";
import { OfflineIcon } from "@webstudio-is/icons";
import { $hasUnsavedSyncChanges, $syncStatus } from "@webstudio-is/sync-client";
import { $externalContentAssetStatuses } from "~/shared/external-content-mutations";
const syncStatusDotSavedDuration = 2000;
const syncStatusDotPendingColor = cssVar("--foreground-warning");
@@ -55,13 +56,23 @@ const subscribeIsOnline = () => {
export const SyncStatusDot = () => {
const statusObject = useStore($syncStatus);
const hasUnsavedSyncChanges = useStore($hasUnsavedSyncChanges);
const externalContentAssetStatuses = useStore($externalContentAssetStatuses);
const hasUnsavedChanges =
hasUnsavedSyncChanges || externalContentAssetStatuses.size > 0;
const hasExternalContentError = Array.from(
externalContentAssetStatuses.values()
).some((status) => status === "failed" || status === "conflicting");
const hadUnsavedSyncChangesRef = useRef(false);
const savedTimeoutRef = useRef<ReturnType<typeof setTimeout>>();
const [savedUntil, setSavedUntil] = useState(0);
let visibleStatus: SyncStatusDotStatus = "idle";
if (statusObject.status === "failed" || statusObject.status === "fatal") {
if (
statusObject.status === "failed" ||
statusObject.status === "fatal" ||
hasExternalContentError
) {
visibleStatus = "error";
} else if (hasUnsavedSyncChanges) {
} else if (hasUnsavedChanges) {
visibleStatus = "pending";
} else if (Date.now() < savedUntil) {
visibleStatus = "saved";
@@ -73,7 +84,7 @@ export const SyncStatusDot = () => {
: statusConfig.label;
useEffect(() => {
if (hasUnsavedSyncChanges) {
if (hasUnsavedChanges) {
hadUnsavedSyncChangesRef.current = true;
return;
}
@@ -89,7 +100,7 @@ export const SyncStatusDot = () => {
setSavedUntil(0);
}, syncStatusDotSavedDuration);
}
}, [hasUnsavedSyncChanges, statusObject.status]);
}, [hasUnsavedChanges, statusObject.status]);
useEffect(() => {
return () => clearTimeout(savedTimeoutRef.current);
@@ -25,6 +25,7 @@ import type {
MdxTemplateInsertion,
} from "@webstudio-is/project-build/runtime";
import type { MdxDocument } from "@webstudio-is/content-engine/mdx";
import type { AssetContentSessionState } from "@webstudio-is/content-engine/asset-content-session";
import { atom, type ReadableAtom } from "nanostores";
import type { ExternalContentOwnership } from "./external-content-persistence";
import type { FrontmatterSource } from "./content-block-document";
@@ -176,6 +177,9 @@ export const getExternalContentSourceSelector = ({
export const $externalContentRoots = atom(
new Map<string, ExternalContentRoot>()
);
export const $externalContentAssetStatuses = atom(
new Map<string, AssetContentSessionState["status"]>()
);
const mutationListeners = new Set<(rootKeys: readonly string[]) => void>();
const templateMutationListeners = new Set<
(rootKeys: readonly string[]) => void
@@ -42,6 +42,7 @@ import {
selectPage,
} from "./nano-states";
import {
$externalContentAssetStatuses,
findExternalContentRoot,
getExternalContentRoots,
resolveExternalContentOccurrence,
@@ -2162,6 +2163,9 @@ test("finishes a queued canvas save after its external root is released", async
});
release();
expect($externalContentAssetStatuses.get().get('["project","asset"]')).toBe(
"pending"
);
continueUpdate?.();
await blockingUpdate;
await flushExternalContentAsset({ projectId: "project", assetId: asset.id });
@@ -2169,6 +2173,9 @@ test("finishes a queued canvas save after its external root is released", async
expect(statuses).not.toContain("failed");
expect(writes).toEqual(["# Stale update\n"]);
expect($externalContentAssetStatuses.get().has('["project","asset"]')).toBe(
false
);
});
test("retains a failed queued update when project teardown cannot drain it", async () => {
@@ -2225,6 +2232,11 @@ test("retains a failed queued update when project teardown cannot drain it", asy
update,
})
).rejects.toThrow("Temporary serialization failure");
expect(
$externalContentAssetStatuses
.get()
.get('["teardown-project","teardown-asset"]')
).toBe("failed");
await expect(
disposeExternalContentProject({
projectId: teardownAsset.projectId!,
@@ -2247,6 +2259,11 @@ test("retains a failed queued update when project teardown cannot drain it", asy
projectId: teardownAsset.projectId!,
session,
});
expect(
$externalContentAssetStatuses
.get()
.has('["teardown-project","teardown-asset"]')
).toBe(false);
});
test("retains pending content when the repository write fails during teardown", async () => {
@@ -62,6 +62,7 @@ import type {
import { getAssetContentBridge } from "./asset-content-bridge.client";
import {
$externalContentRoots,
$externalContentAssetStatuses,
clearExternalContentTemplateInsertions,
getAffectedExternalContentTemplateRootKeys,
getExternalContentRoots,
@@ -195,6 +196,40 @@ const assetQueues = new Map<string, AssetQueue>();
const subscribedSessions = new WeakSet<AssetContentSession>();
const getAssetQueueKey = (projectId: string, assetId: string) =>
JSON.stringify([projectId, assetId]);
const publishAssetSaveStatus = ({
projectId,
assetId,
status,
queue,
}: {
projectId: string;
assetId: string;
status: AssetContentSessionState["status"] | undefined;
queue?: AssetQueue;
}) => {
const key = getAssetQueueKey(projectId, assetId);
const next = new Map($externalContentAssetStatuses.get());
const visibleStatus = queue?.error
? "failed"
: status === "failed" || status === "conflicting"
? status
: (queue?.pendingSnapshots ?? 0) > 0
? "pending"
: status;
if (
(visibleStatus === "saved" || visibleStatus === undefined
? undefined
: visibleStatus) === next.get(key)
) {
return;
}
if (visibleStatus === "saved" || visibleStatus === undefined) {
next.delete(key);
} else {
next.set(key, visibleStatus);
}
$externalContentAssetStatuses.set(next);
};
const getRootKey = (
projectId: string,
sourceBlockInstanceId: string,
@@ -962,6 +997,13 @@ const getSession = (projectId: string) => {
subscribedSessions.add(session);
session.subscribe((assetId, state) => {
const queueKey = getAssetQueueKey(projectId, assetId);
const queue = assetQueues.get(queueKey);
publishAssetSaveStatus({
projectId,
assetId,
status: state.status,
queue,
});
if (state.status === "conflicting") {
getAssetContentBridge().requireReload(
state.error?.message ??
@@ -969,7 +1011,6 @@ const getSession = (projectId: string) => {
);
return;
}
const queue = assetQueues.get(queueKey);
if ((queue?.pendingSnapshots ?? 0) === 0 && queue?.error === undefined) {
void rematerializeAsset(
projectId,
@@ -1058,6 +1099,12 @@ const enqueueAssetUpdate = ({
queue.pendingSnapshots += 1;
queue.error = undefined;
publishAssetQueueError(queue);
publishAssetSaveStatus({
projectId,
assetId,
status: session.get(assetId)?.status,
queue,
});
const saving = queue.serialization.then(async () => {
const state = session.get(assetId);
if (state === undefined) {
@@ -1098,6 +1145,12 @@ const enqueueAssetUpdate = ({
queue.failedPreservedRootKey = undefined;
queue.error = undefined;
publishAssetQueueError(queue);
publishAssetSaveStatus({
projectId,
assetId,
status: session.get(assetId)?.status,
queue,
});
},
(error) => {
queue.failedUpdate = update;
@@ -1110,6 +1163,12 @@ const enqueueAssetUpdate = ({
getAssetContentBridge().requireReload(queue.error.message);
}
publishAssetQueueError(queue);
publishAssetSaveStatus({
projectId,
assetId,
status: session.get(assetId)?.status,
queue,
});
throw queue.error;
}
);
@@ -1117,6 +1176,12 @@ const enqueueAssetUpdate = ({
.catch(() => {})
.then(async () => {
queue.pendingSnapshots -= 1;
publishAssetSaveStatus({
projectId,
assetId,
status: session.get(assetId)?.status,
queue,
});
if (queue.pendingSnapshots === 0 && succeeded) {
const state = session.get(assetId);
if (state !== undefined) {
@@ -2210,6 +2275,13 @@ export const disposeExternalContentProject = async ({
}
}
subscribedSessions.delete(session);
const assetStatuses = new Map($externalContentAssetStatuses.get());
for (const key of assetStatuses.keys()) {
if ((JSON.parse(key) as [string, string])[0] === projectId) {
assetStatuses.delete(key);
}
}
$externalContentAssetStatuses.set(assetStatuses);
const history = new Map($externalContentHistory.get());
history.delete(projectId);
$externalContentHistory.set(history);
@@ -15,6 +15,7 @@ import {
type SyncStatus,
} from "@webstudio-is/sync-client";
import { publicStaticEnv } from "~/env/env.static";
import { $externalContentAssetStatuses } from "~/shared/external-content-mutations";
import { createNativeClient, nativeClient } from "~/shared/trpc/trpc-client";
import * as commandQueue from "./command-queue";
import type { SyncStorage } from "~/shared/sync-client";
@@ -420,7 +421,10 @@ export const isSyncIdle = () => {
export const usePreventUnload = () => {
useEffect(() => {
const handler = (event: BeforeUnloadEvent) => {
if ($hasUnsavedSyncChanges.get() === false) {
if (
$hasUnsavedSyncChanges.get() === false &&
$externalContentAssetStatuses.get().size === 0
) {
return;
}
event.preventDefault();
+8 -1
View File
@@ -88,7 +88,10 @@ import {
areInstanceSelectorsEqual,
type InstanceSelector,
} from "@webstudio-is/project-build/runtime";
import { $externalContentRoots } from "../external-content-mutations";
import {
$externalContentRoots,
$externalContentAssetStatuses,
} from "../external-content-mutations";
import { $externalContentHistory } from "../external-content-history";
enableMapSet();
@@ -417,6 +420,10 @@ export const createObjectPool = () => {
new NanostoresSyncObject("canvasScrollbarWidth", $canvasScrollbarSize),
new NanostoresSyncObject("systemDataByPage", $systemDataByPage),
new NanostoresSyncObject("externalContentRoots", $externalContentRoots),
new NanostoresSyncObject(
"externalContentAssetStatuses",
$externalContentAssetStatuses
),
new NanostoresSyncObject("externalContentHistory", $externalContentHistory),
]);
};
@@ -0,0 +1,11 @@
<ServiceCard>
<CardShell>
<CardText>
<h3>
JÄRKI <br />
myyntistrategian <br />
perustukset
</h3>
</CardText>
</CardShell>
</ServiceCard>
@@ -95,6 +95,33 @@ export const configureNamedTemplateLifecycle = async (projectId: string) => {
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
export const configureNestedHeadingTemplates = async (projectId: string) => {
const { build, instances } = await getBuildData(projectId);
const templates = instances.find((instance) => instance.id === templateId);
if (templates === undefined) {
throw new Error("Expected the Content Block templates fixture instance");
}
const nestedTemplates = [
{ id: "service-card-template", name: "ServiceCard", tag: "a" },
{ id: "card-shell-template", name: "CardShell", tag: "div" },
{ id: "card-text-template", name: "CardText", tag: "div" },
];
templates.children.push(
...nestedTemplates.map(({ id }) => ({ type: "id", value: id }))
);
instances.push(
...nestedTemplates.map(({ id, name, tag }) => ({
type: "instance" as const,
id,
component: "ws:element",
tag,
name,
children: [{ type: "text", value: "Template default" }],
}))
);
await updateBuild(build.id, { instances: JSON.stringify(instances) });
};
const configureSourceBlock = ({
instances,
props,
File diff suppressed because it is too large. Load diff
@@ -4,6 +4,7 @@ import {
configureDynamicDetailContentBlock,
configureEmptyHeadingTemplate,
configureNamedTemplateLifecycle,
configureNestedHeadingTemplates,
configureRepresentableContentBlockBody,
configureRepeatedContentBlock,
} from "../fixtures/mdx-content-block-project";
@@ -46,6 +47,7 @@ const alternateFilename = "alternate-source.mdx";
const unresolvedFilename = "unresolved-source.mdx";
const namedTemplateFilename = "named-template-source.mdx";
const emptyFilename = "empty-source.mdx";
const nestedHeadingFilename = "nested-heading-source.mdx";
const sourceHeading = "MDX source heading";
const editedHeading = "Edited MDX source heading";
@@ -180,6 +182,60 @@ const openFixture = async ({
await waitForSyncStatus({ page, status: "idle" });
};
test("Nested MDX heading edits survive immediate Builder reload", async ({
page,
context,
}) => {
const fixture = await createContentModeProject({
context,
devPlan: e2ePaidPlanName,
email: "mdx-nested-heading-e2e@webstudio.test",
title: "MDX Nested Heading E2E",
});
await configureRepresentableContentBlockBody(fixture.projectId);
await configureNestedHeadingTemplates(fixture.projectId);
await openFixture({
page,
projectId: fixture.projectId,
authToken: fixture.builderToken,
});
await openAssetsPanel({ page });
await uploadAsset({ page, filename: nestedHeadingFilename });
await selectContentBlock({ page });
await chooseContentBlockSource({ page, filename: nestedHeadingFilename });
await confirmContentBlockConnection({ page });
await waitForSyncStatus({ page, status: "idle" });
await openFixture({
page,
projectId: fixture.projectId,
authToken: fixture.editorToken,
mode: "content",
});
await waitForContentEditMode({ page });
const canvas = await waitForCanvasFrame({ page });
const heading = canvas.locator("h3", { hasText: "perustukset" });
await heading.waitFor({ state: "visible" });
await page.route("**/rest/assets/*/content?*", async (route) => {
if (route.request().method() === "PUT") {
await new Promise((resolve) => setTimeout(resolve, 2_000));
}
await route.continue();
});
await replaceCanvasText({
page,
currentText: "perustukset",
text: "Edited nested heading",
waitForProjectSync: false,
});
await waitForSyncStatus({ page, status: "idle" });
await page.reload();
const reopenedCanvas = await waitForCanvasFrame({ page });
await reopenedCanvas
.locator("h3", { hasText: "Edited nested heading" })
.waitFor();
});
test("Content Block MDX source lifecycle persists edits and resets to empty", async ({
page,
context,
@@ -7,6 +7,7 @@ import {
} from "@webstudio-is/content-engine/mdx";
import {
elementComponent,
type Asset,
type ContentBlockExternalContentIdentity,
type WebstudioFragment,
} from "@webstudio-is/sdk";
@@ -1964,7 +1965,102 @@ describe("MDX authored content", () => {
}
changedAsset.value = "other-asset";
expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(
'Asset prop "src" cannot be represented losslessly in MDX'
"Changes to assets cannot be represented losslessly in MDX"
);
});
test("compares existing Asset records by their fields", async () => {
const article: Asset = {
id: "article",
projectId: "project",
name: "article.md",
type: "file",
format: "md",
size: 7,
createdAt: "2026-01-01T00:00:00.000Z",
description: null,
meta: {},
};
const root = materializeMdxAuthoredContent({
identity,
document: await parseMdxDocument({ source: "Before" }),
templateMaterialization: emptyTemplates,
});
root.fragment.assets.push(article);
const next = structuredClone(root.fragment);
next.assets[0] = Object.assign(Object.create(null), article);
next.assets[0]!.meta = Object.create(null);
next.instances[0]!.children = [{ type: "text", value: "After" }];
expect(
serializeMdxDocument(
reconcileMdxAuthoredContent({ root, fragment: next })
)
).toBe("After\n");
});
test("preserves template image assets while editing MDX text", async () => {
const templateImage: Asset = {
id: "template-image",
projectId: "project",
name: "template-image.png",
type: "image",
format: "png",
size: 100,
createdAt: "2026-01-01T00:00:00.000Z",
description: null,
meta: { width: 100, height: 100 },
};
const root = materializeMdxAuthoredContent({
identity,
document: await parseMdxDocument({
source: '<ws.element ws:tag="h3">Before</ws.element>',
}),
templateMaterialization: emptyTemplates,
assetReferenceValues: new Map([
[templateImage.id, "./template-image.png"],
]),
});
const heading = root.fragment.instances[0];
if (heading === undefined) {
throw new Error("Expected an authored heading");
}
root.fragment.breakpoints.push({ id: "base", label: "Base" });
root.fragment.styleSources.push({ type: "local", id: "template-style" });
root.fragment.styleSourceSelections.push({
instanceId: heading.id,
values: ["template-style"],
});
root.fragment.styles.push({
styleSourceId: "template-style",
breakpointId: "base",
property: "backgroundImage",
value: {
type: "image",
value: { type: "asset", value: templateImage.id },
},
});
const next = structuredClone(root.fragment);
next.props.push({
id: "template-image-prop",
instanceId: heading.id,
name: "src",
type: "asset",
value: templateImage.id,
});
next.instances[0]!.children = [{ type: "text", value: "After" }];
expect(
serializeMdxDocument(
reconcileMdxAuthoredContent({ root, fragment: next })
)
).toBe('<h3 src="./template-image.png">After</h3>\n');
next.assets.push({ ...templateImage, id: "unknown-image" });
next.props[0]!.value = "unknown-image";
expect(() => reconcileMdxAuthoredContent({ root, fragment: next })).toThrow(
"Changes to assets cannot be represented losslessly in MDX"
);
});
@@ -1865,10 +1865,25 @@ const assertSupportedNamespaces = ({
deletedTemplateRootIds: ReadonlySet<string>;
}) => {
for (const namespace of unsupportedNamespaces) {
if (namespace === "assets" && root.assetReferenceValues !== undefined) {
if (namespace === "assets") {
const originalById = new Map(
root.fragment.assets.map((asset) => [asset.id, asset])
);
const authoredAssetPropIds = new Set(
root.provenance.nodes.flatMap((node) =>
node.type === "template"
? [
...node.assetProps.map(({ assetId }) => assetId),
...node.overlaidDescendants.flatMap((descendant) =>
descendant.assetProps.map(({ assetId }) => assetId)
),
]
: node.assetProps.map(({ assetId }) => assetId)
)
);
const isKnownAsset = (assetId: string) =>
root.assetReferenceValues?.has(assetId) === true ||
authoredAssetPropIds.has(assetId);
const referencedAssetIds = new Set(
fragment.props.flatMap((prop) =>
prop.type === "asset" ? [prop.value] : []
@@ -1877,12 +1892,15 @@ const assertSupportedNamespaces = ({
const assetIds = new Set<string>();
for (const asset of fragment.assets) {
const original = originalById.get(asset.id);
// Template assets can be referenced by styles or data sources too.
if (
assetIds.has(asset.id) ||
(original === undefined
? referencedAssetIds.has(asset.id) === false ||
root.assetReferenceValues.has(asset.id) === false
: equal(original, asset) === false)
? isKnownAsset(asset.id) === false
: equal(
JSON.parse(JSON.stringify(original)),
JSON.parse(JSON.stringify(asset))
) === false)
) {
throw new Error(
"Changes to assets cannot be represented losslessly in MDX"
@@ -1892,7 +1910,8 @@ const assertSupportedNamespaces = ({
}
if (
Array.from(referencedAssetIds).some(
(assetId) => assetIds.has(assetId) === false
(assetId) =>
assetIds.has(assetId) === false && isKnownAsset(assetId) === false
)
) {
throw new Error(