diff --git a/docs/development/ci-failures.md b/docs/development/ci-failures.md index 4c0169186..5420a3427 100644 --- a/docs/development/ci-failures.md +++ b/docs/development/ci-failures.md @@ -51,6 +51,10 @@ The OpenCode hang tracked as #162 is unrelated and was not verified here. The toolbar top-bar test timed out on both main and PR #689 at 50% zoom. The center of the fixture node was behind the left rail, so the drag pressed Add Text. Use an exposed point on the node and check its hit target before sending pointer input. [Main run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47344640055/job/145081431931) · [PR run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47378835105/job/145201585744) +## Python shard inventory after adding a test module + +The core shard failed on both main and PR #698 because the Ark availability test was missing from the shard manifest. Register each new test module in one shard and run the existing inventory test. [Main run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47460479983/job/145484772476) · [PR run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47484854000/job/145564214390) + ## Packaged runtime dependency resolution A Windows installer rerun and the independent Linux wheel check resolved FastAPI 0.165.1 with OpenTelemetry API 1.46.0. FastAPI passed positional arguments that the newer logging API accepts only as keywords, so HTTP requests returned 500. The wheel declares the compatible OpenTelemetry range until FastAPI supports the new API. Desktop packaging also constrains wheel dependencies to the repository lock. Verify fresh wheel installation and both desktop builds when changing these constraints. [Windows run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47382086691/job/145228863573) · [Linux run](https://github.com/ThinkFlowLab/OpenDirector/actions/runs/47389658023/job/145239847848) diff --git a/docs/development/lessons.md b/docs/development/lessons.md index 292eaf466..2b536998a 100644 --- a/docs/development/lessons.md +++ b/docs/development/lessons.md @@ -52,6 +52,13 @@ When work exposes a consequential risk or a recurring problem, add a lesson or u - **Evidence:** [PR #380](https://github.com/ThinkFlowLab/OpenDirector/pull/380) reproduced delayed assistant reads closing the project picker and ending new-project renaming. Project creation and opening succeeded; the chat's readiness effect moved focus and triggered the other controls' dismissal handlers. - **Check:** Hold the assistant read until the project picker or name editor is active, then release it and verify that both the control and its focus remain. Preserve focus requested by explicitly opening chat or changing conversations, while respecting a later user focus change. Distinguish a controlled reproduction from proof of the original CI event order. - In a narrow chat, dismissing the pending canvas references on pointer-down moved a result button before pointer-up. The click landed on the card and never reached the button. Exercise a real pointer click after returning from a selected canvas node and verify that the node becomes visible again. / 窄屏聊天曾在按下鼠标时收起待引用面板,使结果按钮在松开鼠标前移位。回归应从已有选区的画布返回对话,实际点击结果按钮,并检查对应节点是否重新进入视口。 +- **Clipboard follow-up:** Chromium can target a prior DOM selection when the canvas already owns focus. A toast, project title, or file picker input can receive the clipboard event even though the canvas is the active element. Check both the active element and selection. Use real copy, cut, and paste keystrokes after moving focus between the canvas and a text field. [Browser regression](../../tests/browser/canvas_system_clipboard.mjs) + +## Clipboard HTML parsing stays outside the browser document + +- **Trigger:** Reading HTML from the system clipboard before deciding what to paste. +- **Evidence:** [CodeQL on PR #698](https://github.com/ThinkFlowLab/OpenDirector/runs/145564305656) flagged assignment of clipboard HTML to a template element. +- **Check:** Parse the clipboard string into a data tree without a browser document. Verify known markers, mixed text and images, and inline image paste with the [parser tests](../../tests/canvasSystemClipboard.test.ts) and the real browser clipboard. ## Pointer capture does not transfer keyboard focus diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index b93404a6e..0a97c9715 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -118,7 +118,8 @@ The first launch creates an untitled canvas. Later launches can restore the most - To explore a complete project, select **Browse example canvases** on an empty canvas or **Example canvases** in the project menu. The list shows sample sizes and download progress, and offers manual download links where available. Importing a sample opens a new project. A ZIP containing one `.canvas` file is unpacked automatically. If a download returns a webpage, the picker reports the error. - To connect a generation model, open **Settings → Model connections**. - Right-click empty canvas space to create a node, paste, undo, or redo. -- To copy nodes between tabs in the same browser profile, select them and press `Ctrl+C` (`⌘C` on Mac). Wait for the copy confirmation, then focus the destination canvas and press `Ctrl+V` (`⌘V` on Mac). If the shortcut is unavailable, right-click the destination canvas and choose **Paste**. +- To copy nodes between tabs in the same browser profile, select them and press `Ctrl+C` (`⌘C` on Mac). Wait for the copy confirmation, then focus the destination canvas and press `Ctrl+V` (`⌘V` on Mac). You can also right-click the canvas and choose **Paste** if your browser allows clipboard access. +- Focus the canvas and paste text, a screenshot, or media files from your clipboard to add them as nodes. Copy a text node to paste its text into another app. - Click **Upload** on the left or drag files onto the canvas to add assets. Click **Asset library** to choose existing material. - Single-image HEIC and HEIF photos are supported; multi-image files and sequences are rejected. OpenDirector retains the original file and creates an oriented, full-resolution PNG for browser display. Downloads, canvas archives and timeline media packages retain the original. Files must decode successfully and contain at most 25 million pixels. If an original is unavailable, exporting reports an error instead of substituting the display preview. - Double-click a node's name to rename it. Double-click its content to open the appropriate editor or preview. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index 28b78c1ce..981ef886d 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -118,7 +118,8 @@ vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可 - 想看看完整项目时,点击空画布上的“浏览示例画布”,或从项目菜单打开“示例画布”。列表会显示示例大小和下载进度,部分示例也提供手动下载链接。导入后会打开一个新项目。下载包中若只有一个 `.canvas` 文件,会自动解包。若下载返回网页,列表会提示错误。 - 要连接生成模型,打开“设置 → 模型接入”。 - 右键空白画布可新建节点、粘贴、撤销或重做。 -- 在同一浏览器配置文件的两个标签页间复制节点时,先选中节点,按 `Ctrl+C`(Mac 上为 `⌘C`)。看到复制提示后,点击目标画布并按 `Ctrl+V`(Mac 上为 `⌘V`)。如果快捷键不可用,可右键点击目标画布并选择“粘贴”。 +- 在同一浏览器配置文件的两个标签页间复制节点时,先选中节点,按 `Ctrl+C`(Mac 上为 `⌘C`)。看到复制提示后,点击目标画布并按 `Ctrl+V`(Mac 上为 `⌘V`)。如果浏览器允许读取剪贴板,也可以右键点击画布并选择“粘贴”。 +- 将焦点移到画布后,粘贴剪贴板中的文本、截图或媒体文件,即可添加节点。复制文本节点后,可以把正文粘贴到其他应用。 - 点击左侧“上传”或将文件拖入画布添加素材;“资产库”可选择已有素材。 - 支持单图 HEIC 和 HEIF 照片,不接受多图文件和图像序列。OpenDirector 保留原文件,并生成方向正确、完整分辨率的 PNG 供浏览器显示;下载、画布归档和时间线媒体包均保留原件。文件须能完整解码,且像素总数不超过 2500 万。原件不可用时,导出会报错,不会改用显示预览图。 - 双击节点名称重命名;双击节点内容进入相应编辑或预览界面。 diff --git a/feature-assets/canvas-system-clipboard/README.md b/feature-assets/canvas-system-clipboard/README.md new file mode 100644 index 000000000..74c1588bc --- /dev/null +++ b/feature-assets/canvas-system-clipboard/README.md @@ -0,0 +1,25 @@ +# System clipboard evidence + +These captures use an isolated creation server and synthetic project content. +The baseline is `93bd25b08a53633c08a9d904b1043e8cf6c2de65`. The recording and +corrected screenshots use the build from `cd82ad1ae2294decdd3162806228922b2117bd86`. + +1. Copy an image node. Copy `External clipboard en-US` from a separate + text field, then paste it onto the canvas. +2. On the baseline, the canvas pastes another image. The system + clipboard still contains the external text. [Baseline screenshot](before.png) +3. The candidate creates a text node containing `External clipboard en-US`. + [Corrected screenshot](after.png) + +The [video](clipboard.mp4) shows the same reproduction, cut and paste, menu +paste, screenshot and HTML image paste, and the project after reopening. +It also shows a large UTF-8 paste rejected before the canvas changes. +The model service is a fixture. The recording does not call a real provider. + +The [browser regression](../../tests/browser/canvas_system_clipboard.mjs) +checks the same workflow in English and Chinese. + +The [cross-tab screenshot](cross-tab-after.png) shows the destination project +after the source tab closed and the destination reopened. The +[cross-canvas browser test](../../tests/browser/cross_canvas_paste.mjs) verifies +the registered assets by fingerprint. diff --git a/feature-assets/canvas-system-clipboard/after.png b/feature-assets/canvas-system-clipboard/after.png new file mode 100644 index 000000000..bcbb8c109 Binary files /dev/null and b/feature-assets/canvas-system-clipboard/after.png differ diff --git a/feature-assets/canvas-system-clipboard/before.png b/feature-assets/canvas-system-clipboard/before.png new file mode 100644 index 000000000..7102f43bd Binary files /dev/null and b/feature-assets/canvas-system-clipboard/before.png differ diff --git a/feature-assets/canvas-system-clipboard/clipboard.mp4 b/feature-assets/canvas-system-clipboard/clipboard.mp4 new file mode 100644 index 000000000..78c4f6130 Binary files /dev/null and b/feature-assets/canvas-system-clipboard/clipboard.mp4 differ diff --git a/feature-assets/canvas-system-clipboard/cross-tab-after.png b/feature-assets/canvas-system-clipboard/cross-tab-after.png new file mode 100644 index 000000000..80e79843e Binary files /dev/null and b/feature-assets/canvas-system-clipboard/cross-tab-after.png differ diff --git a/package-lock.json b/package-lock.json index 303e2422f..2ecf49545 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,6 +14,7 @@ "mdast-util-from-markdown": "2.1.0", "mediabunny": "1.62.1", "opencode-ai": "1.19.5", + "parse5": "7.3.0", "react": "19.3.1", "react-dom": "19.3.1", "streamdown": "2.5.0", diff --git a/package.json b/package.json index 4b2ac6471..b17a9de67 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "mdast-util-from-markdown": "2.1.0", "mediabunny": "1.62.1", "opencode-ai": "1.19.5", + "parse5": "7.3.0", "react": "19.3.1", "react-dom": "19.3.1", "streamdown": "2.5.0", diff --git a/scripts/ci/python_shards.json b/scripts/ci/python_shards.json index c2b76342c..d137fb1b9 100644 --- a/scripts/ci/python_shards.json +++ b/scripts/ci/python_shards.json @@ -4,6 +4,7 @@ "core": [ "tests/test_a2_repros.py", "tests/test_app_settings.py", + "tests/test_ark_availability.py", "tests/test_ark_plan_models.py", "tests/test_asset_names.py", "tests/test_atlascloud.py", diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index ec4ccaf17..606fe029a 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -38,6 +38,7 @@ const workflows = [ { name: "canvas composer placement", script: "tests/browser/canvas_composer_placement.mjs" }, { name: "created node focus", script: "tests/browser/created_node_focus.mjs" }, { name: "cross canvas paste", script: "tests/browser/cross_canvas_paste.mjs" }, + { name: "system clipboard", script: "tests/browser/canvas_system_clipboard.mjs" }, { name: "reference reconnect", script: "tests/browser/reference_reconnect.mjs" }, { name: "context menu dismissal", diff --git a/src/canvas/canvasSystemClipboard.ts b/src/canvas/canvasSystemClipboard.ts new file mode 100644 index 000000000..2925d51dc --- /dev/null +++ b/src/canvas/canvasSystemClipboard.ts @@ -0,0 +1,189 @@ +import { defaultTreeAdapter, html as htmlTree, parseFragment, type DefaultTreeAdapterTypes } from "parse5"; +import { downloadFilename } from "./assets.ts"; + +const MARKER = "data-opendirector-clipboard"; +const HTML_WRAPPERS = new Set(["html", "body", "div", "p", "span"]); +const COPY_ID = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/; +const IMAGE_BYTES = 32 * 1024 * 1024; +const RASTER_IMAGE = /^image\/(?:png|jpe?g|webp|gif|avif|bmp|tiff?|heic|heif)$/i; + +export interface CanvasClipboardSnapshot { + html: string; + text: string; + files: File[]; +} + +export function snapshotClipboard(data: DataTransfer): CanvasClipboardSnapshot { + const files = Array.from(data.files); + return { + html: data.getData("text/html"), + text: data.getData("text/plain"), + files: files.length ? files : Array.from(data.items).flatMap((item) => { + const file = item.kind === "file" ? item.getAsFile() : null; + return file ? [file] : []; + }), + }; +} + +export async function readSystemClipboard(imageName: string): Promise { + const entries = await navigator.clipboard.read(); + const readText = async (mime: string) => { + const entry = entries.find((item) => item.types.includes(mime)); + return entry ? (await entry.getType(mime)).text() : ""; + }; + const [html, text, files] = await Promise.all([ + readText("text/html"), + readText("text/plain"), + Promise.all(entries.flatMap((entry) => { + const type = entry.types.find((mime) => RASTER_IMAGE.test(mime)); + return type ? [entry.getType(type).then((blob) => clipboardImageFile(blob, imageName))] : []; + })), + ]); + return { html, text, files }; +} + +export function canvasClipboardFormats(id: string, text: string) { + const marker = document.createElement("span"); + marker.setAttribute(MARKER, id); + marker.textContent = text || "\u200b"; + return { html: marker.outerHTML, text }; +} + +export function writeClipboardEvent( + event: ClipboardEvent, + { html, text }: ReturnType, +) { + if (event.defaultPrevented || !event.cancelable || !event.clipboardData) return false; + event.clipboardData.setData("text/html", html); + event.clipboardData.setData("text/plain", text); + event.preventDefault(); + return true; +} + +export function writeClipboardFromMenu(formats: ReturnType) { + let written = false; + const copy = (event: ClipboardEvent) => { + written = writeClipboardEvent(event, formats); + }; + document.addEventListener("copy", copy, { capture: true, once: true }); + try { + return document.execCommand("copy") && written; + } finally { + document.removeEventListener("copy", copy, true); + } +} + +function clipboardHtml(html: string) { + if (!html || html.length > IMAGE_BYTES * 2) return; + return parseFragment(html); +} + +function isIgnorableClipboardNode(node: DefaultTreeAdapterTypes.ChildNode) { + return defaultTreeAdapter.isCommentNode(node) || + (defaultTreeAdapter.isTextNode(node) && !node.value.trim()) || + (defaultTreeAdapter.isElementNode(node) && node.tagName === "meta"); +} + +export function canvasClipboardId(html: string) { + if (!html.includes(MARKER)) return; + let content: DefaultTreeAdapterTypes.ParentNode | undefined = clipboardHtml(html); + while (content) { + const nodes: DefaultTreeAdapterTypes.ChildNode[] = content.childNodes.filter( + (node) => !isIgnorableClipboardNode(node), + ); + const node = nodes[0]; + if (nodes.length !== 1 || !node || !defaultTreeAdapter.isElementNode(node) || + node.namespaceURI !== htmlTree.NS.HTML) + return; + const id = node.attrs.find((attr) => attr.name === MARKER)?.value; + if (node.tagName === "span" && id) { + if (node.childNodes.some(defaultTreeAdapter.isElementNode)) return; + return COPY_ID.test(id) ? id : undefined; + } + if (!HTML_WRAPPERS.has(node.tagName)) return; + content = node; + } +} + +type ClipboardImage = + | { kind: "inline"; mime: string; base64: string } + | { kind: "url"; url: string }; + +export function clipboardHtmlImage(html: string): ClipboardImage | undefined { + const content = clipboardHtml(html); + if (!content) return; + const pending = [...content.childNodes]; + let image: DefaultTreeAdapterTypes.Element | undefined; + for (let node = pending.pop(); node; node = pending.pop()) { + if (defaultTreeAdapter.isTextNode(node) && node.value.trim()) return; + if (!defaultTreeAdapter.isElementNode(node)) continue; + if (node.tagName === "img" && node.namespaceURI === htmlTree.NS.HTML) { + if (image) return; + image = node; + } + for (const child of node.childNodes) pending.push(child); + } + const src = image?.attrs.find((attr) => attr.name === "src")?.value; + if (!src) return; + const inline = /^data:([^;,]+);base64,/i.exec(src); + const mime = inline?.[1]; + if (inline && mime && RASTER_IMAGE.test(mime)) + return { kind: "inline", mime, base64: src.slice(inline[0].length) }; + try { + const url = new URL(src); + if (url.protocol === "https:" && url.origin !== location.origin && !url.username && !url.password) + return { kind: "url", url: url.href }; + } catch { + return undefined; + } +} + +async function rasterBlob(response: Response): Promise { + const type = response.headers.get("Content-Type")?.split(";")[0] ?? ""; + if (!response.ok || !RASTER_IMAGE.test(type) || + Number(response.headers.get("Content-Length")) > IMAGE_BYTES || !response.body) { + await response.body?.cancel(); + throw new Error("Invalid clipboard image"); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let size = 0; + try { + while (true) { + const result = await reader.read(); + if (result.done) break; + size += result.value.byteLength; + if (size > IMAGE_BYTES) { + await reader.cancel(); + throw new Error("Clipboard image exceeds size limit"); + } + chunks.push(Uint8Array.from(result.value)); + } + } finally { + reader.releaseLock(); + } + return new Blob(chunks, { type }); +} + +function clipboardImageFile(blob: Blob, name: string) { + return new File([blob], downloadFilename(name, blob.type), { type: blob.type }); +} + +export async function loadClipboardImage(image: ClipboardImage, imageName: string) { + if (image.kind === "inline") { + if (image.base64.length > Math.ceil(IMAGE_BYTES / 3) * 4) + throw new Error("Clipboard image exceeds size limit"); + const decoded = atob(image.base64); + if (decoded.length > IMAGE_BYTES) throw new Error("Clipboard image exceeds size limit"); + const bytes = new Uint8Array(decoded.length); + for (let index = 0; index < bytes.length; index++) bytes[index] = decoded.charCodeAt(index); + return clipboardImageFile(new Blob([bytes], { type: image.mime }), imageName); + } + const response = await fetch(image.url, { + credentials: "omit", + redirect: "error", + referrerPolicy: "no-referrer", + signal: AbortSignal.timeout(10_000), + }); + return clipboardImageFile(await rasterBlob(response), imageName); +} diff --git a/src/canvas/clipboardMedia.ts b/src/canvas/clipboardMedia.ts index 87932f949..abc004237 100644 --- a/src/canvas/clipboardMedia.ts +++ b/src/canvas/clipboardMedia.ts @@ -13,9 +13,6 @@ const KINDS = new Set([ "file", ]); -/** Media copied with a fragment. Switching projects revokes the source's object - * URLs, so the bytes are read while the copy is made; saved assets also keep - * their source identity, so a paste can copy them on the server. */ export interface ClipboardMedia { projectId: string; blobs: Map>; @@ -88,7 +85,6 @@ async function readBlob(src: string): Promise { return response.blob(); } -/** Starts reading every inline media field before the source project can close. */ export function captureClipboardMedia( projectId: string, fragment: CanvasFragment, @@ -101,18 +97,23 @@ export function captureClipboardMedia( resolve?: ( src: string, assetId: string | undefined, - ) => Omit | undefined; + ) => (Omit & { cacheBytes?: boolean }) | undefined; } = {}, ): ClipboardMedia { const blobs = new Map>(); const sources = new Map(); for (const node of fragment.nodes) visitMedia(node, (record, key, src) => { + if (sources.has(src)) return; const saved = key === "src" ? resolve(src, savedAssetId(node, record, key)) : undefined; - if (saved && !sources.has(src)) sources.set(src, { projectId, ...saved }); + if (saved) { + const { assetId, fingerprint, cacheBytes } = saved; + sources.set(src, { projectId, assetId, fingerprint }); + if (cacheBytes === false) return; + } if (blobs.has(src)) return; const pending = read(src, key === "src" && typeof record.mimeType === "string" ? record.mimeType : undefined); // A failed read is reported by the paste that needs it. @@ -133,6 +134,7 @@ export async function transferClipboardMedia( media: ClipboardMedia, targetProjectId: string, register: RegisterMedia, + registerSaved?: (source: MediaSource) => Promise, ): Promise { const copy = structuredClone(fragment); const registrations: Promise[] = []; @@ -170,7 +172,7 @@ export async function transferClipboardMedia( : undefined; visitMedia(node, (record, key, src) => { const blob = media.blobs.get(src); - if (!blob) throw new Error(tNow("errors.files.clipboardExpired")); + const source = media.sources.get(src); const title = typeof record.title === "string" ? record.title : node.data.title; const kind = @@ -183,19 +185,23 @@ export async function transferClipboardMedia( const cacheKey = `${targetProjectId}\n${src}`; let pending = media.registered.get(cacheKey); if (!pending) { - pending = blob - .then((bytes) => - register( - bytes, - title, - kind ?? mediaKind(bytes.type), - media.sources.get(src), - ), - ) - .catch((error) => { - media.registered.delete(cacheKey); - throw error; - }); + const copySaved = source && registerSaved + ? () => registerSaved(source) + : undefined; + if (blob) { + pending = blob.then( + (bytes) => register(bytes, title, kind ?? mediaKind(bytes.type), source), + copySaved, + ); + } else if (copySaved) { + pending = copySaved(); + } else { + throw new Error(tNow("errors.files.clipboardExpired")); + } + pending = pending.catch((error) => { + media.registered.delete(cacheKey); + throw error; + }); media.registered.set(cacheKey, pending); } registrations.push( diff --git a/src/canvas/sharedCanvasClipboard.ts b/src/canvas/sharedCanvasClipboard.ts index 3a78209b9..94dbccf12 100644 --- a/src/canvas/sharedCanvasClipboard.ts +++ b/src/canvas/sharedCanvasClipboard.ts @@ -5,7 +5,6 @@ import type { CanvasFragment } from "./operations.ts"; const DATABASE = "opendirector.canvasClipboard.v1"; const STORE = "clipboard"; const LATEST = "latest"; -const CANVAS_CLIPBOARD_TYPE = "application/x-opendirector-canvas"; export interface SharedCanvasClipboard { id: string; @@ -56,26 +55,6 @@ export function sharedCanvasClipboardId(): string | null { } } -export function markCanvasClipboard(id: string): void { - const write = (event: ClipboardEvent) => { - if (!event.clipboardData) return; - event.clipboardData.setData(CANVAS_CLIPBOARD_TYPE, id); - event.preventDefault(); - }; - document.addEventListener("copy", write); - try { - document.execCommand("copy"); - } catch { - } finally { - document.removeEventListener("copy", write); - } -} - -export function isCanvasClipboard(data: DataTransfer | null): boolean { - const id = data?.getData(CANVAS_CLIPBOARD_TYPE); - return Boolean(id && id === sharedCanvasClipboardId()); -} - export async function writeSharedCanvasClipboard({ id, fragment, diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 951ec85f7..0c8712dc9 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -108,7 +108,6 @@ import { TextNodeComposer } from "../TextNodeComposer"; import "../themes.css"; import { TimelineEditor } from "../TimelineEditor"; import { TimelineOutputShortcut, useTimelineOutput } from "../TimelineOutput"; -import { sharedCanvasClipboardId } from "../sharedCanvasClipboard.ts"; import { CANVAS_TOOLS, createCanvasToolTask, initialToolParameters } from "../toolCatalog"; import { imagePresetsFromFields } from "../promptSkill.ts"; @@ -166,7 +165,6 @@ export function WorkspaceView({ rt, editingState, editSession }: { center, change, changeTool, - clipboard, closeAction, closeEditor, command, @@ -186,6 +184,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { contextItems, copy, cut, + duplicate, deleteProject, dismiss, doc, @@ -1607,7 +1606,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { name="copy" disabled={readOnly} label={t("canvas.workspace.selection.duplicate")} - onClick={() => paste(true)} + onClick={() => duplicate()} /> @@ -1750,7 +1749,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { ? () => setTextWindowId(single.id) : undefined } - onDuplicate={() => { if (!readOnly) paste(true); }} + onDuplicate={() => { if (!readOnly) duplicate(); }} /> )} @@ -2179,7 +2178,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { x={menu.x} y={menu.y} mode={menu.mode ?? "context"} - canPaste={Boolean(clipboard.current || sharedCanvasClipboardId())} + canPaste={!readOnly} canUndo={businessHistory.undo && !historyReplaying} canRedo={businessHistory.redo && !historyReplaying} onCreate={(kind) => addNode(kind, menu.world)} @@ -2190,7 +2189,7 @@ export function WorkspaceView({ rt, editingState, editSession }: { }} onUpload={() => openFilePicker()} onImportUrl={readOnly ? undefined : () => setLinkImportPoint(menu.world)} - onPaste={() => paste()} + onPaste={() => void paste(menu.world)} onUndo={() => replayHistory()} onRedo={() => replayHistory(true)} onOrganizeRuns={hasManagedRuns ? () => void applyRunLayout({ kind: "organize" }) : undefined} @@ -2220,8 +2219,8 @@ export function WorkspaceView({ rt, editingState, editSession }: { {menuButton(t("canvas.workspace.menu.copy"), "copy", copy, "⌘ C")} {menuButton(t("canvas.workspace.menu.cut"), "copy", cut, "⌘ X")} - {menuButton(t("canvas.workspace.menu.paste"), "copy", () => paste(), "⌘ V")} - {menuButton(t("canvas.workspace.selection.duplicate"), "copy", () => paste(true), "⌘ D")} + {menuButton(t("canvas.workspace.menu.paste"), "copy", () => void paste(menu.world), "⌘ V")} + {menuButton(t("canvas.workspace.selection.duplicate"), "copy", () => duplicate(), "⌘ D")}
{menuButton(t("canvas.workspace.selection.group"), "group", group, "⌘ G")} {selected.length > 1 && menuButton(t("canvas.workspace.kind.stack"), "stack", stack)} diff --git a/src/canvas/workspace/useWorkspaceDocument.ts b/src/canvas/workspace/useWorkspaceDocument.ts index 0556172b6..119c4c513 100644 --- a/src/canvas/workspace/useWorkspaceDocument.ts +++ b/src/canvas/workspace/useWorkspaceDocument.ts @@ -76,6 +76,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { setTextEditingId, setTextWindowId, setZoomMenu, + projectInstallVersion, switchPending, switching, t, @@ -278,6 +279,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { const installDocument = useCallback( (next: CanvasDocument, fit = false) => { + projectInstallVersion.current++; importAbort.current?.abort(); importAbort.current = null; resultBinding.current = null; @@ -323,7 +325,7 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime, readOnly: boolean) { ); } }, - [flow, setSaveStatus], + [flow, projectInstallVersion, setSaveStatus], ); const switchDocument = useCallback( diff --git a/src/canvas/workspace/useWorkspaceInteraction.tsx b/src/canvas/workspace/useWorkspaceInteraction.tsx index 6db84226f..95b3de0f5 100644 --- a/src/canvas/workspace/useWorkspaceInteraction.tsx +++ b/src/canvas/workspace/useWorkspaceInteraction.tsx @@ -45,14 +45,12 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean) cancelResultImport, center, change, - clipboard, closeAction, command, composerElement, composerNode, connectionStarted, - copy, - cut, + duplicate, dismissedComposer, doc, dragging, @@ -78,7 +76,6 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean) openFilePicker, panel, panning, - paste, persist, pointerGesture, presentationFocus, @@ -890,7 +887,6 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean) code: event.code, mod, shift: event.shiftKey, - hasClipboard: Boolean(clipboard.current), editText: Boolean( single?.type === "text" && !lockedIds.has(single.id) && @@ -914,15 +910,13 @@ export function useWorkspaceInteraction(rt: WorkspaceRuntime, readOnly: boolean) } else if (action.type === "history") replayHistory(action.forward); else if (action.type === "select-all") setSelected(canvasSelectAllIds(doc.nodes)); - else if (action.type === "copy") copy(); - else if (action.type === "cut") cut(); else if (action.type === "reorder") command({ type: "reorder-nodes", ids: selectedRef.current, direction: action.direction, }); - else if (action.type === "paste") paste(action.duplicate); + else if (action.type === "duplicate") duplicate(); else if (action.type === "group") { if (action.ungroup) ungroup(); else group(); diff --git a/src/canvas/workspace/useWorkspaceRuntime.ts b/src/canvas/workspace/useWorkspaceRuntime.ts index b4d8dcb13..fbc2c09b8 100644 --- a/src/canvas/workspace/useWorkspaceRuntime.ts +++ b/src/canvas/workspace/useWorkspaceRuntime.ts @@ -22,7 +22,6 @@ import { validateNodeActionSource, type ResultSource } from "../linkedResults"; import { newNodeGenerationSettings } from "../modelResolution.ts"; import { preferredMediaModel } from "../agentPreferences.ts"; import { type CanvasDocument, type CanvasNode, type CanvasNodeData, type CanvasNodeKind, type Point } from "../model"; -import type { SharedCanvasClipboard } from "../sharedCanvasClipboard.ts"; import { CanvasPointerGesture } from "../pointerGesture"; import { type SubjectMediaSlot } from "../subjectMedia.ts"; @@ -86,6 +85,7 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { ); const versionCounts = useNodeVersionCounts(doc.id, ready && !store.switching); const switchPending = useRef(false); + const projectInstallVersion = useRef(0); const revealCreatedNodes = useRef<(nodes: CanvasNode[], allNodes: CanvasNode[]) => void>(() => {}); const viewportMoving = useRef(false); const selectedRef = useRef(selected); @@ -212,9 +212,6 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { ), [activeGenerations, doc.id, doc.nodes, jobs], ); - const clipboard = useRef(null); - const pasting = useRef(false); - const pasteCount = useRef(0); const fileInput = useRef(null); const uploadTarget = useRef(null); const uploadSource = useRef<{ @@ -333,6 +330,7 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { runtime.liveCanvas = liveCanvas; runtime.versionCounts = versionCounts; runtime.switchPending = switchPending; + runtime.projectInstallVersion = projectInstallVersion; runtime.revealCreatedNodes = revealCreatedNodes; runtime.viewportMoving = viewportMoving; runtime.selectedRef = selectedRef; @@ -368,9 +366,6 @@ export function useWorkspaceRuntime(): WorkspaceRuntime { runtime.theme = theme; runtime.serviceRuns = serviceRuns; runtime.generationByNode = generationByNode; - runtime.clipboard = clipboard; - runtime.pasting = pasting; - runtime.pasteCount = pasteCount; runtime.fileInput = fileInput; runtime.uploadTarget = uploadTarget; runtime.uploadSource = uploadSource; diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts index b0c0ae85e..751e77046 100644 --- a/src/canvas/workspace/useWorkspaceTransfer.ts +++ b/src/canvas/workspace/useWorkspaceTransfer.ts @@ -1,4 +1,5 @@ import { useEffect, useRef } from "react"; +import { flushSync } from "react-dom"; import { errorMessage } from "../../backend/api.ts"; import { @@ -8,6 +9,7 @@ import { type CanvasSource, } from "../../backend/canvasSources"; import { creationClient } from "../../backend/creationClient.ts"; +import { getEditingState } from "../../backend/editSession.ts"; import { fingerprint } from "../../backend/generation.ts"; import { @@ -28,11 +30,22 @@ import { type LibraryItem, } from "../library/libraryClient"; import { type SubjectImportChoice } from "../library/SubjectImportDialog"; -import { applyCommand, createNode, type CanvasCommand, type CanvasNode, type CanvasResource, type Point } from "../model"; +import { applyCommand, createNode, nextNodeTitle, type CanvasCommand, type CanvasNode, type CanvasResource, type Point } from "../model"; import { copySelection, cutSelection, deleteSelection, groupDescendants, groupSelection, pasteFragment, ungroupSelection, type CanvasFragment } from "../operations"; import { createZip } from "../zipArchive"; import { buildCanvasArchive, readCanvasArchive } from "../canvasArchive.ts"; +import { + canvasClipboardFormats, + canvasClipboardId, + clipboardHtmlImage, + loadClipboardImage, + readSystemClipboard, + snapshotClipboard, + writeClipboardEvent, + writeClipboardFromMenu, + type CanvasClipboardSnapshot, +} from "../canvasSystemClipboard.ts"; import { captureClipboardMedia, transferClipboardMedia, @@ -41,8 +54,6 @@ import { import { resourceNodeData } from "../projectAssets"; import { persistCurrentDocument } from "../projectManagement"; import { - isCanvasClipboard, - markCanvasClipboard, readSharedCanvasClipboard, sharedCanvasClipboardId, writeSharedCanvasClipboard, @@ -62,13 +73,14 @@ import { importLinkedVideo } from "./linkImport.ts"; import { assertUpload } from "../uploadPolicy.ts"; import { prefetchLibrary } from "../library/libraryPrefetch"; import type { WorkspaceRuntime } from "./runtimeTypes.ts"; -import { parseAssetSource } from "../../backend/assetSource.ts"; +import { assetSource, parseAssetSource } from "../../backend/assetSource.ts"; + +const MAX_CLIPBOARD_TEXT_BYTES = 1024 * 1024; export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { const { center, change, - clipboard, command, commitCanvasCommand, doc, @@ -78,12 +90,12 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { historyRef, importAbort, lockedIds, + mounted, notify, panel, - pasteCount, - pasting, persist, preview, + projectInstallVersion, ready, referenceTarget, resultBinding, @@ -105,7 +117,12 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { uploadSource, uploadTarget, } = rt; - const receivedClipboard = useRef(null); + const receivedClipboard = useRef<{ + id: string; + pending: Promise; + } | null>(null); + const clipboard = useRef<(SharedCanvasClipboard & { installedAt: number }) | null>(null); + const pasteOffset = useRef({ id: "", count: 0 }); useEffect(() => { if (ready) prefetchWorkspaceProjects(); @@ -473,23 +490,48 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { setMenu(null); }; const captureMedia = (fragment: CanvasFragment) => { + let fallbackBytes = 32 * 1024 * 1024; const projectId = historyRef.current.present.id; const client = creationClient(projectId); return captureClipboardMedia(projectId, fragment, { read: (src, mimeType) => client.originalMedia(src, mimeType), resolve: (src, assetId) => { // A just-imported node may show its upload before it records the asset. - const asset = assetId - ? client.snapshot.assets.find((asset) => asset.id === assetId) - : client.assetForSource(src); - return asset && { assetId: asset.id, fingerprint: asset.fingerprint }; + const asset = (assetId && client.snapshot.assets.find((asset) => asset.id === assetId)) + || client.assetForSource(src); + if (!asset) return; + const cacheBytes = asset.kind !== "video" && asset.kind !== "audio" && + asset.metadata.size <= fallbackBytes; + if (cacheBytes) fallbackBytes -= asset.metadata.size; + return { assetId: asset.id, fingerprint: asset.fingerprint, cacheBytes }; }, }); }; - const rememberClipboard = (fragment: CanvasFragment, message: string) => { - const entry = { id: crypto.randomUUID(), fragment, media: captureMedia(fragment) }; + const writeSelection = (fragment: CanvasFragment, message: string, event?: ClipboardEvent) => { + const id = crypto.randomUUID(); + const text = fragment.nodes.map((node) => + node.type === "text" ? (node.data.text ?? "") : node.data.title, + ).filter(Boolean).join("\n"); + const formats = canvasClipboardFormats(id, text); + try { + const written = event ? writeClipboardEvent(event, formats) : writeClipboardFromMenu(formats); + if (!written) { + notify(t("canvas.workspace.toast.clipboardWriteFailed")); + return false; + } + } catch { + notify(t("canvas.workspace.toast.clipboardWriteFailed")); + return false; + } + + const entry = { + id, + fragment, + media: captureMedia(fragment), + installedAt: projectInstallVersion.current, + }; clipboard.current = entry; - pasteCount.current = 0; + pasteOffset.current = { id, count: 0 }; if (entry.media.blobs.size) notify(t("canvas.workspace.toast.preparingClipboard")); void writeSharedCanvasClipboard(entry).then( (written) => { if (written && clipboard.current === entry) notify(message); }, @@ -497,14 +539,17 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { if (clipboard.current === entry) notify(t("canvas.workspace.toast.clipboardLocalOnly")); }, ); - markCanvasClipboard(entry.id); + + return true; }; - const copy = () => { + const copy = (event?: ClipboardEvent) => { + if (!ready || switchPending.current) return; const fragment = copySelection(historyRef.current.present, selectedRef.current); - if (!fragment.nodes.length) return; - rememberClipboard(fragment, t("canvas.workspace.toast.copied", { count: fragment.nodes.length })); + if (fragment.nodes.length) + writeSelection(fragment, t("canvas.workspace.toast.copied", { count: fragment.nodes.length }), event); }; - const cut = () => { + const cut = (event?: ClipboardEvent) => { + if (readOnly || !ready || switchPending.current) return; const movable = selectedRef.current.filter((id) => !lockedIds.has(id)); if (!movable.length) { notify(t("canvas.workspace.toast.selectEditable")); @@ -515,72 +560,101 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { notify(t("canvas.workspace.toast.cutLocked")); return; } - const fragment = result.fragment; - rememberClipboard(fragment, t("canvas.workspace.toast.cut", { count: fragment.nodes.length })); + const { fragment } = result; + if (!writeSelection(fragment, t("canvas.workspace.toast.cut", { count: fragment.nodes.length }), event)) return; change(() => result.document); setSelected([]); setMenu(null); }; - const paste = (duplicate = false) => { + const duplicate = () => { if (readOnly || !ready || switchPending.current) return; - const before = historyRef.current.present; - if (duplicate) { - const fragment = copySelection(before, selectedRef.current); - if (fragment.nodes.length) insertFragment(fragment, 40, "duplicate"); - return; - } - const id = sharedCanvasClipboardId(); - const local = clipboard.current; - if (local?.media.projectId === before.id && (!id || local.id === id)) { - insertFragment(local.fragment, 40 * ++pasteCount.current); - return; - } - void pasteClipboard(id, before.id); + const fragment = copySelection(historyRef.current.present, selectedRef.current); + if (fragment.nodes.length) insertFragment(fragment, 40, "duplicate"); }; - const pasteClipboard = async (id: string | null, projectId: string) => { - try { - let entry = clipboard.current; - if (id && entry?.id !== id) { - const received = receivedClipboard.current; - if (received && received.id === id) { - entry = received; - } else { - entry = await readSharedCanvasClipboard(id); - if (sharedCanvasClipboardId() !== id) return; - receivedClipboard.current = entry; - pasteCount.current = 0; - } + const pasteDestination = () => ({ + id: historyRef.current.present.id, + installedAt: projectInstallVersion.current, + }); + type PasteDestination = ReturnType; + const canPasteInto = ({ id, installedAt }: PasteDestination) => + mounted.current && !switchPending.current && projectInstallVersion.current === installedAt && + historyRef.current.present.id === id && getEditingState(id)?.mode !== "preview"; + const requirePasteDestination = (visit: PasteDestination) => { + if (!canPasteInto(visit)) throw new DOMException("Clipboard destination changed", "AbortError"); + }; + const insertClipboardFragment = (fragment: CanvasFragment, id: string) => { + const count = pasteOffset.current.id === id ? pasteOffset.current.count + 1 : 1; + insertFragment(fragment, 40 * count); + pasteOffset.current = { id, count }; + }; + const pasteClipboard = async (id: string, visit: PasteDestination) => { + const projectId = visit.id; + const local = clipboard.current?.id === id ? clipboard.current : null; + if (local?.media.projectId === projectId && local.installedAt === visit.installedAt) { + assertClipboardAssets(local.media); + insertClipboardFragment(local.fragment, id); + return true; + } + let entry: SharedCanvasClipboard | null = local; + if (!entry) { + if (receivedClipboard.current?.id !== id) { + const pending = readSharedCanvasClipboard(id); + receivedClipboard.current = { id, pending }; } - if (switchPending.current || historyRef.current.present.id !== projectId) return; - if (!entry || pasting.current) return; - pasting.current = true; - const { fragment, media } = entry; + const reading = receivedClipboard.current; try { - const prepared = await transferClipboardMedia(fragment, media, projectId, registerClipboardMedia(projectId)); - if (switchPending.current || historyRef.current.present.id !== projectId) return; - insertFragment(prepared, 40 * ++pasteCount.current); + entry = await reading.pending; } finally { - pasting.current = false; + if (!entry && receivedClipboard.current === reading) receivedClipboard.current = null; } - } catch (error) { - notify( - t("canvas.workspace.toast.crossCanvasPasteFailed", { - error: errorMessage(error), - }), - ); } + if (!entry || !canPasteInto(visit)) return false; + if (entry.media.projectId === projectId) assertClipboardAssets(entry.media); + const prepared = await transferClipboardMedia( + entry.fragment, + entry.media, + projectId, + registerClipboardMedia(visit), + async (source) => { + requirePasteDestination(visit); + const client = creationClient(projectId); + const assetId = source.projectId === projectId + ? client.snapshot.assets.find((asset) => + asset.id === source.assetId && asset.fingerprint === source.fingerprint, + )?.id + : (await client.copyAsset(source)).assetId; + if (!assetId) throw new Error(t("errors.files.clipboardExpired")); + return { assetId, src: assetSource(projectId, assetId) }; + }, + ); + if (canPasteInto(visit)) insertClipboardFragment(prepared, id); + return true; + }; + const assertClipboardAssets = ({ projectId, sources }: SharedCanvasClipboard["media"]) => { + if (!sources.size) return; + const assets = new Map(creationClient(projectId).snapshot.assets.map((asset) => [ + asset.id, asset.fingerprint, + ])); + if ([...sources.values()].some((source) => assets.get(source.assetId) !== source.fingerprint)) + throw new Error(t("errors.files.clipboardExpired")); }; - const registerClipboardMedia = (projectId: string): RegisterMedia => async (blob, title, kind, source) => { + const registerClipboardMedia = (visit: PasteDestination): RegisterMedia => async (blob, title, kind, source) => { + requirePasteDestination(visit); + const projectId = visit.id; const client = creationClient(projectId); if (source?.projectId === projectId && client.snapshot.assets.some((asset) => ( asset.id === source.assetId && asset.fingerprint === source.fingerprint ))) { return { assetId: source.assetId, src: await client.adoptMedia(source.assetId, blob) }; } - const upload = () => client.importBlob(blob, withMediaSuffix(title, blob.type), kind); + const upload = () => { + requirePasteDestination(visit); + return client.importBlob(blob, withMediaSuffix(title, blob.type), kind); + }; const ref = source && source.projectId !== projectId ? await client.copyAsset(source).catch(upload) : await upload(); + requirePasteDestination(visit); return { assetId: ref.assetId, src: await client.adoptMedia(ref.assetId, blob) }; }; const insertFragment = ( @@ -590,11 +664,19 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { ) => { const before = historyRef.current.present; const result = pasteFragment(before, fragment, { x: distance, y: distance }, mode); - change(() => result.document); - // Keep each paste in its own durable undo step, even inside the autosave debounce. + commitPaste(before, result.document, result.ids, mode); + }; + const commitPaste = ( + before: typeof doc, + after: typeof doc, + ids: string[], + mode: "paste" | "duplicate" = "paste", + ) => { + if (mode === "paste") flushSync(() => change(() => after)); + else change(() => after); void persist(before, false); - void persist(result.document, false); - setSelected(result.ids); + void persist(after, false); + setSelected(ids); setMenu(null); root.current?.focus({ preventScroll: true }); }; @@ -952,35 +1034,123 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { if (importAbort.current === controller) importAbort.current = null; } }; - useEffect(() => { - const onPaste = (event: ClipboardEvent) => { - if (readOnly || !rt.canvasVisible || event.defaultPrevented || !ready || switchPending.current) return; - const target = event.target; - if (!(target instanceof HTMLElement)) return; - if ( - editing || - preview || - (target !== document.body && - target !== root.current && - !target.closest(".react-flow")) - ) + const pasteContent = async ( + snapshot: CanvasClipboardSnapshot, + visit: PasteDestination, + point?: Point, + ) => { + if (!canPasteInto(visit)) return; + const pastedId = canvasClipboardId(snapshot.html); + const id = pastedId && (clipboard.current?.id === pastedId || sharedCanvasClipboardId() === pastedId) + ? pastedId + : undefined; + if (id) { + try { + if (await pasteClipboard(id, visit)) return; + } catch (error) { + if (canPasteInto(visit)) + notify(t("canvas.workspace.toast.crossCanvasPasteFailed", { error: errorMessage(error) })); return; - if ( - target.closest( - "input,textarea,select,[contenteditable=true],[role=dialog]", - ) - ) + } + } + if (!canPasteInto(visit)) return; + + const importPastedFiles = (files: File[]) => { + if (!canPasteInto(visit)) return; + pasteOffset.current = { id: "", count: 0 }; + uploadTarget.current = null; + referenceTarget.current = null; + void importFiles(files, point); + }; + if (snapshot.files.length) { + importPastedFiles(snapshot.files); + return; + } + const image = clipboardHtmlImage(snapshot.html); + if (image) { + try { + const file = await loadClipboardImage(image, t("canvas.workspace.clipboard.imageName")); + importPastedFiles([file]); return; - if (event.clipboardData?.files.length) { - event.preventDefault(); - uploadTarget.current = null; - void importFiles([...event.clipboardData.files]); - } else if (isCanvasClipboard(event.clipboardData)) { - void paste(); + } catch { + if (!canPasteInto(visit)) return; + if (!snapshot.text.trim()) { + notify(t("canvas.workspace.toast.clipboardImageFailed")); + return; + } } + } + if (!snapshot.text.trim()) return; + if (snapshot.text.length > MAX_CLIPBOARD_TEXT_BYTES || + new TextEncoder().encode(snapshot.text).byteLength > MAX_CLIPBOARD_TEXT_BYTES) { + notify(t("canvas.workspace.toast.clipboardTextTooLong")); + return; + } + const before = historyRef.current.present; + const where = point ?? center(); + const node = createNode("text", { x: where.x - 150, y: where.y - 150 }, { + title: nextNodeTitle(before, "text", t("canvasNodes.kind.text")), + text: snapshot.text, + }); + pasteOffset.current = { id: "", count: 0 }; + commitPaste(before, applyCommand(before, { type: "add-nodes", nodes: [node] }), [node.id]); + }; + const paste = async (point?: Point) => { + if (readOnly || !ready || switchPending.current) return; + const visit = pasteDestination(); + let snapshot: CanvasClipboardSnapshot; + try { + snapshot = await readSystemClipboard(t("canvas.workspace.clipboard.imageName")); + } catch { + if (canPasteInto(visit)) + notify(t("canvas.workspace.toast.clipboardPasteShortcut", { + shortcut: navigator.platform.includes("Mac") ? "⌘V" : "Ctrl+V", + })); + return; + } + await pasteContent(snapshot, visit, point); + }; + + useEffect(() => { + const belongsToCanvas = (event: ClipboardEvent) => { + if (!rt.canvasVisible || event.defaultPrevented || !ready || switchPending.current || + editing || preview || rt.activeAction || rt.rename || rt.settingsOpen || rt.help) + return false; + const active = document.activeElement; + const target = event.target; + const editor = "textarea,select,[contenteditable]:not([contenteditable=false]),[role=dialog]"; + if (active?.closest(`input,${editor}`) || + (target instanceof Element && target.closest(`input:not([type=file]),${editor}`))) + return false; + const isCanvasElement = (element: Element) => + element === root.current || Boolean(root.current?.contains(element) && element.closest(".react-flow")); + if (!(active && isCanvasElement(active)) && + !(target instanceof Element && (target === document.body || isCanvasElement(target)))) + return false; + const selection = document.getSelection(); + const anchor = selection?.anchorNode; + const selectionElement = anchor instanceof Element ? anchor : anchor?.parentElement; + return !selection || selection.isCollapsed || Boolean(selectionElement?.closest(".react-flow")); + }; + const onCopy = (event: ClipboardEvent) => { + if (belongsToCanvas(event)) copy(event); + }; + const onCut = (event: ClipboardEvent) => { + if (event.isTrusted && !readOnly && belongsToCanvas(event)) cut(event); + }; + const onPaste = (event: ClipboardEvent) => { + if (readOnly || !belongsToCanvas(event) || !event.clipboardData) return; + const snapshot = snapshotClipboard(event.clipboardData); + if (!snapshot.files.length && !snapshot.html && !snapshot.text.trim()) return; + event.preventDefault(); + void pasteContent(snapshot, pasteDestination()); }; + window.addEventListener("copy", onCopy); + window.addEventListener("cut", onCut); window.addEventListener("paste", onPaste); return () => { + window.removeEventListener("copy", onCopy); + window.removeEventListener("cut", onCut); window.removeEventListener("paste", onPaste); }; }); @@ -996,6 +1166,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime, readOnly: boolean) { rt.copy = copy; rt.cut = cut; rt.paste = paste; + rt.duplicate = duplicate; rt.insertFragment = insertFragment; rt.group = group; rt.ungroup = ungroup; diff --git a/src/canvas/workspaceInteraction.ts b/src/canvas/workspaceInteraction.ts index 3c974c656..6f24c19d2 100644 --- a/src/canvas/workspaceInteraction.ts +++ b/src/canvas/workspaceInteraction.ts @@ -172,10 +172,8 @@ export type CanvasKeyAction = | { type: "edit-text" } | { type: "history"; forward: boolean } | { type: "select-all" } - | { type: "copy" } - | { type: "cut" } | { type: "reorder"; direction: "front" | "back" | "forward" | "backward" } - | { type: "paste"; duplicate: boolean } + | { type: "duplicate" } | { type: "group"; ungroup: boolean } | { type: "save" } | { type: "import" } @@ -192,7 +190,6 @@ export function canvasKeyAction(input: { code: string; mod: boolean; shift: boolean; - hasClipboard: boolean; editText: boolean; hasSingle: boolean; }): CanvasKeyAction | null { @@ -202,8 +199,6 @@ export function canvasKeyAction(input: { if (input.mod && key === "z") return { type: "history", forward: input.shift }; if (input.mod && key === "y") return { type: "history", forward: true }; if (input.mod && key === "a") return { type: "select-all" }; - if (input.mod && key === "c") return { type: "copy" }; - if (input.mod && key === "x") return { type: "cut" }; if ( input.mod && (input.code === "BracketLeft" || input.code === "BracketRight") @@ -219,9 +214,7 @@ export function canvasKeyAction(input: { ? "front" : "forward", }; - if (input.mod && key === "v" && input.hasClipboard) - return { type: "paste", duplicate: false }; - if (input.mod && key === "d") return { type: "paste", duplicate: true }; + if (input.mod && key === "d") return { type: "duplicate" }; if (input.mod && key === "g") return { type: "group", ungroup: input.shift }; if (input.mod && key === "s") return { type: "save" }; if (input.mod && key === "o") return { type: "import" }; diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index e1d835144..09a3024f5 100644 --- a/src/i18n/messages/en-US/canvasWorkspace.ts +++ b/src/i18n/messages/en-US/canvasWorkspace.ts @@ -233,6 +233,11 @@ export const canvasWorkspace = { other: "Copied {count} nodes", }, "canvas.workspace.toast.selectEditable": "Select an editable node first.", + "canvas.workspace.toast.clipboardWriteFailed": "Could not write to the system clipboard.", + "canvas.workspace.toast.clipboardPasteShortcut": "Use {shortcut} to paste from the clipboard.", + "canvas.workspace.toast.clipboardImageFailed": "Could not paste this image. Copy it as an image or save it and upload the file.", + "canvas.workspace.toast.clipboardTextTooLong": "The clipboard text exceeds the text node size limit.", + "canvas.workspace.clipboard.imageName": "Pasted image", "canvas.workspace.toast.clipboardLocalOnly": "Paste these nodes in this tab. Clipboard sharing is unavailable.", "canvas.workspace.toast.preparingClipboard": "Preparing nodes for cross-tab paste…", "canvas.workspace.toast.cutLocked": diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index 88a9ec018..20eb0eb02 100644 --- a/src/i18n/messages/zh-CN/canvasWorkspace.ts +++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts @@ -227,6 +227,11 @@ export const canvasWorkspace = { other: "已复制 {count} 个节点", }, "canvas.workspace.toast.selectEditable": "请先选择可编辑的节点。", + "canvas.workspace.toast.clipboardWriteFailed": "无法写入系统剪贴板。", + "canvas.workspace.toast.clipboardPasteShortcut": "请按 {shortcut} 从剪贴板粘贴。", + "canvas.workspace.toast.clipboardImageFailed": "无法粘贴此图片。请直接复制图片,或保存为文件后上传。", + "canvas.workspace.toast.clipboardTextTooLong": "剪贴板内容超出文本节点长度上限。", + "canvas.workspace.clipboard.imageName": "粘贴的图片", "canvas.workspace.toast.clipboardLocalOnly": "无法共享剪贴板,请在当前标签页粘贴这些节点。", "canvas.workspace.toast.preparingClipboard": "正在准备跨标签页粘贴…", "canvas.workspace.toast.cutLocked": "节点或其成员受锁定引用保护,未剪切。", diff --git a/tests/browser/canvas_system_clipboard.mjs b/tests/browser/canvas_system_clipboard.mjs new file mode 100644 index 000000000..24dee3525 --- /dev/null +++ b/tests/browser/canvas_system_clipboard.mjs @@ -0,0 +1,167 @@ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; +const modifier = process.platform === "darwin" ? "Meta" : "Control"; +const pasteShortcut = modifier === "Meta" ? "⌘V" : "Ctrl+V"; + +const health = await fetch(api + "/api/creation-test-health", { headers }); +assert.equal((await health.json()).isolated, true); + +const browser = await launchBrowser(); +try { + for (const language of [ + { locale: "en-US", saved: "Saved on this device", files: "Choose local asset files", paste: /^Paste/, shortcutHint: `Use ${pasteShortcut} to paste from the clipboard.`, largeTextHint: "The clipboard text exceeds the text node size limit." }, + { locale: "zh-CN", saved: "已保存到本机", files: "选择本地素材文件", paste: /^粘贴/, shortcutHint: `请按 ${pasteShortcut} 从剪贴板粘贴。`, largeTextHint: "剪贴板内容超出文本节点长度上限。" }, + ]) { + const projectId = crypto.randomUUID(); + const created = await fetch(api + `/api/creation/projects/${projectId}/commands`, { + method: "POST", + headers, + body: JSON.stringify({ + projectId, commandId: crypto.randomUUID(), type: "project.create", + payload: { name: `Clipboard ${language.locale} ${projectId}` }, + }), + }); + assert.ok(created.ok, await created.text()); + const context = await browser.newContext({ + locale: language.locale, + viewport: { width: 1500, height: 1000 }, + }); + await context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: base }); + const page = await context.newPage(); + await page.addInitScript(() => { + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + }); + await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`); + const saved = () => page.getByText(language.saved, { exact: true }).waitFor(); + await saved(); + + const workspace = page.locator(".cw-workspace"); + const nodes = page.locator(".react-flow__node"); + const image = nodes.locator("img.cw-image-preview"); + const png = await page.evaluate(() => { + const canvas = document.createElement("canvas"); + canvas.width = canvas.height = 32; + canvas.getContext("2d").fillRect(0, 0, 32, 32); + return canvas.toDataURL().split(",")[1]; + }); + await page.getByLabel(language.files, { exact: true }).setInputFiles({ + name: "copied-image.png", mimeType: "image/png", buffer: Buffer.from(png, "base64"), + }); + await image.waitFor(); + await saved(); + await workspace.focus(); + await page.keyboard.press(`${modifier}+a`); + await page.keyboard.press(`${modifier}+c`); + + const external = `External clipboard ${language.locale}`; + const input = page.locator("#source-clipboard-text"); + await page.evaluate((value) => { + const field = document.createElement("textarea"); + field.id = "source-clipboard-text"; + field.value = value; + document.body.append(field); + field.select(); + }, external); + await page.keyboard.press(`${modifier}+c`); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), external); + await workspace.focus(); + await page.keyboard.press(`${modifier}+v`); + const textNode = nodes.filter({ hasText: external }); + await textNode.waitFor({ timeout: 5000 }); + assert.equal(await image.count(), 1, "the old canvas copy must not replace external clipboard data"); + + await page.evaluate(() => navigator.clipboard.writeText("clipboard probe")); + await workspace.focus(); + await page.keyboard.press(`${modifier}+c`); + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), external); + await input.focus(); + await input.fill(""); + await page.keyboard.press(`${modifier}+v`); + assert.equal(await input.inputValue(), external); + assert.equal(await textNode.count(), 1, "pasting into an input must not add a canvas node"); + await input.evaluate((field) => field.remove()); + + await workspace.focus(); + await page.keyboard.press(`${modifier}+x`); + await textNode.waitFor({ state: "detached" }); + await page.keyboard.press(`${modifier}+v`); + await textNode.waitFor(); + + const mixed = `New text copied from a rich editor ${language.locale}`; + await page.evaluate(async (text) => { + const [item] = await navigator.clipboard.read(); + const canvasHtml = await (await item.getType("text/html")).text(); + await navigator.clipboard.write([new ClipboardItem({ + "text/html": new Blob([`${canvasHtml}

${text}

`], { type: "text/html" }), + "text/plain": new Blob([text], { type: "text/plain" }), + })]); + }, mixed); + await workspace.focus(); + await page.keyboard.press(`${modifier}+v`); + await nodes.filter({ hasText: mixed }).waitFor(); + assert.equal(await textNode.count(), 1, "mixed HTML must not revive an older canvas copy"); + + const menuText = `Paste from menu ${language.locale}`; + await page.evaluate((value) => navigator.clipboard.writeText(value), menuText); + await page.locator(".react-flow__pane").click({ button: "right", position: { x: 800, y: 220 } }); + await page.getByRole("menuitem", { name: language.paste }).click(); + await nodes.filter({ hasText: menuText }).waitFor(); + + await page.evaluate(async (base64) => { + const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0)); + await navigator.clipboard.write([new ClipboardItem({ + "image/png": new Blob([bytes], { type: "image/png" }), + })]); + }, png); + await workspace.focus(); + await page.keyboard.press(`${modifier}+v`); + await image.nth(1).waitFor(); + await page.evaluate(async (base64) => { + const html = ``; + await navigator.clipboard.write([new ClipboardItem({ + "text/html": new Blob([html], { type: "text/html" }), + })]); + }, png); + await workspace.focus(); + await page.keyboard.press(`${modifier}+v`); + await image.nth(2).waitFor(); + await saved(); + await page.reload(); + await saved(); + await nodes.filter({ hasText: menuText }).waitFor(); + await nodes.filter({ hasText: external }).waitFor(); + await image.nth(2).waitFor(); + + const nodeCount = await nodes.count(); + let saveRequests = 0; + const recordSave = (request) => { + if (request.method() === "POST" && new URL(request.url()).pathname.endsWith("/commands")) + saveRequests++; + }; + page.on("request", recordSave); + await page.evaluate(() => navigator.clipboard.writeText("界".repeat(350_000))); + await workspace.focus(); + await page.keyboard.press(`${modifier}+v`); + await page.getByText(language.largeTextHint, { exact: true }).first().waitFor({ timeout: 5000 }); + assert.equal(await nodes.count(), nodeCount); + assert.equal(saveRequests, 0); + page.off("request", recordSave); + + await page.evaluate(() => { + Object.defineProperty(navigator.clipboard, "read", { + value: () => Promise.reject(new DOMException("Clipboard access denied", "NotAllowedError")), + }); + }); + await page.locator(".react-flow__pane").click({ button: "right", position: { x: 800, y: 220 } }); + await page.getByRole("menuitem", { name: language.paste }).click(); + await page.getByText(language.shortcutHint, { exact: true }).first().waitFor(); + await context.close(); + } + console.log("PASS system clipboard: external text and images, canvas cut, native text editing and menu paste in both locales"); +} finally { + await browser.close(); +} diff --git a/tests/browser/cross_canvas_paste.mjs b/tests/browser/cross_canvas_paste.mjs index 0d928e9ee..91e1d06ad 100644 --- a/tests/browser/cross_canvas_paste.mjs +++ b/tests/browser/cross_canvas_paste.mjs @@ -7,6 +7,7 @@ import { launchBrowser } from "./engine.mjs"; import { chooseGenerationModel } from "./model_picker.mjs"; const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const modifier = process.platform === "darwin" ? "Meta" : "Control"; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; async function call(path, body) { const response = await fetch(api + path, { headers, ...(body ? { method: "POST", body: JSON.stringify(body) } : {}) }); @@ -82,9 +83,9 @@ try { await loadedImages(2); await page.locator(".cw-workspace").focus(); - await page.keyboard.press("Control+a"); + await page.keyboard.press(`${modifier}+a`); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node.selected").length === 2); - await page.keyboard.press("Control+c"); + await page.keyboard.press(`${modifier}+c`); // Switching closes the source client and revokes its preview URLs. await page.getByRole("button", { name: "Switch project", exact: true }).click(); await page.getByRole("menuitemradio", { name: target.name, exact: true }).click(); @@ -99,7 +100,7 @@ try { transfers.push(`${request.method()} ${path.replace(/^.*\/projects\/[^/]+/, "")}`); }; page.on("request", watch); - await page.keyboard.press("Control+v"); + await page.keyboard.press(`${modifier}+v`); await nodes.nth(1).waitFor(); await loadedImages(2); page.off("request", watch); @@ -117,7 +118,7 @@ try { assert.ok(pasted.assets.every((asset) => asset.projectId === target.id)); // Paste again: the copied media is registered once per target project. - await page.keyboard.press("Control+v"); + await page.keyboard.press(`${modifier}+v`); await until(async () => (await target.state()).canvasItems.filter((item) => item.visible).length === 4); await saved(); assert.equal((await target.state()).assets.length, 2); @@ -138,7 +139,6 @@ try { await otherTab.goto(`${base}/ai-tool/ai-canvas/${tabTarget.id}`); await savedInOtherTab(); await page.bringToFront(); - const modifier = process.platform === "darwin" ? "Meta" : "Control"; await page.evaluate(() => { const input = document.createElement("textarea"); input.id = "external-clipboard-fixture"; @@ -181,6 +181,7 @@ try { return images.length === 4 && images.every((image) => image.complete && image.naturalWidth > 0); }); if (artifacts) await otherTab.screenshot({ path: join(artifacts, "cross-tab-paste-after.png") }); + await context.grantPermissions(["clipboard-read"], { origin: base }); await otherTab.locator(".react-flow__pane").click({ button: "right", position: { x: 800, y: 220 } }); await otherTab.getByRole("menuitem", { name: /^粘贴/ }).click(); await until(async () => (await tabTarget.state()).canvasItems.filter((item) => item.visible).length === 8); diff --git a/tests/browser/heif_import.mjs b/tests/browser/heif_import.mjs index fe9abdd0b..a34c655dd 100644 --- a/tests/browser/heif_import.mjs +++ b/tests/browser/heif_import.mjs @@ -6,6 +6,7 @@ import { launchBrowser } from "./engine.mjs"; const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; const api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const clipboardModifier = process.platform === "darwin" ? "Meta" : "Control"; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; async function call(path, body) { const response = await fetch(api + path, { headers, @@ -249,7 +250,7 @@ try { await page.locator(".cw-timeline-dialog").waitFor({ state: "hidden" }); await page.locator(`.react-flow__node[data-id="${originalNode.id}"]`).click(); await page.locator(".cw-workspace").focus(); - await page.keyboard.press("Control+c"); + await page.keyboard.press(`${clipboardModifier}+c`); await page.getByRole("button", { name: "Switch project", exact: true }).click(); await page.getByRole("menuitemradio", { name: targetName, exact: true }).click(); await page.locator(".cw-project-name").filter({ hasText: targetName }).waitFor(); @@ -258,7 +259,7 @@ try { await page.route("**/uploads/*/copy", route => route.fulfill({ status: 404, contentType: "application/json", body: JSON.stringify({ detail: "Source unavailable" }) })); await page.locator(".cw-workspace").focus(); - await page.keyboard.press("Control+v"); + await page.keyboard.press(`${clipboardModifier}+v`); const pasted = await until(() => call(`/api/creation/projects/${targetId}`), value => value.canvasItems.length === 1 && value.assets.length === 1, "HEIF cross-project paste"); const pastedBytes = await fetch(`${api}/api/creation/projects/${targetId}/assets/${pasted.assets[0].id}/content`, { headers }); diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index fc5ca1dcc..9c7a36813 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -192,6 +192,11 @@ "file": "canvas_clipboard_order.mjs", "lanes": ["extended"] }, + { + "file": "canvas_system_clipboard.mjs", + "previewSafe": true, + "lanes": ["gate"] + }, { "file": "canvas_crop.mjs", "previewSafe": true, diff --git a/tests/browser/paste_undo.mjs b/tests/browser/paste_undo.mjs index 3b6cb4a3a..dbe6f0168 100644 --- a/tests/browser/paste_undo.mjs +++ b/tests/browser/paste_undo.mjs @@ -2,6 +2,7 @@ import assert from "node:assert/strict"; const { chromium } = await import(process.env.PLAYWRIGHT_MODULE ?? "playwright-core"); const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:8019"; +const modifier = process.platform === "darwin" ? "Meta" : "Control"; const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; const health = await fetch(base + "/api/creation-test-health", { headers }); assert.equal((await health.json()).isolated, true); @@ -37,20 +38,20 @@ try { await nodes.first().waitFor(); const source = await nodes.first().getAttribute("data-id"); await nodes.first().click(); - await page.keyboard.press("Control+c"); - await page.keyboard.press("Control+v"); - await page.keyboard.press("Control+v"); + await page.keyboard.press(`${modifier}+c`); + await page.keyboard.press(`${modifier}+v`); + await page.keyboard.press(`${modifier}+v`); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 3); - await page.keyboard.press("Control+z"); + await page.keyboard.press(`${modifier}+z`); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); assert.equal(await nodes.first().getAttribute("data-id"), source); - await page.keyboard.press("Control+z"); + await page.keyboard.press(`${modifier}+z`); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 1); assert.equal(await nodes.first().getAttribute("data-id"), source); const snapshot = await (await fetch(base + path, { headers })).json(); assert.deepEqual(snapshot.canvasItems.filter(item => item.visible).map(item => item.id), [source]); - await page.keyboard.press("Control+y"); + await page.keyboard.press(`${modifier}+y`); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); let release, started; const gate = new Promise((resolve) => { release = resolve; }); @@ -62,13 +63,13 @@ try { } await route.continue(); }); - await page.keyboard.press("Control+z"); + await page.keyboard.press(`${modifier}+z`); await held; const redone = page.waitForResponse((response) => response.url().endsWith("/commands") && response.request().postDataJSON()?.type === "history.redo", ); - await page.keyboard.press("Control+y"); + await page.keyboard.press(`${modifier}+y`); release(); assert.equal((await (await redone).json()).status, "applied"); await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); diff --git a/tests/canvasInteraction.test.ts b/tests/canvasInteraction.test.ts index 210c054b2..dda885f0b 100644 --- a/tests/canvasInteraction.test.ts +++ b/tests/canvasInteraction.test.ts @@ -44,7 +44,6 @@ const key = ( code: "", mod: false, shift: false, - hasClipboard: false, editText: false, hasSingle: false, ...patch, @@ -259,11 +258,9 @@ test("canvas shortcuts map to history, selection, import, and nudges", () => { assert.equal(key({ key: "o", mod: true })?.type, "import"); assert.equal(key({ key: "s", mod: true })?.type, "save"); assert.equal(key({ key: "v", mod: true })?.type, undefined); - assert.deepEqual(key({ key: "v", mod: true, hasClipboard: true }), { - type: "paste", - duplicate: false, - }); - assert.deepEqual(key({ key: "d", mod: true }), { type: "paste", duplicate: true }); + for (const clipboardKey of ["c", "x", "v"]) + assert.equal(key({ key: clipboardKey, mod: true }), null); + assert.deepEqual(key({ key: "d", mod: true }), { type: "duplicate" }); assert.deepEqual(key({ key: "g", code: "KeyG", mod: true, shift: true }), { type: "group", ungroup: true, diff --git a/tests/canvasSystemClipboard.test.ts b/tests/canvasSystemClipboard.test.ts new file mode 100644 index 000000000..d2212a485 --- /dev/null +++ b/tests/canvasSystemClipboard.test.ts @@ -0,0 +1,23 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { canvasClipboardId, clipboardHtmlImage } from "../src/canvas/canvasSystemClipboard.ts"; + +const id = "00000000-0000-4000-8000-000000000001"; +const marker = `Copied node`; + +test("clipboard HTML accepts a wrapped marker without interpreting it as a live document", () => { + const wrapped = `
${marker}
`; + assert.equal(canvasClipboardId(wrapped), id); + assert.equal(canvasClipboardId(`${wrapped}

External selection

`), undefined); +}); + +test("clipboard HTML extracts a single inline image and rejects mixed content", () => { + const image = ''; + assert.deepEqual(clipboardHtmlImage(`
${image}
`), { + kind: "inline", + mime: "image/png", + base64: "iVBORw0KGgo=", + }); + assert.equal(clipboardHtmlImage(`${image}

Caption

`), undefined); + assert.equal(clipboardHtmlImage(`${image}${image}`), undefined); +}); diff --git a/tests/clipboardMedia.test.ts b/tests/clipboardMedia.test.ts index 55a3af104..76cda736f 100644 --- a/tests/clipboardMedia.test.ts +++ b/tests/clipboardMedia.test.ts @@ -261,3 +261,38 @@ test("saved source assets are offered for a server-side copy", async () => { assert.equal(pasted.nodes[1]!.data.backendAssetId, "copy-of-镜头"); assert.equal(pasted.nodes[2]!.data.subject!.main!.assetId, "copy-of-正脸"); }); + +test("saved media can paste without copying bytes through the browser", async () => { + const video = createNode("video", undefined, { + src: "opendirector-asset://source/video", + backendAssetId: "video", + }); + const image = createNode("image", undefined, { + src: "opendirector-asset://source/image", + backendAssetId: "image", + }); + const fragment = { nodes: [video, image], edges: [] }; + const reads: string[] = []; + const media = captureClipboardMedia("source", fragment, { + read: async (src) => { + reads.push(src); + throw Error("Browser could not read the fallback bytes"); + }, + resolve: (_src, assetId) => assetId + ? { assetId, fingerprint: `sha256:${assetId}`, cacheBytes: assetId === "image" } + : undefined, + }); + const copies: string[] = []; + const registerSaved = async ({ assetId }: MediaSource) => { + copies.push(assetId); + return { assetId: `copy-of-${assetId}`, src: `opendirector-asset://target/copy-of-${assetId}` }; + }; + for (let attempt = 0; attempt < 2; attempt++) { + const pasted = await transferClipboardMedia(fragment, media, "target", async () => { + assert.fail("Server-side copy needs the saved handle only"); + }, registerSaved); + assert.deepEqual(pasted.nodes.map(({ data }) => data.backendAssetId), ["copy-of-video", "copy-of-image"]); + } + assert.deepEqual(reads, [image.data.src]); + assert.deepEqual(copies.sort(), ["image", "video"]); +});