Skip to content

Commit f84b4c2

Browse files
miguel-heygenmiga-heygenclaude
authored
feat(studio): let an agent edit text and styles, guarded (#3518)
* 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. * 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. * 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. * 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. * 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. * 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. --------- Co-authored-by: miga-heygen <miguel.sierra_miga@heygen.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 5b45bcc commit f84b4c2

10 files changed

Lines changed: 882 additions & 7 deletions

packages/studio/src/App.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -433,6 +433,8 @@ export function StudioApp() {
433433
handleRedo: appHotkeys.handleRedo,
434434
renderQueue,
435435
compositionDimensions,
436+
domEditSaveQueuePaused: previewPersistence.domEditSaveQueuePaused,
437+
externalFileConflict: externalFileChanges.blocked !== null,
436438
waitForPendingDomEditSaves: previewPersistence.waitForPendingDomEditSaves,
437439
handlePreviewIframeRef,
438440
refreshPreviewDocumentVersion,

packages/studio/src/contexts/StudioContext.tsx

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ export interface StudioShellValue {
1616
undoLabel: string | undefined;
1717
redoLabel: string | undefined;
1818
};
19+
/**
20+
* Why a composition write would be refused right now, or null when writes
21+
* are possible. Derived from the paused save queue and the external-file
22+
* conflict state, both of which are otherwise banners with no lock behind
23+
* them. One field rather than two, so there is one owner of the question.
24+
*/
25+
writeBlockedReason: string | null;
1926
handleUndo: () => Promise<void>;
2027
handleRedo: () => Promise<void>;
2128
renderQueue: {
@@ -106,6 +113,7 @@ export function StudioShellProvider({
106113
showToast,
107114
previewIframeRef,
108115
editHistory,
116+
writeBlockedReason,
109117
handleUndo,
110118
handleRedo,
111119
renderQueue,
@@ -122,6 +130,7 @@ export function StudioShellProvider({
122130
showToast,
123131
previewIframeRef,
124132
editHistory,
133+
writeBlockedReason,
125134
handleUndo,
126135
handleRedo,
127136
renderQueue,
@@ -138,6 +147,7 @@ export function StudioShellProvider({
138147
setActiveCompPath,
139148
showToast,
140149
previewIframeRef,
150+
writeBlockedReason,
141151
handleUndo,
142152
handleRedo,
143153
waitForPendingDomEditSaves,

packages/studio/src/hooks/useStudioContextValue.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ interface StudioContextInput {
2525
// fields around it: the context type owns it.
2626
renderQueue: StudioContextValue["renderQueue"];
2727
compositionDimensions: { width: number; height: number } | null;
28+
/** Message from `usePreviewPersistence` when auto-save is paused. */
29+
domEditSaveQueuePaused: string | null;
30+
/** True when an external edit to the open file is awaiting the user's decision. */
31+
externalFileConflict: boolean;
2832
waitForPendingDomEditSaves: () => Promise<void>;
2933
handlePreviewIframeRef: (iframe: HTMLIFrameElement | null) => void;
3034
refreshPreviewDocumentVersion: () => void;
@@ -46,6 +50,11 @@ export function buildStudioContextValue(input: StudioContextInput): StudioContex
4650
timelineElements: input.timelineElements,
4751
isPlaying: input.isPlaying,
4852
editHistory: input.editHistory,
53+
// Conflict first: when both are true the conflict is the one the user has
54+
// been asked to decide, and resolving it is what unblocks the queue.
55+
writeBlockedReason: input.externalFileConflict
56+
? "an external change to this file is waiting to be resolved"
57+
: input.domEditSaveQueuePaused,
4958
handleUndo: input.handleUndo,
5059
handleRedo: input.handleRedo,
5160
renderQueue: input.renderQueue,

packages/studio/src/webmcp/StudioAgentTools.tsx

Lines changed: 29 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,23 @@ import type { StudioLookSnapshot } from "./tools/lookTools";
1717
* every animation frame during playback for a value nothing here displays.
1818
*/
1919
export function StudioAgentTools() {
20-
const { projectId, activeCompPath, editHistory } = useStudioShellContext();
20+
const { projectId, activeCompPath, editHistory, writeBlockedReason } = useStudioShellContext();
2121
const {
2222
domEditSelection,
2323
selectedGsapAnimations,
2424
gsapMultipleTimelines,
2525
gsapUnsupportedTimelinePattern,
2626
} = useDomEditSelectionContext();
27-
const { previewIframeRef, buildDomSelectionFromTarget, applyDomSelection } =
28-
useDomEditActionsContext();
27+
const {
28+
previewIframeRef,
29+
buildDomSelectionFromTarget,
30+
applyDomSelection,
31+
handleDomTextCommit,
32+
handleDomStyleCommit,
33+
handleDomPathOffsetCommit,
34+
handleDomBoxSizeCommit,
35+
handleDomRotationCommit,
36+
} = useDomEditActionsContext();
2937

3038
const getSnapshot = useCallback((): StudioLookSnapshot => {
3139
const player = usePlayerStore.getState();
@@ -77,6 +85,18 @@ export function StudioAgentTools() {
7785
},
7886
wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7987
getCurrentSelection: () => domEditSelection,
88+
getWriteBlockedReason: () => writeBlockedReason,
89+
setText: (value, fieldKey) => handleDomTextCommit(value, fieldKey),
90+
setStyle: (property, value) => handleDomStyleCommit(property, value),
91+
// Measured, not authored: the tool compares this before and after to
92+
// tell a real change from a handler that did nothing and resolved.
93+
readBox: (selection) => {
94+
const rect = selection.element.getBoundingClientRect();
95+
return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };
96+
},
97+
moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next),
98+
resizeTo: (selection, next) => handleDomBoxSizeCommit(selection, next),
99+
rotateTo: (selection, next) => handleDomRotationCommit(selection, next),
80100
getGsapDiagnostics: () => ({
81101
animations: selectedGsapAnimations,
82102
multipleTimelines: gsapMultipleTimelines,
@@ -90,6 +110,12 @@ export function StudioAgentTools() {
90110
applyDomSelection,
91111
projectId,
92112
activeCompPath,
113+
writeBlockedReason,
114+
handleDomTextCommit,
115+
handleDomStyleCommit,
116+
handleDomPathOffsetCommit,
117+
handleDomBoxSizeCommit,
118+
handleDomRotationCommit,
93119
domEditSelection,
94120
selectedGsapAnimations,
95121
gsapMultipleTimelines,
Lines changed: 201 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
// @vitest-environment jsdom
2+
import { describe, expect, it, vi } from "vitest";
3+
import {
4+
studioSetStyle,
5+
studioSetText,
6+
type ContentToolDeps,
7+
type StudioSetStyleResult,
8+
type StudioSetTextResult,
9+
} from "./contentTools";
10+
import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils";
11+
12+
function contentDeps(overrides: Partial<ContentToolDeps> = {}): ContentToolDeps {
13+
const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");
14+
return {
15+
getCurrentSelection: () => selectionFor(element),
16+
getWriteBlockedReason: () => null,
17+
setText: async () => ({ ok: true }),
18+
setStyle: async () => ({ ok: true }),
19+
...overrides,
20+
};
21+
}
22+
23+
describe("studioSetText", () => {
24+
it("writes the text and reports what it now is", async () => {
25+
const setText = vi.fn(async () => ({ ok: true }) as const);
26+
27+
const result = await studioSetText(contentDeps({ setText }), { text: "Ship it faster" });
28+
29+
const ok = expectOk<StudioSetTextResult>(result);
30+
expect(ok.text).toBe("Ship it faster");
31+
expect(ok.changed).toBe(true);
32+
expect(setText).toHaveBeenCalledWith("Ship it faster", undefined);
33+
});
34+
35+
it("reports changed:false when the text already said that", async () => {
36+
const result = await studioSetText(contentDeps(), { text: "Ship it" });
37+
38+
expect(expectOk<StudioSetTextResult>(result).changed).toBe(false);
39+
});
40+
41+
it("refuses to write while a conflict is waiting for the user", async () => {
42+
// The paused-save and conflict states are banners with no lock behind them.
43+
// Nothing else stops a programmatic write landing on top of a decision the
44+
// user has been asked to make.
45+
const setText = vi.fn();
46+
47+
const result = expectFailure(
48+
await studioSetText(
49+
contentDeps({
50+
getWriteBlockedReason: () => "an external change to this file is waiting to be resolved",
51+
setText,
52+
}),
53+
{ text: "Ship it faster" },
54+
),
55+
);
56+
57+
expect(result.kind).toBe("blocked");
58+
expect(result.reason).toMatch(/external change/);
59+
expect(setText).not.toHaveBeenCalled();
60+
});
61+
62+
it("does not report success when the commit declined", async () => {
63+
// The whole reason the handlers now return an outcome: they resolve on
64+
// failure, so awaiting them proves nothing.
65+
const result = expectFailure(
66+
await studioSetText(
67+
contentDeps({ setText: async () => ({ ok: false, reason: "persist-failed" }) }),
68+
{ text: "Ship it faster" },
69+
),
70+
);
71+
72+
expect(result.kind).toBe("failed");
73+
expect(result.reason).toMatch(/persist-failed/);
74+
});
75+
76+
it("turns a decline reason into a hint naming what to do instead", async () => {
77+
const result = expectFailure(
78+
await studioSetText(
79+
contentDeps({ setText: async () => ({ ok: false, reason: "not-text-editable" }) }),
80+
{ text: "x" },
81+
),
82+
);
83+
84+
expect(result.kind).toBe("blocked");
85+
expect(result.hint).toMatch(/studio_inspect/);
86+
});
87+
88+
it("rejects a non-string text without dispatching", async () => {
89+
const setText = vi.fn();
90+
91+
const result = expectFailure(await studioSetText(contentDeps({ setText }), { text: 42 }));
92+
93+
expect(result.kind).toBe("invalid");
94+
expect(setText).not.toHaveBeenCalled();
95+
});
96+
97+
it("fails when nothing is selected", async () => {
98+
const setText = vi.fn();
99+
100+
const result = expectFailure(
101+
await studioSetText(contentDeps({ getCurrentSelection: () => null, setText }), { text: "x" }),
102+
);
103+
104+
expect(result.kind).toBe("invalid");
105+
expect(result.hint).toMatch(/studio_select/);
106+
expect(setText).not.toHaveBeenCalled();
107+
});
108+
});
109+
110+
describe("studioSetStyle", () => {
111+
it("applies every property and reports them", async () => {
112+
const setStyle = vi.fn(async () => ({ ok: true }) as const);
113+
114+
const result = await studioSetStyle(contentDeps({ setStyle }), {
115+
styles: { color: "red", "font-size": "48px" },
116+
});
117+
118+
const ok = expectOk<StudioSetStyleResult>(result);
119+
expect(ok.applied).toEqual({ color: "red", "font-size": "48px" });
120+
expect(ok.rejected).toEqual({});
121+
expect(setStyle).toHaveBeenCalledTimes(2);
122+
});
123+
124+
it("commits sequentially, never concurrently", async () => {
125+
// Two commits racing through Studio's client-side read-modify-write can
126+
// record undo entries that both claim the same starting content.
127+
let inFlight = 0;
128+
let maxInFlight = 0;
129+
const setStyle = vi.fn(async () => {
130+
inFlight += 1;
131+
maxInFlight = Math.max(maxInFlight, inFlight);
132+
await Promise.resolve();
133+
inFlight -= 1;
134+
return { ok: true } as const;
135+
});
136+
137+
await studioSetStyle(contentDeps({ setStyle }), {
138+
styles: { color: "red", "font-size": "48px", opacity: "0.5" },
139+
});
140+
141+
expect(maxInFlight).toBe(1);
142+
});
143+
144+
it("reports a partial success as partial, not whole", async () => {
145+
const setStyle = vi.fn(async (property: string) =>
146+
property === "left"
147+
? ({ ok: false, reason: "geometry-property" } as const)
148+
: ({ ok: true } as const),
149+
);
150+
151+
const result = await studioSetStyle(contentDeps({ setStyle }), {
152+
styles: { color: "red", left: "10px" },
153+
});
154+
155+
const ok = expectOk<StudioSetStyleResult>(result);
156+
expect(ok.applied).toEqual({ color: "red" });
157+
expect(ok.rejected).toEqual({ left: "geometry-property" });
158+
});
159+
160+
it("fails when every property was refused", async () => {
161+
const result = expectFailure(
162+
await studioSetStyle(
163+
contentDeps({ setStyle: async () => ({ ok: false, reason: "styles-not-editable" }) }),
164+
{ styles: { color: "red" } },
165+
),
166+
);
167+
168+
expect(result.kind).toBe("blocked");
169+
expect(result.reason).toMatch(/styles-not-editable/);
170+
});
171+
172+
it("rejects an empty styles object rather than committing nothing", async () => {
173+
const setStyle = vi.fn();
174+
175+
const result = expectFailure(await studioSetStyle(contentDeps({ setStyle }), { styles: {} }));
176+
177+
expect(result.kind).toBe("invalid");
178+
expect(setStyle).not.toHaveBeenCalled();
179+
});
180+
181+
it("rejects a non-object styles value", async () => {
182+
for (const styles of ["color: red", 42, null, ["color"]]) {
183+
const result = expectFailure(await studioSetStyle(contentDeps(), { styles }));
184+
expect(result.kind).toBe("invalid");
185+
}
186+
});
187+
188+
it("refuses to write while a conflict is waiting for the user", async () => {
189+
const setStyle = vi.fn();
190+
191+
const result = expectFailure(
192+
await studioSetStyle(
193+
contentDeps({ getWriteBlockedReason: () => "Auto-save is paused", setStyle }),
194+
{ styles: { color: "red" } },
195+
),
196+
);
197+
198+
expect(result.kind).toBe("blocked");
199+
expect(setStyle).not.toHaveBeenCalled();
200+
});
201+
});

0 commit comments

Comments
 (0)