Skip to content

Commit f766c84

Browse files
committed
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.
1 parent 1478adf commit f766c84

8 files changed

Lines changed: 459 additions & 7 deletions

File tree

‎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: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,20 @@ 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+
} = useDomEditActionsContext();
2934

3035
const getSnapshot = useCallback((): StudioLookSnapshot => {
3136
const player = usePlayerStore.getState();
@@ -77,6 +82,9 @@ export function StudioAgentTools() {
7782
},
7883
wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
7984
getCurrentSelection: () => domEditSelection,
85+
getWriteBlockedReason: () => writeBlockedReason,
86+
setText: (value, fieldKey) => handleDomTextCommit(value, fieldKey),
87+
setStyle: (property, value) => handleDomStyleCommit(property, value),
8088
getGsapDiagnostics: () => ({
8189
animations: selectedGsapAnimations,
8290
multipleTimelines: gsapMultipleTimelines,
@@ -90,6 +98,9 @@ export function StudioAgentTools() {
9098
applyDomSelection,
9199
projectId,
92100
activeCompPath,
101+
writeBlockedReason,
102+
handleDomTextCommit,
103+
handleDomStyleCommit,
93104
domEditSelection,
94105
selectedGsapAnimations,
95106
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)