diff --git a/docs/product/architecture.md b/docs/product/architecture.md index dcd94b8a9..1427ea3f5 100644 --- a/docs/product/architecture.md +++ b/docs/product/architecture.md @@ -146,6 +146,8 @@ For catalog discovery requests (browse, compare or recommend), the template rout 3. `openmotion_open_preview({projectId})` opens the project directly. Project switching waits for pending saves and replaces only the project viewer after validating its native context, preserving the application shell. Opening a bookmark warms only its scoped native context without switching other editor tabs. Rendering and write conflicts continue to block unsafe switches. Original creation, reference recreation and template production automatically open the saved project before delivery; the open editor is the deliverable, and video files are handed over only when requested (video-to-template still delivers its template ZIP). Continued edits and restores return a project/revision/version-bound previewHandoff. Reuse the native project tab: present it when the calling chat is active, otherwise queue it without switching chats and resolve the latest version when the user returns. Only this turn's explicit `presentation=now` request permits switching back; explicit background requests suppress presentation. Codex IAB synchronizes visibility within the calling chat. A queued acknowledgment does not establish chat inactivity: hidden/unavailable panels retain presentation recovery, and only host-confirmed inactive-chat deferral waits for return. First delivery uses the same visibility checks; hidden automation playback, markDeliverable and export success do not complete editor delivery. A queued acknowledgment is separate from observed visibility and live-content freshness; `record_display` rejects stale content identities, and stored previewDisplay remains historical host-reported evidence. The shared [editable preview handoff](../../skills/openmotion-production/references/native.md#editable-preview-handoff) defines readiness, host checks and capability limitations. 4. Agent 根据本轮目标直接选择 Skill:openmotion-director 负责原创、局部/整体叙事动作声音重新设计和创作审片;openmotion-template-to-video 负责已有模板出片;openmotion-recreate 负责参考作品重建(已接入实际流程、独立参考与测量脚本);openmotion-video-to-template 负责可复用模板生产;openmotion-production 承接既定决定下的工程操作、预览、技术检查、排错和导出。共享规则同源引用,已有 production/start 保留导航,无需前置总路由。项目来源与画面锁定不固定入口;保持项和已完成操作继续有效。 5. The Agent imports or generates media through the existing backend. In the editor, the user imports assets, edits text/solid color/opacity, previews, and edits clips on the timeline. Element, clip, time-range and official animation-library Ask Agent entry points are hidden in the MVP; users can continue requesting edits through their external Agent. Text controls include headings with explicit line breaks and preserve those breaks when edited. The MVP omits the layer-count heading and Add text field controls. Unselected off-canvas elements have no dashed markers in the MVP preview; selecting an element, including from Layers, retains its selection boundary. Text selections omit the separate Style group and background-fill control; element opacity remains in Text. For opacity-animated elements, the MVP opacity control saves an independent CSS filter multiplier, retaining the authored fade and existing static filters rather than writing over the animated opacity channel. The multiplier is part of project source, so preview and export use the same value. Other element types retain their Style controls. Generation, image replacement, advanced style/animation controls, code and inspector Layout settings are hidden without rewriting existing source content or removing Agent capabilities. + Element deletion compares direct DOM lookup results before and after a simulated deletion, preserving receiver scope and detecting structural-selector changes in surviving inline scripts before either SDK or REST mutation, including computed static method names and legacy JavaScript MIME types. A dependency, dynamic lookup or unparseable executable script refuses the deletion with localized feedback and leaves source and history unchanged; files with executable inline scripts also refuse ambiguous or scoped hf-id handles because SDK and REST resolution can differ. Ordinary GSAP selector cleanup remains delegated to the native engine. This is a conservative guard, not arbitrary JavaScript rewriting or cross-file dependency analysis. + 6. 完成画面、文案、声音检查后,按用户要求导出固定 revision 的快照,等待真实产物并验证。 An explicit HTML/MP4 request for an unchanged editable template follows the [unchanged file-delivery branch](../../skills/openmotion-template-to-video/references/unchanged-export.md), also exposed as `openmotion://workflow/template/unchanged`. It preserves the template source and completes any required editor normalization before pinning the revision/version. Immutable export, packaging of that same version and host presentation can then proceed concurrently. Technical verification and actual final-file full playback, seeking and replay remain required; editorial redesign is scoped to requested changes. Presentation recovery is bounded and its result is reported separately, so a display failure does not prevent delivery of verified files or imply that the editor was visible. diff --git a/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx b/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx index 3a316bd61..a1d421515 100644 --- a/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx +++ b/studio/src/hooks/useElementLifecycleOps.multiDelete.test.tsx @@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { useElementLifecycleOps } from "./useElementLifecycleOps"; import { makeLifecycleOpsParams } from "./elementLifecycleOpsTestUtils"; import { mountReactHarness, makeSelection } from "./domSelectionTestHarness"; +import { SCRIPT_DEPENDENCY_DELETE_MESSAGE } from "../utils/deleteScriptDependencies"; Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true); @@ -36,12 +37,14 @@ describe("useElementLifecycleOps — deleting a canvas multi-selection", () => { const requests: string[] = []; let changes = true; let removeOk = true; + let sourceContent = ""; beforeEach(() => { removed.length = 0; requests.length = 0; changes = true; removeOk = true; + sourceContent = ""; vi.stubGlobal( "fetch", vi.fn(async (url: string, init?: RequestInit) => { @@ -60,7 +63,7 @@ describe("useElementLifecycleOps — deleting a canvas multi-selection", () => { ok: status === 200, status, text: async () => (status === 200 ? "" : "server said no"), - json: async () => ({ changed: changes, content: "" }), + json: async () => ({ changed: changes, content: sourceContent }), } as unknown as Response; }), ); @@ -123,6 +126,82 @@ describe("useElementLifecycleOps — deleting a canvas multi-selection", () => { expect(requests).toEqual([]); }); + it.each([false, true])("preserves a whole selection with script dependencies before deleting through SDK=%s", async (sdk) => { + sourceContent = `
+
+ `; + const onTrySdkDelete = vi.fn(async () => ({ status: "committed", version: "v", before: sourceContent, after: "" }) as const); + const recordEdit = vi.fn(); + const writeProjectFile = vi.fn(); + const reloadPreview = vi.fn(); + const showToast = vi.fn(); + const ops = mountDeleteOps({ projectIdRef: { current: "p1" }, showToast, writeProjectFile, + reloadPreview, editHistory: { recordEdit }, ...(sdk ? { onTrySdkDelete } : {}) }); + const selections = ["a", "b"].map((id) => ({ ...selectionFor(id), hfId: `hf-${id}` })); + + await act(async () => { + expect(await ops.handleDomEditElementsDelete(selections)).toEqual({ ok: false, reason: "persist-failed" }); + }); + + expect(onTrySdkDelete).not.toHaveBeenCalled(); + expect(requests.some((url) => url.includes("remove-elements"))).toBe(false); + expect(writeProjectFile).not.toHaveBeenCalled(); + expect(recordEdit).not.toHaveBeenCalled(); + expect(reloadPreview).not.toHaveBeenCalled(); + expect(showToast).toHaveBeenLastCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("preflights combined structural changes before the first SDK member commits", async () => { + sourceContent = '
'; + const onTrySdkDelete = vi.fn(async () => ({ status: "committed", version: "v", before: sourceContent, after: "" }) as const); + const showToast = vi.fn(); + const ops = mountDeleteOps({ projectIdRef: { current: "p1" }, showToast, onTrySdkDelete }); + const selections = ["a", "b"].map((id) => ({ ...selectionFor(id), hfId: `hf-${id}` })); + await act(async () => { + expect(await ops.handleDomEditElementsDelete(selections)).toEqual({ ok: false, reason: "persist-failed" }); + }); + expect(onTrySdkDelete).not.toHaveBeenCalled(); + expect(requests.some((url) => url.includes("remove-elements"))).toBe(false); + expect(showToast).toHaveBeenLastCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("checks individually committed SDK members before deleting any selection member", async () => { + sourceContent = `
+
+
`; + const onTrySdkDelete = vi.fn(); + const showToast = vi.fn(); + const ops = mountDeleteOps({ projectIdRef: { current: "p1" }, showToast, onTrySdkDelete }); + const selections = ["a", "b", "c"].map((id) => ({ ...selectionFor(id), hfId: `hf-${id}` })); + await act(async () => { + expect(await ops.handleDomEditElementsDelete(selections)).toEqual({ ok: false, reason: "persist-failed" }); + }); + expect(onTrySdkDelete).not.toHaveBeenCalled(); + expect(requests.some((url) => url.includes("remove-elements"))).toBe(false); + expect(showToast).toHaveBeenLastCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("refuses a batch whose shifted selector would delete a script dependency", async () => { + sourceContent = '
A
B
C
'; + const recordEdit = vi.fn(); + const writeProjectFile = vi.fn(); + const reloadPreview = vi.fn(); + const showToast = vi.fn(); + const ops = mountDeleteOps({ projectIdRef: { current: "p1" }, showToast, writeProjectFile, + reloadPreview, editHistory: { recordEdit } }); + const selections = [0, 1].map((selectorIndex) => ({ + ...selectionFor(String(selectorIndex)), id: undefined, selector: ".item", selectorIndex, + })); + await act(async () => { + expect(await ops.handleDomEditElementsDelete(selections)).toEqual({ ok: false, reason: "persist-failed" }); + }); + expect(requests.some((url) => url.includes("remove-elements"))).toBe(false); + expect(writeProjectFile).not.toHaveBeenCalled(); + expect(recordEdit).not.toHaveBeenCalled(); + expect(reloadPreview).not.toHaveBeenCalled(); + expect(showToast).toHaveBeenLastCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + it("reports an HTTP write failure instead of only toasting", async () => { removeOk = false; const ops = mountDeleteOps({ projectIdRef: { current: "p1" } }); diff --git a/studio/src/hooks/useElementLifecycleOps.ts b/studio/src/hooks/useElementLifecycleOps.ts index a4567d9ea..41baeb911 100644 --- a/studio/src/hooks/useElementLifecycleOps.ts +++ b/studio/src/hooks/useElementLifecycleOps.ts @@ -1,5 +1,6 @@ import { buildProjectApiPath } from "../utils/projectRouting"; import { useCallback } from "react"; +import { assertSafeElementDeletion } from "../utils/deleteScriptDependencies"; import { usePlayerStore } from "../player"; import { readProjectFileContent, @@ -125,6 +126,9 @@ export function useElementLifecycleOps({ .filter((hfId): hfId is string => Boolean(hfId)); if (onTrySdkDelete && hfIds.length === sameFile.length) { const originalContent = await readProjectFileContent(pid, targetPath); + assertSafeElementDeletion(originalContent, patchTargets); + // SDK members commit separately; validate each before the first write. + for (const target of patchTargets) assertSafeElementDeletion(originalContent, [target]); let allHandled = true; for (const hfId of hfIds) { // The SDK owns the document it edits, so every member is removed @@ -157,6 +161,7 @@ export function useElementLifecycleOps({ writeFile: writeProjectFile, recordEdit: editHistory.recordEdit, rewrite: async (originalContent) => { + assertSafeElementDeletion(originalContent, patchTargets); const removeResponse = await studioApiFetch( buildProjectApiPath( pid, diff --git a/studio/src/hooks/useTimelineDeleteOps.test.tsx b/studio/src/hooks/useTimelineDeleteOps.test.tsx index ed2b71c96..00d7ddc67 100644 --- a/studio/src/hooks/useTimelineDeleteOps.test.tsx +++ b/studio/src/hooks/useTimelineDeleteOps.test.tsx @@ -7,6 +7,7 @@ import { applyRippleShifts, useTimelineDeleteOps } from "./useTimelineDeleteOps" import { installReactActEnvironment, mountReactHarness } from "./domSelectionTestHarness"; import { useTrackPendingTimelineEdit } from "./useTrackPendingTimelineEdit"; import { flushStudioPendingEdits } from "../utils/studioPendingEdits"; +import { SCRIPT_DEPENDENCY_DELETE_MESSAGE } from "../utils/deleteScriptDependencies"; installReactActEnvironment(); @@ -105,6 +106,46 @@ describe("useTimelineDeleteOps: ripple undo label", () => { }); }); + it("preserves the callout and history when timeline deletion has script dependencies", async () => { + const source = `
+ `; + stubRemoveElementsFetch(source, ""); + const showToast = vi.fn(); + const recordEdit = vi.fn(); + const handleTimelineGroupMove = vi.fn(); + const { elements, b, getHook } = mountDeleteHarness({ showToast, recordEdit, handleTimelineGroupMove }); + b.hfId = "hf-b"; + b.domId = "mk-ch-center"; + usePlayerStore.getState().setElements(elements); + + await act(async () => { await getHook().handleTimelineElementDelete(b); }); + + expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("remove-elements"))).toBe(false); + expect(recordEdit).not.toHaveBeenCalled(); + expect(handleTimelineGroupMove).not.toHaveBeenCalled(); + expect(usePlayerStore.getState().elements).toEqual(elements); + expect(showToast).toHaveBeenCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("preserves a selector batch before shifted indices delete a script dependency", async () => { + const source = '
A
B
C
'; + stubRemoveElementsFetch(source, ""); + const showToast = vi.fn(); + const recordEdit = vi.fn(); + const handleTimelineGroupMove = vi.fn(); + const { elements, getHook } = mountDeleteHarness({ showToast, recordEdit, handleTimelineGroupMove }); + const selected = elements.slice(0, 2).map((element, selectorIndex) => ({ + ...element, domId: undefined, selector: ".item", selectorIndex, + })); + usePlayerStore.getState().setElements(elements); + await act(async () => { await getHook().handleTimelineElementsDelete(selected); }); + expect(vi.mocked(fetch).mock.calls.some(([url]) => String(url).includes("remove-elements"))).toBe(false); + expect(recordEdit).not.toHaveBeenCalled(); + expect(handleTimelineGroupMove).not.toHaveBeenCalled(); + expect(usePlayerStore.getState().elements).toEqual(elements); + expect(showToast).toHaveBeenCalledWith(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + // editHistory.ts's coalescing keeps the LAST recordEdit call's label, so the // folded ripple move must carry the delete's label, not its own. it("passes the delete's own label to the folded ripple move, not 'Move timeline clips'", async () => { diff --git a/studio/src/hooks/useTimelineDeleteOps.ts b/studio/src/hooks/useTimelineDeleteOps.ts index 69ffed018..c19f1fbbb 100644 --- a/studio/src/hooks/useTimelineDeleteOps.ts +++ b/studio/src/hooks/useTimelineDeleteOps.ts @@ -25,6 +25,7 @@ import type { TimelineGroupMoveChange, } from "./useTimelineGroupEditing"; import { studioApiFetch } from "../utils/studioApiFetch"; +import { assertSafeElementDeletion } from "../utils/deleteScriptDependencies"; /** Apply already-resolved ripple changes to the surviving elements for the * optimistic store update after a delete. Pure — no IO. */ @@ -127,6 +128,7 @@ export function useTimelineDeleteOps({ } return patchTarget; }); + assertSafeElementDeletion(originalContent, patchTargets); const removeResponse = await studioApiFetch( buildProjectApiPath( pid, diff --git a/studio/src/i18n/error-ui.json b/studio/src/i18n/error-ui.json index c8bc1d48e..a20392123 100644 --- a/studio/src/i18n/error-ui.json +++ b/studio/src/i18n/error-ui.json @@ -1,5 +1,6 @@ { "zh-CN": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "脚本仍在使用这个元素。请让 Agent 同步修改脚本,或删除整个合成。", "Reconnecting…": "重连中…", "Connection lost.": "连接已断开", "The project changed elsewhere. Resolve the changes before continuing.": "项目已在其他地方修改,请先处理版本冲突。", @@ -49,6 +50,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "界面资源加载失败,请重新加载编辑器后再试。" }, "ja": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "この要素はスクリプトで使用されています。Agent にスクリプトの更新を依頼するか、コンポジション全体を削除してください。", "Reconnecting…": "再接続中…", "Connection lost.": "接続が切れました", "The project changed elsewhere. Resolve the changes before continuing.": "プロジェクトが別の場所で変更されました。競合を解決してから続行してください。", @@ -98,6 +100,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "画面のリソースを読み込めませんでした。エディターを再読み込みしてお試しください。" }, "ko": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "스크립트에서 이 요소를 사용하고 있습니다. Agent에게 스크립트 수정을 요청하거나 전체 컴포지션을 삭제하세요.", "Reconnecting…": "다시 연결 중…", "Connection lost.": "연결이 끊겼습니다", "The project changed elsewhere. Resolve the changes before continuing.": "프로젝트가 다른 곳에서 변경되었습니다. 충돌을 해결한 후 계속하세요.", @@ -147,6 +150,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "인터페이스 리소스를 불러오지 못했습니다. 편집기를 새로고침한 후 다시 시도하세요." }, "de": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Dieses Element wird von einem Skript verwendet. Bitte deinen Agent, das Skript anzupassen, oder lösche die gesamte Komposition.", "Reconnecting…": "Verbindung wird hergestellt…", "Connection lost.": "Verbindung unterbrochen", "The project changed elsewhere. Resolve the changes before continuing.": "Das Projekt wurde andernorts geändert. Lösen Sie den Konflikt, bevor Sie fortfahren.", @@ -196,6 +200,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "Die Oberflächenressourcen konnten nicht geladen werden. Laden Sie den Editor neu und versuchen Sie es erneut." }, "fr": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Cet élément est utilisé par un script. Demandez à votre Agent de modifier le script ou supprimez toute la composition.", "Reconnecting…": "Reconnexion…", "Connection lost.": "Connexion interrompue", "The project changed elsewhere. Resolve the changes before continuing.": "Le projet a été modifié ailleurs. Résolvez le conflit avant de continuer.", @@ -245,6 +250,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "Impossible de charger les ressources de l’interface. Rechargez l’éditeur pour réessayer." }, "es": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Un script utiliza este elemento. Pide a tu Agent que actualice el script o elimina toda la composición.", "Reconnecting…": "Reconectando…", "Connection lost.": "Conexión perdida", "The project changed elsewhere. Resolve the changes before continuing.": "El proyecto se modificó en otro lugar. Resuelve el conflicto antes de continuar.", @@ -294,6 +300,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "No se pudieron cargar los recursos de la interfaz. Recarga el editor para volver a intentarlo." }, "pt-BR": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Este elemento é usado por um script. Peça ao seu Agent para atualizar o script ou exclua toda a composição.", "Reconnecting…": "Reconectando…", "Connection lost.": "Conexão perdida", "The project changed elsewhere. Resolve the changes before continuing.": "O projeto foi alterado em outro local. Resolva o conflito antes de continuar.", @@ -343,6 +350,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "Não foi possível carregar os recursos da interface. Recarregue o editor para tentar novamente." }, "it": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Questo elemento è usato da uno script. Chiedi al tuo Agent di aggiornare lo script oppure elimina l’intera composizione.", "Reconnecting…": "Riconnessione…", "Connection lost.": "Connessione interrotta", "The project changed elsewhere. Resolve the changes before continuing.": "Il progetto è stato modificato altrove. Risolvi il conflitto prima di continuare.", @@ -392,6 +400,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "Impossibile caricare le risorse dell’interfaccia. Ricarica l’editor per riprovare." }, "ru": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Этот элемент используется скриптом. Попросите Agent обновить скрипт или удалите всю композицию.", "Reconnecting…": "Переподключение…", "Connection lost.": "Соединение потеряно", "The project changed elsewhere. Resolve the changes before continuing.": "Проект изменён в другом месте. Разрешите конфликт, прежде чем продолжить.", @@ -441,6 +450,7 @@ "Interface resources could not be loaded. Reload the editor to try again.": "Не удалось загрузить ресурсы интерфейса. Перезагрузите редактор и повторите попытку." }, "tr": { + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition.": "Bu öğe bir betik tarafından kullanılıyor. Agent’tan betiği güncellemesini isteyin veya kompozisyonun tamamını silin.", "Reconnecting…": "Yeniden bağlanılıyor…", "Connection lost.": "Bağlantı kesildi", "The project changed elsewhere. Resolve the changes before continuing.": "Proje başka bir yerde değiştirildi. Devam etmeden önce çakışmayı giderin.", diff --git a/studio/src/i18n/operationFeedback.test.ts b/studio/src/i18n/operationFeedback.test.ts index c3ffef275..0b5a4d664 100644 --- a/studio/src/i18n/operationFeedback.test.ts +++ b/studio/src/i18n/operationFeedback.test.ts @@ -4,6 +4,17 @@ import { importValidationMessage } from './importMessages'; import { splitFailureMessage } from './editorErrors'; import { systemMessage } from './systemMessages'; import { languages } from './messages'; +import { SCRIPT_DEPENDENCY_DELETE_MESSAGE } from '../utils/deleteScriptDependencies'; +import { toastErrorMessage } from '../components/ui/toastErrorMessage'; + +it('localizes script dependency deletion refusals in every editor language', () => { + expect(toastErrorMessage(SCRIPT_DEPENDENCY_DELETE_MESSAGE)).toBe(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + for (const { locale } of languages) { + const message = systemMessage(SCRIPT_DEPENDENCY_DELETE_MESSAGE, (key, values) => translate(locale, key, values)); + if (locale === 'en') expect(message).toBe(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + else expect(message).not.toBe(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + } +}); it('localizes unavailable timeline media in every interface language', () => { expect(translate('zh-CN', 'Media unavailable')).toBe('素材已失效'); diff --git a/studio/src/utils/deleteScriptDependencies.test.ts b/studio/src/utils/deleteScriptDependencies.test.ts new file mode 100644 index 000000000..e44fc8495 --- /dev/null +++ b/studio/src/utils/deleteScriptDependencies.test.ts @@ -0,0 +1,179 @@ +// @vitest-environment happy-dom +import { describe, expect, it } from "vitest"; +import { removeElementsFromHtml } from "@hyperframes/studio-server/source-mutation"; +import { assertSafeElementDeletion, SCRIPT_DEPENDENCY_DELETE_MESSAGE } from "./deleteScriptDependencies"; + +function composition(script: string, markup = '
') { + return `${markup}
`; +} + +describe("script dependencies when deleting elements", () => { + it("protects the callout's descendant text box before its initialization would dereference null", () => { + const source = composition(`const box = document.getElementById("mk-ch-box"); + box.style.fontSize = "60px"; const tl = gsap.timeline({paused:true}); tl.to(box, {opacity:1});`); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-center" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it.each([ + 'document.querySelector("#mk-ch-box").style.color = "red";', + 'document["getElementById"](`mk-ch-box`).remove();', + 'document[`getElementById`]("mk-ch-box").style.color = "red";', + 'document.querySelectorAll(".word").forEach(el => el.remove());', + 'document.getElementsByClassName("word")[0].style.color = "red";', + 'document.getElementsByTagName("div")[0].remove();', + 'const find = document.getElementById; find("mk-ch-box").remove();', + 'document.querySelector(window.selectedElement).remove();', + ])("protects DOM lookup dependencies: %s", (script) => { + expect(() => assertSafeElementDeletion(composition(script), [{ id: "mk-ch-center" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("allows GSAP selector deletion and lookups that only use surviving nodes", () => { + const source = composition(`// document.getElementById("mk-ch-box") + const note = 'document.querySelector("#mk-ch-box")'; + document.getElementById("other").style.color = "red"; + gsap.to("#mk-ch-box", {opacity:0});`); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-center" }])).not.toThrow(); + }); + + it("does not inspect scripts removed with their owning subtree", () => { + const source = composition("", '
'); + expect(() => assertSafeElementDeletion(source, [{ id: "mk-ch-center" }])).not.toThrow(); + }); + + it("checks scripts and descendants inside native composition templates", () => { + const source = ``; + expect(() => assertSafeElementDeletion(source, [{ id: "mk-ch-center" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("respects hf-id precedence and selector indices in a selection", () => { + const source = composition('document.getElementById("mk-ch-box").remove();', '
'); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-other", id: "mk-ch-box" }])).not.toThrow(); + expect(() => assertSafeElementDeletion(source, [{ selector: ".item", selectorIndex: 1 }])).toThrow(); + }); + + it.each(["c", "b"])("checks the backend's sequential batch targets when a script uses %s", (id) => { + const source = composition(`document.getElementById("${id}").style.color = "red";`, + '
A
B
C
'); + const targets = [{ selector: ".item", selectorIndex: 0 }, { selector: ".item", selectorIndex: 1 }]; + const after = new DOMParser().parseFromString(removeElementsFromHtml(source, targets), "text/html"); + expect(after.querySelectorAll(".item")).toHaveLength(1); + expect(after.getElementById("b")).not.toBeNull(); + expect(after.getElementById("c")).toBeNull(); + const check = () => assertSafeElementDeletion(source, targets); + if (id === "c") expect(check).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + else expect(check).not.toThrow(); + }); + + it("retains original ancestor context when matching script selectors against removed nodes", () => { + const source = composition('document.querySelector(".group > .item").style.color = "red";', + '
'); + expect(() => assertSafeElementDeletion(source, [{ id: "group" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("matches REST template ordering when resolving selector targets", () => { + const source = composition('document.getElementById("mk-ch-box").style.color = "red";', + '
'); + const after = new DOMParser().parseFromString(removeElementsFromHtml(source, [{ selector: ".group", selectorIndex: 0 }]), "text/html"); + expect(after.getElementById("outer-group")).toBeNull(); + expect(after.querySelector("template").content.querySelector("#tpl-group")).not.toBeNull(); + expect(() => assertSafeElementDeletion(source, [{ selector: ".group", selectorIndex: 0 }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + expect(() => assertSafeElementDeletion(source, [{ selector: ".group", selectorIndex: 1 }])).not.toThrow(); + }); + + it("resolves selector targets inside templates when no outer match exists", () => { + const source = composition('document.getElementById("tpl-box").style.color = "red";', + ''); + const targets = [{ selector: ".group", selectorIndex: 0 }]; + const after = new DOMParser().parseFromString(removeElementsFromHtml(source, targets), "text/html"); + expect(after.querySelector("template").content.querySelector("#tpl-box")).toBeNull(); + expect(() => assertSafeElementDeletion(source, targets)).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it.each([".item:nth-child(2)", ".item + .item"])("protects surviving nodes whose structural selector stops matching: %s", (selector) => { + const source = composition(`document.querySelector("${selector}").style.color = "red";`, + '
'); + const targets = [{ id: "first" }]; + const before = new DOMParser().parseFromString(source, "text/html"); + const after = new DOMParser().parseFromString(removeElementsFromHtml(source, targets), "text/html"); + expect(before.querySelector(selector)?.id).toBe("second"); + expect(after.getElementById("second")).not.toBeNull(); + expect(after.querySelector(selector)).toBeNull(); + expect(() => assertSafeElementDeletion(source, targets)).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it.each(["querySelector", "querySelectorAll"])("allows ordinary scoped %s lookups in a different container", (method) => { + const source = composition(`document.getElementById("keep").${method}(".word");`, + '
'); + expect(() => assertSafeElementDeletion(source, [{ id: "remove" }])).not.toThrow(); + expect(() => assertSafeElementDeletion(source, [{ id: "keep" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("protects indexed collection lookups when a structural match disappears", () => { + const source = composition('document.getElementById("group").querySelectorAll(".item:nth-child(2)")[0].style.color = "red";', + '
'); + expect(() => assertSafeElementDeletion(source, [{ id: "first" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("retains template dependencies when the outer document has the same selector", () => { + const source = '
'; + expect(() => assertSafeElementDeletion(source, [{ id: "box" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("allows lookups of the surviving document element", () => { + const source = composition('document.querySelector("html").style.color = "red";'); + expect(() => assertSafeElementDeletion(source, [{ id: "mk-ch-center" }])).not.toThrow(); + }); + + it("protects structural lookups inside composition templates", () => { + const source = ''; + expect(() => assertSafeElementDeletion(source, [{ id: "first" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("checks receiver-relative selectors against the lookup container", () => { + const source = composition('document.getElementById("container").querySelector(":scope > .word").style.color = "red";', + '
'); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-word" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("allows receiver-relative selectors that resolve outside the removed subtree", () => { + const source = composition('document.getElementById("container").querySelector(":scope > .word");', + '
'); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-center" }])).not.toThrow(); + }); + + it.each(["getElementsByClassName(\"word\")", "getElementsByTagName(\"span\")"])("protects template collection lookups: %s", (lookup) => { + const source = ``; + expect(() => assertSafeElementDeletion(source, [{ id: "box" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("refuses an invalid static selector conservatively", () => { + expect(() => assertSafeElementDeletion(composition('document.querySelector("[");'), [{ id: "mk-ch-center" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("refuses scoped selectors whose lookup receiver cannot be resolved", () => { + const source = composition('const root = document.getElementById("container"); root.querySelector(":scope > .word");', + '
'); + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-center" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it.each(["hf-box", "hf-host/hf-box"])("refuses ambiguous or scoped handles before SDK and server resolution can disagree: %s", (hfId) => { + const source = composition('document.getElementById("box").style.color = "red";', + '
'); + expect(() => assertSafeElementDeletion(source, [{ hfId }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("ignores data scripts and refuses unparseable executable scripts before deletion", () => { + expect(() => assertSafeElementDeletion('
', [{ id: "box" }])).not.toThrow(); + expect(() => assertSafeElementDeletion('
', [{ id: "box" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it.each(["application/x-javascript", "text/javascript1.5", "text/jscript", "text/x-ecmascript"])("checks executable legacy script types: %s", (type) => { + const source = `
`; + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-box" }])).toThrow(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + }); + + it("does not block ambiguous handles when the file contains only data scripts", () => { + const source = '
'; + expect(() => assertSafeElementDeletion(source, [{ hfId: "hf-box" }])).not.toThrow(); + }); +}); diff --git a/studio/src/utils/deleteScriptDependencies.ts b/studio/src/utils/deleteScriptDependencies.ts new file mode 100644 index 000000000..558c9b589 --- /dev/null +++ b/studio/src/utils/deleteScriptDependencies.ts @@ -0,0 +1,195 @@ +import { parse, type CallExpression, type Identifier, type Literal, type MemberExpression, type Node as AstNode, type TemplateLiteral } from "acorn"; +import { walkCompositionDescendants } from "@hyperframes/parsers/hf-ids"; +import type { PatchTarget } from "./sourcePatcher"; + +export const SCRIPT_DEPENDENCY_DELETE_MESSAGE = + "This element is used by a script. Ask your Agent to update the script, or delete the whole composition."; + +const LOOKUPS = new Set([ + "getElementById", "querySelector", "querySelectorAll", "getElementsByClassName", "getElementsByTagName", +]); + +function descendants(root: Document | Element): Element[] { + const elements: Element[] = []; + walkCompositionDescendants(root, (element) => elements.push(element)); + return elements; +} + +function childElements(parent: Element): Element[] { + const direct = Array.from(parent.children); + if (direct.length || parent.localName !== "template") return direct; + const content = (parent as HTMLTemplateElement).content; + return content ? Array.from(content.children) : direct; +} + +/** Every descendant including markup held in inert templates; REST traversal visits those too. */ +function allDescendants(root: Document | Element): Element[] { + const rootElement: Element | null = root.nodeType === 9 ? (root as Document).documentElement : (root as Element); + const elements: Element[] = []; + const walk = (parent: Element) => { + for (const child of childElements(parent)) { + elements.push(child); + walk(child); + } + }; + if (rootElement) walk(rootElement); + return elements; +} + +/** REST resolves selectors outside templates first, then inside the earliest template. */ +function selectorMatches(root: Document | Element, selector: string): Element[] { + const scope: ParentNode = root.nodeType === 1 && (root as Element).localName === "template" + ? (root as HTMLTemplateElement).content ?? root + : root; + let direct: Element[]; + try { + direct = Array.from(scope.querySelectorAll(selector)); + } catch { + return []; + } + if (direct.length > 0) return direct; + for (const template of Array.from(scope.querySelectorAll("template"))) { + const inner = selectorMatches(template, selector); + if (inner.length > 0) return inner; + } + return []; +} + +function findTarget(document: Document, target: PatchTarget): Element | undefined { + const elements = descendants(document); + const matches = target.hfId ? elements.filter((el) => el.getAttribute("data-hf-id") === target.hfId) : []; + // SDK scope resolution and REST document order can select different nodes. + if (target.hfId?.includes("/") || matches.length > 1) throw new Error(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + if (matches[0]) return matches[0]; + const id = target.id && elements.find((el) => el.id === target.id); + if (id) return id; + return target.selector ? selectorMatches(document, target.selector)[target.selectorIndex ?? 0] : undefined; +} + +function staticString(node: AstNode | undefined): string | null { + if (!node) return null; + if (node.type === "Literal") { + const value = (node as Literal).value; + return typeof value === "string" ? value : null; + } + if (node.type === "TemplateLiteral") { + const template = node as TemplateLiteral; + return template.expressions.length === 0 ? template.quasis[0]?.value.cooked ?? null : null; + } + return null; +} + +/** Resolve the nodes a script receives a lookup from, so scoped selectors keep their own reference point. */ +function lookupScopes(node: AstNode, document: Document): (Document | DocumentFragment | Element)[] | null { + // Each template's script runs with its instantiated composition as document. + if (node.type === "Identifier" && (node as Identifier).name === "document") { + return [document, ...allDescendants(document) + .filter((element) => element.localName === "template") + .map((element) => (element as HTMLTemplateElement).content)]; + } + if (node.type !== "CallExpression") return null; + const call = node as CallExpression; + const callee = call.callee; + if (callee.type !== "MemberExpression") return null; + const member = callee as MemberExpression; + const method = propertyName(member); + const value = staticString(call.arguments[0]); + if (!method || value === null) return null; + const parents = lookupScopes(member.object, document); + if (!parents) return null; + const scopes: (Document | DocumentFragment | Element)[] = []; + try { + for (const parent of parents) { + if (method === "querySelector" || method === "querySelectorAll") { + const matches = Array.from(parent.querySelectorAll(value)); + scopes.push(...(method === "querySelector" ? matches.slice(0, 1) : matches)); + } else if (method === "getElementsByClassName") { + scopes.push(...("getElementsByClassName" in parent + ? Array.from(parent.getElementsByClassName(value)) + : Array.from(parent.querySelectorAll("*")).filter((element) => value.trim().split(/\s+/).every((name) => element.classList.contains(name))))); + } else if (method === "getElementsByTagName") { + scopes.push(...("getElementsByTagName" in parent + ? Array.from(parent.getElementsByTagName(value)) + : Array.from(parent.querySelectorAll("*")).filter((element) => value === "*" || element.localName === value.toLowerCase()))); + } else if (method === "getElementById" && "getElementById" in parent) { + const found = Array.from(parent.querySelectorAll("[id]")).find((element) => element.id === value); + if (found) scopes.push(found); + } else { + return null; + } + } + } catch { + return null; + } + return scopes; +} + +function propertyName(member: MemberExpression): string | undefined { + if (!member.computed && member.property.type === "Identifier") return member.property.name; + if (member.property.type === "Literal" && typeof member.property.value === "string") return member.property.value; + if (member.property.type === "TemplateLiteral" && member.property.expressions.length === 0) return member.property.quasis[0]?.value.cooked ?? undefined; + return undefined; +} + +function lookupTouchesRemoval(member: MemberExpression, parent: AstNode | undefined, document: Document, pendingDocument: Document, originals: ReadonlyMap): boolean { + const method = propertyName(member); + if (!method || !LOOKUPS.has(method)) return false; + // Aliased or dynamic lookups cannot be resolved safely without executing authored code. + if (parent?.type !== "CallExpression" || (parent as CallExpression).callee !== member) return true; + const before = lookupScopes(parent, document); + const after = lookupScopes(parent, pendingDocument); + if (!before || !after) return true; + const survivingMatches = new Set(after.map((element) => originals.get(element))); + // Removing a sibling can invalidate a selector even when its original match survives. + return before.some((element) => !survivingMatches.has(element)); +} + +function hasDependency(node: AstNode, document: Document, pendingDocument: Document, originals: ReadonlyMap, parent?: AstNode): boolean { + if (node.type === "MemberExpression" && lookupTouchesRemoval(node as MemberExpression, parent, document, pendingDocument, originals)) return true; + for (const child of Object.values(node)) { + const children = Array.isArray(child) ? child : [child]; + for (const value of children) { + if (value && typeof value === "object" && typeof value.type === "string" && hasDependency(value, document, pendingDocument, originals, node)) return true; + } + } + return false; +} + +/** Refuse an unsafe subtree deletion before either mutation backend can write or record history. */ +export function assertSafeElementDeletion(source: string, targets: PatchTarget[]): void { + // shortcut: inspect direct inline DOM lookups; extend for external scripts or indirect DOM access when supported by the editor. + if (!/ { + if (el.localName !== "script" || el.hasAttribute("src")) return false; + const type = el.getAttribute("type")?.trim() ?? ""; + return !type || /^(?:module|(?:text|application)\/(?:x-)?(?:java|ecma)script|text\/(?:javascript1\.[0-5]|jscript|livescript))$/i.test(type); + }); + if (scripts.length === 0) return; + // REST resolves each target after prior removals; retain original nodes for script selector matching. + const pendingDocument = document.cloneNode(true) as Document; + const originalDescendants = allDescendants(document); + const originals = new Map(allDescendants(pendingDocument).map((element, index) => [element, originalDescendants[index]])); + originals.set(pendingDocument.documentElement, document.documentElement); + const removed = new Set(); + for (const target of targets) { + const pending = findTarget(pendingDocument, target); + const element = pending && originals.get(pending); + if (element) { + removed.add(element); + for (const child of allDescendants(element)) removed.add(child); + } + pending?.remove(); + } + if (removed.size === 0) return; + for (const script of scripts) { + if (removed.has(script)) continue; + try { + if (!hasDependency(parse(script.textContent ?? "", { ecmaVersion: "latest", sourceType: script.getAttribute("type")?.trim().toLowerCase() === "module" ? "module" : "script" }), document, pendingDocument, originals)) continue; + } catch { + // An unparseable executable script cannot be proven independent of the removed subtree. + } + throw new Error(SCRIPT_DEPENDENCY_DELETE_MESSAGE); + } +} diff --git a/studio/src/utils/sdkCutover.ts b/studio/src/utils/sdkCutover.ts index db0a454fd..3f6eaf93a 100644 --- a/studio/src/utils/sdkCutover.ts +++ b/studio/src/utils/sdkCutover.ts @@ -1,6 +1,7 @@ import type { Composition, GsapTweenSpec } from "@hyperframes/sdk"; import type { DomEditSelection } from "../components/editor/domEditing"; import type { PatchOperation } from "./sourcePatcher"; +import { assertSafeElementDeletion } from "./deleteScriptDependencies"; import * as studioAvailability from "../components/editor/manualEditingAvailability"; import { trackStudioEvent } from "./studioTelemetry"; import { patchOpsToSdkEditOps } from "./sdkOpMapping"; @@ -592,7 +593,10 @@ export async function sdkDeletePersist( targetPath, originalContent, deps, - (session) => session.removeElement(hfId), + (session) => { + assertSafeElementDeletion(session.serialize(), [{ hfId }]); + session.removeElement(hfId); + }, { label: "Delete element" }, ); trackCutoverResult(result, "lifecycle", { hfId, opCount: 1 }); diff --git a/studio/src/utils/sdkDeleteScriptDependencies.test.ts b/studio/src/utils/sdkDeleteScriptDependencies.test.ts new file mode 100644 index 000000000..3c6343dad --- /dev/null +++ b/studio/src/utils/sdkDeleteScriptDependencies.test.ts @@ -0,0 +1,106 @@ +// @vitest-environment happy-dom +import { expect, it, vi } from "vitest"; +import { openComposition } from "@hyperframes/sdk"; +import { sdkDeletePersist } from "./sdkCutover"; +import { SCRIPT_DEPENDENCY_DELETE_MESSAGE } from "./deleteScriptDependencies"; + +vi.mock("../components/editor/manualEditingAvailability", () => ({ + STUDIO_SDK_CUTOVER_ENABLED: true, + STUDIO_SDK_RESOLVER_SHADOW_ENABLED: false, +})); +vi.mock("./studioTelemetry", () => ({ trackStudioEvent: vi.fn() })); + +it.each([false, true])("checks script dependencies in the latest SDK candidate (source changed: %s)", async (changed) => { + const markup = '
'; + const source = markup.replace('', ''); + const original = changed ? markup : source; + const live = await openComposition(original, { history: false }); + const before = live.serialize(); + const deps = { + readProjectFile: vi.fn().mockResolvedValue(source), + writeProjectFile: vi.fn(), + editHistory: { recordEdit: vi.fn() }, + publishSession: vi.fn(), + reloadPreview: vi.fn(), + }; + try { + const result = await sdkDeletePersist("hf-box", original, "index.html", live, deps); + expect(result).toMatchObject({ status: "failed", error: new Error(SCRIPT_DEPENDENCY_DELETE_MESSAGE) }); + expect(deps.writeProjectFile).not.toHaveBeenCalled(); + expect(deps.editHistory.recordEdit).not.toHaveBeenCalled(); + expect(deps.publishSession).not.toHaveBeenCalled(); + expect(deps.reloadPreview).not.toHaveBeenCalled(); + expect(live.serialize()).toBe(before); + } finally { live.dispose(); } +}); + +it.each([ + ["hf-box", "box"], + ["hf-host/hf-box", "nested-box"], +])("preserves the SDK's actual target when its handle is ambiguous or scoped: %s", async (hfId, domId) => { + const source = `
+
+
+ `; + const live = await openComposition(source, { history: false }); + const before = live.serialize(); + const deps = { + readProjectFile: vi.fn().mockResolvedValue(source), + writeProjectFile: vi.fn(), + editHistory: { recordEdit: vi.fn() }, + publishSession: vi.fn(), + reloadPreview: vi.fn(), + }; + try { + expect(live.getElement(hfId)?.attributes.id).toBe(domId); + const result = await sdkDeletePersist(hfId, source, "index.html", live, deps); + expect(result).toMatchObject({ status: "failed", error: new Error(SCRIPT_DEPENDENCY_DELETE_MESSAGE) }); + expect(deps.writeProjectFile).not.toHaveBeenCalled(); + expect(deps.editHistory.recordEdit).not.toHaveBeenCalled(); + expect(deps.publishSession).not.toHaveBeenCalled(); + expect(deps.reloadPreview).not.toHaveBeenCalled(); + expect(live.serialize()).toBe(before); + } finally { live.dispose(); } +}); + +it.each([ + { selector: ".item:nth-child(2)", safe: false }, + { selector: ".item + .item", safe: false }, + { selector: ".word", safe: true }, +])("persists only safe receiver-aware deletes: $selector", async ({ selector, safe }) => { + const markup = safe + ? '
' + : '
'; + const receiver = safe ? 'document.getElementById("keep")' : "document"; + const source = `
${markup}
`; + const live = await openComposition(source, { history: false }); + const before = live.serialize(); + const deps = { + readProjectFile: vi.fn().mockResolvedValue(source), + writeProjectFile: vi.fn(), + editHistory: { recordEdit: vi.fn() }, + publishSession: vi.fn(), + reloadPreview: vi.fn(), + }; + try { + const result = await sdkDeletePersist("hf-first", source, "index.html", live, deps); + if (safe) { + expect(result.status).toBe("committed"); + expect(deps.writeProjectFile).toHaveBeenCalledOnce(); + expect(deps.editHistory.recordEdit).toHaveBeenCalledOnce(); + expect(deps.publishSession).toHaveBeenCalledOnce(); + if (result.status === "committed") { + const after = new DOMParser().parseFromString(result.after, "text/html"); + expect(after.getElementById("first")).toBeNull(); + expect(after.querySelector("#keep .word")).not.toBeNull(); + } + } else { + expect(result).toMatchObject({ status: "failed", error: new Error(SCRIPT_DEPENDENCY_DELETE_MESSAGE) }); + expect(deps.writeProjectFile).not.toHaveBeenCalled(); + expect(deps.editHistory.recordEdit).not.toHaveBeenCalled(); + expect(deps.publishSession).not.toHaveBeenCalled(); + expect(deps.reloadPreview).not.toHaveBeenCalled(); + expect(live.serialize()).toBe(before); + } + } finally { live.dispose(); } +});