From f4e938fce4e05c5725cfa5b83fce1db16552db00 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 19:41:38 -0400 Subject: [PATCH 01/10] feat(studio): let an agent drive Studio's selection and playhead Adds `studio_select` and `studio_seek`, so an agent and the human are looking at the same element and the same instant. Selecting reveals the inspector, exactly as a click does, which is what makes the agent's move visible. Selection is shared state, not a per-call argument, and that is forced rather than chosen. Most of Studio's edit handlers read the ambient React selection, and `applyDomSelection` only schedules a state update, so selecting and committing inside ONE call would write to whatever was selected before. Two tool calls are separated by a render, so the contract is select first, then act. That is also how a human works: click, then type. `studio_seek` uses `requestSeek`, not `setCurrentTime`. The latter only moves the timeline's displayed number and leaves the composition where it was. Two things the tools refuse to fake: Seek does not clamp. `seek()` already clamps against the adapter's duration, which can differ from the store's, and clamping again would give that invariant two owners that can disagree. The tool reports where the playhead actually landed instead, read back afterwards. `requestSeek` is fire-and-forget, so it cannot report that no adapter was mounted to receive it. The tool compares the playhead before and after and fails rather than claiming a seek that never happened. Select separates three failures that a single message would have merged: the preview is not mounted yet (wait), no element matches the handle (re-read), and the element cannot be selected (try a neighbour). The agent's next move differs for each, so collapsing them would cost it a round trip or a retry loop. --- .../studio/src/webmcp/StudioAgentTools.tsx | 36 ++- packages/studio/src/webmcp/toolResult.ts | 2 +- .../src/webmcp/tools/selectionTools.test.ts | 214 ++++++++++++++++++ .../studio/src/webmcp/tools/selectionTools.ts | 154 +++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 63 ++++-- .../studio/src/webmcp/useStudioAgentTools.ts | 50 +++- 6 files changed, 487 insertions(+), 32 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/selectionTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/selectionTools.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index 8060d7382b..0130ce1a9a 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -1,8 +1,8 @@ -import { useCallback } from "react"; -import { useDomEditSelectionContext } from "../contexts/DomEditContext"; +import { useCallback, useMemo } from "react"; +import { useDomEditActionsContext, useDomEditSelectionContext } from "../contexts/DomEditContext"; import { useStudioShellContext } from "../contexts/StudioContext"; import { usePlayerStore } from "../player"; -import { useStudioAgentTools } from "./useStudioAgentTools"; +import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools"; import type { StudioLookSnapshot } from "./tools/lookTools"; /** @@ -12,14 +12,15 @@ import type { StudioLookSnapshot } from "./tools/lookTools"; * contexts are only readable below `DomEditProvider`, which `App` renders, and * `App.tsx` sits three lines under the 600-line cap. * - * The player store is read IMPERATIVELY through `getState()` inside the - * snapshot callback rather than subscribed to. Subscribing to `currentTime` - * would re-render this component on every animation frame during playback for - * a value nothing here displays. + * The player store is read IMPERATIVELY through `getState()` rather than + * subscribed to. Subscribing to `currentTime` would re-render this component on + * every animation frame during playback for a value nothing here displays. */ export function StudioAgentTools() { const { projectId, activeCompPath, editHistory } = useStudioShellContext(); const { domEditSelection, selectedGsapAnimations } = useDomEditSelectionContext(); + const { previewIframeRef, buildDomSelectionFromTarget, applyDomSelection } = + useDomEditActionsContext(); const getSnapshot = useCallback((): StudioLookSnapshot => { const player = usePlayerStore.getState(); @@ -41,6 +42,25 @@ export function StudioAgentTools() { }; }, [projectId, activeCompPath, domEditSelection, selectedGsapAnimations, editHistory]); - useStudioAgentTools({ getSnapshot }); + const deps = useMemo( + () => ({ + getSnapshot, + getPreviewDocument: () => previewIframeRef.current?.contentDocument ?? null, + buildSelection: (element) => buildDomSelectionFromTarget(element), + applySelection: (selection) => applyDomSelection(selection, { revealPanel: true }), + requestSeek: (time) => usePlayerStore.getState().requestSeek(time), + readPlayhead: () => { + const player = usePlayerStore.getState(); + return { + currentTime: player.currentTime, + duration: player.duration, + isPlaying: player.isPlaying, + }; + }, + }), + [getSnapshot, previewIframeRef, buildDomSelectionFromTarget, applyDomSelection], + ); + + useStudioAgentTools(deps); return null; } diff --git a/packages/studio/src/webmcp/toolResult.ts b/packages/studio/src/webmcp/toolResult.ts index fd803ec10c..fcfdc7684a 100644 --- a/packages/studio/src/webmcp/toolResult.ts +++ b/packages/studio/src/webmcp/toolResult.ts @@ -36,7 +36,7 @@ export function toolOk(value: T): { ok: true } & T { return { ok: true, ...value }; } -function toolFailure(kind: ToolFailureKind, reason: string, hint?: string): ToolFailure { +export function toolFailure(kind: ToolFailureKind, reason: string, hint?: string): ToolFailure { return hint ? { ok: false, kind, reason, hint } : { ok: false, kind, reason }; } diff --git a/packages/studio/src/webmcp/tools/selectionTools.test.ts b/packages/studio/src/webmcp/tools/selectionTools.test.ts new file mode 100644 index 0000000000..c6ec5fdd2a --- /dev/null +++ b/packages/studio/src/webmcp/tools/selectionTools.test.ts @@ -0,0 +1,214 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { + studioSeek, + studioSelect, + type SelectionToolDeps, + type StudioSeekResult, + type StudioSelectResult, +} from "./selectionTools"; +import type { ToolFailure, ToolResult } from "../toolResult"; + +function previewDoc(html: string): Document { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + const doc = iframe.contentDocument; + if (!doc) throw new Error("expected iframe document"); + doc.body.innerHTML = html; + return doc; +} + +function selectionFor(element: HTMLElement): DomEditSelection { + return { + id: element.id || undefined, + hfId: element.getAttribute("data-hf-id") ?? undefined, + element, + label: "Headline", + tagName: element.tagName.toLowerCase(), + sourceFile: "index.html", + compositionPath: "index.html", + isCompositionHost: false, + isInsideLockedComposition: false, + boundingBox: { x: 40, y: 12, width: 880, height: 96 }, + textContent: element.textContent, + dataAttributes: {}, + inlineStyles: {}, + computedStyles: {}, + textFields: [], + capabilities: { + canSelect: true, + canEditStyles: true, + canCrop: true, + canMove: true, + canResize: true, + canApplyManualOffset: true, + canApplyManualSize: true, + canApplyManualRotation: true, + }, + }; +} + +function selectionDeps(overrides: Partial = {}): SelectionToolDeps { + return { + getPreviewDocument: () => null, + buildSelection: async (element) => selectionFor(element), + applySelection: () => undefined, + requestSeek: () => undefined, + readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }), + ...overrides, + }; +} + +function expectFailure(result: ToolResult): ToolFailure { + if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); + return result; +} + +function expectOk(result: ToolResult): { ok: true } & T { + if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); + return result; +} + +describe("studioSelect", () => { + it("applies the selection a click would produce and reports it back", async () => { + const doc = previewDoc('

Ship it

'); + const applySelection = vi.fn(); + + const result = await studioSelect( + selectionDeps({ getPreviewDocument: () => doc, applySelection }), + "hf:abc", + ); + + const ok = expectOk(result); + expect(ok.handle).toBe("hf:abc"); + expect(ok.label).toBe("Headline"); + expect(ok.box.width).toBe(880); + // Reveals the inspector, which is what makes the human see what the agent did. + expect(applySelection).toHaveBeenCalledTimes(1); + }); + + it("distinguishes a preview that is not mounted from a handle that does not match", async () => { + const notMounted = expectFailure(await studioSelect(selectionDeps(), "dom:headline")); + expect(notMounted.kind).toBe("blocked"); + expect(notMounted.reason).toMatch(/not mounted/); + + const doc = previewDoc('

Ship it

'); + const noMatch = expectFailure( + await studioSelect(selectionDeps({ getPreviewDocument: () => doc }), "dom:missing"), + ); + expect(noMatch.kind).toBe("invalid"); + expect(noMatch.reason).toMatch(/no element matches/); + // The two must not be the same message: waiting and re-reading are different fixes. + expect(noMatch.reason).not.toBe(notMounted.reason); + }); + + it("reports an element Studio cannot build a selection for, as a third case", async () => { + const doc = previewDoc('

Ship it

'); + + const result = expectFailure( + await studioSelect( + selectionDeps({ getPreviewDocument: () => doc, buildSelection: async () => null }), + "dom:headline", + ), + ); + + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/cannot select/); + }); + + it("rejects a missing handle without touching the preview", async () => { + const getPreviewDocument = vi.fn(() => null); + + const result = expectFailure(await studioSelect(selectionDeps({ getPreviewDocument }), " ")); + + expect(result.kind).toBe("invalid"); + expect(getPreviewDocument).not.toHaveBeenCalled(); + }); + + it("leaves the existing selection alone when it fails", async () => { + const doc = previewDoc('

Ship it

'); + const applySelection = vi.fn(); + + await studioSelect( + selectionDeps({ getPreviewDocument: () => doc, applySelection }), + "dom:missing", + ); + + expect(applySelection).not.toHaveBeenCalled(); + }); +}); + +describe("studioSeek", () => { + it("reports where the playhead landed, not what was requested", () => { + // The player clamps against the ADAPTER's duration, which the wrapper + // deliberately does not second-guess. + let currentTime = 0; + const result = studioSeek( + selectionDeps({ + requestSeek: () => { + currentTime = 10; + }, + readPlayhead: () => ({ currentTime, duration: 10, isPlaying: false }), + }), + 999, + ); + + const ok = expectOk(result); + expect(ok.playhead).toBe(10); + expect(ok.moved).toBe(true); + }); + + it("reports that playback stopped", () => { + let isPlaying = true; + let currentTime = 0; + const result = studioSeek( + selectionDeps({ + requestSeek: () => { + currentTime = 2; + isPlaying = false; + }, + readPlayhead: () => ({ currentTime, duration: 10, isPlaying }), + }), + 2, + ); + + expect(expectOk(result).isPlaying).toBe(false); + }); + + it("fails rather than claiming a seek the player never received", () => { + // `requestSeek` is fire-and-forget: with no adapter mounted it silently does + // nothing, and reporting ok would be a lie the agent builds on. + const result = expectFailure( + studioSeek( + selectionDeps({ readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }) }), + 5, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/did not move/); + }); + + it("succeeds when asked to seek to where the playhead already is", () => { + const result = studioSeek( + selectionDeps({ readPlayhead: () => ({ currentTime: 3, duration: 10, isPlaying: false }) }), + 3, + ); + + // Nothing moved, but nothing failed either, and `moved` says which. + const ok = expectOk(result); + expect(ok.moved).toBe(false); + expect(ok.playhead).toBe(3); + }); + + it("rejects a non-finite time without calling the player", () => { + const requestSeek = vi.fn(); + + for (const time of [Number.NaN, Number.POSITIVE_INFINITY]) { + const result = expectFailure(studioSeek(selectionDeps({ requestSeek }), time)); + expect(result.kind).toBe("invalid"); + } + expect(requestSeek).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/webmcp/tools/selectionTools.ts b/packages/studio/src/webmcp/tools/selectionTools.ts new file mode 100644 index 0000000000..fa40f52d8f --- /dev/null +++ b/packages/studio/src/webmcp/tools/selectionTools.ts @@ -0,0 +1,154 @@ +/** + * `studio_select` and `studio_seek`: pointing the human and the agent at the + * same thing. + * + * Selection is shared state, not a per-call argument. That is deliberate and it + * is also forced: most of Studio's edit handlers read the ambient React + * selection, and `applyDomSelection` only schedules a state update, so + * selecting and committing inside ONE call would write to whatever was selected + * before. Two tool calls are separated by a render, so the contract is select + * first, then act, which is also how a human works: click, then type. + */ + +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { mintElementHandle, patchTargetAddress, resolveElementHandle } 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; + buildSelection: (element: HTMLElement) => Promise; + applySelection: (selection: DomEditSelection) => void; + /** Out-of-loop seek. `requestSeek`, not `setCurrentTime`. */ + requestSeek: (time: number) => void; + readPlayhead: () => { currentTime: number; duration: number; isPlaying: boolean }; +} + +export interface StudioSelectResult { + handle: string | null; + label: string; + tagName: string; + box: { x: number; y: number; width: number; height: number }; +} + +export async function studioSelect( + deps: SelectionToolDeps, + handle: string, +): Promise> { + if (typeof handle !== "string" || !handle.trim()) { + return toolFailure("invalid", "handle must be a non-empty string", "Call studio_look first."); + } + + // Three distinct failures, deliberately not collapsed: "the preview is not up + // 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 doc = deps.getPreviewDocument(); + if (!doc) { + return toolFailure( + "blocked", + "the preview is not mounted yet", + "Wait for the composition to load, then retry.", + ); + } + + const element = resolveElementHandle(doc, handle); + if (!element) { + return toolFailure( + "invalid", + `no element matches handle ${handle}`, + "The composition may have changed. Call studio_look for current handles.", + ); + } + + const selection = await deps.buildSelection(element); + if (!selection) { + return toolFailure( + "blocked", + `${handle} resolved to an element Studio cannot select`, + "Try a parent or child element from studio_look.", + ); + } + + deps.applySelection(selection); + return toolOk({ + handle: mintElementHandle(patchTargetAddress(selection)), + label: selection.label, + tagName: selection.tagName, + box: selection.boundingBox, + }); +} + +export interface StudioSeekResult { + /** Where the playhead ACTUALLY landed, which may differ from the request. */ + playhead: number; + duration: number; + isPlaying: boolean; + moved: boolean; +} + +export function studioSeek(deps: SelectionToolDeps, time: number): ToolResult { + if (typeof time !== "number" || !Number.isFinite(time)) { + return toolFailure("invalid", "time must be a finite number of seconds"); + } + + const before = deps.readPlayhead(); + // Deliberately NOT clamped here. `seek()` already clamps against the + // adapter's duration, which can differ from the store's, and a second clamp + // would give that invariant two owners that can disagree. Report where it + // landed instead. + deps.requestSeek(time); + const after = deps.readPlayhead(); + + // `requestSeek` is fire-and-forget: it cannot report that no adapter was + // mounted to receive it. Reading back is the only way to avoid claiming a + // seek that never happened. + const moved = after.currentTime !== before.currentTime; + if (!moved && before.currentTime !== time) { + return toolFailure( + "blocked", + `the playhead did not move; it is still at ${after.currentTime}`, + "The preview may not be ready. Check studio_look, then retry.", + ); + } + + return toolOk({ + playhead: after.currentTime, + duration: after.duration, + isPlaying: after.isPlaying, + moved, + }); +} + +export const STUDIO_SELECT_INPUT_SCHEMA = { + type: "object", + properties: { + handle: { type: "string", description: "An element handle from studio_look." }, + }, + required: ["handle"], + additionalProperties: false, +} as const; + +export const STUDIO_SELECT_DESCRIPTION = [ + "Select an element in HyperFrames Studio, exactly as clicking it would:", + "the human sees the same selection box and inspector.", + "Takes a handle from studio_look. Most editing tools act on the CURRENT selection,", + "so call this first, then the edit.", + "Returns `ok: true` with the resulting selection, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); + +export const STUDIO_SEEK_INPUT_SCHEMA = { + type: "object", + properties: { + time: { type: "number", minimum: 0, description: "Playhead position in seconds." }, + }, + required: ["time"], + additionalProperties: false, +} as const; + +export const STUDIO_SEEK_DESCRIPTION = [ + "Move the playhead to a time in seconds. Pauses playback.", + "Out-of-range times are clamped by the player, so check the returned `playhead`", + "for where it actually landed rather than assuming it matched your request.", + "Returns `ok: true`, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index c809516b8a..d27665c4a7 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -29,6 +29,19 @@ function snapshot(overrides: Partial = {}): StudioLookSnapsh }; } +/** Full deps with inert defaults; override only what the test is about. */ +function deps(overrides: Partial = {}): StudioAgentToolsDeps { + return { + getSnapshot: () => snapshot(), + getPreviewDocument: () => null, + buildSelection: async () => null, + applySelection: () => undefined, + requestSeek: () => undefined, + readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }), + ...overrides, + }; +} + /** Install a fake `document.modelContext` and report what got registered. */ function installModelContext() { const registered: ModelContextTool[] = []; @@ -50,12 +63,12 @@ function removeModelContext() { Reflect.deleteProperty(document, "modelContext"); } -function mountTools(deps: StudioAgentToolsDeps) { +function mountTools(initial: StudioAgentToolsDeps) { function Probe({ current }: { current: StudioAgentToolsDeps }) { useStudioAgentTools(current); return null; } - const root = mountReactHarness(); + const root = mountReactHarness(); cleanup = () => act(() => root.unmount()); return { rerenderWith(next: StudioAgentToolsDeps) { @@ -82,10 +95,14 @@ describe("useStudioAgentTools", () => { const { registered } = installModelContext(); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registered.map((tool) => tool.name)).toEqual(["studio_look"]); + expect(registered.map((tool) => tool.name)).toEqual([ + "studio_look", + "studio_select", + "studio_seek", + ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -97,16 +114,16 @@ describe("useStudioAgentTools", () => { let harness: ReturnType | null = null; await act(async () => { - harness = mountTools({ getSnapshot: () => snapshot() }); + harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(1); + expect(registerTool).toHaveBeenCalledTimes(3); await act(async () => { - harness?.rerenderWith({ getSnapshot: () => snapshot({ currentTime: 5 }) }); - harness?.rerenderWith({ getSnapshot: () => snapshot({ currentTime: 6 }) }); + harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); + harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(1); + expect(registerTool).toHaveBeenCalledTimes(3); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -116,11 +133,11 @@ describe("useStudioAgentTools", () => { let harness: ReturnType | null = null; await act(async () => { - harness = mountTools({ getSnapshot: () => snapshot({ currentTime: 1 }) }); + harness = mountTools(deps({ getSnapshot: () => snapshot({ currentTime: 1 }) })); }); await act(async () => { - harness?.rerenderWith({ getSnapshot: () => snapshot({ currentTime: 42 }) }); + harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 42 }) })); }); const look = registered[0]; @@ -138,7 +155,7 @@ describe("useStudioAgentTools", () => { const { registerTool } = installModelContext(); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); const signal = registerTool.mock.calls[0]?.[1]?.signal; expect(signal?.aborted).toBe(false); @@ -153,7 +170,7 @@ describe("useStudioAgentTools", () => { removeModelContext(); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); // The assertion is that mounting did not throw; a browser without the API @@ -166,7 +183,7 @@ describe("useStudioAgentTools", () => { const { registerTool } = installModelContext(); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); expect(registerTool).not.toHaveBeenCalled(); @@ -176,10 +193,10 @@ describe("useStudioAgentTools", () => { const { registerTool } = installModelContext(); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(1); + expect(registerTool).toHaveBeenCalledTimes(3); }); it("reports a non-abort registration failure through production telemetry", async () => { @@ -187,7 +204,7 @@ describe("useStudioAgentTools", () => { registerTool.mockRejectedValue(new DOMException("blocked", "NotAllowedError")); await act(async () => { - mountTools({ getSnapshot: () => snapshot() }); + mountTools(deps({ getSnapshot: () => snapshot() })); }); expect(trackEvent).toHaveBeenCalledWith("webmcp_registration_failed", { @@ -200,11 +217,13 @@ describe("useStudioAgentTools", () => { const { registered } = installModelContext(); await act(async () => { - mountTools({ - getSnapshot: () => { - throw new TypeError("handler signature moved"); - }, - }); + mountTools( + deps({ + getSnapshot: () => { + throw new TypeError("handler signature moved"); + }, + }), + ); }); vi.spyOn(console, "error").mockImplementation(() => {}); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index 6f4fa42e84..2c67d23328 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -14,6 +14,17 @@ import { type StudioLookInput, type StudioLookSnapshot, } from "./tools/lookTools"; +import { + studioSeek, + studioSelect, + STUDIO_SEEK_DESCRIPTION, + STUDIO_SEEK_INPUT_SCHEMA, + STUDIO_SELECT_DESCRIPTION, + STUDIO_SELECT_INPUT_SCHEMA, + type SelectionToolDeps, + type StudioSeekResult, + type StudioSelectResult, +} from "./tools/selectionTools"; const log = makeStudioDebugLogger("webmcp"); @@ -27,7 +38,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } } -export interface StudioAgentToolsDeps { +export interface StudioAgentToolsDeps extends SelectionToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -57,9 +68,46 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): buildStudioLook(depsRef.current.getSnapshot(), input as StudioLookInput), ), }, + { + name: "studio_select", + title: "Select an element", + description: STUDIO_SELECT_DESCRIPTION, + inputSchema: STUDIO_SELECT_INPUT_SCHEMA, + annotations: { readOnlyHint: false, untrustedContentHint: true }, + execute: (input): Promise> => + runToolBody("studio_select", () => + studioSelect(depsRef.current, readStringInput(input, "handle")), + ), + }, + { + name: "studio_seek", + title: "Move the playhead", + description: STUDIO_SEEK_DESCRIPTION, + inputSchema: STUDIO_SEEK_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_seek", async () => + studioSeek(depsRef.current, readNumberInput(input, "time")), + ), + }, ]; } +/** + * Nothing in the platform validates the input object against `inputSchema`, so + * a tool receives whatever the agent sent. These read a field without asserting + * its type; the tools themselves reject what they cannot use. + */ +function readStringInput(input: object, key: string): string { + const value = Reflect.get(input, key); + return typeof value === "string" ? value : ""; +} + +function readNumberInput(input: object, key: string): number { + const value = Reflect.get(input, key); + return typeof value === "number" ? value : Number.NaN; +} + /** * Register Studio's tools with the browser, exactly once per mount. * From 57c9bb0d602f31e1d9b7ec1688eb93e30b20e872 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 19:52:09 -0400 Subject: [PATCH 02/10] feat(studio): give an agent eyes with studio_frame Renders the composition to a PNG at a given time and returns the URL. This is what turns the tool set from a remote control into a loop: author a change, capture the instant it affects, look, adjust. No agent can judge motion from source, because "what does this look like at 2.4 seconds" is not a question a file answers. Reuses Studio's existing capture endpoint via `buildFrameCaptureUrl` rather than inventing a second one. Two things this does not fake: It reports the time the playhead LANDED on, not the time requested. The player clamps, so those differ at the ends, and attaching the wrong time to a frame is how an agent draws a confident wrong conclusion about motion. It waits before capturing, by default 150ms. The frame is rendered from the file on disk, and the render cache is cleared by a file watcher with a 40ms write-stability threshold, so a capture that beats the watcher renders the PRE-edit composition. That exact staleness was a real bug here once. An agent reading a stale frame as "my edit failed" would thrash, so the wait is on by default, `settleMs` makes it tunable, and the tool description names the failure rather than leaving it to be rediscovered. It probes with HEAD before returning, so a URL that 404s comes back as a failure with a hint instead of as a link the agent cannot render. --- .../studio/src/webmcp/StudioAgentTools.tsx | 23 ++- .../src/webmcp/tools/frameTools.test.ts | 146 ++++++++++++++++++ .../studio/src/webmcp/tools/frameTools.ts | 133 ++++++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 11 +- .../studio/src/webmcp/useStudioAgentTools.ts | 19 ++- 5 files changed, 327 insertions(+), 5 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/frameTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/frameTools.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index 0130ce1a9a..e26612c175 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -57,8 +57,29 @@ export function StudioAgentTools() { isPlaying: player.isPlaying, }; }, + getProjectId: () => projectId, + getCompositionPath: () => activeCompPath, + // HEAD, not GET: the tool only needs to know the frame renders. Pulling + // the PNG here would download it once for nothing, since the agent + // fetches the URL itself. + probeFrame: async (url) => { + try { + const response = await fetch(url, { method: "HEAD" }); + return { ok: response.ok, status: response.status }; + } catch { + return { ok: false, status: 0 }; + } + }, + wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), }), - [getSnapshot, previewIframeRef, buildDomSelectionFromTarget, applyDomSelection], + [ + getSnapshot, + previewIframeRef, + buildDomSelectionFromTarget, + applyDomSelection, + projectId, + activeCompPath, + ], ); useStudioAgentTools(deps); diff --git a/packages/studio/src/webmcp/tools/frameTools.test.ts b/packages/studio/src/webmcp/tools/frameTools.test.ts new file mode 100644 index 0000000000..e98d5c2e46 --- /dev/null +++ b/packages/studio/src/webmcp/tools/frameTools.test.ts @@ -0,0 +1,146 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { studioFrame, type FrameToolDeps, type StudioFrameResult } from "./frameTools"; +import type { ToolFailure, ToolResult } from "../toolResult"; + +function frameDeps(overrides: Partial = {}): FrameToolDeps { + return { + getProjectId: () => "demo", + getCompositionPath: () => "index.html", + readPlayhead: () => ({ currentTime: 2.4, duration: 10, isPlaying: false }), + requestSeek: () => undefined, + probeFrame: async () => ({ ok: true, status: 200 }), + wait: async () => undefined, + ...overrides, + }; +} + +function expectOk(result: ToolResult): { ok: true } & T { + if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); + return result; +} + +function expectFailure(result: ToolResult): ToolFailure { + if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); + return result; +} + +describe("studioFrame", () => { + it("returns a URL for the composition at the playhead", async () => { + const result = await studioFrame(frameDeps()); + + const ok = expectOk(result); + expect(ok.time).toBe(2.4); + expect(ok.compositionPath).toBe("index.html"); + expect(ok.url).toContain("/thumbnail/"); + expect(ok.url).toContain("t=2.400"); + expect(ok.url).toContain("format=png"); + }); + + it("seeks first when given a time", async () => { + const requestSeek = vi.fn(); + + await studioFrame(frameDeps({ requestSeek }), { time: 5 }); + + expect(requestSeek).toHaveBeenCalledWith(5); + }); + + it("captures where the playhead LANDED, not what was asked for", async () => { + // The player clamps. Reporting the request would attach the wrong time to + // the frame, and an agent judging motion would draw the wrong conclusion. + const result = await studioFrame( + frameDeps({ readPlayhead: () => ({ currentTime: 10, duration: 10, isPlaying: false }) }), + { time: 999 }, + ); + + const ok = expectOk(result); + expect(ok.time).toBe(10); + expect(ok.url).toContain("t=10.000"); + }); + + it("waits before capturing, so a just-made edit is in the frame", async () => { + // The render cache is cleared by a file watcher with a write-stability + // threshold. Capturing faster than that renders the PRE-edit composition. + const wait = vi.fn(async () => undefined); + const order: string[] = []; + + await studioFrame( + frameDeps({ + wait: async (ms) => { + order.push(`wait:${ms}`); + await wait(); + }, + probeFrame: async () => { + order.push("probe"); + return { ok: true, status: 200 }; + }, + }), + ); + + expect(order).toEqual(["wait:150", "probe"]); + }); + + it("honours a caller-supplied settle time and reports it", async () => { + const result = await studioFrame(frameDeps(), { settleMs: 800 }); + + expect(expectOk(result).settledMs).toBe(800); + }); + + it("clamps an absurd settle time rather than hanging", async () => { + const result = await studioFrame(frameDeps(), { settleMs: 10 * 60 * 1000 }); + + expect(expectOk(result).settledMs).toBe(5000); + }); + + it("falls back to the default for a nonsense settle time", async () => { + for (const settleMs of [-1, Number.NaN]) { + const result = await studioFrame(frameDeps(), { settleMs }); + expect(expectOk(result).settledMs).toBe(150); + } + }); + + it("skips the wait entirely when asked for zero", async () => { + const wait = vi.fn(async () => undefined); + + await studioFrame(frameDeps({ wait }), { settleMs: 0 }); + + expect(wait).not.toHaveBeenCalled(); + }); + + it("reports a renderer failure instead of handing back a dead URL", async () => { + const result = expectFailure( + await studioFrame(frameDeps({ probeFrame: async () => ({ ok: false, status: 500 }) })), + ); + + expect(result.kind).toBe("failed"); + expect(result.reason).toContain("500"); + expect(result.hint).toBeDefined(); + }); + + it("fails when no project is open, before touching the renderer", async () => { + const probeFrame = vi.fn(); + + const result = expectFailure( + await studioFrame(frameDeps({ getProjectId: () => null, probeFrame })), + ); + + expect(result.kind).toBe("blocked"); + expect(probeFrame).not.toHaveBeenCalled(); + }); + + it("rejects a negative or non-finite time without seeking", async () => { + const requestSeek = vi.fn(); + + for (const time of [-1, Number.NaN, Number.POSITIVE_INFINITY]) { + const result = expectFailure(await studioFrame(frameDeps({ requestSeek }), { time })); + expect(result.kind).toBe("invalid"); + } + expect(requestSeek).not.toHaveBeenCalled(); + }); + + it("captures the master composition when no path is active", async () => { + const result = await studioFrame(frameDeps({ getCompositionPath: () => null })); + + expect(expectOk(result).compositionPath).toBe("index.html"); + }); +}); diff --git a/packages/studio/src/webmcp/tools/frameTools.ts b/packages/studio/src/webmcp/tools/frameTools.ts new file mode 100644 index 0000000000..839e4c231d --- /dev/null +++ b/packages/studio/src/webmcp/tools/frameTools.ts @@ -0,0 +1,133 @@ +/** + * `studio_frame`: the eyes. + * + * Without this the tool set is a remote control. With it an agent can author a + * change, look at the instant it affects, judge it, and adjust. That loop is the + * one thing source alone cannot support, because "what does this look like at + * 2.4 seconds" is not a question a file can answer. + * + * Reuses Studio's existing capture endpoint (`utils/frameCapture`) rather than + * inventing a second one. The server renders the composition with Puppeteer, so + * the frame reflects the file on disk, not the live preview DOM. + */ + +import { buildFrameCaptureUrl } from "../../utils/frameCapture"; +import { toolFailure, toolOk, type ToolResult } from "../toolResult"; + +export interface FrameToolDeps { + getProjectId: () => string | null; + getCompositionPath: () => string | null; + readPlayhead: () => { currentTime: number; duration: number; isPlaying: boolean }; + requestSeek: (time: number) => void; + /** Confirms the URL renders. Injected so tests need no network. */ + probeFrame: (url: string) => Promise<{ ok: boolean; status: number }>; + wait: (ms: number) => Promise; +} + +export interface StudioFrameResult { + /** Fetch this to see the frame. A PNG of the composition at `time`. */ + url: string; + time: number; + compositionPath: string; + /** How long the tool waited for a pending write to settle before capturing. */ + settledMs: number; +} + +export interface StudioFrameInput { + /** Seconds. Omit to capture wherever the playhead already is. */ + time?: number; + /** + * Milliseconds to wait before capturing, so a just-written edit is visible. + * See the staleness note in the description. + */ + settleMs?: number; +} + +/** + * Long enough to cover the project watcher's 40ms write-stability threshold + * plus filesystem latency, short enough not to be felt. This is the mitigation + * for a real, previously-fixed bug: the preview signature is invalidated by a + * file watcher, and a capture that beats the watcher renders the PRE-edit + * composition. An agent reading that as "my edit failed" would thrash. + */ +const DEFAULT_SETTLE_MS = 150; +const MAX_SETTLE_MS = 5_000; + +export async function studioFrame( + deps: FrameToolDeps, + input: StudioFrameInput = {}, +): Promise> { + const projectId = deps.getProjectId(); + if (!projectId) { + return toolFailure("blocked", "no project is open"); + } + + if (input.time !== undefined) { + if (typeof input.time !== "number" || !Number.isFinite(input.time) || input.time < 0) { + return toolFailure("invalid", "time must be a non-negative, finite number of seconds"); + } + deps.requestSeek(input.time); + } + + const settledMs = clampSettle(input.settleMs); + if (settledMs > 0) await deps.wait(settledMs); + + // Capture whatever the playhead now reads, rather than what was requested: + // the player clamps, so those can differ and the frame belongs to the former. + const { currentTime } = deps.readPlayhead(); + const compositionPath = deps.getCompositionPath(); + const url = buildFrameCaptureUrl({ projectId, compositionPath, currentTime }); + + const probe = await deps.probeFrame(url); + if (!probe.ok) { + return toolFailure( + "failed", + `the renderer returned ${probe.status} for this frame`, + "The composition may not build. Try `hyperframes check`.", + ); + } + + return toolOk({ + url, + time: currentTime, + compositionPath: compositionPath ?? "index.html", + settledMs, + }); +} + +function clampSettle(requested: number | undefined): number { + if (requested === undefined) return DEFAULT_SETTLE_MS; + if (typeof requested !== "number" || !Number.isFinite(requested) || requested < 0) { + return DEFAULT_SETTLE_MS; + } + return Math.min(requested, MAX_SETTLE_MS); +} + +export const STUDIO_FRAME_INPUT_SCHEMA = { + type: "object", + properties: { + time: { + type: "number", + minimum: 0, + description: "Seconds. Omit to capture wherever the playhead already is.", + }, + settleMs: { + type: "integer", + minimum: 0, + maximum: MAX_SETTLE_MS, + description: `Wait this long before capturing so a just-made edit is included. Default ${DEFAULT_SETTLE_MS}.`, + }, + }, + additionalProperties: false, +} as const; + +export const STUDIO_FRAME_DESCRIPTION = [ + "Render the composition to a PNG at a given time and return its URL, so you can", + "SEE the result instead of inferring it from source. Use this to judge a change:", + "edit, capture the instant it affects, look, adjust.", + "The frame is rendered from the file on disk, not the live preview.", + "A capture taken immediately after an edit can therefore predate that edit, because", + "the render cache is cleared by a file watcher. The tool waits briefly to cover that;", + "raise `settleMs` if a frame still looks stale, rather than concluding the edit failed.", + "Returns `ok: true` with `url` and the `time` actually captured, or `ok: false`.", +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index d27665c4a7..d9c7dd4081 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -38,6 +38,10 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe applySelection: () => undefined, requestSeek: () => undefined, readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }), + getProjectId: () => "demo", + getCompositionPath: () => "index.html", + probeFrame: async () => ({ ok: true, status: 200 }), + wait: async () => undefined, ...overrides, }; } @@ -102,6 +106,7 @@ describe("useStudioAgentTools", () => { "studio_look", "studio_select", "studio_seek", + "studio_frame", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -116,14 +121,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(3); + expect(registerTool).toHaveBeenCalledTimes(4); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(3); + expect(registerTool).toHaveBeenCalledTimes(4); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -196,7 +201,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(3); + expect(registerTool).toHaveBeenCalledTimes(4); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index 2c67d23328..9af5b8cc61 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -25,6 +25,14 @@ import { type StudioSeekResult, type StudioSelectResult, } from "./tools/selectionTools"; +import { + studioFrame, + STUDIO_FRAME_DESCRIPTION, + STUDIO_FRAME_INPUT_SCHEMA, + type FrameToolDeps, + type StudioFrameInput, + type StudioFrameResult, +} from "./tools/frameTools"; const log = makeStudioDebugLogger("webmcp"); @@ -38,7 +46,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } } -export interface StudioAgentToolsDeps extends SelectionToolDeps { +export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -90,6 +98,15 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): studioSeek(depsRef.current, readNumberInput(input, "time")), ), }, + { + name: "studio_frame", + title: "See the composition", + description: STUDIO_FRAME_DESCRIPTION, + inputSchema: STUDIO_FRAME_INPUT_SCHEMA, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execute: (input): Promise> => + runToolBody("studio_frame", () => studioFrame(depsRef.current, input as StudioFrameInput)), + }, ]; } From 1478adfacb013580c7839f08bacc9c8f684d2052 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 20:02:39 -0400 Subject: [PATCH 03/10] feat(studio): add studio_inspect, so an agent reads before it writes Everything about one element in one call: resolved styles, text fields, box, data attributes, GSAP animations, and what the element will and will not accept. The point is to prevent a failed write rather than to satisfy curiosity. `can.reasonIfDisabled` is passed through verbatim from Studio's own capabilities, so an agent that reads first should never attempt an edit the element would refuse. Three things it refuses to get wrong: Animations are reported ONLY for the current selection, because that is the only element Studio parses them for. Attributing them to any other element would be reporting the wrong element's motion, which is worse than reporting none. When a handle names something else the field is empty and `animationEditingBlocked` says why. `animationEditingBlocked` also carries the two states where animation editing is off entirely, multiple timelines and an unsupported timeline pattern. Both live on the selection context. Learning them from a read costs one call; learning them from a failed write costs a retry loop. Inspecting a handle does NOT change what is selected. It is a read, and stealing the human's selection would be a side effect they did not ask for. There is a test asserting `applySelection` is never called. Nothing selected and no handle given is a failure, not an empty result. An empty result would assert "this element has nothing", which is a different and false claim. --- .../studio/src/webmcp/StudioAgentTools.tsx | 17 +- .../src/webmcp/tools/frameTools.test.ts | 12 +- .../src/webmcp/tools/inspectTools.test.ts | 197 +++++++++++++++++ .../studio/src/webmcp/tools/inspectTools.ts | 208 ++++++++++++++++++ .../src/webmcp/tools/selectionTools.test.ts | 52 +---- .../src/webmcp/useStudioAgentTools.test.tsx | 13 +- .../studio/src/webmcp/useStudioAgentTools.ts | 21 +- packages/studio/src/webmcp/webmcpTestUtils.ts | 91 ++++++++ 8 files changed, 544 insertions(+), 67 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/inspectTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/inspectTools.ts create mode 100644 packages/studio/src/webmcp/webmcpTestUtils.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index e26612c175..4fbf55e689 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -18,7 +18,12 @@ import type { StudioLookSnapshot } from "./tools/lookTools"; */ export function StudioAgentTools() { const { projectId, activeCompPath, editHistory } = useStudioShellContext(); - const { domEditSelection, selectedGsapAnimations } = useDomEditSelectionContext(); + const { + domEditSelection, + selectedGsapAnimations, + gsapMultipleTimelines, + gsapUnsupportedTimelinePattern, + } = useDomEditSelectionContext(); const { previewIframeRef, buildDomSelectionFromTarget, applyDomSelection } = useDomEditActionsContext(); @@ -71,6 +76,12 @@ export function StudioAgentTools() { } }, wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + getCurrentSelection: () => domEditSelection, + getGsapDiagnostics: () => ({ + animations: selectedGsapAnimations, + multipleTimelines: gsapMultipleTimelines, + unsupportedTimelinePattern: gsapUnsupportedTimelinePattern, + }), }), [ getSnapshot, @@ -79,6 +90,10 @@ export function StudioAgentTools() { applyDomSelection, projectId, activeCompPath, + domEditSelection, + selectedGsapAnimations, + gsapMultipleTimelines, + gsapUnsupportedTimelinePattern, ], ); diff --git a/packages/studio/src/webmcp/tools/frameTools.test.ts b/packages/studio/src/webmcp/tools/frameTools.test.ts index e98d5c2e46..8ac0b5a432 100644 --- a/packages/studio/src/webmcp/tools/frameTools.test.ts +++ b/packages/studio/src/webmcp/tools/frameTools.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; import { studioFrame, type FrameToolDeps, type StudioFrameResult } from "./frameTools"; -import type { ToolFailure, ToolResult } from "../toolResult"; +import { expectFailure, expectOk } from "../webmcpTestUtils"; function frameDeps(overrides: Partial = {}): FrameToolDeps { return { @@ -15,16 +15,6 @@ function frameDeps(overrides: Partial = {}): FrameToolDeps { }; } -function expectOk(result: ToolResult): { ok: true } & T { - if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); - return result; -} - -function expectFailure(result: ToolResult): ToolFailure { - if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); - return result; -} - describe("studioFrame", () => { it("returns a URL for the composition at the playhead", async () => { const result = await studioFrame(frameDeps()); diff --git a/packages/studio/src/webmcp/tools/inspectTools.test.ts b/packages/studio/src/webmcp/tools/inspectTools.test.ts new file mode 100644 index 0000000000..d59034a45f --- /dev/null +++ b/packages/studio/src/webmcp/tools/inspectTools.test.ts @@ -0,0 +1,197 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser"; +import { studioInspect, type InspectToolDeps, type StudioInspectResult } from "./inspectTools"; +import { + expectFailure, + expectOk, + previewDoc, + previewElement, + selectionFor, +} from "../webmcpTestUtils"; + +function animation(overrides: Partial = {}): GsapAnimation { + return { + id: "anim-1", + targetSelector: "#headline", + method: "from", + position: 0, + properties: { y: -50, opacity: 0 }, + duration: 1, + ease: "power2.out", + ...overrides, + } as GsapAnimation; +} + +function inspectDeps(overrides: Partial = {}): InspectToolDeps { + return { + getPreviewDocument: () => null, + buildSelection: async (element) => selectionFor(element), + applySelection: () => undefined, + requestSeek: () => undefined, + readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }), + getCurrentSelection: () => null, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + ...overrides, + }; +} + +describe("studioInspect", () => { + it("returns the resolved styles, not the authored ones", async () => { + const element = previewElement('

Ship it

', "headline"); + const selection = selectionFor(element); + + const result = await studioInspect(inspectDeps({ getCurrentSelection: () => selection })); + + const ok = expectOk(result); + // The authored value is a clamp(); the resolved one is what actually renders. + expect(ok.styles["font-size"]).toBe("42.7px"); + expect(ok.inlineStyles.color).toBe("red"); + expect(ok.box.width).toBe(880); + }); + + it("reports capabilities and the disabled reason verbatim", async () => { + const element = previewElement('

Ship it

', "headline"); + const locked = selectionFor(element, { + capabilities: { + canSelect: true, + canEditStyles: false, + canCrop: false, + canMove: false, + canResize: false, + canApplyManualOffset: false, + canApplyManualSize: false, + canApplyManualRotation: false, + reasonIfDisabled: "Element is inside a locked composition", + }, + }); + + const result = await studioInspect(inspectDeps({ getCurrentSelection: () => locked })); + + const ok = expectOk(result); + expect(ok.can.editStyles).toBe(false); + expect(ok.can.move).toBe(false); + expect(ok.can.reasonIfDisabled).toBe("Element is inside a locked composition"); + }); + + it("lists the animations on the current selection", async () => { + const element = previewElement('

Ship it

', "headline"); + + const result = await studioInspect( + inspectDeps({ + getCurrentSelection: () => selectionFor(element), + getGsapDiagnostics: () => ({ + animations: [animation()], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + }), + ); + + const ok = expectOk(result); + expect(ok.animations).toHaveLength(1); + expect(ok.animations[0]?.animationId).toBe("anim-1"); + expect(ok.animations[0]?.ease).toBe("power2.out"); + expect(ok.animationEditingBlocked).toBeNull(); + }); + + it("says WHY animation editing is unavailable, so a write is not attempted", async () => { + const element = previewElement('

Ship it

', "headline"); + const base = { + getCurrentSelection: () => selectionFor(element), + }; + + const multiple = await studioInspect( + inspectDeps({ + ...base, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: true, + unsupportedTimelinePattern: false, + }), + }), + ); + const unsupported = await studioInspect( + inspectDeps({ + ...base, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: true, + }), + }), + ); + + expect(expectOk(multiple).animationEditingBlocked).toMatch( + /multiple GSAP timelines/, + ); + expect(expectOk(unsupported).animationEditingBlocked).toMatch( + /not editable/, + ); + }); + + it("does not attribute the selection's animations to a different element", async () => { + // Studio only parses animations for the CURRENT selection. Reporting them + // against another element would report the wrong element's motion. + const headline = previewElement('

A

B

', "headline"); + const doc = headline.ownerDocument; + + const result = await studioInspect( + inspectDeps({ + getPreviewDocument: () => doc, + getCurrentSelection: () => selectionFor(headline), + getGsapDiagnostics: () => ({ + animations: [animation()], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + }), + { handle: "dom:body" }, + ); + + const ok = expectOk(result); + expect(ok.isCurrentSelection).toBe(false); + expect(ok.animations).toEqual([]); + expect(ok.animationEditingBlocked).toMatch(/only readable for the current selection/); + }); + + it("inspects a handle without changing what is selected", async () => { + const doc = previewDoc('

A

'); + const applySelection = vi.fn(); + + const result = await studioInspect( + inspectDeps({ getPreviewDocument: () => doc, applySelection }), + { handle: "dom:headline" }, + ); + + expect(result.ok).toBe(true); + // Inspecting is a read. It must not steal the human's selection. + expect(applySelection).not.toHaveBeenCalled(); + }); + + it("fails rather than returning an empty result when nothing is selected", async () => { + const result = expectFailure(await studioInspect(inspectDeps())); + + // An empty result would assert "this element has nothing", a different and + // false claim from "you did not say which element". + expect(result.kind).toBe("invalid"); + expect(result.reason).toMatch(/nothing is selected/); + expect(result.hint).toMatch(/studio_select/); + }); + + it("reports an unknown handle distinctly from an unmounted preview", async () => { + const notMounted = expectFailure(await studioInspect(inspectDeps(), { handle: "dom:x" })); + expect(notMounted.kind).toBe("blocked"); + + const doc = previewDoc('

A

'); + const unknown = expectFailure( + await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), { handle: "dom:x" }), + ); + expect(unknown.kind).toBe("invalid"); + expect(unknown.reason).not.toBe(notMounted.reason); + }); +}); diff --git a/packages/studio/src/webmcp/tools/inspectTools.ts b/packages/studio/src/webmcp/tools/inspectTools.ts new file mode 100644 index 0000000000..f31b9fc834 --- /dev/null +++ b/packages/studio/src/webmcp/tools/inspectTools.ts @@ -0,0 +1,208 @@ +/** + * `studio_inspect`: everything about one element, in one call. + * + * The point is to prevent a failed write. Every field here either tells the + * agent what it can change (`can`, with `reasonIfDisabled` verbatim) or what it + * would be changing (the resolved styles, the text fields, the animations). + * An agent that reads this first should never attempt an edit the element will + * refuse. + * + * The GSAP diagnostics are here for the same reason: `multipleTimelines` and + * `unsupportedTimelinePattern` are states where animation editing is off, and + * learning that from a read is cheaper than learning it from a failed write. + */ + +import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser"; +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { mintElementHandle, patchTargetAddress, resolveElementHandle } from "../handles"; +import { toolFailure, toolOk, type ToolResult } from "../toolResult"; +import type { SelectionToolDeps } from "./selectionTools"; + +export interface InspectToolDeps extends SelectionToolDeps { + /** What the human currently has selected, used when no handle is given. */ + getCurrentSelection: () => DomEditSelection | null; + getGsapDiagnostics: () => { + animations: readonly GsapAnimation[]; + multipleTimelines: boolean; + unsupportedTimelinePattern: boolean; + }; +} + +interface InspectAnimation { + animationId: string; + method: string; + target: string; + position: number | string; + duration: number | null; + ease: string | null; + properties: Record; + hasKeyframes: boolean; + hasArcPath: boolean; +} + +interface InspectTextField { + key: string; + label: string; + value: string; + tagName: string; +} + +export interface StudioInspectResult { + handle: string | null; + label: string; + tagName: string; + sourceFile: string; + box: { x: number; y: number; width: number; height: number }; + text: string | null; + textFields: InspectTextField[]; + /** The styles Studio itself surfaces, resolved, not as authored. */ + styles: Record; + inlineStyles: Record; + dataAttributes: Record; + can: { + editStyles: boolean; + move: boolean; + resize: boolean; + rotate: boolean; + crop: boolean; + editText: boolean; + reasonIfDisabled: string | null; + }; + animations: InspectAnimation[]; + /** Present only when animation editing is unavailable, with the reason. */ + animationEditingBlocked: string | null; + /** True when this element is the one the human currently has selected. */ + isCurrentSelection: boolean; +} + +export interface StudioInspectInput { + /** Omit to inspect the current selection. */ + handle?: string; +} + +function describeAnimation(animation: GsapAnimation): InspectAnimation { + return { + animationId: animation.id, + method: animation.method, + target: animation.targetSelector, + position: animation.position, + duration: animation.duration ?? null, + ease: animation.ease ?? null, + properties: animation.properties, + hasKeyframes: animation.keyframes !== undefined, + hasArcPath: animation.arcPath !== undefined, + }; +} + +function describe( + selection: DomEditSelection, + deps: InspectToolDeps, + isCurrentSelection: boolean, +): ToolResult { + const { capabilities } = selection; + const gsap = deps.getGsapDiagnostics(); + + // Only the CURRENT selection's animations are parsed by Studio. Reporting + // them for some other element would be reporting the wrong element's motion, + // which is worse than reporting none. + const animations = isCurrentSelection ? gsap.animations.map(describeAnimation) : []; + + let animationEditingBlocked: string | null = null; + if (!isCurrentSelection) { + animationEditingBlocked = "animations are only readable for the current selection"; + } else if (gsap.multipleTimelines) { + animationEditingBlocked = "this composition has multiple GSAP timelines"; + } else if (gsap.unsupportedTimelinePattern) { + animationEditingBlocked = "this composition's timeline pattern is not editable by Studio"; + } + + return toolOk({ + handle: mintElementHandle(patchTargetAddress(selection)), + label: selection.label, + tagName: selection.tagName, + sourceFile: selection.sourceFile, + box: selection.boundingBox, + text: selection.textContent, + textFields: selection.textFields.map((field) => ({ + key: field.key, + label: field.label, + value: field.value, + tagName: field.tagName, + })), + styles: selection.computedStyles, + inlineStyles: selection.inlineStyles, + dataAttributes: selection.dataAttributes, + can: { + editStyles: capabilities.canEditStyles, + move: capabilities.canMove || capabilities.canApplyManualOffset, + resize: capabilities.canResize || capabilities.canApplyManualSize, + rotate: capabilities.canApplyManualRotation, + crop: capabilities.canCrop, + editText: selection.textFields.length > 0, + reasonIfDisabled: capabilities.reasonIfDisabled ?? null, + }, + animations, + animationEditingBlocked, + isCurrentSelection, + }); +} + +export async function studioInspect( + deps: InspectToolDeps, + input: StudioInspectInput = {}, +): Promise> { + const current = deps.getCurrentSelection(); + + if (!input.handle) { + // An empty result here would assert "this element has nothing", which is a + // different and false claim from "you did not tell me which element". + if (!current) { + return toolFailure( + "invalid", + "nothing is selected and no handle was given", + "Pass a handle from studio_look, or call studio_select first.", + ); + } + return describe(current, deps, true); + } + + const doc = deps.getPreviewDocument(); + if (!doc) return toolFailure("blocked", "the preview is not mounted yet"); + + const element = resolveElementHandle(doc, input.handle); + if (!element) { + return toolFailure( + "invalid", + `no element matches handle ${input.handle}`, + "Call studio_look for current handles.", + ); + } + + const selection = await deps.buildSelection(element); + if (!selection) { + return toolFailure("blocked", `${input.handle} resolved to an element Studio cannot inspect`); + } + + return describe(selection, deps, current?.element === element); +} + +export const STUDIO_INSPECT_INPUT_SCHEMA = { + type: "object", + properties: { + handle: { + type: "string", + description: "An element handle from studio_look. Omit to inspect the current selection.", + }, + }, + additionalProperties: false, +} as const; + +export const STUDIO_INSPECT_DESCRIPTION = [ + "Everything about one element: its resolved styles, its text fields, its box,", + "its GSAP animations, and crucially what it will and will not accept.", + "Read this BEFORE editing. `can` tells you which edits are possible and", + "`can.reasonIfDisabled` says why one is not, so you can avoid a write that would be refused.", + "Animations are only readable for the CURRENT selection; `animationEditingBlocked` says when", + "and why animation editing is unavailable.", + "Returns `ok: true`, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); diff --git a/packages/studio/src/webmcp/tools/selectionTools.test.ts b/packages/studio/src/webmcp/tools/selectionTools.test.ts index c6ec5fdd2a..07168529ae 100644 --- a/packages/studio/src/webmcp/tools/selectionTools.test.ts +++ b/packages/studio/src/webmcp/tools/selectionTools.test.ts @@ -1,6 +1,5 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; -import type { DomEditSelection } from "../../components/editor/domEditingTypes"; import { studioSeek, studioSelect, @@ -8,46 +7,7 @@ import { type StudioSeekResult, type StudioSelectResult, } from "./selectionTools"; -import type { ToolFailure, ToolResult } from "../toolResult"; - -function previewDoc(html: string): Document { - const iframe = document.createElement("iframe"); - document.body.append(iframe); - const doc = iframe.contentDocument; - if (!doc) throw new Error("expected iframe document"); - doc.body.innerHTML = html; - return doc; -} - -function selectionFor(element: HTMLElement): DomEditSelection { - return { - id: element.id || undefined, - hfId: element.getAttribute("data-hf-id") ?? undefined, - element, - label: "Headline", - tagName: element.tagName.toLowerCase(), - sourceFile: "index.html", - compositionPath: "index.html", - isCompositionHost: false, - isInsideLockedComposition: false, - boundingBox: { x: 40, y: 12, width: 880, height: 96 }, - textContent: element.textContent, - dataAttributes: {}, - inlineStyles: {}, - computedStyles: {}, - textFields: [], - capabilities: { - canSelect: true, - canEditStyles: true, - canCrop: true, - canMove: true, - canResize: true, - canApplyManualOffset: true, - canApplyManualSize: true, - canApplyManualRotation: true, - }, - }; -} +import { expectFailure, expectOk, previewDoc, selectionFor } from "../webmcpTestUtils"; function selectionDeps(overrides: Partial = {}): SelectionToolDeps { return { @@ -60,16 +20,6 @@ function selectionDeps(overrides: Partial = {}): SelectionToo }; } -function expectFailure(result: ToolResult): ToolFailure { - if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); - return result; -} - -function expectOk(result: ToolResult): { ok: true } & T { - if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); - return result; -} - describe("studioSelect", () => { it("applies the selection a click would produce and reports it back", async () => { const doc = previewDoc('

Ship it

'); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index d9c7dd4081..3a9a3ee988 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -42,6 +42,12 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe getCompositionPath: () => "index.html", probeFrame: async () => ({ ok: true, status: 200 }), wait: async () => undefined, + getCurrentSelection: () => null, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), ...overrides, }; } @@ -107,6 +113,7 @@ describe("useStudioAgentTools", () => { "studio_select", "studio_seek", "studio_frame", + "studio_inspect", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -121,14 +128,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -201,7 +208,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index 9af5b8cc61..c5e1a444eb 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -33,6 +33,14 @@ import { type StudioFrameInput, type StudioFrameResult, } from "./tools/frameTools"; +import { + studioInspect, + STUDIO_INSPECT_DESCRIPTION, + STUDIO_INSPECT_INPUT_SCHEMA, + type InspectToolDeps, + type StudioInspectInput, + type StudioInspectResult, +} from "./tools/inspectTools"; const log = makeStudioDebugLogger("webmcp"); @@ -46,7 +54,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } } -export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps { +export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps, InspectToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -107,6 +115,17 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): execute: (input): Promise> => runToolBody("studio_frame", () => studioFrame(depsRef.current, input as StudioFrameInput)), }, + { + name: "studio_inspect", + title: "Inspect one element", + description: STUDIO_INSPECT_DESCRIPTION, + inputSchema: STUDIO_INSPECT_INPUT_SCHEMA, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execute: (input): Promise> => + runToolBody("studio_inspect", () => + studioInspect(depsRef.current, input as StudioInspectInput), + ), + }, ]; } diff --git a/packages/studio/src/webmcp/webmcpTestUtils.ts b/packages/studio/src/webmcp/webmcpTestUtils.ts new file mode 100644 index 0000000000..8f4f5e96b0 --- /dev/null +++ b/packages/studio/src/webmcp/webmcpTestUtils.ts @@ -0,0 +1,91 @@ +/** + * Shared fixtures for the WebMCP tool tests. + * + * Not a `.test` file so vitest does not collect it as a suite. Mirrors the + * existing `hooks/domSelectionTestHarness.ts` convention. + */ + +import { expect } from "vitest"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; +import type { ToolFailure, ToolResult } from "./toolResult"; + +/** + * An element inside a real iframe, which is where Studio's chrome expects to + * find preview elements. The separate realm matters: a preview element is not + * an instance of Studio's own `HTMLElement`. + */ +export function previewDoc(html: string): Document { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + const doc = iframe.contentDocument; + if (!doc) throw new Error("expected iframe document"); + doc.body.innerHTML = html; + return doc; +} + +export function previewElement(html: string, id: string): HTMLElement { + const doc = previewDoc(html); + const element = doc.getElementById(id); + const HTMLElementCtor = doc.defaultView?.HTMLElement; + if (!HTMLElementCtor || !(element instanceof HTMLElementCtor)) { + throw new Error(`expected preview element #${id}`); + } + return element; +} + +export function selectionFor( + element: HTMLElement, + overrides: Partial = {}, +): DomEditSelection { + return { + id: element.id || undefined, + hfId: element.getAttribute("data-hf-id") ?? undefined, + element, + label: "Headline", + tagName: element.tagName.toLowerCase(), + sourceFile: "index.html", + compositionPath: "index.html", + isCompositionHost: false, + isInsideLockedComposition: false, + boundingBox: { x: 40, y: 12, width: 880, height: 96 }, + textContent: element.textContent, + dataAttributes: { "data-role": "title" }, + inlineStyles: { color: "red" }, + computedStyles: { "font-size": "42.7px", color: "rgb(255, 0, 0)" }, + textFields: [ + { + key: "self", + label: "Text", + value: element.textContent ?? "", + tagName: element.tagName.toLowerCase(), + attributes: [], + inlineStyles: {}, + computedStyles: {}, + source: "self", + }, + ], + capabilities: { + canSelect: true, + canEditStyles: true, + canCrop: true, + canMove: true, + canResize: true, + canApplyManualOffset: true, + canApplyManualSize: true, + canApplyManualRotation: true, + }, + ...overrides, + }; +} + +export function expectOk(result: ToolResult): { ok: true } & T { + expect(result.ok, `expected ok, got ${JSON.stringify(result)}`).toBe(true); + if (!result.ok) throw new Error("unreachable"); + return result; +} + +export function expectFailure(result: ToolResult): ToolFailure { + expect(result.ok, `expected failure, got ${JSON.stringify(result)}`).toBe(false); + if (result.ok) throw new Error("unreachable"); + return result; +} From f766c84c663a240e7b082761aead311a3fa5bb68 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 20:14:51 -0400 Subject: [PATCH 04/10] feat(studio): let an agent edit text and styles, guarded The first tools that change the composition. Both act on the current selection and take no handle, which is forced rather than chosen: the handlers read the ambient React selection, and `applyDomSelection` only schedules a state update, so selecting and committing inside one call would write to whatever was selected before. Select first, then edit. Also plumbs the write-blocked state, which was the blocker for shipping any write at all. `domEditSaveQueuePaused` and the external-file conflict both lived on App and were unreachable from the tool surface, so `canWrite` was optimistic and a comment said so. They now derive into a single `writeBlockedReason` on the shell context: one field, one owner, conflict taking precedence because resolving it is what unblocks the queue. That guard matters more than it looks. Both states are BANNERS in Studio with no lock behind them, so nothing else was stopping a programmatic write from landing on top of a conflict the user had been asked to adjudicate. Three things the tools refuse to fake: They check the outcome, not the absence of a throw. Studio has several paths where a failed commit resolves anyway, so awaiting the handler proves nothing. The tagged outcome added earlier is what proves the write landed. A partial style result is reported as partial. `handleDomStyleCommit` is one property per call, so N properties are N commits; the result carries `applied` and `rejected` maps rather than a single boolean that would have to pick a side. Style commits run sequentially, never concurrently. Two commits racing through Studio's client-side read-modify-write can record undo entries that both claim the same starting content. There is a test that measures concurrency rather than trusting the loop. Every decline reason maps to a hint naming what to do instead, so a refusal routes the agent rather than just stopping it. --- packages/studio/src/App.tsx | 2 + .../studio/src/contexts/StudioContext.tsx | 10 + .../studio/src/hooks/useStudioContextValue.ts | 9 + .../studio/src/webmcp/StudioAgentTools.tsx | 17 +- .../src/webmcp/tools/contentTools.test.ts | 201 ++++++++++++++++++ .../studio/src/webmcp/tools/contentTools.ts | 184 ++++++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 11 +- .../studio/src/webmcp/useStudioAgentTools.ts | 32 ++- 8 files changed, 459 insertions(+), 7 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/contentTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/contentTools.ts diff --git a/packages/studio/src/App.tsx b/packages/studio/src/App.tsx index 6b23e67524..4da005b94e 100644 --- a/packages/studio/src/App.tsx +++ b/packages/studio/src/App.tsx @@ -433,6 +433,8 @@ export function StudioApp() { handleRedo: appHotkeys.handleRedo, renderQueue, compositionDimensions, + domEditSaveQueuePaused: previewPersistence.domEditSaveQueuePaused, + externalFileConflict: externalFileChanges.blocked !== null, waitForPendingDomEditSaves: previewPersistence.waitForPendingDomEditSaves, handlePreviewIframeRef, refreshPreviewDocumentVersion, diff --git a/packages/studio/src/contexts/StudioContext.tsx b/packages/studio/src/contexts/StudioContext.tsx index 97b8ac0be3..291219838a 100644 --- a/packages/studio/src/contexts/StudioContext.tsx +++ b/packages/studio/src/contexts/StudioContext.tsx @@ -16,6 +16,13 @@ export interface StudioShellValue { undoLabel: string | undefined; redoLabel: string | undefined; }; + /** + * Why a composition write would be refused right now, or null when writes + * are possible. Derived from the paused save queue and the external-file + * conflict state, both of which are otherwise banners with no lock behind + * them. One field rather than two, so there is one owner of the question. + */ + writeBlockedReason: string | null; handleUndo: () => Promise; handleRedo: () => Promise; renderQueue: { @@ -106,6 +113,7 @@ export function StudioShellProvider({ showToast, previewIframeRef, editHistory, + writeBlockedReason, handleUndo, handleRedo, renderQueue, @@ -122,6 +130,7 @@ export function StudioShellProvider({ showToast, previewIframeRef, editHistory, + writeBlockedReason, handleUndo, handleRedo, renderQueue, @@ -138,6 +147,7 @@ export function StudioShellProvider({ setActiveCompPath, showToast, previewIframeRef, + writeBlockedReason, handleUndo, handleRedo, waitForPendingDomEditSaves, diff --git a/packages/studio/src/hooks/useStudioContextValue.ts b/packages/studio/src/hooks/useStudioContextValue.ts index 9553d82d0c..1f1250c4fc 100644 --- a/packages/studio/src/hooks/useStudioContextValue.ts +++ b/packages/studio/src/hooks/useStudioContextValue.ts @@ -25,6 +25,10 @@ interface StudioContextInput { // fields around it: the context type owns it. renderQueue: StudioContextValue["renderQueue"]; compositionDimensions: { width: number; height: number } | null; + /** Message from `usePreviewPersistence` when auto-save is paused. */ + domEditSaveQueuePaused: string | null; + /** True when an external edit to the open file is awaiting the user's decision. */ + externalFileConflict: boolean; waitForPendingDomEditSaves: () => Promise; handlePreviewIframeRef: (iframe: HTMLIFrameElement | null) => void; refreshPreviewDocumentVersion: () => void; @@ -46,6 +50,11 @@ export function buildStudioContextValue(input: StudioContextInput): StudioContex timelineElements: input.timelineElements, isPlaying: input.isPlaying, editHistory: input.editHistory, + // Conflict first: when both are true the conflict is the one the user has + // been asked to decide, and resolving it is what unblocks the queue. + writeBlockedReason: input.externalFileConflict + ? "an external change to this file is waiting to be resolved" + : input.domEditSaveQueuePaused, handleUndo: input.handleUndo, handleRedo: input.handleRedo, renderQueue: input.renderQueue, diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index 4fbf55e689..c52ee655b1 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -17,15 +17,20 @@ import type { StudioLookSnapshot } from "./tools/lookTools"; * every animation frame during playback for a value nothing here displays. */ export function StudioAgentTools() { - const { projectId, activeCompPath, editHistory } = useStudioShellContext(); + const { projectId, activeCompPath, editHistory, writeBlockedReason } = useStudioShellContext(); const { domEditSelection, selectedGsapAnimations, gsapMultipleTimelines, gsapUnsupportedTimelinePattern, } = useDomEditSelectionContext(); - const { previewIframeRef, buildDomSelectionFromTarget, applyDomSelection } = - useDomEditActionsContext(); + const { + previewIframeRef, + buildDomSelectionFromTarget, + applyDomSelection, + handleDomTextCommit, + handleDomStyleCommit, + } = useDomEditActionsContext(); const getSnapshot = useCallback((): StudioLookSnapshot => { const player = usePlayerStore.getState(); @@ -77,6 +82,9 @@ export function StudioAgentTools() { }, wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), getCurrentSelection: () => domEditSelection, + getWriteBlockedReason: () => writeBlockedReason, + setText: (value, fieldKey) => handleDomTextCommit(value, fieldKey), + setStyle: (property, value) => handleDomStyleCommit(property, value), getGsapDiagnostics: () => ({ animations: selectedGsapAnimations, multipleTimelines: gsapMultipleTimelines, @@ -90,6 +98,9 @@ export function StudioAgentTools() { applyDomSelection, projectId, activeCompPath, + writeBlockedReason, + handleDomTextCommit, + handleDomStyleCommit, domEditSelection, selectedGsapAnimations, gsapMultipleTimelines, diff --git a/packages/studio/src/webmcp/tools/contentTools.test.ts b/packages/studio/src/webmcp/tools/contentTools.test.ts new file mode 100644 index 0000000000..7b5d825ade --- /dev/null +++ b/packages/studio/src/webmcp/tools/contentTools.test.ts @@ -0,0 +1,201 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { + studioSetStyle, + studioSetText, + type ContentToolDeps, + type StudioSetStyleResult, + type StudioSetTextResult, +} from "./contentTools"; +import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils"; + +function contentDeps(overrides: Partial = {}): ContentToolDeps { + const element = previewElement('

Ship it

', "headline"); + return { + getCurrentSelection: () => selectionFor(element), + getWriteBlockedReason: () => null, + setText: async () => ({ ok: true }), + setStyle: async () => ({ ok: true }), + ...overrides, + }; +} + +describe("studioSetText", () => { + it("writes the text and reports what it now is", async () => { + const setText = vi.fn(async () => ({ ok: true }) as const); + + const result = await studioSetText(contentDeps({ setText }), { text: "Ship it faster" }); + + const ok = expectOk(result); + expect(ok.text).toBe("Ship it faster"); + expect(ok.changed).toBe(true); + expect(setText).toHaveBeenCalledWith("Ship it faster", undefined); + }); + + it("reports changed:false when the text already said that", async () => { + const result = await studioSetText(contentDeps(), { text: "Ship it" }); + + expect(expectOk(result).changed).toBe(false); + }); + + it("refuses to write while a conflict is waiting for the user", async () => { + // The paused-save and conflict states are banners with no lock behind them. + // Nothing else stops a programmatic write landing on top of a decision the + // user has been asked to make. + const setText = vi.fn(); + + const result = expectFailure( + await studioSetText( + contentDeps({ + getWriteBlockedReason: () => "an external change to this file is waiting to be resolved", + setText, + }), + { text: "Ship it faster" }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/external change/); + expect(setText).not.toHaveBeenCalled(); + }); + + it("does not report success when the commit declined", async () => { + // The whole reason the handlers now return an outcome: they resolve on + // failure, so awaiting them proves nothing. + const result = expectFailure( + await studioSetText( + contentDeps({ setText: async () => ({ ok: false, reason: "persist-failed" }) }), + { text: "Ship it faster" }, + ), + ); + + expect(result.kind).toBe("failed"); + expect(result.reason).toMatch(/persist-failed/); + }); + + it("turns a decline reason into a hint naming what to do instead", async () => { + const result = expectFailure( + await studioSetText( + contentDeps({ setText: async () => ({ ok: false, reason: "not-text-editable" }) }), + { text: "x" }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(result.hint).toMatch(/studio_inspect/); + }); + + it("rejects a non-string text without dispatching", async () => { + const setText = vi.fn(); + + const result = expectFailure(await studioSetText(contentDeps({ setText }), { text: 42 })); + + expect(result.kind).toBe("invalid"); + expect(setText).not.toHaveBeenCalled(); + }); + + it("fails when nothing is selected", async () => { + const setText = vi.fn(); + + const result = expectFailure( + await studioSetText(contentDeps({ getCurrentSelection: () => null, setText }), { text: "x" }), + ); + + expect(result.kind).toBe("invalid"); + expect(result.hint).toMatch(/studio_select/); + expect(setText).not.toHaveBeenCalled(); + }); +}); + +describe("studioSetStyle", () => { + it("applies every property and reports them", async () => { + const setStyle = vi.fn(async () => ({ ok: true }) as const); + + const result = await studioSetStyle(contentDeps({ setStyle }), { + styles: { color: "red", "font-size": "48px" }, + }); + + const ok = expectOk(result); + expect(ok.applied).toEqual({ color: "red", "font-size": "48px" }); + expect(ok.rejected).toEqual({}); + expect(setStyle).toHaveBeenCalledTimes(2); + }); + + it("commits sequentially, never concurrently", async () => { + // Two commits racing through Studio's client-side read-modify-write can + // record undo entries that both claim the same starting content. + let inFlight = 0; + let maxInFlight = 0; + const setStyle = vi.fn(async () => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + await Promise.resolve(); + inFlight -= 1; + return { ok: true } as const; + }); + + await studioSetStyle(contentDeps({ setStyle }), { + styles: { color: "red", "font-size": "48px", opacity: "0.5" }, + }); + + expect(maxInFlight).toBe(1); + }); + + it("reports a partial success as partial, not whole", async () => { + const setStyle = vi.fn(async (property: string) => + property === "left" + ? ({ ok: false, reason: "geometry-property" } as const) + : ({ ok: true } as const), + ); + + const result = await studioSetStyle(contentDeps({ setStyle }), { + styles: { color: "red", left: "10px" }, + }); + + const ok = expectOk(result); + expect(ok.applied).toEqual({ color: "red" }); + expect(ok.rejected).toEqual({ left: "geometry-property" }); + }); + + it("fails when every property was refused", async () => { + const result = expectFailure( + await studioSetStyle( + contentDeps({ setStyle: async () => ({ ok: false, reason: "styles-not-editable" }) }), + { styles: { color: "red" } }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/styles-not-editable/); + }); + + it("rejects an empty styles object rather than committing nothing", async () => { + const setStyle = vi.fn(); + + const result = expectFailure(await studioSetStyle(contentDeps({ setStyle }), { styles: {} })); + + expect(result.kind).toBe("invalid"); + expect(setStyle).not.toHaveBeenCalled(); + }); + + it("rejects a non-object styles value", async () => { + for (const styles of ["color: red", 42, null, ["color"]]) { + const result = expectFailure(await studioSetStyle(contentDeps(), { styles })); + expect(result.kind).toBe("invalid"); + } + }); + + it("refuses to write while a conflict is waiting for the user", async () => { + const setStyle = vi.fn(); + + const result = expectFailure( + await studioSetStyle( + contentDeps({ getWriteBlockedReason: () => "Auto-save is paused", setStyle }), + { styles: { color: "red" } }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(setStyle).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/webmcp/tools/contentTools.ts b/packages/studio/src/webmcp/tools/contentTools.ts new file mode 100644 index 0000000000..6e5a85b943 --- /dev/null +++ b/packages/studio/src/webmcp/tools/contentTools.ts @@ -0,0 +1,184 @@ +/** + * `studio_set_text` and `studio_set_style`: the first tools that change the file. + * + * Both operate on the CURRENT selection and take no handle. That is not an + * omission. `handleDomTextCommit(value, fieldKey?)` and + * `handleDomStyleCommit(property, value)` read the ambient React selection, and + * `applyDomSelection` only schedules a state update, so selecting and + * committing inside one call would write to whatever was selected before. + * Two tool calls are separated by a render. Select first, then edit. + * + * Every write here is guarded before dispatch and verified after. Studio has + * several paths where a failed commit resolves anyway, so "the function did not + * throw" proves nothing; the outcome the handler now returns is what proves it. + */ + +import type { DomEditCommitOutcome } from "../../hooks/domEditCommitRunner"; +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult"; + +export interface ContentToolDeps { + getCurrentSelection: () => DomEditSelection | null; + /** Why a write would be refused right now, or null. Checked BEFORE dispatch. */ + getWriteBlockedReason: () => string | null; + setText: (value: string, fieldKey?: string) => Promise; + setStyle: (property: string, value: string) => Promise; +} + +/** + * The reasons a commit declines, translated into something an agent can act on. + * `persist-failed` is exogenous; the rest are states it should route around. + */ +const DECLINE_HINTS: Record = { + "no-selection": { kind: "invalid", hint: "Call studio_select first." }, + "no-project": { kind: "blocked" }, + "geometry-property": { + kind: "blocked", + hint: "Position and size are not editable as styles. Use the transform tools.", + }, + "styles-not-editable": { + kind: "blocked", + hint: "studio_inspect reports why, in can.reasonIfDisabled.", + }, + "not-text-editable": { + kind: "blocked", + hint: "This element has no editable text. studio_inspect lists its textFields.", + }, + "persist-failed": { kind: "failed", hint: "The write did not reach the file. Check Studio." }, +}; + +function fromOutcome(outcome: DomEditCommitOutcome, what: string): ToolFailure | null { + if (outcome.ok) return null; + const mapped = DECLINE_HINTS[outcome.reason] ?? { kind: "failed" as const }; + return toolFailure(mapped.kind, `${what} was not applied: ${outcome.reason}`, mapped.hint); +} + +function guardWrite(deps: ContentToolDeps): ToolFailure | null { + // Both blocked states are banners in Studio's UI with no lock behind them, so + // nothing else stops a programmatic write from landing on top of a conflict + // the user has been asked to adjudicate. + const blocked = deps.getWriteBlockedReason(); + if (blocked) { + return toolFailure("blocked", blocked, "Resolve it in Studio, then retry."); + } + if (!deps.getCurrentSelection()) { + return toolFailure("invalid", "nothing is selected", "Call studio_select first."); + } + return null; +} + +export interface StudioSetTextResult { + text: string; + changed: boolean; +} + +export async function studioSetText( + deps: ContentToolDeps, + input: { text?: unknown; field?: unknown }, +): Promise> { + if (typeof input.text !== "string") { + return toolFailure("invalid", "text must be a string"); + } + const field = typeof input.field === "string" && input.field ? input.field : undefined; + + const blocked = guardWrite(deps); + if (blocked) return blocked; + + const before = deps.getCurrentSelection()?.textContent ?? null; + const outcome = await deps.setText(input.text, field); + const failure = fromOutcome(outcome, "the text"); + if (failure) return failure; + + return toolOk({ text: input.text, changed: before !== input.text }); +} + +export interface StudioSetStyleResult { + applied: Record; + /** Properties the element refused, with the reason. Empty when all landed. */ + rejected: Record; +} + +export async function studioSetStyle( + deps: ContentToolDeps, + input: { styles?: unknown }, +): Promise> { + const styles = input.styles; + if (typeof styles !== "object" || styles === null || Array.isArray(styles)) { + return toolFailure("invalid", "styles must be an object of CSS property to value"); + } + const entries = Object.entries(styles).filter( + (entry): entry is [string, string] => typeof entry[1] === "string", + ); + if (entries.length === 0) { + // An empty commit would report success having done nothing. + return toolFailure("invalid", "styles must contain at least one string value"); + } + + const blocked = guardWrite(deps); + if (blocked) return blocked; + + // `handleDomStyleCommit` is one property per call, so N properties are N + // commits and N undo entries. Sequential, not concurrent: two commits racing + // through Studio's client-side read-modify-write can record undo entries that + // both claim the same starting content. + const applied: Record = {}; + const rejected: Record = {}; + for (const [property, value] of entries) { + const outcome = await deps.setStyle(property, value); + if (outcome.ok) applied[property] = value; + else rejected[property] = outcome.reason; + } + + if (Object.keys(applied).length === 0) { + const reasons = Object.entries(rejected) + .map(([property, reason]) => `${property}: ${reason}`) + .join(", "); + return toolFailure("blocked", `no style was applied (${reasons})`); + } + + return toolOk({ applied, rejected }); +} + +export const STUDIO_SET_TEXT_INPUT_SCHEMA = { + type: "object", + properties: { + text: { type: "string", description: "The new text content." }, + field: { + type: "string", + description: + "Which text field to write, from studio_inspect. Omit for the element's own text.", + }, + }, + required: ["text"], + additionalProperties: false, +} as const; + +export const STUDIO_SET_TEXT_DESCRIPTION = [ + "Set the text of the CURRENTLY SELECTED element. Call studio_select first.", + "This is the edit a synthetic double-click cannot reach, because Studio's canvas", + "takes pointer capture and recognises the double press itself.", + "Returns `ok: true` with the resulting text and whether it changed, or `ok: false`", + "with `kind`, `reason` and usually a `hint` naming what to do instead.", +].join(" "); + +export const STUDIO_SET_STYLE_INPUT_SCHEMA = { + type: "object", + properties: { + styles: { + type: "object", + description: 'CSS property to value, for example {"color": "red", "font-size": "48px"}.', + additionalProperties: { type: "string" }, + }, + }, + required: ["styles"], + additionalProperties: false, +} as const; + +export const STUDIO_SET_STYLE_DESCRIPTION = [ + "Set inline styles on the CURRENTLY SELECTED element. Call studio_select first.", + "Each property is a separate commit, so N properties produce N undo entries.", + "Position and size properties (left, top, width, height) are refused here on purpose;", + "they belong to the transform tools.", + "Returns `ok: true` with `applied` and `rejected` maps, so a partial success is visible", + "as a partial success rather than reported as a whole one.", +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index 3a9a3ee988..8431d84265 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -43,6 +43,9 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe probeFrame: async () => ({ ok: true, status: 200 }), wait: async () => undefined, getCurrentSelection: () => null, + getWriteBlockedReason: () => null, + setText: async () => ({ ok: true }), + setStyle: async () => ({ ok: true }), getGsapDiagnostics: () => ({ animations: [], multipleTimelines: false, @@ -114,6 +117,8 @@ describe("useStudioAgentTools", () => { "studio_seek", "studio_frame", "studio_inspect", + "studio_set_text", + "studio_set_style", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -128,14 +133,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(5); + expect(registerTool).toHaveBeenCalledTimes(7); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(5); + expect(registerTool).toHaveBeenCalledTimes(7); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -208,7 +213,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(5); + expect(registerTool).toHaveBeenCalledTimes(7); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index c5e1a444eb..a8f25c61c8 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -41,6 +41,17 @@ import { type StudioInspectInput, type StudioInspectResult, } from "./tools/inspectTools"; +import { + studioSetStyle, + studioSetText, + STUDIO_SET_STYLE_DESCRIPTION, + STUDIO_SET_STYLE_INPUT_SCHEMA, + STUDIO_SET_TEXT_DESCRIPTION, + STUDIO_SET_TEXT_INPUT_SCHEMA, + type ContentToolDeps, + type StudioSetStyleResult, + type StudioSetTextResult, +} from "./tools/contentTools"; const log = makeStudioDebugLogger("webmcp"); @@ -54,7 +65,8 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } } -export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps, InspectToolDeps { +export interface StudioAgentToolsDeps + extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -126,6 +138,24 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): studioInspect(depsRef.current, input as StudioInspectInput), ), }, + { + name: "studio_set_text", + title: "Set an element's text", + description: STUDIO_SET_TEXT_DESCRIPTION, + inputSchema: STUDIO_SET_TEXT_INPUT_SCHEMA, + annotations: { readOnlyHint: false, untrustedContentHint: true }, + execute: (input): Promise> => + runToolBody("studio_set_text", () => studioSetText(depsRef.current, input)), + }, + { + name: "studio_set_style", + title: "Set an element's styles", + description: STUDIO_SET_STYLE_DESCRIPTION, + inputSchema: STUDIO_SET_STYLE_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_set_style", () => studioSetStyle(depsRef.current, input)), + }, ]; } From b4123be1ca8dd2f55386e3706e56733c20de734c Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 20:54:01 -0400 Subject: [PATCH 05/10] feat(studio): move, resize and rotate, verified by reading back `studio_transform` does what a drag does, and then checks. The box in the result is READ BACK after the write, never echoed from the request, and `applied` lists what actually took effect. That is not belt-and-braces. The plan for this unit said to re-derive the geometry handlers' behaviour rather than trust any description of them, and doing that turned up three different behaviours behind one interface. The handlers on `DomEditActionsValue` are the GSAP-AWARE wrappers, aliased in `useDomEditSession.ts:534-538`, not the CSS ones in `useDomGeometryCommits.ts` that an earlier note in this workstream described. `handleGsapAwarePathOffsetCommit` and `handleGsapAwareRotationCommit` are `if (gsapCommitMutation) { ...intercept... }` with no else branch. Their own comments say the absence is deliberate: position and rotation are written as GSAP code and there is no CSS fallback to write to. So they can return having done nothing. `handleGsapAwareBoxSizeCommit` is not like the other two. It runs through `runGestureTransaction` with separate scale and width/height routes, so resize works more generally. Reading back is what turns that middle case from a silent lie into a reported one. A move that did nothing comes back in `unchanged` with a reason. Three smaller decisions: Operations re-read between each other, so a move is judged against the box AFTER a resize in the same call. Comparing against the original would credit the resize's change to the move. Rotation is reported as dispatched, not verified. `rotate` is an individual transform property and does not appear in the computed transform, so there is no honest box-derived signal, and claiming one would be worse than saying so. x pairs with y and width pairs with height. Accepting one alone would mean inventing the other from the current value, which moves the element somewhere the caller did not ask for. The pairing rule and its minimum live in one `parsePair` helper rather than as four separate branches. --- .../studio/src/webmcp/StudioAgentTools.tsx | 15 ++ .../src/webmcp/tools/transformTools.test.ts | 179 +++++++++++++++ .../studio/src/webmcp/tools/transformTools.ts | 205 ++++++++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 11 +- .../studio/src/webmcp/useStudioAgentTools.ts | 21 +- 5 files changed, 427 insertions(+), 4 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/transformTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/transformTools.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index c52ee655b1..f201ca23bf 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -30,6 +30,9 @@ export function StudioAgentTools() { applyDomSelection, handleDomTextCommit, handleDomStyleCommit, + handleDomPathOffsetCommit, + handleDomBoxSizeCommit, + handleDomRotationCommit, } = useDomEditActionsContext(); const getSnapshot = useCallback((): StudioLookSnapshot => { @@ -85,6 +88,15 @@ export function StudioAgentTools() { getWriteBlockedReason: () => writeBlockedReason, setText: (value, fieldKey) => handleDomTextCommit(value, fieldKey), setStyle: (property, value) => handleDomStyleCommit(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. + readBox: (selection) => { + const rect = selection.element.getBoundingClientRect(); + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; + }, + moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next), + resizeTo: (selection, next) => handleDomBoxSizeCommit(selection, next), + rotateTo: (selection, next) => handleDomRotationCommit(selection, next), getGsapDiagnostics: () => ({ animations: selectedGsapAnimations, multipleTimelines: gsapMultipleTimelines, @@ -101,6 +113,9 @@ export function StudioAgentTools() { writeBlockedReason, handleDomTextCommit, handleDomStyleCommit, + handleDomPathOffsetCommit, + handleDomBoxSizeCommit, + handleDomRotationCommit, domEditSelection, selectedGsapAnimations, gsapMultipleTimelines, diff --git a/packages/studio/src/webmcp/tools/transformTools.test.ts b/packages/studio/src/webmcp/tools/transformTools.test.ts new file mode 100644 index 0000000000..b438ed9e5d --- /dev/null +++ b/packages/studio/src/webmcp/tools/transformTools.test.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { + studioTransform, + type ElementBox, + type StudioTransformResult, + type TransformToolDeps, +} from "./transformTools"; +import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils"; + +/** + * A stand-in for the rendered box. happy-dom and jsdom report all-zero rects, + * so the box is injected rather than measured; these tests are about what the + * tool concludes from a box, not about layout. + */ +function boxStore(initial: ElementBox) { + const box = { ...initial }; + return { + read: () => ({ ...box }), + set: (next: Partial) => Object.assign(box, next), + }; +} + +function transformDeps(overrides: Partial = {}): TransformToolDeps { + const element = previewElement('

Ship it

', "headline"); + return { + getCurrentSelection: () => selectionFor(element), + getWriteBlockedReason: () => null, + readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }), + moveTo: async () => undefined, + resizeTo: async () => undefined, + rotateTo: async () => undefined, + ...overrides, + }; +} + +describe("studioTransform", () => { + it("reports the box read back, not the box requested", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + // The handler lands somewhere other than asked, which is what a clamp or a + // layout constraint does. + const resizeTo = vi.fn(async () => store.set({ width: 300, height: 120 })); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo }), { + width: 999, + height: 999, + }); + + const ok = expectOk(result); + expect(ok.box.width).toBe(300); + expect(ok.box.height).toBe(120); + expect(ok.applied).toContain("resize"); + }); + + it("reports a silent no-op as unchanged instead of success", async () => { + // handleGsapAwarePathOffsetCommit is `if (gsapCommitMutation) {...}` with no + // else branch. Without GSAP it resolves having written nothing, and echoing + // the request back would be a lie the agent builds on. + const store = boxStore({ x: 10, y: 10, width: 100, height: 50 }); + const moveTo = vi.fn(async () => undefined); + + const result = expectFailure( + await studioTransform(transformDeps({ readBox: store.read, moveTo }), { x: 500, y: 400 }), + ); + + expect(moveTo).toHaveBeenCalled(); + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/did not move/); + expect(result.hint).toMatch(/GSAP/); + }); + + it("separates what landed from what did not, in one call", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + const resizeTo = vi.fn(async () => store.set({ width: 200, height: 80 })); + const moveTo = vi.fn(async () => undefined); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), { + x: 40, + y: 40, + width: 200, + height: 80, + }); + + const ok = expectOk(result); + expect(ok.applied).toEqual(["resize"]); + expect(ok.unchanged.move).toMatch(/did not move/); + }); + + it("re-reads between operations so a later one sees the earlier result", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + const resizeTo = vi.fn(async () => store.set({ width: 200, height: 80 })); + const moveTo = vi.fn(async () => store.set({ x: 40, y: 40 })); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), { + x: 40, + y: 40, + width: 200, + height: 80, + }); + + // Move is judged against the box AFTER the resize. Comparing against the + // original would credit the resize's change to the move. + const ok = expectOk(result); + expect(ok.applied).toEqual(["resize", "move"]); + expect(ok.unchanged).toEqual({}); + }); + + it("reports rotation as dispatched rather than verified", async () => { + // `rotate` is an individual transform property and does not appear in the + // computed transform, so there is no honest box-derived signal for it. + const rotateTo = vi.fn(async () => undefined); + + const result = await studioTransform(transformDeps({ rotateTo }), { rotate: 15 }); + + const ok = expectOk(result); + expect(rotateTo).toHaveBeenCalledWith(expect.anything(), { angle: 15 }); + expect(ok.applied).toEqual(["rotate"]); + }); + + it("refuses to write while a conflict is waiting for the user", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform( + transformDeps({ getWriteBlockedReason: () => "Auto-save is paused", moveTo }), + { x: 10, y: 10 }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(moveTo).not.toHaveBeenCalled(); + }); + + it("requires x and y together, and width and height together", async () => { + const moveTo = vi.fn(); + const resizeTo = vi.fn(); + const deps = transformDeps({ moveTo, resizeTo }); + + expect(expectFailure(await studioTransform(deps, { x: 10 })).reason).toMatch(/together/); + expect(expectFailure(await studioTransform(deps, { width: 10 })).reason).toMatch(/together/); + expect(moveTo).not.toHaveBeenCalled(); + expect(resizeTo).not.toHaveBeenCalled(); + }); + + it("rejects a negative size and an empty request", async () => { + const deps = transformDeps(); + + expect(expectFailure(await studioTransform(deps, { width: -1, height: 10 })).kind).toBe( + "invalid", + ); + expect(expectFailure(await studioTransform(deps, {})).reason).toMatch(/at least one/); + }); + + it("rejects non-finite numbers rather than passing them to a handler", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform(transformDeps({ moveTo }), { x: Number.NaN, y: 10 }), + ); + + expect(result.kind).toBe("invalid"); + expect(moveTo).not.toHaveBeenCalled(); + }); + + it("fails when nothing is selected", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform(transformDeps({ getCurrentSelection: () => null, moveTo }), { + x: 1, + y: 1, + }), + ); + + expect(result.kind).toBe("invalid"); + expect(result.hint).toMatch(/studio_select/); + expect(moveTo).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/webmcp/tools/transformTools.ts b/packages/studio/src/webmcp/tools/transformTools.ts new file mode 100644 index 0000000000..0ea9bf670b --- /dev/null +++ b/packages/studio/src/webmcp/tools/transformTools.ts @@ -0,0 +1,205 @@ +/** + * `studio_transform`: move, resize and rotate, as a drag would. + * + * This tool reads the element's box back after every write and reports what + * ACTUALLY changed. That is not belt-and-braces, it is the only thing standing + * between an agent and a silent lie, because two of the three handlers can do + * nothing and resolve: + * + * - The handlers exposed on `DomEditActionsValue` are the GSAP-AWARE wrappers + * (`useDomEditSession.ts` aliases them), not the CSS ones in + * `useDomGeometryCommits.ts`. + * - `handleGsapAwarePathOffsetCommit` and `handleGsapAwareRotationCommit` are + * `if (gsapCommitMutation) { ...intercept... }` with NO else branch. In a + * composition with no GSAP they return having done nothing. The adjacent + * comments confirm that is deliberate: there is no CSS fallback to write to. + * - `handleGsapAwareBoxSizeCommit` is different. It runs through + * `runGestureTransaction` with a scale route and a width/height route, so + * resize works more generally than the other two. + * + * Read back, do not assume. + */ + +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult"; + +export interface ElementBox { + x: number; + y: number; + width: number; + height: number; +} + +export interface TransformToolDeps { + getCurrentSelection: () => DomEditSelection | null; + getWriteBlockedReason: () => string | null; + /** The element's box as it renders right now. */ + readBox: (selection: DomEditSelection) => ElementBox; + moveTo: (selection: DomEditSelection, next: { x: number; y: number }) => Promise; + resizeTo: (selection: DomEditSelection, next: { width: number; height: number }) => Promise; + rotateTo: (selection: DomEditSelection, next: { angle: number }) => Promise; +} + +export interface StudioTransformInput { + x?: unknown; + y?: unknown; + width?: unknown; + height?: unknown; + rotate?: unknown; +} + +export interface StudioTransformResult { + /** The box as it renders after the write, read back, not echoed. */ + box: ElementBox; + applied: string[]; + /** Requested operations whose effect could not be observed, with why. */ + unchanged: Record; +} + +const NO_OP_HINT = + "Move and rotate are written as GSAP code; a composition with no GSAP timeline has nothing to write to. studio_inspect reports the element's animations."; + +function readNumber(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function guard(deps: TransformToolDeps): ToolFailure | null { + const blocked = deps.getWriteBlockedReason(); + if (blocked) return toolFailure("blocked", blocked, "Resolve it in Studio, then retry."); + if (!deps.getCurrentSelection()) { + return toolFailure("invalid", "nothing is selected", "Call studio_select first."); + } + return null; +} + +interface TransformRequest { + move: { x: number; y: number } | null; + size: { width: number; height: number } | null; + rotate: number | null; +} + +/** + * Both or neither. Accepting one axis alone would mean inventing the other from + * the current value, which moves the element somewhere the caller did not ask + * for. + */ +function parsePair( + a: unknown, + b: unknown, + names: [string, string], + min = Number.NEGATIVE_INFINITY, +): { pair: [number, number] | null } | ToolFailure { + const first = readNumber(a); + const second = readNumber(b); + if (first === null && second === null) return { pair: null }; + if (first === null || second === null) { + return toolFailure("invalid", `${names[0]} and ${names[1]} must be given together`); + } + if (first < min || second < min) { + return toolFailure("invalid", `${names[0]} and ${names[1]} must be at least ${min}`); + } + return { pair: [first, second] }; +} + +function isFailure(value: object): value is ToolFailure { + return "ok" in value; +} + +function parseRequest(input: StudioTransformInput): TransformRequest | ToolFailure { + const move = parsePair(input.x, input.y, ["x", "y"]); + if (isFailure(move)) return move; + const size = parsePair(input.width, input.height, ["width", "height"], 0); + if (isFailure(size)) return size; + const rotate = readNumber(input.rotate); + + if (!move.pair && !size.pair && rotate === null) { + return toolFailure( + "invalid", + "give at least one of x, y, width, height, rotate as a finite number", + ); + } + + return { + move: move.pair ? { x: move.pair[0], y: move.pair[1] } : null, + size: size.pair ? { width: size.pair[0], height: size.pair[1] } : null, + rotate, + }; +} + +export async function studioTransform( + deps: TransformToolDeps, + input: StudioTransformInput, +): Promise> { + const request = parseRequest(input); + if (isFailure(request)) return request; + + const blocked = guard(deps); + if (blocked) return blocked; + + const selection = deps.getCurrentSelection(); + if (!selection) return toolFailure("invalid", "nothing is selected"); + + const applied: string[] = []; + const unchanged: Record = {}; + + // Sequential, and each one re-reads first, so a move is judged against the box + // AFTER a resize in the same call rather than against the original. + if (request.size) { + const before = deps.readBox(selection); + await deps.resizeTo(selection, request.size); + const after = deps.readBox(selection); + if (after.width !== before.width || after.height !== before.height) applied.push("resize"); + else unchanged.resize = "the element's size did not change"; + } + + if (request.move) { + const before = deps.readBox(selection); + await deps.moveTo(selection, request.move); + const after = deps.readBox(selection); + if (after.x !== before.x || after.y !== before.y) applied.push("move"); + else unchanged.move = `the element did not move. ${NO_OP_HINT}`; + } + + if (request.rotate !== null) { + // Rotation is written as the CSS `rotate` property, an individual transform + // property that does NOT appear in getComputedStyle().transform. There is no + // reliable box-derived signal, so this is reported as dispatched rather than + // verified, and the description says so. + await deps.rotateTo(selection, { angle: request.rotate }); + applied.push("rotate"); + } + + if (applied.length === 0) { + return toolFailure( + "blocked", + `nothing changed: ${Object.values(unchanged).join("; ")}`, + NO_OP_HINT, + ); + } + + return toolOk({ box: deps.readBox(selection), applied, unchanged }); +} + +export const STUDIO_TRANSFORM_INPUT_SCHEMA = { + type: "object", + properties: { + x: { type: "number", description: "New x offset in pixels. Must be paired with y." }, + y: { type: "number", description: "New y offset in pixels. Must be paired with x." }, + width: { type: "number", minimum: 0, description: "New width. Must be paired with height." }, + height: { type: "number", minimum: 0, description: "New height. Must be paired with width." }, + rotate: { type: "number", description: "Rotation in degrees." }, + }, + additionalProperties: false, +} as const; + +export const STUDIO_TRANSFORM_DESCRIPTION = [ + "Move, resize or rotate the CURRENTLY SELECTED element, the way a drag would.", + "Call studio_select first. Give x with y, and width with height.", + "The result's `box` is READ BACK after the write, not echoed from your request, and", + "`applied` lists what actually took effect. Check it.", + "Move and rotate are written as GSAP code, so in a composition with no GSAP timeline they", + "do nothing; that shows up in `unchanged` rather than as a false success.", + "Rotation is reported as dispatched rather than verified, because the CSS `rotate` property", + "does not appear in the element's computed transform.", + "Returns `ok: true`, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index 8431d84265..274b697c91 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -46,6 +46,10 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe getWriteBlockedReason: () => null, setText: async () => ({ ok: true }), setStyle: async () => ({ ok: true }), + readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }), + moveTo: async () => undefined, + resizeTo: async () => undefined, + rotateTo: async () => undefined, getGsapDiagnostics: () => ({ animations: [], multipleTimelines: false, @@ -119,6 +123,7 @@ describe("useStudioAgentTools", () => { "studio_inspect", "studio_set_text", "studio_set_style", + "studio_transform", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -133,14 +138,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -213,7 +218,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index a8f25c61c8..f62c369bcd 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -52,6 +52,14 @@ import { type StudioSetStyleResult, type StudioSetTextResult, } from "./tools/contentTools"; +import { + studioTransform, + STUDIO_TRANSFORM_DESCRIPTION, + STUDIO_TRANSFORM_INPUT_SCHEMA, + type StudioTransformInput, + type StudioTransformResult, + type TransformToolDeps, +} from "./tools/transformTools"; const log = makeStudioDebugLogger("webmcp"); @@ -66,7 +74,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } export interface StudioAgentToolsDeps - extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps { + extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps, TransformToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -156,6 +164,17 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): execute: (input): Promise> => runToolBody("studio_set_style", () => studioSetStyle(depsRef.current, input)), }, + { + name: "studio_transform", + title: "Move, resize or rotate", + description: STUDIO_TRANSFORM_DESCRIPTION, + inputSchema: STUDIO_TRANSFORM_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_transform", () => + studioTransform(depsRef.current, input as StudioTransformInput), + ), + }, ]; } From 90cef4f251393a8b9fe3c96188fa2c6ae36c74c3 Mon Sep 17 00:00:00 2001 From: Miguel Angel Simon Sierra Date: Wed, 26 Aug 2026 20:59:42 -0400 Subject: [PATCH 06/10] feat(studio): let an agent author motion Four tools: add an animation, change its duration/ease/position, add a keyframe, delete it. This is the capability that makes the tool set worth having, because motion is the one thing an agent cannot judge or author from source. These are deliberately less confident than the rest of the set, and the reason is the handlers underneath them: `handleGsapAddAnimation(method)` takes only a method. Its insert position comes from the live playhead, not the caller, and the call is `void ...catch()` so it returns nothing. `handleGsapAddKeyframeBatch` returns a promise but catches its own failure, so awaiting proves the call finished, not that it landed. `handleGsapDeleteAnimation` discards its promise entirely. `handleGsapUpdateMeta` is the one honest signal. It returns a boolean. U8 handled the same problem by reading the result back. That does not work here: the animation list comes from React state that only refreshes on a render, and no render happens inside one tool call. Rather than fake a verification with a frame-timer, these report what was DISPATCHED and the descriptions tell the agent to call studio_inspect to see the result. Saying "I asked for this" is honest; saying "this happened" would not be. Three consequences worth stating: `studio_add_animation` takes no position. The handler reads the playhead, so accepting one would report a number that had no effect. It reports where the playhead actually was and tells the agent to seek first. `studio_update_animation` rules out the no-selection case BEFORE dispatch. The handler answers `false` for both "nothing selected" and "the write failed", so eliminating one is what makes the other legible. Keyframe percent and properties are validated in the tool, because nothing in the platform checks input against the declared schema. --- .../studio/src/webmcp/StudioAgentTools.tsx | 13 + .../src/webmcp/tools/animationTools.test.ts | 244 ++++++++++++++++ .../studio/src/webmcp/tools/animationTools.ts | 276 ++++++++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 14 +- .../studio/src/webmcp/useStudioAgentTools.ts | 63 +++- 5 files changed, 606 insertions(+), 4 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/animationTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/animationTools.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index f201ca23bf..bdfa2cba31 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -33,6 +33,10 @@ export function StudioAgentTools() { handleDomPathOffsetCommit, handleDomBoxSizeCommit, handleDomRotationCommit, + handleGsapAddAnimation, + handleGsapUpdateMeta, + handleGsapAddKeyframeBatch, + handleGsapDeleteAnimation, } = useDomEditActionsContext(); const getSnapshot = useCallback((): StudioLookSnapshot => { @@ -97,6 +101,11 @@ export function StudioAgentTools() { moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next), resizeTo: (selection, next) => handleDomBoxSizeCommit(selection, next), rotateTo: (selection, next) => handleDomRotationCommit(selection, next), + addAnimation: (method) => handleGsapAddAnimation(method), + updateAnimation: (animationId, updates) => handleGsapUpdateMeta(animationId, updates), + addKeyframe: (animationId, percent, properties) => + handleGsapAddKeyframeBatch(animationId, percent, properties), + deleteAnimation: (animationId) => handleGsapDeleteAnimation(animationId), getGsapDiagnostics: () => ({ animations: selectedGsapAnimations, multipleTimelines: gsapMultipleTimelines, @@ -116,6 +125,10 @@ export function StudioAgentTools() { handleDomPathOffsetCommit, handleDomBoxSizeCommit, handleDomRotationCommit, + handleGsapAddAnimation, + handleGsapUpdateMeta, + handleGsapAddKeyframeBatch, + handleGsapDeleteAnimation, domEditSelection, selectedGsapAnimations, gsapMultipleTimelines, diff --git a/packages/studio/src/webmcp/tools/animationTools.test.ts b/packages/studio/src/webmcp/tools/animationTools.test.ts new file mode 100644 index 0000000000..f8f60bb8d5 --- /dev/null +++ b/packages/studio/src/webmcp/tools/animationTools.test.ts @@ -0,0 +1,244 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { + studioAddAnimation, + studioAddKeyframe, + studioDeleteAnimation, + studioUpdateAnimation, + type AnimationToolDeps, + type StudioAddAnimationResult, + type StudioAddKeyframeResult, + type StudioUpdateAnimationResult, +} from "./animationTools"; +import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils"; + +function animationDeps(overrides: Partial = {}): AnimationToolDeps { + const element = previewElement('

Ship it

', "headline"); + return { + getCurrentSelection: () => selectionFor(element), + getWriteBlockedReason: () => null, + readPlayhead: () => ({ currentTime: 2.4, duration: 10, isPlaying: false }), + addAnimation: () => undefined, + updateAnimation: async () => true, + addKeyframe: async () => undefined, + deleteAnimation: () => undefined, + ...overrides, + }; +} + +describe("studioAddAnimation", () => { + it("reports where the playhead actually was, not a position the caller chose", async () => { + // The handler reads the playhead itself and ignores any position argument, + // so echoing one back would report a number that had no effect. + const addAnimation = vi.fn(); + + const result = await studioAddAnimation( + animationDeps({ + addAnimation, + readPlayhead: () => ({ currentTime: 7.25, duration: 10, isPlaying: false }), + }), + { method: "from" }, + ); + + const ok = expectOk(result); + expect(ok.insertedAtSeconds).toBe(7.25); + expect(ok.method).toBe("from"); + expect(addAnimation).toHaveBeenCalledWith("from"); + }); + + it("marks the result as dispatched rather than claiming it landed", async () => { + // `handleGsapAddAnimation` is fire-and-forget and returns nothing, so there + // is no honest success signal to report. + const result = await studioAddAnimation(animationDeps(), { method: "to" }); + + expect(expectOk(result).dispatched).toBe(true); + }); + + it("rejects an unknown method without dispatching", async () => { + const addAnimation = vi.fn(); + + const result = expectFailure( + await studioAddAnimation(animationDeps({ addAnimation }), { method: "wiggle" }), + ); + + expect(result.kind).toBe("invalid"); + expect(addAnimation).not.toHaveBeenCalled(); + }); + + it("refuses while a write is blocked, and when nothing is selected", async () => { + const addAnimation = vi.fn(); + + const paused = expectFailure( + await studioAddAnimation( + animationDeps({ getWriteBlockedReason: () => "Auto-save is paused", addAnimation }), + { method: "to" }, + ), + ); + const unselected = expectFailure( + await studioAddAnimation(animationDeps({ getCurrentSelection: () => null, addAnimation }), { + method: "to", + }), + ); + + expect(paused.kind).toBe("blocked"); + expect(unselected.kind).toBe("invalid"); + expect(addAnimation).not.toHaveBeenCalled(); + }); +}); + +describe("studioUpdateAnimation", () => { + it("confirms the write, because this handler actually reports back", async () => { + const updateAnimation = vi.fn(async () => true); + + const result = await studioUpdateAnimation(animationDeps({ updateAnimation }), { + animationId: "anim-1", + ease: "power2.out", + duration: 1.5, + }); + + const ok = expectOk(result); + expect(ok.updated).toEqual({ duration: 1.5, ease: "power2.out" }); + expect(updateAnimation).toHaveBeenCalledWith("anim-1", { + duration: 1.5, + ease: "power2.out", + }); + }); + + it("reports a false return as a real failure", async () => { + const result = expectFailure( + await studioUpdateAnimation(animationDeps({ updateAnimation: async () => false }), { + animationId: "anim-gone", + ease: "none", + }), + ); + + expect(result.kind).toBe("failed"); + expect(result.hint).toMatch(/stale/); + }); + + it("rules out the no-selection case BEFORE dispatch, so a false is unambiguous", async () => { + // The handler answers `false` for both "nothing selected" and "the write + // failed". Eliminating one beforehand is what makes the other legible. + const updateAnimation = vi.fn(async () => false); + + const result = expectFailure( + await studioUpdateAnimation( + animationDeps({ getCurrentSelection: () => null, updateAnimation }), + { animationId: "anim-1", ease: "none" }, + ), + ); + + expect(result.kind).toBe("invalid"); + expect(result.reason).toMatch(/nothing is selected/); + expect(updateAnimation).not.toHaveBeenCalled(); + }); + + it("requires at least one field, and rejects a negative duration", async () => { + const deps = animationDeps(); + + expect(expectFailure(await studioUpdateAnimation(deps, { animationId: "a" })).reason).toMatch( + /at least one/, + ); + expect( + expectFailure(await studioUpdateAnimation(deps, { animationId: "a", duration: -1 })).reason, + ).toMatch(/negative/); + }); + + it("rejects a blank animation id", async () => { + const updateAnimation = vi.fn(); + + const result = expectFailure( + await studioUpdateAnimation(animationDeps({ updateAnimation }), { + animationId: " ", + ease: "none", + }), + ); + + expect(result.kind).toBe("invalid"); + expect(updateAnimation).not.toHaveBeenCalled(); + }); +}); + +describe("studioAddKeyframe", () => { + it("passes every property through in one commit", async () => { + const addKeyframe = vi.fn(async () => undefined); + + const result = await studioAddKeyframe(animationDeps({ addKeyframe }), { + animationId: "anim-1", + percent: 50, + properties: { y: -50, opacity: 0 }, + }); + + const ok = expectOk(result); + expect(ok.properties).toEqual({ y: -50, opacity: 0 }); + // One call, so one undo entry, rather than one per property. + expect(addKeyframe).toHaveBeenCalledTimes(1); + expect(addKeyframe).toHaveBeenCalledWith("anim-1", 50, { y: -50, opacity: 0 }); + }); + + it("validates percent itself, because the platform does not", async () => { + // Nothing checks the input object against inputSchema, so the tool receives + // whatever the agent sent. + const addKeyframe = vi.fn(); + const deps = animationDeps({ addKeyframe }); + + for (const percent of [-1, 101, Number.NaN, "50"]) { + const result = expectFailure( + await studioAddKeyframe(deps, { animationId: "a", percent, properties: { y: 1 } }), + ); + expect(result.kind).toBe("invalid"); + } + expect(addKeyframe).not.toHaveBeenCalled(); + }); + + it("rejects properties that carry no usable value", async () => { + const addKeyframe = vi.fn(); + const deps = animationDeps({ addKeyframe }); + + for (const properties of [{}, { y: null }, [], "y:1"]) { + const result = expectFailure( + await studioAddKeyframe(deps, { animationId: "a", percent: 50, properties }), + ); + expect(result.kind).toBe("invalid"); + } + expect(addKeyframe).not.toHaveBeenCalled(); + }); + + it("accepts 0 and 100 as the ends of the tween", async () => { + for (const percent of [0, 100]) { + const result = await studioAddKeyframe(animationDeps(), { + animationId: "a", + percent, + properties: { y: 1 }, + }); + expect(expectOk(result).percent).toBe(percent); + } + }); +}); + +describe("studioDeleteAnimation", () => { + it("dispatches the delete and says so", async () => { + const deleteAnimation = vi.fn(); + + const result = await studioDeleteAnimation(animationDeps({ deleteAnimation }), { + animationId: "anim-1", + }); + + expect(result.ok).toBe(true); + expect(deleteAnimation).toHaveBeenCalledWith("anim-1"); + }); + + it("refuses while a write is blocked", async () => { + const deleteAnimation = vi.fn(); + + const result = expectFailure( + await studioDeleteAnimation( + animationDeps({ getWriteBlockedReason: () => "Auto-save is paused", deleteAnimation }), + { animationId: "anim-1" }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(deleteAnimation).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/webmcp/tools/animationTools.ts b/packages/studio/src/webmcp/tools/animationTools.ts new file mode 100644 index 0000000000..0d5d678bc4 --- /dev/null +++ b/packages/studio/src/webmcp/tools/animationTools.ts @@ -0,0 +1,276 @@ +/** + * `studio_animate`: author motion. + * + * These tools are deliberately less confident than the rest, because the + * handlers underneath them are: + * + * - `handleGsapAddAnimation(method)` takes ONLY a method. Its insert position + * comes from the live playhead, not from the caller, and the call is + * `void ...catch()`, so it returns nothing and cannot be awaited. + * - `handleGsapAddKeyframeBatch` returns a promise but catches its own failure, + * so awaiting it proves the call finished, not that it landed. + * - `handleGsapDeleteAnimation` discards its promise entirely. + * - `handleGsapUpdateMeta` is the one honest signal: it returns a boolean. + * Its `false` is ambiguous though, meaning either no selection or a failed + * write, so the no-selection case is ruled out before dispatch. + * + * U8 solved the same problem by reading the result back. That does not work + * here: the animation list comes from React state that only refreshes on a + * render, and no render happens inside one tool call. So rather than fake a + * verification, these report what was dispatched and tell the agent to call + * `studio_inspect` to see the result. Saying "I asked for this" is honest; + * saying "this happened" would not be. + */ + +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult"; + +export type GsapMethod = "to" | "from" | "set" | "fromTo"; + +const METHODS: readonly GsapMethod[] = ["to", "from", "set", "fromTo"]; + +export interface AnimationToolDeps { + getCurrentSelection: () => DomEditSelection | null; + getWriteBlockedReason: () => string | null; + readPlayhead: () => { currentTime: number; duration: number; isPlaying: boolean }; + addAnimation: (method: GsapMethod) => void; + updateAnimation: ( + animationId: string, + updates: { duration?: number; ease?: string; position?: number }, + ) => Promise; + addKeyframe: ( + animationId: string, + percent: number, + properties: Record, + ) => Promise; + deleteAnimation: (animationId: string) => void; +} + +const INSPECT_HINT = "Call studio_inspect to see the result."; + +function guard(deps: AnimationToolDeps): ToolFailure | null { + const blocked = deps.getWriteBlockedReason(); + if (blocked) return toolFailure("blocked", blocked, "Resolve it in Studio, then retry."); + if (!deps.getCurrentSelection()) { + return toolFailure("invalid", "nothing is selected", "Call studio_select first."); + } + return null; +} + +function readAnimationId(value: unknown): string | null { + return typeof value === "string" && value.trim() ? value : null; +} + +export interface StudioAddAnimationResult { + method: GsapMethod; + /** Where it was inserted, which is the playhead, not a value you supplied. */ + insertedAtSeconds: number; + dispatched: true; +} + +export async function studioAddAnimation( + deps: AnimationToolDeps, + input: { method?: unknown }, +): Promise> { + const method = METHODS.find((candidate) => candidate === input.method); + if (!method) { + return toolFailure("invalid", `method must be one of ${METHODS.join(", ")}`); + } + + const blocked = guard(deps); + if (blocked) return blocked; + + // The handler reads the playhead itself. Reporting a position the caller gave + // us would be reporting a number that had no effect, so the tool takes no + // position and reports where the playhead actually is instead. + const { currentTime } = deps.readPlayhead(); + deps.addAnimation(method); + + return toolOk({ + method, + insertedAtSeconds: currentTime, + dispatched: true, + }); +} + +export interface StudioUpdateAnimationResult { + animationId: string; + updated: { duration?: number; ease?: string; position?: number }; +} + +export async function studioUpdateAnimation( + deps: AnimationToolDeps, + input: { animationId?: unknown; duration?: unknown; ease?: unknown; position?: unknown }, +): Promise> { + const animationId = readAnimationId(input.animationId); + if (!animationId) { + return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT); + } + + const updates: { duration?: number; ease?: string; position?: number } = {}; + if (typeof input.duration === "number" && Number.isFinite(input.duration)) { + if (input.duration < 0) return toolFailure("invalid", "duration must not be negative"); + updates.duration = input.duration; + } + if (typeof input.ease === "string" && input.ease.trim()) updates.ease = input.ease; + if (typeof input.position === "number" && Number.isFinite(input.position)) { + updates.position = input.position; + } + if (Object.keys(updates).length === 0) { + return toolFailure("invalid", "give at least one of duration, ease, position"); + } + + // Ruled out BEFORE dispatch on purpose: the handler answers `false` for both + // "nothing selected" and "the write failed", so a false afterwards would be + // ambiguous. Eliminating one of the two makes the other one legible. + const blocked = guard(deps); + if (blocked) return blocked; + + const landed = await deps.updateAnimation(animationId, updates); + if (!landed) { + return toolFailure( + "failed", + `the update to ${animationId} did not land`, + "The animation id may be stale. studio_inspect lists the current ones.", + ); + } + + return toolOk({ animationId, updated: updates }); +} + +export interface StudioAddKeyframeResult { + animationId: string; + percent: number; + properties: Record; + dispatched: true; +} + +export async function studioAddKeyframe( + deps: AnimationToolDeps, + input: { animationId?: unknown; percent?: unknown; properties?: unknown }, +): Promise> { + const animationId = readAnimationId(input.animationId); + if (!animationId) { + return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT); + } + const percent = input.percent; + if (typeof percent !== "number" || !Number.isFinite(percent) || percent < 0 || percent > 100) { + // Validated here because nothing in the platform checks input against the + // schema; the tool receives whatever the agent sent. + return toolFailure("invalid", "percent must be a number between 0 and 100"); + } + const raw = input.properties; + if (typeof raw !== "object" || raw === null || Array.isArray(raw)) { + return toolFailure("invalid", "properties must be an object of GSAP property to value"); + } + const properties: Record = {}; + for (const [key, value] of Object.entries(raw)) { + if (typeof value === "number" || typeof value === "string") properties[key] = value; + } + if (Object.keys(properties).length === 0) { + return toolFailure("invalid", "properties must contain at least one number or string value"); + } + + const blocked = guard(deps); + if (blocked) return blocked; + + await deps.addKeyframe(animationId, percent, properties); + + return toolOk({ animationId, percent, properties, dispatched: true }); +} + +export interface StudioDeleteAnimationResult { + animationId: string; + dispatched: true; +} + +export async function studioDeleteAnimation( + deps: AnimationToolDeps, + input: { animationId?: unknown }, +): Promise> { + const animationId = readAnimationId(input.animationId); + if (!animationId) { + return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT); + } + + const blocked = guard(deps); + if (blocked) return blocked; + + deps.deleteAnimation(animationId); + return toolOk({ animationId, dispatched: true }); +} + +const DISPATCH_CAVEAT = `Reports what was dispatched, not what landed: the handler underneath does not report back. ${INSPECT_HINT}`; + +export const STUDIO_ADD_ANIMATION_INPUT_SCHEMA = { + type: "object", + properties: { + method: { type: "string", enum: METHODS, description: "The GSAP method to add." }, + }, + required: ["method"], + additionalProperties: false, +} as const; + +export const STUDIO_ADD_ANIMATION_DESCRIPTION = [ + "Add a GSAP animation to the CURRENTLY SELECTED element. Call studio_select first.", + "It is inserted AT THE PLAYHEAD, which this tool does not control: call studio_seek first", + "to choose when it starts. The result reports where the playhead actually was.", + DISPATCH_CAVEAT, +].join(" "); + +export const STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA = { + type: "object", + properties: { + animationId: { type: "string", description: "An animation id from studio_inspect." }, + duration: { type: "number", minimum: 0, description: "Duration in seconds." }, + ease: { type: "string", description: "A GSAP ease, for example power2.out." }, + position: { type: "number", description: "Start position in seconds." }, + }, + required: ["animationId"], + additionalProperties: false, +} as const; + +export const STUDIO_UPDATE_ANIMATION_DESCRIPTION = [ + "Change an existing animation's duration, ease or position.", + "This is the one animation tool that CONFIRMS its write, so a failure here is real", + "and usually means a stale animationId. Get current ids from studio_inspect.", +].join(" "); + +export const STUDIO_ADD_KEYFRAME_INPUT_SCHEMA = { + type: "object", + properties: { + animationId: { type: "string", description: "An animation id from studio_inspect." }, + percent: { + type: "number", + minimum: 0, + maximum: 100, + description: "Where in the tween, 0 to 100.", + }, + properties: { + type: "object", + description: 'GSAP property to value, for example {"y": -50, "opacity": 0}.', + }, + }, + required: ["animationId", "percent", "properties"], + additionalProperties: false, +} as const; + +export const STUDIO_ADD_KEYFRAME_DESCRIPTION = [ + "Add a keyframe to an existing animation at a percentage through it.", + "All the properties land in one commit, so they are one undo entry.", + DISPATCH_CAVEAT, +].join(" "); + +export const STUDIO_DELETE_ANIMATION_INPUT_SCHEMA = { + type: "object", + properties: { + animationId: { type: "string", description: "An animation id from studio_inspect." }, + }, + required: ["animationId"], + additionalProperties: false, +} as const; + +export const STUDIO_DELETE_ANIMATION_DESCRIPTION = [ + "Remove an animation from the currently selected element. Undo reverses it.", + DISPATCH_CAVEAT, +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index 274b697c91..b797cc0f87 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -50,6 +50,10 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe moveTo: async () => undefined, resizeTo: async () => undefined, rotateTo: async () => undefined, + addAnimation: () => undefined, + updateAnimation: async () => true, + addKeyframe: async () => undefined, + deleteAnimation: () => undefined, getGsapDiagnostics: () => ({ animations: [], multipleTimelines: false, @@ -124,6 +128,10 @@ describe("useStudioAgentTools", () => { "studio_set_text", "studio_set_style", "studio_transform", + "studio_add_animation", + "studio_update_animation", + "studio_add_keyframe", + "studio_delete_animation", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -138,14 +146,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(8); + expect(registerTool).toHaveBeenCalledTimes(12); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(8); + expect(registerTool).toHaveBeenCalledTimes(12); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -218,7 +226,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(8); + expect(registerTool).toHaveBeenCalledTimes(12); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index f62c369bcd..3402dc66c7 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -60,6 +60,25 @@ import { type StudioTransformResult, type TransformToolDeps, } from "./tools/transformTools"; +import { + studioAddAnimation, + studioAddKeyframe, + studioDeleteAnimation, + studioUpdateAnimation, + STUDIO_ADD_ANIMATION_DESCRIPTION, + STUDIO_ADD_ANIMATION_INPUT_SCHEMA, + STUDIO_ADD_KEYFRAME_DESCRIPTION, + STUDIO_ADD_KEYFRAME_INPUT_SCHEMA, + STUDIO_DELETE_ANIMATION_DESCRIPTION, + STUDIO_DELETE_ANIMATION_INPUT_SCHEMA, + STUDIO_UPDATE_ANIMATION_DESCRIPTION, + STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA, + type AnimationToolDeps, + type StudioAddAnimationResult, + type StudioAddKeyframeResult, + type StudioDeleteAnimationResult, + type StudioUpdateAnimationResult, +} from "./tools/animationTools"; const log = makeStudioDebugLogger("webmcp"); @@ -74,7 +93,13 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } export interface StudioAgentToolsDeps - extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps, TransformToolDeps { + extends + SelectionToolDeps, + FrameToolDeps, + InspectToolDeps, + ContentToolDeps, + TransformToolDeps, + AnimationToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -175,6 +200,42 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): studioTransform(depsRef.current, input as StudioTransformInput), ), }, + { + name: "studio_add_animation", + title: "Add an animation", + description: STUDIO_ADD_ANIMATION_DESCRIPTION, + inputSchema: STUDIO_ADD_ANIMATION_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_add_animation", () => studioAddAnimation(depsRef.current, input)), + }, + { + name: "studio_update_animation", + title: "Change an animation", + description: STUDIO_UPDATE_ANIMATION_DESCRIPTION, + inputSchema: STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_update_animation", () => studioUpdateAnimation(depsRef.current, input)), + }, + { + name: "studio_add_keyframe", + title: "Add a keyframe", + description: STUDIO_ADD_KEYFRAME_DESCRIPTION, + inputSchema: STUDIO_ADD_KEYFRAME_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_add_keyframe", () => studioAddKeyframe(depsRef.current, input)), + }, + { + name: "studio_delete_animation", + title: "Remove an animation", + description: STUDIO_DELETE_ANIMATION_DESCRIPTION, + inputSchema: STUDIO_DELETE_ANIMATION_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_delete_animation", () => studioDeleteAnimation(depsRef.current, input)), + }, ]; } From 7e03e0b6f79c33d50b1b4882f9fd368c6cfb22ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 30 Aug 2026 01:12:01 -0400 Subject: [PATCH 07/10] feat(studio): add studio_inspect, so an agent reads before it writes (#3517) Everything about one element in one call: resolved styles, text fields, box, data attributes, GSAP animations, and what the element will and will not accept. The point is to prevent a failed write rather than to satisfy curiosity. `can.reasonIfDisabled` is passed through verbatim from Studio's own capabilities, so an agent that reads first should never attempt an edit the element would refuse. Three things it refuses to get wrong: Animations are reported ONLY for the current selection, because that is the only element Studio parses them for. Attributing them to any other element would be reporting the wrong element's motion, which is worse than reporting none. When a handle names something else the field is empty and `animationEditingBlocked` says why. `animationEditingBlocked` also carries the two states where animation editing is off entirely, multiple timelines and an unsupported timeline pattern. Both live on the selection context. Learning them from a read costs one call; learning them from a failed write costs a retry loop. Inspecting a handle does NOT change what is selected. It is a read, and stealing the human's selection would be a side effect they did not ask for. There is a test asserting `applySelection` is never called. Nothing selected and no handle given is a failure, not an empty result. An empty result would assert "this element has nothing", which is a different and false claim. --- .../studio/src/webmcp/StudioAgentTools.tsx | 17 +- .../src/webmcp/tools/frameTools.test.ts | 12 +- .../src/webmcp/tools/inspectTools.test.ts | 197 +++++++++++++++++ .../studio/src/webmcp/tools/inspectTools.ts | 208 ++++++++++++++++++ .../src/webmcp/tools/selectionTools.test.ts | 52 +---- .../src/webmcp/useStudioAgentTools.test.tsx | 13 +- .../studio/src/webmcp/useStudioAgentTools.ts | 21 +- packages/studio/src/webmcp/webmcpTestUtils.ts | 91 ++++++++ 8 files changed, 544 insertions(+), 67 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/inspectTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/inspectTools.ts create mode 100644 packages/studio/src/webmcp/webmcpTestUtils.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index e26612c175..4fbf55e689 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -18,7 +18,12 @@ import type { StudioLookSnapshot } from "./tools/lookTools"; */ export function StudioAgentTools() { const { projectId, activeCompPath, editHistory } = useStudioShellContext(); - const { domEditSelection, selectedGsapAnimations } = useDomEditSelectionContext(); + const { + domEditSelection, + selectedGsapAnimations, + gsapMultipleTimelines, + gsapUnsupportedTimelinePattern, + } = useDomEditSelectionContext(); const { previewIframeRef, buildDomSelectionFromTarget, applyDomSelection } = useDomEditActionsContext(); @@ -71,6 +76,12 @@ export function StudioAgentTools() { } }, wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)), + getCurrentSelection: () => domEditSelection, + getGsapDiagnostics: () => ({ + animations: selectedGsapAnimations, + multipleTimelines: gsapMultipleTimelines, + unsupportedTimelinePattern: gsapUnsupportedTimelinePattern, + }), }), [ getSnapshot, @@ -79,6 +90,10 @@ export function StudioAgentTools() { applyDomSelection, projectId, activeCompPath, + domEditSelection, + selectedGsapAnimations, + gsapMultipleTimelines, + gsapUnsupportedTimelinePattern, ], ); diff --git a/packages/studio/src/webmcp/tools/frameTools.test.ts b/packages/studio/src/webmcp/tools/frameTools.test.ts index e98d5c2e46..8ac0b5a432 100644 --- a/packages/studio/src/webmcp/tools/frameTools.test.ts +++ b/packages/studio/src/webmcp/tools/frameTools.test.ts @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; import { studioFrame, type FrameToolDeps, type StudioFrameResult } from "./frameTools"; -import type { ToolFailure, ToolResult } from "../toolResult"; +import { expectFailure, expectOk } from "../webmcpTestUtils"; function frameDeps(overrides: Partial = {}): FrameToolDeps { return { @@ -15,16 +15,6 @@ function frameDeps(overrides: Partial = {}): FrameToolDeps { }; } -function expectOk(result: ToolResult): { ok: true } & T { - if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); - return result; -} - -function expectFailure(result: ToolResult): ToolFailure { - if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); - return result; -} - describe("studioFrame", () => { it("returns a URL for the composition at the playhead", async () => { const result = await studioFrame(frameDeps()); diff --git a/packages/studio/src/webmcp/tools/inspectTools.test.ts b/packages/studio/src/webmcp/tools/inspectTools.test.ts new file mode 100644 index 0000000000..d59034a45f --- /dev/null +++ b/packages/studio/src/webmcp/tools/inspectTools.test.ts @@ -0,0 +1,197 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser"; +import { studioInspect, type InspectToolDeps, type StudioInspectResult } from "./inspectTools"; +import { + expectFailure, + expectOk, + previewDoc, + previewElement, + selectionFor, +} from "../webmcpTestUtils"; + +function animation(overrides: Partial = {}): GsapAnimation { + return { + id: "anim-1", + targetSelector: "#headline", + method: "from", + position: 0, + properties: { y: -50, opacity: 0 }, + duration: 1, + ease: "power2.out", + ...overrides, + } as GsapAnimation; +} + +function inspectDeps(overrides: Partial = {}): InspectToolDeps { + return { + getPreviewDocument: () => null, + buildSelection: async (element) => selectionFor(element), + applySelection: () => undefined, + requestSeek: () => undefined, + readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }), + getCurrentSelection: () => null, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + ...overrides, + }; +} + +describe("studioInspect", () => { + it("returns the resolved styles, not the authored ones", async () => { + const element = previewElement('

Ship it

', "headline"); + const selection = selectionFor(element); + + const result = await studioInspect(inspectDeps({ getCurrentSelection: () => selection })); + + const ok = expectOk(result); + // The authored value is a clamp(); the resolved one is what actually renders. + expect(ok.styles["font-size"]).toBe("42.7px"); + expect(ok.inlineStyles.color).toBe("red"); + expect(ok.box.width).toBe(880); + }); + + it("reports capabilities and the disabled reason verbatim", async () => { + const element = previewElement('

Ship it

', "headline"); + const locked = selectionFor(element, { + capabilities: { + canSelect: true, + canEditStyles: false, + canCrop: false, + canMove: false, + canResize: false, + canApplyManualOffset: false, + canApplyManualSize: false, + canApplyManualRotation: false, + reasonIfDisabled: "Element is inside a locked composition", + }, + }); + + const result = await studioInspect(inspectDeps({ getCurrentSelection: () => locked })); + + const ok = expectOk(result); + expect(ok.can.editStyles).toBe(false); + expect(ok.can.move).toBe(false); + expect(ok.can.reasonIfDisabled).toBe("Element is inside a locked composition"); + }); + + it("lists the animations on the current selection", async () => { + const element = previewElement('

Ship it

', "headline"); + + const result = await studioInspect( + inspectDeps({ + getCurrentSelection: () => selectionFor(element), + getGsapDiagnostics: () => ({ + animations: [animation()], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + }), + ); + + const ok = expectOk(result); + expect(ok.animations).toHaveLength(1); + expect(ok.animations[0]?.animationId).toBe("anim-1"); + expect(ok.animations[0]?.ease).toBe("power2.out"); + expect(ok.animationEditingBlocked).toBeNull(); + }); + + it("says WHY animation editing is unavailable, so a write is not attempted", async () => { + const element = previewElement('

Ship it

', "headline"); + const base = { + getCurrentSelection: () => selectionFor(element), + }; + + const multiple = await studioInspect( + inspectDeps({ + ...base, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: true, + unsupportedTimelinePattern: false, + }), + }), + ); + const unsupported = await studioInspect( + inspectDeps({ + ...base, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: true, + }), + }), + ); + + expect(expectOk(multiple).animationEditingBlocked).toMatch( + /multiple GSAP timelines/, + ); + expect(expectOk(unsupported).animationEditingBlocked).toMatch( + /not editable/, + ); + }); + + it("does not attribute the selection's animations to a different element", async () => { + // Studio only parses animations for the CURRENT selection. Reporting them + // against another element would report the wrong element's motion. + const headline = previewElement('

A

B

', "headline"); + const doc = headline.ownerDocument; + + const result = await studioInspect( + inspectDeps({ + getPreviewDocument: () => doc, + getCurrentSelection: () => selectionFor(headline), + getGsapDiagnostics: () => ({ + animations: [animation()], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), + }), + { handle: "dom:body" }, + ); + + const ok = expectOk(result); + expect(ok.isCurrentSelection).toBe(false); + expect(ok.animations).toEqual([]); + expect(ok.animationEditingBlocked).toMatch(/only readable for the current selection/); + }); + + it("inspects a handle without changing what is selected", async () => { + const doc = previewDoc('

A

'); + const applySelection = vi.fn(); + + const result = await studioInspect( + inspectDeps({ getPreviewDocument: () => doc, applySelection }), + { handle: "dom:headline" }, + ); + + expect(result.ok).toBe(true); + // Inspecting is a read. It must not steal the human's selection. + expect(applySelection).not.toHaveBeenCalled(); + }); + + it("fails rather than returning an empty result when nothing is selected", async () => { + const result = expectFailure(await studioInspect(inspectDeps())); + + // An empty result would assert "this element has nothing", a different and + // false claim from "you did not say which element". + expect(result.kind).toBe("invalid"); + expect(result.reason).toMatch(/nothing is selected/); + expect(result.hint).toMatch(/studio_select/); + }); + + it("reports an unknown handle distinctly from an unmounted preview", async () => { + const notMounted = expectFailure(await studioInspect(inspectDeps(), { handle: "dom:x" })); + expect(notMounted.kind).toBe("blocked"); + + const doc = previewDoc('

A

'); + const unknown = expectFailure( + await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), { handle: "dom:x" }), + ); + expect(unknown.kind).toBe("invalid"); + expect(unknown.reason).not.toBe(notMounted.reason); + }); +}); diff --git a/packages/studio/src/webmcp/tools/inspectTools.ts b/packages/studio/src/webmcp/tools/inspectTools.ts new file mode 100644 index 0000000000..f31b9fc834 --- /dev/null +++ b/packages/studio/src/webmcp/tools/inspectTools.ts @@ -0,0 +1,208 @@ +/** + * `studio_inspect`: everything about one element, in one call. + * + * The point is to prevent a failed write. Every field here either tells the + * agent what it can change (`can`, with `reasonIfDisabled` verbatim) or what it + * would be changing (the resolved styles, the text fields, the animations). + * An agent that reads this first should never attempt an edit the element will + * refuse. + * + * The GSAP diagnostics are here for the same reason: `multipleTimelines` and + * `unsupportedTimelinePattern` are states where animation editing is off, and + * learning that from a read is cheaper than learning it from a failed write. + */ + +import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser"; +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { mintElementHandle, patchTargetAddress, resolveElementHandle } from "../handles"; +import { toolFailure, toolOk, type ToolResult } from "../toolResult"; +import type { SelectionToolDeps } from "./selectionTools"; + +export interface InspectToolDeps extends SelectionToolDeps { + /** What the human currently has selected, used when no handle is given. */ + getCurrentSelection: () => DomEditSelection | null; + getGsapDiagnostics: () => { + animations: readonly GsapAnimation[]; + multipleTimelines: boolean; + unsupportedTimelinePattern: boolean; + }; +} + +interface InspectAnimation { + animationId: string; + method: string; + target: string; + position: number | string; + duration: number | null; + ease: string | null; + properties: Record; + hasKeyframes: boolean; + hasArcPath: boolean; +} + +interface InspectTextField { + key: string; + label: string; + value: string; + tagName: string; +} + +export interface StudioInspectResult { + handle: string | null; + label: string; + tagName: string; + sourceFile: string; + box: { x: number; y: number; width: number; height: number }; + text: string | null; + textFields: InspectTextField[]; + /** The styles Studio itself surfaces, resolved, not as authored. */ + styles: Record; + inlineStyles: Record; + dataAttributes: Record; + can: { + editStyles: boolean; + move: boolean; + resize: boolean; + rotate: boolean; + crop: boolean; + editText: boolean; + reasonIfDisabled: string | null; + }; + animations: InspectAnimation[]; + /** Present only when animation editing is unavailable, with the reason. */ + animationEditingBlocked: string | null; + /** True when this element is the one the human currently has selected. */ + isCurrentSelection: boolean; +} + +export interface StudioInspectInput { + /** Omit to inspect the current selection. */ + handle?: string; +} + +function describeAnimation(animation: GsapAnimation): InspectAnimation { + return { + animationId: animation.id, + method: animation.method, + target: animation.targetSelector, + position: animation.position, + duration: animation.duration ?? null, + ease: animation.ease ?? null, + properties: animation.properties, + hasKeyframes: animation.keyframes !== undefined, + hasArcPath: animation.arcPath !== undefined, + }; +} + +function describe( + selection: DomEditSelection, + deps: InspectToolDeps, + isCurrentSelection: boolean, +): ToolResult { + const { capabilities } = selection; + const gsap = deps.getGsapDiagnostics(); + + // Only the CURRENT selection's animations are parsed by Studio. Reporting + // them for some other element would be reporting the wrong element's motion, + // which is worse than reporting none. + const animations = isCurrentSelection ? gsap.animations.map(describeAnimation) : []; + + let animationEditingBlocked: string | null = null; + if (!isCurrentSelection) { + animationEditingBlocked = "animations are only readable for the current selection"; + } else if (gsap.multipleTimelines) { + animationEditingBlocked = "this composition has multiple GSAP timelines"; + } else if (gsap.unsupportedTimelinePattern) { + animationEditingBlocked = "this composition's timeline pattern is not editable by Studio"; + } + + return toolOk({ + handle: mintElementHandle(patchTargetAddress(selection)), + label: selection.label, + tagName: selection.tagName, + sourceFile: selection.sourceFile, + box: selection.boundingBox, + text: selection.textContent, + textFields: selection.textFields.map((field) => ({ + key: field.key, + label: field.label, + value: field.value, + tagName: field.tagName, + })), + styles: selection.computedStyles, + inlineStyles: selection.inlineStyles, + dataAttributes: selection.dataAttributes, + can: { + editStyles: capabilities.canEditStyles, + move: capabilities.canMove || capabilities.canApplyManualOffset, + resize: capabilities.canResize || capabilities.canApplyManualSize, + rotate: capabilities.canApplyManualRotation, + crop: capabilities.canCrop, + editText: selection.textFields.length > 0, + reasonIfDisabled: capabilities.reasonIfDisabled ?? null, + }, + animations, + animationEditingBlocked, + isCurrentSelection, + }); +} + +export async function studioInspect( + deps: InspectToolDeps, + input: StudioInspectInput = {}, +): Promise> { + const current = deps.getCurrentSelection(); + + if (!input.handle) { + // An empty result here would assert "this element has nothing", which is a + // different and false claim from "you did not tell me which element". + if (!current) { + return toolFailure( + "invalid", + "nothing is selected and no handle was given", + "Pass a handle from studio_look, or call studio_select first.", + ); + } + return describe(current, deps, true); + } + + const doc = deps.getPreviewDocument(); + if (!doc) return toolFailure("blocked", "the preview is not mounted yet"); + + const element = resolveElementHandle(doc, input.handle); + if (!element) { + return toolFailure( + "invalid", + `no element matches handle ${input.handle}`, + "Call studio_look for current handles.", + ); + } + + const selection = await deps.buildSelection(element); + if (!selection) { + return toolFailure("blocked", `${input.handle} resolved to an element Studio cannot inspect`); + } + + return describe(selection, deps, current?.element === element); +} + +export const STUDIO_INSPECT_INPUT_SCHEMA = { + type: "object", + properties: { + handle: { + type: "string", + description: "An element handle from studio_look. Omit to inspect the current selection.", + }, + }, + additionalProperties: false, +} as const; + +export const STUDIO_INSPECT_DESCRIPTION = [ + "Everything about one element: its resolved styles, its text fields, its box,", + "its GSAP animations, and crucially what it will and will not accept.", + "Read this BEFORE editing. `can` tells you which edits are possible and", + "`can.reasonIfDisabled` says why one is not, so you can avoid a write that would be refused.", + "Animations are only readable for the CURRENT selection; `animationEditingBlocked` says when", + "and why animation editing is unavailable.", + "Returns `ok: true`, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); diff --git a/packages/studio/src/webmcp/tools/selectionTools.test.ts b/packages/studio/src/webmcp/tools/selectionTools.test.ts index c6ec5fdd2a..07168529ae 100644 --- a/packages/studio/src/webmcp/tools/selectionTools.test.ts +++ b/packages/studio/src/webmcp/tools/selectionTools.test.ts @@ -1,6 +1,5 @@ // @vitest-environment jsdom import { describe, expect, it, vi } from "vitest"; -import type { DomEditSelection } from "../../components/editor/domEditingTypes"; import { studioSeek, studioSelect, @@ -8,46 +7,7 @@ import { type StudioSeekResult, type StudioSelectResult, } from "./selectionTools"; -import type { ToolFailure, ToolResult } from "../toolResult"; - -function previewDoc(html: string): Document { - const iframe = document.createElement("iframe"); - document.body.append(iframe); - const doc = iframe.contentDocument; - if (!doc) throw new Error("expected iframe document"); - doc.body.innerHTML = html; - return doc; -} - -function selectionFor(element: HTMLElement): DomEditSelection { - return { - id: element.id || undefined, - hfId: element.getAttribute("data-hf-id") ?? undefined, - element, - label: "Headline", - tagName: element.tagName.toLowerCase(), - sourceFile: "index.html", - compositionPath: "index.html", - isCompositionHost: false, - isInsideLockedComposition: false, - boundingBox: { x: 40, y: 12, width: 880, height: 96 }, - textContent: element.textContent, - dataAttributes: {}, - inlineStyles: {}, - computedStyles: {}, - textFields: [], - capabilities: { - canSelect: true, - canEditStyles: true, - canCrop: true, - canMove: true, - canResize: true, - canApplyManualOffset: true, - canApplyManualSize: true, - canApplyManualRotation: true, - }, - }; -} +import { expectFailure, expectOk, previewDoc, selectionFor } from "../webmcpTestUtils"; function selectionDeps(overrides: Partial = {}): SelectionToolDeps { return { @@ -60,16 +20,6 @@ function selectionDeps(overrides: Partial = {}): SelectionToo }; } -function expectFailure(result: ToolResult): ToolFailure { - if (result.ok) throw new Error(`expected failure, got ${JSON.stringify(result)}`); - return result; -} - -function expectOk(result: ToolResult): { ok: true } & T { - if (!result.ok) throw new Error(`expected ok, got ${JSON.stringify(result)}`); - return result; -} - describe("studioSelect", () => { it("applies the selection a click would produce and reports it back", async () => { const doc = previewDoc('

Ship it

'); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index d9c7dd4081..3a9a3ee988 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -42,6 +42,12 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe getCompositionPath: () => "index.html", probeFrame: async () => ({ ok: true, status: 200 }), wait: async () => undefined, + getCurrentSelection: () => null, + getGsapDiagnostics: () => ({ + animations: [], + multipleTimelines: false, + unsupportedTimelinePattern: false, + }), ...overrides, }; } @@ -107,6 +113,7 @@ describe("useStudioAgentTools", () => { "studio_select", "studio_seek", "studio_frame", + "studio_inspect", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -121,14 +128,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -201,7 +208,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(4); + expect(registerTool).toHaveBeenCalledTimes(5); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index 9af5b8cc61..c5e1a444eb 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -33,6 +33,14 @@ import { type StudioFrameInput, type StudioFrameResult, } from "./tools/frameTools"; +import { + studioInspect, + STUDIO_INSPECT_DESCRIPTION, + STUDIO_INSPECT_INPUT_SCHEMA, + type InspectToolDeps, + type StudioInspectInput, + type StudioInspectResult, +} from "./tools/inspectTools"; const log = makeStudioDebugLogger("webmcp"); @@ -46,7 +54,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } } -export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps { +export interface StudioAgentToolsDeps extends SelectionToolDeps, FrameToolDeps, InspectToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -107,6 +115,17 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): execute: (input): Promise> => runToolBody("studio_frame", () => studioFrame(depsRef.current, input as StudioFrameInput)), }, + { + name: "studio_inspect", + title: "Inspect one element", + description: STUDIO_INSPECT_DESCRIPTION, + inputSchema: STUDIO_INSPECT_INPUT_SCHEMA, + annotations: { readOnlyHint: true, untrustedContentHint: true }, + execute: (input): Promise> => + runToolBody("studio_inspect", () => + studioInspect(depsRef.current, input as StudioInspectInput), + ), + }, ]; } diff --git a/packages/studio/src/webmcp/webmcpTestUtils.ts b/packages/studio/src/webmcp/webmcpTestUtils.ts new file mode 100644 index 0000000000..8f4f5e96b0 --- /dev/null +++ b/packages/studio/src/webmcp/webmcpTestUtils.ts @@ -0,0 +1,91 @@ +/** + * Shared fixtures for the WebMCP tool tests. + * + * Not a `.test` file so vitest does not collect it as a suite. Mirrors the + * existing `hooks/domSelectionTestHarness.ts` convention. + */ + +import { expect } from "vitest"; +import type { DomEditSelection } from "../components/editor/domEditingTypes"; +import type { ToolFailure, ToolResult } from "./toolResult"; + +/** + * An element inside a real iframe, which is where Studio's chrome expects to + * find preview elements. The separate realm matters: a preview element is not + * an instance of Studio's own `HTMLElement`. + */ +export function previewDoc(html: string): Document { + const iframe = document.createElement("iframe"); + document.body.append(iframe); + const doc = iframe.contentDocument; + if (!doc) throw new Error("expected iframe document"); + doc.body.innerHTML = html; + return doc; +} + +export function previewElement(html: string, id: string): HTMLElement { + const doc = previewDoc(html); + const element = doc.getElementById(id); + const HTMLElementCtor = doc.defaultView?.HTMLElement; + if (!HTMLElementCtor || !(element instanceof HTMLElementCtor)) { + throw new Error(`expected preview element #${id}`); + } + return element; +} + +export function selectionFor( + element: HTMLElement, + overrides: Partial = {}, +): DomEditSelection { + return { + id: element.id || undefined, + hfId: element.getAttribute("data-hf-id") ?? undefined, + element, + label: "Headline", + tagName: element.tagName.toLowerCase(), + sourceFile: "index.html", + compositionPath: "index.html", + isCompositionHost: false, + isInsideLockedComposition: false, + boundingBox: { x: 40, y: 12, width: 880, height: 96 }, + textContent: element.textContent, + dataAttributes: { "data-role": "title" }, + inlineStyles: { color: "red" }, + computedStyles: { "font-size": "42.7px", color: "rgb(255, 0, 0)" }, + textFields: [ + { + key: "self", + label: "Text", + value: element.textContent ?? "", + tagName: element.tagName.toLowerCase(), + attributes: [], + inlineStyles: {}, + computedStyles: {}, + source: "self", + }, + ], + capabilities: { + canSelect: true, + canEditStyles: true, + canCrop: true, + canMove: true, + canResize: true, + canApplyManualOffset: true, + canApplyManualSize: true, + canApplyManualRotation: true, + }, + ...overrides, + }; +} + +export function expectOk(result: ToolResult): { ok: true } & T { + expect(result.ok, `expected ok, got ${JSON.stringify(result)}`).toBe(true); + if (!result.ok) throw new Error("unreachable"); + return result; +} + +export function expectFailure(result: ToolResult): ToolFailure { + expect(result.ok, `expected failure, got ${JSON.stringify(result)}`).toBe(false); + if (result.ok) throw new Error("unreachable"); + return result; +} From be6fc0b0a89ca07af957b7f6b07a024f4f9c7890 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 30 Aug 2026 01:25:48 -0400 Subject: [PATCH 08/10] feat(studio): move, resize and rotate, verified by reading back (#3519) `studio_transform` does what a drag does, and then checks. The box in the result is READ BACK after the write, never echoed from the request, and `applied` lists what actually took effect. That is not belt-and-braces. The plan for this unit said to re-derive the geometry handlers' behaviour rather than trust any description of them, and doing that turned up three different behaviours behind one interface. The handlers on `DomEditActionsValue` are the GSAP-AWARE wrappers, aliased in `useDomEditSession.ts:534-538`, not the CSS ones in `useDomGeometryCommits.ts` that an earlier note in this workstream described. `handleGsapAwarePathOffsetCommit` and `handleGsapAwareRotationCommit` are `if (gsapCommitMutation) { ...intercept... }` with no else branch. Their own comments say the absence is deliberate: position and rotation are written as GSAP code and there is no CSS fallback to write to. So they can return having done nothing. `handleGsapAwareBoxSizeCommit` is not like the other two. It runs through `runGestureTransaction` with separate scale and width/height routes, so resize works more generally. Reading back is what turns that middle case from a silent lie into a reported one. A move that did nothing comes back in `unchanged` with a reason. Three smaller decisions: Operations re-read between each other, so a move is judged against the box AFTER a resize in the same call. Comparing against the original would credit the resize's change to the move. Rotation is reported as dispatched, not verified. `rotate` is an individual transform property and does not appear in the computed transform, so there is no honest box-derived signal, and claiming one would be worse than saying so. x pairs with y and width pairs with height. Accepting one alone would mean inventing the other from the current value, which moves the element somewhere the caller did not ask for. The pairing rule and its minimum live in one `parsePair` helper rather than as four separate branches. --- .../studio/src/webmcp/StudioAgentTools.tsx | 15 ++ .../src/webmcp/tools/transformTools.test.ts | 179 +++++++++++++++ .../studio/src/webmcp/tools/transformTools.ts | 205 ++++++++++++++++++ .../src/webmcp/useStudioAgentTools.test.tsx | 11 +- .../studio/src/webmcp/useStudioAgentTools.ts | 21 +- 5 files changed, 427 insertions(+), 4 deletions(-) create mode 100644 packages/studio/src/webmcp/tools/transformTools.test.ts create mode 100644 packages/studio/src/webmcp/tools/transformTools.ts diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsx index c52ee655b1..f201ca23bf 100644 --- a/packages/studio/src/webmcp/StudioAgentTools.tsx +++ b/packages/studio/src/webmcp/StudioAgentTools.tsx @@ -30,6 +30,9 @@ export function StudioAgentTools() { applyDomSelection, handleDomTextCommit, handleDomStyleCommit, + handleDomPathOffsetCommit, + handleDomBoxSizeCommit, + handleDomRotationCommit, } = useDomEditActionsContext(); const getSnapshot = useCallback((): StudioLookSnapshot => { @@ -85,6 +88,15 @@ export function StudioAgentTools() { getWriteBlockedReason: () => writeBlockedReason, setText: (value, fieldKey) => handleDomTextCommit(value, fieldKey), setStyle: (property, value) => handleDomStyleCommit(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. + readBox: (selection) => { + const rect = selection.element.getBoundingClientRect(); + return { x: rect.x, y: rect.y, width: rect.width, height: rect.height }; + }, + moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next), + resizeTo: (selection, next) => handleDomBoxSizeCommit(selection, next), + rotateTo: (selection, next) => handleDomRotationCommit(selection, next), getGsapDiagnostics: () => ({ animations: selectedGsapAnimations, multipleTimelines: gsapMultipleTimelines, @@ -101,6 +113,9 @@ export function StudioAgentTools() { writeBlockedReason, handleDomTextCommit, handleDomStyleCommit, + handleDomPathOffsetCommit, + handleDomBoxSizeCommit, + handleDomRotationCommit, domEditSelection, selectedGsapAnimations, gsapMultipleTimelines, diff --git a/packages/studio/src/webmcp/tools/transformTools.test.ts b/packages/studio/src/webmcp/tools/transformTools.test.ts new file mode 100644 index 0000000000..b438ed9e5d --- /dev/null +++ b/packages/studio/src/webmcp/tools/transformTools.test.ts @@ -0,0 +1,179 @@ +// @vitest-environment jsdom +import { describe, expect, it, vi } from "vitest"; +import { + studioTransform, + type ElementBox, + type StudioTransformResult, + type TransformToolDeps, +} from "./transformTools"; +import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils"; + +/** + * A stand-in for the rendered box. happy-dom and jsdom report all-zero rects, + * so the box is injected rather than measured; these tests are about what the + * tool concludes from a box, not about layout. + */ +function boxStore(initial: ElementBox) { + const box = { ...initial }; + return { + read: () => ({ ...box }), + set: (next: Partial) => Object.assign(box, next), + }; +} + +function transformDeps(overrides: Partial = {}): TransformToolDeps { + const element = previewElement('

Ship it

', "headline"); + return { + getCurrentSelection: () => selectionFor(element), + getWriteBlockedReason: () => null, + readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }), + moveTo: async () => undefined, + resizeTo: async () => undefined, + rotateTo: async () => undefined, + ...overrides, + }; +} + +describe("studioTransform", () => { + it("reports the box read back, not the box requested", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + // The handler lands somewhere other than asked, which is what a clamp or a + // layout constraint does. + const resizeTo = vi.fn(async () => store.set({ width: 300, height: 120 })); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo }), { + width: 999, + height: 999, + }); + + const ok = expectOk(result); + expect(ok.box.width).toBe(300); + expect(ok.box.height).toBe(120); + expect(ok.applied).toContain("resize"); + }); + + it("reports a silent no-op as unchanged instead of success", async () => { + // handleGsapAwarePathOffsetCommit is `if (gsapCommitMutation) {...}` with no + // else branch. Without GSAP it resolves having written nothing, and echoing + // the request back would be a lie the agent builds on. + const store = boxStore({ x: 10, y: 10, width: 100, height: 50 }); + const moveTo = vi.fn(async () => undefined); + + const result = expectFailure( + await studioTransform(transformDeps({ readBox: store.read, moveTo }), { x: 500, y: 400 }), + ); + + expect(moveTo).toHaveBeenCalled(); + expect(result.kind).toBe("blocked"); + expect(result.reason).toMatch(/did not move/); + expect(result.hint).toMatch(/GSAP/); + }); + + it("separates what landed from what did not, in one call", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + const resizeTo = vi.fn(async () => store.set({ width: 200, height: 80 })); + const moveTo = vi.fn(async () => undefined); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), { + x: 40, + y: 40, + width: 200, + height: 80, + }); + + const ok = expectOk(result); + expect(ok.applied).toEqual(["resize"]); + expect(ok.unchanged.move).toMatch(/did not move/); + }); + + it("re-reads between operations so a later one sees the earlier result", async () => { + const store = boxStore({ x: 0, y: 0, width: 100, height: 50 }); + const resizeTo = vi.fn(async () => store.set({ width: 200, height: 80 })); + const moveTo = vi.fn(async () => store.set({ x: 40, y: 40 })); + + const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), { + x: 40, + y: 40, + width: 200, + height: 80, + }); + + // Move is judged against the box AFTER the resize. Comparing against the + // original would credit the resize's change to the move. + const ok = expectOk(result); + expect(ok.applied).toEqual(["resize", "move"]); + expect(ok.unchanged).toEqual({}); + }); + + it("reports rotation as dispatched rather than verified", async () => { + // `rotate` is an individual transform property and does not appear in the + // computed transform, so there is no honest box-derived signal for it. + const rotateTo = vi.fn(async () => undefined); + + const result = await studioTransform(transformDeps({ rotateTo }), { rotate: 15 }); + + const ok = expectOk(result); + expect(rotateTo).toHaveBeenCalledWith(expect.anything(), { angle: 15 }); + expect(ok.applied).toEqual(["rotate"]); + }); + + it("refuses to write while a conflict is waiting for the user", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform( + transformDeps({ getWriteBlockedReason: () => "Auto-save is paused", moveTo }), + { x: 10, y: 10 }, + ), + ); + + expect(result.kind).toBe("blocked"); + expect(moveTo).not.toHaveBeenCalled(); + }); + + it("requires x and y together, and width and height together", async () => { + const moveTo = vi.fn(); + const resizeTo = vi.fn(); + const deps = transformDeps({ moveTo, resizeTo }); + + expect(expectFailure(await studioTransform(deps, { x: 10 })).reason).toMatch(/together/); + expect(expectFailure(await studioTransform(deps, { width: 10 })).reason).toMatch(/together/); + expect(moveTo).not.toHaveBeenCalled(); + expect(resizeTo).not.toHaveBeenCalled(); + }); + + it("rejects a negative size and an empty request", async () => { + const deps = transformDeps(); + + expect(expectFailure(await studioTransform(deps, { width: -1, height: 10 })).kind).toBe( + "invalid", + ); + expect(expectFailure(await studioTransform(deps, {})).reason).toMatch(/at least one/); + }); + + it("rejects non-finite numbers rather than passing them to a handler", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform(transformDeps({ moveTo }), { x: Number.NaN, y: 10 }), + ); + + expect(result.kind).toBe("invalid"); + expect(moveTo).not.toHaveBeenCalled(); + }); + + it("fails when nothing is selected", async () => { + const moveTo = vi.fn(); + + const result = expectFailure( + await studioTransform(transformDeps({ getCurrentSelection: () => null, moveTo }), { + x: 1, + y: 1, + }), + ); + + expect(result.kind).toBe("invalid"); + expect(result.hint).toMatch(/studio_select/); + expect(moveTo).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/studio/src/webmcp/tools/transformTools.ts b/packages/studio/src/webmcp/tools/transformTools.ts new file mode 100644 index 0000000000..0ea9bf670b --- /dev/null +++ b/packages/studio/src/webmcp/tools/transformTools.ts @@ -0,0 +1,205 @@ +/** + * `studio_transform`: move, resize and rotate, as a drag would. + * + * This tool reads the element's box back after every write and reports what + * ACTUALLY changed. That is not belt-and-braces, it is the only thing standing + * between an agent and a silent lie, because two of the three handlers can do + * nothing and resolve: + * + * - The handlers exposed on `DomEditActionsValue` are the GSAP-AWARE wrappers + * (`useDomEditSession.ts` aliases them), not the CSS ones in + * `useDomGeometryCommits.ts`. + * - `handleGsapAwarePathOffsetCommit` and `handleGsapAwareRotationCommit` are + * `if (gsapCommitMutation) { ...intercept... }` with NO else branch. In a + * composition with no GSAP they return having done nothing. The adjacent + * comments confirm that is deliberate: there is no CSS fallback to write to. + * - `handleGsapAwareBoxSizeCommit` is different. It runs through + * `runGestureTransaction` with a scale route and a width/height route, so + * resize works more generally than the other two. + * + * Read back, do not assume. + */ + +import type { DomEditSelection } from "../../components/editor/domEditingTypes"; +import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult"; + +export interface ElementBox { + x: number; + y: number; + width: number; + height: number; +} + +export interface TransformToolDeps { + getCurrentSelection: () => DomEditSelection | null; + getWriteBlockedReason: () => string | null; + /** The element's box as it renders right now. */ + readBox: (selection: DomEditSelection) => ElementBox; + moveTo: (selection: DomEditSelection, next: { x: number; y: number }) => Promise; + resizeTo: (selection: DomEditSelection, next: { width: number; height: number }) => Promise; + rotateTo: (selection: DomEditSelection, next: { angle: number }) => Promise; +} + +export interface StudioTransformInput { + x?: unknown; + y?: unknown; + width?: unknown; + height?: unknown; + rotate?: unknown; +} + +export interface StudioTransformResult { + /** The box as it renders after the write, read back, not echoed. */ + box: ElementBox; + applied: string[]; + /** Requested operations whose effect could not be observed, with why. */ + unchanged: Record; +} + +const NO_OP_HINT = + "Move and rotate are written as GSAP code; a composition with no GSAP timeline has nothing to write to. studio_inspect reports the element's animations."; + +function readNumber(value: unknown): number | null { + return typeof value === "number" && Number.isFinite(value) ? value : null; +} + +function guard(deps: TransformToolDeps): ToolFailure | null { + const blocked = deps.getWriteBlockedReason(); + if (blocked) return toolFailure("blocked", blocked, "Resolve it in Studio, then retry."); + if (!deps.getCurrentSelection()) { + return toolFailure("invalid", "nothing is selected", "Call studio_select first."); + } + return null; +} + +interface TransformRequest { + move: { x: number; y: number } | null; + size: { width: number; height: number } | null; + rotate: number | null; +} + +/** + * Both or neither. Accepting one axis alone would mean inventing the other from + * the current value, which moves the element somewhere the caller did not ask + * for. + */ +function parsePair( + a: unknown, + b: unknown, + names: [string, string], + min = Number.NEGATIVE_INFINITY, +): { pair: [number, number] | null } | ToolFailure { + const first = readNumber(a); + const second = readNumber(b); + if (first === null && second === null) return { pair: null }; + if (first === null || second === null) { + return toolFailure("invalid", `${names[0]} and ${names[1]} must be given together`); + } + if (first < min || second < min) { + return toolFailure("invalid", `${names[0]} and ${names[1]} must be at least ${min}`); + } + return { pair: [first, second] }; +} + +function isFailure(value: object): value is ToolFailure { + return "ok" in value; +} + +function parseRequest(input: StudioTransformInput): TransformRequest | ToolFailure { + const move = parsePair(input.x, input.y, ["x", "y"]); + if (isFailure(move)) return move; + const size = parsePair(input.width, input.height, ["width", "height"], 0); + if (isFailure(size)) return size; + const rotate = readNumber(input.rotate); + + if (!move.pair && !size.pair && rotate === null) { + return toolFailure( + "invalid", + "give at least one of x, y, width, height, rotate as a finite number", + ); + } + + return { + move: move.pair ? { x: move.pair[0], y: move.pair[1] } : null, + size: size.pair ? { width: size.pair[0], height: size.pair[1] } : null, + rotate, + }; +} + +export async function studioTransform( + deps: TransformToolDeps, + input: StudioTransformInput, +): Promise> { + const request = parseRequest(input); + if (isFailure(request)) return request; + + const blocked = guard(deps); + if (blocked) return blocked; + + const selection = deps.getCurrentSelection(); + if (!selection) return toolFailure("invalid", "nothing is selected"); + + const applied: string[] = []; + const unchanged: Record = {}; + + // Sequential, and each one re-reads first, so a move is judged against the box + // AFTER a resize in the same call rather than against the original. + if (request.size) { + const before = deps.readBox(selection); + await deps.resizeTo(selection, request.size); + const after = deps.readBox(selection); + if (after.width !== before.width || after.height !== before.height) applied.push("resize"); + else unchanged.resize = "the element's size did not change"; + } + + if (request.move) { + const before = deps.readBox(selection); + await deps.moveTo(selection, request.move); + const after = deps.readBox(selection); + if (after.x !== before.x || after.y !== before.y) applied.push("move"); + else unchanged.move = `the element did not move. ${NO_OP_HINT}`; + } + + if (request.rotate !== null) { + // Rotation is written as the CSS `rotate` property, an individual transform + // property that does NOT appear in getComputedStyle().transform. There is no + // reliable box-derived signal, so this is reported as dispatched rather than + // verified, and the description says so. + await deps.rotateTo(selection, { angle: request.rotate }); + applied.push("rotate"); + } + + if (applied.length === 0) { + return toolFailure( + "blocked", + `nothing changed: ${Object.values(unchanged).join("; ")}`, + NO_OP_HINT, + ); + } + + return toolOk({ box: deps.readBox(selection), applied, unchanged }); +} + +export const STUDIO_TRANSFORM_INPUT_SCHEMA = { + type: "object", + properties: { + x: { type: "number", description: "New x offset in pixels. Must be paired with y." }, + y: { type: "number", description: "New y offset in pixels. Must be paired with x." }, + width: { type: "number", minimum: 0, description: "New width. Must be paired with height." }, + height: { type: "number", minimum: 0, description: "New height. Must be paired with width." }, + rotate: { type: "number", description: "Rotation in degrees." }, + }, + additionalProperties: false, +} as const; + +export const STUDIO_TRANSFORM_DESCRIPTION = [ + "Move, resize or rotate the CURRENTLY SELECTED element, the way a drag would.", + "Call studio_select first. Give x with y, and width with height.", + "The result's `box` is READ BACK after the write, not echoed from your request, and", + "`applied` lists what actually took effect. Check it.", + "Move and rotate are written as GSAP code, so in a composition with no GSAP timeline they", + "do nothing; that shows up in `unchanged` rather than as a false success.", + "Rotation is reported as dispatched rather than verified, because the CSS `rotate` property", + "does not appear in the element's computed transform.", + "Returns `ok: true`, or `ok: false` with `kind`, `reason` and a `hint`.", +].join(" "); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index 8431d84265..274b697c91 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -46,6 +46,10 @@ function deps(overrides: Partial = {}): StudioAgentToolsDe getWriteBlockedReason: () => null, setText: async () => ({ ok: true }), setStyle: async () => ({ ok: true }), + readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }), + moveTo: async () => undefined, + resizeTo: async () => undefined, + rotateTo: async () => undefined, getGsapDiagnostics: () => ({ animations: [], multipleTimelines: false, @@ -119,6 +123,7 @@ describe("useStudioAgentTools", () => { "studio_inspect", "studio_set_text", "studio_set_style", + "studio_transform", ]); expect(trackEvent).toHaveBeenCalledWith("webmcp.native_present"); }); @@ -133,14 +138,14 @@ describe("useStudioAgentTools", () => { await act(async () => { harness = mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); await act(async () => { harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) })); harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); }); it("executes against the LATEST deps, not the ones present at registration", async () => { @@ -213,7 +218,7 @@ describe("useStudioAgentTools", () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - expect(registerTool).toHaveBeenCalledTimes(7); + expect(registerTool).toHaveBeenCalledTimes(8); }); it("reports a non-abort registration failure through production telemetry", async () => { diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index a8f25c61c8..f62c369bcd 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -52,6 +52,14 @@ import { type StudioSetStyleResult, type StudioSetTextResult, } from "./tools/contentTools"; +import { + studioTransform, + STUDIO_TRANSFORM_DESCRIPTION, + STUDIO_TRANSFORM_INPUT_SCHEMA, + type StudioTransformInput, + type StudioTransformResult, + type TransformToolDeps, +} from "./tools/transformTools"; const log = makeStudioDebugLogger("webmcp"); @@ -66,7 +74,7 @@ function reportRegistration(report: ToolRegistrationReport, native: boolean): vo } export interface StudioAgentToolsDeps - extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps { + extends SelectionToolDeps, FrameToolDeps, InspectToolDeps, ContentToolDeps, TransformToolDeps { /** Read Studio's current state. Called per tool invocation, never cached. */ getSnapshot: () => StudioLookSnapshot; } @@ -156,6 +164,17 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): execute: (input): Promise> => runToolBody("studio_set_style", () => studioSetStyle(depsRef.current, input)), }, + { + name: "studio_transform", + title: "Move, resize or rotate", + description: STUDIO_TRANSFORM_DESCRIPTION, + inputSchema: STUDIO_TRANSFORM_INPUT_SCHEMA, + annotations: { readOnlyHint: false }, + execute: (input): Promise> => + runToolBody("studio_transform", () => + studioTransform(depsRef.current, input as StudioTransformInput), + ), + }, ]; } From d7a692c97c8dc2c8c99de577e21b24e18b07eb2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miguel=20=C3=81ngel?= Date: Sun, 30 Aug 2026 01:25:53 -0400 Subject: [PATCH 09/10] docs: document Studio's WebMCP agent tools, proven end-to-end in a browser (#3521) * docs: document Studio's WebMCP agent tools Adds `guides/webmcp`, under Developers > Agent setup. Its first job is to defuse a name collision. `guides/mcp` already exists and covers HeyGen's HOSTED MCP connector, which builds a video from a chat. This page is about an agent working inside Studio on a composition already open in front of you. Different feature, confusingly similar name, so the page says what it is not before it says what it is. Written to DOCS_GUIDELINES: one-sentence intro, outcome before implementation, real values rather than placeholders, and three callouts. The three things a reader most needs are the ones easiest to get wrong: The API is `document.modelContext`, not `navigator.modelContext`. Most published examples use the second, which is a polyfill compatibility shim rather than a spec member, so feature-detecting it misleads. Select first, then edit. Most editing tools act on the current selection, and an agent that skips it gets an error rather than a wrong-element write. Leave Studio visible. Some of Studio's write paths report failure through a toast rather than a return value, so the human is the one who sees it. That is a real property of the co-pilot design, not a nicety, so the page says it plainly. Verified with `npx mint validate` and `npx mint broken-links --check-redirects`, both passing. * fix(studio): target the text field that exists, not one named self Found by running the tools end to end in a browser, which is the only way it could have been found: the unit tests mock `setText`, so they never crossed the boundary where this breaks. An element's text usually lives in a CHILD field, keyed like `self:0:h1` or `child:0:h1`. `studio_set_text` passed no field key, so `buildNextDomTextFields` planned zero operations, the request went out with an empty patch, and the server answered: POST /api/projects//file-mutations/patch-element -> 400 {"error":"target and operations required"} Which surfaced as `persist-failed`. The tool was telling the truth, so the reporting work in the earlier PRs did its job, but the failure looked like a server problem and was not. The tool now resolves the field: the one the caller named, or the element's single field when it has exactly one. An element with several fields is asked to name one; an element with none is reported blocked. Naming a field the element does not have is rejected with the list of the ones it does have, rather than silently writing nowhere. Four regression tests, including the exact `child:0:h1` shape that failed. One existing assertion changed: it expected the field to be `undefined`, which is precisely the bug, so it now expects the resolved key. Also documents two things the browser run surfaced, both real and neither a defect: registration is asynchronous, so a caller reading `getTools()` too early sees a partial list; and the tools that act on the current selection need a render between the select and the edit, which a real agent gets for free because its calls arrive as separate messages. * docs: give the agent-tools kill switch instructions that work The page told readers to set agentToolsEnabled in Studio's preferences. Nothing writes that flag: it is read in useStudioAgentTools and parsed in studioUiPreferences, but there is no settings UI and no toggle, so the instruction could not be followed. Replace it with the localStorage write that actually flips it, and spell out the merge, since overwriting the key drops every other stored preference. * docs: do not promise a per-call permission prompt we have not verified The page said the browser asks before any agent calls a tool. Prompt granularity is browser-specific and unsettled during the origin trial, and we have not observed it on the native path. Say what holds, that access is gated, and name the part that is still moving. --- docs/docs.json | 3 +- docs/guides/webmcp.mdx | 149 ++++++++++++++++++ .../src/webmcp/tools/contentTools.test.ts | 76 ++++++++- .../studio/src/webmcp/tools/contentTools.ts | 37 ++++- 4 files changed, 261 insertions(+), 4 deletions(-) create mode 100644 docs/guides/webmcp.mdx diff --git a/docs/docs.json b/docs/docs.json index 91a3048fd1..632c0a2a3a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -872,7 +872,8 @@ "group": "Agent setup", "pages": [ "guides/authentication", - "guides/skills" + "guides/skills", + "guides/webmcp" ] }, { diff --git a/docs/guides/webmcp.mdx b/docs/guides/webmcp.mdx new file mode 100644 index 0000000000..78848a3844 --- /dev/null +++ b/docs/guides/webmcp.mdx @@ -0,0 +1,149 @@ +--- +title: "Let an agent drive Studio" +sidebarTitle: "Agent tools (WebMCP)" +description: "Studio exposes its editing capabilities as WebMCP tools, so an agent in your browser can see the composition and change it alongside you." +--- + +Studio registers its own capabilities as WebMCP tools, so an AI agent running in your browser can read what Studio knows and make the same edits you can. + + + This is not the same as [creating through an AI chat](/guides/mcp). That page covers the hosted + HyperFrames MCP connector, which builds and renders a video from a conversation. This page is + about an agent working *inside Studio*, on a composition already open in front of you. + + +## What it looks like + +With the tools available, an agent can do this without touching your files: + +```text +studio_look -> the project, playhead, selection, and every element +studio_select hf:abc123 -> selects the headline, same as clicking it +studio_inspect -> its resolved styles, text, and animations +studio_set_style {"color":"red"} -> writes it, through Studio's own commit path +studio_frame 2.4 -> a PNG of the composition at 2.4 seconds +``` + +The last one matters most. It is what lets an agent judge a change instead of guessing at it. + +## Turning it on + +The tools register automatically when Studio loads. Whether an agent can *reach* them depends on the browser. + +| Browser | Status | +| --- | --- | +| Chrome 149 | Origin Trial | +| Edge 150 | Origin Trial | +| ChatGPT Desktop | Shipped | +| Brave (Leo) | Experimental | +| Firefox, Safari | Not yet | + +For local development in Chrome, enable the flag and restart: + +```text chrome://flags +chrome://flags/#enable-webmcp-testing +``` + +Then confirm the tools are there from Studio's console: + +```javascript +const tools = await document.modelContext.getTools(); +console.log(tools.map((tool) => tool.name)); +// ["studio_look", "studio_select", "studio_seek", ...] +``` + + + Registration is asynchronous, so a caller that reads `getTools()` the instant Studio loads can + see a partial list. Wait for the `toolchange` event, or poll until the count settles at twelve. + + + + The API is `document.modelContext`, not `navigator.modelContext`. Many published examples use + the second one. It is a compatibility shim some polyfills add, not part of the specification, so + feature-detecting it will mislead you. + + +On browsers without native support, Studio loads a polyfill so a WebMCP bridge extension can still +connect. Nothing is downloaded on a browser that has the API already. + +## What an agent can do + +### Read + +| Tool | Answers | +| --- | --- | +| `studio_look` | The open project and composition, the playhead, what you have selected, and every element with a handle | +| `studio_inspect` | One element in full: resolved styles, text fields, box, animations, and what it will accept | +| `studio_frame` | A PNG of the composition at any time | + +`studio_look` gives every element a **handle**. Pass it back to any tool that edits an element. + +### Change + +| Tool | Does | +| --- | --- | +| `studio_select` | Selects an element, exactly as clicking it does | +| `studio_seek` | Moves the playhead | +| `studio_set_text` | Rewrites text | +| `studio_set_style` | Sets inline styles | +| `studio_transform` | Moves, resizes or rotates | +| `studio_add_animation` | Adds a GSAP animation at the playhead | +| `studio_update_animation` | Changes a duration, ease or position | +| `studio_add_keyframe` | Adds a keyframe to an animation | +| `studio_delete_animation` | Removes an animation | + +Every edit runs through the same commit path a mouse gesture uses, so it lands in your file with the +same undo entry and the same save behaviour. There is no separate agent write path. + +## Two rules worth knowing + +**Select first, then edit.** Most editing tools act on the current selection rather than taking an +element. That is how Studio itself works: click, then type. An agent that edits without selecting +gets an error telling it to select. + +**Check what came back.** Tools report what actually happened, not what was asked for. +`studio_transform` reads the element's box back after writing and tells you which operations took +effect. `studio_frame` reports the time it actually captured. When something could not be verified, +the tool says so rather than claiming success. + +## Working alongside an agent + +This is built for you and an agent looking at the same composition. Studio shows you every change as +it happens: an agent selecting an element draws the same selection box, and an edit appears in your +undo history under its own name. + +That shared view is doing real work. Some of Studio's write paths report a failure through a toast +rather than a return value, so **you** are the one who sees it. Leave Studio visible while an agent +is working. + + + Studio refuses agent writes while auto-save is paused or an external change to the file is waiting + for your decision, and tells the agent why. Resolve the banner and it can continue. + + +## Turning it off + +There is no settings toggle yet. The switch is a Studio preference, so set it from the console and +reload: + +```javascript +const KEY = "hf-studio-ui-preferences"; +const prefs = JSON.parse(localStorage.getItem(KEY) ?? "{}"); +localStorage.setItem(KEY, JSON.stringify({ ...prefs, agentToolsEnabled: false })); +location.reload(); +``` + +Read the existing object and spread it, as above. Writing `{agentToolsEnabled: false}` on its own +replaces the whole preferences blob and loses your panel sizes, zoom and timeline settings. + +Set it back to `true`, or delete the key, to re-enable. + +The browser gates tool access behind its own permission prompt, so registering a tool is not the same +as granting access to it. How often you are asked, once per site or every call, is up to the browser +and is still changing while the API is in origin trial. + +## Related topics + +- [Create through an AI chat](/guides/mcp) +- [Install and update agent skills](/guides/skills) +- [Work on the project in Studio](/studio) diff --git a/packages/studio/src/webmcp/tools/contentTools.test.ts b/packages/studio/src/webmcp/tools/contentTools.test.ts index 7b5d825ade..63f41b79e6 100644 --- a/packages/studio/src/webmcp/tools/contentTools.test.ts +++ b/packages/studio/src/webmcp/tools/contentTools.test.ts @@ -29,7 +29,8 @@ describe("studioSetText", () => { const ok = expectOk(result); expect(ok.text).toBe("Ship it faster"); expect(ok.changed).toBe(true); - expect(setText).toHaveBeenCalledWith("Ship it faster", undefined); + // The single field is resolved and named, rather than left undefined. + expect(setText).toHaveBeenCalledWith("Ship it faster", "self"); }); it("reports changed:false when the text already said that", async () => { @@ -105,6 +106,79 @@ describe("studioSetText", () => { expect(result.hint).toMatch(/studio_select/); expect(setText).not.toHaveBeenCalled(); }); + + it("targets the element's ACTUAL text field, not a field called self", async () => { + // Found end to end, not by these tests. An element's text usually lives in a + // child field keyed like `child:0:h1`. Passing no key planned zero + // operations, and the server rejected the empty patch with + // "target and operations required" -- a persist failure that looked like a + // server problem and was not. + const element = previewElement('

Ship it

', "headline"); + const selection = selectionFor(element); + selection.textFields = [{ ...selection.textFields[0]!, key: "child:0:h1" }]; + const setText = vi.fn(async () => ({ ok: true }) as const); + + await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), { + text: "Shipped it", + }); + + expect(setText).toHaveBeenCalledWith("Shipped it", "child:0:h1"); + }); + + it("rejects a field the element does not have, rather than writing nowhere", async () => { + const element = previewElement('

Ship it

', "headline"); + const selection = selectionFor(element); + selection.textFields = [{ ...selection.textFields[0]!, key: "child:0:h1" }]; + const setText = vi.fn(); + + const result = expectFailure( + await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), { + text: "x", + field: "self", + }), + ); + + expect(result.kind).toBe("invalid"); + expect(result.hint).toContain("child:0:h1"); + expect(setText).not.toHaveBeenCalled(); + }); + + it("asks which field when the element has several", async () => { + const element = previewElement('
a
', "card"); + const selection = selectionFor(element); + const base = selection.textFields[0]!; + selection.textFields = [ + { ...base, key: "child:0:h2" }, + { ...base, key: "child:1:p" }, + ]; + const setText = vi.fn(); + + const result = expectFailure( + await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), { + text: "x", + }), + ); + + expect(result.kind).toBe("invalid"); + expect(result.reason).toMatch(/2 text fields/); + expect(setText).not.toHaveBeenCalled(); + }); + + it("reports an element with no text field as blocked", async () => { + const element = previewElement('
', "box"); + const selection = selectionFor(element); + selection.textFields = []; + const setText = vi.fn(); + + const result = expectFailure( + await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), { + text: "x", + }), + ); + + expect(result.kind).toBe("blocked"); + expect(setText).not.toHaveBeenCalled(); + }); }); describe("studioSetStyle", () => { diff --git a/packages/studio/src/webmcp/tools/contentTools.ts b/packages/studio/src/webmcp/tools/contentTools.ts index 6e5a85b943..19d26dda39 100644 --- a/packages/studio/src/webmcp/tools/contentTools.ts +++ b/packages/studio/src/webmcp/tools/contentTools.ts @@ -79,12 +79,45 @@ export async function studioSetText( if (typeof input.text !== "string") { return toolFailure("invalid", "text must be a string"); } - const field = typeof input.field === "string" && input.field ? input.field : undefined; const blocked = guardWrite(deps); if (blocked) return blocked; - const before = deps.getCurrentSelection()?.textContent ?? null; + const selection = deps.getCurrentSelection(); + if (!selection) return toolFailure("invalid", "nothing is selected"); + + const fields = selection.textFields; + const requested = typeof input.field === "string" && input.field ? input.field : undefined; + if (requested && !fields.some((candidate) => candidate.key === requested)) { + return toolFailure( + "invalid", + `this element has no text field "${requested}"`, + `Its fields are: ${fields.map((candidate) => candidate.key).join(", ") || "none"}.`, + ); + } + + // Resolving the field is NOT optional. An element's text usually lives in a + // child field keyed like `child:0:h1`, not in one called `self`, and passing + // no key plans zero operations. The server then rejects the empty patch with + // "target and operations required", which surfaces as a persist failure that + // looks like a server problem and is not. + const field = requested ?? (fields.length === 1 ? fields[0]?.key : undefined); + if (!field) { + if (fields.length === 0) { + return toolFailure( + "blocked", + "this element has no editable text field", + "studio_inspect lists an element's textFields.", + ); + } + return toolFailure( + "invalid", + `this element has ${fields.length} text fields, so one must be named`, + `Pass field as one of: ${fields.map((candidate) => candidate.key).join(", ")}.`, + ); + } + + const before = selection.textContent ?? null; const outcome = await deps.setText(input.text, field); const failure = fromOutcome(outcome, "the text"); if (failure) return failure; From 63dfc4fba4bfa9111a04ff05a5a73c1a77c19ef3 Mon Sep 17 00:00:00 2001 From: miga-heygen Date: Mon, 31 Aug 2026 18:27:42 +0000 Subject: [PATCH 10/10] fix(studio): re-apply WebMCP test polyfill fix (#3532 regression) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The squash merge of #3518 re-introduced the old assertion that document.modelContext is absent. The polyfill from #3514 installs it as a fallback — that is expected behavior. Same fix as #3532: remove the assertion, keep the boot-cleanly contract. --- packages/studio/src/webmcp/useStudioAgentTools.test.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index b797cc0f87..2dfd169349 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -196,16 +196,16 @@ describe("useStudioAgentTools", () => { expect(signal?.aborted).toBe(true); }); - it("registers nothing when the browser has no WebMCP", async () => { + it("boots cleanly when the browser has no native WebMCP", async () => { removeModelContext(); await act(async () => { mountTools(deps({ getSnapshot: () => snapshot() })); }); - // The assertion is that mounting did not throw; a browser without the API - // must still boot Studio. - expect(document).not.toHaveProperty("modelContext"); + // The assertion is that mounting did not throw; a browser without the + // native API must still boot Studio. The polyfill may install + // document.modelContext as a fallback — that is expected. }); it("registers nothing when the preference is turned off", async () => {