Write HTML. Render video. Built for agents.
JavaScript aiai-agentsanimationclaude-codeffmpegframeworkgsaphtmlhtml-to-videomcpmotion-graphicspuppeteerrenderingtypescriptvideo-editor
feat(studio): make agent edits live and explicit (#3581)
Miguel Ángel6b5b4cb98890
diff --git a/docs/guides/webmcp.mdx b/docs/guides/webmcp.mdxindex 78848a3844..02b08004ae 100644--- a/docs/guides/webmcp.mdx+++ b/docs/guides/webmcp.mdx@@ -14,14 +14,16 @@ Studio registers its own capabilities as WebMCP tools, so an AI agent running in## What it looks like-With the tools available, an agent can do this without touching your files:+With the tools available, an agent can inspect the source-backed scene, make one targeted edit, and+check the result:```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+studio_look -> find the headline and copy its handle+studio_select {"handle":"hf:abc123"} -> share the target with the person in Studio+studio_inspect {"handle":"hf:abc123"} -> read its styles, text, and capabilities+studio_set_style {"handle":"hf:abc123",+ "styles":{"color":"red"}} -> write that source-backed element+studio_frame {"time":2.4} -> capture 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.@@ -63,8 +65,9 @@ console.log(tools.map((tool) => tool.name));feature-detecting it will mislead you.</Warning>-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.+On browsers without native support, Studio loads a bundled polyfill so a WebMCP bridge extension can+still connect. Nothing is downloaded on a browser that has the API already. When the Studio+preference is disabled, it registers no tools.## What an agent can do@@ -72,11 +75,14 @@ connect. Nothing is downloaded on a browser that has the API already.| Tool | Answers || --- | --- |-| `studio_look` | The open project and composition, the playhead, what you have selected, and every element with a handle |+| `studio_look` | The open project and composition, the playhead, selection, undo state, and a bounded source-backed scene in nested order || `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.+Each element returned by `studio_look` has a **handle**. It also reports `sourceFile`, `parentHandle`,+`depth`, and `childCount`, so an agent can distinguish the same authored ID in two nested scene+files. Pass a handle back unchanged to every element write. Handles are source-safe addresses, not+CSS selectors.### Change@@ -92,29 +98,49 @@ connect. Nothing is downloaded on a browser that has the API already.| `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.+Element writes run through the same commit actors Studio uses. When that actor forwards versioned+durability evidence, the receipt names the source file and content version, and the edit enters the+same undo history. Actors without that evidence stay at `dispatched`.## 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.+**Show intent, then address every write explicitly.** Before the first write to a target, call+`studio_select` so the person in Studio sees the same selection box and inspector as the agent.+Selection communicates intent; it does not grant write authority. `studio_set_text`,+`studio_set_style`, `studio_transform`, and the animation tools still require that target's handle+from `studio_look`, so a later human click cannot redirect an already-addressed write.-**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.+**Read the receipt stage.** A write result separates acceptance from proof:++| Stage | What it proves |+| --- | --- |+| `refused` | No commit actor ran. Fix the handle, input, capability, or Studio state before retrying. |+| `dispatched` | The actor accepted the request, but the tool has no durable version or independent readback. Follow with `studio_inspect` or `studio_frame`. |+| `saved` | Studio received versioned evidence that the named source file persisted the write. |+| `verified` | The write was saved and an independent readback observed the result. |+| `failed` | A commit actor ran and then failed. Inspect `kind`, `reason`, and any `hint`. |++`changed` is separate from the stage. A saved no-op is still truthful: the file accepted the request,+but the value was already present. Style writes include a receipt per property and can be partial.+Animation handlers currently report `dispatched` after their persistence and live-preview sync+settle; they do not claim versioned durability or independent readback when the underlying handler+cannot provide that evidence. A late cancellation request also does not undo an edit that was+already dispatched or saved.## 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.+This is built for you and an agent looking at the same composition. Studio shows selection normally+and adds a **Topology Lens** around the addressed element while a transaction is resolving. A new+target is acquired, repeated edits localize more quickly, and a durable result seals. The lens is+Studio-only transaction feedback: it is not added to authored HTML, the preview iframe, captured+frames, or thumbnails.++When a write tool finishes successfully, the open Studio preview has already synchronized that+edit. The person watching does not need to scrub the timeline or refresh the browser to see it.-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.+After an accepted source-file change, Studio advances the project thumbnail revision and regenerates+visible composition thumbnails. This lets the sidebar converge on the saved project instead of+continuing to show cached pre-edit pixels.<Note>Studio refuses agent writes while auto-save is paused or an external change to the file is waitingdiff --git a/packages/studio-server/src/helpers/projectSignature.test.ts b/packages/studio-server/src/helpers/projectSignature.test.tsindex d6d5afcdd4..266173ef81 100644--- a/packages/studio-server/src/helpers/projectSignature.test.ts+++ b/packages/studio-server/src/helpers/projectSignature.test.ts@@ -1,6 +1,23 @@-import { describe, expect, it } from "vitest";+import { afterEach, describe, expect, it } from "vitest";+import {+ closeSync,+ fstatSync,+ ftruncateSync,+ futimesSync,+ mkdtempSync,+ openSync,+ rmSync,+ writeSync,+} from "node:fs";+import { tmpdir } from "node:os";import { resolve } from "node:path";-import { affectsProjectSignature } from "./projectSignature.js";+import { affectsProjectSignature, createProjectSignature } from "./projectSignature.js";++const temporaryProjects: string[] = [];++afterEach(() => {+ for (const project of temporaryProjects.splice(0)) rmSync(project, { recursive: true });+});const PROJECT = resolve("/projects/demo");const affects = (relativePath: string) =>@@ -42,3 +59,25 @@ describe("affectsProjectSignature", () => {expect(affectsProjectSignature(PROJECT, PROJECT)).toBe(false);});});++describe("createProjectSignature", () => {+ it("changes after same-size content is written with the original mtime restored", () => {+ const project = mkdtempSync(resolve(tmpdir(), "hf-signature-"));+ temporaryProjects.push(project);+ const file = resolve(project, "index.html");+ const descriptor = openSync(file, "w+");+ try {+ writeSync(descriptor, "first");+ const originalMtime = fstatSync(descriptor).mtime;+ const before = createProjectSignature(project);++ ftruncateSync(descriptor, 0);+ writeSync(descriptor, "other", 0, "utf8");+ futimesSync(descriptor, originalMtime, originalMtime);++ expect(createProjectSignature(project)).not.toBe(before);+ } finally {+ closeSync(descriptor);+ }+ });+});diff --git a/packages/studio-server/src/helpers/projectSignature.ts b/packages/studio-server/src/helpers/projectSignature.tsindex 051616e11b..c0a1bd5201 100644--- a/packages/studio-server/src/helpers/projectSignature.ts+++ b/packages/studio-server/src/helpers/projectSignature.ts@@ -70,6 +70,7 @@ export function affectsProjectSignature(projectDir: string, changedPath: string)interface ProjectSignatureFile {file: string;mtimeMs: number;+ ctimeMs: number;size: number;textContentEligible: boolean;}@@ -124,6 +125,7 @@ function collectProjectSignatureFiles(files.push({file,mtimeMs: stat.mtimeMs,+ ctimeMs: stat.ctimeMs,size: stat.size,textContentEligible: isTextContentEligible(file, stat.size),});@@ -149,6 +151,7 @@ function collectProjectSignatureManifestFiles(files.push({file,mtimeMs: stat.mtimeMs,+ ctimeMs: stat.ctimeMs,size: stat.size,textContentEligible: isTextContentEligible(file, stat.size),});@@ -165,6 +168,8 @@ function createProjectFingerprint(projectDir: string, files: ProjectSignatureFilhash.update("\0");hash.update(String(entry.mtimeMs));hash.update("\0");+ hash.update(String(entry.ctimeMs));+ hash.update("\0");hash.update(entry.textContentEligible ? "text" : "binary");hash.update("\0");}diff --git a/packages/studio-server/src/routes/files.test.ts b/packages/studio-server/src/routes/files.test.tsindex d3d42d3e2b..0a68396a20 100644--- a/packages/studio-server/src/routes/files.test.ts+++ b/packages/studio-server/src/routes/files.test.ts@@ -437,11 +437,15 @@ describe("registerFileRoutes", () => {const payload = (await response.json()) as {changed?: boolean;path?: string;+ version?: string;backupPath?: string;};expect(payload.changed).toBe(true);expect(payload.path).toBe("index.html");+ expect(payload.version).toBe(+ fileContentVersion(readFileSync(join(projectDir, "index.html"), "utf-8")),+ );expect(payload.backupPath).toMatch(/^\.hyperframes\/backup\//);expect(readFileSync(join(projectDir, payload.backupPath!), "utf-8")).toBe('<div id="title">Before</div>',@@ -449,6 +453,43 @@ describe("registerFileRoutes", () => {expect(readFileSync(join(projectDir, "index.html"), "utf-8")).toContain("After");});+ it("returns the current durable version for a matched no-op element patch", async () => {+ const projectDir = createProjectDir();+ const original = '<div id="title">Before</div>';+ writeFileSync(join(projectDir, "index.html"), original);+ const app = new Hono();+ registerFileRoutes(app, createAdapter(projectDir));++ const response = await app.request(+ "http://localhost/projects/demo/file-mutations/patch-element/index.html",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ target: { id: "title" },+ operations: [{ type: "text-content", property: "textContent", value: "Before" }],+ }),+ },+ );+ const payload = (await response.json()) as {+ changed?: boolean;+ matched?: boolean;+ path?: string;+ version?: string;+ backupPath?: string;+ };++ expect(response.status).toBe(200);+ expect(payload).toMatchObject({+ changed: false,+ matched: true,+ path: "index.html",+ version: fileContentVersion(original),+ });+ expect(payload.backupPath).toBeUndefined();+ expect(existsSync(join(projectDir, ".hyperframes", "backup"))).toBe(false);+ });+// Without the receipt the client cannot recognise its own edit in the watcher// broadcast, so it treats it as someone else's write and does a full preview// reload — a visible blank on the stage right after the user typed.@@ -1292,6 +1333,30 @@ const tl = gsap.timeline({ paused: true });expect(res.status).toBe(400);});+ it("rejects raw JavaScript expressions at the GSAP mutation boundary", async () => {+ const projectDir = createProjectDir();+ writeHtml(projectDir, "comp.html", FROMTO_COMP);+ const app = new Hono();+ registerFileRoutes(app, createAdapter(projectDir));+ const animation = await getFirstAnimation(app, "comp.html");++ const response = await app.request("http://localhost/projects/demo/gsap-mutations/comp.html", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ type: "update-meta",+ animationId: animation.id,+ updates: { ease: "__raw:(()=>alert(1))()" },+ }),+ });++ expect(response.status).toBe(400);+ expect(await response.json()).toEqual({+ error: "raw JavaScript expressions are not accepted",+ });+ expect(readFileSync(join(projectDir, "comp.html"), "utf8")).toBe(FROMTO_COMP);+ });+it("update-from-property updates a fromTo start value in place", async () => {const projectDir = createProjectDir();writeHtml(projectDir, "comp.html", FROMTO_COMP);diff --git a/packages/studio-server/src/routes/files.ts b/packages/studio-server/src/routes/files.tsindex c45641a33f..7c5d439be9 100644--- a/packages/studio-server/src/routes/files.ts+++ b/packages/studio-server/src/routes/files.ts@@ -1186,6 +1186,9 @@ function validateGsapMutationRequest(if (!body || typeof body !== "object" || !("type" in body) || !body.type) {return c.json({ error: "mutation type required" }, 400);}+ if (containsRawGsapExpression(body)) {+ return c.json({ error: "raw JavaScript expressions are not accepted" }, 400);+ }const unsafeFields = findUnsafeMutationValues(body);if (unsafeFields.length > 0) return rejectUnsafeMutationValues(c, unsafeFields);if (@@ -1197,6 +1200,13 @@ function validateGsapMutationRequest(return null;}+function containsRawGsapExpression(value: unknown): boolean {+ if (typeof value === "string") return value.startsWith("__raw:");+ if (Array.isArray(value)) return value.some(containsRawGsapExpression);+ if (!value || typeof value !== "object") return false;+ return Object.values(value).some(containsRawGsapExpression);+}+async function prepareGsapMutationScript(c: RouteContext,res: ResolvedGsapFile,@@ -2769,27 +2779,32 @@ export function registerFileRoutes(api: Hono, adapter: StudioApiAdapter): void {parsed.body.operations,);if (patched === originalContent) {+ const version = fileContentVersion(originalContent);+ c.header("ETag", version);return c.json({ok: true,changed: false,matched,content: originalContent,path: ctx.filePath,+ version,});}- const { backupPath } = writeMutationResult(+ const { backupPath, version } = writeMutationResult(c,ctx.project.dir,ctx.filePath,ctx.absPath,patched,);+ c.header("ETag", version);return c.json({ok: true,changed: true,matched,content: patched,path: ctx.filePath,+ version,backupPath,});});diff --git a/packages/studio-server/src/routes/thumbnail.test.ts b/packages/studio-server/src/routes/thumbnail.test.tsindex e5101cfcd6..c45b94491b 100644--- a/packages/studio-server/src/routes/thumbnail.test.ts+++ b/packages/studio-server/src/routes/thumbnail.test.ts@@ -14,6 +14,7 @@ import { tmpdir } from "node:os";import { join } from "node:path";import { pruneThumbnailCache, registerThumbnailRoutes } from "./thumbnail";import type { StudioApiAdapter } from "../types";+import { createProjectSignature } from "../helpers/projectSignature.js";const tempProjectDirs: string[] = [];@@ -320,6 +321,98 @@ describe("registerThumbnailRoutes", () => {expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);});+ it("regenerates a parent thumbnail when nested composition HTML changes", async () => {+ const adapter = createAdapter();+ const project = await adapter.resolveProject("demo");+ if (!project) throw new Error("missing project");+ const app = new Hono();+ registerThumbnailRoutes(app, adapter);++ writeFileSync(+ join(project.dir, "index.html"),+ `<div data-width="640" data-height="360" data-composition-src="compositions/nested.html"></div>`,+ );+ const compositionsDir = join(project.dir, "compositions");+ mkdirSync(compositionsDir, { recursive: true });+ const nestedPath = join(compositionsDir, "nested.html");+ writeFileSync(nestedPath, `<div>before</div>`);+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=2&v=test";++ await app.request(url);+ writeFileSync(nestedPath, `<div>after with a different size</div>`);+ await app.request(url);++ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);+ });++ it("regenerates a thumbnail when imported CSS changes", async () => {+ const adapter = createAdapter();+ const project = await adapter.resolveProject("demo");+ if (!project) throw new Error("missing project");+ const app = new Hono();+ registerThumbnailRoutes(app, adapter);++ writeFileSync(+ join(project.dir, "index.html"),+ `<link rel="stylesheet" href="./styles.css"><div data-width="640" data-height="360"></div>`,+ );+ const stylesPath = join(project.dir, "styles.css");+ writeFileSync(stylesPath, `.card { color: red; }`);+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=2&v=test";++ await app.request(url);+ writeFileSync(stylesPath, `.card { color: rebeccapurple; }`);+ await app.request(url);++ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);+ });++ it("uses the adapter-cached project signature for disk reuse and in-flight dedupe", async () => {+ const adapter = createAdapter();+ const project = await adapter.resolveProject("demo");+ if (!project) throw new Error("missing project");+ const getProjectSignature = vi.fn(() => createProjectSignature(project.dir));+ adapter.getProjectSignature = getProjectSignature;+ let resolve!: (buffer: Buffer) => void;+ const generated = new Promise<Buffer>((done) => (resolve = done));+ adapter.generateThumbnail = vi.fn(async () => generated);+ const app = new Hono();+ registerThumbnailRoutes(app, adapter);+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=3";++ const first = app.request(url);+ const duplicate = app.request(url);+ await vi.waitFor(() => expect(adapter.generateThumbnail).toHaveBeenCalledTimes(1));+ resolve(Buffer.from("shared"));+ expect(await (await first).text()).toBe("shared");+ expect(await (await duplicate).text()).toBe("shared");+ expect(await (await app.request(url)).text()).toBe("shared");++ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(1);+ expect(getProjectSignature).toHaveBeenCalledTimes(4);+ expect(getProjectSignature).toHaveBeenNthCalledWith(1, project.dir);+ });++ it("does not cache generated pixels under a signature that changed in flight", async () => {+ const adapter = createAdapter();+ const project = await adapter.resolveProject("demo");+ if (!project) throw new Error("missing project");+ const signatures = ["old", "new", "old", "old"];+ adapter.getProjectSignature = vi.fn(() => signatures.shift() ?? "old");+ adapter.generateThumbnail = vi+ .fn()+ .mockResolvedValueOnce(Buffer.from("rendered-after-change"))+ .mockResolvedValueOnce(Buffer.from("rendered-old"));+ const app = new Hono();+ registerThumbnailRoutes(app, adapter);+ const url = "http://localhost/projects/demo/thumbnail/index.html?t=3";++ expect(await (await app.request(url)).text()).toBe("rendered-after-change");+ expect(existsSync(join(project.dir, ".thumbnails"))).toBe(false);+ expect(await (await app.request(url)).text()).toBe("rendered-old");+ expect(adapter.generateThumbnail).toHaveBeenCalledTimes(2);+ });+it("keeps changed studio motion separated in the disk cache", async () => {const adapter = createAdapter();const project = await adapter.resolveProject("demo");diff --git a/packages/studio-server/src/routes/thumbnail.ts b/packages/studio-server/src/routes/thumbnail.tsindex 81ac047744..ab1a482fe7 100644--- a/packages/studio-server/src/routes/thumbnail.ts+++ b/packages/studio-server/src/routes/thumbnail.ts@@ -14,6 +14,7 @@ import { join } from "node:path";import { createHash, randomUUID } from "node:crypto";import type { StudioApiAdapter } from "../types.js";import { STUDIO_MANUAL_EDITS_PATH } from "../helpers/manualEditsRenderScript.js";+import { createProjectSignature, resolveProjectAndSignature } from "../helpers/projectSignature.js";import { STUDIO_MOTION_PATH } from "../helpers/studioMotionRenderScript.js";import { thumbnailGenerationCoordinator } from "./thumbnailGenerationCoordinator.js";@@ -78,8 +79,9 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): vif (!adapter.generateThumbnail) {return c.json({ error: "Thumbnails not available" }, 501);}- const project = await adapter.resolveProject(c.req.param("id"));- if (!project) return c.json({ error: "not found" }, 404);+ const resolved = await resolveProjectAndSignature(adapter, c.req.param("id"));+ if (!resolved) return c.json({ error: "not found" }, 404);+ const { project, signature: projectSignature } = resolved;let compPath = decodeURIComponent(c.req.path.replace(`/projects/${project.id}/thumbnail/`, "").split("?")[0] ?? "",@@ -162,6 +164,7 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): vconst urlVersionKey = urlVersion? `_${urlVersion.replace(/[^a-zA-Z0-9_-]+/g, "_").slice(0, 32)}`: "";+ const projectSignatureKey = `_${createHash("sha1").update(projectSignature).digest("hex").slice(0, 16)}`;const outputScale =outputMode === "source"? 1@@ -174,7 +177,7 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): v: Math.min(1, THUMBNAIL_MAX_OUTPUT_WIDTH / compW, THUMBNAIL_MAX_OUTPUT_HEIGHT / compH);const outputWidth = Math.max(1, Math.round(compW * outputScale));const outputHeight = Math.max(1, Math.round(compH * outputScale));- const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${outputMode}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${outputWidth}x${outputHeight}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;+ const cacheKey = `${THUMBNAIL_CACHE_VERSION}${urlVersionKey}${projectSignatureKey}${manualEditsKey}${motionKey}${sourceKey}_${format}_${outputMode}_${compPath.replace(/\//g, "_")}_${compW}x${compH}_${outputWidth}x${outputHeight}_${sourceMtime}_${seekTime.toFixed(2)}${selectorKey}.${format === "png" ? "png" : "jpg"}`;const cachePath = join(cacheDir, cacheKey);if (!prunedCacheDirs.has(cacheDir)) {prunedCacheDirs.add(cacheDir);@@ -209,6 +212,19 @@ export function registerThumbnailRoutes(api: Hono, adapter: StudioApiAdapter): vsignal,});if (!generated) return null;+ const afterGeneration = await resolveProjectAndSignature(adapter, project.id);+ const freshSignature = createProjectSignature(project.dir);+ if (+ !afterGeneration ||+ afterGeneration.project.dir !== project.dir ||+ afterGeneration.signature !== projectSignature ||+ freshSignature !== projectSignature+ ) {+ // The browser may have rendered content written after this request+ // captured its cache identity. Return the pixels to this caller,+ // but never file them under a signature they do not prove.+ return generated;+ }if (!existsSync(cacheDir)) mkdirSync(cacheDir, { recursive: true });writeThumbnailAtomically(cachePath, generated);return generated;diff --git a/packages/studio/.gitignore b/packages/studio/.gitignoreindex 9012af4f97..b3fcb6c57a 100644--- a/packages/studio/.gitignore+++ b/packages/studio/.gitignore@@ -1,3 +1,4 @@dist/node_modules/data/projects/+tests/e2e/evidence/diff --git a/packages/studio/package.json b/packages/studio/package.jsonindex f20937b136..6e9172fcf2 100644--- a/packages/studio/package.json+++ b/packages/studio/package.json@@ -49,6 +49,7 @@"build": "vite build && tsup","typecheck": "tsc --noEmit","test": "vitest run",+ "test:webmcp-edit-loop": "node tests/e2e/webmcp-edit-loop.mjs","test:timeline-virtualization": "TIMELINE_ROW_VIRTUALIZATION=on TIMELINE_ELEMENT_COUNT=50000 node tests/e2e/timeline-virtualization.mjs","test:watch": "vitest","report:sdk-cutover": "bun src/utils/sdkCutoverPolicy.report.ts",diff --git a/packages/studio/src/components/editor/TopologyLens.test.tsx b/packages/studio/src/components/editor/TopologyLens.test.tsxnew file mode 100644index 0000000000..54b7cb44b7--- /dev/null+++ b/packages/studio/src/components/editor/TopologyLens.test.tsx@@ -0,0 +1,294 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { studioEditLifecycle, type StudioWriteResult } from "../../webmcp/writeCoordinator";+import { TopologyLens } from "./TopologyLens";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const geometryMock = vi.hoisted(() => ({ measure: vi.fn() }));+vi.mock("./topologyLensGeometry", () => ({+ measureTopologyLensGeometry: geometryMock.measure,+}));++const target = { handle: "dom:target", sourceFile: "index.html" };+let root: Root | null = null;+let host: HTMLDivElement | null = null;+let iframe: HTMLIFrameElement | null = null;++function matchMedia(reducedMotion: boolean): typeof window.matchMedia {+ return vi.fn().mockReturnValue({+ matches: reducedMotion,+ media: "(prefers-reduced-motion: reduce)",+ onchange: null,+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ addListener: vi.fn(),+ removeListener: vi.fn(),+ dispatchEvent: vi.fn(),+ });+}++function mount(reducedMotion = false, strictMode = false): void {+ window.matchMedia = matchMedia(reducedMotion);+ host = document.createElement("div");+ iframe = document.createElement("iframe");+ document.body.append(host, iframe);+ root = createRoot(host);+ act(() => {+ const lens = (+ <TopologyLens iframeRef={{ current: iframe }} activeCompositionPath="index.html" />+ );+ root?.render(strictMode ? <React.StrictMode>{lens}</React.StrictMode> : lens);+ });+}++function begin(): string {+ let callId = "";+ act(() => {+ callId = studioEditLifecycle.begin("project-a", target, "set-text");+ });+ return callId;+}++function finish(+ callId: string,+ stage: "dispatched" | "saved" | "verified" | "failed",+ changed = true,+): void {+ const result: StudioWriteResult<object> =+ stage === "failed"+ ? {+ ok: false,+ kind: "failed",+ reason: "save failed",+ stage,+ target,+ operation: "set-text",+ }+ : {+ ok: true,+ stage,+ target,+ operation: "set-text",+ changed,+ evidence:+ stage === "dispatched"+ ? { kind: "dispatch", followUp: "studio_inspect" }+ : { kind: "content-version", sourceFile: "index.html", version: "v1" },+ };+ act(() => studioEditLifecycle.finish(callId, result));+}++beforeEach(() => {+ vi.useFakeTimers();+ geometryMock.measure.mockReset().mockReturnValue({+ field: {+ label: "section",+ rect: { left: 5, top: 10, width: 320, height: 180, editScaleX: 1, editScaleY: 1 },+ },+ target: {+ label: "h1",+ rect: { left: 10, top: 20, width: 200, height: 100, editScaleX: 1, editScaleY: 1 },+ },+ contours: [+ {+ label: "p",+ rect: { left: 20, top: 30, width: 80, height: 20, editScaleX: 1, editScaleY: 1 },+ },+ {+ label: "aside",+ rect: { left: 110, top: 30, width: 60, height: 50, editScaleX: 1, editScaleY: 1 },+ },+ ],+ });+});++afterEach(() => {+ if (root) act(() => root?.unmount());+ act(() => vi.runOnlyPendingTimers());+ root = null;+ host = null;+ iframe = null;+ studioEditLifecycle.reset();+ document.body.replaceChildren();+ vi.useRealTimers();+});++describe("TopologyLens", () => {+ it("reveals real contours for a new target and seals only a durable receipt", () => {+ mount();+ const callId = begin();++ expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();+ expect(+ host?.querySelector('[data-topology-field="true"][data-topology-node="section"]'),+ ).not.toBeNull();+ expect(host?.querySelector('[data-topology-target][data-topology-node="h1"]')).not.toBeNull();+ expect(host?.querySelectorAll('[data-topology-contour="true"]')).toHaveLength(2);+ expect(+ [...(host?.querySelectorAll<HTMLElement>("[data-topology-contour]") ?? [])].map(+ (element) => element.dataset.topologyNode,+ ),+ ).toEqual(["p", "aside"]);+ expect(host?.querySelector('[data-topology-scan="true"]')).not.toBeNull();++ finish(callId, "saved");+ expect(host?.querySelector('[data-topology-lens="sealing"]')).not.toBeNull();+ expect(+ host+ ?.querySelector('[data-topology-field][data-topology-phase="sealing"]')+ ?.querySelector('[data-topology-seal="saved"]'),+ ).not.toBeNull();+ expect(host?.querySelector("[data-topology-target] [data-topology-seal]")).toBeNull();+ expect(geometryMock.measure).toHaveBeenCalledTimes(2);++ act(() => vi.advanceTimersByTime(240));+ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });+ });++ it("remeasures the post-write target before drawing the persistence seal", () => {+ geometryMock.measure+ .mockReturnValueOnce({+ field: {+ label: "section",+ rect: { left: 5, top: 10, width: 300, height: 180, editScaleX: 1, editScaleY: 1 },+ },+ target: {+ label: "h1",+ rect: { left: 10, top: 20, width: 200, height: 100, editScaleX: 1, editScaleY: 1 },+ },+ contours: [],+ })+ .mockReturnValueOnce({+ field: {+ label: "section",+ rect: { left: 50, top: 20, width: 360, height: 220, editScaleX: 1, editScaleY: 1 },+ },+ target: {+ label: "h1",+ rect: { left: 70, top: 40, width: 240, height: 120, editScaleX: 1, editScaleY: 1 },+ },+ contours: [],+ });+ mount();+ const callId = begin();+ expect(host?.querySelector<HTMLElement>("[data-topology-target]")?.style.left).toBe("10px");++ finish(callId, "verified");++ const sealedTarget = host?.querySelector<HTMLElement>("[data-topology-target]");+ expect(sealedTarget?.style.left).toBe("70px");+ expect(sealedTarget?.style.width).toBe("240px");+ expect(host?.querySelector('[data-topology-seal="verified"]')).not.toBeNull();+ });++ it("skips acquisition when the coordinator identifies a repeated target", () => {+ mount();+ const firstCall = begin();+ finish(firstCall, "saved");+ act(() => vi.advanceTimersByTime(240));++ begin();++ expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();+ expect(host?.querySelector('[data-topology-contour="true"]')).toBeNull();+ });++ it.each(["dispatched", "failed"] as const)("retracts %s without a seal", (stage) => {+ mount();+ const callId = begin();++ finish(callId, stage);++ expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();+ expect(host?.querySelector("[data-topology-seal]")).toBeNull();+ act(() => vi.advanceTimersByTime(180));+ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });+ });++ it.each(["saved", "verified"] as const)("retracts a %s no-op without a seal", (stage) => {+ mount();+ const callId = begin();++ finish(callId, stage, false);++ expect(host?.querySelector('[data-topology-lens="localizing"]')).not.toBeNull();+ expect(host?.querySelector('[data-topology-terminal="no-change"]')).not.toBeNull();+ expect(host?.querySelector("[data-topology-seal]")).toBeNull();+ act(() => vi.advanceTimersByTime(180));+ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();+ });++ it("does not replay a terminal seal after the overlay remounts", () => {+ mount();+ const callId = begin();+ finish(callId, "saved");+ act(() => vi.advanceTimersByTime(240));+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });++ act(() => root?.unmount());+ root = null;+ host?.remove();+ iframe?.remove();+ mount();++ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();+ expect(host?.querySelector("[data-topology-seal]")).toBeNull();+ });++ it("keeps an active invocation through StrictMode effect replay", () => {+ const callId = begin();++ mount(false, true);+ act(() => vi.advanceTimersByTime(0));++ expect(studioEditLifecycle.getSnapshot()).toMatchObject({+ callId,+ phase: "dispatching",+ });+ expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();+ });++ it("clears on iframe reload and project switch", () => {+ mount();+ begin();++ act(() => iframe?.dispatchEvent(new Event("load")));+ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();++ begin();+ act(() => studioEditLifecycle.activateProject("project-b"));+ expect(host?.querySelector('[data-topology-lens="hidden"]')).not.toBeNull();+ });++ it("removes spatial travel in reduced motion while preserving target state", () => {+ mount(true);+ begin();++ expect(host?.querySelector('[data-topology-lens="acquiring"]')).not.toBeNull();+ expect(host?.querySelector('[data-topology-contour="true"]')).not.toBeNull();+ expect(host?.querySelector('[data-topology-scan="true"]')).toBeNull();+ });++ it("cleans its timer and iframe listener on unmount", () => {+ mount();+ const removeListener = vi.spyOn(iframe!, "removeEventListener");+ begin();+ expect(vi.getTimerCount()).toBe(1);++ act(() => root?.unmount());+ root = null;++ expect(vi.getTimerCount()).toBe(1);+ expect(removeListener).toHaveBeenCalledWith("load", expect.any(Function));+ expect(studioEditLifecycle.getSnapshot()).toMatchObject({ phase: "dispatching" });+ act(() => vi.advanceTimersByTime(0));+ expect(vi.getTimerCount()).toBe(0);+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });+ });+});diff --git a/packages/studio/src/components/editor/TopologyLens.tsx b/packages/studio/src/components/editor/TopologyLens.tsxnew file mode 100644index 0000000000..bb0b1503d6--- /dev/null+++ b/packages/studio/src/components/editor/TopologyLens.tsx@@ -0,0 +1,206 @@+import {+ useEffect,+ useLayoutEffect,+ useReducer,+ useRef,+ useState,+ useSyncExternalStore,+ type CSSProperties,+ type RefObject,+} from "react";+import { studioEditLifecycle } from "../../webmcp/writeCoordinator";+import { HyperframesMark } from "../ui/HyperframesMark";+import { measureTopologyLensGeometry, type TopologyLensGeometry } from "./topologyLensGeometry";+import { reduceTopologyLens, type TopologyLensState } from "./topologyLensState";++const ACQUISITION_MS = 240;+const TERMINAL_RETRACT_MS = 180;+const SEAL_MS = 240;++interface TopologyLensProps {+ iframeRef: RefObject<HTMLIFrameElement | null>;+ activeCompositionPath: string | null;+}++interface MeasuredLens {+ callId: string;+ geometry: TopologyLensGeometry;+}++function rectStyle(rect: TopologyLensGeometry["target"]["rect"]): CSSProperties {+ return { left: rect.left, top: rect.top, width: rect.width, height: rect.height };+}++function getReducedMotion(): boolean {+ return window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;+}++function subscribeReducedMotion(listener: () => void): () => void {+ const query = window.matchMedia?.("(prefers-reduced-motion: reduce)");+ if (!query) return () => undefined;+ query.addEventListener("change", listener);+ return () => query.removeEventListener("change", listener);+}++function useTopologyLensState(): TopologyLensState {+ const lifecycle = useSyncExternalStore(+ studioEditLifecycle.subscribe,+ studioEditLifecycle.getSnapshot,+ studioEditLifecycle.getSnapshot,+ );+ const [state, dispatch] = useReducer(+ reduceTopologyLens,+ lifecycle,+ (initialLifecycle): TopologyLensState =>+ reduceTopologyLens({ phase: "hidden" }, { type: "lifecycle", value: initialLifecycle }),+ );++ useEffect(() => dispatch({ type: "lifecycle", value: lifecycle }), [lifecycle]);+ useEffect(() => {+ if (state.phase === "hidden") return;+ const delay =+ state.phase === "acquiring"+ ? ACQUISITION_MS+ : state.phase === "sealing"+ ? SEAL_MS+ : state.terminal+ ? TERMINAL_RETRACT_MS+ : null;+ if (delay === null) return;+ const timeout = window.setTimeout(() => {+ if (state.phase === "acquiring") {+ dispatch({ type: "acquisition-elapsed", callId: state.callId });+ return;+ }+ studioEditLifecycle.dismiss(state.callId);+ }, delay);+ return () => window.clearTimeout(timeout);+ }, [state]);++ return state;+}++/** Studio-parent chrome driven by the same invocation and receipt as WebMCP. */+export function TopologyLens({ iframeRef, activeCompositionPath }: TopologyLensProps) {+ const overlayRef = useRef<HTMLDivElement | null>(null);+ const state = useTopologyLensState();+ const reducedMotion = useSyncExternalStore(subscribeReducedMotion, getReducedMotion, () => false);+ const [measured, setMeasured] = useState<MeasuredLens | null>(null);+ const callId = state.phase === "hidden" ? null : state.callId;+ const handle = state.phase === "hidden" ? null : state.target.handle;+ const phase = state.phase;+ const ownedCallIdRef = useRef(callId);+ const pendingUnmountDismissRef = useRef<number | null>(null);+ ownedCallIdRef.current = callId;++ useLayoutEffect(() => {+ if (!callId || !handle) {+ setMeasured(null);+ return;+ }+ const overlay = overlayRef.current;+ const iframe = iframeRef.current;+ if (!overlay || !iframe) {+ setMeasured(null);+ return;+ }+ const geometry = measureTopologyLensGeometry({+ overlay,+ iframe,+ activeCompositionPath,+ handle,+ });+ setMeasured(geometry ? { callId, geometry } : null);+ }, [activeCompositionPath, callId, handle, iframeRef, phase]);++ useEffect(() => {+ const iframe = iframeRef.current;+ if (!iframe || !callId) return;+ const dismiss = () => studioEditLifecycle.dismiss(callId);+ iframe.addEventListener("load", dismiss);+ return () => iframe.removeEventListener("load", dismiss);+ }, [callId, iframeRef]);++ useEffect(() => {+ if (pendingUnmountDismissRef.current !== null) {+ window.clearTimeout(pendingUnmountDismissRef.current);+ pendingUnmountDismissRef.current = null;+ }+ return () => {+ const ownedCallId = ownedCallIdRef.current;+ if (!ownedCallId) return;+ pendingUnmountDismissRef.current = window.setTimeout(() => {+ pendingUnmountDismissRef.current = null;+ studioEditLifecycle.dismiss(ownedCallId);+ }, 0);+ };+ }, []);++ const geometry = measured?.callId === callId ? measured.geometry : null;+ const visible = state.phase !== "hidden" && geometry;+ return (+ <div+ ref={overlayRef}+ aria-hidden="true"+ data-topology-lens={visible ? state.phase : "hidden"}+ className="pointer-events-none absolute inset-0 z-[58] overflow-hidden"+ >+ {visible && (+ <>+ {(state.phase === "acquiring" || state.phase === "sealing") && (+ <div+ data-topology-field="true"+ data-topology-node={geometry.field.label}+ data-topology-phase={state.phase}+ className="hf-topology-field pointer-events-none absolute overflow-hidden rounded-md"+ style={rectStyle(geometry.field.rect)}+ >+ {state.phase === "sealing" && (+ <HyperframesMark+ data-topology-seal={state.receiptStage}+ className="hf-topology-seal absolute right-2 top-2 h-7 w-11 overflow-visible"+ viewBox="0 18 100 64"+ />+ )}+ </div>+ )}+ {(state.phase === "acquiring" || state.phase === "sealing") && (+ <>+ {geometry.contours.map(({ label, rect }, index) => (+ <div+ key={index}+ data-topology-contour="true"+ data-topology-node={label}+ className="hf-topology-contour pointer-events-none absolute z-[1] rounded"+ style={{+ ...rectStyle(rect),+ animationDelay: `${Math.min(index, 5) * 28}ms`,+ }}+ />+ ))}+ {!reducedMotion && (+ <div+ data-topology-scan="true"+ className="pointer-events-none absolute z-[2] overflow-hidden rounded"+ style={rectStyle(geometry.field.rect)}+ >+ <div className="hf-topology-scan absolute inset-y-0 left-0 w-1/4" />+ </div>+ )}+ </>+ )}+ <div+ data-topology-target="true"+ data-topology-node={geometry.target.label}+ data-topology-phase={state.phase}+ data-topology-terminal={+ state.phase === "localizing" ? (state.terminal ?? undefined) : undefined+ }+ className="hf-topology-target pointer-events-none absolute z-[3] rounded-md"+ style={rectStyle(geometry.target.rect)}+ />+ </>+ )}+ </div>+ );+}diff --git a/packages/studio/src/components/editor/domEditOverlayGeometry.ts b/packages/studio/src/components/editor/domEditOverlayGeometry.tsindex 95535d5317..b45b0ff460 100644--- a/packages/studio/src/components/editor/domEditOverlayGeometry.ts+++ b/packages/studio/src/components/editor/domEditOverlayGeometry.ts@@ -107,6 +107,20 @@ export function toVisibleOverlayRect(return rect ? { ...rect, ...hugRectForElement(rect, element) } : null;}+/** Batch transient chrome through one shared iframe-to-overlay coordinate basis. */+export function toVisibleOverlayRects(+ overlayEl: HTMLDivElement,+ iframe: HTMLIFrameElement,+ elements: readonly HTMLElement[],+): Array<OverlayRect | null> {+ const scale = computeOverlayRootScale(overlayEl, iframe, iframe.contentDocument);+ if (!scale) return elements.map(() => null);+ return elements.map((element) => {+ const rect = toOverlayRect(overlayEl, iframe, element, scale);+ return rect ? { ...rect, ...hugRectForElement(rect, element) } : null;+ });+}+/*** getComputedStyle(element).transform decomposed into a DOMMatrix, read ONCE.* Shared by orientedOverlayRect's rotation gate and elementCornerOverlayPointsdiff --git a/packages/studio/src/components/editor/domEditOverlayGeometryBatch.test.ts b/packages/studio/src/components/editor/domEditOverlayGeometryBatch.test.tsnew file mode 100644index 0000000000..f7136636b9--- /dev/null+++ b/packages/studio/src/components/editor/domEditOverlayGeometryBatch.test.ts@@ -0,0 +1,18 @@+// @vitest-environment happy-dom++import { expect, it, vi } from "vitest";+import { toVisibleOverlayRects } from "./domEditOverlayGeometry";++it("does not fall back to per-element basis reads when the shared basis is unavailable", () => {+ const overlay = document.createElement("div");+ const iframe = document.createElement("iframe");+ document.body.append(overlay, iframe);+ const doc = iframe.contentDocument;+ if (!doc) throw new Error("expected iframe document");+ doc.body.innerHTML = '<main data-composition-id="root"><div id="target"></div></main>';+ const target = doc.getElementById("target") as HTMLElement;+ const targetRead = vi.spyOn(target, "getBoundingClientRect");++ expect(toVisibleOverlayRects(overlay, iframe, [target])).toEqual([null]);+ expect(targetRead).not.toHaveBeenCalled();+});diff --git a/packages/studio/src/components/editor/domEditingLayers.test.ts b/packages/studio/src/components/editor/domEditingLayers.test.tsindex c0e972dffd..e5bb830704 100644--- a/packages/studio/src/components/editor/domEditingLayers.test.ts+++ b/packages/studio/src/components/editor/domEditingLayers.test.ts@@ -126,6 +126,15 @@ describe("resolveDomEditSelection — data-hf-group capture", () => {expect(selection?.selector).toBe('[data-hf-group="Group 1"]');});+ it("resolves an explicit agent target without promoting it to the group", async () => {+ const { parent, child } = buildNestedGroups();+ const selection = await resolveDomEditSelection(child, { ...opts, exactTarget: true });+ document.body.removeChild(parent);++ expect(selection?.element).toBe(child);+ expect(selection?.id).toBe("child");+ });+it("selects the next nested group when drilled into the outer group", async () => {const { parent, outer, inner, child } = buildNestedGroups();const selection = await resolveDomEditSelection(child, { ...opts, activeGroupElement: outer });diff --git a/packages/studio/src/components/editor/domEditingLayers.ts b/packages/studio/src/components/editor/domEditingLayers.tsindex b1af3fb61e..3b24e2ec98 100644--- a/packages/studio/src/components/editor/domEditingLayers.ts+++ b/packages/studio/src/components/editor/domEditingLayers.ts@@ -281,10 +281,6 @@ export function resolveDomEditCapabilities(args: {).capabilities;}-// ─── Element label ────────────────────────────────────────────────────────────--// ─── Source probe ────────────────────────────────────────────────────────────-async function probeSourceElement(projectId: string,sourceFile: string,@@ -310,17 +306,21 @@ async function probeSourceElement(}}-// ─── Selection resolution ────────────────────────────────────────────────────-// fallow-ignore-next-line complexityexport async function resolveDomEditSelection(startEl: HTMLElement | null,- options: DomEditContextOptions & { projectId?: string | null; skipSourceProbe?: boolean },+ options: DomEditContextOptions & {+ projectId?: string | null;+ skipSourceProbe?: boolean;+ exactTarget?: boolean;+ },): Promise<DomEditSelection | null> {if (!startEl) return null;const doc = startEl.ownerDocument;- let capture = resolveGroupCapture(startEl, options.activeGroupElement ?? null);+ let capture = options.exactTarget+ ? ({ kind: "unit", element: startEl } as const)+ : resolveGroupCapture(startEl, options.activeGroupElement ?? null);if (capture.kind === "out-of-scope") {// Drill-in is non-sticky: clicking/hovering OUTSIDE the drilled-into group// exits it and resolves the target normally, rather than selecting nothingdiff --git a/packages/studio/src/components/editor/topologyLensGeometry.test.ts b/packages/studio/src/components/editor/topologyLensGeometry.test.tsnew file mode 100644index 0000000000..15a7d22080--- /dev/null+++ b/packages/studio/src/components/editor/topologyLensGeometry.test.ts@@ -0,0 +1,44 @@+// @vitest-environment jsdom++import { describe, expect, it } from "vitest";+import { mintElementHandle } from "../../webmcp/handles";+import { previewDoc } from "../../webmcp/webmcpTestUtils";+import { resolveTopologyLensElements } from "./topologyLensGeometry";++describe("Topology Lens scene geometry", () => {+ it("reveals the nearest same-source context while preserving the exact target", () => {+ const doc = previewDoc(`+ <main data-composition-id="root" data-composition-file="index.html">+ <section id="duplicate"><span id="root-child">root</span></section>+ <section data-composition-id="nested" data-composition-file="compositions/nested.html">+ <article id="nested-context">+ <div id="duplicate"><strong id="nested-child">nested</strong></div>+ <aside id="unrelated">outside target</aside>+ </article>+ </section>+ </main>+ `);+ const handle = mintElementHandle({+ domId: "duplicate",+ sourceFile: "compositions/nested.html",+ activeCompositionPath: "index.html",+ });+ if (!handle) throw new Error("expected source-safe handle");++ const resolved = resolveTopologyLensElements(doc, "index.html", handle);++ expect(resolved?.target.textContent).toBe("nested");+ expect(resolved?.context.getAttribute("data-composition-file")).toBe(+ "compositions/nested.html",+ );+ expect(resolved?.contours.map((element) => element.id)).toEqual(["nested-child", "unrelated"]);+ });++ it("returns no geometry for a stale handle", () => {+ const doc = previewDoc(+ '<main data-composition-id="root" data-composition-file="index.html"></main>',+ );++ expect(resolveTopologyLensElements(doc, "index.html", "dom:missing")).toBeNull();+ });+});diff --git a/packages/studio/src/components/editor/topologyLensGeometry.ts b/packages/studio/src/components/editor/topologyLensGeometry.tsnew file mode 100644index 0000000000..751e8676be--- /dev/null+++ b/packages/studio/src/components/editor/topologyLensGeometry.ts@@ -0,0 +1,119 @@+import { resolveElementHandle } from "../../webmcp/handles";+import { collectStudioLookScene } from "../../webmcp/tools/lookTools";+import type { DomEditLayerItem } from "./domEditingTypes";+import { toVisibleOverlayRects, type OverlayRect } from "./domEditOverlayGeometry";++export interface TopologyLensNode {+ label: string;+ rect: OverlayRect;+}++export interface TopologyLensGeometry {+ field: TopologyLensNode;+ target: TopologyLensNode;+ contours: TopologyLensNode[];+}++function findSourceContextIndex(items: readonly DomEditLayerItem[], targetIndex: number): number {+ const target = items[targetIndex]!;+ let contextIndex = targetIndex;+ let parentDepth = target.depth - 1;+ for (let index = targetIndex - 1; index >= 0 && parentDepth >= 0; index--) {+ const item = items[index]!;+ if (item.depth !== parentDepth) continue;+ if (item.sourceFile !== target.sourceFile) break;+ contextIndex = index;+ parentDepth -= 1;+ }+ return contextIndex;+}++function collectSourceContours(+ items: readonly DomEditLayerItem[],+ contextIndex: number,+ target: DomEditLayerItem,+): HTMLElement[] {+ const context = items[contextIndex]!;+ const contours: HTMLElement[] = [];+ for (let index = contextIndex + 1; index < items.length; index++) {+ const item = items[index]!;+ if (item.depth <= context.depth) break;+ if (item.sourceFile === target.sourceFile && item.element !== target.element) {+ contours.push(item.element);+ }+ }+ return contours;+}++/**+ * Resolve the same nested preorder used by studio_look. This keeps the lens on+ * the agent's source-safe scene model instead of guessing hierarchy from an+ * unrelated presentation selector.+ */+export function resolveTopologyLensElements(+ doc: Document,+ activeCompositionPath: string | null,+ handle: string,+): { context: HTMLElement; target: HTMLElement; contours: HTMLElement[] } | null {+ const target = resolveElementHandle(doc, handle);+ if (!target) return null;+ const scene = collectStudioLookScene(doc, activeCompositionPath, null);+ if (scene.status === "loading") return null;+ const targetIndex = scene.items.findIndex((item) => item.element === target);+ if (targetIndex < 0) return { context: target, target, contours: [] };++ const targetItem = scene.items[targetIndex]!;+ const contextIndex = findSourceContextIndex(scene.items, targetIndex);+ const contextItem = scene.items[contextIndex]!;+ const sourceContext = target.closest<HTMLElement>(+ "[data-composition-file], [data-composition-src]",+ );+ return {+ context: sourceContext ?? contextItem.element,+ target,+ contours: collectSourceContours(scene.items, contextIndex, targetItem),+ };+}++function isRenderableRect(rect: OverlayRect | null | undefined): rect is OverlayRect {+ return Boolean(rect && rect.width > 0 && rect.height > 0);+}++export function measureTopologyLensGeometry(input: {+ overlay: HTMLDivElement;+ iframe: HTMLIFrameElement;+ activeCompositionPath: string | null;+ handle: string;+}): TopologyLensGeometry | null {+ const doc = input.iframe.contentDocument;+ if (!doc) return null;+ const elements = resolveTopologyLensElements(doc, input.activeCompositionPath, input.handle);+ if (!elements) return null;+ const sharedField = elements.context === elements.target;+ const measured = toVisibleOverlayRects(+ input.overlay,+ input.iframe,+ sharedField+ ? [elements.target, ...elements.contours]+ : [elements.context, elements.target, ...elements.contours],+ );+ const target = measured[sharedField ? 0 : 1];+ if (!isRenderableRect(target)) return null;+ const measuredField = measured[0];+ const fieldUsesContext = !sharedField && isRenderableRect(measuredField);+ const contourOffset = sharedField ? 1 : 2;+ return {+ field: {+ label: (fieldUsesContext ? elements.context : elements.target).tagName.toLowerCase(),+ rect: fieldUsesContext ? measuredField : target,+ },+ target: { label: elements.target.tagName.toLowerCase(), rect: target },+ contours: measured+ .slice(contourOffset)+ .map((rect, index) => ({+ label: elements.contours[index]!.tagName.toLowerCase(),+ rect,+ }))+ .filter((item): item is TopologyLensNode => isRenderableRect(item.rect)),+ };+}diff --git a/packages/studio/src/components/editor/topologyLensState.test.ts b/packages/studio/src/components/editor/topologyLensState.test.tsnew file mode 100644index 0000000000..95c6a59119--- /dev/null+++ b/packages/studio/src/components/editor/topologyLensState.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";+import { reduceTopologyLens, type TopologyLensState } from "./topologyLensState";+import type { StudioEditLifecycleState } from "../../webmcp/writeCoordinator";++const targetA = { handle: "dom:v1:index.html:index.html:target-a", sourceFile: "index.html" };+const targetB = { handle: "dom:v1:index.html:index.html:target-b", sourceFile: "index.html" };++function lifecycle(+ overrides: Partial<Exclude<StudioEditLifecycleState, { phase: "idle" }>> = {},+): Exclude<StudioEditLifecycleState, { phase: "idle" }> {+ return {+ callId: "call-a",+ projectId: "project-a",+ target: targetA,+ operation: "set-text",+ targetChanged: true,+ phase: "dispatching",+ ...overrides,+ };+}++function hidden(): TopologyLensState {+ return { phase: "hidden" };+}++describe("Topology Lens state", () => {+ it("reveals a new target but localizes a repeated target immediately", () => {+ expect(reduceTopologyLens(hidden(), { type: "lifecycle", value: lifecycle() })).toMatchObject({+ phase: "acquiring",+ callId: "call-a",+ });+ expect(+ reduceTopologyLens(hidden(), {+ type: "lifecycle",+ value: lifecycle({ callId: "call-repeat", targetChanged: false }),+ }),+ ).toMatchObject({ phase: "localizing", callId: "call-repeat" });+ });++ it("lets a fast durable receipt interrupt acquisition and seal once", () => {+ const acquiring = reduceTopologyLens(hidden(), { type: "lifecycle", value: lifecycle() });+ const sealing = reduceTopologyLens(acquiring, {+ type: "lifecycle",+ value: lifecycle({ phase: "verified" }),+ });++ expect(sealing).toMatchObject({ phase: "sealing", receiptStage: "verified" });+ expect(reduceTopologyLens(sealing, { type: "lifecycle", value: { phase: "idle" } })).toEqual(+ hidden(),+ );+ });++ it.each(["dispatched", "failed"] as const)(+ "retracts %s without manufacturing a success seal",+ (phase) => {+ const localizing = reduceTopologyLens(hidden(), {+ type: "lifecycle",+ value: lifecycle({ phase }),+ });++ expect(localizing).toMatchObject({ phase: "localizing", terminal: phase });+ expect(+ reduceTopologyLens(localizing, { type: "lifecycle", value: { phase: "idle" } }),+ ).toEqual(hidden());+ },+ );++ it.each(["saved", "verified"] as const)(+ "retracts a %s no-op without manufacturing a success seal",+ (phase) => {+ const noChange = reduceTopologyLens(hidden(), {+ type: "lifecycle",+ value: lifecycle({+ phase,+ receipt: {+ ok: true,+ stage: phase,+ target: targetA,+ operation: "set-text",+ changed: false,+ evidence: { kind: "content-version", sourceFile: "index.html", version: "v1" },+ },+ }),+ });++ expect(noChange).toMatchObject({ phase: "localizing", terminal: "no-change" });+ },+ );++ it("ignores elapsed events owned by an older invocation", () => {+ const newer = reduceTopologyLens(hidden(), {+ type: "lifecycle",+ value: lifecycle({ callId: "call-b", target: targetB }),+ });++ expect(reduceTopologyLens(newer, { type: "acquisition-elapsed", callId: "call-a" })).toBe(+ newer,+ );+ });++ it("clears when the coordinator publishes idle", () => {+ const acquiring = reduceTopologyLens(hidden(), { type: "lifecycle", value: lifecycle() });++ expect(reduceTopologyLens(acquiring, { type: "lifecycle", value: { phase: "idle" } })).toEqual(+ hidden(),+ );+ });++ it("advances acquisition to localization only for the same visual invocation", () => {+ const acquiring = reduceTopologyLens(hidden(), { type: "lifecycle", value: lifecycle() });++ expect(+ reduceTopologyLens(acquiring, { type: "acquisition-elapsed", callId: "call-a" }),+ ).toMatchObject({ phase: "localizing", terminal: null });+ });+});diff --git a/packages/studio/src/components/editor/topologyLensState.ts b/packages/studio/src/components/editor/topologyLensState.tsnew file mode 100644index 0000000000..0cafc6a88b--- /dev/null+++ b/packages/studio/src/components/editor/topologyLensState.ts@@ -0,0 +1,72 @@+import type {+ StudioEditLifecycleState,+ StudioWriteOperation,+ StudioWriteTarget,+} from "../../webmcp/writeCoordinator";++type TopologyLensBase = {+ callId: string;+ projectId: string;+ target: StudioWriteTarget;+ operation: StudioWriteOperation;+};++export type TopologyLensState =+ | { phase: "hidden" }+ | (TopologyLensBase & { phase: "acquiring" })+ | (TopologyLensBase & {+ phase: "localizing";+ terminal: "dispatched" | "failed" | "no-change" | null;+ })+ | (TopologyLensBase & {+ phase: "sealing";+ receiptStage: "saved" | "verified";+ });++export type TopologyLensEvent =+ | { type: "lifecycle"; value: StudioEditLifecycleState }+ | { type: "acquisition-elapsed"; callId: string };++function visibleBase(+ value: Exclude<StudioEditLifecycleState, { phase: "idle" }>,+): TopologyLensBase {+ return {+ callId: value.callId,+ projectId: value.projectId,+ target: value.target,+ operation: value.operation,+ };+}++/**+ * Presentation follows transaction facts. Elapsed events may finish a visual+ * transition, but cannot promote a receipt or invent persistence.+ */+export function reduceTopologyLens(+ state: TopologyLensState,+ event: TopologyLensEvent,+): TopologyLensState {+ if (event.type === "lifecycle") {+ const lifecycle = event.value;+ if (lifecycle.phase === "idle") return { phase: "hidden" };+ const base = visibleBase(lifecycle);+ switch (lifecycle.phase) {+ case "dispatching":+ return lifecycle.targetChanged+ ? { ...base, phase: "acquiring" }+ : { ...base, phase: "localizing", terminal: null };+ case "dispatched":+ case "failed":+ return { ...base, phase: "localizing", terminal: lifecycle.phase };+ case "saved":+ case "verified":+ if (lifecycle.receipt?.ok && lifecycle.receipt.changed === false) {+ return { ...base, phase: "localizing", terminal: "no-change" };+ }+ return { ...base, phase: "sealing", receiptStage: lifecycle.phase };+ }+ }++ if (state.phase === "hidden" || state.callId !== event.callId) return state;+ return state.phase === "acquiring" ? { ...state, phase: "localizing", terminal: null } : state;+}diff --git a/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx b/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsxnew file mode 100644index 0000000000..1b80925bcb--- /dev/null+++ b/packages/studio/src/components/nle/PreviewOverlays.topologyLens.test.tsx@@ -0,0 +1,126 @@+// @vitest-environment happy-dom++import React, { act } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import { PreviewOverlays } from "./PreviewOverlays";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++const previewState = vi.hoisted(() => ({ captionEditMode: false }));+const iframeRef = { current: null as HTMLIFrameElement | null };++vi.mock("../../contexts/StudioContext", () => ({+ useStudioShellContext: () => ({ activeCompPath: "index.html", previewIframeRef: iframeRef }),+ useStudioPlaybackContext: () => ({+ captionEditMode: previewState.captionEditMode,+ compositionLoading: false,+ isPlaying: false,+ }),+}));+vi.mock("../../contexts/DomEditContext", () => ({+ useDomEditSelectionContext: () => ({+ domEditHoverSelection: null,+ domEditSelection: null,+ domEditGroupSelections: [],+ }),+ useDomEditActionsContext: () => ({+ handlePreviewCanvasMouseDown: vi.fn(),+ handlePreviewCanvasPointerMove: vi.fn(),+ handlePreviewCanvasPointerLeave: vi.fn(),+ applyDomSelection: vi.fn(),+ handleBlockedDomMove: vi.fn(),+ handleDomManualDragStart: vi.fn(),+ handleDomPathOffsetCommit: vi.fn(),+ handleDomGroupPathOffsetCommit: vi.fn(),+ handleDomBoxSizeCommit: vi.fn(),+ handleDomRotationCommit: vi.fn(),+ handleDomStyleCommit: vi.fn(),+ applyMarqueeSelection: vi.fn(),+ handleDomEditElementDelete: vi.fn(),+ handleDomZIndexReorderCommit: vi.fn(),+ }),+}));+vi.mock("../../captions/store", () => {+ const state = {+ model: null,+ dismissed: false,+ syncError: null,+ clearSelection: vi.fn(),+ setDismissed: vi.fn(),+ setEditMode: vi.fn(),+ setSyncError: vi.fn(),+ };+ return {+ useCaptionStore: Object.assign(+ (selector: (value: typeof state) => unknown) => selector(state),+ { getState: () => state },+ ),+ };+});+vi.mock("../../hooks/useCompositionDimensions", () => ({+ useCompositionDimensions: () => null,+}));+vi.mock("../../utils/studioUiPreferences", () => ({ readStudioUiPreferences: () => ({}) }));+vi.mock("./useCanvasZOrderTimelineMirror", () => ({+ useCanvasZOrderTimelineMirror: () => vi.fn(),+}));+vi.mock("../editor/TopologyLens", async () => {+ const { createElement } = await import("react");+ return {+ TopologyLens: () => createElement("div", { "data-topology-host": "true" }),+ };+});+vi.mock("../../captions/components/CaptionOverlay", () => ({ CaptionOverlay: () => null }));+vi.mock("../editor/DomEditOverlay", () => ({ DomEditOverlay: () => null }));+vi.mock("../editor/MotionPathOverlay", () => ({ MotionPathOverlay: () => null }));+vi.mock("../editor/SnapToolbar", () => ({ SnapToolbar: () => null }));++let root: Root | null = null;+let host: HTMLDivElement | null = null;++function render(props: Partial<React.ComponentProps<typeof PreviewOverlays>> = {}): void {+ host = document.createElement("div");+ iframeRef.current = document.createElement("iframe");+ document.body.append(host, iframeRef.current);+ root = createRoot(host);+ act(() => {+ root?.render(+ <PreviewOverlays+ shouldShowMotionPath={false}+ shouldShowSelectedDomBounds={false}+ {...props}+ />,+ );+ });+}++afterEach(() => {+ if (root) act(() => root?.unmount());+ root = null;+ host = null;+ iframeRef.current = null;+ previewState.captionEditMode = false;+ document.body.replaceChildren();+});++describe("PreviewOverlays Topology Lens host", () => {+ it("stays in Studio chrome while a block preview covers the composition", () => {+ render({+ blockPreview: {+ id: "block-a",+ title: "Block",+ posterUrl: "poster.png",+ } as React.ComponentProps<typeof PreviewOverlays>["blockPreview"],+ });++ expect(host?.querySelector('[data-topology-host="true"]')).not.toBeNull();+ });++ it("stays independent of caption editing chrome", () => {+ previewState.captionEditMode = true;+ render();++ expect(host?.querySelector('[data-topology-host="true"]')).not.toBeNull();+ });+});diff --git a/packages/studio/src/components/nle/PreviewOverlays.tsx b/packages/studio/src/components/nle/PreviewOverlays.tsxindex bdb67a2fce..5bbbbcd6dd 100644--- a/packages/studio/src/components/nle/PreviewOverlays.tsx+++ b/packages/studio/src/components/nle/PreviewOverlays.tsx@@ -2,6 +2,7 @@ import { useCallback, useState } from "react";import { CaptionOverlay } from "../../captions/components/CaptionOverlay";import { useCaptionStore } from "../../captions/store";import { DomEditOverlay } from "../editor/DomEditOverlay";+import { TopologyLens } from "../editor/TopologyLens";import { MotionPathOverlay } from "../editor/MotionPathOverlay";import { SnapToolbar } from "../editor/SnapToolbar";import { useCompositionDimensions } from "../../hooks/useCompositionDimensions";@@ -191,30 +192,34 @@ export function PreviewOverlays({if (blockPreview) {return (- <div className="absolute inset-0 z-30 bg-black pointer-events-none">- {blockPreview.videoUrl ? (- <video- src={blockPreview.videoUrl}- autoPlay- muted- loop- playsInline- className="w-full h-full object-contain"- />- ) : blockPreview.posterUrl ? (- <img- src={blockPreview.posterUrl}- alt={blockPreview.title}- className="w-full h-full object-contain"- />- ) : null}- </div>+ <>+ <TopologyLens iframeRef={previewIframeRef} activeCompositionPath={activeCompPath} />+ <div className="absolute inset-0 z-30 bg-black pointer-events-none">+ {blockPreview.videoUrl ? (+ <video+ src={blockPreview.videoUrl}+ autoPlay+ muted+ loop+ playsInline+ className="w-full h-full object-contain"+ />+ ) : blockPreview.posterUrl ? (+ <img+ src={blockPreview.posterUrl}+ alt={blockPreview.title}+ className="w-full h-full object-contain"+ />+ ) : null}+ </div>+ </>);}if (captionEditMode) {return (<>+ <TopologyLens iframeRef={previewIframeRef} activeCompositionPath={activeCompPath} /><CaptionOverlay iframeRef={previewIframeRef} />{/* Mode indicator + explicit exit */}<div className="absolute top-2 left-1/2 -translate-x-1/2 z-[60] flex items-center gap-2 rounded-full border border-studio-accent/40 bg-black/70 px-2.5 py-1">@@ -257,6 +262,7 @@ export function PreviewOverlays({return (<>+ <TopologyLens iframeRef={previewIframeRef} activeCompositionPath={activeCompPath} /><DomEditOverlayiframeRef={previewIframeRef}activeCompositionPath={activeCompPath}diff --git a/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx b/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsxindex 862a357221..d244167b53 100644--- a/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx+++ b/packages/studio/src/components/sidebar/CompositionsTab.drag.test.tsx@@ -3,6 +3,7 @@import { act } from "react";import { createRoot, type Root } from "react-dom/client";import { afterEach, describe, expect, it, vi } from "vitest";+import { usePlayerStore } from "../../player/store/playerStore";import { TIMELINE_COMPOSITION_MIME } from "../../utils/timelineCompositionDrop";import { CompositionsTab } from "./CompositionsTab";@@ -17,6 +18,7 @@ afterEach(() => {if (root) act(() => root?.unmount());root = null;document.body.innerHTML = "";+ usePlayerStore.setState({ thumbnailContentRevision: 0 });});function mount(onSelect = vi.fn(), onAddToTimeline = vi.fn()) {@@ -59,6 +61,20 @@ describe("composition card drag", () => {expect(host.querySelector('img[src*="/thumbnail/"]')).toBeNull();});+ it("retries a failed thumbnail at the next persisted content revision", () => {+ const { host } = mount();+ const thumbnail = host.querySelector<HTMLImageElement>('img[src*="/thumbnail/"]');+ if (!thumbnail) throw new Error("composition thumbnail did not render");+ act(() => thumbnail.dispatchEvent(new Event("error")));+ expect(host.textContent).toContain("Preview unavailable");++ act(() => usePlayerStore.getState().bumpThumbnailContentRevision());++ const retry = host.querySelector<HTMLImageElement>('img[src*="/thumbnail/"]');+ expect(retry).not.toBeNull();+ expect(new URL(retry?.src ?? "").searchParams.get("revision")).toBe("1");+ });+it("mounts one live preview only after sustained hover and removes it on leave", () => {vi.useFakeTimers();const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});diff --git a/packages/studio/src/components/sidebar/CompositionsTab.tsx b/packages/studio/src/components/sidebar/CompositionsTab.tsxindex 29079d4c11..47a9e61a17 100644--- a/packages/studio/src/components/sidebar/CompositionsTab.tsx+++ b/packages/studio/src/components/sidebar/CompositionsTab.tsx@@ -1,6 +1,7 @@import { memo, useCallback, useEffect, useRef, useState } from "react";-import { setPreviewMediaMuted } from "../../player/lib/timelineIframeHelpers";import { buildCompositionThumbnailUrl } from "../../player/components/CompositionThumbnail";+import { setPreviewMediaMuted } from "../../player/lib/timelineIframeHelpers";+import { usePlayerStore } from "../../player/store/playerStore";import { TIMELINE_COMPOSITION_MIME } from "../../utils/timelineCompositionDrop";import { Tooltip } from "../ui/Tooltip";@@ -120,6 +121,7 @@ function CompCard({isRendering,lintInfo,onAddToTimeline,+ contentRevision,}: {projectId: string;comp: string;@@ -129,11 +131,12 @@ function CompCard({isRendering?: boolean;lintInfo?: { count: number; messages: string[] };onAddToTimeline?: () => void;+ contentRevision: number;}) {const [hovered, setHovered] = useState(false);const [stageSize, setStageSize] = useState(DEFAULT_PREVIEW_STAGE);const [livePreviewLoaded, setLivePreviewLoaded] = useState(false);- const [thumbnailFailed, setThumbnailFailed] = useState(false);+ const [failedThumbnailUrl, setFailedThumbnailUrl] = useState<string | null>(null);const iframeRef = useRef<HTMLIFrameElement | null>(null);const hoverTimer = useRef<ReturnType<typeof setTimeout> | null>(null);const syncTimer = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -176,7 +179,9 @@ function CompCard({seekTime: THUMBNAIL_SEEK_TIME_SECONDS,duration: 0,origin: window.location.origin,+ contentRevision,});+ const thumbnailFailed = failedThumbnailUrl === thumbnailUrl;const previewScale = resolveCompositionPreviewScale({cardWidth: CARD_W,cardHeight: CARD_H,@@ -246,7 +251,7 @@ function CompCard({draggable={false}loading="lazy"decoding="async"- onError={() => setThumbnailFailed(true)}+ onError={() => setFailedThumbnailUrl(thumbnailUrl)}className={`absolute inset-0 h-full w-full object-contain transition-opacity ${livePreviewLoaded ? "opacity-0" : "opacity-100"}`}@@ -368,6 +373,7 @@ export const CompositionsTab = memo(function CompositionsTab({isRendering,lintFindingsByFile,}: CompositionsTabProps) {+ const contentRevision = usePlayerStore((state) => state.thumbnailContentRevision);if (compositions.length === 0) {return (<div className="flex-1 flex items-center justify-center px-4">@@ -389,6 +395,7 @@ export const CompositionsTab = memo(function CompositionsTab({onAddToTimeline={onAddToTimeline ? () => onAddToTimeline(comp) : undefined}isRendering={isRendering}lintInfo={lintFindingsByFile?.get(comp)}+ contentRevision={contentRevision}/>))}</div>diff --git a/packages/studio/src/components/ui/HyperframesLoader.tsx b/packages/studio/src/components/ui/HyperframesLoader.tsxindex 1a6b5fceec..280ea8a051 100644--- a/packages/studio/src/components/ui/HyperframesLoader.tsx+++ b/packages/studio/src/components/ui/HyperframesLoader.tsx@@ -1,3 +1,5 @@+import { HyperframesMark } from "./HyperframesMark";+export interface HyperframesLoaderProps {/** Status text shown below the mark. */title: string;@@ -31,54 +33,7 @@ export function HyperframesLoader({style={{ width: markFrameSize, height: markFrameSize }}draggable={false}>- <svg- className="hf-loader-mark"- width={size}- height={size}- viewBox="0 0 100 100"- fill="none"- xmlns="http://www.w3.org/2000/svg"- aria-hidden="true"- >- <g className="hf-loader-mark__mark" transform="translate(50 50)">- <g className="hf-loader-mark__core" transform="scale(1)" opacity=".92">- <g transform="translate(-50 -50)">- <path- d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z"- fill="url(#hf-loader-grad-left)"- />- <path- d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z"- fill="url(#hf-loader-grad-right)"- />- </g>- </g>- </g>- <defs>- <linearGradient- id="hf-loader-grad-left"- x1="48.5676"- y1="25"- x2="44.7804"- y2="71.9384"- gradientUnits="userSpaceOnUse"- >- <stop stopColor="#06E3FA" />- <stop offset="1" stopColor="#4FDB5E" />- </linearGradient>- <linearGradient- id="hf-loader-grad-right"- x1="54.8282"- y1="73.8392"- x2="72.0989"- y2="32.8932"- gradientUnits="userSpaceOnUse"- >- <stop stopColor="#06E3FA" />- <stop offset="1" stopColor="#4FDB5E" />- </linearGradient>- </defs>- </svg>+ <HyperframesMark className="hf-loader-mark" width={size} height={size} /></div><div className="hf-loader-title">{title}</div>{detail && <div className="hf-loader-detail">{detail}</div>}diff --git a/packages/studio/src/components/ui/HyperframesMark.tsx b/packages/studio/src/components/ui/HyperframesMark.tsxnew file mode 100644index 0000000000..36092b1d4b--- /dev/null+++ b/packages/studio/src/components/ui/HyperframesMark.tsx@@ -0,0 +1,53 @@+import { useId, type SVGProps } from "react";++export function HyperframesMark({ viewBox = "0 0 100 100", ...props }: SVGProps<SVGSVGElement>) {+ const gradientId = useId();+ const leftGradient = `${gradientId}-left`;+ const rightGradient = `${gradientId}-right`;+ return (+ <svg+ viewBox={viewBox}+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ aria-hidden="true"+ {...props}+ >+ <g transform="translate(50 50)" opacity=".92">+ <g transform="translate(-50 -50)">+ <path+ d="M10.1851 57.8021L33.1145 73.8313C36.2202 75.9978 41.5173 73.5433 42.4816 69.4984L51.7611 30.4271C52.7253 26.3822 48.5802 23.9277 44.4602 26.0942L13.917 42.1235C6.96677 45.7676 4.97564 54.1579 10.1851 57.8021Z"+ fill={`url(#${leftGradient})`}+ />+ <path+ d="M87.5129 57.5141L56.9696 73.5433C52.8371 75.7098 48.7046 73.2553 49.6688 69.2104L58.9483 30.1391C59.9125 26.0942 65.2097 23.6397 68.3154 25.8062L91.2447 41.8354C96.4668 45.4796 94.4631 53.8699 87.5129 57.5141Z"+ fill={`url(#${rightGradient})`}+ />+ </g>+ </g>+ <defs>+ <linearGradient+ id={leftGradient}+ x1="48.5676"+ y1="25"+ x2="44.7804"+ y2="71.9384"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#06E3FA" />+ <stop offset="1" stopColor="#4FDB5E" />+ </linearGradient>+ <linearGradient+ id={rightGradient}+ x1="54.8282"+ y1="73.8392"+ x2="72.0989"+ y2="32.8932"+ gradientUnits="userSpaceOnUse"+ >+ <stop stopColor="#06E3FA" />+ <stop offset="1" stopColor="#4FDB5E" />+ </linearGradient>+ </defs>+ </svg>+ );+}diff --git a/packages/studio/src/contexts/DomEditContext.tsx b/packages/studio/src/contexts/DomEditContext.tsxindex 31210b3f72..6c1eba1e17 100644--- a/packages/studio/src/contexts/DomEditContext.tsx+++ b/packages/studio/src/contexts/DomEditContext.tsx@@ -14,6 +14,7 @@ export interface DomEditActionsValue extends Pick<| "applyDomSelection"| "clearDomSelection"| "handleDomStyleCommit"+ | "handleDomStyleCommitForSelection"| "handleDomAttributeCommit"| "handleDomAttributeLiveCommit"| "handleDomAttributeQuietCommit"@@ -26,10 +27,12 @@ export interface DomEditActionsValue extends Pick<| "handleDomRotationCommit"| "handleDomManualEditsReset"| "handleDomTextCommit"+ | "handleDomTextCommitForSelection"| "handleDomRichTextCommit"| "handleDomTextFieldStyleCommit"| "handleDomAddTextField"| "handleDomRemoveTextField"+ | "getGsapAnimationsForSelection"| "handleAskAgent"| "handleAgentModalSubmit"| "handleBlockedDomMove"@@ -153,6 +156,7 @@ export function DomEditProvider({applyDomSelection,clearDomSelection,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,@@ -166,10 +170,12 @@ export function DomEditProvider({handleDomManualEditsReset,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,handleDomTextFieldStyleCommit,handleDomAddTextField,handleDomRemoveTextField,+ getGsapAnimationsForSelection,handleAskAgent,handleAgentModalSubmit,handleBlockedDomMove,@@ -243,6 +249,7 @@ export function DomEditProvider({applyDomSelection,clearDomSelection,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,@@ -255,10 +262,12 @@ export function DomEditProvider({handleDomRotationCommit,handleDomManualEditsReset,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,handleDomTextFieldStyleCommit,handleDomAddTextField,handleDomRemoveTextField,+ getGsapAnimationsForSelection,handleAskAgent,handleAgentModalSubmit,handleBlockedDomMove,@@ -314,6 +323,7 @@ export function DomEditProvider({applyDomSelection,clearDomSelection,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,@@ -326,10 +336,12 @@ export function DomEditProvider({handleDomRotationCommit,handleDomManualEditsReset,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,handleDomTextFieldStyleCommit,handleDomAddTextField,handleDomRemoveTextField,+ getGsapAnimationsForSelection,handleAskAgent,handleAgentModalSubmit,handleBlockedDomMove,diff --git a/packages/studio/src/hooks/domEditCommitRunner.test.ts b/packages/studio/src/hooks/domEditCommitRunner.test.tsnew file mode 100644index 0000000000..096f257c52--- /dev/null+++ b/packages/studio/src/hooks/domEditCommitRunner.test.ts@@ -0,0 +1,59 @@+import { describe, expect, it, vi } from "vitest";+import { bumpDomEditCommitMapVersion, runDomEditCommit } from "./domEditCommitRunner";++function commitConfig(overrides: Partial<Parameters<typeof runDomEditCommit>[0]> = {}) {+ return {+ capture: vi.fn(),+ apply: vi.fn(),+ persist: vi.fn(async () => undefined),+ shouldRevert: vi.fn(() => true),+ revert: vi.fn(),+ onError: vi.fn(),+ shouldResync: vi.fn(() => false),+ resync: vi.fn(),+ ...overrides,+ };+}++describe("DOM edit commit version cleanup", () => {+ it("releases a settled target without deleting a newer target version", () => {+ const versions = new Map<string, symbol>();+ const first = bumpDomEditCommitMapVersion(versions, "headline");+ const second = bumpDomEditCommitMapVersion(versions, "headline");++ first.release();+ expect(versions.size).toBe(1);+ expect(second()).toBe(true);++ second.release();+ expect(versions.size).toBe(0);+ });++ it("never lets an old commit become latest again after cleanup and reuse", () => {+ const versions = new Map<string, symbol>();+ const first = bumpDomEditCommitMapVersion(versions, "headline");+ const second = bumpDomEditCommitMapVersion(versions, "headline");+ second.release();++ const third = bumpDomEditCommitMapVersion(versions, "headline");++ expect(first()).toBe(false);+ expect(third()).toBe(true);+ });++ it("runs settlement cleanup even when capture throws", async () => {+ const onFinally = vi.fn();+ await expect(+ runDomEditCommit(+ commitConfig({+ capture: () => {+ throw new Error("capture failed");+ },+ onFinally,+ }),+ ),+ ).rejects.toThrow("capture failed");++ expect(onFinally).toHaveBeenCalledOnce();+ });+});diff --git a/packages/studio/src/hooks/domEditCommitRunner.ts b/packages/studio/src/hooks/domEditCommitRunner.tsindex b4a4a6cd2f..623e25d079 100644--- a/packages/studio/src/hooks/domEditCommitRunner.ts+++ b/packages/studio/src/hooks/domEditCommitRunner.ts@@ -1,7 +1,9 @@+import type { DomEditPersistOutcome } from "./domEditCommitTypes";+interface DomEditCommitRunnerConfig {capture: () => void;apply: () => void;- persist: () => Promise<void>;+ persist: () => Promise<unknown>;shouldRevert: (error: unknown) => boolean;revert: () => void;onError: (error: unknown) => void;@@ -16,6 +18,8 @@ interface DomEditCommitRunnerConfig {* instead of relying on a rejection that will never come.*/onSettled?: (ok: boolean) => void;+ /** Always runs once after persistence, resync, or an unexpected runner error. */+ onFinally?: () => void;}interface CommitVersionRef {@@ -28,32 +32,46 @@ export function bumpDomEditCommitVersion(versionRef: CommitVersionRef): () => boreturn () => versionRef.current === commitVersion;}+export interface DomEditCommitVersionGuard {+ (): boolean;+ release: () => void;+}+export function bumpDomEditCommitMapVersion<TKey>(- versionMap: Map<TKey, number>,+ versionMap: Map<TKey, symbol>,versionKey: TKey,-): () => boolean {- const commitVersion = (versionMap.get(versionKey) ?? 0) + 1;+): DomEditCommitVersionGuard {+ const commitVersion = Symbol("dom-edit-commit");versionMap.set(versionKey, commitVersion);- return () => versionMap.get(versionKey) === commitVersion;+ const isLatest = () => versionMap.get(versionKey) === commitVersion;+ return Object.assign(isLatest, {+ release: () => {+ if (isLatest()) versionMap.delete(versionKey);+ },+ });}export async function runDomEditCommit(config: DomEditCommitRunnerConfig): Promise<void> {- config.capture();- config.apply();-try {- await config.persist();- config.onSettled?.(true);- } catch (error) {- if (config.shouldRevert(error)) {- config.revert();+ config.capture();+ config.apply();++ try {+ await config.persist();+ config.onSettled?.(true);+ } catch (error) {+ if (config.shouldRevert(error)) {+ config.revert();+ }+ config.onError(error);+ config.onSettled?.(false);}- config.onError(error);- config.onSettled?.(false);- }- if (!config.shouldResync()) return;- await config.resync();+ if (!config.shouldResync()) return;+ await config.resync();+ } finally {+ config.onFinally?.();+ }}/**@@ -75,7 +93,9 @@ export type DomEditCommitDeclineReason =| "preview-stale"| "persist-failed";-export type DomEditCommitOutcome = { ok: true } | { ok: false; reason: DomEditCommitDeclineReason };+export type DomEditCommitOutcome =+ | { ok: true; persistence?: DomEditPersistOutcome }+ | { ok: false; reason: DomEditCommitDeclineReason };export function domEditCommitDeclined(reason: DomEditCommitDeclineReason): DomEditCommitOutcome {return { ok: false, reason };@@ -93,12 +113,27 @@ export async function runReportedDomEditCommit(config: DomEditCommitRunnerConfig,): Promise<DomEditCommitOutcome> {let landed = false;+ let persistence: DomEditPersistOutcome | undefined;await runDomEditCommit({...config,+ persist: async () => {+ const result = await config.persist();+ if (isDomEditPersistOutcome(result)) persistence = result;+ },onSettled: (ok) => {landed = ok;config.onSettled?.(ok);},});- return landed ? { ok: true } : domEditCommitDeclined("persist-failed");+ if (!landed) return domEditCommitDeclined("persist-failed");+ return persistence ? { ok: true, persistence } : { ok: true };+}++function isDomEditPersistOutcome(value: unknown): value is DomEditPersistOutcome {+ if (typeof value !== "object" || value === null) return false;+ return (+ typeof Reflect.get(value, "sourceFile") === "string" &&+ typeof Reflect.get(value, "version") === "string" &&+ typeof Reflect.get(value, "changed") === "boolean"+ );}diff --git a/packages/studio/src/hooks/domEditCommitTypes.ts b/packages/studio/src/hooks/domEditCommitTypes.tsindex 808f50a1fa..882edf5e4b 100644--- a/packages/studio/src/hooks/domEditCommitTypes.ts+++ b/packages/studio/src/hooks/domEditCommitTypes.ts@@ -6,6 +6,13 @@ export interface DomEditPatchBatch {patches: Array<{ target: PatchTarget; operations: PatchOperation[] }>;}+/** Durable evidence returned by the one Studio DOM persistence actor. */+export interface DomEditPersistOutcome {+ sourceFile: string;+ version: string;+ changed: boolean;+}+export type CommitDomEditPatchBatches = (batches: DomEditPatchBatch[],options: {@@ -49,4 +56,4 @@ export type PersistDomEditOperations = (prepareContent?: (html: string, sourceFile: string) => string;shouldSave?: () => boolean;},-) => Promise<void>;+) => Promise<DomEditPersistOutcome | undefined>;diff --git a/packages/studio/src/hooks/domEditTextCommitPlan.ts b/packages/studio/src/hooks/domEditTextCommitPlan.tsnew file mode 100644index 0000000000..c233be8684--- /dev/null+++ b/packages/studio/src/hooks/domEditTextCommitPlan.ts@@ -0,0 +1,47 @@+import {+ buildDomEditRichTextPatchOperation,+ buildDomEditTextPatchOperation,+ serializeDomEditTextFields,+ type DomEditTextField,+} from "../components/editor/domEditing";+import type { PatchOperation } from "../utils/sourcePatcher";+import { buildTextFieldChildOperations } from "./domEditTextFieldCommitOps";++interface DomTextCommitPlan {+ usesSerializedTextFields: boolean;+ nextContent: string;+ operations: PatchOperation[];+}++export function buildNextDomTextFields(+ textFields: DomEditTextField[],+ value: string,+ fieldKey?: string,+): DomEditTextField[] {+ if (textFields.length === 0) return [];+ return textFields.map((field) => (field.key === fieldKey ? { ...field, value } : field));+}++export function planDomTextCommit(+ originalTextFields: DomEditTextField[],+ nextTextFields: DomEditTextField[],+ plainTextContent: string,+): DomTextCommitPlan {+ const usesSerializedTextFields =+ nextTextFields.length > 1 || nextTextFields.some((field) => field.source === "child");+ const nextContent = usesSerializedTextFields+ ? serializeDomEditTextFields(nextTextFields)+ : plainTextContent;+ const childOperations = usesSerializedTextFields+ ? buildTextFieldChildOperations(originalTextFields, nextTextFields)+ : null;+ // Per-child operations when the layers still line up one-for-one. Structure+ // changes write the element's markup because no stable child address exists.+ const operations =+ childOperations ??+ (usesSerializedTextFields+ ? [buildDomEditRichTextPatchOperation(nextContent)]+ : [buildDomEditTextPatchOperation(nextContent)]);++ return { usesSerializedTextFields, nextContent, operations };+}diff --git a/packages/studio/src/hooks/useDomEditAttributeCommits.ts b/packages/studio/src/hooks/useDomEditAttributeCommits.tsindex 423e5da7eb..1ab929dd39 100644--- a/packages/studio/src/hooks/useDomEditAttributeCommits.ts+++ b/packages/studio/src/hooks/useDomEditAttributeCommits.ts@@ -135,7 +135,7 @@ export function useDomEditAttributeCommits({refreshDomEditSelectionFromPreview,persistDomEditOperations,}: UseDomEditAttributeCommitsParams) {- const domAttributeCommitVersionRef = useRef(new Map<string, number>());+ const domAttributeCommitVersionRef = useRef(new Map<string, symbol>());const commitDataAttribute = useCallback(async (attr: string, value: string | null, options: DataAttributeCommitOptions) => {@@ -200,6 +200,7 @@ export function useDomEditAttributeCommits({syncStoredAutomationFromPreview(previewIframeRef.current?.contentDocument ?? null);},onSettled: options.onSettled,+ onFinally: isLatestCommit.release,});},[@@ -288,6 +289,7 @@ export function useDomEditAttributeCommits({shouldResync: () => isLatestCommit() && !!options.refreshAfter,resync: () => refreshDomEditSelectionFromPreview(selection),onSettled: options.onSettled,+ onFinally: isLatestCommit.release,});},[@@ -420,6 +422,7 @@ export function useDomEditAttributeCommits({// shipped without one.syncStoredAutomationFromPreview(previewIframeRef.current?.contentDocument ?? null);},+ onFinally: isLatestCommit.release,});},[diff --git a/packages/studio/src/hooks/useDomEditCommits.test.tsx b/packages/studio/src/hooks/useDomEditCommits.test.tsxindex 5bd2957a29..54bdea39f9 100644--- a/packages/studio/src/hooks/useDomEditCommits.test.tsx+++ b/packages/studio/src/hooks/useDomEditCommits.test.tsx@@ -8,7 +8,9 @@ import type { DomEditSelection, DomEditTextField } from "../components/editor/doimport type { ImportedFontAsset } from "../components/editor/fontAssets";import { usePlayerStore } from "../player";import { StudioSaveHttpError } from "../utils/studioSaveDiagnostics";+import { createDomEditSaveQueue } from "../utils/domEditSaveQueue";import { trackStudioEvent } from "../utils/studioTelemetry";+import type { CutoverResult } from "../utils/sdkCutover";import { useDomEditCommits } from "./useDomEditCommits";Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);@@ -22,6 +24,8 @@ interface PatchResponseBody {changed?: boolean;matched?: boolean;content?: string;+ path?: string;+ version?: string;}interface RenderedDomEditCommits {@@ -35,6 +39,9 @@ interface RenderedDomEditCommits {interface RenderDomEditCommitsOptions {importedFontAssets?: ImportedFontAsset[];writeProjectFile?: (path: string, content: string, expectedContent?: string) => Promise<void>;+ onTrySdkPersist?: () => Promise<CutoverResult>;+ queueDomEditSave?: <T>(save: () => Promise<T>) => Promise<T>;+ projectIdRef?: MutableRefObject<string | null>;}type FetchHandler = (@@ -201,7 +208,7 @@ function renderDomEditCommits(const showToast = makeShowToast();const recordEdit = vi.fn(async () => {});const previewIframeRef: MutableRefObject<HTMLIFrameElement | null> = { current: iframe };- const projectIdRef: MutableRefObject<string | null> = { current: "p1" };+ const projectIdRef: MutableRefObject<string | null> = options.projectIdRef ?? { current: "p1" };const domEditSaveTimestampRef: MutableRefObject<number> = { current: 0 };const reloadPreview = vi.fn();@@ -210,7 +217,7 @@ function renderDomEditCommits(activeCompPath: "index.html",previewIframeRef,showToast,- queueDomEditSave: async (save) => save(),+ queueDomEditSave: options.queueDomEditSave ?? (async (save) => save()),writeProjectFile: options.writeProjectFile ?? (async () => {}),domEditSaveTimestampRef,editHistory: { recordEdit },@@ -224,6 +231,7 @@ function renderDomEditCommits(clearDomSelection: vi.fn(),refreshDomEditSelectionFromPreview: vi.fn(),buildDomSelectionFromTarget: vi.fn(async () => null),+ onTrySdkPersist: options.onTrySdkPersist,});return null;}@@ -772,11 +780,13 @@ async function commitStyleAgainst(response: Parameters<typeof stubPatchFetch>[0]const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => {});const { iframe, element } = createPreviewElement();const rendered = renderDomEditCommits(createSelection(element), iframe);+ let outcome: Awaited<ReturnType<typeof rendered.hook.handleDomStyleCommit>> | undefined;await act(async () => {- await rendered.hook.handleDomStyleCommit("color", "blue");+ outcome = await rendered.hook.handleDomStyleCommit("color", "blue");});return {element,+ outcome,rendered,warnSpy,cleanup: () => {@@ -944,10 +954,12 @@ describe("useDomEditCommits style persist handling", () => {});it("warns without a toast when the server matched the element but reported no change", async () => {- const { rendered, warnSpy, cleanup } = await commitStyleAgainst({+ const { rendered, outcome, warnSpy, cleanup } = await commitStyleAgainst({ok: true,changed: false,matched: true,+ path: "index.html",+ version: '"sha256:current"',});try {@@ -956,6 +968,14 @@ describe("useDomEditCommits style persist handling", () => {"[Studio] DOM edit persist no-op",expect.objectContaining({ operations: "inline-style:color" }),);+ expect(outcome).toEqual({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:current"',+ changed: false,+ },+ });} finally {cleanup();}@@ -976,22 +996,203 @@ describe("useDomEditCommits style persist handling", () => {});it("keeps the optimistic style and records history when the patch succeeds", async () => {- const { element, rendered, cleanup } = await commitStyleAgainst({+ const { element, rendered, outcome, cleanup } = await commitStyleAgainst({ok: true,changed: true,matched: true,content: '<div data-hf-id="hf-card" style="color: blue">Card</div>',+ path: "index.html",+ version: '"sha256:after"',});try {expect(rendered.showToast).not.toHaveBeenCalled();expect(element.style.getPropertyValue("color")).toBe("blue");expect(rendered.recordEdit).toHaveBeenCalledTimes(1);+ expect(outcome).toEqual({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:after"',+ changed: true,+ },+ });} finally {cleanup();}});+ it("serializes the full read, write, and history transaction across overlapping commits", async () => {+ const firstPatch = createDeferred<Response>();+ let readCount = 0;+ let patchCount = 0;+ vi.stubGlobal(+ "fetch",+ vi.fn(async (input: Parameters<typeof fetch>[0]) => {+ const url = requestUrl(input);+ if (url.includes("/api/projects/p1/files/")) {+ readCount += 1;+ return jsonResponse({+ content:+ readCount === 1+ ? '<div data-hf-id="hf-card" style="color: red">Card</div>'+ : '<div data-hf-id="hf-card" style="color: blue">Card</div>',+ });+ }+ if (url.includes("/api/projects/p1/file-mutations/patch-element/")) {+ patchCount += 1;+ if (patchCount === 1) return firstPatch.promise;+ return jsonResponse({+ ok: true,+ changed: true,+ matched: true,+ content: '<div data-hf-id="hf-card" style="color: green">Card</div>',+ path: "index.html",+ version: '"sha256:green"',+ });+ }+ throw new Error(`Unexpected fetch: ${url}`);+ }),+ );+ const queue = createDomEditSaveQueue();+ const { iframe, element } = createPreviewElement();+ const rendered = renderDomEditCommits(createSelection(element), iframe, {+ queueDomEditSave: queue.enqueue,+ });++ try {+ const first = rendered.hook.handleDomStyleCommit("color", "blue");+ await flushAsyncWork();+ const second = rendered.hook.handleDomStyleCommit("color", "green");+ await flushAsyncWork();++ expect(readCount).toBe(1);+ expect(patchCount).toBe(1);++ firstPatch.resolve(+ jsonResponse({+ ok: true,+ changed: true,+ matched: true,+ content: '<div data-hf-id="hf-card" style="color: blue">Card</div>',+ path: "index.html",+ version: '"sha256:blue"',+ }),+ );+ await first;+ await second;++ expect(readCount).toBe(2);+ expect(patchCount).toBe(2);+ expect(rendered.recordEdit).toHaveBeenNthCalledWith(+ 1,+ expect.objectContaining({+ files: {+ "index.html": expect.objectContaining({+ before: expect.stringContaining("color: red"),+ after: expect.stringContaining("color: blue"),+ }),+ },+ }),+ );+ expect(rendered.recordEdit).toHaveBeenNthCalledWith(+ 2,+ expect.objectContaining({+ files: {+ "index.html": expect.objectContaining({+ before: expect.stringContaining("color: blue"),+ after: expect.stringContaining("color: green"),+ }),+ },+ }),+ );+ } finally {+ queue.destroy();+ rendered.cleanup();+ }+ });++ it("refuses queued persistence after the active project changes", async () => {+ const firstPatch = createDeferred<Response>();+ const projectIdRef: MutableRefObject<string | null> = { current: "p1" };+ const fetchMock = vi.fn(async (input: Parameters<typeof fetch>[0]) => {+ const url = requestUrl(input);+ if (url.includes("/api/projects/p1/files/")) {+ return jsonResponse({+ content: '<div data-hf-id="hf-card" style="color: red">Card</div>',+ });+ }+ if (url.includes("/api/projects/p1/file-mutations/patch-element/")) {+ return firstPatch.promise;+ }+ throw new Error(`Unexpected fetch: ${url}`);+ });+ vi.stubGlobal("fetch", fetchMock);+ const queue = createDomEditSaveQueue();+ const { iframe, element } = createPreviewElement();+ const rendered = renderDomEditCommits(createSelection(element), iframe, {+ queueDomEditSave: queue.enqueue,+ projectIdRef,+ });++ try {+ const first = rendered.hook.handleDomStyleCommit("color", "blue");+ await flushAsyncWork();+ const second = rendered.hook.handleDomStyleCommit("color", "green");+ projectIdRef.current = "p2";+ firstPatch.resolve(+ jsonResponse({+ ok: true,+ changed: true,+ matched: true,+ content: '<div data-hf-id="hf-card" style="color: blue">Card</div>',+ path: "index.html",+ version: '"sha256:blue"',+ }),+ );++ await first;+ await expect(second).resolves.toMatchObject({+ ok: false,+ reason: "persist-failed",+ });+ expect(fetchMock.mock.calls.some(([input]) => requestUrl(input).includes("/p2/"))).toBe(+ false,+ );+ expect(fetchMock).toHaveBeenCalledTimes(2);+ } finally {+ queue.destroy();+ rendered.cleanup();+ }+ });++ it("preserves the SDK cutover version as the style commit's durable evidence", async () => {+ const fetchMock = stubPatchFetch({ ok: true, changed: true, matched: true });+ const { iframe, element } = createPreviewElement();+ const rendered = renderDomEditCommits(createSelection(element), iframe, {+ onTrySdkPersist: async () => ({ status: "committed", version: "sdk-version-2" }),+ });++ try {+ let outcome: Awaited<ReturnType<typeof rendered.hook.handleDomStyleCommit>> | undefined;+ await act(async () => {+ outcome = await rendered.hook.handleDomStyleCommit("color", "blue");+ });++ expect(outcome).toEqual({+ ok: true,+ persistence: { sourceFile: "index.html", version: "sdk-version-2", changed: true },+ });+ expect(+ fetchMock.mock.calls.some(([input]) =>+ requestUrl(input).includes("/file-mutations/patch-element/"),+ ),+ ).toBe(false);+ } finally {+ rendered.cleanup();+ }+ });+it("keeps a newer style value when an older overlapping commit later fails", async () => {const firstPatch = createDeferred<Response>();const secondPatch = createDeferred<Response>();@@ -1466,9 +1667,7 @@ describe("useDomEditCommits attribute persist handling", () => {// optimistic apply) and succeeds before the older one rejects. Without the// per-key version guard, the stale rejection would revert to the older// commit's own previousValue (null) and stomp the newer commit's value.- const firstCommit = act(async () => {- await rendered.hook.handleDomHtmlAttributeCommit("muted", "first-value");- });+ const firstCommit = rendered.hook.handleDomHtmlAttributeCommit("muted", "first-value");await act(async () => {await rendered.hook.handleDomHtmlAttributeCommit("muted", "second-value");});diff --git a/packages/studio/src/hooks/useDomEditCommits.ts b/packages/studio/src/hooks/useDomEditCommits.tsindex 11deb45fd9..baa7a66964 100644--- a/packages/studio/src/hooks/useDomEditCommits.ts+++ b/packages/studio/src/hooks/useDomEditCommits.ts@@ -32,7 +32,7 @@ import {patchElementBatches,readErrorResponseBody,} from "./useDomEditCommitsHelpers";-import { cutoverCommittedOrThrow, type CutoverResult } from "../utils/sdkCutover";+import type { CutoverResult } from "../utils/sdkCutover";import { studioWriteHeaders } from "../utils/studioFileVersion";interface RecordEditInput {label: string;@@ -139,11 +139,18 @@ export function useDomEditCommits({const reportedUnresolvableRef = useRef(new Set<string>());// fallow-ignore-next-line complexity- const persistDomEditOperations: PersistDomEditOperations = useCallback(+ const performPersistDomEditOperations = useCallback(// fallow-ignore-next-line complexity- async (selection, operations, options) => {- const pid = projectIdRef.current;- if (!pid) throw new Error("No active project");+ async (+ selection: DomEditSelection,+ operations: PatchOperation[],+ options: Parameters<PersistDomEditOperations>[2],+ expectedProjectId: string,+ ) => {+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+ const pid = expectedProjectId;if (options?.shouldSave && !options.shouldSave()) return;const targetPath = selection.sourceFile || activeCompPath || "index.html";@@ -160,6 +167,10 @@ export function useDomEditCommits({throw new Error(`Missing file contents for ${targetPath}`);}+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+if (options?.shouldSave && !options.shouldSave()) return;// Validate layout values BEFORE any persist path runs. The SDK cutover@@ -186,10 +197,11 @@ export function useDomEditCommits({coalesceKey: options?.coalesceKey,skipRefresh: options?.skipRefresh,});- if (cutoverCommittedOrThrow(cutover)) {+ if (cutover.status === "failed") throw cutover.error;+ if (cutover.status === "committed") {// SDK handled it — its in-memory doc is already current, so do NOT// forceReload (that would echo-reload the session we just wrote).- return;+ return { sourceFile: targetPath, version: cutover.version, changed: true };}}@@ -218,6 +230,8 @@ export function useDomEditCommits({changed?: boolean;matched?: boolean;content?: string;+ path?: string;+ version?: string;};if (!patchData.changed) {@@ -235,7 +249,9 @@ export function useDomEditCommits({throw new DomEditPersistUnresolvableError(targetPath);}warnDomEditPersistNoOp(selection, operations);- return;+ return typeof patchData.path === "string" && typeof patchData.version === "string"+ ? { sourceFile: patchData.path, version: patchData.version, changed: false }+ : undefined;}const patchedContent =@@ -273,6 +289,11 @@ export function useDomEditCommits({if (!options?.skipRefresh) {reloadPreview();}+ return finalContent === patchedContent &&+ typeof patchData.path === "string" &&+ typeof patchData.version === "string"+ ? { sourceFile: patchData.path, version: patchData.version, changed: true }+ : undefined;},[activeCompPath,@@ -287,15 +308,30 @@ export function useDomEditCommits({],);+ const persistDomEditOperations: PersistDomEditOperations = useCallback(+ (selection, operations, options) => {+ const expectedProjectId = projectIdRef.current;+ if (!expectedProjectId) return Promise.reject(new Error("No active project"));+ return queueDomEditSave(() =>+ performPersistDomEditOperations(selection, operations, options, expectedProjectId),+ );+ },+ [performPersistDomEditOperations, projectIdRef, queueDomEditSave],+ );+const commitDomEditPatchBatches: CommitDomEditPatchBatches = useCallback(- (batches, options) =>- queueDomEditSave(+ (batches, options) => {+ const expectedProjectId = projectIdRef.current;+ if (!expectedProjectId) return Promise.reject(new Error("No active project"));+ return queueDomEditSave(// One queued transaction owns validation, persistence, history, reload,// and its durable result; splitting those phases risks partial commits.// fallow-ignore-next-line complexityasync () => {- const pid = projectIdRef.current;- if (!pid) throw new Error("No active project");+ if (projectIdRef.current !== expectedProjectId) {+ throw new Error("Active project changed before the edit could be saved");+ }+ const pid = expectedProjectId;const unsafeFields = batches.flatMap((batch) =>batch.patches.flatMap((patch) => findUnsafeDomPatchValues(patch)),);@@ -357,7 +393,8 @@ export function useDomEditCommits({label: options.label,});throw error;- }),+ });+ },[domEditSaveTimestampRef,editHistory,@@ -373,12 +410,14 @@ export function useDomEditCommits({const {handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,handleDomHtmlAttributeCommit,handleDomAttributesCommit,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,commitDomTextFields,handleDomTextFieldStyleCommit,@@ -401,7 +440,6 @@ export function useDomEditCommits({const commitPositionPatchToHtml = useDomEditPositionPatchCommit({activeCompPath,persistDomEditOperations,- queueDomEditSave,showToast,});@@ -439,12 +477,14 @@ export function useDomEditCommits({return {resolveImportedFontAsset,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,handleDomHtmlAttributeCommit,handleDomAttributesCommit,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,commitDomTextFields,handleDomTextFieldStyleCommit,diff --git a/packages/studio/src/hooks/useDomEditPositionPatchCommit.test.tsx b/packages/studio/src/hooks/useDomEditPositionPatchCommit.test.tsxindex c9d2a3bdc2..fd80f89e52 100644--- a/packages/studio/src/hooks/useDomEditPositionPatchCommit.test.tsx+++ b/packages/studio/src/hooks/useDomEditPositionPatchCommit.test.tsx@@ -55,14 +55,13 @@ function renderCommit(params: Parameters<typeof useDomEditPositionPatchCommit>[0return captured.commit;}-function paramsWith(queueDomEditSave: (save: () => Promise<void>) => Promise<void>) {+function paramsWith(persistDomEditOperations: () => Promise<undefined>) {const showToast = vi.fn();return {showToast,params: {activeCompPath: "index.html",- persistDomEditOperations: vi.fn().mockResolvedValue(undefined),- queueDomEditSave,+ persistDomEditOperations,showToast,},};@@ -104,7 +103,7 @@ describe("useDomEditPositionPatchCommit", () => {});it("resolves when the write lands", async () => {- const { showToast, params } = paramsWith((save) => save());+ const { showToast, params } = paramsWith(() => Promise.resolve(undefined));const commit = renderCommit(params);await act(async () => {diff --git a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts b/packages/studio/src/hooks/useDomEditPositionPatchCommit.tsindex 1f6489abe4..dd693fff97 100644--- a/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts+++ b/packages/studio/src/hooks/useDomEditPositionPatchCommit.ts@@ -8,7 +8,6 @@ import type { PersistDomEditOperations } from "./domEditCommitTypes";interface UseDomEditPositionPatchCommitParams {activeCompPath: string | null;persistDomEditOperations: PersistDomEditOperations;- queueDomEditSave: (save: () => Promise<void>) => Promise<void>;showToast: (message: string, tone?: "error" | "info") => void;}@@ -22,39 +21,38 @@ interface PositionPatchOptions {export function useDomEditPositionPatchCommit({activeCompPath,persistDomEditOperations,- queueDomEditSave,showToast,}: UseDomEditPositionPatchCommitParams) {return useCallback((selection: DomEditSelection, patches: PatchOperation[], options: PositionPatchOptions) => {- return queueDomEditSave(async () => {- await persistDomEditOperations(selection, patches, {- label: options.label,- coalesceKey: options.coalesceKey,- coalesceMs: options.coalesceMs,- skipRefresh: options.skipRefresh ?? true,+ return persistDomEditOperations(selection, patches, {+ label: options.label,+ coalesceKey: options.coalesceKey,+ coalesceMs: options.coalesceMs,+ skipRefresh: options.skipRefresh ?? true,+ })+ .then(() => undefined)+ .catch((error) => {+ // A paused save queue is not worth a toast: the paused-save banner is+ // already on screen, and one toast per blocked edit is what this branch+ // exists to prevent. It still has to REJECT, though. Swallowing it+ // resolved the commit, which skipped the caller's revert, so the element+ // stayed where the drag put it while nothing reached the file.+ if (error instanceof DomEditSaveQueueOpenError) throw error;+ showToast(error instanceof Error ? error.message : "Failed to save position");+ trackStudioSaveFailure({+ source: "dom_edit",+ error,+ filePath: selection.sourceFile ?? activeCompPath ?? "index.html",+ mutationType: "position",+ label: options.label,+ targetId: selection.id,+ targetSelector: selection.selector,+ targetSourceFile: selection.sourceFile,+ });+ throw error;});- }).catch((error) => {- // A paused save queue is not worth a toast: the paused-save banner is- // already on screen, and one toast per blocked edit is what this branch- // exists to prevent. It still has to REJECT, though. Swallowing it- // resolved the commit, which skipped the caller's revert, so the element- // stayed where the drag put it while nothing reached the file.- if (error instanceof DomEditSaveQueueOpenError) throw error;- showToast(error instanceof Error ? error.message : "Failed to save position");- trackStudioSaveFailure({- source: "dom_edit",- error,- filePath: selection.sourceFile ?? activeCompPath ?? "index.html",- mutationType: "position",- label: options.label,- targetId: selection.id,- targetSelector: selection.selector,- targetSourceFile: selection.sourceFile,- });- throw error;- });},- [activeCompPath, persistDomEditOperations, queueDomEditSave, showToast],+ [activeCompPath, persistDomEditOperations, showToast],);}diff --git a/packages/studio/src/hooks/useDomEditSession.ts b/packages/studio/src/hooks/useDomEditSession.tsindex b88babf4a0..d3d650af07 100644--- a/packages/studio/src/hooks/useDomEditSession.ts+++ b/packages/studio/src/hooks/useDomEditSession.ts@@ -227,12 +227,14 @@ export function useDomEditSession({const {resolveImportedFontAsset,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,handleDomHtmlAttributeCommit,handleDomAttributesCommit,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,handleDomTextFieldStyleCommit,handleDomAddTextField,@@ -478,6 +480,7 @@ export function useDomEditSession({onClickToSource,});const {+ getGsapAnimationsForSelection,handleGsapAwarePathOffsetCommit,handleGsapAwareGroupPathOffsetCommit,handleGsapAwareBoxSizeCommit,@@ -506,7 +509,6 @@ export function useDomEditSession({const { handleUpdateSegmentEase, handleUpdateKeyframeEase, handleSetAllKeyframeEases } =useKeyframeEaseCommits({ gsapCommitMutation, domEditSelectionRef });return {- // StatedomEditSelection,domEditGroupSelections,domEditHoverSelection,@@ -515,7 +517,6 @@ export function useDomEditSession({agentModalAnchorPoint,copiedAgentPrompt,agentPromptSelectionContext,- // RefsdomEditSelectionRef,// CallbackshandleTimelineElementSelect,@@ -525,6 +526,7 @@ export function useDomEditSession({applyDomSelection,clearDomSelection,handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,@@ -537,10 +539,12 @@ export function useDomEditSession({handleDomRotationCommit: handleGsapAwareRotationCommit,handleDomManualEditsReset,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,handleDomTextFieldStyleCommit,handleDomAddTextField,handleDomRemoveTextField,+ getGsapAnimationsForSelection,handleAskAgent,handleAgentModalSubmit,handleBlockedDomMove,diff --git a/packages/studio/src/hooks/useDomEditTextCommits.test.tsx b/packages/studio/src/hooks/useDomEditTextCommits.test.tsxindex cc440823e7..a48bcf0775 100644--- a/packages/studio/src/hooks/useDomEditTextCommits.test.tsx+++ b/packages/studio/src/hooks/useDomEditTextCommits.test.tsx@@ -124,6 +124,44 @@ afterEach(() => {});describe("useDomEditTextCommits", () => {+ it("keeps concurrent text commit ownership isolated by target", async () => {+ const { iframe, element: firstElement } = previewElement(+ "<div id='first'>First</div><div id='second'>Second</div>",+ "first",+ );+ const secondElement = iframe.contentDocument?.getElementById("second") as HTMLElement;+ const firstSelection = selectionFor(firstElement);+ const secondSelection = selectionFor(secondElement);+ const firstPersist = createDeferred<void>();+ const persistDomEditOperations = vi+ .fn()+ .mockImplementationOnce(() => firstPersist.promise)+ .mockResolvedValueOnce(undefined);+ vi.spyOn(console, "warn").mockImplementation(() => {});+ const hook = renderTextCommitHook(+ commitParams({+ previewIframeRef: { current: iframe },+ domEditSelection: firstSelection,+ persistDomEditOperations,+ }),+ );++ let firstCommit: Promise<unknown> | undefined;+ act(() => {+ firstCommit = hook.handleDomTextCommitForSelection(firstSelection, "Pending first", "self");+ });+ await act(async () => {+ await hook.handleDomTextCommitForSelection(secondSelection, "Saved second", "self");+ });+ firstPersist.reject(new Error("first target failed"));+ await act(async () => {+ await firstCommit;+ });++ expect(firstElement.textContent).toBe("First");+ expect(secondElement.textContent).toBe("Saved second");+ });+it("does not let a stale failed fields commit revert newer text", async () => {const { iframe, element } = previewElement("<div id='card'>Original</div>", "card");vi.spyOn(console, "warn").mockImplementation(() => {});@@ -183,8 +221,17 @@ describe("useDomEditTextCommits", () => {it("reports a successful style commit", async () => {const { iframe, element } = previewElement("<div id='card'>Original</div>", "card");const selection = selectionFor(element);+ const persistence = {+ sourceFile: "index.html",+ version: '"sha256:after"',+ changed: true,+ } as const;const hook = renderTextCommitHook(- commitParams({ previewIframeRef: { current: iframe }, domEditSelection: selection }),+ commitParams({+ previewIframeRef: { current: iframe },+ domEditSelection: selection,+ persistDomEditOperations: vi.fn().mockResolvedValue(persistence),+ }),);let outcome: unknown;@@ -192,7 +239,7 @@ describe("useDomEditTextCommits", () => {outcome = await hook.handleDomStyleCommit("color", "red");});- expect(outcome).toEqual({ ok: true });+ expect(outcome).toEqual({ ok: true, persistence });});it("declines a style commit with no selection, without reaching the writer", async () => {@@ -286,4 +333,41 @@ describe("useDomEditTextCommits", () => {expect(outcome).toEqual({ ok: false, reason: "no-selection" });expect(persistDomEditOperations).not.toHaveBeenCalled();});++ it("preserves text persistence evidence for an explicit selection", async () => {+ const { iframe, element: ambientElement } = previewElement(+ "<div id='ambient'>Ambient</div><div id='agent'>Agent</div>",+ "ambient",+ );+ const agentElement = iframe.contentDocument?.getElementById("agent") as HTMLElement;+ const ambientSelection = selectionFor(ambientElement);+ const agentSelection = selectionFor(agentElement);+ const persistence = {+ sourceFile: "index.html",+ version: '"sha256:text"',+ changed: true,+ } as const;+ const persistDomEditOperations = vi.fn().mockResolvedValue(persistence);+ const hook = renderTextCommitHook(+ commitParams({+ previewIframeRef: { current: iframe },+ domEditSelection: ambientSelection,+ persistDomEditOperations,+ }),+ );++ let outcome: unknown;+ await act(async () => {+ outcome = await hook.handleDomTextCommitForSelection(agentSelection, "Edited", "self");+ });++ expect(outcome).toEqual({ ok: true, persistence });+ expect(persistDomEditOperations).toHaveBeenCalledWith(+ agentSelection,+ expect.any(Array),+ expect.any(Object),+ );+ expect(ambientElement.textContent).toBe("Ambient");+ expect(agentElement.textContent).toBe("Edited");+ });});diff --git a/packages/studio/src/hooks/useDomEditTextCommits.ts b/packages/studio/src/hooks/useDomEditTextCommits.tsindex 557ee7abe9..16feac7056 100644--- a/packages/studio/src/hooks/useDomEditTextCommits.ts+++ b/packages/studio/src/hooks/useDomEditTextCommits.ts@@ -13,11 +13,9 @@ import {import {buildDomEditRichTextPatchOperation,buildDomEditStylePatchOperation,- buildDomEditTextPatchOperation,findElementForSelection,getDomEditTargetKey,isTextEditableSelection,- serializeDomEditTextFields,buildDefaultDomEditTextField,type DomEditTextField,type DomEditSelection,@@ -25,11 +23,10 @@ import {import type { ImportedFontAsset } from "../components/editor/fontAssets";import type { PersistDomEditOperations } from "./domEditCommitTypes";import { canEditElementTextInline } from "../components/editor/domEditInlineText";-import { buildTextFieldChildOperations } from "./domEditTextFieldCommitOps";+import { buildNextDomTextFields, planDomTextCommit } from "./domEditTextCommitPlan";import { reportDomEditPersistFailure } from "./domEditPersistFailure";import {bumpDomEditCommitMapVersion,- bumpDomEditCommitVersion,domEditCommitDeclined,runDomEditCommit,runReportedDomEditCommit,@@ -58,13 +55,6 @@ export interface UseDomEditTextCommitsParams {resolveImportedFontAsset: (fontFamilyValue: string) => ImportedFontAsset | null;}-interface DomTextCommitPlan {- usesSerializedTextFields: boolean;- nextContent: string;- childOperations: PatchOperation[] | null;- operations: PatchOperation[];-}-function canCommitInlineTextSelection(selection: DomEditSelection, element: HTMLElement): boolean {if (selection.isCompositionHost || selection.isInsideLockedComposition) return false;return canEditElementTextInline(element);@@ -97,51 +87,6 @@ function buildDomStyleCommitOperations(return operations;}-function buildNextDomTextFields(- textFields: DomEditTextField[],- value: string,- fieldKey?: string,-): DomEditTextField[] {- if (textFields.length === 0) return [];- return textFields.map((field) => (field.key === fieldKey ? { ...field, value } : field));-}--function planDomTextCommit(- originalTextFields: DomEditTextField[],- nextTextFields: DomEditTextField[],- plainTextContent: string,-): DomTextCommitPlan {- const usesSerializedTextFields =- nextTextFields.length > 1 || nextTextFields.some((field) => field.source === "child");- const nextContent = usesSerializedTextFields- ? serializeDomEditTextFields(nextTextFields)- : plainTextContent;- const childOperations = usesSerializedTextFields- ? buildTextFieldChildOperations(originalTextFields, nextTextFields)- : null;- // Per-child operations when the layers still line up one-for-one, and the- // element's whole markup when they do not.- //- // `buildTextFieldChildOperations` can only address children that already- // exist, so it returns null for any change in how many there are — which is- // every delete and every add. That used to end here with "Couldn't save this- // text structure change": the panel offered a remove button and an Add text- // field row, and neither could ever save. A structure change has one honest- // operation, which is to write the structure.- const operations =- childOperations ??- (usesSerializedTextFields- ? [buildDomEditRichTextPatchOperation(nextContent)]- : [buildDomEditTextPatchOperation(nextContent)]);-- return {- usesSerializedTextFields,- nextContent,- childOperations,- operations,- };-}-async function resyncDomTextSelectionFromPreview(doc: Document | null | undefined,selection: DomEditSelection,@@ -170,8 +115,8 @@ export function useDomEditTextCommits({persistDomEditOperations,resolveImportedFontAsset,}: UseDomEditTextCommitsParams) {- const domTextCommitVersionRef = useRef(0);- const domStyleCommitVersionRef = useRef(new Map<string, number>());+ const domTextCommitVersionRef = useRef(new Map<string, symbol>());+ const domStyleCommitVersionRef = useRef(new Map<string, symbol>());const {handleDomAttributeCommit,@@ -188,15 +133,18 @@ export function useDomEditTextCommits({persistDomEditOperations,});- const handleDomStyleCommit = useCallback(- async (property: string, value: string): Promise<DomEditCommitOutcome> => {- if (!domEditSelection) return domEditCommitDeclined("no-selection");+ const handleDomStyleCommitForSelection = useCallback(+ async (+ selection: DomEditSelection,+ property: string,+ value: string,+ ): Promise<DomEditCommitOutcome> => {if (isManualGeometryStyleProperty(property))return domEditCommitDeclined("geometry-property");- if (!domEditSelection.capabilities.canEditStyles) {+ if (!selection.capabilities.canEditStyles) {return domEditCommitDeclined("styles-not-editable");}- const styleCommitKey = `${getDomEditTargetKey(domEditSelection)}:${property}`;+ const styleCommitKey = `${getDomEditTargetKey(selection)}:${property}`;const isLatestStyleCommit = bumpDomEditCommitMapVersion(domStyleCommitVersionRef.current,styleCommitKey,@@ -219,7 +167,7 @@ export function useDomEditTextCommits({return runReportedDomEditCommit({capture: () => {if (!doc) return;- const el = findElementForSelection(doc, domEditSelection, activeCompPath);+ const el = findElementForSelection(doc, selection, activeCompPath);if (!el) return;editedElement = el;previousInlineValue = el.style.getPropertyValue(property);@@ -238,7 +186,7 @@ export function useDomEditTextCommits({}},persist: () =>- persistDomEditOperations(domEditSelection, operations, {+ persistDomEditOperations(selection, operations, {label: "Edit layer style",skipRefresh,prepareContent: importedFont@@ -255,15 +203,14 @@ export function useDomEditTextCommits({editedElement.style.setProperty(property, previousInlineValue);}},- onError: (error) =>- reportDomEditPersistFailure(domEditSelection, operations, error, showToast),+ onError: (error) => reportDomEditPersistFailure(selection, operations, error, showToast),shouldResync: isLatestStyleCommit,- resync: () => refreshDomEditSelectionFromPreview(domEditSelection),+ resync: () => refreshDomEditSelectionFromPreview(selection),+ onFinally: isLatestStyleCommit.release,});},[activeCompPath,- domEditSelection,persistDomEditOperations,refreshDomEditSelectionFromPreview,resolveImportedFontAsset,@@ -272,15 +219,29 @@ export function useDomEditTextCommits({],);- const handleDomTextCommit = useCallback(- async (value: string, fieldKey?: string): Promise<DomEditCommitOutcome> => {- if (!domEditSelection) return domEditCommitDeclined("no-selection");- if (!isTextEditableSelection(domEditSelection)) {+ const handleDomStyleCommit = useCallback(+ (property: string, value: string): Promise<DomEditCommitOutcome> =>+ domEditSelection+ ? handleDomStyleCommitForSelection(domEditSelection, property, value)+ : Promise.resolve(domEditCommitDeclined("no-selection")),+ [domEditSelection, handleDomStyleCommitForSelection],+ );++ const handleDomTextCommitForSelection = useCallback(+ async (+ selection: DomEditSelection,+ value: string,+ fieldKey?: string,+ ): Promise<DomEditCommitOutcome> => {+ if (!isTextEditableSelection(selection)) {return domEditCommitDeclined("not-text-editable");}- const isLatestTextCommit = bumpDomEditCommitVersion(domTextCommitVersionRef);- const nextTextFields = buildNextDomTextFields(domEditSelection.textFields, value, fieldKey);- const textCommit = planDomTextCommit(domEditSelection.textFields, nextTextFields, value);+ const isLatestTextCommit = bumpDomEditCommitMapVersion(+ domTextCommitVersionRef.current,+ getDomEditTargetKey(selection),+ );+ const nextTextFields = buildNextDomTextFields(selection.textFields, value, fieldKey);+ const textCommit = planDomTextCommit(selection.textFields, nextTextFields, value);const iframe = previewIframeRef.current;const doc = iframe?.contentDocument;let editedElement: HTMLElement | null = null;@@ -289,7 +250,7 @@ export function useDomEditTextCommits({return runReportedDomEditCommit({capture: () => {if (!doc) return;- const el = findElementForSelection(doc, domEditSelection, activeCompPath);+ const el = findElementForSelection(doc, selection, activeCompPath);if (!el) return;editedElement = el;previousInnerHtml = el.innerHTML;@@ -302,42 +263,49 @@ export function useDomEditTextCommits({editedElement.textContent = value;}},- persist: async () => {- await persistDomEditOperations(domEditSelection, textCommit.operations, {+ persist: () =>+ persistDomEditOperations(selection, textCommit.operations, {label: "Edit text",skipRefresh: true,shouldSave: isLatestTextCommit,- });- },+ }),shouldRevert: () => isLatestTextCommit(),revert: () => {if (!editedElement || previousInnerHtml === null) return;editedElement.innerHTML = previousInnerHtml;},onError: (error) =>- reportDomEditPersistFailure(domEditSelection, textCommit.operations, error, showToast),+ reportDomEditPersistFailure(selection, textCommit.operations, error, showToast),shouldResync: isLatestTextCommit,resync: () =>resyncDomTextSelectionFromPreview(doc,- domEditSelection,+ selection,activeCompPath,buildDomSelectionFromTarget,applyDomSelection,),+ onFinally: isLatestTextCommit.release,});},[activeCompPath,applyDomSelection,buildDomSelectionFromTarget,- domEditSelection,persistDomEditOperations,previewIframeRef,showToast,],);+ const handleDomTextCommit = useCallback(+ (value: string, fieldKey?: string): Promise<DomEditCommitOutcome> =>+ domEditSelection+ ? handleDomTextCommitForSelection(domEditSelection, value, fieldKey)+ : Promise.resolve(domEditCommitDeclined("no-selection")),+ [domEditSelection, handleDomTextCommitForSelection],+ );+/*** Persist an element's own markup, for a text edit that styled part of it.*@@ -366,7 +334,10 @@ export function useDomEditTextCommits({// A preview reload replaces the document. Never resolve this commit onto// the replacement node: it did not own the edit or its rollback snapshot.if (!ownsCurrentPreviewElement(domEditSelection, element, doc)) return;- const isLatestTextCommit = bumpDomEditCommitVersion(domTextCommitVersionRef);+ const isLatestTextCommit = bumpDomEditCommitMapVersion(+ domTextCommitVersionRef.current,+ getDomEditTargetKey(domEditSelection),+ );const operations = [buildDomEditRichTextPatchOperation(html)];let appliedHtml = "";@@ -404,6 +375,7 @@ export function useDomEditTextCommits({buildDomSelectionFromTarget,applyDomSelection,),+ onFinally: isLatestTextCommit.release,});},[@@ -423,7 +395,10 @@ export function useDomEditTextCommits({nextTextFields: DomEditTextField[],options?: { importedFont?: ImportedFontAsset | null },) => {- const isLatestTextCommit = bumpDomEditCommitVersion(domTextCommitVersionRef);+ const isLatestTextCommit = bumpDomEditCommitMapVersion(+ domTextCommitVersionRef.current,+ getDomEditTargetKey(selection),+ );const textCommit = planDomTextCommit(selection.textFields,nextTextFields,@@ -476,6 +451,7 @@ export function useDomEditTextCommits({buildDomSelectionFromTarget,applyDomSelection,),+ onFinally: isLatestTextCommit.release,});},[@@ -579,12 +555,14 @@ export function useDomEditTextCommits({return {handleDomStyleCommit,+ handleDomStyleCommitForSelection,handleDomAttributeCommit,handleDomAttributeLiveCommit,handleDomAttributeQuietCommit,handleDomHtmlAttributeCommit,handleDomAttributesCommit,handleDomTextCommit,+ handleDomTextCommitForSelection,handleDomRichTextCommit,commitDomTextFields,handleDomTextFieldStyleCommit,diff --git a/packages/studio/src/hooks/useDomEditWiring.ts b/packages/studio/src/hooks/useDomEditWiring.tsindex a6f42f8def..7dc5261085 100644--- a/packages/studio/src/hooks/useDomEditWiring.ts+++ b/packages/studio/src/hooks/useDomEditWiring.ts@@ -223,7 +223,7 @@ export function useDomEditWiring({// ── Telemetry & fallback ──const trackGsapInteractionFailure = useGsapInteractionFailureTelemetry(activeCompPath, showToast);- const makeFetchFallback = useGsapAnimationFetchFallback(projectId, gsapSourceFile);+ const makeFetchFallback = useGsapAnimationFetchFallback(projectId);// ── GSAP selection handlers ──diff --git a/packages/studio/src/hooks/useDomSelection.ts b/packages/studio/src/hooks/useDomSelection.tsindex 8c665aca37..76ca4bca94 100644--- a/packages/studio/src/hooks/useDomSelection.ts+++ b/packages/studio/src/hooks/useDomSelection.ts@@ -210,6 +210,7 @@ export function useDomSelection({options?: {preferClipAncestor?: boolean;skipSourceProbe?: boolean;+ exactTarget?: boolean;// Override the drill-in scope (used by canvas double-click to resolve the// child inside a group before the activeGroupElement state has re-rendered).activeGroupElement?: HTMLElement | null;@@ -220,6 +221,7 @@ export function useDomSelection({isMasterView,preferClipAncestor: options?.preferClipAncestor,skipSourceProbe: options?.skipSourceProbe,+ exactTarget: options?.exactTarget,activeGroupElement:options && "activeGroupElement" in options? options.activeGroupElementdiff --git a/packages/studio/src/hooks/useDomSelectionTypes.ts b/packages/studio/src/hooks/useDomSelectionTypes.tsindex 9a5bdb6b4a..7cbb3d5a0e 100644--- a/packages/studio/src/hooks/useDomSelectionTypes.ts+++ b/packages/studio/src/hooks/useDomSelectionTypes.ts@@ -16,6 +16,8 @@ export interface ResolveDomSelectionOptions {preferClipAncestor?: boolean;skipSourceProbe?: boolean;activeGroupElement?: HTMLElement | null;+ /** Resolve this node itself instead of applying human group-capture behavior. */+ exactTarget?: boolean;}export interface UseDomSelectionParams {diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsxindex 3e0c7168d4..5269a1dfd1 100644--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.test.tsx@@ -4,6 +4,7 @@ import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { StudioFileConflictError } from "../utils/studioSaveDiagnostics";import { markStudioWriteToken, resetStudioWriteTokens } from "../utils/studioFileVersion";+import { markSelfWrite, resetSelfWriteRegistry } from "./sdkSelfWriteRegistry";import {useExternalFileChangeCoordinator,type ExternalFileChangeCoordinatorHandle,@@ -29,6 +30,7 @@ async function mountCoordinator(overrides: Partial<CoordinatorOptions> = {}) {discardPendingChanges: vi.fn(),overwriteConflict: vi.fn(async () => undefined),readProjectFile: vi.fn(async () => "external"),+ onAcceptedPersistedFileChange: vi.fn(),};const options = { ...defaults, ...overrides };const root = createRoot(document.createElement("div"));@@ -45,6 +47,7 @@ describe("external file change coordinator", () => {beforeEach(() => {handler = null;resetStudioWriteTokens();+ resetSelfWriteRegistry();vi.stubGlobal("__HF_STUDIO_HOT_TEST_ADAPTER__", {on: (_event: string, next: HotHandler) => {handler = next;@@ -67,23 +70,61 @@ describe("external file change coordinator", () => {order.push("drain");return { status: "clean" };},+ onAcceptedPersistedFileChange: () => order.push("thumbnail"),reloadPreview: () => order.push("preview"),reloadSdkSession: () => order.push("sdk"),});await act(async () => handler?.({ path: "index.html", content: "external", version: "v2" }));- expect(order).toEqual(["drain", "preview", "sdk"]);+ expect(order).toEqual(["drain", "thumbnail", "preview", "sdk"]);expect(captured.handle?.blocked).toBeNull();});- it("suppresses an exact Studio write receipt", async () => {+ it("refreshes thumbnails once but suppresses Preview reload for an exact Studio write", async () => {const drainPendingChanges = vi.fn(async () => ({ status: "clean" as const }));const reloadPreview = vi.fn();const reloadSdkSession = vi.fn();- await mountCoordinator({ drainPendingChanges, reloadPreview, reloadSdkSession });+ const onAcceptedPersistedFileChange = vi.fn();+ await mountCoordinator({+ drainPendingChanges,+ reloadPreview,+ reloadSdkSession,+ onAcceptedPersistedFileChange,+ });markStudioWriteToken("studio-write-1");+ const payload = {+ path: "index.html",+ content: "studio",+ version: "v2",+ writeToken: "studio-write-1",+ };+ await act(async () => handler?.(payload));+ await act(async () => handler?.(payload));+ expect(drainPendingChanges).not.toHaveBeenCalled();+ expect(reloadPreview).not.toHaveBeenCalled();+ expect(reloadSdkSession).not.toHaveBeenCalled();+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html");+ });++ it("accepts a matching content echo without a write token and suppresses every reload", async () => {+ const drainPendingChanges = vi.fn(async () => ({ status: "clean" as const }));+ const reloadPreview = vi.fn();+ const reloadSdkSession = vi.fn();+ const onAcceptedPersistedFileChange = vi.fn();+ await mountCoordinator({+ drainPendingChanges,+ reloadPreview,+ reloadSdkSession,+ onAcceptedPersistedFileChange,+ });+ markSelfWrite("index.html", "studio content");+await act(async () =>- handler?.({ path: "index.html", content: "studio", writeToken: "studio-write-1" }),+ handler?.({ path: "index.html", content: "studio content", version: "v2" }),);++ expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledWith("index.html");expect(drainPendingChanges).not.toHaveBeenCalled();expect(reloadPreview).not.toHaveBeenCalled();expect(reloadSdkSession).not.toHaveBeenCalled();@@ -115,15 +156,23 @@ describe("external file change coordinator", () => {attemptedContent: "studio",});const persistConflictSnapshot = vi.fn(async () => undefined);+ const onAcceptedPersistedFileChange = vi.fn();const { captured, options } = await mountCoordinator({drainPendingChanges: async () => ({ status: "conflict", error: conflict }),persistConflictSnapshot,+ onAcceptedPersistedFileChange,});await act(async () => handler?.({ path: "index.html", content: "external", version: "v2" }));expect(persistConflictSnapshot).toHaveBeenCalledWith("project-a", conflict);expect(captured.handle?.blocked).toMatchObject({ status: "conflict", error: conflict });expect(options.reloadPreview).not.toHaveBeenCalled();expect(options.reloadSdkSession).not.toHaveBeenCalled();+ expect(onAcceptedPersistedFileChange).not.toHaveBeenCalled();++ await act(async () => captured.handle?.useExternalFile());+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();+ expect(options.reloadPreview).toHaveBeenCalledOnce();+ expect(options.reloadSdkSession).toHaveBeenCalledOnce();});it("ignores stale drain completion after a newer generation", async () => {@@ -165,6 +214,7 @@ describe("external file change coordinator", () => {const failure = new Error("network unavailable");const persistFailureSnapshot = vi.fn(async () => undefined);const deleteConflictSnapshot = vi.fn(async () => undefined);+ const onAcceptedPersistedFileChange = vi.fn();const { captured } = await mountCoordinator({drainPendingChanges: vi.fn()@@ -173,6 +223,7 @@ describe("external file change coordinator", () => {getPendingCandidate: () => ({ path: "index.html", content: "final local candidate" }),persistFailureSnapshot,deleteConflictSnapshot,+ onAcceptedPersistedFileChange,});await act(async () => handler?.({ path: "index.html" }));expect(captured.handle?.blocked).toMatchObject({@@ -188,15 +239,19 @@ describe("external file change coordinator", () => {null,failure,);+ expect(onAcceptedPersistedFileChange).not.toHaveBeenCalled();await act(async () => captured.handle?.retry());expect(deleteConflictSnapshot).toHaveBeenCalledWith("project-a", "index.html");+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();});it("restores and overwrites from a durable failed draft", async () => {const overwriteConflict = vi.fn(async () => undefined);+ const onAcceptedPersistedFileChange = vi.fn();const { captured } = await mountCoordinator({recoveryFilePath: "index.html",overwriteConflict,+ onAcceptedPersistedFileChange,loadConflictSnapshot: vi.fn(async () => ({kind: "failed" as const,projectId: "project-a",@@ -217,5 +272,17 @@ describe("external file change coordinator", () => {expect(overwriteConflict).toHaveBeenCalledWith(expect.objectContaining({ attemptedContent: "recover me", currentVersion: "v2" }),);+ expect(onAcceptedPersistedFileChange).not.toHaveBeenCalled();++ markStudioWriteToken("keep-studio-write");+ await act(async () =>+ handler?.({+ path: "index.html",+ content: "recover me",+ version: "v3",+ writeToken: "keep-studio-write",+ }),+ );+ expect(onAcceptedPersistedFileChange).toHaveBeenCalledOnce();});});diff --git a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts b/packages/studio/src/hooks/useExternalFileChangeCoordinator.tsindex b1de697b09..11748c7436 100644--- a/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts+++ b/packages/studio/src/hooks/useExternalFileChangeCoordinator.ts@@ -56,6 +56,7 @@ interface ExternalFileChangeCoordinatorOptions {readProjectFile: (path: string) => Promise<string>;onUseExternalFile?: (path: string, content: string) => void;resetSaveQueues?: () => void;+ onAcceptedPersistedFileChange: (path: string) => void;}export interface ExternalFileChangeCoordinatorHandle {@@ -126,6 +127,7 @@ export function useExternalFileChangeCoordinator({readProjectFile,onUseExternalFile,resetSaveQueues,+ onAcceptedPersistedFileChange,}: ExternalFileChangeCoordinatorOptions): ExternalFileChangeCoordinatorHandle {const [blocked, setBlocked] = useState<ExternalFileChangeBlockedState | null>(null);const generationRef = useRef(0);@@ -225,21 +227,24 @@ export function useExternalFileChangeCoordinator({const content = readFileChangeContent(payload);const token = readFileChangeWriteToken(payload);logReload("file-change", { path, token: token ?? null, hasContent: content != null });- if (consumeStudioWriteToken(token)) {- logReload("suppressed", { path, why: "own write token" });- return;- }- if (content != null && isSelfWriteEcho(path, content)) {- logReload("suppressed", { path, why: "own content echo" });- return;- }-const identity = eventIdentity(path, payload);if (!allowDuplicate && identity != null && identity === lastEventIdentityRef.current) {logReload("suppressed", { path, why: "duplicate event" });return;}lastEventIdentityRef.current = identity;++ const ownWriteToken = consumeStudioWriteToken(token);+ const ownContentEcho = content != null && isSelfWriteEcho(path, content);+ if (ownWriteToken || ownContentEcho) {+ onAcceptedPersistedFileChange(path);+ logReload("suppressed", {+ path,+ why: ownWriteToken ? "own write token" : "own content echo",+ });+ return;+ }+const generation = ++generationRef.current;const result = await drainPendingChanges();if (!mountedRef.current || generation !== generationRef.current) return;@@ -258,6 +263,7 @@ export function useExternalFileChangeCoordinator({}if (!mountedRef.current || generation !== generationRef.current) return;setBlocked(null);+ onAcceptedPersistedFileChange(path);reloadAcceptedGeneration(path);return;}@@ -326,6 +332,7 @@ export function useExternalFileChangeCoordinator({persistFailureSnapshot,persistSnapshotInOrder,reloadAcceptedGeneration,+ onAcceptedPersistedFileChange,],);@@ -369,12 +376,14 @@ export function useExternalFileChangeCoordinator({onUseExternalFile?.(path, external);await deleteConflictSnapshot?.(projectId, path);setBlocked(null);+ onAcceptedPersistedFileChange(path);reloadAcceptedGeneration(path);},[deleteConflictSnapshot,discardPendingChanges,onUseExternalFile,+ onAcceptedPersistedFileChange,projectId,readProjectFile,reloadAcceptedGeneration,diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.tsindex 6bba06f913..edefdcdff9 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.test.ts@@ -1,6 +1,18 @@import { describe, expect, it } from "vitest";import type { GsapAnimation, ParsedGsap } from "@hyperframes/core/gsap-parser";-import { selectElementAnimationsOrRetry } from "./useGsapAnimationFetchFallback";+import {+ gsapSourceFileForSelection,+ selectElementAnimationsOrRetry,+} from "./useGsapAnimationFetchFallback";+import type { DomEditSelection } from "../components/editor/domEditingTypes";++describe("gsapSourceFileForSelection", () => {+ it("uses the explicit target source instead of ambient selection state", () => {+ expect(+ gsapSourceFileForSelection({ sourceFile: "compositions/card.html" } as DomEditSelection),+ ).toBe("compositions/card.html");+ });+});const anim = (targetSelector: string): GsapAnimation =>({ id: targetSelector, targetSelector, properties: {} }) as unknown as GsapAnimation;diff --git a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts b/packages/studio/src/hooks/useGsapAnimationFetchFallback.tsindex f7ad8529f1..c5e98c60c9 100644--- a/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts+++ b/packages/studio/src/hooks/useGsapAnimationFetchFallback.ts@@ -37,6 +37,10 @@ export interface GsapAnimationFetchOptions {fresh?: boolean;}+export function gsapSourceFileForSelection(selection: DomEditSelection): string {+ return selection.sourceFile || "index.html";+}+/*** Classify a parse result for one element. Differentiates a hard fetch failure* (`parsed === null`) from a warm-but-empty cold parse (`animations.length === 0`)@@ -82,7 +86,7 @@ async function fetchElementAnimationsWithRetry(}}-export function useGsapAnimationFetchFallback(projectId: string | null, gsapSourceFile: string) {+export function useGsapAnimationFetchFallback(projectId: string | null) {return useCallback((selection: DomEditSelection, options?: GsapAnimationFetchOptions) =>async (): Promise<GsapAnimation[]> => {@@ -90,12 +94,12 @@ export function useGsapAnimationFetchFallback(projectId: string | null, gsapSourconst target = { id: selection.id ?? null, selector: selection.selector ?? null };return fetchElementAnimationsWithRetry(projectId,- gsapSourceFile,+ gsapSourceFileForSelection(selection),target,options?.failOnFetchError === true,options?.fresh === true,);},- [projectId, gsapSourceFile],+ [projectId],);}diff --git a/packages/studio/src/hooks/useGsapAnimationOps.test.tsx b/packages/studio/src/hooks/useGsapAnimationOps.test.tsxnew file mode 100644index 0000000000..06e2055e69--- /dev/null+++ b/packages/studio/src/hooks/useGsapAnimationOps.test.tsx@@ -0,0 +1,101 @@+// @vitest-environment happy-dom+import { act } from "react";+import { createRoot } from "react-dom/client";+import { afterEach, describe, expect, it, vi } from "vitest";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { useGsapAnimationOps } from "./useGsapAnimationOps";++(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true;++type HookApi = ReturnType<typeof useGsapAnimationOps>;++let cleanup: (() => void) | null = null;+afterEach(() => {+ cleanup?.();+ cleanup = null;+});++const selection = { id: "box", selector: "#box" } as DomEditSelection;++function renderOps(+ commitMutationSafely: (...args: unknown[]) => Promise<void>,+ commitMutation: (...args: unknown[]) => Promise<void> = vi.fn(async () => undefined),+): HookApi {+ const captured: { api: HookApi | null } = { api: null };+ function Probe() {+ captured.api = useGsapAnimationOps({+ projectIdRef: { current: "project" },+ activeCompPath: "index.html",+ commitMutation,+ commitMutationSafely,+ showToast: vi.fn(),+ sdkSession: null,+ sdkDeps: null,+ });+ return null;+ }++ const root = createRoot(document.createElement("div"));+ act(() => root.render(<Probe />));+ cleanup = () => act(() => root.unmount());+ if (!captured.api) throw new Error("hook did not initialize");+ return captured.api;+}++function deferredCommit() {+ let release!: () => void;+ const promise = new Promise<void>((resolve) => {+ release = resolve;+ });+ return { commitMutationSafely: vi.fn(() => promise), release };+}++describe("useGsapAnimationOps settlement", () => {+ it.each([+ ["update", (api: HookApi) => api.updateGsapMeta(selection, "anim-1", { duration: 2 })],+ ["delete", (api: HookApi) => api.deleteGsapAnimation(selection, "anim-1")],+ ])("keeps %s pending until the shared preview synchronizer settles", async (_name, run) => {+ const deferred = deferredCommit();+ const api = renderOps(deferred.commitMutationSafely);+ let settled = false;++ const resultPromise = run(api).then(() => {+ settled = true;+ });+ await Promise.resolve();+ expect(settled).toBe(false);++ deferred.release();+ await resultPromise;+ expect(settled).toBe(true);+ });++ it("soft-reloads the preview when adding an animation", async () => {+ const commitMutation = vi.fn(async () => undefined);+ const api = renderOps(+ vi.fn(async () => undefined),+ commitMutation,+ );++ await api.addGsapAnimation(selection, "from");++ expect(commitMutation).toHaveBeenCalledWith(+ selection,+ expect.objectContaining({ type: "add" }),+ expect.objectContaining({ softReload: true }),+ );+ });++ it("soft-reloads the preview when deleting an animation", async () => {+ const commitMutationSafely = vi.fn(async () => undefined);+ const api = renderOps(commitMutationSafely);++ await api.deleteGsapAnimation(selection, "anim-1");++ expect(commitMutationSafely).toHaveBeenCalledWith(+ selection,+ expect.objectContaining({ type: "delete" }),+ expect.objectContaining({ softReload: true }),+ );+ });+});diff --git a/packages/studio/src/hooks/useGsapAnimationOps.ts b/packages/studio/src/hooks/useGsapAnimationOps.tsindex 260c5cac1c..95f9ea97ec 100644--- a/packages/studio/src/hooks/useGsapAnimationOps.ts+++ b/packages/studio/src/hooks/useGsapAnimationOps.ts@@ -55,7 +55,7 @@ export function useGsapAnimationOps({);if (cutoverCommittedOrThrow(handled)) return;}- commitMutationSafely(+ return commitMutationSafely(selection,{ type: "update-meta", animationId, updates },{ label: "Edit GSAP animation", coalesceKey: `gsap:${animationId}:meta`, softReload: true },@@ -77,10 +77,10 @@ export function useGsapAnimationOps({);if (cutoverCommittedOrThrow(handled)) return;}- commitMutationSafely(+ return commitMutationSafely(selection,{ type: "delete", animationId, stripStudioEdits: true },- { label: "Delete GSAP animation" },+ { label: "Delete GSAP animation", softReload: true },);},[commitMutationSafely, activeCompPath, sdkSession, sdkDeps],@@ -178,7 +178,7 @@ export function useGsapAnimationOps({properties: toDefaults[method] ?? { opacity: 1 },fromProperties: method === "fromTo" ? { opacity: 0 } : undefined,},- { label: `Add GSAP ${method} animation` },+ { label: `Add GSAP ${method} animation`, softReload: true },);},[activeCompPath, commitMutation, projectIdRef, showToast, sdkSession, sdkDeps],diff --git a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx b/packages/studio/src/hooks/useGsapAwareEditing.test.tsxindex 9d16157b2d..4997a10901 100644--- a/packages/studio/src/hooks/useGsapAwareEditing.test.tsx+++ b/packages/studio/src/hooks/useGsapAwareEditing.test.tsx@@ -45,7 +45,10 @@ afterEach(() => {vi.clearAllMocks();});-function mountResizeHandler(animations: GsapAnimation[]) {+function mountResizeHandler(+ animations: GsapAnimation[],+ targetAnimations: GsapAnimation[] = animations,+) {const element = document.createElement("div");const selection = { element, id: "clip", selector: "#clip" } as unknown as DomEditSelection;const fallback = vi.fn().mockResolvedValue(undefined);@@ -66,7 +69,7 @@ function mountResizeHandler(animations: GsapAnimation[]) {previewIframeRef: { current: null },showToast: vi.fn(),bumpGsapCache: vi.fn(),- makeFetchFallback: () => vi.fn().mockResolvedValue(animations),+ makeFetchFallback: () => vi.fn().mockResolvedValue(targetAnimations),trackGsapInteractionFailure: vi.fn(),handleDomBoxSizeCommit: fallback,addGsapAnimation: vi.fn(),@@ -112,6 +115,31 @@ function mountGroupHandler({}describe("useGsapAwareEditing anchored resize", () => {+ it("uses the explicit target's animations instead of the human selection cache", async () => {+ const humanAnimation = { id: "human", propertyGroup: "scale" } as GsapAnimation;+ const targetAnimation = { id: "target", propertyGroup: "size" } as GsapAnimation;+ mocks.resize.mockResolvedValue({ status: "persisted" });+ const h = mountResizeHandler([humanAnimation], [targetAnimation]);+ const target = {+ ...h.selection,+ element: document.createElement("div"),+ id: "agent-target",+ selector: "#agent-target",+ } as DomEditSelection;++ await act(() => h.resize(target, { width: 300, height: 200 }));++ expect(mocks.resize).toHaveBeenCalledWith(+ target,+ { width: 300, height: 200 },+ [targetAnimation],+ null,+ expect.any(Function),+ expect.any(Function),+ );+ act(() => h.root.unmount());+ });+it("rejects a blocked resize instead of falling through to a competing DOM write", async () => {mocks.resize.mockResolvedValue({ status: "blocked", reason: "source-uneditable" });const h = mountResizeHandler([]);diff --git a/packages/studio/src/hooks/useGsapAwareEditing.ts b/packages/studio/src/hooks/useGsapAwareEditing.tsindex 384527f5fb..ea1e2accd3 100644--- a/packages/studio/src/hooks/useGsapAwareEditing.ts+++ b/packages/studio/src/hooks/useGsapAwareEditing.ts@@ -125,6 +125,14 @@ export function useGsapAwareEditing({}: UseGsapAwareEditingParams) {// ── GSAP-aware geometry commits ──+ const getGsapAnimationsForSelection = useCallback(+ (selection: DomEditSelection): GsapAnimation[] | Promise<GsapAnimation[]> => {+ if (domEditSelection?.element === selection.element) return selectedGsapAnimations;+ return makeFetchFallback(selection, { failOnFetchError: true })();+ },+ [domEditSelection, selectedGsapAnimations, makeFetchFallback],+ );+const handleGsapAwarePathOffsetCommit = useCallback(async (selection: DomEditSelection,@@ -133,10 +141,14 @@ export function useGsapAwareEditing({) => {if (gsapCommitMutation) {try {+ const ownedAnimations = getGsapAnimationsForSelection(selection);+ const targetAnimations = Array.isArray(ownedAnimations)+ ? ownedAnimations+ : await ownedAnimations;const outcome = await tryGsapDragIntercept(selection,next,- selectedGsapAnimations,+ targetAnimations,previewIframeRef.current,gsapCommitMutation,makeFetchFallback(selection),@@ -150,11 +162,11 @@ export function useGsapAwareEditing({}},[- selectedGsapAnimations,gsapCommitMutation,previewIframeRef,makeFetchFallback,trackGsapInteractionFailure,+ getGsapAnimationsForSelection,],);@@ -286,7 +298,11 @@ export function useGsapAwareEditing({offset?: { x: number; y: number },restore: () => void = () => undefined,) => {- const scaleRoute = selectedGsapAnimations.some((anim) => anim.propertyGroup === "scale");+ const ownedAnimations = getGsapAnimationsForSelection(selection);+ const targetAnimations = Array.isArray(ownedAnimations)+ ? ownedAnimations+ : await ownedAnimations;+ const scaleRoute = targetAnimations.some((anim) => anim.propertyGroup === "scale");const selector = selectorFromSelection(selection);const hasLivePositionTween = selector? hasNonHoldTweenForElement(@@ -300,8 +316,8 @@ export function useGsapAwareEditing({next,offset: offset ?? null,scaleRoute,- animCount: selectedGsapAnimations.length,- animGroups: selectedGsapAnimations.map((a) => `${a.propertyGroup}:${a.method}`),+ animCount: targetAnimations.length,+ animGroups: targetAnimations.map((a) => `${a.propertyGroup}:${a.method}`),});return runGestureTransaction({element: selection.element,@@ -325,7 +341,7 @@ export function useGsapAwareEditing({const outcome = await tryGsapResizeIntercept(selection,next,- selectedGsapAnimations,+ targetAnimations,previewIframeRef.current,commitMutation,makeFetchFallback(selection),@@ -349,7 +365,7 @@ export function useGsapAwareEditing({const dragOutcome = await tryGsapDragIntercept(selection,offset,- selectedGsapAnimations,+ targetAnimations,previewIframeRef.current,commitMutation,makeFetchFallback(selection),@@ -377,11 +393,11 @@ export function useGsapAwareEditing({},[handleDomBoxSizeCommit,- selectedGsapAnimations,gsapCommitMutation,previewIframeRef,makeFetchFallback,trackGsapInteractionFailure,+ getGsapAnimationsForSelection,],);@@ -389,6 +405,10 @@ export function useGsapAwareEditing({async (selection: DomEditSelection, next: { angle: number }) => {if (gsapCommitMutation) {try {+ const ownedAnimations = getGsapAnimationsForSelection(selection);+ const targetAnimations = Array.isArray(ownedAnimations)+ ? ownedAnimations+ : await ownedAnimations;// Single source of truth for rotation too: tryGsapRotationIntercept handles// tweened elements (keyframes) and static ones (a tl.set), so there's no// CSS-var fallback. Selectorless/computed source rejects so the gesture@@ -396,7 +416,7 @@ export function useGsapAwareEditing({const outcome = await tryGsapRotationIntercept(selection,next.angle,- selectedGsapAnimations,+ targetAnimations,previewIframeRef.current,gsapCommitMutation,makeFetchFallback(selection),@@ -409,11 +429,11 @@ export function useGsapAwareEditing({}},[- selectedGsapAnimations,gsapCommitMutation,previewIframeRef,makeFetchFallback,trackGsapInteractionFailure,+ getGsapAnimationsForSelection,],);@@ -507,6 +527,7 @@ export function useGsapAwareEditing({}, [commitMutation]);return {+ getGsapAnimationsForSelection,handleGsapAwarePathOffsetCommit,handleGsapAwareGroupPathOffsetCommit,handleGsapAwareBoxSizeCommit,diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsxindex b20423876a..6317c2b249 100644--- a/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.test.tsx@@ -113,7 +113,9 @@ describe("useGsapSelectionHandlers save failures", () => {makeParams({ addGsapAnimation: vi.fn().mockRejectedValue(error), showToast }),);- act(() => rendered.handlers().handleGsapAddAnimation("to"));+ act(() => {+ void rendered.handlers().handleGsapAddAnimation("to");+ });await flushRejection();expect(showToast).not.toHaveBeenCalled();diff --git a/packages/studio/src/hooks/useGsapSelectionHandlers.ts b/packages/studio/src/hooks/useGsapSelectionHandlers.tsindex 9b39cd1ecb..6479061cd5 100644--- a/packages/studio/src/hooks/useGsapSelectionHandlers.ts+++ b/packages/studio/src/hooks/useGsapSelectionHandlers.ts@@ -200,8 +200,13 @@ export function useGsapSelectionHandlers({const handleGsapDeleteAnimation = useCallback((animId: string, selectionOverride?: DomEditSelection | null) => {const sel = resolveWriteSelection(selectionOverride);- if (!sel) return;- observeGsapMutation(deleteGsapAnimation(sel, animId), sel, "delete", "Delete GSAP animation");+ if (!sel) return Promise.resolve(false);+ return observeGsapMutation(+ deleteGsapAnimation(sel, animId),+ sel,+ "delete",+ "Delete GSAP animation",+ );},[resolveWriteSelection, deleteGsapAnimation, observeGsapMutation],);@@ -222,20 +227,25 @@ export function useGsapSelectionHandlers({);const handleGsapAddAnimation = useCallback(- (method: "to" | "from" | "set" | "fromTo") => {- if (!domEditSelection) return;- void addGsapAnimation(domEditSelection, method, usePlayerStore.getState().currentTime).catch(- (error) => {- trackGsapHandlerFailure(error, domEditSelection, "add", `Add GSAP ${method} animation`);- },+ (method: "to" | "from" | "set" | "fromTo", selectionOverride?: DomEditSelection | null) => {+ const selection = resolveWriteSelection(selectionOverride);+ if (!selection) return Promise.resolve(false);+ const landed = observeGsapMutation(+ addGsapAnimation(selection, method, usePlayerStore.getState().currentTime),+ selection,+ "add",+ `Add GSAP ${method} animation`,);- if (domEditSelection.element.hasAttribute("data-hf-studio-path-offset")) {+ if (selection.element.hasAttribute("data-hf-studio-path-offset")) {// The reset owns rollback and the position commit already owns user and// telemetry reporting. This is only the fire-and-forget UI boundary.- void handleDomManualEditsReset(domEditSelection).catch(() => undefined);+ void landed.then((didLand) => {+ if (didLand) void handleDomManualEditsReset(selection).catch(() => undefined);+ });}+ return landed;},- [domEditSelection, addGsapAnimation, handleDomManualEditsReset, trackGsapHandlerFailure],+ [resolveWriteSelection, addGsapAnimation, handleDomManualEditsReset, observeGsapMutation],);const handleGsapAddProperty = useCallback(diff --git a/packages/studio/src/hooks/useRenderClipContent.test.ts b/packages/studio/src/hooks/useRenderClipContent.test.tsindex 5b85989ad6..b7131e046e 100644--- a/packages/studio/src/hooks/useRenderClipContent.test.ts+++ b/packages/studio/src/hooks/useRenderClipContent.test.ts@@ -241,4 +241,31 @@ describe("useRenderClipContent", () => {});}});++ it("forwards persisted content revision to mounted composition thumbnails", () => {+ usePlayerStore.setState({+ thumbnailMode: "adaptive",+ timelineSessionEpoch: 7,+ thumbnailContentRevision: 11,+ });++ const content = renderClipContent({+ id: "nested",+ tag: "div",+ start: 0,+ duration: 4,+ track: 0,+ compositionSrc: "compositions/nested.html",+ });++ expect(isValidElement(content)).toBe(true);+ if (isValidElement(content)) {+ expect(content.type).toBe(CompositionThumbnail);+ expect(content.props).toMatchObject({+ projectId: "my-project",+ sessionEpoch: 7,+ contentRevision: 11,+ });+ }+ });});diff --git a/packages/studio/src/hooks/useRenderClipContent.ts b/packages/studio/src/hooks/useRenderClipContent.tsindex cbd3c6934f..7d4f7b1579 100644--- a/packages/studio/src/hooks/useRenderClipContent.ts+++ b/packages/studio/src/hooks/useRenderClipContent.ts@@ -110,6 +110,7 @@ export function useRenderClipContent({const thumbnailMode = usePlayerStore((s) => s.thumbnailMode);const effectiveMode = effectiveThumbnailMode(thumbnailMode);const sessionEpoch = usePlayerStore((s) => s.timelineSessionEpoch);+ const contentRevision = usePlayerStore((s) => s.thumbnailContentRevision);return useCallback(// Pre-existing clip-content dispatcher; reduced by extracting renderAudioClip.// fallow-ignore-next-line complexity@@ -153,6 +154,7 @@ export function useRenderClipContent({duration: el.duration,projectId: pid,sessionEpoch,+ contentRevision,priority: context.priority,rich: context.rich,});@@ -179,6 +181,7 @@ export function useRenderClipContent({duration: el.duration,projectId: pid,sessionEpoch,+ contentRevision,priority: context.priority,rich: context.rich,});@@ -232,6 +235,7 @@ export function useRenderClipContent({duration: el.duration,projectId: pid,sessionEpoch,+ contentRevision,priority: context.priority,rich: context.rich,});@@ -246,6 +250,7 @@ export function useRenderClipContent({effectiveTimelineDuration,effectiveMode,sessionEpoch,+ contentRevision,],);}diff --git a/packages/studio/src/hooks/useStudioExternalFileChanges.ts b/packages/studio/src/hooks/useStudioExternalFileChanges.tsindex 57ccd9b825..0469c9abbf 100644--- a/packages/studio/src/hooks/useStudioExternalFileChanges.ts+++ b/packages/studio/src/hooks/useStudioExternalFileChanges.ts@@ -1,4 +1,5 @@import { useCallback, type MutableRefObject } from "react";+import { usePlayerStore } from "../player/store/playerStore";import {deleteExternalConflictSnapshot,loadExternalConflictSnapshot,@@ -48,6 +49,9 @@ export function useStudioExternalFileChanges({}: UseStudioExternalFileChangesOptions) {const { flushPendingSourceSave, discardPendingSourceSave } = fileManager;const { drainPendingDomEditSaves, resetDomEditSaveQueueBreaker } = previewPersistence;+ const bumpThumbnailContentRevision = usePlayerStore(+ (state) => state.bumpThumbnailContentRevision,+ );const drainPendingChanges = useCallback(async () => {const source = await flushPendingSourceSave();if (source.status !== "clean") return source;@@ -77,5 +81,6 @@ export function useStudioExternalFileChanges({readProjectFile: fileManager.readProjectFile,onUseExternalFile: fileManager.updateEditingFileContent,resetSaveQueues: resetDomEditSaveQueueBreaker,+ onAcceptedPersistedFileChange: bumpThumbnailContentRevision,});}diff --git a/packages/studio/src/player/components/CompositionThumbnail.test.ts b/packages/studio/src/player/components/CompositionThumbnail.test.tsindex f9a3e986ca..d6240a0e7a 100644--- a/packages/studio/src/player/components/CompositionThumbnail.test.ts+++ b/packages/studio/src/player/components/CompositionThumbnail.test.ts@@ -73,7 +73,7 @@ describe("buildCompositionThumbnailUrl", () => {origin: "http://localhost:3000",}),).toBe(- "http://localhost:3000/api/projects/demo/thumbnail/index.html?t=2.00&v=v3&selector=.card&selectorIndex=2",+ "http://localhost:3000/api/projects/demo/thumbnail/index.html?t=2.00&v=v3&revision=0&selector=.card&selectorIndex=2",);});@@ -91,6 +91,16 @@ describe("buildCompositionThumbnailUrl", () => {"output=storyboard",);});++ it("includes the persisted content revision in the cache identity", () => {+ const url = buildCompositionThumbnailUrl({+ previewUrl: "/api/projects/demo/preview",+ origin: "http://localhost:3000",+ contentRevision: 7,+ });++ expect(new URL(url).searchParams.get("revision")).toBe("7");+ });});describe("CompositionThumbnail", () => {@@ -148,4 +158,59 @@ describe("CompositionThumbnail", () => {expect(probe.src).toBe("");expect(URL.revokeObjectURL).toHaveBeenCalledWith("blob:composition-thumbnail");});++ it("releases the old request and ignores its late result when persisted content changes", async () => {+ const signals: AbortSignal[] = [];+ const resolveFetches: Array<(response: Response) => void> = [];+ globalThis.fetch = vi.fn((_url, init) => {+ signals.push(init?.signal as AbortSignal);+ return new Promise<Response>((resolve) => resolveFetches.push(resolve));+ });+ root = createRoot(host);++ await act(async () => {+ root!.render(+ React.createElement(CompositionThumbnail, {+ previewUrl: "/api/projects/demo/preview",+ label: "",+ labelColor: "#fff",+ projectId: "demo",+ contentRevision: 0,+ }),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ await act(async () => {+ root!.render(+ React.createElement(CompositionThumbnail, {+ previewUrl: "/api/projects/demo/preview",+ label: "",+ labelColor: "#fff",+ projectId: "demo",+ contentRevision: 1,+ }),+ );+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(globalThis.fetch).toHaveBeenCalledTimes(2);+ expect(signals[0]?.aborted).toBe(true);+ expect(signals[1]?.aborted).toBe(false);+ expect((globalThis.fetch as ReturnType<typeof vi.fn>).mock.calls[1]?.[0]).toContain(+ "revision=1",+ );++ await act(async () => {+ resolveFetches[0]?.(new Response(new Blob(["stale"]), { status: 200 }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ expect(MockImage.instances).toHaveLength(0);++ await act(async () => {+ resolveFetches[1]?.(new Response(new Blob(["fresh"]), { status: 200 }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ });+ expect(MockImage.instances).toHaveLength(1);+ expect(MockImage.instances[0]?.src).toBe("blob:composition-thumbnail");+ });});diff --git a/packages/studio/src/player/components/CompositionThumbnail.tsx b/packages/studio/src/player/components/CompositionThumbnail.tsxindex 301206ec37..ddb571dcd2 100644--- a/packages/studio/src/player/components/CompositionThumbnail.tsx+++ b/packages/studio/src/player/components/CompositionThumbnail.tsx@@ -17,6 +17,7 @@ interface CompositionThumbnailProps {height?: number;projectId?: string;sessionEpoch?: number;+ contentRevision?: number;priority?: ThumbnailPriority;rich?: boolean;}@@ -32,6 +33,7 @@ export function buildCompositionThumbnailUrl({selectorIndex,origin,output,+ contentRevision = 0,}: {previewUrl: string;seekTime?: number;@@ -46,6 +48,7 @@ export function buildCompositionThumbnailUrl({* high-density review size; `"source"` uses the composition's own dimensions.*/output?: "source" | "storyboard";+ contentRevision?: number;}): string {const thumbnailBase = previewUrl.replace("/preview/comp/", "/thumbnail/")@@ -53,6 +56,7 @@ export function buildCompositionThumbnailUrl({const thumbnailUrl = new URL(thumbnailBase, origin);thumbnailUrl.searchParams.set("t", (seekTime + duration / 2).toFixed(2));thumbnailUrl.searchParams.set("v", THUMBNAIL_URL_VERSION);+ thumbnailUrl.searchParams.set("revision", String(contentRevision));if (output) thumbnailUrl.searchParams.set("output", output);if (selector) {thumbnailUrl.searchParams.set("selector", selector);@@ -96,6 +100,7 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({duration = 5,projectId = previewUrl,sessionEpoch = 0,+ contentRevision = 0,priority = "visible",}: CompositionThumbnailProps) {const [containerWidth, setContainerWidth] = useState(0);@@ -107,6 +112,7 @@ export const CompositionThumbnail = memo(function CompositionThumbnail({selector,selectorIndex,origin: window.location.origin,+ contentRevision,});const request = useMemo(() => ({diff --git a/packages/studio/src/player/store/playerStore.test.ts b/packages/studio/src/player/store/playerStore.test.tsindex 7f471e9089..951468d1c9 100644--- a/packages/studio/src/player/store/playerStore.test.ts+++ b/packages/studio/src/player/store/playerStore.test.ts@@ -30,6 +30,30 @@ describe("usePlayerStore", () => {});});+ describe("thumbnail content revision", () => {+ it("advances once per accepted persisted file event", () => {+ const before = usePlayerStore.getState().thumbnailContentRevision;++ usePlayerStore.getState().bumpThumbnailContentRevision();++ expect(usePlayerStore.getState().thumbnailContentRevision).toBe(before + 1);+ });++ it("remains monotonic across soft resets while project identity stays with the session epoch", () => {+ const store = usePlayerStore.getState();+ store.beginTimelineSession("project-a");+ store.bumpThumbnailContentRevision();+ const revision = usePlayerStore.getState().thumbnailContentRevision;+ const firstEpoch = usePlayerStore.getState().timelineSessionEpoch;++ store.reset();+ expect(usePlayerStore.getState().thumbnailContentRevision).toBe(revision);+ store.beginTimelineSession("project-b");+ expect(usePlayerStore.getState().thumbnailContentRevision).toBe(revision);+ expect(usePlayerStore.getState().timelineSessionEpoch).toBe(firstEpoch + 1);+ });+ });+describe("expandedClipIds", () => {it("toggles clip membership", () => {const store = usePlayerStore.getState();diff --git a/packages/studio/src/player/store/thumbnailSlice.ts b/packages/studio/src/player/store/thumbnailSlice.tsindex 26aa469839..42b3717124 100644--- a/packages/studio/src/player/store/thumbnailSlice.ts+++ b/packages/studio/src/player/store/thumbnailSlice.ts@@ -4,15 +4,21 @@ import { defaultThumbnailMode, type ThumbnailMode } from "../lib/thumbnailPolicyexport interface ThumbnailSlice {thumbnailMode: ThumbnailMode;+ /** Monotonic identity for persisted project content shown by mounted thumbnails. */+ thumbnailContentRevision: number;setThumbnailMode: (mode: ThumbnailMode) => void;+ bumpThumbnailContentRevision: () => void;}export function createThumbnailSlice(set: StoreApi<ThumbnailSlice>["setState"]): ThumbnailSlice {return {thumbnailMode: defaultThumbnailMode(readStudioUiPreferences().thumbnailMode),+ thumbnailContentRevision: 0,setThumbnailMode: (mode) => {writeStudioUiPreferences({ thumbnailMode: mode });set({ thumbnailMode: mode });},+ bumpThumbnailContentRevision: () =>+ set((state) => ({ thumbnailContentRevision: state.thumbnailContentRevision + 1 })),};}diff --git a/packages/studio/src/styles/studio.css b/packages/studio/src/styles/studio.cssindex 7e0fe46e14..d5f777bd98 100644--- a/packages/studio/src/styles/studio.css+++ b/packages/studio/src/styles/studio.css@@ -618,6 +618,185 @@ body {}}+/* Receipt-driven WebMCP Topology Lens. Every animation is one-shot Studio+ chrome; none of these nodes enter the composition iframe or rendered output. */+.hf-topology-contour {+ border: 1px solid rgba(60, 230, 172, 0.62);+ box-shadow:+ 0 0 0 1px rgba(6, 227, 250, 0.08),+ inset 0 0 18px rgba(60, 230, 172, 0.035);+}++.hf-topology-field::before,+.hf-topology-contour::before,+.hf-topology-target::before {+ content: attr(data-topology-node);+ position: absolute;+ top: 2px;+ left: 3px;+ z-index: 2;+ padding: 1px 3px;+ border-radius: 2px;+ background: rgba(5, 15, 12, 0.86);+ color: rgb(90, 247, 193);+ font:+ 600 7px/1.3 ui-monospace,+ SFMono-Regular,+ Menlo,+ Monaco,+ Consolas,+ monospace;+ letter-spacing: 0.04em;+ text-transform: lowercase;+}++.hf-topology-field {+ z-index: 0;+ border: 1px solid rgba(60, 230, 172, 0.28);+ background: linear-gradient(+ 90deg,+ rgba(60, 230, 172, 0.025),+ rgba(60, 230, 172, 0.1) 68%,+ rgba(6, 227, 250, 0.06)+ );+ box-shadow: inset 0 0 28px rgba(60, 230, 172, 0.05);+}++.hf-topology-target {+ border: 1px solid rgba(60, 230, 172, 0.82);+ box-shadow:+ 0 0 0 1px rgba(60, 230, 172, 0.14),+ 0 0 18px rgba(6, 227, 250, 0.09);+}++.hf-topology-scan {+ background: linear-gradient(+ 90deg,+ transparent,+ rgba(60, 230, 172, 0.16) 55%,+ rgba(230, 255, 247, 0.9)+ );+ clip-path: polygon(0 0, 100% 0, 72% 100%, 0 100%);+}++.hf-topology-seal {+ filter: drop-shadow(0 0 6px rgba(60, 230, 172, 0.36));+}++@media (prefers-reduced-motion: no-preference) {+ .hf-topology-contour {+ animation: hf-topology-reveal 176ms cubic-bezier(0.77, 0, 0.175, 1) both;+ }++ .hf-topology-field[data-topology-phase="acquiring"] {+ animation: hf-topology-reveal 240ms cubic-bezier(0.77, 0, 0.175, 1) both;+ }++ .hf-topology-scan {+ animation: hf-topology-scan 224ms cubic-bezier(0.77, 0, 0.175, 1) both;+ }++ .hf-topology-target[data-topology-phase="acquiring"] {+ animation: hf-topology-localize 224ms cubic-bezier(0.23, 1, 0.32, 1) 72ms both;+ }++ .hf-topology-target[data-topology-phase="localizing"] {+ animation: hf-topology-localize 176ms cubic-bezier(0.23, 1, 0.32, 1) both;+ }++ .hf-topology-target[data-topology-phase="sealing"] {+ animation: hf-topology-localize 144ms cubic-bezier(0.23, 1, 0.32, 1) both;+ }++ .hf-topology-seal {+ animation: hf-topology-seal 224ms cubic-bezier(0.23, 1, 0.32, 1) both;+ }++ .hf-topology-seal path:first-of-type {+ animation: hf-topology-seal-left 224ms cubic-bezier(0.23, 1, 0.32, 1) both;+ }++ .hf-topology-seal path:nth-of-type(2) {+ animation: hf-topology-seal-right 224ms cubic-bezier(0.23, 1, 0.32, 1) both;+ }+}++@keyframes hf-topology-reveal {+ from {+ opacity: 0;+ clip-path: inset(0 100% 0 0);+ }+ to {+ opacity: 1;+ clip-path: inset(0);+ }+}++@keyframes hf-topology-scan {+ from {+ opacity: 0;+ transform: translate3d(-100%, 0, 0);+ }+ 16% {+ opacity: 1;+ }+ to {+ opacity: 0;+ transform: translate3d(400%, 0, 0);+ }+}++@keyframes hf-topology-localize {+ from {+ opacity: 0;+ transform: scaleX(0.76);+ }+ to {+ opacity: 1;+ transform: scaleX(1);+ }+}++@keyframes hf-topology-seal {+ from {+ opacity: 0;+ transform: scale(0.88);+ }+ to {+ opacity: 1;+ transform: scale(1);+ }+}++@keyframes hf-topology-seal-left {+ from {+ transform: translate3d(-9px, 0, 0);+ }+ to {+ transform: translate3d(0, 0, 0);+ }+}++@keyframes hf-topology-seal-right {+ from {+ transform: translate3d(9px, 0, 0);+ }+ to {+ transform: translate3d(0, 0, 0);+ }+}++@media (prefers-reduced-motion: reduce) {+ .hf-topology-contour,+ .hf-topology-field,+ .hf-topology-target,+ .hf-topology-seal,+ .hf-topology-seal path {+ animation: none;+ transform: none;+ }+}+@keyframes hf-fx-preset-wave {0%,100% {diff --git a/packages/studio/src/utils/domEditSaveQueue.test.ts b/packages/studio/src/utils/domEditSaveQueue.test.tsindex f1166f7ee0..cb08d771b4 100644--- a/packages/studio/src/utils/domEditSaveQueue.test.ts+++ b/packages/studio/src/utils/domEditSaveQueue.test.ts@@ -51,7 +51,7 @@ describe("dom edit save queue", () => {queue.destroy();});- it("keeps an open breaker paused even when already queued work succeeds", async () => {+ it("stops already queued work when the preceding save opens the breaker", async () => {const onOpen = vi.fn();const onReset = vi.fn();const queue = createDomEditSaveQueue({@@ -72,13 +72,15 @@ describe("dom edit save queue", () => {resolveFirstStarted?.();}),);- const second = queue.enqueue(async () => {});+ const secondSave = vi.fn(async () => undefined);+ const second = queue.enqueue(secondSave);await firstStarted;expect(rejectFirst).toBeTypeOf("function");rejectFirst?.(new StudioSaveHttpError("Server down", 503));await expect(first).rejects.toThrow("Server down");- await expect(second).resolves.toBeUndefined();+ await expect(second).rejects.toThrow("Auto-save is paused");+ expect(secondSave).not.toHaveBeenCalled();expect(onOpen).toHaveBeenCalledOnce();expect(onReset).not.toHaveBeenCalled();diff --git a/packages/studio/src/utils/domEditSaveQueue.ts b/packages/studio/src/utils/domEditSaveQueue.tsindex 280c8dadd0..eb9ad868c7 100644--- a/packages/studio/src/utils/domEditSaveQueue.ts+++ b/packages/studio/src/utils/domEditSaveQueue.ts@@ -81,7 +81,12 @@ export function createDomEditSaveQueue(options: DomEditSaveQueueOptions = {}): Dreturn {enqueue(save) {if (breakerOpen) return Promise.reject(new DomEditSaveQueueOpenError());- const queued = tail.catch(() => undefined).then(() => run(save));+ const queued = tail+ .catch(() => undefined)+ .then(() => {+ if (breakerOpen) throw new DomEditSaveQueueOpenError();+ return run(save);+ });tail = queued.then(() => undefined,() => undefined,diff --git a/packages/studio/src/webmcp/StudioAgentTools.test.ts b/packages/studio/src/webmcp/StudioAgentTools.test.tsnew file mode 100644index 0000000000..296ef969d0--- /dev/null+++ b/packages/studio/src/webmcp/StudioAgentTools.test.ts@@ -0,0 +1,70 @@+// @vitest-environment jsdom+import { describe, expect, it } from "vitest";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { vi } from "vitest";+import { readLiveSelectionBox, resizeSelectionFromAgent } from "./StudioAgentTools";++function rect(width: number, height: number): DOMRect {+ return { x: 10, y: 20, width, height } as DOMRect;+}++describe("readLiveSelectionBox", () => {+ it("measures the replacement preview node after a commit reload", () => {+ const oldElement = document.createElement("h1");+ oldElement.id = "headline";+ oldElement.getBoundingClientRect = () => rect(300, 50);+ const selection = {+ id: "headline",+ sourceFile: "index.html",+ element: oldElement,+ } as DomEditSelection;++ const liveDocument = document.implementation.createHTMLDocument();+ const replacement = liveDocument.createElement("h1");+ replacement.id = "headline";+ replacement.getBoundingClientRect = () => rect(280, 60);+ liveDocument.body.append(replacement);++ expect(readLiveSelectionBox(liveDocument, selection, "index.html")).toEqual({+ x: 10,+ y: 20,+ width: 280,+ height: 60,+ });+ });++ it("does not hide a stale target behind its detached old node", () => {+ const oldElement = document.createElement("h1");+ oldElement.id = "headline";+ const selection = {+ id: "headline",+ sourceFile: "index.html",+ element: oldElement,+ } as DomEditSelection;+ const liveDocument = document.implementation.createHTMLDocument();++ expect(() => readLiveSelectionBox(liveDocument, selection, "index.html")).toThrow(+ "target is missing",+ );+ });+});++describe("resizeSelectionFromAgent", () => {+ it("applies the same live draft a pointer gesture shows before persistence", async () => {+ const element = document.createElement("div");+ element.style.width = "300px";+ element.style.height = "50px";+ const selection = { element } as DomEditSelection;+ const commit = vi.fn(async (_selection, _next, _offset, restore: () => void) => {+ expect(element.style.width).toBe("280px");+ expect(element.style.height).toBe("60px");+ restore();+ });++ await resizeSelectionFromAgent(selection, { width: 280, height: 60 }, commit);++ expect(commit).toHaveBeenCalledOnce();+ expect(element.style.width).toBe("300px");+ expect(element.style.height).toBe("50px");+ });+});diff --git a/packages/studio/src/webmcp/StudioAgentTools.tsx b/packages/studio/src/webmcp/StudioAgentTools.tsxindex bdfa2cba31..0b20cb0696 100644--- a/packages/studio/src/webmcp/StudioAgentTools.tsx+++ b/packages/studio/src/webmcp/StudioAgentTools.tsx@@ -1,9 +1,49 @@-import { useCallback, useMemo } from "react";+import { useCallback, useEffect, useMemo } from "react";import { useDomEditActionsContext, useDomEditSelectionContext } from "../contexts/DomEditContext";import { useStudioShellContext } from "../contexts/StudioContext";import { usePlayerStore } from "../player";import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";-import type { StudioLookSnapshot } from "./tools/lookTools";+import { collectStudioLookScene, type StudioLookSnapshot } from "./tools/lookTools";+import { studioEditLifecycle } from "./writeCoordinator";+import { findElementForSelection } from "../components/editor/domEditingElement";+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import {+ applyStudioBoxSizeDraft,+ captureStudioBoxSize,+ restoreStudioBoxSize,+} from "../components/editor/manualEdits";++export function readLiveSelectionBox(+ doc: Document | null | undefined,+ selection: DomEditSelection,+ activeCompositionPath: string | null,+) {+ const liveElement = doc+ ? findElementForSelection(doc, selection, activeCompositionPath)+ : selection.element;+ if (!liveElement) throw new Error("the target is missing from the current Studio preview");+ const rect = liveElement.getBoundingClientRect();+ return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };+}++type ResizeCommit = (+ selection: DomEditSelection,+ next: { width: number; height: number },+ offset?: { x: number; y: number },+ restore?: () => void,+) => Promise<void>;++export function resizeSelectionFromAgent(+ selection: DomEditSelection,+ next: { width: number; height: number },+ commit: ResizeCommit,+): Promise<void> {+ const previous = captureStudioBoxSize(selection.element);+ applyStudioBoxSizeDraft(selection.element, next);+ return commit(selection, next, undefined, () => {+ restoreStudioBoxSize(selection.element, previous);+ });+}/*** Mounts Studio's WebMCP tool surface. Renders nothing.@@ -20,6 +60,7 @@ export function StudioAgentTools() {const { projectId, activeCompPath, editHistory, writeBlockedReason } = useStudioShellContext();const {domEditSelection,+ activeGroupElement,selectedGsapAnimations,gsapMultipleTimelines,gsapUnsupportedTimelinePattern,@@ -28,8 +69,8 @@ export function StudioAgentTools() {previewIframeRef,buildDomSelectionFromTarget,applyDomSelection,- handleDomTextCommit,- handleDomStyleCommit,+ handleDomTextCommitForSelection,+ handleDomStyleCommitForSelection,handleDomPathOffsetCommit,handleDomBoxSizeCommit,handleDomRotationCommit,@@ -37,8 +78,14 @@ export function StudioAgentTools() {handleGsapUpdateMeta,handleGsapAddKeyframeBatch,handleGsapDeleteAnimation,+ getGsapAnimationsForSelection,} = useDomEditActionsContext();+ useEffect(() => {+ studioEditLifecycle.activateProject(projectId);+ return () => studioEditLifecycle.reset();+ }, [projectId]);+const getSnapshot = useCallback((): StudioLookSnapshot => {const player = usePlayerStore.getState();return {@@ -48,6 +95,11 @@ export function StudioAgentTools() {duration: player.duration,isPlaying: player.isPlaying,elements: player.elements,+ scene: collectStudioLookScene(+ previewIframeRef.current?.contentDocument ?? null,+ activeCompPath,+ activeGroupElement,+ ),selection: domEditSelection,selectionAnimationCount: selectedGsapAnimations.length,history: {@@ -57,13 +109,21 @@ export function StudioAgentTools() {redoLabel: editHistory.redoLabel ?? null,},};- }, [projectId, activeCompPath, domEditSelection, selectedGsapAnimations, editHistory]);+ }, [+ projectId,+ activeCompPath,+ domEditSelection,+ activeGroupElement,+ selectedGsapAnimations,+ editHistory,+ previewIframeRef,+ ]);const deps = useMemo<StudioAgentToolsDeps>(() => ({getSnapshot,getPreviewDocument: () => previewIframeRef.current?.contentDocument ?? null,- buildSelection: (element) => buildDomSelectionFromTarget(element),+ buildSelection: (element) => buildDomSelectionFromTarget(element, { exactTarget: true }),applySelection: (selection) => applyDomSelection(selection, { revealPanel: true }),requestSeek: (time) => usePlayerStore.getState().requestSeek(time),readPlayhead: () => {@@ -90,22 +150,29 @@ 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),+ setText: (selection, value, fieldKey) =>+ handleDomTextCommitForSelection(selection, value, fieldKey),+ setStyle: (selection, property, value) =>+ handleDomStyleCommitForSelection(selection, property, value),// Measured, not authored: the tool compares this before and after to- // tell a real change from a handler that did nothing and resolved.- readBox: (selection) => {- const rect = selection.element.getBoundingClientRect();- return { x: rect.x, y: rect.y, width: rect.width, height: rect.height };- },+ // tell a real change from a handler that did nothing and resolved. A+ // successful commit may replace the preview document, so re-resolve the+ // source-safe selection instead of measuring its detached old node.+ readBox: (selection) =>+ readLiveSelectionBox(previewIframeRef.current?.contentDocument, selection, activeCompPath),moveTo: (selection, next) => handleDomPathOffsetCommit(selection, next),- resizeTo: (selection, next) => handleDomBoxSizeCommit(selection, next),+ resizeTo: (selection, next) =>+ resizeSelectionFromAgent(selection, next, handleDomBoxSizeCommit),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),+ addAnimation: (selection, method) => handleGsapAddAnimation(method, selection),+ updateAnimation: (selection, animationId, updates) =>+ handleGsapUpdateMeta(animationId, updates, selection),+ addKeyframe: (selection, animationId, percent, properties) =>+ handleGsapAddKeyframeBatch(animationId, percent, properties, undefined, selection),+ deleteAnimation: (selection, animationId) =>+ handleGsapDeleteAnimation(animationId, selection),+ getAnimationsForSelection: async (selection) =>+ await getGsapAnimationsForSelection(selection),getGsapDiagnostics: () => ({animations: selectedGsapAnimations,multipleTimelines: gsapMultipleTimelines,@@ -120,8 +187,8 @@ export function StudioAgentTools() {projectId,activeCompPath,writeBlockedReason,- handleDomTextCommit,- handleDomStyleCommit,+ handleDomTextCommitForSelection,+ handleDomStyleCommitForSelection,handleDomPathOffsetCommit,handleDomBoxSizeCommit,handleDomRotationCommit,@@ -129,6 +196,7 @@ export function StudioAgentTools() {handleGsapUpdateMeta,handleGsapAddKeyframeBatch,handleGsapDeleteAnimation,+ getGsapAnimationsForSelection,domEditSelection,selectedGsapAnimations,gsapMultipleTimelines,diff --git a/packages/studio/src/webmcp/handles.test.ts b/packages/studio/src/webmcp/handles.test.tsindex d164dbadff..61e69b6a71 100644--- a/packages/studio/src/webmcp/handles.test.ts+++ b/packages/studio/src/webmcp/handles.test.ts@@ -5,23 +5,15 @@ import {mintElementHandle,parseElementHandle,resolveElementHandle,+ resolveLiveHandleSelection,timelineElementAddress,} from "./handles";+import { previewDoc } from "./webmcpTestUtils";function timelineElement(overrides: Partial<TimelineElement>): TimelineElement {return { id: "synthetic-id", tag: "div", start: 0, duration: 1, track: 0, ...overrides };}-/** A separate document, standing in for the preview iframe's realm. */-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;-}-describe("mintElementHandle", () => {it("prefers data-hf-id, the stable patch target", () => {const handle = mintElementHandle(@@ -29,7 +21,7 @@ describe("mintElementHandle", () => {timelineElement({ hfId: "abc123", domId: "headline", selector: ".title" }),),);- expect(handle).toBe("hf:abc123");+ expect(handle).toBe("hf:v1:index.html:index.html:abc123");});it("falls back to the DOM id when there is no hf id", () => {@@ -37,7 +29,7 @@ describe("mintElementHandle", () => {mintElementHandle(timelineElementAddress(timelineElement({ domId: "headline", selector: ".title" })),),- ).toBe("dom:headline");+ ).toBe("dom:v1:index.html:index.html:headline");});it("falls back to a selector with its occurrence index", () => {@@ -45,12 +37,12 @@ describe("mintElementHandle", () => {mintElementHandle(timelineElementAddress(timelineElement({ selector: ".card", selectorIndex: 2 })),),- ).toBe("sel:.card#2");+ ).toBe("sel:v1:index.html:index.html:.card#2");});it("defaults a missing occurrence index to the first match", () => {expect(mintElementHandle(timelineElementAddress(timelineElement({ selector: ".card" })))).toBe(- "sel:.card#0",+ "sel:v1:index.html:index.html:.card#0",);});@@ -60,17 +52,110 @@ describe("mintElementHandle", () => {});});+describe("resolveLiveHandleSelection", () => {+ it("reports a transient change when the replacement preview has not rebuilt the target", async () => {+ const firstDoc = previewDoc('<div id="headline">before</div>');+ const replacementDoc = previewDoc("<main>reloading</main>");+ let currentDoc = firstDoc;++ const result = await resolveLiveHandleSelection(+ () => currentDoc,+ "dom:headline",+ async (element) => {+ currentDoc = replacementDoc;+ return { element };+ },+ );++ expect(result).toEqual({ status: "changed" });+ });++ it("reports a stable missing target as not found", async () => {+ const doc = previewDoc("<main>settled</main>");++ const result = await resolveLiveHandleSelection(+ () => doc,+ "dom:headline",+ async (element) => ({ element }),+ );++ expect(result).toEqual({ status: "not-found" });+ });+});+describe("parseElementHandle", () => {+ it("round-trips source ownership and the active composition", () => {+ expect(+ parseElementHandle(+ mintElementHandle({+ domId: "headline:hero",+ sourceFile: "compositions/hero.html",+ activeCompositionPath: "index.html",+ })!,+ ),+ ).toEqual({+ scheme: "dom",+ version: 1,+ value: "headline:hero",+ index: 0,+ sourceFile: "compositions/hero.html",+ activeCompositionPath: "index.html",+ });+ });++ it("encodes path, selector, colon, and hash delimiters without ambiguity", () => {+ const handle = mintElementHandle({+ selector: '#hero[data-label="a:b"] > .card:nth-child(2)',+ selectorIndex: 3,+ sourceFile: "compositions/a:b#hero.html",+ activeCompositionPath: "scenes/root:wide.html",+ });++ expect(parseElementHandle(handle!)).toEqual({+ scheme: "sel",+ version: 1,+ value: '#hero[data-label="a:b"] > .card:nth-child(2)',+ index: 3,+ sourceFile: "compositions/a:b#hero.html",+ activeCompositionPath: "scenes/root:wide.html",+ });+ });+it("splits the index off the LAST hash, so id selectors survive", () => {expect(parseElementHandle("sel:#card > .title#3")).toEqual({scheme: "sel",+ version: 0,value: "#card > .title",index: 3,});});it("treats a selector with no index as the first match", () => {- expect(parseElementHandle("sel:.card")).toEqual({ scheme: "sel", value: ".card", index: 0 });+ expect(parseElementHandle("sel:.card")).toEqual({+ scheme: "sel",+ version: 0,+ value: ".card",+ index: 0,+ });+ });++ it("round-trips the project identity in a writable v2 handle", () => {+ const handle = mintElementHandle({+ projectId: "project:demo",+ domId: "headline",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });++ expect(parseElementHandle(handle!)).toEqual({+ scheme: "dom",+ version: 2,+ projectId: "project:demo",+ value: "headline",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ index: 0,+ });});it("rejects an unknown scheme", () => {@@ -106,6 +191,78 @@ describe("resolveElementHandle", () => {expect(resolved instanceof HTMLElement).toBe(false);});+ it("distinguishes duplicate authored ids by source file", () => {+ const doc = previewDoc(+ `<main data-composition-id="root" data-composition-file="index.html">+ <div id="duplicate">root</div>+ <section data-composition-id="nested" data-composition-file="compositions/nested.html">+ <div id="duplicate">nested</div>+ </section>+ </main>`,+ );+ const rootHandle = mintElementHandle({+ domId: "duplicate",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ const nestedHandle = mintElementHandle({+ domId: "duplicate",+ sourceFile: "compositions/nested.html",+ activeCompositionPath: "index.html",+ });++ expect(rootHandle).not.toBe(nestedHandle);+ expect(resolveElementHandle(doc, rootHandle!)?.textContent).toBe("root");+ expect(resolveElementHandle(doc, nestedHandle!)?.textContent).toBe("nested");+ });++ it("keeps selector occurrence indexes scoped to their source file", () => {+ const doc = previewDoc(+ `<main data-composition-id="root" data-composition-file="index.html">+ <div class="card">root first</div><div class="card">root second</div>+ <section data-composition-id="nested" data-composition-file="compositions/nested.html">+ <div class="card">nested first</div><div class="card">nested second</div>+ </section>+ </main>`,+ );+ const rootSecond = mintElementHandle({+ selector: ".card",+ selectorIndex: 1,+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ const nestedSecond = mintElementHandle({+ selector: ".card",+ selectorIndex: 1,+ sourceFile: "compositions/nested.html",+ activeCompositionPath: "index.html",+ });++ expect(resolveElementHandle(doc, rootSecond!)?.textContent).toBe("root second");+ expect(resolveElementHandle(doc, nestedSecond!)?.textContent).toBe("nested second");+ });++ it("re-resolves a scoped handle against the live document after reload", () => {+ const handle = mintElementHandle({+ domId: "headline",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ const firstDoc = previewDoc(+ '<main data-composition-id="root" data-composition-file="index.html"><div id="headline">before</div></main>',+ );+ const first = resolveElementHandle(firstDoc, handle!);+ const reloadedDoc = previewDoc(+ '<main data-composition-id="root" data-composition-file="index.html"><div id="headline">after</div></main>',+ );+ const reloaded = resolveElementHandle(reloadedDoc, handle!);++ expect(first?.textContent).toBe("before");+ expect(reloaded?.textContent).toBe("after");+ expect(reloaded).not.toBe(first);+ expect(reloaded?.ownerDocument).toBe(reloadedDoc);+ });+it("returns null for a handle that no longer matches", () => {const doc = previewDoc('<div id="headline">A</div>');expect(resolveElementHandle(doc, "dom:deleted")).toBeNull();diff --git a/packages/studio/src/webmcp/handles.ts b/packages/studio/src/webmcp/handles.tsindex 9f8420bcd1..b5119745f9 100644--- a/packages/studio/src/webmcp/handles.ts+++ b/packages/studio/src/webmcp/handles.ts@@ -13,6 +13,7 @@*/import type { TimelineElement } from "../player/store/timelineElement";+import { findElementForSelection } from "../components/editor/domEditingElement";import type { PatchTarget } from "../utils/sourcePatcher";const SEPARATOR = ":";@@ -24,10 +25,13 @@ const INDEX_SEPARATOR = "#";* knowing about either.*/export interface ElementAddress {+ projectId?: string | null;hfId?: string;domId?: string | null;selector?: string;selectorIndex?: number;+ sourceFile?: string;+ activeCompositionPath?: string | null;}/**@@ -35,37 +39,108 @@ export interface ElementAddress {* `data-hf-id` survives edits that renumber or reorder; a bare selector does not.*/export function mintElementHandle(address: ElementAddress): string | null {- if (address.hfId) return `hf${SEPARATOR}${address.hfId}`;- if (address.domId) return `dom${SEPARATOR}${address.domId}`;+ const scoped = (value: string) => {+ if (!address.sourceFile || !address.activeCompositionPath) return value;+ if (address.projectId) {+ return [+ "v2",+ encodeURIComponent(address.projectId),+ encodeURIComponent(address.activeCompositionPath),+ encodeURIComponent(address.sourceFile),+ encodeURIComponent(value),+ ].join(SEPARATOR);+ }+ return [+ "v1",+ encodeURIComponent(address.activeCompositionPath),+ encodeURIComponent(address.sourceFile),+ encodeURIComponent(value),+ ].join(SEPARATOR);+ };++ if (address.hfId) return `hf${SEPARATOR}${scoped(address.hfId)}`;+ if (address.domId) return `dom${SEPARATOR}${scoped(address.domId)}`;if (address.selector) {const index = address.selectorIndex ?? 0;- return `sel${SEPARATOR}${address.selector}${INDEX_SEPARATOR}${index}`;+ return `sel${SEPARATOR}${scoped(address.selector)}${INDEX_SEPARATOR}${index}`;}return null;}-export function timelineElementAddress(element: TimelineElement): ElementAddress {+export function timelineElementAddress(+ element: TimelineElement,+ activeCompositionPath: string | null = "index.html",+ projectId?: string | null,+): ElementAddress {+ const rootFile = activeCompositionPath ?? "index.html";return {+ projectId,hfId: element.hfId,domId: element.domId,selector: element.selector,selectorIndex: element.selectorIndex,+ sourceFile: element.sourceFile ?? rootFile,+ activeCompositionPath: rootFile,};}-export function patchTargetAddress(target: PatchTarget): ElementAddress {+export function patchTargetAddress(+ target: PatchTarget & { sourceFile?: string },+ activeCompositionPath?: string | null,+ projectId?: string | null,+): ElementAddress {return {+ projectId,hfId: target.hfId,domId: target.id,selector: target.selector,selectorIndex: target.selectorIndex,+ sourceFile: target.sourceFile,+ activeCompositionPath,};}-interface ParsedHandle {+export interface ParsedHandle {scheme: "hf" | "dom" | "sel";+ version: 0 | 1 | 2;value: string;index: number;+ projectId?: string;+ sourceFile?: string;+ activeCompositionPath?: string;+}++function decodeScopedParts(rest: string, version: "v1" | "v2", count: number) {+ const parts = rest.split(SEPARATOR);+ if (parts[0] !== version || parts.length !== count + 1) return null;+ return parts.slice(1).map(decodeHandlePart);+}++function parseV1ScopedValue(rest: string): Omit<ParsedHandle, "scheme" | "index"> | null {+ const [activeCompositionPath, sourceFile, value] = decodeScopedParts(rest, "v1", 3) ?? [];+ if (!activeCompositionPath || !sourceFile || !value) return null;+ return { version: 1, value, sourceFile, activeCompositionPath };+}++function parseV2ScopedValue(rest: string): Omit<ParsedHandle, "scheme" | "index"> | null {+ const [projectId, activeCompositionPath, sourceFile, value] =+ decodeScopedParts(rest, "v2", 4) ?? [];+ if (!projectId || !activeCompositionPath || !sourceFile || !value) return null;+ return { version: 2, projectId, value, sourceFile, activeCompositionPath };+}++function parseScopedValue(rest: string): Omit<ParsedHandle, "scheme" | "index"> | null {+ if (rest.startsWith(`v1${SEPARATOR}`)) return parseV1ScopedValue(rest);+ if (rest.startsWith(`v2${SEPARATOR}`)) return parseV2ScopedValue(rest);+ return { value: rest, version: 0 };+}++function decodeHandlePart(value: string): string | null {+ try {+ return decodeURIComponent(value) || null;+ } catch {+ return null;+ }}export function parseElementHandle(handle: string): ParsedHandle | null {@@ -74,15 +149,25 @@ export function parseElementHandle(handle: string): ParsedHandle | null {const scheme = handle.slice(0, separatorAt);const rest = handle.slice(separatorAt + 1);if (!rest) return null;- if (scheme === "hf" || scheme === "dom") return { scheme, value: rest, index: 0 };+ if (scheme === "hf" || scheme === "dom") {+ const scoped = parseScopedValue(rest);+ return scoped ? { scheme, ...scoped, index: 0 } : null;+ }if (scheme !== "sel") return null;// Only the LAST `#` splits the index off: CSS selectors contain `#` themselves.const indexAt = rest.lastIndexOf(INDEX_SEPARATOR);- if (indexAt <= 0) return { scheme, value: rest, index: 0 };+ if (indexAt <= 0) {+ const scoped = parseScopedValue(rest);+ return scoped ? { scheme, ...scoped, index: 0 } : null;+ }const index = Number(rest.slice(indexAt + 1));- if (!Number.isInteger(index) || index < 0) return { scheme, value: rest, index: 0 };- return { scheme, value: rest.slice(0, indexAt), index };+ if (!Number.isInteger(index) || index < 0) {+ const scoped = parseScopedValue(rest);+ return scoped ? { scheme, ...scoped, index: 0 } : null;+ }+ const scoped = parseScopedValue(rest.slice(0, indexAt));+ return scoped ? { scheme, ...scoped, index } : null;}/**@@ -95,35 +180,67 @@ export function parseElementHandle(handle: string): ParsedHandle | null {export function resolveElementHandle(doc: Document, handle: string): HTMLElement | null {const parsed = parseElementHandle(handle);if (!parsed) return null;-- if (parsed.scheme === "dom") return asHtmlElement(doc, doc.getElementById(parsed.value));- if (parsed.scheme === "hf") {- return asHtmlElement(doc, doc.querySelector(`[data-hf-id="${cssEscape(parsed.value)}"]`));- }-- let matches: NodeListOf<Element>;- try {- matches = doc.querySelectorAll(parsed.value);- } catch {- // A selector minted from a previous document can be invalid in this one.- return null;- }- return asHtmlElement(doc, matches.item(parsed.index));+ return findElementForSelection(+ doc,+ {+ hfId: parsed.scheme === "hf" ? parsed.value : undefined,+ id: parsed.scheme === "dom" ? parsed.value : undefined,+ selector: parsed.scheme === "sel" ? parsed.value : undefined,+ selectorIndex: parsed.scheme === "sel" ? parsed.index : undefined,+ sourceFile: parsed.sourceFile,+ },+ parsed.activeCompositionPath ?? null,+ );}-function cssEscape(value: string): string {- // ponytail: happy-dom and jsdom don't always ship CSS.escape; quoting the two- // characters that can break out of an attribute selector covers this use.- return typeof CSS?.escape === "function" ? CSS.escape(value) : value.replace(/["\\]/g, "\\$&");+/** Legacy read handles remain valid, but a scoped handle must name the active project. */+export function elementHandleMatchesProject(handle: string, projectId: string | null): boolean {+ const parsed = parseElementHandle(handle);+ if (!parsed) return false;+ return parsed.version !== 2 || (!!projectId && parsed.projectId === projectId);}+export type LiveHandleResolution<T extends { element: HTMLElement }> =+ | { status: "ready"; selection: T }+ | { status: "preview-unavailable" }+ | { status: "not-found" }+ | { status: "unsupported" }+ | { status: "changed" };+/**- * `instanceof HTMLElement` is checked against the OWNING document's realm.- * The preview lives in an iframe, so Studio's own `HTMLElement` is a different- * constructor and the naive check fails on every real preview element.+ * Resolve and build a selection across one possible preview reload.+ *+ * Building a selection can await a source probe. A thumbnail refresh may+ * replace the preview document during that await, leaving an otherwise valid+ * selection attached to the old document with a truthful-looking 0x0 box.+ * Reacquire once from the current document, then refuse if it moves again.*/-function asHtmlElement(doc: Document, node: Element | null): HTMLElement | null {- if (!node) return null;- const ctor = doc.defaultView?.HTMLElement;- return ctor && node instanceof ctor ? node : null;+export async function resolveLiveHandleSelection<T extends { element: HTMLElement }>(+ getPreviewDocument: () => Document | null,+ handle: string,+ buildSelection: (element: HTMLElement) => Promise<T | null>,+): Promise<LiveHandleResolution<T>> {+ let reloadObserved = false;+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const doc = getPreviewDocument();+ if (!doc) return { status: "preview-unavailable" };+ const element = resolveElementHandle(doc, handle);+ if (!element) return { status: reloadObserved ? "changed" : "not-found" };++ const selection = await buildSelection(element);+ const currentDoc = getPreviewDocument();+ const previewChanged =+ currentDoc !== doc ||+ element.ownerDocument !== doc ||+ !element.isConnected ||+ (selection !== null &&+ (selection.element.ownerDocument !== doc || !selection.element.isConnected));+ if (previewChanged) {+ reloadObserved = true;+ continue;+ }+ if (!selection) return { status: "unsupported" };+ return { status: "ready", selection };+ }+ return { status: "changed" };}diff --git a/packages/studio/src/webmcp/tools/animationTools.test.ts b/packages/studio/src/webmcp/tools/animationTools.test.tsindex f8f60bb8d5..b03d5fdace 100644--- a/packages/studio/src/webmcp/tools/animationTools.test.ts+++ b/packages/studio/src/webmcp/tools/animationTools.test.ts@@ -10,46 +10,89 @@ import {type StudioAddKeyframeResult,type StudioUpdateAnimationResult,} from "./animationTools";-import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils";+import {+ expectFailure,+ expectOk,+ previewElement,+ selectionFor,+ sourceHandle,+ targetedWriteDeps,+} from "../webmcpTestUtils";++const animationInput = (input: Record<string, unknown>) => ({+ handle: sourceHandle("headline"),+ ...input,+});function animationDeps(overrides: Partial<AnimationToolDeps> = {}): AnimationToolDeps {const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");+ const selection = selectionFor(element);return {- getCurrentSelection: () => selectionFor(element),- getWriteBlockedReason: () => null,+ ...targetedWriteDeps(selection),+ getAnimationsForSelection: async () => [{ id: "anim-1" }, { id: "anim-gone" }, { id: "a" }],readPlayhead: () => ({ currentTime: 2.4, duration: 10, isPlaying: false }),- addAnimation: () => undefined,+ addAnimation: async () => true,updateAnimation: async () => true,addKeyframe: async () => undefined,- deleteAnimation: () => undefined,+ deleteAnimation: async () => true,...overrides,};}describe("studioAddAnimation", () => {+ it("does not report success before persistence and preview sync settle", async () => {+ let release!: (landed: boolean) => void;+ let actorStarted!: () => void;+ const pending = new Promise<boolean>((resolve) => {+ release = resolve;+ });+ const started = new Promise<void>((resolve) => {+ actorStarted = resolve;+ });+ let settled = false;++ const resultPromise = studioAddAnimation(+ animationDeps({+ addAnimation: () => {+ actorStarted();+ return pending;+ },+ }),+ animationInput({ method: "from" }),+ ).then((result) => {+ settled = true;+ return result;+ });++ await started;+ await Promise.resolve();+ expect(settled).toBe(false);++ release(true);+ expect((await resultPromise).ok).toBe(true);+ });+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 addAnimation = vi.fn(async () => true);const result = await studioAddAnimation(animationDeps({addAnimation,readPlayhead: () => ({ currentTime: 7.25, duration: 10, isPlaying: false }),}),- { method: "from" },+ animationInput({ method: "from" }),);const ok = expectOk<StudioAddAnimationResult>(result);expect(ok.insertedAtSeconds).toBe(7.25);expect(ok.method).toBe("from");- expect(addAnimation).toHaveBeenCalledWith("from");+ expect(addAnimation).toHaveBeenCalledWith(expect.anything(), "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" });+ it("marks the result as dispatched after the underlying write settles", async () => {+ const result = await studioAddAnimation(animationDeps(), animationInput({ method: "to" }));expect(expectOk<StudioAddAnimationResult>(result).dispatched).toBe(true);});@@ -58,7 +101,10 @@ describe("studioAddAnimation", () => {const addAnimation = vi.fn();const result = expectFailure(- await studioAddAnimation(animationDeps({ addAnimation }), { method: "wiggle" }),+ await studioAddAnimation(+ animationDeps({ addAnimation }),+ animationInput({ method: "wiggle" }),+ ),);expect(result.kind).toBe("invalid");@@ -71,45 +117,67 @@ describe("studioAddAnimation", () => {const paused = expectFailure(await studioAddAnimation(animationDeps({ getWriteBlockedReason: () => "Auto-save is paused", addAnimation }),- { method: "to" },+ animationInput({ method: "to" }),),);const unselected = expectFailure(- await studioAddAnimation(animationDeps({ getCurrentSelection: () => null, addAnimation }), {- method: "to",- }),+ await studioAddAnimation(+ animationDeps({ buildSelection: async () => null, addAnimation }),+ animationInput({ method: "to" }),+ ),);expect(paused.kind).toBe("blocked");- expect(unselected.kind).toBe("invalid");+ expect(unselected.kind).toBe("blocked");expect(addAnimation).not.toHaveBeenCalled();});});describe("studioUpdateAnimation", () => {- it("confirms the write, because this handler actually reports back", async () => {+ it("dispatches the write after the handler reports acceptance", async () => {const updateAnimation = vi.fn(async () => true);- const result = await studioUpdateAnimation(animationDeps({ updateAnimation }), {- animationId: "anim-1",- ease: "power2.out",- duration: 1.5,- });+ const result = await studioUpdateAnimation(+ animationDeps({ updateAnimation }),+ animationInput({+ animationId: "anim-1",+ ease: "power2.out",+ duration: 1.5,+ }),+ );const ok = expectOk<StudioUpdateAnimationResult>(result);+ expect(ok.changed).toBe(false);expect(ok.updated).toEqual({ duration: 1.5, ease: "power2.out" });- expect(updateAnimation).toHaveBeenCalledWith("anim-1", {+ expect(updateAnimation).toHaveBeenCalledWith(expect.anything(), "anim-1", {duration: 1.5,ease: "power2.out",});});+ it("refuses an animation id owned by another target before calling the actor", async () => {+ const updateAnimation = vi.fn(async () => true);+ const result = await studioUpdateAnimation(+ animationDeps({+ getAnimationsForSelection: async () => [{ id: "other-animation" }],+ updateAnimation,+ }),+ animationInput({ animationId: "anim-1", duration: 2 }),+ );++ expect(result).toMatchObject({ ok: false, stage: "refused", kind: "invalid" });+ expect(updateAnimation).not.toHaveBeenCalled();+ });+it("reports a false return as a real failure", async () => {const result = expectFailure(- await studioUpdateAnimation(animationDeps({ updateAnimation: async () => false }), {- animationId: "anim-gone",- ease: "none",- }),+ await studioUpdateAnimation(+ animationDeps({ updateAnimation: async () => false }),+ animationInput({+ animationId: "anim-gone",+ ease: "none",+ }),+ ),);expect(result.kind).toBe("failed");@@ -123,24 +191,26 @@ describe("studioUpdateAnimation", () => {const result = expectFailure(await studioUpdateAnimation(- animationDeps({ getCurrentSelection: () => null, updateAnimation }),- { animationId: "anim-1", ease: "none" },+ animationDeps({ buildSelection: async () => null, updateAnimation }),+ animationInput({ animationId: "anim-1", ease: "none" }),),);- expect(result.kind).toBe("invalid");- expect(result.reason).toMatch(/nothing is selected/);+ expect(result.kind).toBe("blocked");+ expect(result.reason).toMatch(/cannot edit/);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,+ expectFailure(await studioUpdateAnimation(deps, animationInput({ animationId: "a" }))).reason,+ ).toMatch(/at least one/);+ expect(+ expectFailure(+ await studioUpdateAnimation(deps, animationInput({ animationId: "a", duration: -1 })),+ ).reason,).toMatch(/negative/);});@@ -148,32 +218,53 @@ describe("studioUpdateAnimation", () => {const updateAnimation = vi.fn();const result = expectFailure(- await studioUpdateAnimation(animationDeps({ updateAnimation }), {- animationId: " ",- ease: "none",- }),+ await studioUpdateAnimation(+ animationDeps({ updateAnimation }),+ animationInput({+ animationId: " ",+ ease: "none",+ }),+ ),);expect(result.kind).toBe("invalid");expect(updateAnimation).not.toHaveBeenCalled();});++ it("rejects raw JavaScript ease expressions before dispatch", async () => {+ const updateAnimation = vi.fn();++ const result = await studioUpdateAnimation(+ animationDeps({ updateAnimation }),+ animationInput({ animationId: "anim-1", ease: "__raw:(()=>alert(1))()" }),+ );++ expect(result).toMatchObject({ ok: false, stage: "refused", kind: "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 result = await studioAddKeyframe(+ animationDeps({ addKeyframe }),+ animationInput({+ animationId: "anim-1",+ percent: 50,+ properties: { y: -50, opacity: 0 },+ }),+ );const ok = expectOk<StudioAddKeyframeResult>(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 });+ expect(addKeyframe).toHaveBeenCalledWith(expect.anything(), "anim-1", 50, {+ y: -50,+ opacity: 0,+ });});it("validates percent itself, because the platform does not", async () => {@@ -184,7 +275,10 @@ describe("studioAddKeyframe", () => {for (const percent of [-1, 101, Number.NaN, "50"]) {const result = expectFailure(- await studioAddKeyframe(deps, { animationId: "a", percent, properties: { y: 1 } }),+ await studioAddKeyframe(+ deps,+ animationInput({ animationId: "a", percent, properties: { y: 1 } }),+ ),);expect(result.kind).toBe("invalid");}@@ -197,35 +291,107 @@ describe("studioAddKeyframe", () => {for (const properties of [{}, { y: null }, [], "y:1"]) {const result = expectFailure(- await studioAddKeyframe(deps, { animationId: "a", percent: 50, properties }),+ await studioAddKeyframe(+ deps,+ animationInput({ animationId: "a", percent: 50, properties }),+ ),);expect(result.kind).toBe("invalid");}expect(addKeyframe).not.toHaveBeenCalled();});+ it("rejects raw JavaScript keyframe values before dispatch", async () => {+ const addKeyframe = vi.fn();++ const result = await studioAddKeyframe(+ animationDeps({ addKeyframe }),+ animationInput({+ animationId: "anim-1",+ percent: 50,+ properties: { x: "__raw:(()=>alert(1))()" },+ }),+ );++ expect(result).toMatchObject({ ok: false, stage: "refused", kind: "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 },- });+ const result = await studioAddKeyframe(+ animationDeps(),+ animationInput({+ animationId: "a",+ percent,+ properties: { y: 1 },+ }),+ );expect(expectOk<StudioAddKeyframeResult>(result).percent).toBe(percent);}});++ it("refuses an animation id owned by another target before calling the actor", async () => {+ const addKeyframe = vi.fn(async () => undefined);++ const result = await studioAddKeyframe(+ animationDeps({+ getAnimationsForSelection: async () => [{ id: "other-animation" }],+ addKeyframe,+ }),+ animationInput({ animationId: "anim-1", percent: 50, properties: { y: 1 } }),+ );++ expect(result).toMatchObject({ ok: false, stage: "refused", kind: "invalid" });+ expect(addKeyframe).not.toHaveBeenCalled();+ });});describe("studioDeleteAnimation", () => {- it("dispatches the delete and says so", async () => {- const deleteAnimation = vi.fn();+ it("does not report success before persistence and preview sync settle", async () => {+ let release!: (landed: boolean) => void;+ let actorStarted!: () => void;+ const pending = new Promise<boolean>((resolve) => {+ release = resolve;+ });+ const started = new Promise<void>((resolve) => {+ actorStarted = resolve;+ });+ let settled = false;- const result = await studioDeleteAnimation(animationDeps({ deleteAnimation }), {- animationId: "anim-1",+ const resultPromise = studioDeleteAnimation(+ animationDeps({+ deleteAnimation: () => {+ actorStarted();+ return pending;+ },+ }),+ animationInput({ animationId: "anim-1" }),+ ).then((result) => {+ settled = true;+ return result;});+ await started;+ await Promise.resolve();+ expect(settled).toBe(false);++ release(true);+ expect((await resultPromise).ok).toBe(true);+ });++ it("dispatches the delete and says so", async () => {+ const deleteAnimation = vi.fn(async () => true);++ const result = await studioDeleteAnimation(+ animationDeps({ deleteAnimation }),+ animationInput({+ animationId: "anim-1",+ }),+ );+expect(result.ok).toBe(true);- expect(deleteAnimation).toHaveBeenCalledWith("anim-1");+ expect(deleteAnimation).toHaveBeenCalledWith(expect.anything(), "anim-1");});it("refuses while a write is blocked", async () => {@@ -234,11 +400,26 @@ describe("studioDeleteAnimation", () => {const result = expectFailure(await studioDeleteAnimation(animationDeps({ getWriteBlockedReason: () => "Auto-save is paused", deleteAnimation }),- { animationId: "anim-1" },+ animationInput({ animationId: "anim-1" }),),);expect(result.kind).toBe("blocked");expect(deleteAnimation).not.toHaveBeenCalled();});++ it("refuses an animation id owned by another target before calling the actor", async () => {+ const deleteAnimation = vi.fn();++ const result = await studioDeleteAnimation(+ animationDeps({+ getAnimationsForSelection: async () => [{ id: "other-animation" }],+ deleteAnimation,+ }),+ animationInput({ animationId: "anim-1" }),+ );++ expect(result).toMatchObject({ ok: false, stage: "refused", kind: "invalid" });+ expect(deleteAnimation).not.toHaveBeenCalled();+ });});diff --git a/packages/studio/src/webmcp/tools/animationTools.ts b/packages/studio/src/webmcp/tools/animationTools.tsindex 0d5d678bc4..dd983a7b7a 100644--- a/packages/studio/src/webmcp/tools/animationTools.ts+++ b/packages/studio/src/webmcp/tools/animationTools.ts@@ -1,66 +1,70 @@/*** `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.+ * Add, update, and delete await the shared GSAP commit pipeline. Its promise is+ * the single settlement boundary for persistence and live-preview sync, so a+ * successful tool response never races ahead of the pixels the user sees.+ * Keyframe writes still report dispatch because their existing actor catches+ * its own failure instead of returning a landed signal.*/import type { DomEditSelection } from "../../components/editor/domEditingTypes";-import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult";+import { toolFailure, type ToolFailure } from "../toolResult";+import {+ dispatched,+ runTargetedWrite,+ type StudioWriteResult,+ type TargetedWriteDeps,+ WRITE_RECEIPT_DESCRIPTION,+} from "../writeCoordinator";export type GsapMethod = "to" | "from" | "set" | "fromTo";const METHODS: readonly GsapMethod[] = ["to", "from", "set", "fromTo"];-export interface AnimationToolDeps {- getCurrentSelection: () => DomEditSelection | null;- getWriteBlockedReason: () => string | null;+export interface AnimationToolDeps extends TargetedWriteDeps {+ getAnimationsForSelection: (selection: DomEditSelection) => Promise<readonly { id: string }[]>;readPlayhead: () => { currentTime: number; duration: number; isPlaying: boolean };- addAnimation: (method: GsapMethod) => void;+ addAnimation: (selection: DomEditSelection, method: GsapMethod) => Promise<boolean>;updateAnimation: (+ selection: DomEditSelection,animationId: string,updates: { duration?: number; ease?: string; position?: number },) => Promise<boolean>;addKeyframe: (+ selection: DomEditSelection,animationId: string,percent: number,properties: Record<string, number | string>,) => Promise<void>;- deleteAnimation: (animationId: string) => void;+ deleteAnimation: (selection: DomEditSelection, animationId: string) => Promise<boolean>;}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;+async function animationBelongsToTarget(+ deps: AnimationToolDeps,+ selection: DomEditSelection,+ animationId: string,+): Promise<ToolFailure | null> {+ const animations = await deps.getAnimationsForSelection(selection);+ return animations.some((animation) => animation.id === animationId)+ ? null+ : toolFailure(+ "invalid",+ `animation ${animationId} does not belong to the target handle`,+ "Select the target, then call studio_inspect for its current animation ids.",+ );}function readAnimationId(value: unknown): string | null {return typeof value === "string" && value.trim() ? value : null;}+function isRawGsapExpression(value: unknown): value is string {+ return typeof value === "string" && value.startsWith("__raw:");+}+export interface StudioAddAnimationResult {method: GsapMethod;/** Where it was inserted, which is the playhead, not a value you supplied. */@@ -70,26 +74,32 @@ export interface StudioAddAnimationResult {export async function studioAddAnimation(deps: AnimationToolDeps,- input: { method?: unknown },-): Promise<ToolResult<StudioAddAnimationResult>> {+ input: { handle?: unknown; method?: unknown },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioAddAnimationResult>> {const method = METHODS.find((candidate) => candidate === input.method);if (!method) {- return toolFailure("invalid", `method must be one of ${METHODS.join(", ")}`);+ return preDispatchFailure(+ "add-animation",+ 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<StudioAddAnimationResult>({- method,- insertedAtSeconds: currentTime,- dispatched: true,+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "add-animation",+ signal,+ write: async (selection) => {+ const { currentTime } = deps.readPlayhead();+ const landed = await deps.addAnimation(selection, method);+ if (!landed) {+ return toolFailure(+ "failed",+ "the animation did not land",+ "The target may be stale. Call studio_look and try again with its current handle.",+ );+ }+ return dispatched({ method, insertedAtSeconds: currentTime, dispatched: true }, false);+ },});}@@ -100,42 +110,65 @@ export interface StudioUpdateAnimationResult {export async function studioUpdateAnimation(deps: AnimationToolDeps,- input: { animationId?: unknown; duration?: unknown; ease?: unknown; position?: unknown },-): Promise<ToolResult<StudioUpdateAnimationResult>> {+ input: {+ handle?: unknown;+ animationId?: unknown;+ duration?: unknown;+ ease?: unknown;+ position?: unknown;+ },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioUpdateAnimationResult>> {const animationId = readAnimationId(input.animationId);if (!animationId) {- return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT);+ return preDispatchFailure(+ "update-animation",+ 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");+ if (input.duration < 0)+ return preDispatchFailure(+ "update-animation",+ toolFailure("invalid", "duration must not be negative"),+ );updates.duration = input.duration;}+ if (isRawGsapExpression(input.ease)) {+ return preDispatchFailure(+ "update-animation",+ toolFailure("invalid", "raw JavaScript expressions are not accepted"),+ );+ }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 preDispatchFailure(+ "update-animation",+ toolFailure("invalid", "give at least one of duration, ease, position"),);}-- return toolOk<StudioUpdateAnimationResult>({ animationId, updated: updates });+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "update-animation",+ signal,+ preflight: (selection) => animationBelongsToTarget(deps, selection, animationId),+ write: async (selection) => {+ const landed = await deps.updateAnimation(selection, 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 dispatched({ animationId, updated: updates }, false);+ },+ });}export interface StudioAddKeyframeResult {@@ -147,36 +180,58 @@ export interface StudioAddKeyframeResult {export async function studioAddKeyframe(deps: AnimationToolDeps,- input: { animationId?: unknown; percent?: unknown; properties?: unknown },-): Promise<ToolResult<StudioAddKeyframeResult>> {+ input: { handle?: unknown; animationId?: unknown; percent?: unknown; properties?: unknown },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioAddKeyframeResult>> {const animationId = readAnimationId(input.animationId);if (!animationId) {- return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT);+ return preDispatchFailure(+ "add-keyframe",+ 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");+ return preDispatchFailure(+ "add-keyframe",+ 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");+ return preDispatchFailure(+ "add-keyframe",+ toolFailure("invalid", "properties must be an object of GSAP property to value"),+ );}const properties: Record<string, number | string> = {};for (const [key, value] of Object.entries(raw)) {+ if (isRawGsapExpression(value)) {+ return preDispatchFailure(+ "add-keyframe",+ toolFailure("invalid", "raw JavaScript expressions are not accepted"),+ );+ }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");+ return preDispatchFailure(+ "add-keyframe",+ 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<StudioAddKeyframeResult>({ animationId, percent, properties, dispatched: true });+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "add-keyframe",+ signal,+ preflight: (selection) => animationBelongsToTarget(deps, selection, animationId),+ write: async (selection) => {+ await deps.addKeyframe(selection, animationId, percent, properties);+ return dispatched({ animationId, percent, properties, dispatched: true }, false);+ },+ });}export interface StudioDeleteAnimationResult {@@ -186,59 +241,81 @@ export interface StudioDeleteAnimationResult {export async function studioDeleteAnimation(deps: AnimationToolDeps,- input: { animationId?: unknown },-): Promise<ToolResult<StudioDeleteAnimationResult>> {+ input: { handle?: unknown; animationId?: unknown },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioDeleteAnimationResult>> {const animationId = readAnimationId(input.animationId);if (!animationId) {- return toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT);+ return preDispatchFailure(+ "delete-animation",+ toolFailure("invalid", "animationId must be a non-empty string", INSPECT_HINT),+ );}-- const blocked = guard(deps);- if (blocked) return blocked;-- deps.deleteAnimation(animationId);- return toolOk<StudioDeleteAnimationResult>({ animationId, dispatched: true });+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "delete-animation",+ signal,+ preflight: (selection) => animationBelongsToTarget(deps, selection, animationId),+ write: async (selection) => {+ const landed = await deps.deleteAnimation(selection, animationId);+ if (!landed) {+ return toolFailure(+ "failed",+ `the delete of ${animationId} did not land`,+ "The animation id may be stale. studio_inspect lists the current ones.",+ );+ }+ return dispatched({ animationId, dispatched: true }, false);+ },+ });}-const DISPATCH_CAVEAT = `Reports what was dispatched, not what landed: the handler underneath does not report back. ${INSPECT_HINT}`;+const SETTLEMENT_NOTE =+ "Success means persistence and live-preview synchronization have finished. Inspect afterward when exact authored values matter.";+const KEYFRAME_DISPATCH_CAVEAT = `Reports what was dispatched, not what landed: the keyframe actor does not report back. ${INSPECT_HINT}`;export const STUDIO_ADD_ANIMATION_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },method: { type: "string", enum: METHODS, description: "The GSAP method to add." },},- required: ["method"],+ required: ["handle", "method"],additionalProperties: false,} as const;export const STUDIO_ADD_ANIMATION_DESCRIPTION = [- "Add a GSAP animation to the CURRENTLY SELECTED element. Call studio_select first.",+ "Add a GSAP animation to one element using its source-safe handle from studio_look.","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,+ SETTLEMENT_NOTE,+ WRITE_RECEIPT_DESCRIPTION,].join(" ");export const STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },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"],+ required: ["handle", "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.",+ "It waits for persistence and live-preview synchronization before reporting success.",+ "Get current ids from studio_inspect.",+ WRITE_RECEIPT_DESCRIPTION,].join(" ");export const STUDIO_ADD_KEYFRAME_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },animationId: { type: "string", description: "An animation id from studio_inspect." },percent: {type: "number",@@ -251,26 +328,36 @@ export const STUDIO_ADD_KEYFRAME_INPUT_SCHEMA = {description: 'GSAP property to value, for example {"y": -50, "opacity": 0}.',},},- required: ["animationId", "percent", "properties"],+ required: ["handle", "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,+ KEYFRAME_DISPATCH_CAVEAT,+ WRITE_RECEIPT_DESCRIPTION,].join(" ");export const STUDIO_DELETE_ANIMATION_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },animationId: { type: "string", description: "An animation id from studio_inspect." },},- required: ["animationId"],+ required: ["handle", "animationId"],additionalProperties: false,} as const;export const STUDIO_DELETE_ANIMATION_DESCRIPTION = [- "Remove an animation from the currently selected element. Undo reverses it.",- DISPATCH_CAVEAT,+ "Remove an animation from the element named by handle. Undo reverses it.",+ SETTLEMENT_NOTE,+ WRITE_RECEIPT_DESCRIPTION,].join(" ");++function preDispatchFailure<T extends object>(+ operation: "add-animation" | "update-animation" | "add-keyframe" | "delete-animation",+ failure: ToolFailure,+): StudioWriteResult<T> {+ return { ...failure, stage: "refused", operation };+}diff --git a/packages/studio/src/webmcp/tools/contentTools.test.ts b/packages/studio/src/webmcp/tools/contentTools.test.tsindex 63f41b79e6..4079a4d190 100644--- a/packages/studio/src/webmcp/tools/contentTools.test.ts+++ b/packages/studio/src/webmcp/tools/contentTools.test.ts@@ -7,34 +7,61 @@ import {type StudioSetStyleResult,type StudioSetTextResult,} from "./contentTools";-import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils";+import {+ expectFailure,+ expectOk,+ previewElement,+ selectionFor,+ sourceHandle,+ targetedWriteDeps,+} from "../webmcpTestUtils";++const textInput = (input: Record<string, unknown>) => ({+ handle: sourceHandle("headline"),+ ...input,+});++const styleInput = (styles: unknown) => ({ handle: sourceHandle("headline"), styles });function contentDeps(overrides: Partial<ContentToolDeps> = {}): ContentToolDeps {const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");+ const selection = selectionFor(element);return {- getCurrentSelection: () => selectionFor(element),- getWriteBlockedReason: () => null,+ ...targetedWriteDeps(selection),setText: async () => ({ ok: true }),setStyle: async () => ({ ok: true }),...overrides,};}+function childTextSelection() {+ const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");+ const selection = selectionFor(element);+ selection.textFields = [{ ...selection.textFields[0]!, key: "child:0:h1" }];+ return selection;+}+describe("studioSetText", () => {it("writes the text and reports what it now is", async () => {- const setText = vi.fn(async () => ({ ok: true }) as const);+ const setText = vi.fn(async (selection) => {+ selection.element.textContent = "Ship it faster";+ return { ok: true } as const;+ });- const result = await studioSetText(contentDeps({ setText }), { text: "Ship it faster" });+ const result = await studioSetText(+ contentDeps({ setText }),+ textInput({ text: "Ship it faster" }),+ );const ok = expectOk<StudioSetTextResult>(result);expect(ok.text).toBe("Ship it faster");expect(ok.changed).toBe(true);// The single field is resolved and named, rather than left undefined.- expect(setText).toHaveBeenCalledWith("Ship it faster", "self");+ expect(setText).toHaveBeenCalledWith(expect.anything(), "Ship it faster", "self");});it("reports changed:false when the text already said that", async () => {- const result = await studioSetText(contentDeps(), { text: "Ship it" });+ const result = await studioSetText(contentDeps(), textInput({ text: "Ship it" }));expect(expectOk<StudioSetTextResult>(result).changed).toBe(false);});@@ -51,7 +78,7 @@ describe("studioSetText", () => {getWriteBlockedReason: () => "an external change to this file is waiting to be resolved",setText,}),- { text: "Ship it faster" },+ textInput({ text: "Ship it faster" }),),);@@ -66,7 +93,7 @@ describe("studioSetText", () => {const result = expectFailure(await studioSetText(contentDeps({ setText: async () => ({ ok: false, reason: "persist-failed" }) }),- { text: "Ship it faster" },+ textInput({ text: "Ship it faster" }),),);@@ -78,32 +105,38 @@ describe("studioSetText", () => {const result = expectFailure(await studioSetText(contentDeps({ setText: async () => ({ ok: false, reason: "not-text-editable" }) }),- { text: "x" },+ textInput({ text: "x" }),),);- expect(result.kind).toBe("blocked");+ expect(result.kind).toBe("failed");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 }));+ const result = expectFailure(+ await studioSetText(contentDeps({ setText }), textInput({ text: 42 })),+ );expect(result.kind).toBe("invalid");expect(setText).not.toHaveBeenCalled();});- it("fails when nothing is selected", async () => {+ it("reports an unsupported target when Studio cannot build its selection", async () => {const setText = vi.fn();const result = expectFailure(- await studioSetText(contentDeps({ getCurrentSelection: () => null, setText }), { text: "x" }),+ await studioSetText(+ contentDeps({ buildSelection: async () => null, setText }),+ textInput({ text: "x" }),+ ),);- expect(result.kind).toBe("invalid");- expect(result.hint).toMatch(/studio_select/);+ expect(result.kind).toBe("blocked");+ expect(result.reason).toBe("the target resolved to an element Studio cannot edit");+ expect(result.hint).toMatch(/parent or child/);expect(setText).not.toHaveBeenCalled();});@@ -113,29 +146,26 @@ describe("studioSetText", () => {// 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('<h1 id="headline">Ship it</h1>', "headline");- const selection = selectionFor(element);- selection.textFields = [{ ...selection.textFields[0]!, key: "child:0:h1" }];+ const selection = childTextSelection();const setText = vi.fn(async () => ({ ok: true }) as const);- await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), {- text: "Shipped it",- });+ await studioSetText(+ contentDeps({ ...targetedWriteDeps(selection), setText }),+ textInput({ text: "Shipped it" }),+ );- expect(setText).toHaveBeenCalledWith("Shipped it", "child:0:h1");+ expect(setText).toHaveBeenCalledWith(selection, "Shipped it", "child:0:h1");});it("rejects a field the element does not have, rather than writing nowhere", async () => {- const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");- const selection = selectionFor(element);- selection.textFields = [{ ...selection.textFields[0]!, key: "child:0:h1" }];+ const selection = childTextSelection();const setText = vi.fn();const result = expectFailure(- await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), {- text: "x",- field: "self",- }),+ await studioSetText(+ contentDeps({ ...targetedWriteDeps(selection), setText }),+ textInput({ text: "x", field: "self" }),+ ),);expect(result.kind).toBe("invalid");@@ -154,7 +184,8 @@ describe("studioSetText", () => {const setText = vi.fn();const result = expectFailure(- await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), {+ await studioSetText(contentDeps({ ...targetedWriteDeps(selection), setText }), {+ handle: sourceHandle("card"),text: "x",}),);@@ -171,7 +202,8 @@ describe("studioSetText", () => {const setText = vi.fn();const result = expectFailure(- await studioSetText(contentDeps({ getCurrentSelection: () => selection, setText }), {+ await studioSetText(contentDeps({ ...targetedWriteDeps(selection), setText }), {+ handle: sourceHandle("box"),text: "x",}),);@@ -186,7 +218,7 @@ describe("studioSetStyle", () => {const setStyle = vi.fn(async () => ({ ok: true }) as const);const result = await studioSetStyle(contentDeps({ setStyle }), {- styles: { color: "red", "font-size": "48px" },+ ...styleInput({ color: "red", "font-size": "48px" }),});const ok = expectOk<StudioSetStyleResult>(result);@@ -195,6 +227,36 @@ describe("studioSetStyle", () => {expect(setStyle).toHaveBeenCalledTimes(2);});+ it("keeps an earlier changed property when the latest saved property is a no-op", async () => {+ const setStyle = vi+ .fn()+ .mockResolvedValueOnce({+ ok: true,+ persistence: { sourceFile: "index.html", version: "v1", changed: true },+ })+ .mockResolvedValueOnce({+ ok: true,+ persistence: { sourceFile: "index.html", version: "v2", changed: false },+ });++ const result = expectOk<StudioSetStyleResult>(+ await studioSetStyle(+ contentDeps({ setStyle }),+ styleInput({ color: "red", "font-size": "48px" }),+ ),+ );++ expect(result).toMatchObject({+ stage: "saved",+ changed: true,+ evidence: { kind: "content-version", sourceFile: "index.html", version: "v2" },+ propertyReceipts: {+ color: { stage: "saved", changed: true },+ "font-size": { stage: "saved", changed: false },+ },+ });+ });+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.@@ -209,21 +271,21 @@ describe("studioSetStyle", () => {});await studioSetStyle(contentDeps({ setStyle }), {- styles: { color: "red", "font-size": "48px", opacity: "0.5" },+ ...styleInput({ 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) =>+ const setStyle = vi.fn(async (_selection, 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" },+ ...styleInput({ color: "red", left: "10px" }),});const ok = expectOk<StudioSetStyleResult>(result);@@ -235,18 +297,18 @@ describe("studioSetStyle", () => {const result = expectFailure(await studioSetStyle(contentDeps({ setStyle: async () => ({ ok: false, reason: "styles-not-editable" }) }),- { styles: { color: "red" } },+ styleInput({ color: "red" }),),);- expect(result.kind).toBe("blocked");+ expect(result.kind).toBe("failed");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: {} }));+ const result = expectFailure(await studioSetStyle(contentDeps({ setStyle }), styleInput({})));expect(result.kind).toBe("invalid");expect(setStyle).not.toHaveBeenCalled();@@ -254,7 +316,7 @@ describe("studioSetStyle", () => {it("rejects a non-object styles value", async () => {for (const styles of ["color: red", 42, null, ["color"]]) {- const result = expectFailure(await studioSetStyle(contentDeps(), { styles }));+ const result = expectFailure(await studioSetStyle(contentDeps(), styleInput(styles)));expect(result.kind).toBe("invalid");}});@@ -265,7 +327,7 @@ describe("studioSetStyle", () => {const result = expectFailure(await studioSetStyle(contentDeps({ getWriteBlockedReason: () => "Auto-save is paused", setStyle }),- { styles: { color: "red" } },+ styleInput({ color: "red" }),),);diff --git a/packages/studio/src/webmcp/tools/contentTools.ts b/packages/studio/src/webmcp/tools/contentTools.tsindex 19d26dda39..bdebbca30a 100644--- a/packages/studio/src/webmcp/tools/contentTools.ts+++ b/packages/studio/src/webmcp/tools/contentTools.ts@@ -1,28 +1,36 @@/*** `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.+ * The explicit source-safe handle is resolved to one selection per invocation.+ * That captured selection is passed into Studio's existing commit actor; visible+ * selection is presentation only and cannot redirect the write.*/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<DomEditCommitOutcome>;- setStyle: (property: string, value: string) => Promise<DomEditCommitOutcome>;+import { toolFailure, type ToolFailure } from "../toolResult";+import {+ dispatched,+ runTargetedWrite,+ saved,+ type StudioWriteAdapterSuccess,+ type StudioWriteEvidence,+ type StudioWriteResult,+ type TargetedWriteDeps,+ WRITE_RECEIPT_DESCRIPTION,+} from "../writeCoordinator";++export interface ContentToolDeps extends TargetedWriteDeps {+ setText: (+ selection: DomEditSelection,+ value: string,+ fieldKey?: string,+ ) => Promise<DomEditCommitOutcome>;+ setStyle: (+ selection: DomEditSelection,+ property: string,+ value: string,+ ) => Promise<DomEditCommitOutcome>;}/**@@ -53,20 +61,6 @@ function fromOutcome(outcome: DomEditCommitOutcome, what: string): ToolFailure |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;@@ -74,107 +68,147 @@ export interface StudioSetTextResult {export async function studioSetText(deps: ContentToolDeps,- input: { text?: unknown; field?: unknown },-): Promise<ToolResult<StudioSetTextResult>> {+ input: { handle?: unknown; text?: unknown; field?: unknown },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioSetTextResult>> {if (typeof input.text !== "string") {- return toolFailure("invalid", "text must be a string");+ return preDispatchFailure("set-text", toolFailure("invalid", "text must be a string"));}+ const text = input.text;- const blocked = guardWrite(deps);- if (blocked) return blocked;-- 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) {+ let field: string | undefined;+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "set-text",+ signal,+ preflight: (selection) => {+ const fields = selection.textFields;+ 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"}.`,+ );+ }+ field = requested ?? (fields.length === 1 ? fields[0]?.key : undefined);+ if (field) return null;+ if (fields.length === 0) {+ return toolFailure(+ "blocked",+ "this element has no editable text field",+ "studio_inspect lists an element's textFields.",+ );+ }return toolFailure(- "blocked",- "this element has no editable text field",- "studio_inspect lists an element's textFields.",+ "invalid",+ `this element has ${fields.length} text fields, so one must be named`,+ `Pass field as one of: ${fields.map((candidate) => candidate.key).join(", ")}.`,);- }- 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;-- return toolOk<StudioSetTextResult>({ text: input.text, changed: before !== input.text });+ },+ write: async (selection) => {+ const before = selection.element.textContent;+ const outcome = await deps.setText(selection, text, field);+ if (!outcome.ok) return fromOutcome(outcome, "the text")!;+ const value = { text, changed: selection.element.textContent !== before };+ return outcome.persistence+ ? saved(value, outcome.persistence)+ : dispatched(value, value.changed);+ },+ });}export interface StudioSetStyleResult {applied: Record<string, string>;/** Properties the element refused, with the reason. Empty when all landed. */rejected: Record<string, string>;+ partial: boolean;+ propertyReceipts: Record<+ string,+ { stage: "dispatched" | "saved"; changed: boolean; evidence: StudioWriteEvidence }+ >;}export async function studioSetStyle(deps: ContentToolDeps,- input: { styles?: unknown },-): Promise<ToolResult<StudioSetStyleResult>> {+ input: { handle?: unknown; styles?: unknown },+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioSetStyleResult>> {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");+ return preDispatchFailure(+ "set-style",+ 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<string, string> = {};- const rejected: Record<string, string> = {};- for (const [property, value] of entries) {- const outcome = await deps.setStyle(property, value);- if (outcome.ok) applied[property] = value;- else rejected[property] = outcome.reason;+ return preDispatchFailure(+ "set-style",+ toolFailure("invalid", "styles must contain at least one string value"),+ );}- 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 runTargetedWrite(deps, {+ handle: input.handle,+ operation: "set-style",+ signal,+ preflight: (selection) =>+ selection.capabilities.canEditStyles+ ? null+ : toolFailure(+ "blocked",+ "this element's styles are not editable",+ "studio_inspect reports why, in can.reasonIfDisabled.",+ ),+ write: async (selection) => {+ const applied: Record<string, string> = {};+ const rejected: Record<string, string> = {};+ const propertyReceipts: StudioSetStyleResult["propertyReceipts"] = {};+ let weakest: StudioWriteAdapterSuccess<object> | null = null;+ for (const [property, value] of entries) {+ const outcome = await deps.setStyle(selection, property, value);+ if (!outcome.ok) {+ rejected[property] = outcome.reason;+ continue;+ }+ applied[property] = value;+ const receipt = outcome.persistence ? saved({}, outcome.persistence) : dispatched({}, true);+ propertyReceipts[property] = {+ stage: receipt.stage,+ changed: receipt.changed,+ evidence: receipt.evidence,+ };+ if (!weakest || weakest.stage !== "dispatched") weakest = receipt;+ }- return toolOk<StudioSetStyleResult>({ applied, rejected });+ if (!weakest) {+ const reasons = Object.entries(rejected)+ .map(([property, reason]) => `${property}: ${reason}`)+ .join(", ");+ return toolFailure("blocked", `no style was applied (${reasons})`);+ }+ const value: StudioSetStyleResult = {+ applied,+ rejected,+ partial: Object.keys(rejected).length > 0,+ propertyReceipts,+ };+ const changed = Object.values(propertyReceipts).some((receipt) => receipt.changed);+ return weakest.stage === "dispatched"+ ? dispatched(value, changed)+ : { ...weakest, ...value, changed };+ },+ });}export const STUDIO_SET_TEXT_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },text: { type: "string", description: "The new text content." },field: {type: "string",@@ -182,36 +216,46 @@ export const STUDIO_SET_TEXT_INPUT_SCHEMA = {"Which text field to write, from studio_inspect. Omit for the element's own text.",},},- required: ["text"],+ required: ["handle", "text"],additionalProperties: false,} as const;export const STUDIO_SET_TEXT_DESCRIPTION = [- "Set the text of the CURRENTLY SELECTED element. Call studio_select first.",+ "Set one element's text using its source-safe handle from studio_look.","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.",+ WRITE_RECEIPT_DESCRIPTION,].join(" ");export const STUDIO_SET_STYLE_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },styles: {type: "object",description: 'CSS property to value, for example {"color": "red", "font-size": "48px"}.',additionalProperties: { type: "string" },},},- required: ["styles"],+ required: ["handle", "styles"],additionalProperties: false,} as const;export const STUDIO_SET_STYLE_DESCRIPTION = [- "Set inline styles on the CURRENTLY SELECTED element. Call studio_select first.",+ "Set inline styles on one element using its source-safe handle from studio_look.","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.",+ WRITE_RECEIPT_DESCRIPTION,].join(" ");++function preDispatchFailure<T extends object>(+ operation: "set-text" | "set-style",+ failure: ToolFailure,+): StudioWriteResult<T> {+ return { ...failure, stage: "refused", operation };+}diff --git a/packages/studio/src/webmcp/tools/inspectTools.test.ts b/packages/studio/src/webmcp/tools/inspectTools.test.tsindex d59034a45f..f097ead711 100644--- a/packages/studio/src/webmcp/tools/inspectTools.test.ts+++ b/packages/studio/src/webmcp/tools/inspectTools.test.ts@@ -8,6 +8,8 @@ import {previewDoc,previewElement,selectionFor,+ selectionToolDeps,+ sourceHandle,} from "../webmcpTestUtils";function animation(overrides: Partial<GsapAnimation> = {}): GsapAnimation {@@ -25,11 +27,8 @@ function animation(overrides: Partial<GsapAnimation> = {}): GsapAnimation {function inspectDeps(overrides: Partial<InspectToolDeps> = {}): InspectToolDeps {return {- getPreviewDocument: () => null,- buildSelection: async (element) => selectionFor(element),- applySelection: () => undefined,- requestSeek: () => undefined,- readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),+ ...selectionToolDeps(),+ getProjectId: () => "project-a",getCurrentSelection: () => null,getGsapDiagnostics: () => ({animations: [],@@ -41,6 +40,20 @@ function inspectDeps(overrides: Partial<InspectToolDeps> = {}): InspectToolDeps}describe("studioInspect", () => {+ it("refuses a scoped handle from another project before inspecting", async () => {+ const doc = previewDoc('<h1 id="headline">Ship it</h1>');++ const result = await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), {+ handle: sourceHandle("headline", "project-b"),+ });++ expect(result).toMatchObject({+ ok: false,+ kind: "invalid",+ reason: "the handle belongs to a different project",+ });+ });+it("returns the resolved styles, not the authored ones", async () => {const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");const selection = selectionFor(element);@@ -173,6 +186,35 @@ describe("studioInspect", () => {expect(applySelection).not.toHaveBeenCalled();});+ it("keeps a resolved source-safe handle instead of weakening it", async () => {+ const doc = previewDoc(+ '<main data-composition-id="root" data-composition-file="index.html"><h1 id="headline">A</h1></main>',+ );+ const handle = "dom:v1:index.html:index.html:headline";++ const ok = expectOk<StudioInspectResult>(+ await studioInspect(inspectDeps({ getPreviewDocument: () => doc }), { handle }),+ );++ expect(ok.handle).toBe(handle);+ });++ it("mints a source-safe handle for the current selection", async () => {+ const element = previewElement('<h1 id="headline">A</h1>', "headline");+ const current = selectionFor(element, { sourceFile: "compositions/hero.html" });++ const ok = expectOk<StudioInspectResult>(+ await studioInspect(+ inspectDeps({+ getCompositionPath: () => "index.html",+ getCurrentSelection: () => current,+ }),+ ),+ );++ expect(ok.handle).toBe("dom:v2:project-a:index.html:compositions%2Fhero.html:headline");+ });+it("fails rather than returning an empty result when nothing is selected", async () => {const result = expectFailure(await studioInspect(inspectDeps()));diff --git a/packages/studio/src/webmcp/tools/inspectTools.ts b/packages/studio/src/webmcp/tools/inspectTools.tsindex f31b9fc834..2316bdd6e2 100644--- a/packages/studio/src/webmcp/tools/inspectTools.ts+++ b/packages/studio/src/webmcp/tools/inspectTools.ts@@ -14,7 +14,12 @@import type { GsapAnimation } from "@hyperframes/parsers/gsap-parser";import type { DomEditSelection } from "../../components/editor/domEditingTypes";-import { mintElementHandle, patchTargetAddress, resolveElementHandle } from "../handles";+import {+ elementHandleMatchesProject,+ mintElementHandle,+ patchTargetAddress,+ resolveLiveHandleSelection,+} from "../handles";import { toolFailure, toolOk, type ToolResult } from "../toolResult";import type { SelectionToolDeps } from "./selectionTools";@@ -94,10 +99,23 @@ function describeAnimation(animation: GsapAnimation): InspectAnimation {};}+function getAnimationEditingBlock(+ isCurrentSelection: boolean,+ diagnostics: ReturnType<InspectToolDeps["getGsapDiagnostics"]>,+): string | null {+ if (!isCurrentSelection) return "animations are only readable for the current selection";+ if (diagnostics.multipleTimelines) return "this composition has multiple GSAP timelines";+ if (diagnostics.unsupportedTimelinePattern) {+ return "this composition's timeline pattern is not editable by Studio";+ }+ return null;+}+function describe(selection: DomEditSelection,deps: InspectToolDeps,isCurrentSelection: boolean,+ resolvedHandle?: string,): ToolResult<StudioInspectResult> {const { capabilities } = selection;const gsap = deps.getGsapDiagnostics();@@ -107,17 +125,18 @@ function describe(// 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";- }+ const animationEditingBlocked = getAnimationEditingBlock(isCurrentSelection, gsap);return toolOk<StudioInspectResult>({- handle: mintElementHandle(patchTargetAddress(selection)),+ handle:+ resolvedHandle ??+ mintElementHandle(+ patchTargetAddress(+ selection,+ deps.getCompositionPath() ?? "index.html",+ deps.getProjectId(),+ ),+ ),label: selection.label,tagName: selection.tagName,sourceFile: selection.sourceFile,@@ -165,25 +184,46 @@ export async function studioInspect(}return describe(current, deps, true);}+ if (!elementHandleMatchesProject(input.handle, deps.getProjectId())) {+ return toolFailure(+ "invalid",+ "the handle belongs to a different project",+ "Call studio_look in the active project.",+ );+ }- const doc = deps.getPreviewDocument();- if (!doc) return toolFailure("blocked", "the preview is not mounted yet");-- const element = resolveElementHandle(doc, input.handle);- if (!element) {+ const resolved = await resolveLiveHandleSelection(+ deps.getPreviewDocument,+ input.handle,+ deps.buildSelection,+ );+ if (resolved.status === "preview-unavailable") {+ return toolFailure("blocked", "the preview is not mounted yet");+ }+ if (resolved.status === "not-found") {return toolFailure("invalid",`no element matches handle ${input.handle}`,"Call studio_look for current handles.",);}-- const selection = await deps.buildSelection(element);- if (!selection) {+ if (resolved.status === "unsupported") {return toolFailure("blocked", `${input.handle} resolved to an element Studio cannot inspect`);}+ if (resolved.status === "changed") {+ return toolFailure(+ "invalid",+ "the target changed while it was resolving",+ "Call studio_look again.",+ );+ }- return describe(selection, deps, current?.element === element);+ return describe(+ resolved.selection,+ deps,+ current?.element === resolved.selection.element,+ input.handle,+ );}export const STUDIO_INSPECT_INPUT_SCHEMA = {diff --git a/packages/studio/src/webmcp/tools/lookTools.test.ts b/packages/studio/src/webmcp/tools/lookTools.test.tsindex 33c37ce9c6..4daa3e200e 100644--- a/packages/studio/src/webmcp/tools/lookTools.test.ts+++ b/packages/studio/src/webmcp/tools/lookTools.test.ts@@ -2,7 +2,12 @@import { describe, expect, it } from "vitest";import type { DomEditSelection } from "../../components/editor/domEditingTypes";import type { TimelineElement } from "../../player/store/timelineElement";-import { buildStudioLook, STUDIO_LOOK_INPUT_SCHEMA, type StudioLookSnapshot } from "./lookTools";+import {+ buildStudioLook,+ collectStudioLookScene,+ STUDIO_LOOK_INPUT_SCHEMA,+ type StudioLookSnapshot,+} from "./lookTools";function element(overrides: Partial<TimelineElement>): TimelineElement {return { id: "synthetic", tag: "div", start: 0, duration: 1, track: 0, ...overrides };@@ -16,6 +21,7 @@ function snapshot(overrides: Partial<StudioLookSnapshot> = {}): StudioLookSnapshduration: 10,isPlaying: false,elements: [],+ scene: { status: "ready", items: [], drillInItem: null },selection: null,selectionAnimationCount: 0,history: { canUndo: true, canRedo: false, undoLabel: "Move layer", redoLabel: null },@@ -84,90 +90,140 @@ describe("buildStudioLook", () => {const look = expectOk<{ elements: { handle: string | null; label: string | null }[] }>(buildStudioLook(snapshot({- elements: [- element({ hfId: "abc", label: "Headline" }),- element({ domId: "cta", label: "Button" }),- element({ selector: ".card", selectorIndex: 2, label: "Card" }),- ],+ scene: {+ status: "ready",+ items: [+ layer("Headline", { hfId: "abc" }),+ layer("Button", { id: "cta" }),+ layer("Card", { selector: ".card", selectorIndex: 2 }),+ ],+ drillInItem: null,+ },}),),);- expect(look.elements.map((e) => e.handle)).toEqual(["hf:abc", "dom:cta", "sel:.card#2"]);+ expect(look.elements.map((e) => e.handle)).toEqual([+ "hf:v2:demo:index.html:index.html:abc",+ "dom:v2:demo:index.html:index.html:cta",+ "sel:v2:demo:index.html:index.html:.card#2",+ ]);});- it("reports an unaddressable element with a null handle rather than hiding it", () => {- const look = expectOk<{ elements: { handle: string | null }[]; elementCount: number }>(- buildStudioLook(snapshot({ elements: [element({ label: "Anonymous" })] })),+ it("distinguishes an empty ready scene from a preview that is still loading", () => {+ const ready = expectOk<{ sceneStatus: string; elements: unknown[]; elementCount: number }>(+ buildStudioLook(snapshot()),+ );+ const loading = expectOk<{ sceneStatus: string; elements: unknown[]; elementCount: number }>(+ buildStudioLook(snapshot({ scene: { status: "loading" } })),);- expect(look.elementCount).toBe(1);- expect(look.elements[0]?.handle).toBeNull();+ expect(ready).toMatchObject({ sceneStatus: "ready", elements: [], elementCount: 0 });+ expect(loading).toMatchObject({ sceneStatus: "loading", elements: [], elementCount: 0 });});- it("returns an empty list for an empty timeline, not a failure", () => {- const look = expectOk<{ elements: unknown[]; elementCount: number }>(- buildStudioLook(snapshot()),- );-- expect(look.elements).toEqual([]);- expect(look.elementCount).toBe(0);+ it("treats an about-blank iframe as loading and a mounted empty composition as ready", () => {+ const blank = document.implementation.createHTMLDocument();+ const mounted = document.implementation.createHTMLDocument();+ mounted.body.innerHTML =+ '<main data-composition-id="root" data-composition-file="index.html"></main>';++ expect(collectStudioLookScene(blank, "index.html", null)).toEqual({ status: "loading" });+ expect(collectStudioLookScene(mounted, "index.html", null)).toEqual({+ status: "ready",+ items: [],+ drillInItem: null,+ });});it("filters on label, tag and handle, case-insensitively", () => {- const elements = [- element({ hfId: "abc", label: "Headline", tag: "h1" }),- element({ domId: "cta", label: "Button", tag: "button" }),+ const items = [+ layer("Headline", { hfId: "abc", tagName: "h1" }),+ layer("Button", { id: "cta", tagName: "button" }),];const byLabel = expectOk<{ elements: { handle: string | null }[] }>(- buildStudioLook(snapshot({ elements }), { filter: "HEADLINE" }),+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } }), {+ filter: "HEADLINE",+ }),);const byTag = expectOk<{ elements: { handle: string | null }[] }>(- buildStudioLook(snapshot({ elements }), { filter: "button" }),+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } }), {+ filter: "button",+ }),);const byHandle = expectOk<{ elements: { handle: string | null }[] }>(- buildStudioLook(snapshot({ elements }), { filter: "hf:abc" }),+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } }), {+ filter: "hf:v2:demo:index.html:index.html:abc",+ }),);- expect(byLabel.elements.map((e) => e.handle)).toEqual(["hf:abc"]);- expect(byTag.elements.map((e) => e.handle)).toEqual(["dom:cta"]);- expect(byHandle.elements.map((e) => e.handle)).toEqual(["hf:abc"]);+ expect(byLabel.elements.map((e) => e.handle)).toEqual(["hf:v2:demo:index.html:index.html:abc"]);+ expect(byTag.elements.map((e) => e.handle)).toEqual(["dom:v2:demo:index.html:index.html:cta"]);+ expect(byHandle.elements.map((e) => e.handle)).toEqual([+ "hf:v2:demo:index.html:index.html:abc",+ ]);});it("bounds a filter before normalizing it", () => {const boundedFilter = "x".repeat(128);const look = expectOk<{ elements: { handle: string | null }[] }>(buildStudioLook(- snapshot({ elements: [element({ domId: "bounded", label: boundedFilter })] }),+ snapshot({+ scene: {+ status: "ready",+ items: [layer(boundedFilter, { id: "bounded" })],+ drillInItem: null,+ },+ }),{ filter: `${boundedFilter}${"y".repeat(10_000)}` },),);- expect(look.elements.map((entry) => entry.handle)).toEqual(["dom:bounded"]);+ expect(look.elements.map((entry) => entry.handle)).toEqual([+ "dom:v2:demo:index.html:index.html:bounded",+ ]);expect(STUDIO_LOOK_INPUT_SCHEMA.properties.filter.maxLength).toBe(128);});it("keeps the true match count when the list is truncated", () => {- const elements = Array.from({ length: 5 }, (_, index) =>- element({ domId: `el-${index}`, label: "Card" }),- );+ const items = Array.from({ length: 5 }, (_, index) => layer("Card", { id: `el-${index}` }));- const look = expectOk<{ elements: unknown[]; elementCount: number }>(- buildStudioLook(snapshot({ elements }), { limit: 2 }),+ const look = expectOk<{ elements: unknown[]; elementCount: number; truncated: boolean }>(+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } }), {+ filter: "card",+ limit: 2,+ }),);// A truncated list must not read as "that is all there is".expect(look.elements).toHaveLength(2);expect(look.elementCount).toBe(5);+ expect(look.truncated).toBe(true);+ });++ it("preserves the 200-item default and maximum response bound", () => {+ const items = Array.from({ length: 205 }, (_, index) =>+ layer(`Layer ${index}`, { id: `el-${index}` }),+ );++ const look = expectOk<{ elements: unknown[]; elementCount: number; truncated: boolean }>(+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } })),+ );++ expect(look.elements).toHaveLength(200);+ expect(look.elementCount).toBe(205);+ expect(look.truncated).toBe(true);});it("clamps a nonsense limit instead of failing the call", () => {- const elements = [element({ domId: "a" }), element({ domId: "b" })];+ const items = [layer("A", { id: "a" }), layer("B", { id: "b" })];for (const limit of [0, -3, 1.5, Number.NaN]) {const look = expectOk<{ elements: unknown[] }>(- buildStudioLook(snapshot({ elements }), { limit }),+ buildStudioLook(snapshot({ scene: { status: "ready", items, drillInItem: null } }), {+ limit,+ }),);expect(look.elements).toHaveLength(2);}@@ -178,7 +234,7 @@ describe("buildStudioLook", () => {selection: { handle: string | null; box: { width: number }; can: { editStyles: boolean } };}>(buildStudioLook(snapshot({ selection: selection() })));- expect(look.selection?.handle).toBe("hf:abc123");+ expect(look.selection?.handle).toBe("hf:v2:demo:index.html:index.html:abc123");expect(look.selection?.box.width).toBe(880);expect(look.selection?.can.editStyles).toBe(true);});@@ -222,4 +278,95 @@ describe("buildStudioLook", () => {expect(look).not.toHaveProperty("canWrite");expect(look).not.toHaveProperty("writeBlockedReason");});++ it("returns DOM preorder with source-safe parents, DOM-only descendants, and optional timeline timing", () => {+ const doc = sceneDoc();+ const scene = collectStudioLookScene(doc, "index.html", null);+ const look = expectOk<{+ elements: Array<{+ handle: string;+ parentHandle: string | null;+ depth: number;+ sourceFile: string;+ timeline: { start: number } | null;+ }>;+ }>(+ buildStudioLook(+ snapshot({+ scene,+ elements: [+ element({ domId: "shell", sourceFile: "index.html", start: 2 }),+ element({ domId: "duplicate", sourceFile: "compositions/nested.html", start: 4 }),+ ],+ }),+ ),+ );++ expect(look.elements.map(({ sourceFile, depth }) => [sourceFile, depth])).toEqual([+ ["index.html", 0],+ ["index.html", 1],+ ["index.html", 1],+ ["compositions/nested.html", 1],+ ["compositions/nested.html", 2],+ ]);+ expect(look.elements[1]?.parentHandle).toBe(look.elements[0]?.handle);+ expect(look.elements[4]?.parentHandle).toBe(look.elements[3]?.handle);+ expect(look.elements[2]?.timeline).toBeNull();+ expect(look.elements[4]?.timeline?.start).toBe(4);+ expect(look.elements[1]?.handle).not.toBe(look.elements[4]?.handle);+ });++ it("reports the current drill-in group separately without narrowing the whole scene", () => {+ const doc = sceneDoc();+ const group = doc.getElementById("nested-parent") as HTMLElement;+ const look = expectOk<{+ drillIn: { handle: string; label: string } | null;+ elements: unknown[];+ }>(buildStudioLook(snapshot({ scene: collectStudioLookScene(doc, "index.html", group) })));++ expect(look.elements).toHaveLength(5);+ expect(look.drillIn?.handle).toContain("nested-parent");+ });});++function layer(+ label: string,+ overrides: Partial<{+ id: string;+ hfId: string;+ selector: string;+ selectorIndex: number;+ sourceFile: string;+ tagName: string;+ depth: number;+ childCount: number;+ }> = {},+) {+ const element = document.createElement(overrides.tagName ?? "div");+ return {+ key: label,+ element,+ label,+ tagName: overrides.tagName ?? "div",+ depth: overrides.depth ?? 0,+ childCount: overrides.childCount ?? 0,+ sourceFile: overrides.sourceFile ?? "index.html",+ ...overrides,+ };+}++function sceneDoc(): Document {+ const doc = document.implementation.createHTMLDocument();+ doc.body.innerHTML = `<main data-composition-id="root" data-composition-file="index.html">+ <section id="shell">+ <span id="duplicate">root duplicate</span>+ <em class="dom-only">no timeline</em>+ <div data-composition-id="nested" data-composition-file="compositions/nested.html">+ <section id="nested-parent" data-hf-group>+ <span id="duplicate">nested duplicate</span>+ </section>+ </div>+ </section>+ </main>`;+ return doc;+}diff --git a/packages/studio/src/webmcp/tools/lookTools.ts b/packages/studio/src/webmcp/tools/lookTools.tsindex 1cadcffb2b..16ef97558c 100644--- a/packages/studio/src/webmcp/tools/lookTools.ts+++ b/packages/studio/src/webmcp/tools/lookTools.ts@@ -8,11 +8,20 @@* values. Gathering the snapshot is the React layer's job.*/-import type { DomEditSelection } from "../../components/editor/domEditingTypes";+import { collectDomEditLayerItems } from "../../components/editor/domEditingLayers";+import type { DomEditLayerItem, DomEditSelection } from "../../components/editor/domEditingTypes";import type { TimelineElement } from "../../player/store/timelineElement";import { mintElementHandle, patchTargetAddress, timelineElementAddress } from "../handles";import { toolOk, type ToolResult } from "../toolResult";+export type StudioLookSceneSnapshot =+ | { status: "loading" }+ | {+ status: "ready";+ items: readonly DomEditLayerItem[];+ drillInItem: DomEditLayerItem | null;+ };+export interface StudioLookSnapshot {projectId: string | null;compositionPath: string | null;@@ -20,6 +29,7 @@ export interface StudioLookSnapshot {duration: number;isPlaying: boolean;elements: readonly TimelineElement[];+ scene: StudioLookSceneSnapshot;selection: DomEditSelection | null;/** Live animations for the current selection arrive outside DomEditSelection. */selectionAnimationCount: number;@@ -41,16 +51,24 @@ export interface StudioLookSnapshot {};}-interface LookElement {- /** Pass back to any tool that takes a handle. Null means unaddressable. */- handle: string | null;- label: string | null;- tag: string;- kind: string | null;+interface LookTimeline {start: number;duration: number;track: number;zIndex: number | null;+ kind: string | null;+}++interface LookElement {+ /** Pass back unchanged to tools that take a handle. */+ handle: string;+ parentHandle: string | null;+ label: string;+ tag: string;+ depth: number;+ childCount: number;+ sourceFile: string;+ timeline: LookTimeline | null;}interface LookSelection {@@ -84,7 +102,10 @@ export interface StudioLook {isPlaying: boolean;history: StudioLookSnapshot["history"];selection: LookSelection | null;+ sceneStatus: StudioLookSceneSnapshot["status"];+ drillIn: { handle: string; label: string; sourceFile: string } | null;elementCount: number;+ truncated: boolean;elements: LookElement[];}@@ -98,23 +119,25 @@ export interface StudioLookInput {const DEFAULT_LIMIT = 200;const MAX_FILTER_LENGTH = 128;-function describeElement(element: TimelineElement): LookElement {+function describeTimeline(element: TimelineElement): LookTimeline {return {- handle: mintElementHandle(timelineElementAddress(element)),- label: element.label ?? null,- tag: element.tag,- kind: element.kind ?? null,start: element.start,duration: element.duration,track: element.track,zIndex: element.zIndex ?? null,+ kind: element.kind ?? null,};}-function describeSelection(selection: DomEditSelection, animationCount: number): LookSelection {+function describeSelection(+ selection: DomEditSelection,+ animationCount: number,+ activeCompositionPath: string,+ projectId: string | null,+): LookSelection {const { capabilities } = selection;return {- handle: mintElementHandle(patchTargetAddress(selection)),+ handle: mintElementHandle(patchTargetAddress(selection, activeCompositionPath, projectId)),label: selection.label,tagName: selection.tagName,sourceFile: selection.sourceFile,@@ -133,21 +156,102 @@ function describeSelection(selection: DomEditSelection, animationCount: number):function matchesFilter(element: LookElement, needle: string): boolean {return (- (element.label?.toLowerCase().includes(needle) ?? false) ||+ element.label.toLowerCase().includes(needle) ||element.tag.toLowerCase().includes(needle) ||- (element.handle?.toLowerCase().includes(needle) ?? false)+ element.handle.toLowerCase().includes(needle));}+/** Gather the live scene once per tool call. The response never retains DOM nodes. */+export function collectStudioLookScene(+ doc: Document | null,+ activeCompositionPath: string | null,+ activeGroupElement: HTMLElement | null,+): StudioLookSceneSnapshot {+ if (!doc) return { status: "loading" };++ const root = doc.querySelector<HTMLElement>("[data-composition-id]");+ if (!root) return { status: "loading" };++ const options = {+ activeCompositionPath,+ isMasterView: !activeCompositionPath || activeCompositionPath === "index.html",+ activeGroupElement: null,+ };+ const items = collectDomEditLayerItems(root, options);+ const liveGroup =+ activeGroupElement?.isConnected && activeGroupElement.ownerDocument === doc+ ? activeGroupElement+ : null;+ return {+ status: "ready",+ items,+ drillInItem: liveGroup ? (items.find((item) => item.element === liveGroup) ?? null) : null,+ };+}++function describeScene(snapshot: StudioLookSnapshot): {+ elements: LookElement[];+ drillIn: StudioLook["drillIn"];+} {+ if (snapshot.scene.status === "loading") return { elements: [], drillIn: null };++ const activeCompositionPath = snapshot.compositionPath ?? "index.html";+ const timelineByHandle = new Map<string, LookTimeline>();+ for (const element of snapshot.elements) {+ const handle = mintElementHandle(+ timelineElementAddress(element, activeCompositionPath, snapshot.projectId),+ );+ if (handle) timelineByHandle.set(handle, describeTimeline(element));+ }++ const parentHandles: string[] = [];+ const elements = snapshot.scene.items.map((item) => {+ const handle = mintElementHandle(+ patchTargetAddress(item, activeCompositionPath, snapshot.projectId),+ );+ if (!handle) throw new Error("collectDomEditLayerItems returned an unaddressable layer");+ const parentHandle = item.depth > 0 ? (parentHandles[item.depth - 1] ?? null) : null;+ parentHandles[item.depth] = handle;+ parentHandles.length = item.depth + 1;+ return {+ handle,+ parentHandle,+ label: item.label,+ tag: item.tagName,+ depth: item.depth,+ childCount: item.childCount,+ sourceFile: item.sourceFile,+ timeline: timelineByHandle.get(handle) ?? null,+ };+ });++ const drillInItem = snapshot.scene.drillInItem;+ const drillInHandle = drillInItem+ ? mintElementHandle(patchTargetAddress(drillInItem, activeCompositionPath, snapshot.projectId))+ : null;+ return {+ elements,+ drillIn:+ drillInItem && drillInHandle+ ? {+ handle: drillInHandle,+ label: drillInItem.label,+ sourceFile: drillInItem.sourceFile,+ }+ : null,+ };+}+export function buildStudioLook(snapshot: StudioLookSnapshot,input: StudioLookInput = {},): ToolResult<StudioLook> {- const described = snapshot.elements.map(describeElement);+ const scene = describeScene(snapshot);const needle = input.filter?.slice(0, MAX_FILTER_LENGTH).trim().toLowerCase();const matched = needle- ? described.filter((element) => matchesFilter(element, needle))- : described;+ ? scene.elements.filter((element) => matchesFilter(element, needle))+ : scene.elements;// Clamp rather than reject: a bad limit should not cost the agent a round trip// when the answer it wants is right here.@@ -163,11 +267,19 @@ export function buildStudioLook(isPlaying: snapshot.isPlaying,history: snapshot.history,selection: snapshot.selection- ? describeSelection(snapshot.selection, snapshot.selectionAnimationCount)+ ? describeSelection(+ snapshot.selection,+ snapshot.selectionAnimationCount,+ snapshot.compositionPath ?? "index.html",+ snapshot.projectId,+ ): null,+ sceneStatus: snapshot.scene.status,+ drillIn: scene.drillIn,// The count is of everything that MATCHED, so a truncated list is visible// as a truncated list rather than reading as "that is all there is".elementCount: matched.length,+ truncated: matched.length > limit,elements: matched.slice(0, limit),});}@@ -193,7 +305,8 @@ export const STUDIO_LOOK_INPUT_SCHEMA = {export const STUDIO_LOOK_DESCRIPTION = ["Read HyperFrames Studio's live state in one call: the open project and composition,","the playhead and duration, what the human currently has selected (including what that",- "element will and will not accept), and the timeline's elements with a handle for each.",+ "element will and will not accept), and the live nested scene in DOM preorder.",+ "Each scene element includes source ownership, hierarchy, and optional timeline timing.","Pass a handle back to any tool that edits an element.","Returns an object with `ok: true`, or `ok: false` with `kind`, `reason` and often a `hint`.","`history.undoLabel` is worth checkpointing before a batch: if it later names something",diff --git a/packages/studio/src/webmcp/tools/selectionTools.test.ts b/packages/studio/src/webmcp/tools/selectionTools.test.tsindex 07168529ae..ec637bfd0b 100644--- a/packages/studio/src/webmcp/tools/selectionTools.test.ts+++ b/packages/studio/src/webmcp/tools/selectionTools.test.ts@@ -7,20 +7,37 @@ import {type StudioSeekResult,type StudioSelectResult,} from "./selectionTools";-import { expectFailure, expectOk, previewDoc, selectionFor } from "../webmcpTestUtils";+import {+ expectFailure,+ expectOk,+ previewDoc,+ selectionFor,+ selectionToolDeps,+ sourceHandle,+} from "../webmcpTestUtils";function selectionDeps(overrides: Partial<SelectionToolDeps> = {}): SelectionToolDeps {- return {- getPreviewDocument: () => null,- buildSelection: async (element) => selectionFor(element),- applySelection: () => undefined,- requestSeek: () => undefined,- readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),- ...overrides,- };+ return selectionToolDeps(overrides);}describe("studioSelect", () => {+ it("refuses a scoped handle from another project before selecting", async () => {+ const doc = previewDoc('<h1 id="headline">Ship it</h1>');+ const applySelection = vi.fn();++ const result = await studioSelect(+ selectionDeps({ getPreviewDocument: () => doc, applySelection }),+ sourceHandle("headline", "project-b"),+ );++ expect(result).toMatchObject({+ ok: false,+ kind: "invalid",+ reason: "the handle belongs to a different project",+ });+ expect(applySelection).not.toHaveBeenCalled();+ });+it("applies the selection a click would produce and reports it back", async () => {const doc = previewDoc('<h1 id="headline" data-hf-id="abc">Ship it</h1>');const applySelection = vi.fn();@@ -38,6 +55,85 @@ describe("studioSelect", () => {expect(applySelection).toHaveBeenCalledTimes(1);});+ it("returns the exact source-safe handle it resolved", async () => {+ const doc = previewDoc(+ '<main data-composition-id="root" data-composition-file="index.html"><h1 id="headline">Ship it</h1></main>',+ );+ const handle = "dom:v1:index.html:index.html:headline";++ const ok = expectOk<StudioSelectResult>(+ await studioSelect(selectionDeps({ getPreviewDocument: () => doc }), handle),+ );++ expect(ok.handle).toBe(handle);+ });++ it("reacquires once when the preview document reloads during selection resolution", async () => {+ const firstDoc = previewDoc('<h1 data-hf-id="abc">Old preview</h1>');+ const nextDoc = previewDoc('<h1 data-hf-id="abc">Current preview</h1>');+ let currentDoc = firstDoc;+ const buildSelection = vi.fn(async (element: HTMLElement) => {+ if (element.ownerDocument === firstDoc) {+ currentDoc = nextDoc;+ return selectionFor(element, { boundingBox: { x: 0, y: 0, width: 0, height: 0 } });+ }+ return selectionFor(element, {+ boundingBox: { x: 98, y: 206, width: 304, height: 50 },+ });+ });+ const applySelection = vi.fn();++ const ok = expectOk<StudioSelectResult>(+ await studioSelect(+ selectionDeps({+ getPreviewDocument: () => currentDoc,+ buildSelection,+ applySelection,+ }),+ "hf:abc",+ ),+ );++ expect(ok.box).toEqual({ x: 98, y: 206, width: 304, height: 50 });+ expect(buildSelection).toHaveBeenCalledTimes(2);+ expect(applySelection).toHaveBeenCalledWith(+ expect.objectContaining({ element: nextDoc.querySelector("h1") }),+ );+ });++ it("refuses when the preview changes again during the bounded reacquire", async () => {+ const documents = [+ previewDoc('<h1 data-hf-id="abc">First preview</h1>'),+ previewDoc('<h1 data-hf-id="abc">Second preview</h1>'),+ previewDoc('<h1 data-hf-id="abc">Third preview</h1>'),+ ];+ let currentIndex = 0;+ const buildSelection = vi.fn(async (element: HTMLElement) => {+ currentIndex += 1;+ return selectionFor(element);+ });+ const applySelection = vi.fn();++ const failure = expectFailure(+ await studioSelect(+ selectionDeps({+ getPreviewDocument: () => documents[currentIndex] ?? documents.at(-1)!,+ buildSelection,+ applySelection,+ }),+ "hf:abc",+ ),+ );++ expect(failure).toMatchObject({+ kind: "invalid",+ reason: "the target changed while it was resolving",+ hint: "Call studio_look again.",+ });+ expect(buildSelection).toHaveBeenCalledTimes(2);+ expect(applySelection).not.toHaveBeenCalled();+ });+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");diff --git a/packages/studio/src/webmcp/tools/selectionTools.ts b/packages/studio/src/webmcp/tools/selectionTools.tsindex fa40f52d8f..166193658f 100644--- a/packages/studio/src/webmcp/tools/selectionTools.ts+++ b/packages/studio/src/webmcp/tools/selectionTools.ts@@ -2,21 +2,20 @@* `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.+ * Selection is shared human-visible state. Element writes do not infer their+ * target from it: they resolve an explicit source-safe handle per call. Keeping+ * these contracts separate means a human click cannot redirect an agent write.*/import type { DomEditSelection } from "../../components/editor/domEditingTypes";-import { mintElementHandle, patchTargetAddress, resolveElementHandle } from "../handles";+import { elementHandleMatchesProject, resolveLiveHandleSelection } 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;+ getCompositionPath: () => string | null;+ getProjectId: () => string | null;buildSelection: (element: HTMLElement) => Promise<DomEditSelection | null>;applySelection: (selection: DomEditSelection) => void;/** Out-of-loop seek. `requestSeek`, not `setCurrentTime`. */@@ -25,7 +24,7 @@ export interface SelectionToolDeps {}export interface StudioSelectResult {- handle: string | null;+ handle: string;label: string;tagName: string;box: { x: number; y: number; width: number; height: number };@@ -38,41 +37,56 @@ export async function studioSelect(if (typeof handle !== "string" || !handle.trim()) {return toolFailure("invalid", "handle must be a non-empty string", "Call studio_look first.");}+ if (!elementHandleMatchesProject(handle, deps.getProjectId())) {+ return toolFailure(+ "invalid",+ "the handle belongs to a different project",+ "Call studio_look in the active project.",+ );+ }// 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) {+ const resolved = await resolveLiveHandleSelection(+ deps.getPreviewDocument,+ handle,+ deps.buildSelection,+ );+ if (resolved.status === "preview-unavailable") {return toolFailure("blocked","the preview is not mounted yet","Wait for the composition to load, then retry.",);}-- const element = resolveElementHandle(doc, handle);- if (!element) {+ if (resolved.status === "not-found") {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) {+ if (resolved.status === "unsupported") {return toolFailure("blocked",`${handle} resolved to an element Studio cannot select`,"Try a parent or child element from studio_look.",);}+ if (resolved.status === "changed") {+ return toolFailure(+ "invalid",+ "the target changed while it was resolving",+ "Call studio_look again.",+ );+ }+ const { selection } = resolved;deps.applySelection(selection);return toolOk<StudioSelectResult>({- handle: mintElementHandle(patchTargetAddress(selection)),+ handle,label: selection.label,tagName: selection.tagName,box: selection.boundingBox,@@ -132,8 +146,9 @@ export const STUDIO_SELECT_INPUT_SCHEMA = {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.",+ "Call this before the first write to a target so the human sees the agent's intent.",+ "Takes a handle from studio_look. Selection is visual context for the human;",+ "element writes take their own explicit handle and do not require this tool first.","Returns `ok: true` with the resulting selection, or `ok: false` with `kind`, `reason` and a `hint`.",].join(" ");diff --git a/packages/studio/src/webmcp/tools/targetedWriteTools.test.ts b/packages/studio/src/webmcp/tools/targetedWriteTools.test.tsnew file mode 100644index 0000000000..d3b07f9c81--- /dev/null+++ b/packages/studio/src/webmcp/tools/targetedWriteTools.test.ts@@ -0,0 +1,125 @@+// @vitest-environment jsdom+import { describe, expect, it, vi } from "vitest";+import { mintElementHandle } from "../handles";+import { previewDoc, selectionFor } from "../webmcpTestUtils";+import {+ studioAddAnimation,+ studioAddKeyframe,+ studioDeleteAnimation,+ studioUpdateAnimation,+ type AnimationToolDeps,+} from "./animationTools";+import { studioTransform, type ElementBox, type TransformToolDeps } from "./transformTools";++function target() {+ const doc = previewDoc('<div id="agent">Agent</div>');+ const element = doc.getElementById("agent") as HTMLElement;+ const handle = mintElementHandle({+ projectId: "demo",+ domId: "agent",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ if (!handle) throw new Error("expected handle");+ const common = {+ getPreviewDocument: () => doc,+ getCompositionPath: () => "index.html",+ getProjectId: () => "demo",+ getWriteBlockedReason: () => null,+ buildSelection: async (targetElement: HTMLElement) => selectionFor(targetElement),+ applySelection: () => undefined,+ };+ return { common, element, handle };+}++function transformDeps(+ common: ReturnType<typeof target>["common"],+ box: ElementBox,+ overrides: Partial<TransformToolDeps> = {},+): TransformToolDeps {+ return {+ ...common,+ readBox: () => ({ ...box }),+ moveTo: async () => undefined,+ resizeTo: async () => undefined,+ rotateTo: async () => undefined,+ ...overrides,+ };+}++function animationDeps(+ common: ReturnType<typeof target>["common"],+ overrides: Partial<AnimationToolDeps> = {},+): AnimationToolDeps {+ return {+ ...common,+ getAnimationsForSelection: async () => [{ id: "anim-1" }],+ readPlayhead: () => ({ currentTime: 2, duration: 10, isPlaying: false }),+ addAnimation: async () => true,+ updateAnimation: async () => true,+ addKeyframe: async () => undefined,+ deleteAnimation: async () => true,+ ...overrides,+ };+}++describe("targeted write actor families", () => {+ it("passes the live handle selection to transform and every animation actor", async () => {+ const { common, element, handle } = target();+ const box = { x: 0, y: 0, width: 100, height: 50 };+ const moveTo = vi.fn(async (_selection, next: { x: number; y: number }) => {+ Object.assign(box, next);+ });+ const addAnimation = vi.fn();+ const updateAnimation = vi.fn(async () => true);+ const addKeyframe = vi.fn(async () => undefined);+ const deleteAnimation = vi.fn();++ await studioTransform(transformDeps(common, box, { moveTo }), { handle, x: 20, y: 30 });+ const animations = animationDeps(common, {+ addAnimation,+ updateAnimation,+ addKeyframe,+ deleteAnimation,+ });+ await studioAddAnimation(animations, { handle, method: "to" });+ await studioUpdateAnimation(animations, { handle, animationId: "anim-1", duration: 2 });+ await studioAddKeyframe(animations, {+ handle,+ animationId: "anim-1",+ percent: 50,+ properties: { opacity: 0 },+ });+ await studioDeleteAnimation(animations, { handle, animationId: "anim-1" });++ for (const actor of [moveTo, addAnimation, updateAnimation, addKeyframe, deleteAnimation]) {+ expect(actor.mock.calls[0]?.[0]).toEqual(expect.objectContaining({ element }));+ }+ });++ it("keeps mixed durable and void transform operations at dispatched", async () => {+ const { common, handle } = target();+ const box = { x: 0, y: 0, width: 100, height: 50 };+ const result = await studioTransform(+ transformDeps(common, box, {+ resizeTo: async (_selection, next) => {+ Object.assign(box, next);+ return {+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:size"',+ changed: true,+ },+ };+ },+ moveTo: async (_selection, next) => {+ Object.assign(box, next);+ },+ }),+ { handle, width: 200, height: 80, x: 20, y: 30 },+ );++ expect(result).toMatchObject({ ok: true, stage: "dispatched" });+ });+});diff --git a/packages/studio/src/webmcp/tools/transformTools.test.ts b/packages/studio/src/webmcp/tools/transformTools.test.tsindex b438ed9e5d..5eea971561 100644--- a/packages/studio/src/webmcp/tools/transformTools.test.ts+++ b/packages/studio/src/webmcp/tools/transformTools.test.ts@@ -6,7 +6,19 @@ import {type StudioTransformResult,type TransformToolDeps,} from "./transformTools";-import { expectFailure, expectOk, previewElement, selectionFor } from "../webmcpTestUtils";+import {+ expectFailure,+ expectOk,+ previewElement,+ selectionFor,+ sourceHandle,+ targetedWriteDeps,+} from "../webmcpTestUtils";++const transformInput = (input: Record<string, unknown>) => ({+ handle: sourceHandle("headline"),+ ...input,+});/*** A stand-in for the rendered box. happy-dom and jsdom report all-zero rects,@@ -23,9 +35,9 @@ function boxStore(initial: ElementBox) {function transformDeps(overrides: Partial<TransformToolDeps> = {}): TransformToolDeps {const element = previewElement('<h1 id="headline">Ship it</h1>', "headline");+ const selection = selectionFor(element);return {- getCurrentSelection: () => selectionFor(element),- getWriteBlockedReason: () => null,+ ...targetedWriteDeps(selection),readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }),moveTo: async () => undefined,resizeTo: async () => undefined,@@ -34,16 +46,31 @@ function transformDeps(overrides: Partial<TransformToolDeps> = {}): TransformToo};}+async function resizeAndMove(moveLands: boolean): Promise<StudioTransformResult> {+ 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 () => {+ if (moveLands) store.set({ x: 40, y: 40 });+ });+ const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo, moveTo }), {+ ...transformInput({ x: 40, y: 40, width: 200, height: 80 }),+ });+ return expectOk<StudioTransformResult>(result);+}+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 resizeTo = vi.fn(async () => {+ store.set({ width: 300, height: 120 });+ });const result = await studioTransform(transformDeps({ readBox: store.read, resizeTo }), {- width: 999,- height: 999,+ ...transformInput({ width: 999, height: 999 }),});const ok = expectOk<StudioTransformResult>(result);@@ -52,69 +79,122 @@ describe("studioTransform", () => {expect(ok.applied).toContain("resize");});- it("reports a silent no-op as unchanged instead of success", async () => {+ it("reports a void actor's silent no-op as dispatched and unchanged", 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 }),+ const result = expectOk<StudioTransformResult>(+ await studioTransform(+ transformDeps({ readBox: store.read, moveTo }),+ transformInput({ x: 500, y: 400 }),+ ),);expect(moveTo).toHaveBeenCalled();- expect(result.kind).toBe("blocked");- expect(result.reason).toMatch(/did not move/);- expect(result.hint).toMatch(/GSAP/);+ expect(result.stage).toBe("dispatched");+ expect(result.unchanged.move).toMatch(/did not move/);});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 result = await resizeAndMove(false);- const ok = expectOk<StudioTransformResult>(result);- expect(ok.applied).toEqual(["resize"]);- expect(ok.unchanged.move).toMatch(/did not move/);+ expect(result.applied).toEqual(["resize"]);+ expect(result.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,- });+ const result = await resizeAndMove(true);// 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<StudioTransformResult>(result);- expect(ok.applied).toEqual(["resize", "move"]);- expect(ok.unchanged).toEqual({});+ expect(result.applied).toEqual(["resize", "move"]);+ expect(result.unchanged).toEqual({});});- it("reports rotation as dispatched rather than verified", async () => {+ it("reports durable partial success when a later operation fails", async () => {+ const store = boxStore({ x: 0, y: 0, width: 100, height: 50 });+ const result = expectOk<StudioTransformResult>(+ await studioTransform(+ transformDeps({+ readBox: store.read,+ resizeTo: async () => {+ store.set({ width: 200, height: 80 });+ return {+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:resize"',+ changed: true,+ },+ };+ },+ moveTo: async () => ({ ok: false, reason: "the move actor failed" }),+ }),+ transformInput({ width: 200, height: 80, x: 40, y: 40 }),+ ),+ );++ expect(result).toMatchObject({+ stage: "saved",+ changed: true,+ partial: true,+ applied: ["resize"],+ failed: { move: expect.stringContaining("move actor failed") },+ });+ });++ it("aggregates changed across durable operations instead of trusting the last no-op", async () => {+ const store = boxStore({ x: 0, y: 0, width: 100, height: 50 });+ const result = expectOk<StudioTransformResult>(+ await studioTransform(+ transformDeps({+ readBox: store.read,+ resizeTo: async () => {+ store.set({ width: 200, height: 80 });+ return {+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:resize"',+ changed: true,+ },+ };+ },+ moveTo: async () => ({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:noop"',+ changed: false,+ },+ }),+ }),+ transformInput({ width: 200, height: 80, x: 0, y: 0 }),+ ),+ );++ expect(result.changed).toBe(true);+ expect(result.applied).toEqual(["resize"]);+ });++ it("reports unobserved rotation as dispatched without claiming it applied", 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 result = await studioTransform(+ transformDeps({ rotateTo }),+ transformInput({ rotate: 15 }),+ );const ok = expectOk<StudioTransformResult>(result);expect(rotateTo).toHaveBeenCalledWith(expect.anything(), { angle: 15 });- expect(ok.applied).toEqual(["rotate"]);+ expect(ok.applied).toEqual([]);+ expect(ok.unchanged.rotation).toMatch(/dispatched but not independently observed/);+ expect(ok.changed).toBe(false);});it("refuses to write while a conflict is waiting for the user", async () => {@@ -123,7 +203,7 @@ describe("studioTransform", () => {const result = expectFailure(await studioTransform(transformDeps({ getWriteBlockedReason: () => "Auto-save is paused", moveTo }),- { x: 10, y: 10 },+ transformInput({ x: 10, y: 10 }),),);@@ -136,8 +216,12 @@ describe("studioTransform", () => {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(expectFailure(await studioTransform(deps, transformInput({ x: 10 }))).reason).toMatch(+ /together/,+ );+ expect(+ expectFailure(await studioTransform(deps, transformInput({ width: 10 }))).reason,+ ).toMatch(/together/);expect(moveTo).not.toHaveBeenCalled();expect(resizeTo).not.toHaveBeenCalled();});@@ -145,17 +229,19 @@ describe("studioTransform", () => {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, transformInput({ width: -1, height: 10 }))).kind,+ ).toBe("invalid");+ expect(expectFailure(await studioTransform(deps, transformInput({}))).reason).toMatch(+ /at least one/,);- 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 }),+ await studioTransform(transformDeps({ moveTo }), transformInput({ x: Number.NaN, y: 10 })),);expect(result.kind).toBe("invalid");@@ -166,14 +252,14 @@ describe("studioTransform", () => {const moveTo = vi.fn();const result = expectFailure(- await studioTransform(transformDeps({ getCurrentSelection: () => null, moveTo }), {- x: 1,- y: 1,- }),+ await studioTransform(+ transformDeps({ buildSelection: async () => null, moveTo }),+ transformInput({ x: 1, y: 1 }),+ ),);- expect(result.kind).toBe("invalid");- expect(result.hint).toMatch(/studio_select/);+ expect(result.kind).toBe("blocked");+ expect(result.hint).toMatch(/parent or child/);expect(moveTo).not.toHaveBeenCalled();});});diff --git a/packages/studio/src/webmcp/tools/transformTools.ts b/packages/studio/src/webmcp/tools/transformTools.tsindex 0ea9bf670b..355fc01136 100644--- a/packages/studio/src/webmcp/tools/transformTools.ts+++ b/packages/studio/src/webmcp/tools/transformTools.ts@@ -21,7 +21,19 @@*/import type { DomEditSelection } from "../../components/editor/domEditingTypes";-import { toolFailure, toolOk, type ToolFailure, type ToolResult } from "../toolResult";+import type { DomEditCommitOutcome } from "../../hooks/domEditCommitRunner";+import type { DomEditPersistOutcome } from "../../hooks/domEditCommitTypes";+import { toolFailure, type ToolFailure } from "../toolResult";+import {+ dispatched,+ runTargetedWrite,+ saved,+ verified,+ type StudioWriteAdapterSuccess,+ type StudioWriteResult,+ type TargetedWriteDeps,+ WRITE_RECEIPT_DESCRIPTION,+} from "../writeCoordinator";export interface ElementBox {x: number;@@ -30,17 +42,25 @@ export interface ElementBox {height: number;}-export interface TransformToolDeps {- getCurrentSelection: () => DomEditSelection | null;- getWriteBlockedReason: () => string | null;+export interface TransformToolDeps extends TargetedWriteDeps {/** The element's box as it renders right now. */readBox: (selection: DomEditSelection) => ElementBox;- moveTo: (selection: DomEditSelection, next: { x: number; y: number }) => Promise<void>;- resizeTo: (selection: DomEditSelection, next: { width: number; height: number }) => Promise<void>;- rotateTo: (selection: DomEditSelection, next: { angle: number }) => Promise<void>;+ moveTo: (+ selection: DomEditSelection,+ next: { x: number; y: number },+ ) => Promise<DomEditCommitOutcome | void>;+ resizeTo: (+ selection: DomEditSelection,+ next: { width: number; height: number },+ ) => Promise<DomEditCommitOutcome | void>;+ rotateTo: (+ selection: DomEditSelection,+ next: { angle: number },+ ) => Promise<DomEditCommitOutcome | void>;}export interface StudioTransformInput {+ handle?: unknown;x?: unknown;y?: unknown;width?: unknown;@@ -54,6 +74,9 @@ export interface StudioTransformResult {applied: string[];/** Requested operations whose effect could not be observed, with why. */unchanged: Record<string, string>;+ /** Present when earlier operations landed before a later operation failed. */+ partial?: true;+ failed?: Partial<Record<TransformOperation, string>>;}const NO_OP_HINT =@@ -63,15 +86,6 @@ 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;@@ -126,75 +140,219 @@ function parseRequest(input: StudioTransformInput): TransformRequest | ToolFailu};}-export async function studioTransform(+type TransformOperation = "resize" | "move" | "rotate";++interface TransformObservation {+ operation: TransformOperation;+ changed: boolean;+ unchangedReason?: string;+ persistence?: DomEditPersistOutcome;+}++function transformPreflight(+ request: TransformRequest,+ selection: DomEditSelection,+): ToolFailure | null {+ if (+ request.size &&+ !selection.capabilities.canResize &&+ !selection.capabilities.canApplyManualSize+ ) {+ return toolFailure("blocked", "this target cannot be resized");+ }+ if (+ request.move &&+ !selection.capabilities.canMove &&+ !selection.capabilities.canApplyManualOffset+ ) {+ return toolFailure("blocked", "this target cannot be moved");+ }+ if (request.rotate !== null && !selection.capabilities.canApplyManualRotation) {+ return toolFailure("blocked", "this target cannot be rotated");+ }+ return null;+}++async function observeResize(deps: TransformToolDeps,- input: StudioTransformInput,-): Promise<ToolResult<StudioTransformResult>> {- const request = parseRequest(input);- if (isFailure(request)) return request;+ selection: DomEditSelection,+ size: NonNullable<TransformRequest["size"]>,+): Promise<TransformObservation | ToolFailure> {+ const before = deps.readBox(selection);+ const outcome = await deps.resizeTo(selection, size);+ if (outcome && !outcome.ok) return outcomeFailure(outcome.reason);+ const after = deps.readBox(selection);+ const changed = after.width !== before.width || after.height !== before.height;+ return {+ operation: "resize",+ changed,+ ...(!changed ? { unchangedReason: "the element's size did not change" } : {}),+ ...(outcome?.ok && outcome.persistence ? { persistence: outcome.persistence } : {}),+ };+}++async function observeMove(+ deps: TransformToolDeps,+ selection: DomEditSelection,+ move: NonNullable<TransformRequest["move"]>,+): Promise<TransformObservation | ToolFailure> {+ const before = deps.readBox(selection);+ const outcome = await deps.moveTo(selection, move);+ if (outcome && !outcome.ok) return outcomeFailure(outcome.reason);+ const after = deps.readBox(selection);+ const changed = after.x !== before.x || after.y !== before.y;+ return {+ operation: "move",+ changed,+ ...(!changed ? { unchangedReason: `the element did not move. ${NO_OP_HINT}` } : {}),+ ...(outcome?.ok && outcome.persistence ? { persistence: outcome.persistence } : {}),+ };+}- const blocked = guard(deps);- if (blocked) return blocked;+async function observeRotation(+ deps: TransformToolDeps,+ selection: DomEditSelection,+ rotate: number,+): Promise<TransformObservation | ToolFailure> {+ const outcome = await deps.rotateTo(selection, { angle: rotate });+ if (outcome && !outcome.ok) return outcomeFailure(outcome.reason);+ if (!outcome || !outcome.persistence) {+ return {+ operation: "rotate",+ changed: false,+ unchangedReason: "rotation was dispatched but not independently observed",+ };+ }+ if (!outcome.persistence.changed) {+ return {+ operation: "rotate",+ changed: false,+ unchangedReason: "the durable write reported no rotation change",+ persistence: outcome.persistence,+ };+ }+ return { operation: "rotate", changed: true, persistence: outcome.persistence };+}- const selection = deps.getCurrentSelection();- if (!selection) return toolFailure("invalid", "nothing is selected");+function requestMatchesBox(request: TransformRequest, box: ElementBox): boolean {+ const sizeMatches =+ !request.size || (box.width === request.size.width && box.height === request.size.height);+ const moveMatches = !request.move || (box.x === request.move.x && box.y === request.move.y);+ return sizeMatches && moveMatches;+}- const applied: string[] = [];- const unchanged: Record<string, string> = {};+function transformReceipt(+ request: TransformRequest,+ initial: ElementBox,+ box: ElementBox,+ observations: TransformObservation[],+ failure?: { operation: TransformOperation; reason: string },+): StudioWriteAdapterSuccess<StudioTransformResult> {+ const applied = observations.filter((item) => item.changed).map((item) => item.operation);+ const unchanged = Object.fromEntries(+ observations.flatMap((item) => {+ if (!item.unchangedReason) return [];+ const key = item.operation === "rotate" ? "rotation" : item.operation;+ return [[key, item.unchangedReason]];+ }),+ );+ const value: StudioTransformResult = {+ box,+ applied,+ unchanged,+ ...(failure ? { partial: true, failed: { [failure.operation]: failure.reason } } : {}),+ };+ const changed = observations.some((item) => item.changed) || !boxesEqual(initial, box);+ const allDurable = observations.every((item) => item.persistence !== undefined);+ const persistence = observations.at(-1)?.persistence;+ if (!allDurable || !persistence) return dispatched(value, changed);+ if (!failure && requestMatchesBox(request, box) && request.rotate === null) {+ return { ...verified(value, persistence, { before: initial, after: box }), changed };+ }+ return { ...saved(value, persistence), changed };+}- // 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.+async function writeTransform(+ deps: TransformToolDeps,+ selection: DomEditSelection,+ request: TransformRequest,+): Promise<StudioWriteAdapterSuccess<StudioTransformResult> | ToolFailure> {+ const initial = deps.readBox(selection);+ const observations: TransformObservation[] = [];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";+ const observation = await observeResize(deps, selection, request.size);+ if (isFailure(observation)) return observation;+ observations.push(observation);}-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}`;+ const observation = await observeMove(deps, selection, request.move);+ if (isFailure(observation)) {+ if (observations.length === 0) return observation;+ return transformReceipt(request, initial, deps.readBox(selection), observations, {+ operation: "move",+ reason: observation.reason,+ });+ }+ observations.push(observation);}-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");+ const observation = await observeRotation(deps, selection, request.rotate);+ if (isFailure(observation)) {+ if (observations.length === 0) return observation;+ return transformReceipt(request, initial, deps.readBox(selection), observations, {+ operation: "rotate",+ reason: observation.reason,+ });+ }+ observations.push(observation);}+ return transformReceipt(request, initial, deps.readBox(selection), observations);+}- if (applied.length === 0) {- return toolFailure(- "blocked",- `nothing changed: ${Object.values(unchanged).join("; ")}`,- NO_OP_HINT,- );+export async function studioTransform(+ deps: TransformToolDeps,+ input: StudioTransformInput,+ signal: AbortSignal = new AbortController().signal,+): Promise<StudioWriteResult<StudioTransformResult>> {+ const request = parseRequest(input);+ if (isFailure(request)) {+ return { ...request, stage: "refused", operation: "transform" };}- return toolOk<StudioTransformResult>({ box: deps.readBox(selection), applied, unchanged });+ return runTargetedWrite(deps, {+ handle: input.handle,+ operation: "transform",+ signal,+ preflight: (selection) => transformPreflight(request, selection),+ write: (selection) => writeTransform(deps, selection, request),+ });+}++function boxesEqual(a: ElementBox, b: ElementBox): boolean {+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;+}++function outcomeFailure(reason: string): ToolFailure {+ return toolFailure("failed", `the transform was not applied: ${reason}`);}export const STUDIO_TRANSFORM_INPUT_SCHEMA = {type: "object",properties: {+ handle: { type: "string", description: "A source-safe element handle from studio_look." },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." },},+ required: ["handle"],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.",+ "Move, resize or rotate one element using its source-safe handle from studio_look.",+ "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",@@ -202,4 +360,5 @@ export const STUDIO_TRANSFORM_DESCRIPTION = ["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`.",+ WRITE_RECEIPT_DESCRIPTION,].join(" ");diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsxindex 2dfd169349..19b252ee32 100644--- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx+++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx@@ -3,9 +3,11 @@ import { act } from "react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { mountReactHarness } from "../hooks/domSelectionTestHarness";import { writeStudioUiPreferences } from "../utils/studioUiPreferences";+import { mintElementHandle } from "./handles";import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";import type { ModelContext, ModelContextRegisterToolOptions, ModelContextTool } from "./types";import type { StudioLookSnapshot } from "./tools/lookTools";+import { previewDoc, selectionFor } from "./webmcpTestUtils";const trackEvent = vi.hoisted(() => vi.fn());vi.mock("../telemetry/client", () => ({ trackEvent }));@@ -22,6 +24,7 @@ function snapshot(overrides: Partial<StudioLookSnapshot> = {}): StudioLookSnapshduration: 10,isPlaying: false,elements: [],+ scene: { status: "ready", items: [], drillInItem: null },selection: null,selectionAnimationCount: 0,history: { canUndo: false, canRedo: false, undoLabel: null, redoLabel: null },@@ -50,10 +53,11 @@ function deps(overrides: Partial<StudioAgentToolsDeps> = {}): StudioAgentToolsDemoveTo: async () => undefined,resizeTo: async () => undefined,rotateTo: async () => undefined,- addAnimation: () => undefined,+ addAnimation: async () => true,updateAnimation: async () => true,addKeyframe: async () => undefined,- deleteAnimation: () => undefined,+ deleteAnimation: async () => true,+ getAnimationsForSelection: async () => [],getGsapDiagnostics: () => ({animations: [],multipleTimelines: false,@@ -63,6 +67,40 @@ function deps(overrides: Partial<StudioAgentToolsDeps> = {}): StudioAgentToolsDe};}+async function executeRegistered<T>(+ registered: ModelContextTool[],+ name: string,+ input: object,+ signal: AbortSignal = new AbortController().signal,+): Promise<T> {+ const tool = registered.find((candidate) => candidate.name === name);+ if (!tool) throw new Error(`expected ${name} to be registered`);+ return (await tool.execute(input, { signal })) as T;+}++function mountedTargetDeps(overrides: Partial<StudioAgentToolsDeps> = {}) {+ const doc = previewDoc('<h1 id="human">Human</h1><h1 id="agent">Agent</h1>');+ const human = doc.getElementById("human") as HTMLElement;+ const agent = doc.getElementById("agent") as HTMLElement;+ const agentHandle = mintElementHandle({+ projectId: "demo",+ domId: "agent",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ if (!agentHandle) throw new Error("expected agent handle");+ return {+ agent,+ agentHandle,+ currentSelection: selectionFor(human),+ deps: deps({+ getPreviewDocument: () => doc,+ buildSelection: async (element) => selectionFor(element),+ ...overrides,+ }),+ };+}+/** Install a fake `document.modelContext` and report what got registered. */function installModelContext() {const registered: ModelContextTool[] = [];@@ -80,6 +118,12 @@ function installModelContext() {return { registered, registerTool };}+async function executeFirstRegistered<T>(registered: ModelContextTool[]): Promise<T> {+ const look = registered[0];+ if (!look) throw new Error("expected studio_look to be registered");+ return (await look.execute({}, { signal: new AbortController().signal })) as T;+}+function removeModelContext() {Reflect.deleteProperty(document, "modelContext");}@@ -170,12 +214,10 @@ describe("useStudioAgentTools", () => {harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 42 }) }));});- const look = registered[0];- if (!look) throw new Error("expected studio_look to be registered");- const result = (await look.execute({}, { signal: new AbortController().signal })) as {+ const result = await executeFirstRegistered<{ok: boolean;playhead: number;- };+ }>(registered);expect(result.ok).toBe(true);expect(result.playhead).toBe(42);@@ -257,14 +299,272 @@ describe("useStudioAgentTools", () => {});vi.spyOn(console, "error").mockImplementation(() => {});- const look = registered[0];- if (!look) throw new Error("expected studio_look to be registered");- const result = (await look.execute({}, { signal: new AbortController().signal })) as {+ const result = await executeFirstRegistered<{ok: boolean;kind: string;- };+ }>(registered);expect(result.ok).toBe(false);expect(result.kind).toBe("internal");});++ it("requires a source-safe handle on every source-writing tool", async () => {+ const { registered } = installModelContext();+ await act(async () => mountTools(deps()));++ for (const name of [+ "studio_set_text",+ "studio_set_style",+ "studio_transform",+ "studio_add_animation",+ "studio_update_animation",+ "studio_add_keyframe",+ "studio_delete_animation",+ ]) {+ const schema = registered.find((tool) => tool.name === name)?.inputSchema as {+ required?: string[];+ };+ expect(schema.required, name).toContain("handle");+ }+ });++ it("binds a text write to the explicit handle even when human selection points elsewhere", async () => {+ const { registered } = installModelContext();+ const targeted = mountedTargetDeps();+ const setText = vi.fn(+ async () =>+ ({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:after"',+ changed: true,+ },+ }) as const,+ );+ await act(async () => mountTools({ ...targeted.deps, setText }));++ const result = await executeRegistered<{+ ok: boolean;+ stage: string;+ changed: boolean;+ target: { handle: string; sourceFile: string };+ }>(registered, "studio_set_text", {+ handle: targeted.agentHandle,+ text: "Edited by agent",+ });++ expect(setText).toHaveBeenCalledWith(+ expect.objectContaining({ element: targeted.agent }),+ "Edited by agent",+ "self",+ );+ expect(result).toMatchObject({+ ok: true,+ stage: "saved",+ changed: true,+ target: { handle: targeted.agentHandle, sourceFile: "index.html" },+ });+ });++ it("refuses a locked target and an early abort before invoking the write actor", async () => {+ const { registered } = installModelContext();+ const setText = vi.fn();+ const targeted = mountedTargetDeps({+ buildSelection: async (element) => selectionFor(element, { isInsideLockedComposition: true }),+ });+ await act(async () => mountTools({ ...targeted.deps, setText }));++ const locked = await executeRegistered<{ ok: boolean; stage: string }>(+ registered,+ "studio_set_text",+ { handle: targeted.agentHandle, text: "No" },+ );+ const controller = new AbortController();+ controller.abort();+ const aborted = await executeRegistered<{ ok: boolean; stage: string; cancelRequested: true }>(+ registered,+ "studio_set_text",+ { handle: targeted.agentHandle, text: "No" },+ controller.signal,+ );++ expect(locked).toMatchObject({ ok: false, stage: "refused" });+ expect(aborted).toMatchObject({ ok: false, stage: "refused", cancelRequested: true });+ expect(setText).not.toHaveBeenCalled();+ });++ it("reports dispatched, saved, and verified only from their corresponding evidence", async () => {+ const { registered } = installModelContext();+ const targeted = mountedTargetDeps();+ const box = { x: 0, y: 0, width: 100, height: 50 };+ await act(async () =>+ mountTools({+ ...targeted.deps,+ setText: async () => ({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:after"',+ changed: true,+ },+ }),+ addAnimation: async () => true,+ readBox: () => ({ ...box }),+ resizeTo: async (_selection, next) => {+ Object.assign(box, next);+ return {+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:transform"',+ changed: true,+ },+ } as const;+ },+ }),+ );++ const dispatched = await executeRegistered<{ stage: string }>(+ registered,+ "studio_add_animation",+ { handle: targeted.agentHandle, method: "to" },+ );+ const saved = await executeRegistered<{ stage: string }>(registered, "studio_set_text", {+ handle: targeted.agentHandle,+ text: "Saved",+ });+ const verified = await executeRegistered<{ stage: string }>(registered, "studio_transform", {+ handle: targeted.agentHandle,+ width: 200,+ height: 80,+ });++ expect(dispatched.stage).toBe("dispatched");+ expect(saved.stage).toBe("saved");+ expect(verified.stage).toBe("verified");+ });++ it("reports a matched no-op with its durable version without fabricating a change", async () => {+ const { registered } = installModelContext();+ const targeted = mountedTargetDeps();+ await act(async () =>+ mountTools({+ ...targeted.deps,+ setText: async () => ({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:current"',+ changed: false,+ },+ }),+ }),+ );++ const result = await executeRegistered<{+ ok: boolean;+ stage: string;+ changed: boolean;+ evidence: { version: string };+ }>(registered, "studio_set_text", {+ handle: targeted.agentHandle,+ text: "Agent",+ });++ expect(result).toMatchObject({+ ok: true,+ stage: "saved",+ changed: false,+ evidence: { version: '"sha256:current"' },+ });+ });++ it("reports the actual saved outcome and late cancellation without promising rollback", async () => {+ const { registered } = installModelContext();+ const targeted = mountedTargetDeps();+ let finish: (() => void) | undefined;+ const setText = vi.fn(+ () =>+ new Promise<{+ ok: true;+ persistence: { sourceFile: string; version: string; changed: true };+ }>((resolve) => {+ finish = () =>+ resolve({+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:late"',+ changed: true,+ },+ });+ }),+ );+ await act(async () => mountTools({ ...targeted.deps, setText }));+ const controller = new AbortController();++ const pending = executeRegistered<{+ ok: boolean;+ stage: string;+ cancelRequested?: boolean;+ }>(+ registered,+ "studio_set_text",+ { handle: targeted.agentHandle, text: "Late" },+ controller.signal,+ );+ await vi.waitFor(() => expect(setText).toHaveBeenCalledTimes(1));+ controller.abort();+ finish?.();++ expect(await pending).toMatchObject({+ ok: true,+ stage: "saved",+ cancelRequested: true,+ });+ expect(setText).toHaveBeenCalledTimes(1);+ });++ it("aggregates partial style evidence and uses the weakest applied assurance", async () => {+ const { registered } = installModelContext();+ const targeted = mountedTargetDeps();+ const setStyle = vi.fn(async (_selection, property: string) => {+ if (property === "left") return { ok: false, reason: "geometry-property" } as const;+ if (property === "opacity") return { ok: true } as const;+ return {+ ok: true,+ persistence: {+ sourceFile: "index.html",+ version: '"sha256:color"',+ changed: true,+ },+ } as const;+ });+ await act(async () => mountTools({ ...targeted.deps, setStyle }));++ const result = await executeRegistered<{+ ok: boolean;+ stage: string;+ partial: boolean;+ applied: Record<string, string>;+ rejected: Record<string, string>;+ propertyReceipts: Record<string, { stage: string }>;+ }>(registered, "studio_set_style", {+ handle: targeted.agentHandle,+ styles: { color: "red", left: "10px", opacity: "0.5" },+ });++ expect(result).toMatchObject({+ ok: true,+ stage: "dispatched",+ partial: true,+ applied: { color: "red", opacity: "0.5" },+ rejected: { left: "geometry-property" },+ propertyReceipts: {+ color: { stage: "saved" },+ opacity: { stage: "dispatched" },+ },+ });+ });});diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.tsindex 3402dc66c7..717f9dcd38 100644--- a/packages/studio/src/webmcp/useStudioAgentTools.ts+++ b/packages/studio/src/webmcp/useStudioAgentTools.ts@@ -177,8 +177,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_SET_TEXT_DESCRIPTION,inputSchema: STUDIO_SET_TEXT_INPUT_SCHEMA,annotations: { readOnlyHint: false, untrustedContentHint: true },- execute: (input): Promise<ToolResult<StudioSetTextResult>> =>- runToolBody("studio_set_text", () => studioSetText(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioSetTextResult>> =>+ runToolBody<StudioSetTextResult>("studio_set_text", () =>+ studioSetText(depsRef.current, input, signal),+ ),},{name: "studio_set_style",@@ -186,8 +188,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_SET_STYLE_DESCRIPTION,inputSchema: STUDIO_SET_STYLE_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioSetStyleResult>> =>- runToolBody("studio_set_style", () => studioSetStyle(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioSetStyleResult>> =>+ runToolBody<StudioSetStyleResult>("studio_set_style", () =>+ studioSetStyle(depsRef.current, input, signal),+ ),},{name: "studio_transform",@@ -195,9 +199,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_TRANSFORM_DESCRIPTION,inputSchema: STUDIO_TRANSFORM_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioTransformResult>> =>- runToolBody("studio_transform", () =>- studioTransform(depsRef.current, input as StudioTransformInput),+ execute: (input, { signal }): Promise<ToolResult<StudioTransformResult>> =>+ runToolBody<StudioTransformResult>("studio_transform", () =>+ studioTransform(depsRef.current, input as StudioTransformInput, signal),),},{@@ -206,8 +210,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_ADD_ANIMATION_DESCRIPTION,inputSchema: STUDIO_ADD_ANIMATION_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioAddAnimationResult>> =>- runToolBody("studio_add_animation", () => studioAddAnimation(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioAddAnimationResult>> =>+ runToolBody<StudioAddAnimationResult>("studio_add_animation", () =>+ studioAddAnimation(depsRef.current, input, signal),+ ),},{name: "studio_update_animation",@@ -215,8 +221,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_UPDATE_ANIMATION_DESCRIPTION,inputSchema: STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioUpdateAnimationResult>> =>- runToolBody("studio_update_animation", () => studioUpdateAnimation(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioUpdateAnimationResult>> =>+ runToolBody<StudioUpdateAnimationResult>("studio_update_animation", () =>+ studioUpdateAnimation(depsRef.current, input, signal),+ ),},{name: "studio_add_keyframe",@@ -224,8 +232,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_ADD_KEYFRAME_DESCRIPTION,inputSchema: STUDIO_ADD_KEYFRAME_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioAddKeyframeResult>> =>- runToolBody("studio_add_keyframe", () => studioAddKeyframe(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioAddKeyframeResult>> =>+ runToolBody<StudioAddKeyframeResult>("studio_add_keyframe", () =>+ studioAddKeyframe(depsRef.current, input, signal),+ ),},{name: "studio_delete_animation",@@ -233,8 +243,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):description: STUDIO_DELETE_ANIMATION_DESCRIPTION,inputSchema: STUDIO_DELETE_ANIMATION_INPUT_SCHEMA,annotations: { readOnlyHint: false },- execute: (input): Promise<ToolResult<StudioDeleteAnimationResult>> =>- runToolBody("studio_delete_animation", () => studioDeleteAnimation(depsRef.current, input)),+ execute: (input, { signal }): Promise<ToolResult<StudioDeleteAnimationResult>> =>+ runToolBody<StudioDeleteAnimationResult>("studio_delete_animation", () =>+ studioDeleteAnimation(depsRef.current, input, signal),+ ),},];}diff --git a/packages/studio/src/webmcp/webmcpTestUtils.ts b/packages/studio/src/webmcp/webmcpTestUtils.tsindex 8f4f5e96b0..f7f0c8c553 100644--- a/packages/studio/src/webmcp/webmcpTestUtils.ts+++ b/packages/studio/src/webmcp/webmcpTestUtils.ts@@ -8,6 +8,9 @@import { expect } from "vitest";import type { DomEditSelection } from "../components/editor/domEditingTypes";import type { ToolFailure, ToolResult } from "./toolResult";+import type { SelectionToolDeps } from "./tools/selectionTools";+import { mintElementHandle } from "./handles";+import type { TargetedWriteDeps } from "./writeCoordinator";/*** An element inside a real iframe, which is where Studio's chrome expects to@@ -78,6 +81,40 @@ export function selectionFor(};}+export function selectionToolDeps(overrides: Partial<SelectionToolDeps> = {}): SelectionToolDeps {+ return {+ getPreviewDocument: () => null,+ getCompositionPath: () => "index.html",+ getProjectId: () => "project-a",+ buildSelection: async (element) => selectionFor(element),+ applySelection: () => undefined,+ requestSeek: () => undefined,+ readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),+ ...overrides,+ };+}++export function sourceHandle(domId: string, projectId = "project-a"): string {+ const handle = mintElementHandle({+ projectId,+ domId,+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ if (!handle) throw new Error(`expected source handle for #${domId}`);+ return handle;+}++export function targetedWriteDeps(selection: DomEditSelection): TargetedWriteDeps {+ return {+ getPreviewDocument: () => selection.element.ownerDocument,+ getProjectId: () => "project-a",+ getWriteBlockedReason: () => null,+ buildSelection: async () => selection,+ applySelection: () => undefined,+ };+}+export function expectOk<T>(result: ToolResult<T>): { ok: true } & T {expect(result.ok, `expected ok, got ${JSON.stringify(result)}`).toBe(true);if (!result.ok) throw new Error("unreachable");diff --git a/packages/studio/src/webmcp/writeCoordinator.test.ts b/packages/studio/src/webmcp/writeCoordinator.test.tsnew file mode 100644index 0000000000..79ed63ee48--- /dev/null+++ b/packages/studio/src/webmcp/writeCoordinator.test.ts@@ -0,0 +1,375 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from "vitest";+import { mintElementHandle } from "./handles";+import { previewDoc, selectionFor } from "./webmcpTestUtils";+import {+ dispatched,+ runTargetedWrite,+ saved,+ studioEditLifecycle,+ type TargetedWriteDeps,+} from "./writeCoordinator";++function fixture() {+ const doc = previewDoc('<div id="target">Target</div>');+ const element = doc.getElementById("target") as HTMLElement;+ const handle = mintElementHandle({+ projectId: "project-a",+ domId: "target",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ if (!handle) throw new Error("expected handle");+ const deps: TargetedWriteDeps = {+ getPreviewDocument: () => doc,+ getProjectId: () => "project-a",+ getWriteBlockedReason: () => null,+ buildSelection: async (target) => selectionFor(target),+ applySelection: () => undefined,+ };+ return { deps, element, handle };+}++afterEach(() => {+ studioEditLifecycle.reset();+ document.body.replaceChildren();+});++describe("studio write coordinator", () => {+ it("refuses legacy and stale-project handles before resolving or calling the actor", async () => {+ const { deps } = fixture();+ const actor = vi.fn();+ const buildSelection = vi.fn(deps.buildSelection);+ const legacy = mintElementHandle({+ domId: "target",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ const staleProject = mintElementHandle({+ projectId: "project-b",+ domId: "target",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });++ const legacyResult = await runTargetedWrite(+ { ...deps, buildSelection },+ {+ handle: legacy,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );+ const staleResult = await runTargetedWrite(+ { ...deps, buildSelection },+ {+ handle: staleProject,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );++ expect(legacyResult).toMatchObject({ ok: false, stage: "refused", kind: "invalid" });+ expect(staleResult).toMatchObject({+ ok: false,+ stage: "refused",+ kind: "invalid",+ reason: "the handle belongs to a different project",+ });+ expect(buildSelection).not.toHaveBeenCalled();+ expect(actor).not.toHaveBeenCalled();+ });++ it("refuses an unavailable preview with its exact reason before calling the actor", async () => {+ const { deps, handle } = fixture();+ const actor = vi.fn();++ const result = await runTargetedWrite(+ { ...deps, getPreviewDocument: () => null },+ {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );++ expect(result).toEqual({+ ok: false,+ kind: "blocked",+ reason: "the composition preview is not ready",+ stage: "refused",+ operation: "set-text",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("refuses a missing handle with its exact reason before calling the actor", async () => {+ const { deps } = fixture();+ const actor = vi.fn();++ const result = await runTargetedWrite(deps, {+ handle: mintElementHandle({+ projectId: "project-a",+ domId: "missing",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ }),+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ });++ expect(result).toEqual({+ ok: false,+ kind: "invalid",+ reason: "the target handle is stale",+ hint: "Call studio_look and retry.",+ stage: "refused",+ operation: "set-text",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("refuses an unsupported element with its exact reason before calling the actor", async () => {+ const { deps, handle } = fixture();+ const actor = vi.fn();++ const result = await runTargetedWrite(+ { ...deps, buildSelection: async () => null },+ {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );++ expect(result).toEqual({+ ok: false,+ kind: "blocked",+ reason: "the target resolved to an element Studio cannot edit",+ hint: "Try a parent or child element from studio_look.",+ stage: "refused",+ operation: "set-text",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("refuses a twice-replaced preview with its exact reason before calling the actor", async () => {+ const firstDoc = previewDoc('<div id="target">First</div>');+ const secondDoc = previewDoc('<div id="target">Second</div>');+ const thirdDoc = previewDoc('<div id="target">Third</div>');+ const handle = mintElementHandle({+ projectId: "project-a",+ domId: "target",+ sourceFile: "index.html",+ activeCompositionPath: "index.html",+ });+ let currentDoc = firstDoc;+ const actor = vi.fn();+ const result = await runTargetedWrite(+ {+ getPreviewDocument: () => currentDoc,+ getProjectId: () => "project-a",+ getWriteBlockedReason: () => null,+ buildSelection: async (element) => {+ currentDoc = currentDoc === firstDoc ? secondDoc : thirdDoc;+ return selectionFor(element);+ },+ applySelection: () => undefined,+ },+ {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );++ expect(result).toEqual({+ ok: false,+ kind: "invalid",+ reason: "the target changed while it was resolving",+ hint: "Call studio_look again.",+ stage: "refused",+ operation: "set-text",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("returns a structured refusal when async preflight fails before dispatch", async () => {+ const { deps, handle } = fixture();+ const actor = vi.fn();++ const result = await runTargetedWrite(deps, {+ handle,+ operation: "update-animation",+ signal: new AbortController().signal,+ preflight: async () => {+ throw new Error("animation ownership is unavailable");+ },+ write: actor,+ });++ expect(result).toMatchObject({+ ok: false,+ stage: "refused",+ kind: "failed",+ reason: "animation ownership is unavailable",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("refuses when the active project changes during target resolution", async () => {+ const { deps, handle } = fixture();+ const actor = vi.fn();+ let projectId = "project-a";++ const result = await runTargetedWrite(+ {+ ...deps,+ getProjectId: () => projectId,+ buildSelection: async (element) => {+ projectId = "project-b";+ return selectionFor(element);+ },+ },+ {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: actor,+ },+ );++ expect(result).toMatchObject({+ ok: false,+ stage: "refused",+ kind: "blocked",+ reason: "the active project changed while the target was resolving",+ });+ expect(actor).not.toHaveBeenCalled();+ });++ it("publishes nothing when cancellation refuses the write before dispatch", async () => {+ const { deps, handle } = fixture();+ const actor = vi.fn();+ const controller = new AbortController();+ controller.abort();++ const result = await runTargetedWrite(deps, {+ handle,+ operation: "set-text",+ signal: controller.signal,+ write: actor,+ });++ expect(result).toMatchObject({ ok: false, stage: "refused", cancelRequested: true });+ expect(actor).not.toHaveBeenCalled();+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });+ });++ it("marks repeat targets only after a terminal receipt and resets on project switch", async () => {+ const { deps, handle } = fixture();+ await runTargetedWrite(deps, {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: async () => {+ expect(studioEditLifecycle.getSnapshot()).toMatchObject({ targetChanged: true });+ return saved(+ { text: "first", changed: true },+ { sourceFile: "index.html", version: "v1", changed: true },+ );+ },+ });++ await runTargetedWrite(deps, {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: async () => {+ expect(studioEditLifecycle.getSnapshot()).toMatchObject({ targetChanged: false });+ return dispatched({ text: "second", changed: true }, true);+ },+ });++ studioEditLifecycle.activateProject("project-b");+ expect(studioEditLifecycle.getSnapshot()).toEqual({ phase: "idle" });+ });++ it("does not let an older completion overwrite the newer invocation", () => {+ const target = { handle: "dom:target", sourceFile: "index.html" };+ const older = studioEditLifecycle.begin("project-a", target, "set-text");+ const newer = studioEditLifecycle.begin("project-a", target, "set-style");++ studioEditLifecycle.finish(older, {+ ok: true,+ stage: "saved",+ target,+ operation: "set-text",+ changed: true,+ evidence: { kind: "content-version", sourceFile: "index.html", version: "v1" },+ });++ expect(studioEditLifecycle.getSnapshot()).toMatchObject({+ callId: newer,+ operation: "set-style",+ phase: "dispatching",+ });+ });++ it("does not let an older dismissal clear the newer invocation", () => {+ const target = { handle: "dom:target", sourceFile: "index.html" };+ const older = studioEditLifecycle.begin("project-a", target, "set-text");+ const newer = studioEditLifecycle.begin("project-a", target, "set-style");++ studioEditLifecycle.dismiss(older);++ expect(studioEditLifecycle.getSnapshot()).toMatchObject({+ callId: newer,+ operation: "set-style",+ phase: "dispatching",+ });+ });++ it("dismisses its terminal call without forgetting repeated-target identity", () => {+ const target = { handle: "dom:target", sourceFile: "index.html" };+ const first = studioEditLifecycle.begin("project-a", target, "set-text");+ studioEditLifecycle.finish(first, {+ ok: true,+ stage: "saved",+ target,+ operation: "set-text",+ changed: true,+ evidence: { kind: "content-version", sourceFile: "index.html", version: "v1" },+ });++ studioEditLifecycle.dismiss(first);+ const repeated = studioEditLifecycle.begin("project-a", target, "set-style");++ expect(studioEditLifecycle.getSnapshot()).toMatchObject({+ callId: repeated,+ targetChanged: false,+ });+ });++ it("finishes the owning lifecycle as failed when an actor throws", async () => {+ const { deps, handle } = fixture();++ const result = await runTargetedWrite(deps, {+ handle,+ operation: "set-text",+ signal: new AbortController().signal,+ write: async () => {+ throw new Error("network down");+ },+ });++ expect(result).toMatchObject({ ok: false, stage: "failed", reason: "network down" });+ expect(studioEditLifecycle.getSnapshot()).toMatchObject({ phase: "failed", receipt: result });+ });+});diff --git a/packages/studio/src/webmcp/writeCoordinator.ts b/packages/studio/src/webmcp/writeCoordinator.tsnew file mode 100644index 0000000000..b24e248736--- /dev/null+++ b/packages/studio/src/webmcp/writeCoordinator.ts@@ -0,0 +1,473 @@+import type { DomEditSelection } from "../components/editor/domEditingTypes";+import { parseElementHandle, resolveLiveHandleSelection } from "./handles";+import { toolFailure, type ToolFailure, type ToolFailureKind } from "./toolResult";++export type StudioWriteOperation =+ | "set-text"+ | "set-style"+ | "transform"+ | "add-animation"+ | "update-animation"+ | "add-keyframe"+ | "delete-animation";++export const WRITE_RECEIPT_DESCRIPTION =+ "Read `stage` as the proof level: refused, dispatched, saved, verified, or failed. " ++ "`changed` is separate, and evidence explains what was actually proven.";++export interface StudioWriteTarget {+ handle: string;+ sourceFile: string;+}++export type StudioWriteEvidence =+ | { kind: "dispatch"; followUp: "studio_inspect" }+ | { kind: "content-version"; sourceFile: string; version: string }+ | {+ kind: "readback";+ sourceFile: string;+ version: string;+ before: unknown;+ after: unknown;+ };++export type StudioWriteAdapterSuccess<T extends object> = T & {+ ok: true;+ stage: "dispatched" | "saved" | "verified";+ changed: boolean;+ evidence: StudioWriteEvidence;+};++type StudioWriteAdapterResult<T extends object> = StudioWriteAdapterSuccess<T> | ToolFailure;++export type StudioWriteResult<T extends object> =+ | (T & {+ ok: true;+ stage: "dispatched" | "saved" | "verified";+ target: StudioWriteTarget;+ operation: StudioWriteOperation;+ changed: boolean;+ evidence: StudioWriteEvidence;+ cancelRequested?: true;+ })+ | (ToolFailure & {+ stage: "refused" | "failed";+ target?: StudioWriteTarget;+ operation: StudioWriteOperation;+ cancelRequested?: true;+ });++export interface TargetedWriteDeps {+ getPreviewDocument: () => Document | null;+ getProjectId: () => string | null;+ getWriteBlockedReason: () => string | null;+ buildSelection: (element: HTMLElement) => Promise<DomEditSelection | null>;+ applySelection: (selection: DomEditSelection) => void;+}++export type StudioEditLifecycleState =+ | { phase: "idle" }+ | {+ callId: string;+ projectId: string;+ target: StudioWriteTarget;+ operation: StudioWriteOperation;+ targetChanged: boolean;+ phase: "dispatching" | "dispatched" | "saved" | "verified" | "failed";+ receipt?: StudioWriteResult<object>;+ };++type LifecycleListener = () => void;++class StudioEditLifecycle {+ private state: StudioEditLifecycleState = { phase: "idle" };+ private listeners = new Set<LifecycleListener>();+ private lastTerminalTarget: { projectId: string; handle: string } | null = null;+ private activeProjectId: string | null = null;+ private callSequence = 0;++ getSnapshot = (): StudioEditLifecycleState => this.state;++ subscribe = (listener: LifecycleListener): (() => void) => {+ this.listeners.add(listener);+ return () => this.listeners.delete(listener);+ };++ begin(projectId: string, target: StudioWriteTarget, operation: StudioWriteOperation): string {+ this.activateProject(projectId);+ const callId = `studio-edit-${++this.callSequence}`;+ const previous = this.lastTerminalTarget;+ const targetChanged =+ previous === null || previous.projectId !== projectId || previous.handle !== target.handle;+ this.publish({+ callId,+ projectId,+ target,+ operation,+ targetChanged,+ phase: "dispatching",+ });+ return callId;+ }++ finish(callId: string, receipt: StudioWriteResult<object>): void {+ if (this.state.phase === "idle" || this.state.callId !== callId) return;+ this.lastTerminalTarget = {+ projectId: this.state.projectId,+ handle: this.state.target.handle,+ };+ this.publish({+ ...this.state,+ phase: receipt.ok ? receipt.stage : "failed",+ receipt,+ });+ }++ /** Clear only the invocation that still owns the visual lifecycle. */+ dismiss(callId: string): void {+ if (this.state.phase === "idle" || this.state.callId !== callId) return;+ this.publish({ phase: "idle" });+ }++ reset(): void {+ this.activeProjectId = null;+ this.lastTerminalTarget = null;+ this.publish({ phase: "idle" });+ }++ activateProject(projectId: string | null): void {+ if (this.activeProjectId === projectId) return;+ this.activeProjectId = projectId;+ this.lastTerminalTarget = null;+ this.publish({ phase: "idle" });+ }++ private publish(state: StudioEditLifecycleState): void {+ this.state = state;+ for (const listener of this.listeners) listener();+ }+}++/** One state owner shared by the coordinator and Studio's future overlay. */+export const studioEditLifecycle = new StudioEditLifecycle();++interface TargetedWriteInput<T extends object> {+ handle: unknown;+ operation: StudioWriteOperation;+ signal: AbortSignal;+ preflight?: (selection: DomEditSelection) => ToolFailure | null | Promise<ToolFailure | null>;+ write: (selection: DomEditSelection) => Promise<StudioWriteAdapterResult<T>>;+}++type ResolvedWriteSelection =+ | { ok: true; selection: DomEditSelection }+ | { ok: false; failure: ToolFailure };++async function resolveWriteSelection(+ deps: TargetedWriteDeps,+ handle: string,+): Promise<ResolvedWriteSelection> {+ const resolved = await resolveLiveHandleSelection(+ deps.getPreviewDocument,+ handle,+ deps.buildSelection,+ );+ if (resolved.status === "preview-unavailable") {+ return { ok: false, failure: toolFailure("blocked", "the composition preview is not ready") };+ }+ if (resolved.status === "not-found") {+ return {+ ok: false,+ failure: toolFailure("invalid", "the target handle is stale", "Call studio_look and retry."),+ };+ }+ if (resolved.status === "unsupported") {+ return {+ ok: false,+ failure: toolFailure(+ "blocked",+ "the target resolved to an element Studio cannot edit",+ "Try a parent or child element from studio_look.",+ ),+ };+ }+ if (resolved.status === "changed") {+ return {+ ok: false,+ failure: toolFailure(+ "invalid",+ "the target changed while it was resolving",+ "Call studio_look again.",+ ),+ };+ }+ return { ok: true, selection: resolved.selection };+}++function refusedResult<T extends object>(+ operation: StudioWriteOperation,+ failure: ToolFailure,+ cancelRequested = false,+): StudioWriteResult<T> {+ return {+ ...failure,+ stage: "refused",+ operation,+ ...(cancelRequested ? { cancelRequested: true as const } : {}),+ };+}++function completedWrite<T extends object>(+ adapter: StudioWriteAdapterResult<T>,+ target: StudioWriteTarget,+ operation: StudioWriteOperation,+ cancelRequested: boolean,+): StudioWriteResult<T> {+ const cancellation = cancelRequested ? { cancelRequested: true as const } : {};+ return adapter.ok+ ? { ...adapter, target, operation, ...cancellation }+ : { ...asFailed(adapter), stage: "failed", target, operation, ...cancellation };+}++function classifyThrownError(error: unknown): { kind: ToolFailureKind; reason: string } {+ return {+ kind: error instanceof TypeError || error instanceof ReferenceError ? "internal" : "failed",+ reason: error instanceof Error ? error.message : String(error),+ };+}++type ValidatedWriteAddress<T extends object> =+ | { ok: true; handle: string; projectId: string }+ | { ok: false; result: StudioWriteResult<T> };++function validateProjectScopedHandle<T extends object>(+ handle: string,+ projectId: string,+ operation: StudioWriteOperation,+): StudioWriteResult<T> | null {+ const parsedHandle = parseElementHandle(handle);+ if (!parsedHandle || parsedHandle.version !== 2 || !parsedHandle.projectId) {+ return refusedResult(+ operation,+ toolFailure(+ "invalid",+ "writes require a current project-scoped handle from studio_look",+ "Call studio_look again and pass the returned handle unchanged.",+ ),+ );+ }+ if (parsedHandle.projectId === projectId) return null;+ return refusedResult(+ operation,+ toolFailure(+ "invalid",+ "the handle belongs to a different project",+ "Call studio_look in the active project.",+ ),+ );+}++function validateWriteAddress<T extends object>(+ deps: TargetedWriteDeps,+ input: TargetedWriteInput<T>,+): ValidatedWriteAddress<T> {+ if (input.signal.aborted) {+ return {+ ok: false,+ result: refusedResult(+ input.operation,+ toolFailure("blocked", "the write was cancelled before dispatch"),+ true,+ ),+ };+ }+ if (typeof input.handle !== "string" || !input.handle) {+ return {+ ok: false,+ result: refusedResult(+ input.operation,+ toolFailure("invalid", "handle must name an element from studio_look"),+ ),+ };+ }+ const projectId = deps.getProjectId();+ if (!projectId) {+ return {+ ok: false,+ result: refusedResult(input.operation, toolFailure("blocked", "there is no active project")),+ };+ }+ const handleFailure = validateProjectScopedHandle<T>(input.handle, projectId, input.operation);+ if (handleFailure) return { ok: false, result: handleFailure };+ const blocked = deps.getWriteBlockedReason();+ if (blocked) {+ return {+ ok: false,+ result: refusedResult(+ input.operation,+ toolFailure("blocked", blocked, "Resolve it in Studio, then retry."),+ ),+ };+ }+ return { ok: true, handle: input.handle, projectId };+}++type PreparedWriteSelection<T extends object> =+ | { ok: true; selection: DomEditSelection }+ | { ok: false; result: StudioWriteResult<T> };++async function prepareWriteSelection<T extends object>(+ deps: TargetedWriteDeps,+ input: TargetedWriteInput<T>,+ handle: string,+): Promise<PreparedWriteSelection<T>> {+ const resolved = await resolveWriteSelection(deps, handle);+ if (!resolved.ok) {+ return { ok: false, result: refusedResult(input.operation, resolved.failure) };+ }+ const { selection } = resolved;+ if (selection.isInsideLockedComposition) {+ return {+ ok: false,+ result: refusedResult(+ input.operation,+ toolFailure("blocked", "the target is inside a locked composition"),+ ),+ };+ }+ const preflight = await input.preflight?.(selection);+ if (preflight) return { ok: false, result: refusedResult(input.operation, preflight) };+ if (input.signal.aborted) {+ return {+ ok: false,+ result: refusedResult(+ input.operation,+ toolFailure("blocked", "the write was cancelled before dispatch"),+ true,+ ),+ };+ }+ return { ok: true, selection };+}++export async function runTargetedWrite<T extends object>(+ deps: TargetedWriteDeps,+ input: TargetedWriteInput<T>,+): Promise<StudioWriteResult<T>> {+ const address = validateWriteAddress(deps, input);+ if (!address.ok) return address.result;+ let prepared: PreparedWriteSelection<T>;+ try {+ prepared = await prepareWriteSelection(deps, input, address.handle);+ } catch (error) {+ const { kind, reason } = classifyThrownError(error);+ if (kind === "internal") console.error(`[hf-webmcp] ${input.operation} preflight threw`, error);+ return refusedResult(input.operation, toolFailure(kind, reason));+ }+ if (!prepared.ok) return prepared.result;+ if (deps.getProjectId() !== address.projectId) {+ return refusedResult(+ input.operation,+ toolFailure(+ "blocked",+ "the active project changed while the target was resolving",+ "Call studio_look in the active project and retry.",+ ),+ );+ }+ const { selection } = prepared;+ const target = { handle: address.handle, sourceFile: selection.sourceFile };+ deps.applySelection(selection);+ const callId = studioEditLifecycle.begin(address.projectId, target, input.operation);+ let adapter: StudioWriteAdapterResult<T>;+ try {+ adapter = await input.write(selection);+ } catch (error) {+ const { kind, reason } = classifyThrownError(error);+ if (kind === "internal") console.error(`[hf-webmcp] ${input.operation} threw`, error);+ const result: StudioWriteResult<T> = {+ ok: false,+ kind,+ reason,+ stage: "failed",+ target,+ operation: input.operation,+ ...(input.signal.aborted ? { cancelRequested: true as const } : {}),+ };+ studioEditLifecycle.finish(callId, result);+ return result;+ }+ const result = completedWrite(adapter, target, input.operation, input.signal.aborted);+ studioEditLifecycle.finish(callId, result);+ return result;+}++function asFailed(failure: ToolFailure): ToolFailure {+ const kind: ToolFailureKind =+ failure.kind === "invalid" || failure.kind === "blocked" ? "failed" : failure.kind;+ return { ...failure, kind };+}++export function dispatched<T extends object>(+ value: T,+ changed: boolean,+): StudioWriteAdapterSuccess<T> & {+ stage: "dispatched";+ evidence: { kind: "dispatch"; followUp: "studio_inspect" };+} {+ return {+ ok: true,+ ...value,+ stage: "dispatched",+ changed,+ evidence: { kind: "dispatch", followUp: "studio_inspect" },+ };+}++export function saved<T extends object>(+ value: T,+ persistence: { sourceFile: string; version: string; changed: boolean },+): StudioWriteAdapterSuccess<T> & {+ stage: "saved";+ evidence: { kind: "content-version"; sourceFile: string; version: string };+} {+ return {+ ok: true,+ ...value,+ stage: "saved",+ changed: persistence.changed,+ evidence: {+ kind: "content-version",+ sourceFile: persistence.sourceFile,+ version: persistence.version,+ },+ };+}++export function verified<T extends object>(+ value: T,+ persistence: { sourceFile: string; version: string; changed: boolean },+ readback: { before: unknown; after: unknown },+): StudioWriteAdapterSuccess<T> & {+ stage: "verified";+ evidence: {+ kind: "readback";+ sourceFile: string;+ version: string;+ before: unknown;+ after: unknown;+ };+} {+ return {+ ok: true,+ ...value,+ stage: "verified",+ changed: persistence.changed,+ evidence: {+ kind: "readback",+ sourceFile: persistence.sourceFile,+ version: persistence.version,+ ...readback,+ },+ };+}diff --git a/packages/studio/tests/e2e/chrome-executable.mjs b/packages/studio/tests/e2e/chrome-executable.mjsnew file mode 100644index 0000000000..b1a868916e--- /dev/null+++ b/packages/studio/tests/e2e/chrome-executable.mjs@@ -0,0 +1,24 @@+import { existsSync, readdirSync } from "node:fs";+import { homedir } from "node:os";+import { join } from "node:path";++/** Resolve the same Chrome binary for every local Studio browser acceptance test. */+export function resolveChromeExecutable() {+ const chromeRoot = join(homedir(), ".cache", "puppeteer", "chrome");+ const builds = existsSync(chromeRoot) ? readdirSync(chromeRoot).sort().reverse() : [];+ const installed = builds.flatMap((build) =>+ [+ "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",+ "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",+ "chrome-linux64/chrome",+ ].map((relative) => join(chromeRoot, build, relative)),+ );+ return [+ process.env.PUPPETEER_EXECUTABLE_PATH,+ process.env.CHROME_PATH,+ "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",+ "/usr/bin/google-chrome",+ "/usr/bin/chromium",+ ...installed,+ ].find((candidate) => candidate && existsSync(candidate));+}diff --git a/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/README.md b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/README.mdnew file mode 100644index 0000000000..e034d8141f--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/README.md@@ -0,0 +1,8 @@+# WebMCP edit-loop acceptance fixture++Two nested source files intentionally author the same `id` and `data-hf-id` for their headline.+The browser acceptance test must use the source-safe handle returned by `studio_look`, edit only one+headline, and prove the sibling source stays byte-for-byte unchanged.++The runner copies this fixture to scratch and symlinks that copy into Studio's ignored+`data/projects` directory. It never mutates the checked-in fixture.diff --git a/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/left-card.html b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/left-card.htmlnew file mode 100644index 0000000000..d809cafc08--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/left-card.html@@ -0,0 +1,33 @@+<template id="left-card-template">+ <section+ id="left-card"+ data-composition-id="left-card"+ data-width="380"+ data-height="300"+ data-start="0"+ data-duration="5"+ data-no-timeline+ style="+ box-sizing: border-box;+ width: 380px;+ height: 300px;+ padding: 36px;+ border: 2px solid #2dd4bf;+ border-radius: 28px;+ background: #10231f;+ "+ >+ <div id="left-card-body" data-hf-id="left-card-body" style="width: 100%; height: 100%">+ <p style="margin: 0 0 28px; color: #5eead4; font-size: 16px; letter-spacing: 0.16em">+ LEFT SOURCE+ </p>+ <h1+ id="duplicate-headline"+ data-hf-id="duplicate-headline"+ style="margin: 0; color: #ecfeff; font-size: 48px; line-height: 1.05"+ >+ Left source+ </h1>+ </div>+ </section>+</template>diff --git a/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/right-card.html b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/right-card.htmlnew file mode 100644index 0000000000..df572dccf4--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/compositions/right-card.html@@ -0,0 +1,33 @@+<template id="right-card-template">+ <section+ id="right-card"+ data-composition-id="right-card"+ data-width="380"+ data-height="300"+ data-start="0"+ data-duration="5"+ data-no-timeline+ style="+ box-sizing: border-box;+ width: 380px;+ height: 300px;+ padding: 36px;+ border: 2px solid #a78bfa;+ border-radius: 28px;+ background: #201936;+ "+ >+ <div id="right-card-body" data-hf-id="right-card-body" style="width: 100%; height: 100%">+ <p style="margin: 0 0 28px; color: #c4b5fd; font-size: 16px; letter-spacing: 0.16em">+ RIGHT SOURCE+ </p>+ <h1+ id="duplicate-headline"+ data-hf-id="duplicate-headline"+ style="margin: 0; color: #f5f3ff; font-size: 48px; line-height: 1.05"+ >+ Right source+ </h1>+ </div>+ </section>+</template>diff --git a/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/hyperframes.json b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/hyperframes.jsonnew file mode 100644index 0000000000..5fb1d6d872--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/hyperframes.json@@ -0,0 +1,9 @@+{+ "$schema": "https://hyperframes.heygen.com/schema/hyperframes.json",+ "registry": "https://raw.githubusercontent.com/heygen-com/hyperframes/main/registry",+ "paths": {+ "blocks": "compositions",+ "components": "compositions/components",+ "assets": "assets"+ }+}diff --git a/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/index.html b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/index.htmlnew file mode 100644index 0000000000..1628d61ccd--- /dev/null+++ b/packages/studio/tests/e2e/fixtures/webmcp-edit-loop/index.html@@ -0,0 +1,72 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <title>WebMCP edit-loop fixture</title>+ <style>+ html,+ body {+ width: 960px;+ height: 540px;+ margin: 0;+ overflow: hidden;+ background: #0b0f17;+ color: #f7fafc;+ font-family: Arial, sans-serif;+ }+ #webmcp-edit-loop {+ position: relative;+ width: 960px;+ height: 540px;+ overflow: hidden;+ background:+ radial-gradient(circle at 50% 10%, rgba(103, 232, 183, 0.12), transparent 40%), #0b0f17;+ }+ .card-host {+ position: absolute;+ top: 120px;+ width: 380px;+ height: 300px;+ }+ #left-host {+ left: 60px;+ }+ #right-host {+ left: 520px;+ }+ </style>+ </head>+ <body>+ <main+ id="webmcp-edit-loop"+ data-composition-id="webmcp-edit-loop"+ data-width="960"+ data-height="540"+ data-start="0"+ data-duration="5"+ data-fps="30"+ data-no-timeline+ >+ <div+ id="left-host"+ class="clip card-host"+ data-hf-id="left-host"+ data-composition-id="left-card-host"+ data-composition-src="compositions/left-card.html"+ data-start="0"+ data-duration="5"+ data-track-index="0"+ ></div>+ <div+ id="right-host"+ class="clip card-host"+ data-hf-id="right-host"+ data-composition-id="right-card-host"+ data-composition-src="compositions/right-card.html"+ data-start="0"+ data-duration="5"+ data-track-index="1"+ ></div>+ </main>+ </body>+</html>diff --git a/packages/studio/tests/e2e/timeline-virtualization.mjs b/packages/studio/tests/e2e/timeline-virtualization.mjsindex 7795bdbd95..89e1ea803f 100644--- a/packages/studio/tests/e2e/timeline-virtualization.mjs+++ b/packages/studio/tests/e2e/timeline-virtualization.mjs@@ -21,10 +21,9 @@* rather than trusting the caller: the server is configured by whoever started* it, and a mismatch would otherwise pass silently against the wrong build.*/-import { existsSync, readdirSync } from "node:fs";-import { homedir, platform, arch } from "node:os";-import { join } from "node:path";+import { platform, arch } from "node:os";import puppeteer from "puppeteer-core";+import { resolveChromeExecutable } from "./chrome-executable.mjs";const STUDIO_URL = process.env.STUDIO_URL;const PROFILE = process.env.TIMELINE_PROFILE || "dense-short";@@ -62,26 +61,6 @@ if (ROW_VIRTUALIZATION === "off" && ELEMENT_COUNT === 50_000) {process.exit(2);}-function resolveChromeExecutable() {- const chromeRoot = join(homedir(), ".cache", "puppeteer", "chrome");- const builds = existsSync(chromeRoot) ? readdirSync(chromeRoot).sort().reverse() : [];- const installedCandidates = builds.flatMap((build) =>- [- "chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",- "chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",- "chrome-linux64/chrome",- ].map((relative) => join(chromeRoot, build, relative)),- );- return [- process.env.PUPPETEER_EXECUTABLE_PATH,- process.env.CHROME_PATH,- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",- "/usr/bin/google-chrome",- "/usr/bin/chromium",- ...installedCandidates,- ].find((candidate) => candidate && existsSync(candidate));-}-function percentile(values, ratio) {if (values.length === 0) return 0;const sorted = [...values].sort((a, b) => a - b);diff --git a/packages/studio/tests/e2e/webmcp-edit-loop.mjs b/packages/studio/tests/e2e/webmcp-edit-loop.mjsnew file mode 100644index 0000000000..3116ca5e73--- /dev/null+++ b/packages/studio/tests/e2e/webmcp-edit-loop.mjs@@ -0,0 +1,836 @@+#!/usr/bin/env node+/**+ * Real-browser proof of Studio's complete WebMCP edit loop.+ *+ * The runner owns its environment: it copies the checked-in adversarial fixture+ * to a temporary directory, symlinks that copy into Studio's ignored project+ * directory, starts a bounded Vite server, injects the real+ * `document.modelContext.registerTool` producer boundary before React mounts,+ * and calls the registered tool definitions through their `execute` callbacks.+ * It never calls a tool implementation directly and never mutates the fixture.+ *+ * Run from the repository root:+ *+ * node packages/studio/tests/e2e/webmcp-edit-loop.mjs+ *+ * Optional environment:+ *+ * WEBMCP_E2E_PORT=5197+ * WEBMCP_E2E_EVIDENCE_DIR=/absolute/output/directory+ * PUPPETEER_EXECUTABLE_PATH=/absolute/path/to/chrome+ */+import {+ cpSync,+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ realpathSync,+ readdirSync,+ rmSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";+import { createHash } from "node:crypto";+import { spawn } from "node:child_process";+import { createServer } from "node:net";+import { arch, platform, tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import puppeteer from "puppeteer-core";+import { resolveChromeExecutable } from "./chrome-executable.mjs";++const E2E_DIR = dirname(fileURLToPath(import.meta.url));+const STUDIO_DIR = resolve(E2E_DIR, "../..");+const FIXTURE_DIR = join(E2E_DIR, "fixtures/webmcp-edit-loop");+const PROJECT_ID = "webmcp-edit-loop";+const REQUESTED_PORT = process.env.WEBMCP_E2E_PORT ? Number(process.env.WEBMCP_E2E_PORT) : null;+const PORT = REQUESTED_PORT ?? (await findAvailablePort());+const ORIGIN = `http://127.0.0.1:${PORT}`;+const RUN_ID = new Date().toISOString().replace(/[:.]/g, "-");+const EVIDENCE_DIR = resolve(+ process.env.WEBMCP_E2E_EVIDENCE_DIR || join(E2E_DIR, "evidence", PROJECT_ID, RUN_ID),+);+const TOOL_COUNT = 12;+const NAVIGATION_TIMEOUT_MS = 90_000;+const RENDER_TIMEOUT_MS = 120_000;++function assert(condition, message) {+ if (!condition) throw new Error(message);+}++function sha256(bytes) {+ return createHash("sha256").update(bytes).digest("hex");+}++function findAvailablePort() {+ return new Promise((resolvePort, reject) => {+ const server = createServer();+ server.once("error", reject);+ server.listen(0, "127.0.0.1", () => {+ const address = server.address();+ if (!address || typeof address === "string") {+ server.close();+ reject(new Error("Could not allocate a Studio test port"));+ return;+ }+ server.close((error) => (error ? reject(error) : resolvePort(address.port)));+ });+ });+}++// Bounded polling is the contract here: startup failure must include the child logs.+// fallow-ignore-next-line complexity+async function waitForServer(child, logs) {+ const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;+ while (Date.now() < deadline) {+ if (child.exitCode !== null) {+ throw new Error(`Studio server exited early (${child.exitCode})\n${logs.join("")}`);+ }+ try {+ const response = await fetch(`${ORIGIN}/api/projects`);+ if (response.ok) return;+ } catch {+ // The port is not listening yet.+ }+ await new Promise((resolveWait) => setTimeout(resolveWait, 250));+ }+ throw new Error(`Studio server did not become ready in ${NAVIGATION_TIMEOUT_MS}ms`);+}++function startStudioServer(logs) {+ const child = spawn("bun", ["run", "dev", "--", "--port", String(PORT), "--strictPort"], {+ cwd: STUDIO_DIR,+ env: { ...process.env, HYPERFRAMES_AUTO_PROXY: "false" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ const record = (chunk) => {+ logs.push(String(chunk));+ if (logs.length > 120) logs.shift();+ };+ child.stdout.on("data", record);+ child.stderr.on("data", record);+ return child;+}++function installModelContextHarness(disabled) {+ if (window.top !== window) return;+ if (disabled) {+ const key = "hf-studio-ui-preferences";+ const previous = JSON.parse(localStorage.getItem(key) ?? "{}");+ localStorage.setItem(key, JSON.stringify({ ...previous, agentToolsEnabled: false }));+ }++ const registered = new Map();+ const pending = new Map();+ const registrationLog = [];+ let nextCallId = 0;++ const abortError = () => new DOMException("Registration aborted", "AbortError");+ const modelContext = {+ async registerTool(tool, options = {}) {+ await Promise.resolve();+ if (options.signal?.aborted) throw abortError();+ if (registered.has(tool.name)) {+ throw new DOMException(`Tool ${tool.name} is already registered`, "InvalidStateError");+ }+ registered.set(tool.name, tool);+ registrationLog.push(tool.name);+ options.signal?.addEventListener(+ "abort",+ () => {+ if (registered.get(tool.name) === tool) registered.delete(tool.name);+ },+ { once: true },+ );+ },+ };++ Object.defineProperty(document, "modelContext", {+ configurable: true,+ value: modelContext,+ });+ Object.defineProperty(window, "__webMcpHarness", {+ configurable: true,+ value: {+ names: () => [...registered.keys()].sort(),+ registrationLog: () => [...registrationLog],+ definitions: () =>+ [...registered.values()].map((tool) => ({+ name: tool.name,+ inputSchema: tool.inputSchema ?? null,+ annotations: tool.annotations ?? null,+ })),+ startCall(name, input) {+ const tool = registered.get(name);+ if (!tool) throw new Error(`Tool ${name} is not registered`);+ const callId = ++nextCallId;+ const controller = new AbortController();+ pending.set(callId, Promise.resolve(tool.execute(input, { signal: controller.signal })));+ return callId;+ },+ async awaitCall(callId) {+ const promise = pending.get(callId);+ if (!promise) throw new Error(`Unknown call ${callId}`);+ try {+ return await promise;+ } finally {+ pending.delete(callId);+ }+ },+ async call(name, input) {+ const callId = this.startCall(name, input);+ return this.awaitCall(callId);+ },+ },+ });+}++async function callTool(page, name, input = {}) {+ return page.evaluate(+ ({ toolName, toolInput }) => window.__webMcpHarness.call(toolName, toolInput),+ { toolName: name, toolInput: input },+ );+}++async function startToolCall(page, name, input) {+ return page.evaluate(+ ({ toolName, toolInput }) => window.__webMcpHarness.startCall(toolName, toolInput),+ { toolName: name, toolInput: input },+ );+}++async function awaitToolCall(page, callId) {+ return page.evaluate((id) => window.__webMcpHarness.awaitCall(id), callId);+}++async function waitForToolSurface(page, expectedCount = TOOL_COUNT) {+ await page.waitForFunction(+ (count) => window.__webMcpHarness?.names().length === count,+ { timeout: NAVIGATION_TIMEOUT_MS },+ expectedCount,+ );+ // Registration is sequential. Require a stable settled count rather than a+ // transient prefix that happens to equal the expected number.+ await new Promise((resolveWait) => setTimeout(resolveWait, 100));+ const names = await page.evaluate(() => window.__webMcpHarness.names());+ assert(names.length === expectedCount, `Expected ${expectedCount} settled tools, got ${names}`);+ return names;+}++// The tool may truthfully refuse while the preview is replacing its document.+// fallow-ignore-next-line complexity+async function waitForReadyLook(page) {+ const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const result = await callTool(page, "studio_look", { limit: 200 });+ if (result.ok && result.sceneStatus === "ready" && result.elementCount > 0) return result;+ await new Promise((resolveWait) => setTimeout(resolveWait, 150));+ }+ throw new Error("studio_look never observed a ready scene");+}++async function waitForLens(page, phase) {+ await page.waitForSelector(`[data-topology-lens="${phase}"] [data-topology-target="true"]`, {+ visible: true,+ timeout: NAVIGATION_TIMEOUT_MS,+ });+ return page.evaluate((expectedPhase) => {+ const player = document.querySelector("hyperframes-player");+ const frame = player?.shadowRoot?.querySelector("iframe");+ return {+ parentPhase: document+ .querySelector("[data-topology-lens]")+ ?.getAttribute("data-topology-lens"),+ iframeHasLens: Boolean(frame?.contentDocument?.querySelector("[data-topology-lens]")),+ targetText: frame?.contentDocument?.querySelector("#duplicate-headline")?.textContent?.trim(),+ expectedPhase,+ };+ }, phase);+}++async function savePageScreenshot(page, name) {+ await page.screenshot({ path: join(EVIDENCE_DIR, name), fullPage: false });+}++async function saveAnimatedPageScreenshot(page, name) {+ // Capture after the motion has become legible, not on the first rendered frame.+ await new Promise((resolveWait) => setTimeout(resolveWait, 96));+ await savePageScreenshot(page, name);+}++async function savePreviewScreenshot(page, name) {+ const handle = await page.evaluateHandle(() => {+ const player = document.querySelector("hyperframes-player");+ return player?.shadowRoot?.querySelector("iframe") ?? null;+ });+ const element = handle.asElement();+ assert(element, "Could not find the Studio preview iframe");+ await element.screenshot({ path: join(EVIDENCE_DIR, name) });+ await handle.dispose();+}++async function capturePreviewHash(page) {+ const handle = await page.evaluateHandle(() => {+ const player = document.querySelector("hyperframes-player");+ return player?.shadowRoot?.querySelector("iframe") ?? null;+ });+ const element = handle.asElement();+ assert(element, "Could not find the Studio preview iframe");+ const bytes = await element.screenshot({ type: "png" });+ await handle.dispose();+ return sha256(bytes);+}++async function waitForPreviewHashChange(page, previousHash) {+ const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;+ while (Date.now() < deadline) {+ const currentHash = await capturePreviewHash(page);+ if (currentHash !== previousHash) return currentHash;+ await new Promise((resolveWait) => setTimeout(resolveWait, 40));+ }+ throw new Error("Open Studio preview pixels stayed stale while the write was pending");+}++async function saveImageEvidenceFromBrowser(url, evidenceName, contentType) {+ assert(browser, "Browser is unavailable for image evidence");+ const evidencePage = await browser.newPage();+ try {+ await evidencePage.setViewport({ width: 1200, height: 800, deviceScaleFactor: 1 });+ await evidencePage.goto(url, {+ waitUntil: "networkidle0",+ timeout: RENDER_TIMEOUT_MS,+ });+ const image = await evidencePage.waitForSelector("img", {+ visible: true,+ timeout: RENDER_TIMEOUT_MS,+ });+ assert(image, `Browser did not render image evidence for ${url}`);+ const outputPath = join(EVIDENCE_DIR, evidenceName);+ if (contentType.includes("jpeg")) {+ await image.screenshot({ path: outputPath, type: "jpeg", quality: 92 });+ } else {+ await image.screenshot({ path: outputPath, type: "png" });+ }+ } finally {+ await evidencePage.close();+ }+}++async function fetchImage(url, evidenceName, expectedContentType = null) {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), RENDER_TIMEOUT_MS);+ try {+ const response = await fetch(url, { signal: controller.signal });+ assert(response.ok, `Image request failed (${response.status}) for ${url}`);+ const contentType = response.headers.get("content-type") ?? "";+ assert(contentType.startsWith("image/"), `Expected image bytes, got ${contentType} for ${url}`);+ if (expectedContentType) {+ assert(+ contentType.includes(expectedContentType),+ `Expected ${expectedContentType}, got ${contentType} for ${url}`,+ );+ }+ const bytes = Buffer.from(await response.arrayBuffer());+ assert(bytes.length > 1_000, `Image evidence was unexpectedly small (${bytes.length} bytes)`);+ await saveImageEvidenceFromBrowser(url, evidenceName, contentType);+ return { contentType, sha256: sha256(bytes), size: bytes.length };+ } finally {+ clearTimeout(timeout);+ }+}++async function findMountedThumbnailUrl(page, sourceFile, previous = null) {+ await page.waitForFunction(+ ({ source, old }) =>+ [...document.querySelectorAll('#sidebar-panel-compositions img[src*="/thumbnail/"]')].some(+ (image) => image.src.includes(source) && (!old || image.src !== old),+ ),+ { timeout: RENDER_TIMEOUT_MS },+ { source: sourceFile, old: previous },+ );+ return page.evaluate((source) => {+ const image = [+ ...document.querySelectorAll('#sidebar-panel-compositions img[src*="/thumbnail/"]'),+ ].find((candidate) => candidate.src.includes(source));+ return image?.src ?? null;+ }, sourceFile);+}++function targetForSource(look, sourceFile) {+ const candidates = look.elements.filter(+ (element) => element.sourceFile === sourceFile && element.handle.includes("duplicate-headline"),+ );+ assert(+ candidates.length === 1,+ `Expected one duplicate headline in ${sourceFile}, got ${candidates.length}`,+ );+ return candidates[0];+}++// An agent follows the refusal hint with a fresh look, but never retries forever.+// fallow-ignore-next-line complexity+async function selectWithBoundedReacquire(page, initialTarget, sourceFile) {+ let target = initialTarget;+ for (let attempt = 0; attempt < 3; attempt += 1) {+ const selection = await callTool(page, "studio_select", { handle: target.handle });+ if (selection.ok) return { selection, target };+ const targetChanged =+ selection.kind === "invalid" &&+ selection.reason === "the target changed while it was resolving";+ if (!targetChanged || attempt === 2) {+ throw new Error(+ `studio_select failed after ${attempt + 1} attempt(s): ${JSON.stringify(selection)}`,+ );+ }+ target = targetForSource(await waitForReadyLook(page), sourceFile);+ }+ throw new Error("unreachable selection retry state");+}++// Linear browser acceptance scenario. Splitting it would hide the causal chain+// between the write receipt, source bytes, overlay, thumbnail, frame, and reload.+// fallow-ignore-next-line complexity+async function runBrowserProof(page) {+ const mutationResponses = [];+ await page.evaluateOnNewDocument(installModelContextHarness, false);+ await page.setRequestInterception(true);+ page.on("request", (request) => {+ if (+ request.method() === "POST" &&+ (request.url().includes("/file-mutations/") || request.url().includes("/gsap-mutations/"))+ ) {+ setTimeout(() => void request.continue(), 340);+ return;+ }+ void request.continue();+ });+ page.on("response", (response) => {+ if (!response.url().includes("/file-mutations/patch-element/")) return;+ void response+ .json()+ .then((body) => mutationResponses.push({ status: response.status(), body }))+ .catch(() => undefined);+ });++ await page.goto(`${ORIGIN}/#project/${PROJECT_ID}`, {+ waitUntil: "domcontentloaded",+ timeout: NAVIGATION_TIMEOUT_MS,+ });+ const registeredTools = await waitForToolSurface(page);+ const definitions = await page.evaluate(() => window.__webMcpHarness.definitions());+ const writeTools = definitions.filter(+ (definition) =>+ definition.name.startsWith("studio_") &&+ [+ "studio_set_text",+ "studio_set_style",+ "studio_transform",+ "studio_add_animation",+ "studio_update_animation",+ "studio_add_keyframe",+ "studio_delete_animation",+ ].includes(definition.name),+ );+ for (const tool of writeTools) {+ assert(tool.inputSchema?.required?.includes("handle"), `${tool.name} does not require handle`);+ }++ const lookBefore = await waitForReadyLook(page);+ let left = targetForSource(lookBefore, "compositions/left-card.html");+ const right = targetForSource(lookBefore, "compositions/right-card.html");+ assert(left.handle !== right.handle, "Duplicate authored ids produced the same handle");+ assert(+ left.parentHandle && right.parentHandle && left.depth > 0 && right.depth > 0,+ `Nested targets did not report source hierarchy: ${JSON.stringify([left, right])}`,+ );++ const selected = await selectWithBoundedReacquire(page, left, "compositions/left-card.html");+ left = selected.target;+ const { selection } = selected;+ assert(+ selection.ok && selection.handle === left.handle,+ `studio_select did not select the left handle: ${JSON.stringify(selection)}`,+ );+ assert(+ selection.box.width > 1 && selection.box.height > 1,+ `studio_select returned inert geometry: ${JSON.stringify(selection)}`,+ );+ const selectedTarget = await page.waitForSelector('[data-dom-edit-selection-box="true"]', {+ visible: true,+ timeout: NAVIGATION_TIMEOUT_MS,+ });+ assert(selectedTarget, "studio_select did not expose the agent target in Studio");+ await savePageScreenshot(page, "00-agent-target-selected.png");++ const thumbnailBeforeUrl = await findMountedThumbnailUrl(page, "left-card.html");+ assert(thumbnailBeforeUrl, "No mounted left-card thumbnail URL was found");+ const thumbnailBefore = await fetchImage(+ thumbnailBeforeUrl,+ "thumbnail-before.jpg",+ "image/jpeg",+ );++ const frameBeforeResult = await callTool(page, "studio_frame", { time: 1, settleMs: 0 });+ assert(frameBeforeResult.ok, `Initial studio_frame failed: ${JSON.stringify(frameBeforeResult)}`);+ const frameBefore = await fetchImage(+ new URL(frameBeforeResult.url, ORIGIN),+ "frame-before.png",+ "image/png",+ );++ const leftSourcePath = join(globalThis.__webmcpProjectRoot, "compositions/left-card.html");+ const rightSourcePath = join(globalThis.__webmcpProjectRoot, "compositions/right-card.html");+ const leftSourceBefore = readFileSync(leftSourcePath, "utf8");+ const rightSourceBefore = readFileSync(rightSourcePath, "utf8");++ const previewBeforeText = await capturePreviewHash(page);+ const firstCall = await startToolCall(page, "studio_set_text", {+ handle: left.handle,+ text: "Agent saved this",+ });+ const acquiring = await waitForLens(page, "acquiring");+ assert(acquiring.parentPhase === "acquiring", "New target did not enter acquisition");+ assert(!acquiring.iframeHasLens, "Topology Lens leaked into the preview iframe DOM");+ const previewDuringText = await waitForPreviewHashChange(page, previewBeforeText);+ await saveAnimatedPageScreenshot(page, "01-new-target-acquiring.png");+ await savePreviewScreenshot(page, "02-preview-during-action.png");++ // Start the source renderer while acquisition is visible, but do not await+ // its comparatively slow Chrome capture before observing the short seal.+ const frameDuringActionCall = await startToolCall(page, "studio_frame", { time: 1, settleMs: 0 });++ const firstReceipt = await awaitToolCall(page, firstCall);+ assert(firstReceipt.ok, `Text write failed: ${JSON.stringify(firstReceipt)}`);+ assert(+ ["saved", "verified"].includes(firstReceipt.stage),+ `Expected durable receipt, got ${JSON.stringify(firstReceipt)}; mutation=${JSON.stringify(mutationResponses.at(-1))}`,+ );+ assert(firstReceipt.changed === true, "First write did not report a durable change");+ assert(+ firstReceipt.target?.sourceFile === "compositions/left-card.html",+ `Receipt named the wrong source: ${JSON.stringify(firstReceipt.target)}`,+ );+ const sealing = await waitForLens(page, "sealing");+ assert(!sealing.iframeHasLens, "Persisted seal leaked into the preview iframe DOM");+ await saveAnimatedPageScreenshot(page, "03-persisted-seal.png");+ const frameDuringActionResult = await awaitToolCall(page, frameDuringActionCall);+ assert(frameDuringActionResult.ok, "studio_frame failed after starting during acquisition");+ const frameDuringAction = await fetchImage(+ new URL(frameDuringActionResult.url, ORIGIN),+ "frame-during-action.png",+ "image/png",+ );++ const repeatedCall = await startToolCall(page, "studio_set_style", {+ handle: left.handle,+ styles: { color: "#67e8f9" },+ });+ const localizing = await waitForLens(page, "localizing");+ assert(+ localizing.parentPhase === "localizing",+ "Repeated target reacquired instead of localizing",+ );+ await saveAnimatedPageScreenshot(page, "04-repeated-target-localizing.png");+ const repeatedReceipt = await awaitToolCall(page, repeatedCall);+ assert(+ repeatedReceipt.ok && repeatedReceipt.stage === "saved",+ "Repeated style write was not saved",+ );++ const newTargetCall = await startToolCall(page, "studio_set_style", {+ handle: right.handle,+ styles: { color: "#f5f3ff" },+ });+ const reacquiring = await waitForLens(page, "acquiring");+ assert(reacquiring.parentPhase === "acquiring", "Changing targets did not restore acquisition");+ await saveAnimatedPageScreenshot(page, "05-new-target-reacquiring.png");+ const newTargetReceipt = await awaitToolCall(page, newTargetCall);+ assert(+ newTargetReceipt.ok && newTargetReceipt.changed === false,+ `Sibling no-op was not truthful: ${JSON.stringify(newTargetReceipt)}`,+ );++ const previewBeforeTransform = await capturePreviewHash(page);+ const transformReceipt = await callTool(page, "studio_transform", {+ handle: left.handle,+ width: 280,+ height: 60,+ });+ assert(+ transformReceipt.ok && transformReceipt.applied.includes("resize"),+ `Transform did not land: ${JSON.stringify(transformReceipt)}`,+ );+ const previewAfterTransform = await capturePreviewHash(page);+ assert(+ previewAfterTransform !== previewBeforeTransform,+ "Open Studio preview pixels stayed stale after transform success",+ );++ const animationTime = 0.25;+ const seekBeforeAnimation = await callTool(page, "studio_seek", { time: animationTime });+ assert(seekBeforeAnimation.ok, "Could not seek before the live-animation proof");+ const previewBeforeAnimation = await capturePreviewHash(page);+ const animationReceipt = await callTool(page, "studio_add_animation", {+ handle: left.handle,+ method: "from",+ });+ assert(+ animationReceipt.ok,+ `Animation write failed: ${JSON.stringify(animationReceipt)}; mutation=${JSON.stringify(mutationResponses.at(-1))}`,+ );+ const sourceAfterAnimation = readFileSync(leftSourcePath, "utf8");+ assert(+ sourceAfterAnimation.includes("gsap"),+ "Animation tool returned before the GSAP source write was durable",+ );+ const seekAfterAnimation = await callTool(page, "studio_seek", { time: animationTime });+ assert(seekAfterAnimation.ok, "Could not seek after the live-animation proof");+ const previewAfterAnimation = await capturePreviewHash(page);+ assert(+ previewAfterAnimation !== previewBeforeAnimation,+ "Open Studio preview pixels stayed stale after animation success",+ );+ await savePreviewScreenshot(page, "05-live-animation-preview.png");++ const leftSourceAfter = readFileSync(leftSourcePath, "utf8");+ const rightSourceAfter = readFileSync(rightSourcePath, "utf8");+ assert(+ leftSourceAfter.includes("Agent saved this"),+ "Left source file did not persist the text edit",+ );+ assert(leftSourceAfter.includes("#67e8f9"), "Left source file did not persist the style edit");+ assert(leftSourceAfter !== leftSourceBefore, "Target source stayed byte-for-byte unchanged");+ assert(rightSourceAfter === rightSourceBefore, "The duplicate-id sibling source was modified");++ const thumbnailAfterUrl = await findMountedThumbnailUrl(+ page,+ "left-card.html",+ thumbnailBeforeUrl,+ );+ assert(thumbnailAfterUrl, "Mounted thumbnail URL did not advance after persistence");+ const beforeRevision = new URL(thumbnailBeforeUrl).searchParams.get("revision");+ const afterRevision = new URL(thumbnailAfterUrl).searchParams.get("revision");+ assert(beforeRevision !== afterRevision, `Thumbnail revision stayed at ${beforeRevision}`);+ const thumbnailAfter = await fetchImage(thumbnailAfterUrl, "thumbnail-after.jpg", "image/jpeg");+ assert(+ thumbnailAfter.sha256 !== thumbnailBefore.sha256,+ "Fresh thumbnail bytes matched stale bytes",+ );++ const frameAfterResult = await callTool(page, "studio_frame", { time: 1, settleMs: 200 });+ assert(+ frameAfterResult.ok,+ `Post-write studio_frame failed: ${JSON.stringify(frameAfterResult)}`,+ );+ const frameAfter = await fetchImage(+ new URL(frameAfterResult.url, ORIGIN),+ "frame-after.png",+ "image/png",+ );+ assert(+ frameAfter.sha256 !== frameBefore.sha256,+ "Post-write frame bytes matched pre-write frame",+ );+ await savePageScreenshot(page, "06-studio-after.png");++ const historyBeforeReload = (await callTool(page, "studio_look", { limit: 1 })).history;+ assert(+ historyBeforeReload?.canUndo && historyBeforeReload.undoLabel,+ "Write did not enter undo history",+ );++ await page.reload({ waitUntil: "domcontentloaded", timeout: NAVIGATION_TIMEOUT_MS });+ await waitForToolSurface(page);+ const lookAfterReload = await waitForReadyLook(page);+ const leftAfterReload = targetForSource(lookAfterReload, "compositions/left-card.html");+ const inspectAfterReload = await callTool(page, "studio_inspect", {+ handle: leftAfterReload.handle,+ });+ assert(inspectAfterReload.ok, "Reloaded target could not be inspected by its new handle");+ assert(inspectAfterReload.text?.includes("Agent saved this"), "Reload lost the persisted text");+ assert(+ inspectAfterReload.inlineStyles?.color === "#67e8f9" ||+ inspectAfterReload.styles?.color?.includes("103, 232, 249"),+ `Reload lost the persisted style: ${JSON.stringify(inspectAfterReload.inlineStyles)}`,+ );+ assert(+ lookAfterReload.history.undoLabel === historyBeforeReload.undoLabel,+ `Reload changed undo identity (${historyBeforeReload.undoLabel} -> ${lookAfterReload.history.undoLabel})`,+ );+ await savePageScreenshot(page, "07-reload-persistence.png");++ return {+ registeredTools,+ writeSchemasRequireHandle: writeTools.map((tool) => tool.name),+ duplicateTargets: [left, right],+ selection,+ receipts: {+ first: firstReceipt,+ repeated: repeatedReceipt,+ siblingNoOp: newTargetReceipt,+ transform: transformReceipt,+ animation: animationReceipt,+ },+ lens: { acquiring, sealing, localizing, reacquiring },+ source: {+ changed: "compositions/left-card.html",+ unchanged: "compositions/right-card.html",+ leftBefore: sha256(leftSourceBefore),+ leftAfter: sha256(leftSourceAfter),+ rightBefore: sha256(rightSourceBefore),+ rightAfter: sha256(rightSourceAfter),+ },+ thumbnail: {+ beforeRevision,+ afterRevision,+ before: thumbnailBefore,+ after: thumbnailAfter,+ },+ frame: {+ before: frameBefore,+ duringAction: frameDuringAction,+ after: frameAfter,+ liveTextPreview: { before: previewBeforeText, during: previewDuringText },+ livePreview: { before: previewBeforeAnimation, after: previewAfterAnimation },+ transformPreview: { before: previewBeforeTransform, after: previewAfterTransform },+ },+ reload: {+ text: inspectAfterReload.text,+ color: inspectAfterReload.inlineStyles?.color ?? inspectAfterReload.styles?.color,+ undoLabel: lookAfterReload.history.undoLabel,+ },+ };+}++async function proveDisabledPreference(browser) {+ const page = await browser.newPage();+ await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 1 });+ await page.evaluateOnNewDocument(installModelContextHarness, true);+ await page.goto(`${ORIGIN}/#project/${PROJECT_ID}`, {+ waitUntil: "domcontentloaded",+ timeout: NAVIGATION_TIMEOUT_MS,+ });+ await page.waitForFunction(() => document.querySelector("hyperframes-player"), {+ timeout: NAVIGATION_TIMEOUT_MS,+ });+ await new Promise((resolveWait) => setTimeout(resolveWait, 500));+ const names = await page.evaluate(() => window.__webMcpHarness.names());+ assert(names.length === 0, `Disabled preference registered tools: ${names.join(", ")}`);+ await page.close();+ return { registeredTools: names };+}++const chromeExecutable = resolveChromeExecutable();+if (!chromeExecutable) {+ console.error("No Chrome executable found. Set PUPPETEER_EXECUTABLE_PATH.");+ process.exit(2);+}+assert(Number.isInteger(PORT) && PORT > 0 && PORT < 65_536, `Invalid WEBMCP_E2E_PORT: ${PORT}`);++mkdirSync(EVIDENCE_DIR, { recursive: true });+const tempRoot = mkdtempSync(join(tmpdir(), "hf-webmcp-edit-loop-"));+const projectRoot = join(tempRoot, PROJECT_ID);+const dataProjectsDir = join(STUDIO_DIR, "data/projects");+const projectLink = join(dataProjectsDir, PROJECT_ID);+const serverLogs = [];+let server = null;+let browser = null;++try {+ cpSync(FIXTURE_DIR, projectRoot, { recursive: true });+ mkdirSync(dataProjectsDir, { recursive: true });+ assert(!existsSync(projectLink), `${projectLink} already exists; refusing to replace it`);+ symlinkSync(projectRoot, projectLink, "dir");+ globalThis.__webmcpProjectRoot = projectRoot;++ server = startStudioServer(serverLogs);+ await waitForServer(server, serverLogs);+ browser = await puppeteer.launch({+ executablePath: chromeExecutable,+ headless: true,+ args: ["--disable-gpu", "--no-first-run", "--no-default-browser-check"],+ });+ const page = await browser.newPage();+ page.setDefaultTimeout(NAVIGATION_TIMEOUT_MS);+ await page.setViewport({ width: 1600, height: 1000, deviceScaleFactor: 1 });++ const consoleErrors = [];+ const failedResponses = [];+ page.on("pageerror", (error) => consoleErrors.push(`pageerror: ${error.message}`));+ page.on("console", (message) => {+ if (message.type() === "error") consoleErrors.push(`console: ${message.text()}`);+ });+ page.on("response", (response) => {+ if (response.status() >= 400) {+ failedResponses.push({ status: response.status(), url: response.url() });+ }+ });++ const proof = await runBrowserProof(page);+ const disabledPreference = await proveDisabledPreference(browser);+ const allowedFfmpegProbeMisses = failedResponses.filter((response) => {+ const url = new URL(response.url);+ return response.status === 404 && url.pathname === "/api/environment/ffmpeg";+ });+ assert(+ allowedFfmpegProbeMisses.length === failedResponses.length,+ `Unexpected failed browser response: ${JSON.stringify(failedResponses)}`,+ );+ assert(+ consoleErrors.length === allowedFfmpegProbeMisses.length &&+ consoleErrors.every((message) => message.includes("404 (Not Found)")),+ `Unexpected browser console error: ${JSON.stringify(consoleErrors)}`,+ );+ const environment = {+ browser: await browser.version(),+ platform: platform(),+ architecture: arch(),+ viewport: { width: 1600, height: 1000, deviceScaleFactor: 1 },+ origin: ORIGIN,+ headless: true,+ };+ const report = {+ ok: true,+ environment,+ proof,+ disabledPreference,+ consoleErrors,+ failedResponses,+ allowedResourceWarning: {+ path: "/api/environment/ffmpeg",+ reason:+ "The standalone Vite server lacks the optional CLI probe; Studio treats it as unknown.",+ occurrences: allowedFfmpegProbeMisses.length,+ },+ evidenceFiles: readdirSync(EVIDENCE_DIR).sort(),+ };+ writeFileSync(join(EVIDENCE_DIR, "report.json"), `${JSON.stringify(report, null, 2)}\n`);+ console.log(JSON.stringify({ ok: true, environment, evidenceDir: EVIDENCE_DIR, proof }, null, 2));+} catch (error) {+ const failure = {+ ok: false,+ error: error instanceof Error ? (error.stack ?? error.message) : String(error),+ serverLogs: serverLogs.join("").slice(-12_000),+ };+ console.error(failure.error);+ process.exitCode = 1;+} finally {+ await browser?.close().catch(() => undefined);+ if (server && server.exitCode === null) {+ server.kill("SIGTERM");+ await Promise.race([+ new Promise((resolveExit) => server.once("exit", resolveExit)),+ new Promise((resolveWait) => setTimeout(resolveWait, 2_000)),+ ]);+ if (server.exitCode === null) server.kill("SIGKILL");+ }+ if (existsSync(projectLink)) {+ const linkedRoot = realpathSync(projectLink);+ const expectedRoot = realpathSync(projectRoot);+ assert(linkedRoot === expectedRoot, `Refusing to remove unexpected project link ${linkedRoot}`);+ unlinkSync(projectLink);+ }+ rmSync(tempRoot, { recursive: true });+}diff --git a/packages/studio/vite.config.ts b/packages/studio/vite.config.tsindex 649e3a2ece..5fecdc02fe 100644--- a/packages/studio/vite.config.ts+++ b/packages/studio/vite.config.ts@@ -6,6 +6,7 @@ import { readNodeRequestBody } from "./vite.request-body.js";import { watch } from "chokidar";import { createProjectSignatureCache, createViteAdapter } from "./vite.adapter";import { previewConfigPayload } from "./vite.preview-config";+import { loadStudioServerDevModule } from "./vite.studio-server-module";async function loadRuntimeSourceForDev(server: import("vite").ViteDevServer,@@ -115,8 +116,13 @@ function devProjectApi(): Plugin {} | null = null;const getApi = async () => {if (!_api) {- const mod = await server.ssrLoadModule("@hyperframes/studio-server");- _studioServerModule = mod as typeof _studioServerModule;+ // The package's `node` condition resolves to ignored dist output,+ // which may predate the source under test. Studio dev owns a source+ // workspace, so load that producer explicitly.+ const mod = (await loadStudioServerDevModule(server, __dirname)) as NonNullable<+ typeof _studioServerModule+ >;+ _studioServerModule = mod;const adapter = createViteAdapter(dataDir, server, signatureCache);_api = mod.createStudioApi(adapter);}diff --git a/packages/studio/vite.studio-server-module.test.ts b/packages/studio/vite.studio-server-module.test.tsnew file mode 100644index 0000000000..62b35c10df--- /dev/null+++ b/packages/studio/vite.studio-server-module.test.ts@@ -0,0 +1,14 @@+import { resolve } from "node:path";+import { describe, expect, it, vi } from "vitest";+import { loadStudioServerDevModule } from "./vite.studio-server-module";++describe("loadStudioServerDevModule", () => {+ it("passes the workspace server source entry to Vite instead of the package node export", async () => {+ const ssrLoadModule = vi.fn().mockResolvedValue({ createStudioApi: vi.fn() });+ const studioDir = resolve("repo/packages/studio");++ await loadStudioServerDevModule({ ssrLoadModule }, studioDir);++ expect(ssrLoadModule).toHaveBeenCalledWith(resolve(studioDir, "../studio-server/src/index.ts"));+ });+});diff --git a/packages/studio/vite.studio-server-module.ts b/packages/studio/vite.studio-server-module.tsnew file mode 100644index 0000000000..faefc5d38e--- /dev/null+++ b/packages/studio/vite.studio-server-module.ts@@ -0,0 +1,13 @@+import { resolve } from "node:path";++interface StudioServerDevModuleLoader {+ ssrLoadModule(id: string): Promise<unknown>;+}++/** Load the workspace server source so Studio dev cannot execute a stale ignored dist build. */+export function loadStudioServerDevModule(+ server: StudioServerDevModuleLoader,+ studioDir: string,+): Promise<unknown> {+ return server.ssrLoadModule(resolve(studioDir, "../studio-server/src/index.ts"));+}