fix(studio): a sealed resize, move or turn typed or made by the agent shows in the preview (#8283)

* fix(studio): a sealed resize, move or turn typed in or made by the agent shows in the preview

* test(studio): a sealed geometry save leaves the frame to a live drag draft
This commit is contained in:
Miguel Ángel
2026-11-20 10:03:39 +00:00
committed by GitHub
parent c34df57abd
commit 89edb0af00
6 changed files with 185 additions and 9 deletions
@@ -37,6 +37,11 @@ export function registerPreviewStandIn(
export const previewStandIn = (standIn: Element) => standIns.get(standIn);
export function previewDraftLive(standIn: Element): boolean {
const target = standIns.get(standIn);
return !!target && !!queues.get(target.iframe)?.drawn.has(target.handle);
}
function queueFor(iframe: HTMLIFrameElement): Queue {
let queue = queues.get(iframe);
if (!queue) {
@@ -0,0 +1,135 @@
// @vitest-environment happy-dom
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
findPreviewElementForSelection,
resolvePreviewSelection,
} from "../components/editor/previewSelection";
import { drawPreviewDraft } from "../components/editor/previewDrafts";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
import { resizeSelectionFromAgent } from "../webmcp/StudioAgentTools";
import type { PersistDomEditOperations } from "./domEditCommitTypes";
import { useDomEditPositionPatchCommit } from "./useDomEditPositionPatchCommit";
import { useDomGeometryCommits } from "./useDomGeometryCommits";
(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
const PATH = "index.html";
const CARD = `<div id="card" style="position: absolute; left: 10px; top: 10px; width: 100px; height: 50px">Hi</div>`;
afterEach(() => {
document.body.innerHTML = "";
});
/** Studio's geometry commits on a sealed preview of CARD, saving through `persist`. */
async function sealedCard(persist: PersistDomEditOperations) {
document.body.innerHTML = CARD;
const card = document.getElementById("card")!;
const { iframe } = sealedPreviewFrame();
const found = await findPreviewElementForSelection(
iframe,
{ id: "card", sourceFile: PATH },
PATH,
);
const selection = (await resolvePreviewSelection(iframe, found!, {
activeCompositionPath: PATH,
isMasterView: false,
skipSourceProbe: true,
}))!;
let commits: ReturnType<typeof useDomGeometryCommits> | undefined;
function Harness() {
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath: PATH,
previewIframeRef: { current: iframe },
persistDomEditOperations: persist,
showToast: vi.fn(),
});
commits = useDomGeometryCommits({
showToast: vi.fn(),
readOnlyPreview: false,
commitPositionPatchToHtml,
});
return null;
}
act(() => createRoot(document.createElement("div")).render(createElement(Harness)));
return { card, selection, commits: commits! };
}
/** Lets the port's request and the frame's reply land. */
const settle = () => act(() => new Promise((resolve) => setTimeout(resolve, 20)));
const saved = () => vi.fn<PersistDomEditOperations>(async () => undefined);
describe("geometry commits in a sealed preview", () => {
it("draws a resize from the agent on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());
await resizeSelectionFromAgent(
selection,
{ width: 200, height: 80 },
commits.handleDomBoxSizeCommit,
);
await settle();
expect([card.style.width, card.style.height]).toEqual(["200px", "80px"]);
});
it("draws a size typed in the inspector on the frame's element", async () => {
const persist = saved();
const { card, selection, commits } = await sealedCard(persist);
await commits.handleDomBoxSizeCommit(selection, { width: 160, height: 90 });
await settle();
expect([card.style.width, card.style.height]).toEqual(["160px", "90px"]);
expect(persist.mock.calls[0]?.[2]).toMatchObject({ skipRefresh: true });
});
it("draws an offset typed in the inspector on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());
await commits.stageElementPositionOffset(selection, { x: 40, y: 20 }, true).save();
await settle();
expect(card.style.translate).toBe(selection.element.style.translate);
expect(card.style.translate).toMatch(/40px/);
});
it("draws a rotation from the agent on the frame's element", async () => {
const { card, selection, commits } = await sealedCard(saved());
await commits.handleDomRotationCommit(selection, { angle: 30 });
await settle();
expect(card.style.rotate).toBe("30deg");
});
it("leaves the frame to a drag whose draft is still live", async () => {
const { card, selection, commits } = await sealedCard(saved());
drawPreviewDraft(selection.element, { size: { width: 150, height: 50 } });
await settle();
await commits.handleDomBoxSizeCommit(selection, { width: 200, height: 80 });
await settle();
expect(card.style.width).toBe("150px");
});
it("puts the frame's element and the selection back exactly when the save fails", async () => {
const failed = vi.fn<PersistDomEditOperations>(async () => {
throw new Error("disk full");
});
const { card, selection, commits } = await sealedCard(failed);
const frameBefore = card.style.cssText;
const shownBefore = selection.element.style.cssText;
await expect(
commits.handleDomBoxSizeCommit(selection, { width: 200, height: 80 }),
).rejects.toThrow("disk full");
await settle();
expect(card.style.cssText).toBe(frameBefore);
expect(selection.element.style.cssText).toBe(shownBefore);
});
});
@@ -273,6 +273,7 @@ export function useDomEditCommits({
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef,
persistDomEditOperations,
showToast,
});
@@ -61,6 +61,7 @@ function paramsWith(persistDomEditOperations: () => Promise<undefined>) {
showToast,
params: {
activeCompPath: "index.html",
previewIframeRef: { current: null },
persistDomEditOperations,
showToast,
},
@@ -1,5 +1,11 @@
import { useCallback } from "react";
import { useCallback, type RefObject } from "react";
import type { DomEditSelection } from "../components/editor/domEditing";
import { previewDraftLive } from "../components/editor/previewDrafts";
import {
editSealedSelection,
showSavedStylesOnStandIn,
} from "../components/editor/previewSelection";
import { afterSealedDraw } from "../player/lib/previewElements";
import type { PatchOperation } from "../utils/sourcePatcher";
import { trackStudioSaveFailure } from "../utils/studioSaveDiagnostics";
import { DomEditSaveQueueOpenError } from "../utils/domEditSaveQueue";
@@ -8,6 +14,7 @@ import { wasAlreadyToasted } from "./domEditPersistFailure";
interface UseDomEditPositionPatchCommitParams {
activeCompPath: string | null;
previewIframeRef: RefObject<HTMLIFrameElement | null>;
persistDomEditOperations: PersistDomEditOperations;
showToast: (message: string, tone?: "error" | "info") => void;
}
@@ -20,20 +27,46 @@ type PositionPatchOptions = {
deferRender?: boolean;
};
/** A sealed frame shows the patch's own styles and attributes, unless a gesture's draft already does. */
function drawOnSealedFrame(
iframe: HTMLIFrameElement | null,
selection: DomEditSelection,
patches: PatchOperation[],
) {
if (previewDraftLive(selection.element)) return null;
const own = patches.filter((p) => p.childSelector === undefined && p.childIndex === undefined);
const entries = (type: PatchOperation["type"]) =>
own.filter((p) => p.type === type).map((p): [string, string | null] => [p.property, p.value]);
const styles = entries("inline-style");
const edit = editSealedSelection(iframe, selection, {
styles,
attributes: entries("attribute"),
});
const shown = styles.filter((entry): entry is [string, string] => entry[1] !== null);
if (edit) showSavedStylesOnStandIn(selection.element, shown);
return edit;
}
export function useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef,
persistDomEditOperations,
showToast,
}: UseDomEditPositionPatchCommitParams) {
return useCallback(
(selection: DomEditSelection, patches: PatchOperation[], options: PositionPatchOptions) => {
return persistDomEditOperations(selection, patches, {
label: options.label,
coalesceKey: options.coalesceKey,
coalesceMs: options.coalesceMs,
skipRefresh: options.skipRefresh ?? true,
deferRender: options.deferRender,
}).catch((error) => {
const sealedEdit = drawOnSealedFrame(previewIframeRef.current, selection, patches);
const saved = afterSealedDraw(sealedEdit, (drawn) =>
persistDomEditOperations(selection, patches, {
label: options.label,
coalesceKey: options.coalesceKey,
coalesceMs: options.coalesceMs,
skipRefresh: (options.skipRefresh ?? true) && drawn,
deferRender: options.deferRender,
}),
);
return Promise.resolve(saved).catch((error) => {
sealedEdit?.restore();
// The paused-save banner already explains this refusal. Rethrow so the
// caller reverts the preview instead of treating an unsaved edit as committed.
if (error instanceof DomEditSaveQueueOpenError) throw error;
@@ -53,6 +86,6 @@ export function useDomEditPositionPatchCommit({
throw error;
});
},
[activeCompPath, persistDomEditOperations, showToast],
[activeCompPath, persistDomEditOperations, previewIframeRef, showToast],
);
}
@@ -96,6 +96,7 @@ export function useDomGeometryCommit({
});
const commitPositionPatchToHtml = useDomEditPositionPatchCommit({
activeCompPath,
previewIframeRef: iframeRef,
persistDomEditOperations,
showToast,
});