Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 12 additions & 8 deletions packages/studio/src/webmcp/StudioAgentTools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,20 @@
import { describe, expect, it } from "vitest";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { vi } from "vitest";
import { readLiveSelectionBox, resizeSelectionFromAgent } from "./StudioAgentTools";
import { agentPreview } from "./agentPreview";
import { resizeSelectionFromAgent } from "./StudioAgentTools";

const readNowIn = (doc: Document, selection: DomEditSelection) =>
agentPreview(() => ({ contentDocument: doc }) as HTMLIFrameElement, "index.html").readNow(
selection,
);

function rect(width: number, height: number): DOMRect {
return { x: 10, y: 20, width, height } as DOMRect;
}

describe("readLiveSelectionBox", () => {
it("measures the replacement preview node after a commit reload", () => {
describe("agentPreview readNow on a live preview", () => {
it("measures the replacement preview node after a commit reload", async () => {
const oldElement = document.createElement("h1");
oldElement.id = "headline";
oldElement.getBoundingClientRect = () => rect(300, 50);
Expand All @@ -25,15 +31,15 @@ describe("readLiveSelectionBox", () => {
replacement.getBoundingClientRect = () => rect(280, 60);
liveDocument.body.append(replacement);

expect(readLiveSelectionBox(liveDocument, selection, "index.html")).toEqual({
expect((await readNowIn(liveDocument, selection)).box).toEqual({
x: 10,
y: 20,
width: 280,
height: 60,
});
});

it("does not hide a stale target behind its detached old node", () => {
it("does not hide a stale target behind its detached old node", async () => {
const oldElement = document.createElement("h1");
oldElement.id = "headline";
const selection = {
Expand All @@ -43,9 +49,7 @@ describe("readLiveSelectionBox", () => {
} as DomEditSelection;
const liveDocument = document.implementation.createHTMLDocument();

expect(() => readLiveSelectionBox(liveDocument, selection, "index.html")).toThrow(
"target is missing",
);
await expect(readNowIn(liveDocument, selection)).rejects.toThrow("target is missing");
});
});

Expand Down
43 changes: 14 additions & 29 deletions packages/studio/src/webmcp/StudioAgentTools.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { useDomEditActionsContext, useDomEditSelectionContext } from "../context
import { useStudioShellContext } from "../contexts/StudioContext";
import { usePlayerStore } from "../player";
import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
import { collectStudioLookScene, type StudioLookSnapshot } from "./tools/lookTools";
import type { StudioLookSnapshot } from "./tools/lookTools";
import { agentPreview } from "./agentPreview";
import { studioEditLifecycle } from "./writeCoordinator";
import { findElementForSelection } from "../components/editor/domEditingElement";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import {
applyStudioBoxSizeDraft,
Expand All @@ -14,19 +14,6 @@ import {
} from "../components/editor/manualEdits";
import { studioApiFetch } from "../utils/studioApiFetch";

export function readLiveSelectionBox(
doc: Document | null | undefined,
selection: DomEditSelection,
activeCompositionPath: string | null,
) {
const liveElement = doc
? findElementForSelection(doc, selection, activeCompositionPath)
: selection.element;
if (!liveElement) throw new Error("the target is missing from the current Studio preview");
const rect = liveElement.getBoundingClientRect();
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
}

type ResizeCommit = (
selection: DomEditSelection,
next: { width: number; height: number },
Expand Down Expand Up @@ -87,7 +74,12 @@ export function StudioAgentTools() {
return () => studioEditLifecycle.reset();
}, [projectId]);

const getSnapshot = useCallback((): StudioLookSnapshot => {
const preview = useMemo(
() => agentPreview(() => previewIframeRef.current, activeCompPath),
[previewIframeRef, activeCompPath],
);

const getSnapshot = useCallback(async (): Promise<StudioLookSnapshot> => {
const player = usePlayerStore.getState();
return {
projectId,
Expand All @@ -96,11 +88,7 @@ export function StudioAgentTools() {
duration: player.duration,
isPlaying: player.isPlaying,
elements: player.elements,
scene: collectStudioLookScene(
previewIframeRef.current?.contentDocument ?? null,
activeCompPath,
activeGroupElement,
),
scene: await preview.scene(activeGroupElement),
selection: domEditSelection,
selectionAnimationCount: selectedGsapAnimations.length,
history: {
Expand All @@ -117,13 +105,13 @@ export function StudioAgentTools() {
activeGroupElement,
selectedGsapAnimations,
editHistory,
previewIframeRef,
preview,
]);

const deps = useMemo<StudioAgentToolsDeps>(
() => ({
getSnapshot,
getPreviewDocument: () => previewIframeRef.current?.contentDocument ?? null,
preview,
buildSelection: (element) => buildDomSelectionFromTarget(element, { exactTarget: true }),
applySelection: (selection) => applyDomSelection(selection, { revealPanel: true }),
requestSeek: (time) => usePlayerStore.getState().requestSeek(time),
Expand Down Expand Up @@ -156,11 +144,8 @@ export function StudioAgentTools() {
setStyle: (selection, property, value) =>
handleDomStyleCommitForSelection(selection, property, value),
// Measured, not authored: the tool compares this before and after to
// tell a real change from a handler that did nothing and resolved. A
// successful commit may replace the preview document, so re-resolve the
// source-safe selection instead of measuring its detached old node.
readBox: (selection) =>
readLiveSelectionBox(previewIframeRef.current?.contentDocument, selection, activeCompPath),
// tell a real change from a handler that did nothing and resolved.
readNow: preview.readNow,
moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next),
resizeTo: (selection, next) =>
resizeSelectionFromAgent(selection, next, handleDomBoxSizeCommit),
Expand All @@ -182,7 +167,7 @@ export function StudioAgentTools() {
}),
[
getSnapshot,
previewIframeRef,
preview,
buildDomSelectionFromTarget,
applyDomSelection,
projectId,
Expand Down
158 changes: 158 additions & 0 deletions packages/studio/src/webmcp/agentPreview.sealed.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
// @vitest-environment happy-dom

import { afterEach, describe, expect, it, vi } from "vitest";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { resolveFoundSelection } from "../components/editor/previewSelection";
import { sealedPreviewFrame } from "../player/lib/sealedPreviewFrame.test-helpers";
import { agentPreview } from "./agentPreview";
import { studioSetStyle, studioSetText } from "./tools/contentTools";
import { studioInspect } from "./tools/inspectTools";
import { buildStudioLook, collectStudioLookScene, type StudioLook } from "./tools/lookTools";
import { studioSelect } from "./tools/selectionTools";
import { studioTransform, type StudioTransformResult } from "./tools/transformTools";
import type { StudioSelectResult } from "./tools/selectionTools";
import {
expectOk,
lookSnapshot,
selectionFor,
sourceHandle,
studioAgentToolsDeps,
} from "./webmcpTestUtils";

const FIXTURE = `
<div data-composition-id="main" data-width="1920" data-height="1080">
<div id="card" class="clip"><h1 id="target">Ship it</h1></div>
</div>`;
const CONTEXT = { activeCompositionPath: "index.html", isMasterView: false };
const selfTextField = selectionFor(document.createElement("h1")).textFields[0]!;

afterEach(() => {
document.body.innerHTML = "";
});

/** Studio's agent tools on a sealed preview of FIXTURE, whose #target paints at `box`. */
function sealedStudio() {
document.body.innerHTML = FIXTURE;
const target = document.getElementById("target")!;
const box = { x: 10, y: 20, width: 300, height: 60 };
target.getBoundingClientRect = () =>
({
...box,
top: box.y,
left: box.x,
right: box.x + box.width,
bottom: box.y + box.height,
}) as DOMRect;
const { iframe } = sealedPreviewFrame();
const preview = agentPreview(() => iframe, "index.html");
const applySelection = vi.fn<(selection: DomEditSelection) => void>();
const deps = studioAgentToolsDeps({
preview,
readNow: preview.readNow,
getProjectId: () => "project-a",
buildSelection: (found) => resolveFoundSelection(iframe, found, CONTEXT),
applySelection,
});
return { preview, deps, target, box, applySelection, handle: sourceHandle("target") };
}

describe("agent tools on a sealed preview", () => {
it("looks at the same scene, with the same handles, as on a live preview", async () => {
const { preview } = sealedStudio();
const look = (scene: Awaited<ReturnType<typeof preview.scene>>) =>
expectOk<StudioLook>(buildStudioLook(lookSnapshot({ projectId: "project-a", scene })));

const sealed = look(await preview.scene(null));
const live = look(collectStudioLookScene(document, "index.html", null));

expect(sealed.sceneStatus).toBe("ready");
expect(sealed.elements.map((element) => element.handle)).toContain(sourceHandle("target"));
expect(sealed.elements).toEqual(live.elements);
});

it("selects an element by its handle", async () => {
const { deps, handle, applySelection } = sealedStudio();

const selected = expectOk<StudioSelectResult>(await studioSelect(deps, handle));

expect(selected.tagName).toBe("h1");
expect(selected.box).toEqual({ x: 10, y: 20, width: 300, height: 60 });
expect(applySelection.mock.calls[0]?.[0].handle).toBeDefined();
});

it("inspects an element by its handle", async () => {
const { deps, handle } = sealedStudio();

const inspected = expectOk(await studioInspect(deps, { handle }));

expect(inspected).toMatchObject({ tagName: "h1", text: "Ship it" });
});

it("writes a style to an element by its handle", async () => {
const { deps, handle, target } = sealedStudio();
const setStyle = vi.fn(
async (_selection: DomEditSelection, property: string, value: string) => {
target.style.setProperty(property, value);
return { ok: true as const };
},
);

const result = await studioSetStyle(
{ ...deps, setStyle },
{ handle, styles: { opacity: "0.5" } },
);

expect(result).toMatchObject({ ok: true });
expect(setStyle.mock.calls[0]?.[0].handle).toBeDefined();
});

it("reads a move it made off the frame's element", async () => {
const { deps, handle, box } = sealedStudio();
const moveTo = vi.fn(async (_selection: DomEditSelection, next: { x: number; y: number }) => {
Object.assign(box, next);
});

const moved = expectOk<StudioTransformResult>(
await studioTransform({ ...deps, moveTo }, { handle, x: 40, y: 50 }),
);

expect(moved.applied).toEqual(["move"]);
expect(moved.box).toEqual({ x: 40, y: 50, width: 300, height: 60 });
});

it("reads new text it wrote off the frame's element", async () => {
const { deps, handle, target } = sealedStudio();
// A sealed selection lists no text fields yet; one is given here so the write reaches its read-back.
const buildSelection = async (found: Parameters<typeof deps.buildSelection>[0]) => {
const selection = await deps.buildSelection(found);
return selection && { ...selection, textFields: [selfTextField] };
};
const setText = vi.fn(async (_selection: DomEditSelection, value: string) => {
target.textContent = value;
return { ok: true as const };
});

const result = await studioSetText(
{ ...deps, buildSelection, setText },
{ handle, text: "Shipped" },
);

expect(result).toMatchObject({ ok: true, text: "Shipped", changed: true });
});
});

describe("studio_look before the timeline is known", () => {
it("says the scene is still loading, and lists nothing", () => {
const look = expectOk<StudioLook>(
buildStudioLook(
lookSnapshot({
duration: 0,
scene: { status: "ready", items: [], drillInItem: null },
}),
),
);

expect(look.sceneStatus).toBe("loading");
expect(look.elements).toEqual([]);
});
});
82 changes: 82 additions & 0 deletions packages/studio/src/webmcp/agentPreview.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import { collectPreviewLayerItems } from "../components/editor/previewLayers";
import { findSelectionElement, standInHandle } from "../components/editor/previewSelection";
import { previewEditingClient, previewFrameOpaque } from "../player/lib/previewChannel";
import { handleLookup, type PreviewTargets } from "./handles";
import { collectStudioLookScene, type StudioLookSceneSnapshot } from "./tools/lookTools";

export interface ElementNow {
box: { x: number; y: number; width: number; height: number };
text: string | null;
}

/** The agent tools' one read of the preview, answered by the frame's runtime when Studio cannot script it. */
export interface AgentPreview extends PreviewTargets {
/** The selection's element as the preview shows it now. Throws when the preview no longer has it. */
readNow: (selection: DomEditSelection) => Promise<ElementNow>;
scene: (activeGroupElement: HTMLElement | null) => Promise<StudioLookSceneSnapshot>;
}

function frameDocument(iframe: HTMLIFrameElement | null): Document | null {
try {
return iframe?.contentDocument ?? null;
} catch {
return null;
}
}

async function sealedScene(
iframe: HTMLIFrameElement,
activeCompositionPath: string | null,
activeGroupElement: HTMLElement | null,
): Promise<StudioLookSceneSnapshot> {
// ponytail: one layers page (MAX_QUERY_MATCHES); page on with previewLayers' offset if films outgrow it.
const reply = await collectPreviewLayerItems(iframe, {
activeCompositionPath,
activeGroupElement: null,
});
if (!reply) return { status: "loading" };
const group = activeGroupElement && standInHandle(activeGroupElement) ? activeGroupElement : null;
const drillInItem = group ? (reply.items.find((item) => item.element === group) ?? null) : null;
return { status: "ready", items: reply.items, drillInItem };
}

export function agentPreview(
getIframe: () => HTMLIFrameElement | null,
activeCompositionPath: string | null,
): AgentPreview {
return {
load: () => {
const iframe = getIframe();
if (!iframe) return null;
return previewFrameOpaque(iframe) ? previewEditingClient(iframe) : frameDocument(iframe);
},
find: async (handle) => {
const lookup = handleLookup(handle);
return lookup ? findSelectionElement(getIframe(), lookup.target, lookup.path) : null;
},
readNow: async (selection) => {
const found = await findSelectionElement(getIframe(), selection, activeCompositionPath);
const element =
found ?? (found === undefined && !selection.handle ? selection.element : null);
if (!element) throw new Error("the target is missing from the current Studio preview");
if (!isHtmlElement(element)) {
const { x, y, width, height } = element.rect;
return { box: { x, y, width, height }, text: element.text };
}
const { x, y, width, height } = element.getBoundingClientRect();
return { box: { x, y, width, height }, text: element.textContent };
},
scene: async (activeGroupElement) => {
const iframe = getIframe();
if (iframe && previewFrameOpaque(iframe))
return sealedScene(iframe, activeCompositionPath, activeGroupElement);
return collectStudioLookScene(
frameDocument(iframe),
activeCompositionPath,
activeGroupElement,
);
},
};
}
Loading
Loading