Skip to content

The open-source full-stack studio for Opus 5.5 motion video. Reverse engineering for any video. Code video with HTML: recreate, edit and render. BYOA + BYOK · Motion.md · Images, Video, Music & Voice.

fix(studio): explain why canvas source targets cannot be edited

罗高60fce4e7df3e
diff --git a/docs/product/architecture.md b/docs/product/architecture.md
index c4bbff59..f0f8c868 100644
--- a/docs/product/architecture.md
+++ b/docs/product/architecture.md
@@ -264,6 +264,8 @@ The collector uses an explicit file/field allowlist, bounded log tails and job s
## 成功标准与验证
+Canvas selection checks distinguish missing source files, denied access, failed reads/connections, unmatched source targets and unsupported element namespaces. A negative native probe reads the named source once per batch to explain the refusal; an absent target alone never establishes script generation. Unverified targets stay blocked, temporary failures retry on selection, and existing source-write, conflict and undo paths remain authoritative. Static SVG visual editing is still unsupported.
+
当前交付标准:连接可验证、模板可定位、工程可继续编辑、预览与源文件一致、导出存在真实文件、检查结果有证据。相关实现由 `tests/`、`npm run test:studio` 的原生单元/DOM 与宿主回归、类型检查、设计检查和按需浏览器验证覆盖;没有执行的检查不能记为通过。
The runtime includes an explicit-event tracking package shared by MCP and Studio. Stable releases collect by default; test/prerelease/local application versions are locked off regardless of the saved preference or launch overrides. The test-build Privacy switch explains the lock without overwriting the saved stable-release choice. Shared-backend discovery rejects test/stable cross-policy reuse rather than allowing a reporting authority to execute test actions. In stable releases, a persistent user preference can stop collection for the whole installation and resume new reports when enabled again; discarded events are not replayed. Environment force-off controls still take priority. Studio submits allowlisted events to the local service; Node adds a random installation identity before asynchronous ingestion into the existing OpenDesign PostHog project. OM events carry product=openmotion; queries must distinguish products. An OM-only transformation preserves coarse country/region/timezone and removes raw IP and precise location after the existing GeoIP transformation, without changing other OpenDesign events or global project settings. The implementation covers tool results, selected domain operations and selected Studio interactions; it does not establish a product analytics baseline or implement every proposed event. See [tracking configuration, privacy and coverage](../../tracking/README.md).
diff --git a/studio/src/components/editor/domEditingLayers.test.ts b/studio/src/components/editor/domEditingLayers.test.ts
index 57fe2df1..9a499009 100644
--- a/studio/src/components/editor/domEditingLayers.test.ts
+++ b/studio/src/components/editor/domEditingLayers.test.ts
@@ -105,8 +105,8 @@ describe("resolveDomEditSelection — source probe on re-resolve", () => {
const probing = { activeCompositionPath: "index.html", isMasterView: true, projectId: "p" };
it("asks the server once per node and target; re-resolving the same pair keeps the answer", async () => {
- const fetchMock = vi.fn(() =>
- Promise.resolve({ ok: true, json: () => Promise.resolve({ exists: [false] }) }),
+ const fetchMock = vi.fn((_url: unknown, init?: RequestInit) =>
+ Promise.resolve({ ok: true, json: () => Promise.resolve(init?.method === "POST" ? { exists: [false] } : { content: '<div id="other"></div>' }) }),
);
vi.stubGlobal("fetch", fetchMock);
const el = document.createElement("div");
@@ -127,7 +127,23 @@ describe("resolveDomEditSelection — source probe on re-resolve", () => {
expect(first?.existsInSource).toBe(false);
expect(again?.existsInSource).toBe(false);
expect(again?.capabilities.canMove).toBe(false);
- expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(first?.capabilities.reasonIfDisabled).toContain("not found in the current source");
+ expect(fetchMock).toHaveBeenCalledTimes(6);
+ });
+
+ it("retries temporary failures for the same target and restores normal editing capabilities", async () => {
+ vi.stubGlobal("fetch", vi.fn().mockRejectedValueOnce(new TypeError("offline"))
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ exists: [true] }) }));
+ const el = document.createElement("div");
+ el.id = "retryable";
+ document.body.appendChild(el);
+ const first = await resolveDomEditSelection(el, probing);
+ expect(first?.capabilities.canEditStyles).toBe(false);
+ expect(first?.capabilities.reasonIfDisabled).toContain("Cannot connect");
+ const again = await resolveDomEditSelection(el, { ...probing, previous: first });
+ expect(again?.capabilities.canEditStyles).toBe(true);
+ expect(again?.sourceProbeFailure).toBeUndefined();
+ el.remove();
});
});
diff --git a/studio/src/components/editor/domEditingLayers.ts b/studio/src/components/editor/domEditingLayers.ts
index b1173b1b..063c15d0 100644
--- a/studio/src/components/editor/domEditingLayers.ts
+++ b/studio/src/components/editor/domEditingLayers.ts
@@ -1,5 +1,5 @@
import { isClipHiddenByRuntime, PREVIEW_ONLY_ATTRS } from "@hyperframes/core/studio-preview-mark";
-import { knownSourceAnswer, probeSourceElement, type ProbeTarget } from "./probeSourceElement";
+import { knownSourceAnswer, probeSourceElement, sourceProbeMessages, type ProbeTarget } from "./probeSourceElement";
import { isAudibleVideoNode } from "../../player/lib/timelineElementHelpers";
import type { PatchOperation } from "../../utils/sourcePatcher";
import {
@@ -347,11 +347,12 @@ export async function resolveDomEditSelection(
if (hfId) probeTarget.hfId = hfId;
if (selector) probeTarget.selector = selector;
if (selectorIndex != null) probeTarget.selectorIndex = selectorIndex;
- let existsInSource = knownSourceAnswer(options.previous, current, sourceFile, probeTarget);
- const probe = existsInSource === undefined && !options.skipSourceProbe;
+ let sourceProbe = knownSourceAnswer(options.previous, current, sourceFile, probeTarget);
+ const probe = sourceProbe === undefined && !options.skipSourceProbe;
if (probe && options.projectId && (current.id || selector || hfId)) {
- existsInSource = await probeSourceElement(options.projectId, sourceFile, probeTarget);
+ sourceProbe = await probeSourceElement(options.projectId, sourceFile, probeTarget);
}
+ const existsInSource = sourceProbe?.exists;
const capabilities = resolveEditingAffordances(
capabilityFacts({
hasStableTarget: Boolean(selector || hfId),
@@ -365,6 +366,9 @@ export async function resolveDomEditSelection(
existsInSource: existsInSource ?? true,
}),
).capabilities;
+ if (sourceProbe?.failure && !isInsideLocked) {
+ capabilities.reasonIfDisabled = sourceProbeMessages[sourceProbe.failure];
+ }
const rect = current.getBoundingClientRect();
return {
@@ -393,6 +397,7 @@ export async function resolveDomEditSelection(
textFields,
capabilities,
existsInSource,
+ sourceProbeFailure: sourceProbe?.failure,
};
}
diff --git a/studio/src/components/editor/domEditingTypes.ts b/studio/src/components/editor/domEditingTypes.ts
index 434af6cc..662481b5 100644
--- a/studio/src/components/editor/domEditingTypes.ts
+++ b/studio/src/components/editor/domEditingTypes.ts
@@ -95,6 +95,7 @@ export interface DomEditSelection extends PatchTarget {
textFields: DomEditTextField[];
capabilities: DomEditCapabilities;
existsInSource?: boolean;
+ sourceProbeFailure?: import("./probeSourceElement").SourceProbeFailure;
gsapAnimations?: GsapAnimation[];
}
diff --git a/studio/src/components/editor/probeSourceElement.test.ts b/studio/src/components/editor/probeSourceElement.test.ts
index ccdcfb43..6857e98b 100644
--- a/studio/src/components/editor/probeSourceElement.test.ts
+++ b/studio/src/components/editor/probeSourceElement.test.ts
@@ -1,45 +1,66 @@
+// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from "vitest";
-import { probeSourceElement } from "./probeSourceElement";
+import { probeSourceElement, sourceProbeMessages } from "./probeSourceElement";
+import { languages, translate } from "../../i18n/messages";
+import { toastErrorMessage } from "../ui/toastErrorMessage";
afterEach(() => vi.unstubAllGlobals());
-
-const answer = (body: unknown, ok = true) =>
- vi.fn(() => Promise.resolve({ ok, json: () => Promise.resolve(body) }));
+const answer = (body: unknown, status = 200) => ({ ok: status === 200, status, json: async () => body });
describe("probeSourceElement", () => {
- it("sends the asks for one file in one tick as a single request", async () => {
- const fetchMock = answer({ exists: [true, false, true] });
+ it("batches probes and reads a rejected file only once to diagnose its missing targets", async () => {
+ const fetchMock = vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "POST"
+ ? answer({ exists: [true, false, false] })
+ : answer({ content: '<div id="a"></div><svg id="b"></svg><script>const html = `<div id="c"></div>`;</script>' }));
vi.stubGlobal("fetch", fetchMock);
-
- const results = await Promise.all([
- probeSourceElement("p", "index.html", { id: "a" }),
- probeSourceElement("p", "index.html", { id: "b" }),
- probeSourceElement("p", "index.html", { id: "c" }),
+ expect(await Promise.all(["a", "b", "c"].map(id => probeSourceElement("p", "index.html", { id })))).toEqual([
+ { exists: true }, { exists: false, failure: "unsupported-element" }, { exists: false, failure: "element-not-found" },
]);
-
- expect(results).toEqual([true, false, true]);
- expect(fetchMock).toHaveBeenCalledOnce();
- const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
- expect(JSON.parse(String(init.body)).targets).toEqual([{ id: "a" }, { id: "b" }, { id: "c" }]);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body)).targets).toEqual([{ id: "a" }, { id: "b" }, { id: "c" }]);
});
- it("keeps one request per file", async () => {
- const fetchMock = answer({ exists: [true] });
+ it("keeps successful requests per file and never reads their source", async () => {
+ const fetchMock = vi.fn(async (_url: unknown, _init?: RequestInit) => answer({ exists: [true] }));
vi.stubGlobal("fetch", fetchMock);
await Promise.all([
probeSourceElement("p", "index.html", { id: "a" }),
probeSourceElement("p", "compositions/x.html", { id: "a" }),
]);
expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls.every(call => call[1]?.method === "POST")).toBe(true);
+ });
+
+ it.each([404, 403, 503])("reports source read status %s without attributing it to generated content", async status => {
+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "POST"
+ ? answer({ exists: [false] }) : answer({}, status)));
+ expect(await probeSourceElement("p", "index.html", { id: "a" })).toEqual({
+ exists: false, failure: status === 404 ? "source-missing" : status === 403 ? "source-denied" : "source-unreadable",
+ });
+ });
+
+ it("identifies a source/preview mismatch when an HTML target exists but native probing refused it", async () => {
+ vi.stubGlobal("fetch", vi.fn(async (_url: unknown, init?: RequestInit) => init?.method === "POST"
+ ? answer({ exists: [false] }) : answer({ content: '<div id="a" data-hf-id="new-id"></div>' })));
+ expect(await probeSourceElement("p", "index.html", { id: "a", hfId: "stale-id" })).toEqual({ exists: false, failure: "source-mismatch" });
+ });
+
+ it("blocks an unverified target on network and malformed responses, then recovers on retry", async () => {
+ const fetchMock = vi.fn().mockRejectedValueOnce(new TypeError("offline"))
+ .mockResolvedValueOnce(answer({ exists: [] })).mockResolvedValueOnce(answer({ exists: [true] }));
+ vi.stubGlobal("fetch", fetchMock);
+ expect(await probeSourceElement("p", "index.html", { id: "a" })).toEqual({ exists: false, failure: "connection-failed" });
+ expect(await probeSourceElement("p", "index.html", { id: "a" })).toEqual({ exists: false, failure: "check-failed" });
+ expect(await probeSourceElement("p", "index.html", { id: "a" })).toEqual({ exists: true });
});
- it("reads a failed or malformed answer as existing", async () => {
- vi.stubGlobal("fetch", answer({}, false));
- expect(await probeSourceElement("p", "index.html", { id: "a" })).toBe(true);
- vi.stubGlobal(
- "fetch",
- vi.fn(() => Promise.reject(new Error("offline"))),
- );
- expect(await probeSourceElement("p", "index.html", { id: "a" })).toBe(true);
+ it("gives every reason a localized next step without claiming script generation", () => {
+ for (const message of Object.values(sourceProbeMessages)) {
+ expect(message).not.toContain("generated by a script");
+ expect(toastErrorMessage(message)).toBe(message);
+ for (const { locale } of languages) {
+ if (locale !== "en") expect(translate(locale, message), locale).not.toBe(message);
+ }
+ }
});
});
diff --git a/studio/src/components/editor/probeSourceElement.ts b/studio/src/components/editor/probeSourceElement.ts
index a1e6c551..871a2fe4 100644
--- a/studio/src/components/editor/probeSourceElement.ts
+++ b/studio/src/components/editor/probeSourceElement.ts
@@ -3,31 +3,84 @@ import { studioApiFetch } from "../../utils/studioApiFetch";
import type { DomEditSelection } from "./domEditingTypes";
export type ProbeTarget = { id?: string; hfId?: string; selector?: string; selectorIndex?: number };
+export type SourceProbeFailure = "element-not-found" | "source-mismatch" | "unsupported-element" | "source-missing" | "source-denied" | "source-unreadable" | "connection-failed" | "check-failed";
+export type SourceProbeResult = { exists: boolean; failure?: SourceProbeFailure };
+
+export const sourceProbeMessages: Record<SourceProbeFailure, string> = {
+ "element-not-found": "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.",
+ "source-mismatch": "The preview element does not match the current source. Refresh the preview and select it again.",
+ "unsupported-element": "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.",
+ "source-missing": "The source file could not be found. Refresh the preview or ask an agent to restore the source file.",
+ "source-denied": "Access to the source file was denied. Check file permissions and select the element again.",
+ "source-unreadable": "The source file could not be read. Try again or ask an agent to check the source file.",
+ "connection-failed": "Cannot connect to the editor to check this element. Check the connection and select it again.",
+ "check-failed": "Could not check whether this element can be edited. Select it again or refresh the preview.",
+};
export function knownSourceAnswer(
previous: DomEditSelection | null | undefined,
element: HTMLElement,
sourceFile: string,
target: ProbeTarget,
-): boolean | undefined {
+): SourceProbeResult | undefined {
if (!previous || previous.element !== element || previous.sourceFile !== sourceFile) return;
const same =
previous.id === target.id &&
previous.hfId === target.hfId &&
previous.selector === target.selector &&
previous.selectorIndex === target.selectorIndex;
- return same ? previous.existsInSource : undefined;
+ // Failed reads must be retried; a DOM/target change invalidates definitive answers.
+ if (!same || previous.existsInSource === undefined) return;
+ if (previous.sourceProbeFailure && !["element-not-found", "source-mismatch", "unsupported-element"].includes(previous.sourceProbeFailure)) return;
+ return { exists: previous.existsInSource, failure: previous.sourceProbeFailure };
}
interface PendingProbe {
target: ProbeTarget;
- resolve: (exists: boolean) => void;
+ resolve: (result: SourceProbeResult) => void;
}
const pending = new Map<string, PendingProbe[]>();
+function responseFailure(status: number): SourceProbeFailure {
+ if (status === 404) return "source-missing";
+ if (status === 401 || status === 403) return "source-denied";
+ return "source-unreadable";
+}
+
+function requestFailure(error: unknown): SourceProbeFailure {
+ return error instanceof TypeError || (error as { name?: string })?.name === "TimeoutError" ? "connection-failed" : "check-failed";
+}
+
+function findSourceElement(doc: Document, target: ProbeTarget): Element | null {
+ const attrValue = (value: string) => value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
+ const byHfId = target.hfId && doc.querySelector(`[data-hf-id="${attrValue(target.hfId)}"]`);
+ const byId = target.id && doc.getElementById(target.id);
+ if (byHfId || byId) return byHfId || byId || null;
+ return target.selector ? doc.querySelectorAll(target.selector)[target.selectorIndex ?? 0] ?? null : null;
+}
+
+async function diagnoseMissingTargets(projectId: string, sourceFile: string, targets: ProbeTarget[]): Promise<SourceProbeFailure[]> {
+ try {
+ const response = await studioApiFetch(buildProjectApiPath(projectId, `/files/${encodeURIComponent(sourceFile)}`), { signal: AbortSignal.timeout(10_000) });
+ if (!response.ok) return targets.map(() => responseFailure(response.status));
+ const data = await response.json();
+ if (typeof data?.content !== "string") return targets.map(() => "check-failed");
+ const doc = new DOMParser().parseFromString(data.content, "text/html");
+ return targets.map(target => {
+ try {
+ const element = findSourceElement(doc, target);
+ if (!element) return "element-not-found";
+ return element.namespaceURI !== "http://www.w3.org/1999/xhtml" ? "unsupported-element" : "source-mismatch";
+ } catch { return "check-failed"; }
+ });
+ } catch (error) {
+ return targets.map(() => requestFailure(error));
+ }
+}
+
async function sendBatch(projectId: string, sourceFile: string, probes: PendingProbe[]) {
- let exists: boolean[] = [];
+ let results: SourceProbeResult[];
try {
const response = await studioApiFetch(
buildProjectApiPath(
@@ -38,21 +91,33 @@ async function sendBatch(projectId: string, sourceFile: string, probes: PendingP
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ targets: probes.map((probe) => probe.target) }),
+ signal: AbortSignal.timeout(10_000),
},
);
- if (response.ok) {
+ if (!response.ok) {
+ results = probes.map(() => ({ exists: false, failure: response.status === 401 || response.status === 403 ? "source-denied" : "check-failed" }));
+ } else {
const data = await response.json();
- if (Array.isArray(data?.exists)) exists = data.exists;
+ if (!Array.isArray(data?.exists) || data.exists.length !== probes.length || data.exists.some((value: unknown) => typeof value !== "boolean")) {
+ results = probes.map(() => ({ exists: false, failure: "check-failed" }));
+ } else {
+ const missing = probes.filter((_, index) => !data.exists[index]);
+ const failures = missing.length ? await diagnoseMissingTargets(projectId, sourceFile, missing.map(probe => probe.target)) : [];
+ let missingIndex = 0;
+ results = data.exists.map((exists: boolean) => exists ? { exists } : { exists, failure: failures[missingIndex++] });
+ }
}
- } catch {}
- probes.forEach((probe, index) => probe.resolve(exists[index] !== false));
+ } catch (error) {
+ results = probes.map(() => ({ exists: false, failure: requestFailure(error) }));
+ }
+ probes.forEach((probe, index) => probe.resolve(results[index]!));
}
export function probeSourceElement(
projectId: string,
sourceFile: string,
target: ProbeTarget,
-): Promise<boolean> {
+): Promise<SourceProbeResult> {
return new Promise((resolve) => {
const key = `${projectId}\0${sourceFile}`;
let probes = pending.get(key);
diff --git a/studio/src/i18n/error-ui.json b/studio/src/i18n/error-ui.json
index 6a8447d8..c2b81eb7 100644
--- a/studio/src/i18n/error-ui.json
+++ b/studio/src/i18n/error-ui.json
@@ -37,7 +37,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "日志会脱敏后保存到本机,不会上传。分享前请检查 ZIP 内容。",
"Please wait 30 seconds before exporting diagnostics again.": "请等待 30 秒后再次导出诊断信息。",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "无法导出诊断信息。工作室无法连接时可使用命令行。",
- "Download started. Check your browser downloads.": "已发起下载,请查看浏览器下载列表。"
+ "Download started. Check your browser downloads.": "已发起下载,请查看浏览器下载列表。",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "在当前源码中找不到此元素。请刷新预览;仍无法编辑时,可让 Agent 修改源码。",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "预览元素与当前源码不匹配。请刷新预览后重新选择。",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "暂不支持直接编辑此类元素。请选择外层容器,或让 Agent 修改源码。",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "找不到源文件。请刷新预览,或让 Agent 恢复源文件。",
+ "Access to the source file was denied. Check file permissions and select the element again.": "没有源文件访问权限。请检查文件权限后重新选择元素。",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "无法读取源文件。请重试,或让 Agent 检查源文件。",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "无法连接编辑器以检查此元素。请检查连接后重新选择。",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "暂时无法确认此元素能否编辑。请重新选择,或刷新预览。"
},
"ja": {
"Reconnecting…": "再接続中…",
@@ -77,7 +85,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "機密情報を伏せたログを端末に保存します。アップロードは行いません。共有前に ZIP の内容をご確認ください。",
"Please wait 30 seconds before exporting diagnostics again.": "診断情報を再度書き出すには 30 秒お待ちください。",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "診断情報を書き出せませんでした。Studio に接続できない場合はコマンドラインをご利用ください。",
- "Download started. Check your browser downloads.": "ダウンロードを開始しました。ブラウザーのダウンロード一覧をご確認ください。"
+ "Download started. Check your browser downloads.": "ダウンロードを開始しました。ブラウザーのダウンロード一覧をご確認ください。",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "現在のソースにこの要素が見つかりません。プレビューを更新し、解決しない場合はエージェントにソースの編集を依頼してください。",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "プレビューの要素と現在のソースが一致しません。プレビューを更新して選択し直してください。",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "この種類の要素はまだ直接編集できません。外側のコンテナを選択するか、エージェントにソースの編集を依頼してください。",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "ソースファイルが見つかりません。プレビューを更新するか、エージェントに復元を依頼してください。",
+ "Access to the source file was denied. Check file permissions and select the element again.": "ソースファイルへのアクセスが拒否されました。権限を確認して要素を選択し直してください。",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "ソースファイルを読み込めません。再試行するか、エージェントに確認を依頼してください。",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "要素を確認するためにエディターに接続できません。接続を確認して選択し直してください。",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "この要素を編集できるか確認できませんでした。選択し直すか、プレビューを更新してください。"
},
"ko": {
"Reconnecting…": "다시 연결 중…",
@@ -117,7 +133,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "민감한 값을 가린 로그를 기기에 저장합니다. 업로드하지 않습니다. 공유 전에 ZIP 내용을 확인하세요.",
"Please wait 30 seconds before exporting diagnostics again.": "진단 정보를 다시 내보내려면 30초 기다려 주세요.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "진단 정보를 내보낼 수 없습니다. Studio에 연결할 수 없으면 명령줄을 사용하세요.",
- "Download started. Check your browser downloads.": "다운로드를 시작했습니다. 브라우저의 다운로드 목록을 확인하세요."
+ "Download started. Check your browser downloads.": "다운로드를 시작했습니다. 브라우저의 다운로드 목록을 확인하세요.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "현재 소스에서 이 요소를 찾을 수 없습니다. 미리보기를 새로고침하고, 문제가 지속되면 에이전트에게 소스 수정을 요청하세요.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "미리보기 요소가 현재 소스와 일치하지 않습니다. 미리보기를 새로고침한 후 다시 선택하세요.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "이 유형의 요소는 아직 직접 편집할 수 없습니다. 바깥 컨테이너를 선택하거나 에이전트에게 소스 수정을 요청하세요.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "소스 파일을 찾을 수 없습니다. 미리보기를 새로고침하거나 에이전트에게 파일 복원을 요청하세요.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "소스 파일에 대한 접근이 거부되었습니다. 파일 권한을 확인한 후 요소를 다시 선택하세요.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "소스 파일을 읽을 수 없습니다. 다시 시도하거나 에이전트에게 파일 확인을 요청하세요.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "요소를 확인하기 위해 편집기에 연결할 수 없습니다. 연결을 확인한 후 다시 선택하세요.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "이 요소의 편집 가능 여부를 확인할 수 없습니다. 다시 선택하거나 미리보기를 새로고침하세요."
},
"de": {
"Reconnecting…": "Verbindung wird hergestellt…",
@@ -157,7 +181,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Speichert Protokolle mit unkenntlich gemachten vertraulichen Werten auf Ihrem Gerät. Kein Upload. Prüfen Sie die ZIP vor dem Teilen.",
"Please wait 30 seconds before exporting diagnostics again.": "Bitte warten Sie 30 Sekunden, bevor Sie erneut Diagnosedaten exportieren.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Diagnosedaten konnten nicht exportiert werden. Nutzen Sie die Befehlszeile, wenn Studio keine Verbindung herstellen kann.",
- "Download started. Check your browser downloads.": "Download gestartet. Prüfe die Downloadliste deines Browsers."
+ "Download started. Check your browser downloads.": "Download gestartet. Prüfe die Downloadliste deines Browsers.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Dieses Element wurde im aktuellen Quelltext nicht gefunden. Aktualisiere die Vorschau. Falls das Problem bleibt, bitte einen Agenten, den Quelltext zu bearbeiten.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "Das Vorschauelement stimmt nicht mit dem aktuellen Quelltext überein. Aktualisiere die Vorschau und wähle es erneut aus.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Dieser Elementtyp kann noch nicht visuell bearbeitet werden. Wähle den äußeren Container oder bitte einen Agenten, den Quelltext zu bearbeiten.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "Die Quelldatei wurde nicht gefunden. Aktualisiere die Vorschau oder bitte einen Agenten, die Datei wiederherzustellen.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "Der Zugriff auf die Quelldatei wurde verweigert. Prüfe die Dateiberechtigungen und wähle das Element erneut aus.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Die Quelldatei konnte nicht gelesen werden. Versuche es erneut oder bitte einen Agenten, die Datei zu prüfen.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Keine Verbindung zum Editor, um dieses Element zu prüfen. Prüfe die Verbindung und wähle es erneut aus.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Es konnte nicht geprüft werden, ob dieses Element bearbeitbar ist. Wähle es erneut aus oder aktualisiere die Vorschau."
},
"fr": {
"Reconnecting…": "Reconnexion…",
@@ -197,7 +229,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Enregistre les journaux sur votre appareil en masquant les valeurs sensibles. Aucun envoi. Vérifiez le ZIP avant de le partager.",
"Please wait 30 seconds before exporting diagnostics again.": "Veuillez patienter 30 secondes avant de réexporter le diagnostic.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Impossible d’exporter le diagnostic. Utilisez la ligne de commande si Studio ne peut pas se connecter.",
- "Download started. Check your browser downloads.": "Téléchargement lancé. Consultez les téléchargements de votre navigateur."
+ "Download started. Check your browser downloads.": "Téléchargement lancé. Consultez les téléchargements de votre navigateur.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Cet élément est introuvable dans le code source actuel. Actualisez l’aperçu puis, si le problème persiste, demandez à un agent de modifier le code source.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "L’élément de l’aperçu ne correspond pas au code source actuel. Actualisez l’aperçu et sélectionnez-le à nouveau.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Ce type d’élément ne peut pas encore être modifié visuellement. Sélectionnez son conteneur parent ou demandez à un agent de modifier le code source.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "Le fichier source est introuvable. Actualisez l’aperçu ou demandez à un agent de restaurer le fichier.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "L’accès au fichier source a été refusé. Vérifiez les autorisations et sélectionnez à nouveau l’élément.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Impossible de lire le fichier source. Réessayez ou demandez à un agent de vérifier le fichier.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Impossible de se connecter à l’éditeur pour vérifier cet élément. Vérifiez la connexion et sélectionnez-le à nouveau.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Impossible de vérifier si cet élément est modifiable. Sélectionnez-le à nouveau ou actualisez l’aperçu."
},
"es": {
"Reconnecting…": "Reconectando…",
@@ -237,7 +277,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Guarda los registros en tu dispositivo con los valores sensibles ocultos. No se suben. Revisa el ZIP antes de compartirlo.",
"Please wait 30 seconds before exporting diagnostics again.": "Espera 30 segundos antes de volver a exportar el diagnóstico.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "No se pudo exportar el diagnóstico. Usa la línea de comandos si Studio no puede conectarse.",
- "Download started. Check your browser downloads.": "Descarga iniciada. Revisa las descargas de tu navegador."
+ "Download started. Check your browser downloads.": "Descarga iniciada. Revisa las descargas de tu navegador.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "No se encontró este elemento en el código fuente actual. Actualiza la vista previa y, si el problema persiste, pide a un agente que edite el código fuente.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "El elemento de la vista previa no coincide con el código fuente actual. Actualiza la vista previa y vuelve a seleccionarlo.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Este tipo de elemento aún no se puede editar visualmente. Selecciona su contenedor exterior o pide a un agente que edite el código fuente.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "No se encontró el archivo fuente. Actualiza la vista previa o pide a un agente que restaure el archivo.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "Se denegó el acceso al archivo fuente. Revisa sus permisos y vuelve a seleccionar el elemento.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "No se pudo leer el archivo fuente. Inténtalo de nuevo o pide a un agente que revise el archivo.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "No se puede conectar con el editor para comprobar este elemento. Revisa la conexión y vuelve a seleccionarlo.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "No se pudo comprobar si este elemento se puede editar. Vuelve a seleccionarlo o actualiza la vista previa."
},
"pt-BR": {
"Reconnecting…": "Reconectando…",
@@ -277,7 +325,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Salva os registros no seu dispositivo com valores sensíveis ocultos. Sem envio. Revise o ZIP antes de compartilhar.",
"Please wait 30 seconds before exporting diagnostics again.": "Aguarde 30 segundos antes de exportar o diagnóstico novamente.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Não foi possível exportar o diagnóstico. Use a linha de comando se o Studio não conseguir se conectar.",
- "Download started. Check your browser downloads.": "Download iniciado. Confira os downloads do navegador."
+ "Download started. Check your browser downloads.": "Download iniciado. Confira os downloads do navegador.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Este elemento não foi encontrado no código-fonte atual. Atualize a prévia e, se o problema persistir, peça a um agente para editar o código-fonte.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "O elemento da prévia não corresponde ao código-fonte atual. Atualize a prévia e selecione-o novamente.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Este tipo de elemento ainda não pode ser editado visualmente. Selecione o contêiner externo ou peça a um agente para editar o código-fonte.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "O arquivo-fonte não foi encontrado. Atualize a prévia ou peça a um agente para restaurar o arquivo.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "O acesso ao arquivo-fonte foi negado. Verifique suas permissões e selecione o elemento novamente.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Não foi possível ler o arquivo-fonte. Tente novamente ou peça a um agente para verificar o arquivo.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Não foi possível conectar ao editor para verificar este elemento. Verifique a conexão e selecione-o novamente.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Não foi possível verificar se este elemento pode ser editado. Selecione-o novamente ou atualize a prévia."
},
"it": {
"Reconnecting…": "Riconnessione…",
@@ -317,7 +373,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Salva i log sul dispositivo oscurando i valori sensibili. Nessun caricamento. Controlla lo ZIP prima di condividerlo.",
"Please wait 30 seconds before exporting diagnostics again.": "Attendi 30 secondi prima di esportare nuovamente la diagnostica.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Impossibile esportare la diagnostica. Usa la riga di comando se Studio non riesce a connettersi.",
- "Download started. Check your browser downloads.": "Download avviato. Controlla i download del browser."
+ "Download started. Check your browser downloads.": "Download avviato. Controlla i download del browser.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Questo elemento non è stato trovato nel codice sorgente attuale. Aggiorna l’anteprima e, se il problema persiste, chiedi a un agente di modificare il codice sorgente.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "L’elemento dell’anteprima non corrisponde al codice sorgente attuale. Aggiorna l’anteprima e selezionalo di nuovo.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Questo tipo di elemento non è ancora modificabile visivamente. Seleziona il contenitore esterno o chiedi a un agente di modificare il codice sorgente.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "Il file sorgente non è stato trovato. Aggiorna l’anteprima o chiedi a un agente di ripristinare il file.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "L’accesso al file sorgente è stato negato. Controlla i permessi e seleziona di nuovo l’elemento.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Impossibile leggere il file sorgente. Riprova o chiedi a un agente di controllare il file.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Impossibile connettersi all’editor per verificare questo elemento. Controlla la connessione e selezionalo di nuovo.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Impossibile verificare se questo elemento è modificabile. Selezionalo di nuovo o aggiorna l’anteprima."
},
"ru": {
"Reconnecting…": "Переподключение…",
@@ -357,7 +421,15 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Журналы сохраняются на устройстве с маскировкой конфиденциальных данных. Отправки нет. Проверьте ZIP перед передачей.",
"Please wait 30 seconds before exporting diagnostics again.": "Подождите 30 секунд перед повторным экспортом диагностики.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Не удалось экспортировать диагностику. Если Studio не подключается, используйте командную строку.",
- "Download started. Check your browser downloads.": "Загрузка началась. Проверьте список загрузок браузера."
+ "Download started. Check your browser downloads.": "Загрузка началась. Проверьте список загрузок браузера.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Элемент не найден в текущем исходном коде. Обновите предпросмотр. Если проблема сохранится, попросите агента изменить исходный код.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "Элемент предпросмотра не соответствует текущему исходному коду. Обновите предпросмотр и выберите элемент снова.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Этот тип элемента пока нельзя редактировать визуально. Выберите внешний контейнер или попросите агента изменить исходный код.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "Исходный файл не найден. Обновите предпросмотр или попросите агента восстановить файл.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "Доступ к исходному файлу запрещён. Проверьте права доступа и выберите элемент снова.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Не удалось прочитать исходный файл. Повторите попытку или попросите агента проверить файл.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Не удалось подключиться к редактору для проверки элемента. Проверьте соединение и выберите элемент снова.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Не удалось проверить, можно ли редактировать элемент. Выберите его снова или обновите предпросмотр."
},
"tr": {
"Reconnecting…": "Yeniden bağlanılıyor…",
@@ -397,6 +469,14 @@
"Saves logs on your device with sensitive values redacted. No upload. Review the ZIP before sharing.": "Günlükleri hassas değerler gizlenmiş olarak cihazınıza kaydeder. Yükleme yapılmaz. Paylaşmadan önce ZIP içeriğini inceleyin.",
"Please wait 30 seconds before exporting diagnostics again.": "Tanılamayı yeniden dışa aktarmadan önce 30 saniye bekleyin.",
"Could not export diagnostics. Use the command line if Studio cannot connect.": "Tanılama dışa aktarılamadı. Studio bağlanamıyorsa komut satırını kullanın.",
- "Download started. Check your browser downloads.": "İndirme başlatıldı. Tarayıcınızın indirme listesini kontrol edin."
+ "Download started. Check your browser downloads.": "İndirme başlatıldı. Tarayıcınızın indirme listesini kontrol edin.",
+ "This element was not found in the current source. Refresh the preview, then ask an agent to edit the source if it is still unavailable.": "Bu öğe geçerli kaynakta bulunamadı. Önizlemeyi yenileyin; sorun sürerse bir ajandan kaynağı düzenlemesini isteyin.",
+ "The preview element does not match the current source. Refresh the preview and select it again.": "Önizleme öğesi geçerli kaynakla eşleşmiyor. Önizlemeyi yenileyip öğeyi yeniden seçin.",
+ "This element type cannot be edited visually yet. Select its outer container or ask an agent to edit the source.": "Bu öğe türü henüz görsel olarak düzenlenemiyor. Dış kapsayıcıyı seçin veya bir ajandan kaynağı düzenlemesini isteyin.",
+ "The source file could not be found. Refresh the preview or ask an agent to restore the source file.": "Kaynak dosya bulunamadı. Önizlemeyi yenileyin veya bir ajandan dosyayı geri yüklemesini isteyin.",
+ "Access to the source file was denied. Check file permissions and select the element again.": "Kaynak dosyaya erişim reddedildi. Dosya izinlerini kontrol edip öğeyi yeniden seçin.",
+ "The source file could not be read. Try again or ask an agent to check the source file.": "Kaynak dosya okunamadı. Yeniden deneyin veya bir ajandan dosyayı kontrol etmesini isteyin.",
+ "Cannot connect to the editor to check this element. Check the connection and select it again.": "Bu öğeyi kontrol etmek için düzenleyiciye bağlanılamıyor. Bağlantıyı kontrol edip öğeyi yeniden seçin.",
+ "Could not check whether this element can be edited. Select it again or refresh the preview.": "Bu öğenin düzenlenip düzenlenemeyeceği kontrol edilemedi. Öğeyi yeniden seçin veya önizlemeyi yenileyin."
}
}
diff --git a/studio/src/i18n/messages.ts b/studio/src/i18n/messages.ts
index 7de4e837..696c243a 100644
--- a/studio/src/i18n/messages.ts
+++ b/studio/src/i18n/messages.ts
@@ -47,7 +47,7 @@ const singular: Record<string, string> = {
};
const pluralRules = Object.fromEntries(languages.map(({ locale }) => [locale, new Intl.PluralRules(locale)]));
-export const isKnownMessage = (message: string): boolean => Object.hasOwn(zhCN, message) || Object.hasOwn(mvpZhCN, message);
+export const isKnownMessage = (message: string): boolean => Object.hasOwn(zhCN, message) || Object.hasOwn(mvpZhCN, message) || Object.hasOwn(errorUi['zh-CN'], message);
/** Accept legacy Chinese labels and already-localized built-in labels. */
export function sourceMessage(message: string, locale: Locale = 'zh-CN'): string {
diff --git a/studio/tests/e2e/source-probe-reasons.mjs b/studio/tests/e2e/source-probe-reasons.mjs
new file mode 100644
index 00000000..e6b23815
--- /dev/null
+++ b/studio/tests/e2e/source-probe-reasons.mjs
@@ -0,0 +1,109 @@
+// Run under the shared browser-lock lane and real lock. Owns an isolated project and native Studio.
+import assert from 'node:assert/strict';
+import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+import { WorkspaceStore } from '../../../workspace.ts';
+import { pluginRoot } from '../../../hyperframes.ts';
+import { startServer } from '../../../server.ts';
+import { launchStudioChrome } from './chrome-executable.mjs';
+import { installWebMcpHost } from './webmcp-host.mjs';
+
+const evidence = process.env.EVIDENCE_DIR || await mkdtemp(path.join(tmpdir(), 'motion-source-probe-evidence-'));
+await mkdir(evidence, { recursive: true });
+const directory = await mkdtemp(path.join(tmpdir(), 'motion-source-probe-'));
+const store = new WorkspaceStore(directory);
+let server, browser;
+const results = {};
+try {
+ await store.initialize(pluginRoot);
+ const index = path.join(store.projectDirectory, 'index.html');
+ await writeFile(index, `<!doctype html><html><head><meta charset="utf-8"><script src="assets/gsap.min.js"></script>
+<style>html,body{margin:0;width:1920px;height:1080px;background:#101418;color:white;font-family:Arial}#main{position:relative;width:1920px;height:1080px}#target,#dynamic{position:absolute;left:180px;top:180px;width:550px;height:240px;background:#2463eb;display:grid;place-items:center;font-size:52px}#static-svg{position:absolute;left:1050px;top:180px;width:550px;height:240px}#dynamic{top:600px;background:#6d28d9}</style></head>
+<body><div id="main" data-composition-id="main" data-width="1920" data-height="1080" data-duration="7">
+<div id="target">可编辑元素</div><svg id="static-svg" viewBox="0 0 550 240"><rect width="550" height="240" fill="#0891b2"/><text x="90" y="140" fill="white" font-size="44">静态 SVG</text></svg></div>
+<script>const dynamic=document.createElement('div');dynamic.id='dynamic';dynamic.textContent='动态生成元素';document.getElementById('main').appendChild(dynamic);window.__timelines={main:gsap.timeline({paused:true}).to({}, {duration:7})};</script></body></html>`);
+ server = await startServer(store, Number(process.env.D4_LANE_PREVIEW_PORT || 0));
+ const url = (await server.info()).studioUrl;
+ ({ browser } = await launchStudioChrome());
+ const page = await browser.newPage();
+ await page.setViewport({ width: 1600, height: 1000 });
+ await page.evaluateOnNewDocument(installWebMcpHost, '__sourceProbe');
+ await page.evaluateOnNewDocument(() => localStorage.setItem('motion.studio.locale', 'zh-CN'));
+ const call = (name, input) => page.evaluate((name, input) => window.__sourceProbe.call(name, input), name, input);
+ const wait = async predicate => {
+ const deadline = Date.now() + 20_000;
+ while (Date.now() < deadline) {
+ if (await predicate()) return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw new Error('Expected state did not settle');
+ };
+ const open = async () => {
+ await page.goto(url, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => window.__sourceProbe?.has('studio_look'), { timeout: 90_000 });
+ await wait(async () => (await call('studio_seek', { time: 1 })).ok);
+ };
+ const handle = async label => {
+ let found;
+ await wait(async () => {
+ found = (await call('studio_look', { limit: 100 })).elements?.find(element => element.label === label)?.handle;
+ return found;
+ });
+ return found;
+ };
+ const color = () => page.evaluate(() => {
+ const iframe = document.querySelector('hyperframes-player')?.shadowRoot?.querySelector('iframe');
+ const element = iframe?.contentDocument?.getElementById('target');
+ return element ? iframe.contentWindow.getComputedStyle(element).backgroundColor : null;
+ });
+ await open();
+ const target = await handle('Target');
+ assert.equal((await call('studio_inspect', { handle: target })).can.editStyles, true);
+ const before = await readFile(index, 'utf8');
+ results.save = await call('studio_set_style', { handle: target, styles: { backgroundColor: '#e11d48' } });
+ assert.equal(results.save.ok, true, JSON.stringify(results.save));
+ await wait(async () => (await readFile(index, 'utf8')) !== before);
+ const saved = await readFile(index, 'utf8');
+ await open();
+ await wait(async () => await color() === 'rgb(225, 29, 72)');
+ results.refreshAfterSave = true;
+ await page.keyboard.down('Control'); await page.keyboard.press('z'); await page.keyboard.up('Control');
+ await wait(async () => (await readFile(index, 'utf8')) === before);
+ await wait(async () => await color() === 'rgb(36, 99, 235)');
+ results.undo = true;
+ await open();
+ await wait(async () => await color() === 'rgb(36, 99, 235)');
+ results.refreshAfterUndo = true;
+ await page.screenshot({ path: path.join(evidence, 'save-refresh-undo.png') });
+
+ for (const [label, id, reason, text] of [
+ ['Static Svg', 'static-svg', 'cannot be edited visually yet', '暂不支持直接编辑此类元素'],
+ ['Dynamic', 'dynamic', 'not found in the current source', '在当前源码中找不到此元素'],
+ ]) {
+ const current = await handle(label);
+ const inspected = await call('studio_inspect', { handle: current });
+ assert.equal(inspected.can.editStyles, false);
+ assert.ok(inspected.can.reasonIfDisabled.includes(reason), JSON.stringify(inspected));
+ assert.equal((await call('studio_select', { handle: current })).ok, true);
+ await page.waitForSelector('[data-dom-edit-selection-box="true"]');
+ await page.click('[data-dom-edit-selection-box="true"]');
+ await page.waitForFunction(text => document.body.innerText.includes(text), {}, text);
+ await new Promise(resolve => setTimeout(resolve, 450));
+ await page.screenshot({ path: path.join(evidence, `${id}-reason.png`) });
+ assert.equal(await readFile(index, 'utf8'), before, 'Blocked selection must not write source');
+ results[id] = inspected.can.reasonIfDisabled;
+ await page.waitForFunction(text => !document.body.innerText.includes(text), {}, text);
+ }
+ results.savedSourceChanged = saved !== before;
+ await writeFile(path.join(evidence, 'browser-result.json'), JSON.stringify({ status: 'PASS', results }, null, 2));
+ console.log(JSON.stringify({ status: 'PASS', evidence, results }, null, 2));
+} catch (error) {
+ await writeFile(path.join(evidence, 'browser-result.json'), JSON.stringify({ status: 'FAIL', error: error.stack, results }, null, 2));
+ if (browser) await (await browser.pages()).at(-1)?.screenshot({ path: path.join(evidence, 'failure.png') });
+ throw error;
+} finally {
+ await browser?.close();
+ await server?.close();
+ await rm(directory, { recursive: true, force: true });
+}