fix(studio): the topology lens shows in a sealed preview (#8420)

* test(studio): a sealed preview's topology lens is drawn from the frame's geometry answer

* fix(studio): the topology lens shows in a sealed preview

* test(studio): a sealed frame's lens matches a live frame's on the real runtime

* fix(studio): a sealed lens finds its composition host by walking the frame's parents

* refactor(studio): the topology lens measures in its own hook
This commit is contained in:
Miguel Ángel
2026-11-22 02:22:44 +00:00
committed by GitHub
parent 2a24357338
commit 79e43a33a8
4 changed files with 266 additions and 81 deletions
@@ -47,19 +47,24 @@ function mount(reducedMotion = false, strictMode = false): void {
});
}
function begin(): string {
async function settle(): Promise<void> {
await act(async () => {});
}
async function begin(): Promise<string> {
let callId = "";
act(() => {
callId = studioEditLifecycle.begin("project-a", target, "set-text");
});
await settle();
return callId;
}
function finish(
async function finish(
callId: string,
stage: "dispatched" | "saved" | "verified" | "failed",
changed = true,
): void {
): Promise<void> {
const result: StudioWriteResult<object> =
stage === "failed"
? {
@@ -82,11 +87,12 @@ function finish(
: { kind: "content-version", sourceFile: "index.html", version: "v1" },
};
act(() => studioEditLifecycle.finish(callId, result));
await settle();
}
beforeEach(() => {
vi.useFakeTimers();
geometryMock.measure.mockReset().mockReturnValue({
geometryMock.measure.mockReset().mockResolvedValue({
field: {
label: "section",
rect: { left: 5, top: 10, width: 320, height: 180, editScaleX: 1, editScaleY: 1 },
@@ -120,9 +126,9 @@ afterEach(() => {
});
describe("TopologyLens", () => {
it("reveals real contours for a new target and seals only a durable receipt", () => {
it("reveals real contours for a new target and seals only a durable receipt", async () => {
mount();
const callId = begin();
const callId = await begin();
expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();
expect(
@@ -137,7 +143,7 @@ describe("TopologyLens", () => {
).toEqual(["p", "aside"]);
expect(host?.querySelector('[data-topology-scan="true"]')).not.toBeNull();
finish(callId, "saved");
await finish(callId, "saved");
expect(host?.querySelector('[data-topology-lens="sealing"]')).not.toBeNull();
expect(
host
@@ -152,9 +158,9 @@ describe("TopologyLens", () => {
expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });
});
it("remeasures the post-write target before drawing the persistence seal", () => {
it("remeasures the post-write target before drawing the persistence seal", async () => {
geometryMock.measure
.mockReturnValueOnce({
.mockResolvedValueOnce({
field: {
label: "section",
rect: { left: 5, top: 10, width: 300, height: 180, editScaleX: 1, editScaleY: 1 },
@@ -165,7 +171,7 @@ describe("TopologyLens", () => {
},
contours: [],
})
.mockReturnValueOnce({
.mockResolvedValueOnce({
field: {
label: "section",
rect: { left: 50, top: 20, width: 360, height: 220, editScaleX: 1, editScaleY: 1 },
@@ -177,10 +183,10 @@ describe("TopologyLens", () => {
contours: [],
});
mount();
const callId = begin();
const callId = await begin();
expect(host?.querySelector<HTMLElement>("[data-topology-target]")?.style.left).toBe("10px");
finish(callId, "verified");
await finish(callId, "verified");
const sealedTarget = host?.querySelector<HTMLElement>("[data-topology-target]");
expect(sealedTarget?.style.left).toBe("70px");
@@ -188,23 +194,23 @@ describe("TopologyLens", () => {
expect(host?.querySelector('[data-topology-seal="verified"]')).not.toBeNull();
});
it("skips acquisition when the coordinator identifies a repeated target", () => {
it("skips acquisition when the coordinator identifies a repeated target", async () => {
mount();
const firstCall = begin();
finish(firstCall, "saved");
const firstCall = await begin();
await finish(firstCall, "saved");
act(() => vi.advanceTimersByTime(240));
begin();
await begin();
expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();
expect(host?.querySelector('[data-topology-contour="true"]')).toBeNull();
});
it.each(["dispatched", "failed"] as const)("retracts %s without a seal", (stage) => {
it.each(["dispatched", "failed"] as const)("retracts %s without a seal", async (stage) => {
mount();
const callId = begin();
const callId = await begin();
finish(callId, stage);
await finish(callId, stage);
expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();
expect(host?.querySelector("[data-topology-seal]")).toBeNull();
@@ -213,11 +219,11 @@ describe("TopologyLens", () => {
expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });
});
it.each(["saved", "verified"] as const)("retracts a %s no-op without a seal", (stage) => {
it.each(["saved", "verified"] as const)("retracts a %s no-op without a seal", async (stage) => {
mount();
const callId = begin();
const callId = await begin();
finish(callId, stage, false);
await finish(callId, stage, false);
expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();
expect(host?.querySelector('[data-topology-terminal="no-change"]')).not.toBeNull();
@@ -226,10 +232,10 @@ describe("TopologyLens", () => {
expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();
});
it("does not replay a terminal seal after the overlay remounts", () => {
it("does not replay a terminal seal after the overlay remounts", async () => {
mount();
const callId = begin();
finish(callId, "saved");
const callId = await begin();
await finish(callId, "saved");
act(() => vi.advanceTimersByTime(240));
expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });
@@ -243,11 +249,12 @@ describe("TopologyLens", () => {
expect(host?.querySelector("[data-topology-seal]")).toBeNull();
});
it("keeps an active invocation through StrictMode effect replay", () => {
const callId = begin();
it("keeps an active invocation through StrictMode effect replay", async () => {
const callId = await begin();
mount(false, true);
act(() => vi.advanceTimersByTime(0));
await settle();
expect(studioEditLifecycle.getSnapshot()).toMatchObject({
callId,
@@ -256,31 +263,31 @@ describe("TopologyLens", () => {
expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();
});
it("clears on iframe reload and project switch", () => {
it("clears on iframe reload and project switch", async () => {
mount();
begin();
await begin();
act(() => announcePreviewDocumentLoaded(iframe!));
expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();
begin();
await begin();
act(() => studioEditLifecycle.activateProject("project-b"));
expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();
});
it("removes spatial travel in reduced motion while preserving target state", () => {
it("removes spatial travel in reduced motion while preserving target state", async () => {
mount(true);
begin();
await begin();
expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();
expect(host?.querySelector('[data-topology-contour="true"]')).not.toBeNull();
expect(host?.querySelector('[data-topology-scan="true"]')).toBeNull();
});
it("cleans its timer and iframe listener on unmount", () => {
it("cleans its timer and iframe listener on unmount", async () => {
mount();
const removeListener = vi.spyOn(iframe!, "removeEventListener");
begin();
await begin();
expect(vi.getTimerCount()).toBe(1);
act(() => root?.unmount());
@@ -294,7 +301,7 @@ describe("TopologyLens", () => {
expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });
});
it("dismisses on the promoted iframe's load, not the replaced one", () => {
it("dismisses on the promoted iframe's load, not the replaced one", async () => {
const a = document.createElement("iframe");
const b = document.createElement("iframe");
document.body.append(a, b);
@@ -307,7 +314,7 @@ describe("TopologyLens", () => {
act(() => {
root?.render(<TopologyLens iframeRef={ref} activeCompositionPath="index.html" />);
});
begin();
await begin();
act(() => {
ref.current = b;
@@ -82,12 +82,35 @@ function useTopologyLensState(): TopologyLensState {
return state;
}
function useLensGeometry(
overlayRef: RefObject<HTMLDivElement | null>,
iframeRef: TopologyLensProps["iframeRef"],
activeCompositionPath: string | null,
callId: string | null,
handle: string | null,
phase: TopologyLensState["phase"],
): TopologyLensGeometry | null {
const [measured, setMeasured] = useState<MeasuredLens | null>(null);
useLayoutEffect(() => {
const overlay = overlayRef.current;
const iframe = iframeRef.current;
if (!callId || !handle || !overlay || !iframe) return setMeasured(null);
let current = true;
void measureTopologyLensGeometry({ overlay, iframe, activeCompositionPath, handle }).then(
(geometry) => current && setMeasured(geometry ? { callId, geometry } : null),
);
return () => {
current = false;
};
}, [activeCompositionPath, callId, handle, iframeRef, overlayRef, phase]);
return measured?.callId === callId ? measured.geometry : null;
}
/** Studio-parent chrome driven by the same invocation and receipt as WebMCP. */
export function TopologyLens({ iframeRef, activeCompositionPath }: TopologyLensProps) {
const overlayRef = useRef<HTMLDivElement | null>(null);
const state = useTopologyLensState();
const reducedMotion = useSyncExternalStore(subscribeReducedMotion, getReducedMotion, () => false);
const [measured, setMeasured] = useState<MeasuredLens | null>(null);
const callId = state.phase === "hidden" ? null : state.callId;
const handle = state.phase === "hidden" ? null : state.target.handle;
const phase = state.phase;
@@ -95,26 +118,6 @@ export function TopologyLens({ iframeRef, activeCompositionPath }: TopologyLensP
const pendingUnmountDismissRef = useRef<number | null>(null);
ownedCallIdRef.current = callId;
useLayoutEffect(() => {
if (!callId || !handle) {
setMeasured(null);
return;
}
const overlay = overlayRef.current;
const iframe = iframeRef.current;
if (!overlay || !iframe) {
setMeasured(null);
return;
}
const geometry = measureTopologyLensGeometry({
overlay,
iframe,
activeCompositionPath,
handle,
});
setMeasured(geometry ? { callId, geometry } : null);
}, [activeCompositionPath, callId, handle, iframeRef, phase]);
const livePreviewIframe = useLivePreviewIframe();
useEffect(() => {
const iframe = iframeRef.current;
@@ -138,7 +141,14 @@ export function TopologyLens({ iframeRef, activeCompositionPath }: TopologyLensP
};
}, []);
const geometry = measured?.callId === callId ? measured.geometry : null;
const geometry = useLensGeometry(
overlayRef,
iframeRef,
activeCompositionPath,
callId,
handle,
phase,
);
const visible = state.phase !== "hidden" && geometry;
return (
<div
@@ -0,0 +1,90 @@
// @vitest-environment happy-dom
import { afterEach, beforeEach, expect, it } from "vitest";
import { watchPreviewFrame } from "../../player/lib/bridgePlayback";
import { detachedFakeIframe } from "../../player/hooks/timelinePlayerTestHarness";
import { sealedPreviewFrame } from "../../player/lib/sealedPreviewFrame.test-helpers";
import { mintElementHandle } from "../../webmcp/handles";
import { measureTopologyLensGeometry } from "./topologyLensGeometry";
const FIXTURE = `
<main id="root" data-composition-id="root" data-composition-file="index.html" data-width="1920" data-height="1080">
<section id="host" data-composition-id="nested" data-composition-file="compositions/nested.html">
<article id="context">
<div id="duplicate"><strong id="child">nested</strong></div>
<aside id="aside">outside target</aside>
</article>
</section>
</main>`;
const RECTS: Record<string, number[]> = {
root: [0, 0, 1920, 1080],
host: [100, 100, 1200, 800],
context: [150, 150, 1000, 600],
duplicate: [200, 200, 400, 200],
child: [220, 220, 200, 60],
aside: [700, 200, 300, 200],
};
const FRAME = [100, 50, 960, 540];
function sized<T extends Element>(element: T, [x, y, width, height]: number[]): T {
element.getBoundingClientRect = () =>
({ x, y, width, height, left: x, top: y, right: x + width, bottom: y + height }) as DOMRect;
Object.defineProperty(element, "offsetWidth", { value: width, configurable: true });
Object.defineProperty(element, "offsetHeight", { value: height, configurable: true });
return element;
}
beforeEach(() => {
document.body.innerHTML = FIXTURE;
for (const [id, rect] of Object.entries(RECTS)) sized(document.getElementById(id)!, rect);
});
afterEach(() => {
document.body.innerHTML = "";
});
function liveFrame(): HTMLIFrameElement {
const iframe = detachedFakeIframe(window as unknown as Record<string, unknown>);
Object.defineProperty(iframe, "contentDocument", { value: document });
return sized(iframe, FRAME);
}
function sealedFrame(): HTMLIFrameElement {
const { iframe: sealed, frame } = sealedPreviewFrame();
const iframe = sized(sealed, FRAME);
watchPreviewFrame(iframe);
window.dispatchEvent(
new MessageEvent("message", {
source: frame as unknown as Window,
origin: window.location.origin,
data: { source: "hf-preview", type: "stage-size", width: 1920, height: 1080 },
}),
);
return iframe;
}
const labels = (geometry: Awaited<ReturnType<typeof measureTopologyLensGeometry>>) =>
geometry && {
field: geometry.field.label,
target: geometry.target.label,
contours: geometry.contours.map((contour) => contour.label),
};
it("draws the same lens in a sealed frame as in a live one", async () => {
const handle = mintElementHandle({
domId: "duplicate",
sourceFile: "compositions/nested.html",
activeCompositionPath: "index.html",
})!;
const measure = (iframe: HTMLIFrameElement) =>
measureTopologyLensGeometry({
overlay: sized(document.createElement("div"), [0, 0, 1200, 800]),
iframe,
activeCompositionPath: "index.html",
handle,
});
const live = labels(await measure(liveFrame()));
const sealed = labels(await measure(sealedFrame()));
expect(live).toEqual({ field: "section", target: "div", contours: ["strong", "aside"] });
expect(sealed).toEqual(live);
});
@@ -1,7 +1,12 @@
import { previewFrameOpaque } from "../../player/lib/previewChannel";
import { agentPreview } from "../../webmcp/agentPreview";
import { resolveElementHandle } from "../../webmcp/handles";
import { collectStudioLookScene } from "../../webmcp/tools/lookTools";
import type { DomEditLayerItem } from "./domEditingTypes";
import { toVisibleOverlayRects, type OverlayRect } from "./domEditOverlayGeometry";
import { describePreviewElements, type PreviewElement } from "../../player/lib/previewElements";
import { measurePreviewVisibleRects } from "./previewOverlayRects";
import { standInFor } from "./previewSelection";
export interface TopologyLensNode {
label: string;
@@ -45,6 +50,40 @@ function collectSourceContours(
return contours;
}
const SOURCE_HOST = ["data-composition-file", "data-composition-src"] as const;
const SOURCE_HOST_SELECTOR = SOURCE_HOST.map((name) => `[${name}]`).join();
type LensElements = { context: HTMLElement; target: HTMLElement; contours: HTMLElement[] };
function lensElements(
items: readonly DomEditLayerItem[],
targetIndex: number,
sourceHost: HTMLElement | null,
): LensElements {
const targetItem = items[targetIndex]!;
const contextIndex = findSourceContextIndex(items, targetIndex);
return {
context: sourceHost ?? items[contextIndex]!.element,
target: targetItem.element,
contours: collectSourceContours(items, contextIndex, targetItem),
};
}
const MAX_HOST_DEPTH = 64;
/** `closest(SOURCE_HOST_SELECTOR)` for an element of a frame Studio cannot script, one parent at a time. */
async function sealedSourceHost(
iframe: HTMLIFrameElement,
element: PreviewElement,
): Promise<PreviewElement | null> {
let at: PreviewElement | null = element;
for (let depth = 0; at && depth < MAX_HOST_DEPTH; depth++) {
if (at.attributes.some(([name]) => (SOURCE_HOST as readonly string[]).includes(name)))
return at;
at = at.parent ? ((await describePreviewElements(iframe, [at.parent]))?.[0] ?? null) : null;
}
return null;
}
/**
* Resolve the same nested preorder used by studio_look. This keeps the lens on
* the agent's source-safe scene model instead of guessing hierarchy from an
@@ -54,49 +93,88 @@ export function resolveTopologyLensElements(
doc: Document,
activeCompositionPath: string | null,
handle: string,
): { context: HTMLElement; target: HTMLElement; contours: HTMLElement[] } | null {
): LensElements | null {
const target = resolveElementHandle(doc, handle);
if (!target) return null;
const scene = collectStudioLookScene(doc, activeCompositionPath, null);
if (scene.status === "loading") return null;
const targetIndex = scene.items.findIndex((item) => item.element === target);
if (targetIndex < 0) return { context: target, target, contours: [] };
return lensElements(scene.items, targetIndex, target.closest<HTMLElement>(SOURCE_HOST_SELECTOR));
}
const targetItem = scene.items[targetIndex]!;
const contextIndex = findSourceContextIndex(scene.items, targetIndex);
const contextItem = scene.items[contextIndex]!;
const sourceContext = target.closest<HTMLElement>(
"[data-composition-file], [data-composition-src]",
);
async function resolveSealedLensElements(
iframe: HTMLIFrameElement,
activeCompositionPath: string | null,
handle: string,
): Promise<{ elements: LensElements; handles: Map<HTMLElement, string> } | null> {
const preview = agentPreview(() => iframe, activeCompositionPath);
const [found, scene] = await Promise.all([preview.find(handle), preview.scene(null)]);
if (!found || !("handle" in found) || scene.status === "loading") return null;
const targetIndex = scene.items.findIndex((item) => item.preview?.handle === found.handle);
if (targetIndex < 0) return null;
const handles = new Map<HTMLElement, string>();
for (const item of scene.items) if (item.preview) handles.set(item.element, item.preview.handle);
const host = await sealedSourceHost(iframe, found);
return {
context: sourceContext ?? contextItem.element,
target,
contours: collectSourceContours(scene.items, contextIndex, targetItem),
elements: lensElements(scene.items, targetIndex, host && heldStandIn(iframe, host, handles)),
handles,
};
}
function heldStandIn(
iframe: HTMLIFrameElement,
element: PreviewElement,
handles: Map<HTMLElement, string>,
) {
const standIn = standInFor(iframe, element);
handles.set(standIn, element.handle);
return standIn;
}
function isRenderableRect(rect: OverlayRect | null | undefined): rect is OverlayRect {
return Boolean(rect && rect.width > 0 && rect.height > 0);
}
export function measureTopologyLensGeometry(input: {
function lensOrder({ context, target, contours }: LensElements): HTMLElement[] {
return context === target ? [target, ...contours] : [context, target, ...contours];
}
async function measureLens(input: {
overlay: HTMLDivElement;
iframe: HTMLIFrameElement;
activeCompositionPath: string | null;
handle: string;
}): TopologyLensGeometry | null {
const doc = input.iframe.contentDocument;
if (!doc) return null;
const elements = resolveTopologyLensElements(doc, input.activeCompositionPath, input.handle);
if (!elements) return null;
}): Promise<{ elements: LensElements; measured: Array<OverlayRect | null> } | null> {
const { overlay, iframe, activeCompositionPath, handle } = input;
if (!previewFrameOpaque(iframe)) {
const doc = iframe.contentDocument;
const elements = doc && resolveTopologyLensElements(doc, activeCompositionPath, handle);
return (
elements && {
elements,
measured: toVisibleOverlayRects(overlay, iframe, lensOrder(elements)),
}
);
}
const resolved = await resolveSealedLensElements(iframe, activeCompositionPath, handle);
if (!resolved) return null;
const order = lensOrder(resolved.elements).map((element) => resolved.handles.get(element));
if (order.some((entry) => entry === undefined)) return null;
const boxes = await measurePreviewVisibleRects(iframe, overlay, order as string[]);
return boxes && { elements: resolved.elements, measured: boxes.map((box) => box?.rect ?? null) };
}
export async function measureTopologyLensGeometry(input: {
overlay: HTMLDivElement;
iframe: HTMLIFrameElement;
activeCompositionPath: string | null;
handle: string;
}): Promise<TopologyLensGeometry | null> {
const lens = await measureLens(input);
if (!lens) return null;
const { elements, measured } = lens;
const sharedField = elements.context === elements.target;
const measured = toVisibleOverlayRects(
input.overlay,
input.iframe,
sharedField
? [elements.target, ...elements.contours]
: [elements.context, elements.target, ...elements.contours],
);
const target = measured[sharedField ? 0 : 1];
if (!isRenderableRect(target)) return null;
const measuredField = measured[0];