mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-11-23 11:29:54 +00:00
fix(studio): agent tools see the film in a sealed preview (#8281)
* fix(studio): agent tools read a sealed preview through its runtime * test(studio): agent tool tests build selections from live elements * test(studio): agent tools on a sealed preview look, select, inspect, write and read back * test(studio): resolver and tool tests find elements through the preview read * test(studio): the socket-pool walk waits for studio_look's ready scene
This commit is contained in:
@@ -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);
|
||||
@@ -25,7 +31,7 @@ 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,
|
||||
@@ -33,7 +39,7 @@ describe("readLiveSelectionBox", () => {
|
||||
});
|
||||
});
|
||||
|
||||
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 = {
|
||||
@@ -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");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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,
|
||||
@@ -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 },
|
||||
@@ -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,
|
||||
@@ -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: {
|
||||
@@ -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),
|
||||
@@ -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),
|
||||
@@ -182,7 +167,7 @@ export function StudioAgentTools() {
|
||||
}),
|
||||
[
|
||||
getSnapshot,
|
||||
previewIframeRef,
|
||||
preview,
|
||||
buildDomSelectionFromTarget,
|
||||
applyDomSelection,
|
||||
projectId,
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
resolveLiveHandleSelection,
|
||||
timelineElementAddress,
|
||||
} from "./handles";
|
||||
import { previewDoc } from "./webmcpTestUtils";
|
||||
import { documentPreview, liveTarget, previewDoc } from "./webmcpTestUtils";
|
||||
|
||||
function timelineElement(overrides: Partial<TimelineElement>): TimelineElement {
|
||||
return { id: "synthetic-id", tag: "div", start: 0, duration: 1, track: 0, ...overrides };
|
||||
@@ -59,11 +59,11 @@ describe("resolveLiveHandleSelection", () => {
|
||||
let currentDoc = firstDoc;
|
||||
|
||||
const result = await resolveLiveHandleSelection(
|
||||
() => currentDoc,
|
||||
documentPreview(() => currentDoc),
|
||||
"dom:headline",
|
||||
async (element) => {
|
||||
currentDoc = replacementDoc;
|
||||
return { element };
|
||||
return { element: liveTarget(element) };
|
||||
},
|
||||
);
|
||||
|
||||
@@ -74,9 +74,9 @@ describe("resolveLiveHandleSelection", () => {
|
||||
const doc = previewDoc("<main>settled</main>");
|
||||
|
||||
const result = await resolveLiveHandleSelection(
|
||||
() => doc,
|
||||
documentPreview(() => doc),
|
||||
"dom:headline",
|
||||
async (element) => ({ element }),
|
||||
async (element) => ({ element: liveTarget(element) }),
|
||||
);
|
||||
|
||||
expect(result).toEqual({ status: "not-found" });
|
||||
|
||||
@@ -12,8 +12,12 @@
|
||||
* untouched. The agent never builds one; it passes back what a read gave it.
|
||||
*/
|
||||
|
||||
import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";
|
||||
import type { TimelineElement } from "../player/store/timelineElement";
|
||||
import type { PreviewElement } from "../player/lib/previewElements";
|
||||
import { findElementForSelection } from "../components/editor/domEditingElement";
|
||||
import type { SelectionLookupTarget } from "../components/editor/domEditSelectionRules";
|
||||
import { standInHandle } from "../components/editor/previewSelection";
|
||||
import type { PatchTarget } from "../utils/sourcePatcher";
|
||||
|
||||
const SEPARATOR = ":";
|
||||
@@ -170,27 +174,27 @@ export function parseElementHandle(handle: string): ParsedHandle | null {
|
||||
return scoped ? { scheme, ...scoped, index } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a handle against the preview document.
|
||||
*
|
||||
* Always re-resolve per call rather than holding an element across calls: a
|
||||
* preview reload replaces the document, and a node from the destroyed one is
|
||||
* detached but still looks like an element.
|
||||
*/
|
||||
export function resolveElementHandle(doc: Document, handle: string): HTMLElement | null {
|
||||
export function handleLookup(
|
||||
handle: string,
|
||||
): { target: SelectionLookupTarget; path: string | null } | null {
|
||||
const parsed = parseElementHandle(handle);
|
||||
if (!parsed) return null;
|
||||
return findElementForSelection(
|
||||
doc,
|
||||
{
|
||||
return {
|
||||
target: {
|
||||
hfId: parsed.scheme === "hf" ? parsed.value : undefined,
|
||||
id: parsed.scheme === "dom" ? parsed.value : undefined,
|
||||
selector: parsed.scheme === "sel" ? parsed.value : undefined,
|
||||
selectorIndex: parsed.scheme === "sel" ? parsed.index : undefined,
|
||||
sourceFile: parsed.sourceFile,
|
||||
},
|
||||
parsed.activeCompositionPath ?? null,
|
||||
);
|
||||
path: parsed.activeCompositionPath ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** Re-resolve per call: a reload replaces the document, and a node from the old one still looks like an element. */
|
||||
export function resolveElementHandle(doc: Document, handle: string): HTMLElement | null {
|
||||
const lookup = handleLookup(handle);
|
||||
return lookup ? findElementForSelection(doc, lookup.target, lookup.path) : null;
|
||||
}
|
||||
|
||||
/** Legacy read handles remain valid, but a scoped handle must name the active project. */
|
||||
@@ -207,35 +211,48 @@ export type LiveHandleResolution<T extends { element: HTMLElement }> =
|
||||
| { status: "unsupported" }
|
||||
| { status: "changed" };
|
||||
|
||||
/** `load`: the preview's document, or a sealed frame's per-load port client. `find` is undefined unanswered. */
|
||||
export interface PreviewTargets {
|
||||
load: () => object | null;
|
||||
find: (handle: string) => Promise<HTMLElement | PreviewElement | null | undefined>;
|
||||
}
|
||||
|
||||
function previewMoved(
|
||||
preview: PreviewTargets,
|
||||
load: object,
|
||||
elements: ReadonlyArray<HTMLElement | PreviewElement | undefined>,
|
||||
): boolean {
|
||||
const held = (element: HTMLElement) =>
|
||||
element.ownerDocument === load ? element.isConnected : standInHandle(element) !== undefined;
|
||||
return (
|
||||
preview.load() !== load ||
|
||||
elements.some((element) => element && isHtmlElement(element) && !held(element))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve and build a selection across one possible preview reload.
|
||||
*
|
||||
* Building a selection can await a source probe. A thumbnail refresh may
|
||||
* replace the preview document during that await, leaving an otherwise valid
|
||||
* selection attached to the old document with a truthful-looking 0x0 box.
|
||||
* Reacquire once from the current document, then refuse if it moves again.
|
||||
* Reacquire once from the current load, then refuse if it moves again.
|
||||
*/
|
||||
export async function resolveLiveHandleSelection<T extends { element: HTMLElement }>(
|
||||
getPreviewDocument: () => Document | null,
|
||||
preview: PreviewTargets,
|
||||
handle: string,
|
||||
buildSelection: (element: HTMLElement) => Promise<T | null>,
|
||||
buildSelection: (target: HTMLElement | PreviewElement) => Promise<T | null>,
|
||||
): Promise<LiveHandleResolution<T>> {
|
||||
let reloadObserved = false;
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
const doc = getPreviewDocument();
|
||||
if (!doc) return { status: "preview-unavailable" };
|
||||
const element = resolveElementHandle(doc, handle);
|
||||
if (!element) return { status: reloadObserved ? "changed" : "not-found" };
|
||||
const load = preview.load();
|
||||
if (!load) return { status: "preview-unavailable" };
|
||||
const found = await preview.find(handle);
|
||||
if (found === undefined) return { status: "preview-unavailable" };
|
||||
if (!found) return { status: reloadObserved ? "changed" : "not-found" };
|
||||
|
||||
const selection = await buildSelection(element);
|
||||
const currentDoc = getPreviewDocument();
|
||||
const previewChanged =
|
||||
currentDoc !== doc ||
|
||||
element.ownerDocument !== doc ||
|
||||
!element.isConnected ||
|
||||
(selection !== null &&
|
||||
(selection.element.ownerDocument !== doc || !selection.element.isConnected));
|
||||
if (previewChanged) {
|
||||
const selection = await buildSelection(found);
|
||||
if (previewMoved(preview, load, [found, selection?.element])) {
|
||||
reloadObserved = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -107,10 +107,10 @@ export async function studioSetText(
|
||||
);
|
||||
},
|
||||
write: async (selection) => {
|
||||
const before = selection.element.textContent;
|
||||
const before = (await deps.readNow(selection)).text;
|
||||
const outcome = await deps.setText(selection, text, field);
|
||||
if (!outcome.ok) return fromOutcome(outcome, "the text")!;
|
||||
const value = { text, changed: selection.element.textContent !== before };
|
||||
const value = { text, changed: (await deps.readNow(selection)).text !== before };
|
||||
return outcome.persistence
|
||||
? saved(value, outcome.persistence)
|
||||
: dispatched(value, value.changed);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { studioInspect, type InspectToolDeps, type StudioInspectResult } from ".
|
||||
import {
|
||||
expectFailure,
|
||||
expectOk,
|
||||
documentPreview,
|
||||
previewDoc,
|
||||
previewElement,
|
||||
selectionFor,
|
||||
@@ -43,7 +44,7 @@ describe("studioInspect", () => {
|
||||
it("refuses a scoped handle from another project before inspecting", async () => {
|
||||
const doc = previewDoc('<h1 id="headline">Ship it</h1>');
|
||||
|
||||
const result = await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), {
|
||||
const result = await studioInspect(inspectDeps({ preview: documentPreview(() => doc) }), {
|
||||
handle: sourceHandle("headline", "project-b"),
|
||||
});
|
||||
|
||||
@@ -155,7 +156,7 @@ describe("studioInspect", () => {
|
||||
|
||||
const result = await studioInspect(
|
||||
inspectDeps({
|
||||
getPreviewDocument: () => doc,
|
||||
preview: documentPreview(() => doc),
|
||||
getCurrentSelection: () => selectionFor(headline),
|
||||
getGsapDiagnostics: () => ({
|
||||
animations: [animation()],
|
||||
@@ -177,7 +178,7 @@ describe("studioInspect", () => {
|
||||
const applySelection = vi.fn();
|
||||
|
||||
const result = await studioInspect(
|
||||
inspectDeps({ getPreviewDocument: () => doc, applySelection }),
|
||||
inspectDeps({ preview: documentPreview(() => doc), applySelection }),
|
||||
{ handle: "dom:headline" },
|
||||
);
|
||||
|
||||
@@ -193,7 +194,7 @@ describe("studioInspect", () => {
|
||||
const handle = "dom:v1:index.html:index.html:headline";
|
||||
|
||||
const ok = expectOk<StudioInspectResult>(
|
||||
await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), { handle }),
|
||||
await studioInspect(inspectDeps({ preview: documentPreview(() => doc) }), { handle }),
|
||||
);
|
||||
|
||||
expect(ok.handle).toBe(handle);
|
||||
@@ -231,7 +232,9 @@ describe("studioInspect", () => {
|
||||
|
||||
const doc = previewDoc('<h1 id="headline">A</h1>');
|
||||
const unknown = expectFailure(
|
||||
await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), { handle: "dom:x" }),
|
||||
await studioInspect(inspectDeps({ preview: documentPreview(() => doc) }), {
|
||||
handle: "dom:x",
|
||||
}),
|
||||
);
|
||||
expect(unknown.kind).toBe("invalid");
|
||||
expect(unknown.reason).not.toBe(notMounted.reason);
|
||||
|
||||
@@ -193,7 +193,7 @@ export async function studioInspect(
|
||||
}
|
||||
|
||||
const resolved = await resolveLiveHandleSelection(
|
||||
deps.getPreviewDocument,
|
||||
deps.preview,
|
||||
input.handle,
|
||||
deps.buildSelection,
|
||||
);
|
||||
|
||||
@@ -214,11 +214,16 @@ export function collectStudioLookScene(
|
||||
};
|
||||
}
|
||||
|
||||
const sceneStatusOnceTimelinePosted = (snapshot: StudioLookSnapshot) =>
|
||||
snapshot.duration > 0 ? snapshot.scene.status : "loading";
|
||||
|
||||
function describeScene(snapshot: StudioLookSnapshot): {
|
||||
elements: LookElement[];
|
||||
drillIn: StudioLook["drillIn"];
|
||||
} {
|
||||
if (snapshot.scene.status === "loading") return { elements: [], drillIn: null };
|
||||
const { scene } = snapshot;
|
||||
if (scene.status === "loading" || sceneStatusOnceTimelinePosted(snapshot) === "loading")
|
||||
return { elements: [], drillIn: null };
|
||||
|
||||
const activeCompositionPath = snapshot.compositionPath ?? "index.html";
|
||||
const timelineByHandle = new Map<string, LookTimeline>();
|
||||
@@ -230,7 +235,7 @@ function describeScene(snapshot: StudioLookSnapshot): {
|
||||
}
|
||||
|
||||
const parentHandles: string[] = [];
|
||||
const elements = snapshot.scene.items.map((item) => {
|
||||
const elements = scene.items.map((item) => {
|
||||
const handle = mintElementHandle(
|
||||
patchTargetAddress(item, activeCompositionPath, snapshot.projectId),
|
||||
);
|
||||
@@ -250,7 +255,7 @@ function describeScene(snapshot: StudioLookSnapshot): {
|
||||
};
|
||||
});
|
||||
|
||||
const drillInItem = snapshot.scene.drillInItem;
|
||||
const drillInItem = scene.drillInItem;
|
||||
const drillInHandle = drillInItem
|
||||
? mintElementHandle(patchTargetAddress(drillInItem, activeCompositionPath, snapshot.projectId))
|
||||
: null;
|
||||
@@ -300,7 +305,7 @@ export function buildStudioLook(
|
||||
snapshot.projectId,
|
||||
)
|
||||
: null,
|
||||
sceneStatus: snapshot.scene.status,
|
||||
sceneStatus: sceneStatusOnceTimelinePosted(snapshot),
|
||||
drillIn: scene.drillIn,
|
||||
// The count is of everything that MATCHED, so a truncated list is visible
|
||||
// as a truncated list rather than reading as "that is all there is".
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
type StudioSelectResult,
|
||||
} from "./selectionTools";
|
||||
import {
|
||||
documentPreview,
|
||||
expectFailure,
|
||||
expectOk,
|
||||
previewDoc,
|
||||
@@ -26,7 +27,7 @@ describe("studioSelect", () => {
|
||||
const applySelection = vi.fn();
|
||||
|
||||
const result = await studioSelect(
|
||||
selectionDeps({ getPreviewDocument: () => doc, applySelection }),
|
||||
selectionDeps({ preview: documentPreview(() => doc), applySelection }),
|
||||
sourceHandle("headline", "project-b"),
|
||||
);
|
||||
|
||||
@@ -43,7 +44,7 @@ describe("studioSelect", () => {
|
||||
const applySelection = vi.fn();
|
||||
|
||||
const result = await studioSelect(
|
||||
selectionDeps({ getPreviewDocument: () => doc, applySelection }),
|
||||
selectionDeps({ preview: documentPreview(() => doc), applySelection }),
|
||||
"hf:abc",
|
||||
);
|
||||
|
||||
@@ -62,7 +63,7 @@ describe("studioSelect", () => {
|
||||
const handle = "dom:v1:index.html:index.html:headline";
|
||||
|
||||
const ok = expectOk<StudioSelectResult>(
|
||||
await studioSelect(selectionDeps({ getPreviewDocument: () => doc }), handle),
|
||||
await studioSelect(selectionDeps({ preview: documentPreview(() => doc) }), handle),
|
||||
);
|
||||
|
||||
expect(ok.handle).toBe(handle);
|
||||
@@ -86,7 +87,7 @@ describe("studioSelect", () => {
|
||||
const ok = expectOk<StudioSelectResult>(
|
||||
await studioSelect(
|
||||
selectionDeps({
|
||||
getPreviewDocument: () => currentDoc,
|
||||
preview: documentPreview(() => currentDoc),
|
||||
buildSelection,
|
||||
applySelection,
|
||||
}),
|
||||
@@ -117,7 +118,7 @@ describe("studioSelect", () => {
|
||||
const failure = expectFailure(
|
||||
await studioSelect(
|
||||
selectionDeps({
|
||||
getPreviewDocument: () => documents[currentIndex] ?? documents.at(-1)!,
|
||||
preview: documentPreview(() => documents[currentIndex] ?? documents.at(-1)!),
|
||||
buildSelection,
|
||||
applySelection,
|
||||
}),
|
||||
@@ -141,7 +142,7 @@ describe("studioSelect", () => {
|
||||
|
||||
const doc = previewDoc('<h1 id="headline">Ship it</h1>');
|
||||
const noMatch = expectFailure(
|
||||
await studioSelect(selectionDeps({ getPreviewDocument: () => doc }), "dom:missing"),
|
||||
await studioSelect(selectionDeps({ preview: documentPreview(() => doc) }), "dom:missing"),
|
||||
);
|
||||
expect(noMatch.kind).toBe("invalid");
|
||||
expect(noMatch.reason).toMatch(/no element matches/);
|
||||
@@ -154,7 +155,7 @@ describe("studioSelect", () => {
|
||||
|
||||
const result = expectFailure(
|
||||
await studioSelect(
|
||||
selectionDeps({ getPreviewDocument: () => doc, buildSelection: async () => null }),
|
||||
selectionDeps({ preview: documentPreview(() => doc), buildSelection: async () => null }),
|
||||
"dom:headline",
|
||||
),
|
||||
);
|
||||
@@ -164,12 +165,16 @@ describe("studioSelect", () => {
|
||||
});
|
||||
|
||||
it("rejects a missing handle without touching the preview", async () => {
|
||||
const getPreviewDocument = vi.fn(() => null);
|
||||
const load = vi.fn(() => null);
|
||||
const find = vi.fn(async () => null);
|
||||
|
||||
const result = expectFailure(await studioSelect(selectionDeps({ getPreviewDocument }), " "));
|
||||
const result = expectFailure(
|
||||
await studioSelect(selectionDeps({ preview: { load, find } }), " "),
|
||||
);
|
||||
|
||||
expect(result.kind).toBe("invalid");
|
||||
expect(getPreviewDocument).not.toHaveBeenCalled();
|
||||
expect(load).not.toHaveBeenCalled();
|
||||
expect(find).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("leaves the existing selection alone when it fails", async () => {
|
||||
@@ -177,7 +182,7 @@ describe("studioSelect", () => {
|
||||
const applySelection = vi.fn();
|
||||
|
||||
await studioSelect(
|
||||
selectionDeps({ getPreviewDocument: () => doc, applySelection }),
|
||||
selectionDeps({ preview: documentPreview(() => doc), applySelection }),
|
||||
"dom:missing",
|
||||
);
|
||||
|
||||
|
||||
@@ -8,15 +8,19 @@
|
||||
*/
|
||||
|
||||
import type { DomEditSelection } from "../../components/editor/domEditingTypes";
|
||||
import { elementHandleMatchesProject, resolveLiveHandleSelection } from "../handles";
|
||||
import type { PreviewElement } from "../../player/lib/previewElements";
|
||||
import {
|
||||
elementHandleMatchesProject,
|
||||
resolveLiveHandleSelection,
|
||||
type PreviewTargets,
|
||||
} from "../handles";
|
||||
import { toolFailure, toolOk, type ToolResult } from "../toolResult";
|
||||
|
||||
export interface SelectionToolDeps {
|
||||
/** The preview iframe's document, or null before it mounts. */
|
||||
getPreviewDocument: () => Document | null;
|
||||
preview: PreviewTargets;
|
||||
getCompositionPath: () => string | null;
|
||||
getProjectId: () => string | null;
|
||||
buildSelection: (element: HTMLElement) => Promise<DomEditSelection | null>;
|
||||
buildSelection: (target: HTMLElement | PreviewElement) => Promise<DomEditSelection | null>;
|
||||
applySelection: (selection: DomEditSelection) => void;
|
||||
/** Out-of-loop seek. `requestSeek`, not `setCurrentTime`. */
|
||||
requestSeek: (time: number) => void;
|
||||
@@ -49,11 +53,7 @@ export async function studioSelect(
|
||||
// yet" is a wait, "no such element" is a stale handle, and "could not build a
|
||||
// selection" is an element Studio cannot drive. The agent's next move differs
|
||||
// for each.
|
||||
const resolved = await resolveLiveHandleSelection(
|
||||
deps.getPreviewDocument,
|
||||
handle,
|
||||
deps.buildSelection,
|
||||
);
|
||||
const resolved = await resolveLiveHandleSelection(deps.preview, handle, deps.buildSelection);
|
||||
if (resolved.status === "preview-unavailable") {
|
||||
return toolFailure(
|
||||
"blocked",
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { mintElementHandle } from "../handles";
|
||||
import { previewDoc, selectionFor } from "../webmcpTestUtils";
|
||||
import type { PreviewElement } from "../../player/lib/previewElements";
|
||||
import {
|
||||
documentPreview,
|
||||
liveTarget,
|
||||
previewDoc,
|
||||
readElementNow,
|
||||
selectionFor,
|
||||
} from "../webmcpTestUtils";
|
||||
import {
|
||||
studioAddAnimation,
|
||||
studioAddKeyframe,
|
||||
@@ -22,12 +29,14 @@ function target() {
|
||||
});
|
||||
if (!handle) throw new Error("expected handle");
|
||||
const common = {
|
||||
getPreviewDocument: () => doc,
|
||||
preview: documentPreview(() => doc),
|
||||
getCompositionPath: () => "index.html",
|
||||
getProjectId: () => "demo",
|
||||
getWriteBlockedReason: () => null,
|
||||
buildSelection: async (targetElement: HTMLElement) => selectionFor(targetElement),
|
||||
buildSelection: async (targetElement: HTMLElement | PreviewElement) =>
|
||||
selectionFor(liveTarget(targetElement)),
|
||||
applySelection: () => undefined,
|
||||
readNow: readElementNow,
|
||||
};
|
||||
return { common, element, handle };
|
||||
}
|
||||
@@ -39,7 +48,7 @@ function transformDeps(
|
||||
): TransformToolDeps {
|
||||
return {
|
||||
...common,
|
||||
readBox: () => ({ ...box }),
|
||||
readNow: async () => ({ box: { ...box }, text: null }),
|
||||
moveTo: async () => undefined,
|
||||
resizeTo: async () => undefined,
|
||||
rotateTo: async () => undefined,
|
||||
|
||||
@@ -28,7 +28,7 @@ const transformInput = (input: Record<string, unknown>) => ({
|
||||
function boxStore(initial: ElementBox) {
|
||||
const box = { ...initial };
|
||||
return {
|
||||
read: () => ({ ...box }),
|
||||
read: async () => ({ box: { ...box }, text: null }),
|
||||
set: (next: Partial<ElementBox>) => Object.assign(box, next),
|
||||
};
|
||||
}
|
||||
@@ -38,7 +38,7 @@ function transformDeps(overrides: Partial<TransformToolDeps> = {}): TransformToo
|
||||
const selection = selectionFor(element);
|
||||
return {
|
||||
...targetedWriteDeps(selection),
|
||||
readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }),
|
||||
readNow: async () => ({ box: { x: 0, y: 0, width: 100, height: 50 }, text: null }),
|
||||
moveTo: async () => undefined,
|
||||
resizeTo: async () => undefined,
|
||||
rotateTo: async () => undefined,
|
||||
@@ -54,7 +54,7 @@ async function resizeAndMove(moveLands: boolean): Promise<StudioTransformResult>
|
||||
const moveTo = vi.fn(async () => {
|
||||
if (moveLands) store.set({ x: 40, y: 40 });
|
||||
});
|
||||
const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), {
|
||||
const result = await studioTransform(transformDeps({ readNow: store.read, resizeTo, moveTo }), {
|
||||
...transformInput({ x: 40, y: 40, width: 200, height: 80 }),
|
||||
});
|
||||
return expectOk<StudioTransformResult>(result);
|
||||
@@ -69,7 +69,7 @@ describe("studioTransform", () => {
|
||||
store.set({ width: 300, height: 120 });
|
||||
});
|
||||
|
||||
const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo }), {
|
||||
const result = await studioTransform(transformDeps({ readNow: store.read, resizeTo }), {
|
||||
...transformInput({ width: 999, height: 999 }),
|
||||
});
|
||||
|
||||
@@ -88,7 +88,7 @@ describe("studioTransform", () => {
|
||||
|
||||
const result = expectOk<StudioTransformResult>(
|
||||
await studioTransform(
|
||||
transformDeps({ readBox: store.read, moveTo }),
|
||||
transformDeps({ readNow: store.read, moveTo }),
|
||||
transformInput({ x: 500, y: 400 }),
|
||||
),
|
||||
);
|
||||
@@ -119,7 +119,7 @@ describe("studioTransform", () => {
|
||||
const result = expectOk<StudioTransformResult>(
|
||||
await studioTransform(
|
||||
transformDeps({
|
||||
readBox: store.read,
|
||||
readNow: store.read,
|
||||
resizeTo: async () => {
|
||||
store.set({ width: 200, height: 80 });
|
||||
return {
|
||||
@@ -151,7 +151,7 @@ describe("studioTransform", () => {
|
||||
const result = expectOk<StudioTransformResult>(
|
||||
await studioTransform(
|
||||
transformDeps({
|
||||
readBox: store.read,
|
||||
readNow: store.read,
|
||||
resizeTo: async () => {
|
||||
store.set({ width: 200, height: 80 });
|
||||
return {
|
||||
|
||||
@@ -43,8 +43,6 @@ export interface ElementBox {
|
||||
}
|
||||
|
||||
export interface TransformToolDeps extends TargetedWriteDeps {
|
||||
/** The element's box as it renders right now. */
|
||||
readBox: (selection: DomEditSelection) => ElementBox;
|
||||
moveTo: (
|
||||
selection: DomEditSelection,
|
||||
next: { x: number; y: number },
|
||||
@@ -178,10 +176,10 @@ async function observeResize(
|
||||
selection: DomEditSelection,
|
||||
size: NonNullable<TransformRequest["size"]>,
|
||||
): Promise<TransformObservation | ToolFailure> {
|
||||
const before = deps.readBox(selection);
|
||||
const before = (await deps.readNow(selection)).box;
|
||||
const outcome = await deps.resizeTo(selection, size);
|
||||
if (outcome && !outcome.ok) return outcomeFailure(outcome.reason);
|
||||
const after = deps.readBox(selection);
|
||||
const after = (await deps.readNow(selection)).box;
|
||||
const changed = after.width !== before.width || after.height !== before.height;
|
||||
return {
|
||||
operation: "resize",
|
||||
@@ -196,10 +194,10 @@ async function observeMove(
|
||||
selection: DomEditSelection,
|
||||
move: NonNullable<TransformRequest["move"]>,
|
||||
): Promise<TransformObservation | ToolFailure> {
|
||||
const before = deps.readBox(selection);
|
||||
const before = (await deps.readNow(selection)).box;
|
||||
const outcome = await deps.moveTo(selection, move);
|
||||
if (outcome && !outcome.ok) return outcomeFailure(outcome.reason);
|
||||
const after = deps.readBox(selection);
|
||||
const after = (await deps.readNow(selection)).box;
|
||||
const changed = after.x !== before.x || after.y !== before.y;
|
||||
return {
|
||||
operation: "move",
|
||||
@@ -277,7 +275,7 @@ async function writeTransform(
|
||||
selection: DomEditSelection,
|
||||
request: TransformRequest,
|
||||
): Promise<StudioWriteAdapterSuccess<StudioTransformResult> | ToolFailure> {
|
||||
const initial = deps.readBox(selection);
|
||||
const initial = (await deps.readNow(selection)).box;
|
||||
const observations: TransformObservation[] = [];
|
||||
if (request.size) {
|
||||
const observation = await observeResize(deps, selection, request.size);
|
||||
@@ -288,7 +286,7 @@ async function writeTransform(
|
||||
const observation = await observeMove(deps, selection, request.move);
|
||||
if (isFailure(observation)) {
|
||||
if (observations.length === 0) return observation;
|
||||
return transformReceipt(request, initial, deps.readBox(selection), observations, {
|
||||
return transformReceipt(request, initial, (await deps.readNow(selection)).box, observations, {
|
||||
operation: "move",
|
||||
reason: observation.reason,
|
||||
});
|
||||
@@ -299,14 +297,14 @@ async function writeTransform(
|
||||
const observation = await observeRotation(deps, selection, request.rotate);
|
||||
if (isFailure(observation)) {
|
||||
if (observations.length === 0) return observation;
|
||||
return transformReceipt(request, initial, deps.readBox(selection), observations, {
|
||||
return transformReceipt(request, initial, (await deps.readNow(selection)).box, observations, {
|
||||
operation: "rotate",
|
||||
reason: observation.reason,
|
||||
});
|
||||
}
|
||||
observations.push(observation);
|
||||
}
|
||||
return transformReceipt(request, initial, deps.readBox(selection), observations);
|
||||
return transformReceipt(request, initial, (await deps.readNow(selection)).box, observations);
|
||||
}
|
||||
|
||||
export async function studioTransform(
|
||||
|
||||
@@ -24,7 +24,13 @@ import {
|
||||
import { mountReactHarness } from "../hooks/domSelectionTestHarness";
|
||||
import { mintElementHandle } from "./handles";
|
||||
import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
|
||||
import { previewDoc, selectionFor, studioAgentToolsDeps } from "./webmcpTestUtils";
|
||||
import {
|
||||
documentPreview,
|
||||
liveTarget,
|
||||
previewDoc,
|
||||
selectionFor,
|
||||
studioAgentToolsDeps,
|
||||
} from "./webmcpTestUtils";
|
||||
|
||||
vi.mock("../telemetry/client", () => ({ trackEvent: vi.fn() }));
|
||||
|
||||
@@ -105,8 +111,8 @@ async function mountEditableAgent() {
|
||||
}) as const,
|
||||
);
|
||||
const deps: StudioAgentToolsDeps = studioAgentToolsDeps({
|
||||
getPreviewDocument: () => doc,
|
||||
buildSelection: async (element) => selectionFor(element),
|
||||
preview: documentPreview(() => doc),
|
||||
buildSelection: async (element) => selectionFor(liveTarget(element)),
|
||||
setText,
|
||||
});
|
||||
|
||||
|
||||
@@ -6,7 +6,14 @@ import { writeStudioUiPreferences } from "../utils/studioUiPreferences";
|
||||
import { mintElementHandle } from "./handles";
|
||||
import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
|
||||
import type { ModelContext, ModelContextRegisterToolOptions, ModelContextTool } from "./types";
|
||||
import { lookSnapshot, previewDoc, selectionFor, studioAgentToolsDeps } from "./webmcpTestUtils";
|
||||
import {
|
||||
documentPreview,
|
||||
liveTarget,
|
||||
lookSnapshot,
|
||||
previewDoc,
|
||||
selectionFor,
|
||||
studioAgentToolsDeps,
|
||||
} from "./webmcpTestUtils";
|
||||
|
||||
const trackEvent = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../telemetry/client", () => ({ trackEvent }));
|
||||
@@ -53,8 +60,8 @@ function mountedTargetDeps(overrides: Partial<StudioAgentToolsDeps> = {}) {
|
||||
agentHandle,
|
||||
currentSelection: selectionFor(human),
|
||||
deps: studioAgentToolsDeps({
|
||||
getPreviewDocument: () => doc,
|
||||
buildSelection: async (element) => selectionFor(element),
|
||||
preview: documentPreview(() => doc),
|
||||
buildSelection: async (element) => selectionFor(liveTarget(element)),
|
||||
...overrides,
|
||||
}),
|
||||
};
|
||||
@@ -338,7 +345,8 @@ describe("useStudioAgentTools", () => {
|
||||
const { registered } = installModelContext();
|
||||
const setText = vi.fn();
|
||||
const targeted = mountedTargetDeps({
|
||||
buildSelection: async (element) => selectionFor(element, { isInsideLockedComposition: true }),
|
||||
buildSelection: async (element) =>
|
||||
selectionFor(liveTarget(element), { isInsideLockedComposition: true }),
|
||||
});
|
||||
await act(async () => mountTools({ ...targeted.deps, setText }));
|
||||
|
||||
@@ -424,7 +432,7 @@ describe("useStudioAgentTools", () => {
|
||||
},
|
||||
}),
|
||||
addAnimation: async () => true,
|
||||
readBox: () => ({ ...box }),
|
||||
readNow: async () => ({ box: { ...box }, text: null }),
|
||||
resizeTo: async (_selection, next) => {
|
||||
Object.assign(box, next);
|
||||
return {
|
||||
|
||||
@@ -101,7 +101,7 @@ export interface StudioAgentToolsDeps
|
||||
TransformToolDeps,
|
||||
AnimationToolDeps {
|
||||
/** Read Studio's current state. Called per tool invocation, never cached. */
|
||||
getSnapshot: () => StudioLookSnapshot;
|
||||
getSnapshot: () => StudioLookSnapshot | Promise<StudioLookSnapshot>;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -153,7 +153,7 @@ export function buildStudioTools(depsRef: {
|
||||
},
|
||||
execute: (input): Promise<ToolResult<StudioLook>> =>
|
||||
runToolBody("studio_look", async () =>
|
||||
buildStudioLook(depsRef.current.getSnapshot(), input as StudioLookInput),
|
||||
buildStudioLook(await depsRef.current.getSnapshot(), input as StudioLookInput),
|
||||
),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -8,11 +8,12 @@
|
||||
import { isHtmlElement } from "@hyperframes/core/runtime/dom-realm";
|
||||
import { expect } from "vitest";
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import type { PreviewElement } from "../player/lib/previewElements";
|
||||
import type { ToolFailure, ToolResult } from "./toolResult";
|
||||
import type { StudioLookSnapshot } from "./tools/lookTools";
|
||||
import type { SelectionToolDeps } from "./tools/selectionTools";
|
||||
import type { StudioAgentToolsDeps } from "./useStudioAgentTools";
|
||||
import { mintElementHandle } from "./handles";
|
||||
import { mintElementHandle, resolveElementHandle, type PreviewTargets } from "./handles";
|
||||
import type { TargetedWriteDeps } from "./writeCoordinator";
|
||||
|
||||
/**
|
||||
@@ -38,6 +39,26 @@ export function previewElement(html: string, id: string): HTMLElement {
|
||||
return element;
|
||||
}
|
||||
|
||||
export function liveTarget(target: HTMLElement | PreviewElement): HTMLElement {
|
||||
if (!isHtmlElement(target)) throw new Error("expected a live preview element");
|
||||
return target;
|
||||
}
|
||||
|
||||
export function documentPreview(getDocument: () => Document | null): PreviewTargets {
|
||||
return {
|
||||
load: getDocument,
|
||||
find: async (handle) => {
|
||||
const doc = getDocument();
|
||||
return doc ? resolveElementHandle(doc, handle) : undefined;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function readElementNow(selection: DomEditSelection) {
|
||||
const { x, y, width, height } = selection.element.getBoundingClientRect();
|
||||
return { box: { x, y, width, height }, text: selection.element.textContent };
|
||||
}
|
||||
|
||||
export function selectionFor(
|
||||
element: HTMLElement,
|
||||
overrides: Partial<DomEditSelection> = {},
|
||||
@@ -85,10 +106,10 @@ export function selectionFor(
|
||||
|
||||
export function selectionToolDeps(overrides: Partial<SelectionToolDeps> = {}): SelectionToolDeps {
|
||||
return {
|
||||
getPreviewDocument: () => null,
|
||||
preview: documentPreview(() => null),
|
||||
getCompositionPath: () => "index.html",
|
||||
getProjectId: () => "project-a",
|
||||
buildSelection: async (element) => selectionFor(element),
|
||||
buildSelection: async (element) => selectionFor(liveTarget(element)),
|
||||
applySelection: () => undefined,
|
||||
requestSeek: () => undefined,
|
||||
readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),
|
||||
@@ -109,9 +130,10 @@ export function sourceHandle(domId: string, projectId = "project-a"): string {
|
||||
|
||||
export function targetedWriteDeps(selection: DomEditSelection): TargetedWriteDeps {
|
||||
return {
|
||||
getPreviewDocument: () => selection.element.ownerDocument,
|
||||
preview: documentPreview(() => selection.element.ownerDocument),
|
||||
getProjectId: () => "project-a",
|
||||
getWriteBlockedReason: () => null,
|
||||
readNow: readElementNow,
|
||||
buildSelection: async () => selection,
|
||||
applySelection: () => undefined,
|
||||
};
|
||||
@@ -152,7 +174,7 @@ export function studioAgentToolsDeps(
|
||||
): StudioAgentToolsDeps {
|
||||
return {
|
||||
getSnapshot: () => lookSnapshot(),
|
||||
getPreviewDocument: () => null,
|
||||
preview: documentPreview(() => null),
|
||||
buildSelection: async () => null,
|
||||
applySelection: () => undefined,
|
||||
requestSeek: () => undefined,
|
||||
@@ -165,7 +187,7 @@ export function studioAgentToolsDeps(
|
||||
getWriteBlockedReason: () => null,
|
||||
setText: async () => ({ ok: true }),
|
||||
setStyle: async () => ({ ok: true }),
|
||||
readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }),
|
||||
readNow: async () => ({ box: { x: 0, y: 0, width: 100, height: 50 }, text: null }),
|
||||
moveTo: async () => undefined,
|
||||
resizeTo: async () => undefined,
|
||||
rotateTo: async () => undefined,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { mintElementHandle } from "./handles";
|
||||
import { previewDoc, selectionFor } from "./webmcpTestUtils";
|
||||
import { documentPreview, previewDoc, selectionFor } from "./webmcpTestUtils";
|
||||
import {
|
||||
dispatched,
|
||||
runTargetedWrite,
|
||||
@@ -21,7 +21,7 @@ function fixture() {
|
||||
});
|
||||
if (!handle) throw new Error("expected handle");
|
||||
const deps: TargetedWriteDeps = {
|
||||
getPreviewDocument: () => doc,
|
||||
preview: documentPreview(() => doc),
|
||||
getProjectId: () => "project-a",
|
||||
getWriteBlockedReason: () => null,
|
||||
buildSelection: async (target) => selectionFor(target),
|
||||
@@ -87,7 +87,7 @@ describe("studio write coordinator", () => {
|
||||
const actor = vi.fn();
|
||||
|
||||
const result = await runTargetedWrite(
|
||||
{ ...deps, getPreviewDocument: () => null },
|
||||
{ ...deps, preview: documentPreview(() => null) },
|
||||
{
|
||||
handle,
|
||||
operation: "set-text",
|
||||
@@ -172,7 +172,7 @@ describe("studio write coordinator", () => {
|
||||
const actor = vi.fn();
|
||||
const result = await runTargetedWrite(
|
||||
{
|
||||
getPreviewDocument: () => currentDoc,
|
||||
preview: documentPreview(() => currentDoc),
|
||||
getProjectId: () => "project-a",
|
||||
getWriteBlockedReason: () => null,
|
||||
buildSelection: async (element) => {
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { DomEditSelection } from "../components/editor/domEditingTypes";
|
||||
import { parseElementHandle, resolveLiveHandleSelection } from "./handles";
|
||||
import type { PreviewElement } from "../player/lib/previewElements";
|
||||
import type { ElementNow } from "./agentPreview";
|
||||
import { parseElementHandle, resolveLiveHandleSelection, type PreviewTargets } from "./handles";
|
||||
import { toolFailure, type ToolFailure, type ToolFailureKind } from "./toolResult";
|
||||
|
||||
export type StudioWriteOperation =
|
||||
@@ -58,10 +60,11 @@ export type StudioWriteResult<T extends object> =
|
||||
});
|
||||
|
||||
export interface TargetedWriteDeps {
|
||||
getPreviewDocument: () => Document | null;
|
||||
preview: PreviewTargets;
|
||||
getProjectId: () => string | null;
|
||||
getWriteBlockedReason: () => string | null;
|
||||
buildSelection: (element: HTMLElement) => Promise<DomEditSelection | null>;
|
||||
buildSelection: (target: HTMLElement | PreviewElement) => Promise<DomEditSelection | null>;
|
||||
readNow: (selection: DomEditSelection) => Promise<ElementNow>;
|
||||
applySelection: (selection: DomEditSelection) => void;
|
||||
}
|
||||
|
||||
@@ -167,11 +170,7 @@ async function resolveWriteSelection(
|
||||
deps: TargetedWriteDeps,
|
||||
handle: string,
|
||||
): Promise<ResolvedWriteSelection> {
|
||||
const resolved = await resolveLiveHandleSelection(
|
||||
deps.getPreviewDocument,
|
||||
handle,
|
||||
deps.buildSelection,
|
||||
);
|
||||
const resolved = await resolveLiveHandleSelection(deps.preview, handle, deps.buildSelection);
|
||||
if (resolved.status === "preview-unavailable") {
|
||||
return { ok: false, failure: toolFailure("blocked", "the composition preview is not ready") };
|
||||
}
|
||||
|
||||
@@ -119,8 +119,12 @@ try {
|
||||
await page.goto(STUDIO_URL, { waitUntil: "domcontentloaded" });
|
||||
await page.waitForFunction(() => window.__undoPool?.has("studio_seek"), { timeout: 90_000 });
|
||||
await until(async () => (await call("studio_seek", { time: 1 }).catch(() => null))?.ok, 30_000);
|
||||
const look = await call("studio_look", { limit: 50 });
|
||||
const target = (look.elements ?? []).find((element) => element.label === "Target");
|
||||
let look = null;
|
||||
await until(async () => {
|
||||
look = await call("studio_look", { limit: 50 }).catch(() => null);
|
||||
return look?.sceneStatus === "ready";
|
||||
}, 30_000);
|
||||
const target = (look?.elements ?? []).find((element) => element.label === "Target");
|
||||
if (!target)
|
||||
throw new Error(`studio_look found no #target: ${JSON.stringify(look).slice(0, 400)}`);
|
||||
// Chrome cancels a paused video's request about 15 s after its last use, so on a slow runner the videos stopped
|
||||
|
||||
Reference in New Issue
Block a user