diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.yml index 69c7927cd..98075b68d 100644 --- a/.github/workflows/desktop-release.yml +++ b/.github/workflows/desktop-release.yml @@ -67,15 +67,20 @@ jobs: codesign --verify --deep --strict "$app" - name: Build and smoke-test DMG run: | - staging="$RUNNER_TEMP/desktop-dmg" mount="$RUNNER_TEMP/desktop-mount" - mkdir -p "$staging" "$mount" release-assets - ditto apps/desktop/build/mac-arm64/OpenDirector.app "$staging/OpenDirector.app" - ln -s /Applications "$staging/Applications" + installer="$PWD/apps/desktop/installer/macos" + mkdir -p "$mount" release-assets dmg="OpenDirector-v${DESKTOP_VERSION}-mac-arm64-adhoc.dmg" - hdiutil create -volname OpenDirector -srcfolder "$staging" -format UDZO "release-assets/$dmg" + uv tool run --from 'dmgbuild==2.0.0' dmgbuild \ + -s "$installer/dmg-settings.py" \ + -D "app=$PWD/apps/desktop/build/mac-arm64/OpenDirector.app" \ + -D "background=$installer/background.png" \ + OpenDirector "release-assets/$dmg" hdiutil attach "release-assets/$dmg" -readonly -nobrowse -mountpoint "$mount" trap 'hdiutil detach "$mount"' EXIT + test -s "$mount/.DS_Store" + test -s "$mount/.background.tiff" + test "$(readlink "$mount/Applications")" = /Applications installed=$(mktemp -d "$RUNNER_TEMP/desktop-install.XXXXXX")/OpenDirector.app ditto "$mount/OpenDirector.app" "$installed" codesign --verify --deep --strict "$installed" diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index c1de28496..d2ca75cec 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -105,12 +105,13 @@ def open_project(project_id: UUID, x_opendirector_session: UUID = Header()): @router.post('/projects/{project_id}/open-canvas') def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header()): - # The canvas needs its reference edges on first render too. Reuse the + # The canvas needs its reference edges and text on first render too. Reuse the # single snapshot this open read already published instead of making the # page read the same project again through GET /canvas. The no-flag # route above still returns a bare ProjectSnapshot. snapshot = projects.open(project_id, str(x_opendirector_session)) - return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot)} + return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot), + 'texts': canvas.text_contents(snapshot)} @router.put('/sessions/{session_id}') def heartbeat(session_id: UUID, value: Session): diff --git a/apps/desktop/installer/macos/background.png b/apps/desktop/installer/macos/background.png new file mode 100644 index 000000000..34111e21f Binary files /dev/null and b/apps/desktop/installer/macos/background.png differ diff --git a/apps/desktop/installer/macos/background@2x.png b/apps/desktop/installer/macos/background@2x.png new file mode 100644 index 000000000..e32973300 Binary files /dev/null and b/apps/desktop/installer/macos/background@2x.png differ diff --git a/apps/desktop/installer/macos/dmg-settings.py b/apps/desktop/installer/macos/dmg-settings.py new file mode 100644 index 000000000..0c2e48534 --- /dev/null +++ b/apps/desktop/installer/macos/dmg-settings.py @@ -0,0 +1,20 @@ +from pathlib import Path + +app = Path(defines["app"]) +format = "UDZO" +filesystem = "APFS" +files = [str(app)] +symlinks = {"Applications": "/Applications"} + +# Keep presentation on the volume. Hiding the app extension adds Finder +# metadata to the signed bundle, which fails strict signature validation. +background = defines["background"] +window_rect = ((150, 150), (700, 410)) +icon_locations = {app.name: (190, 147), "Applications": (510, 147)} +icon_size = 90 +text_size = 13 +show_toolbar = False +show_tab_view = False +show_sidebar = False +show_pathbar = False +show_status_bar = False diff --git a/apps/desktop/scripts/smoke-window.mjs b/apps/desktop/scripts/smoke-window.mjs index 1cb6e35b0..4085b79d0 100644 --- a/apps/desktop/scripts/smoke-window.mjs +++ b/apps/desktop/scripts/smoke-window.mjs @@ -14,16 +14,13 @@ export async function smokeWindow({ window, host, getLocale }) { })()`); if (result.health.status !== 'ok' || result.projects !== 200 || !result.isolated || !result.bridge) throw new Error('Desktop smoke failed'); await waitFor(() => window.webContents.executeJavaScript('document.querySelectorAll("button").length > 2'), 'Workbench did not become interactive'); - if (process.platform === 'win32' && await window.webContents.executeJavaScript('!localStorage.getItem("opendirector.modelSetup.v1")')) { - await checkWindowsWelcomeCaption(window); + if (process.env.OPENDIRECTOR_DESKTOP_DATA && !process.env.OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT) { + if (process.platform === 'win32') await checkWindowsWelcomeCaption(window); + await completeWelcome(window); } - await window.webContents.executeJavaScript('document.querySelector(".cw-welcome-secondary")?.click()'); await waitFor(() => window.webContents.executeJavaScript('!!document.querySelector(".react-flow") && !!document.querySelector(".cw-save-status i.saved")'), 'Canvas did not open'); result.projectIds = await waitFor(() => window.webContents.executeJavaScript(`fetch('/api/creation/projects', {headers: {'X-OpenDirector-Request': '1'}}) .then(r => r.json()).then(value => value.projects.length ? value.projects.map(project => project.id).sort() : null)`), 'Canvas project was not persisted'); - await delay(500); - await window.webContents.executeJavaScript('document.querySelector(".cw-welcome-secondary")?.click()'); - await delay(300); if (await window.webContents.executeJavaScript('!!document.querySelector("dialog[open]")')) throw new Error('A dialog obscures the canvas'); if (process.platform === 'win32') await checkWindowsCaption(window); if (process.env.OPENDIRECTOR_DESKTOP_DATA) { @@ -31,18 +28,21 @@ export async function smokeWindow({ window, host, getLocale }) { ? result.projectIds[0] : process.env.OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT; if (result.projectIds.length === 1) await dropMedia(window); - const fingerprints = Object.fromEntries( - Object.entries({ image: 'png', video: 'mp4', audio: 'wav' }).map(([kind, extension]) => { - const bytes = readFileSync(join(process.env.OPENDIRECTOR_DESKTOP_DATA, `desktop-drop.${extension}`)); - return [kind, 'sha256:' + createHash('sha256').update(bytes).digest('hex')]; - }), - ); + const fingerprints = [ + ['image', 'desktop-drop.png'], + ['video', 'desktop-drop.mp4'], + ['audio', 'desktop-drop.wav'], + ['audio', 'desktop-welcome.wav'], + ].map(([kind, name]) => { + const bytes = readFileSync(join(process.env.OPENDIRECTOR_DESKTOP_DATA, name)); + return [kind, 'sha256:' + createHash('sha256').update(bytes).digest('hex')]; + }); let state; try { await waitFor(async () => { state = await droppedMediaState(window, projectId, fingerprints); return state.saved; - }, 'Dropped video, image and audio were not saved'); + }, 'Welcome import and dropped media were not saved'); } catch (error) { throw new Error(`${error.message}: ${JSON.stringify(state)}`, { cause: error }); } @@ -287,6 +287,38 @@ async function smokeLargeVideo(window, host, projectId, fixture, firstLaunch) { return binding; } +async function completeWelcome(window) { + const { webContents } = window; + for (const [selector, label, error] of [ + ['.cw-welcome-intro .cw-welcome-primary', null, 'Welcome did not offer Get started'], + ['.cw-welcome-connection-options > button:last-child', null, 'Welcome did not offer an existing harness'], + ['.cw-welcome-options > button', 'OpenCode', 'Bundled OpenCode was not available in Welcome'], + ]) { + await waitFor(() => webContents.executeJavaScript(`(() => { + const label = ${JSON.stringify(label)}; + const buttons = document.querySelectorAll(${JSON.stringify(`dialog.cw-welcome[open] ${selector}`)}); + const button = [...buttons].find(item => !item.disabled && (!label || item.querySelector('strong')?.textContent === label)); + if (!button) return false; + button.click(); + return true; + })()`), error); + } + const input = 'dialog.cw-welcome[open] input[type="file"]'; + await waitFor(() => webContents.executeJavaScript(`!!document.querySelector(${JSON.stringify(input)})`), 'Welcome did not reach the task chooser'); + const debuggerSession = webContents.debugger; + debuggerSession.attach(); + try { + const { root } = await debuggerSession.sendCommand('DOM.getDocument'); + const { nodeId } = await debuggerSession.sendCommand('DOM.querySelector', { nodeId: root.nodeId, selector: input }); + await debuggerSession.sendCommand('DOM.setFileInputFiles', { + nodeId, files: [join(process.env.OPENDIRECTOR_DESKTOP_DATA, 'desktop-welcome.wav')], + }); + } finally { + debuggerSession.detach(); + } + await waitFor(() => webContents.executeJavaScript('!document.querySelector("dialog.cw-welcome[open]")'), 'Welcome did not complete after importing media'); +} + async function dropMedia(window) { const { webContents } = window; const { x, y } = await webContents.executeJavaScript(`(() => { @@ -314,7 +346,7 @@ async function droppedMediaState(window, projectId, fingerprints) { }); if (!response.ok) return { status: response.status }; const { canvasItems, assets } = await response.json(); - const saved = Object.entries(${JSON.stringify(fingerprints)}).every(([kind, fingerprint]) => + const saved = ${JSON.stringify(fingerprints)}.every(([kind, fingerprint]) => canvasItems.some(item => item.kind === kind && item.binding.role === 'material' && assets.some(asset => asset.id === item.binding.objectRef.assetId && asset.kind === kind && asset.provenance.source === 'upload' && asset.fingerprint === fingerprint))); diff --git a/apps/desktop/scripts/smoke.mjs b/apps/desktop/scripts/smoke.mjs index e9be815ca..75bca79c3 100644 --- a/apps/desktop/scripts/smoke.mjs +++ b/apps/desktop/scripts/smoke.mjs @@ -1,9 +1,9 @@ -import { copyFile, mkdtemp, readFile, realpath, rm } from 'node:fs/promises'; +import { access, copyFile, mkdtemp, readFile, realpath, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { delimiter, dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { createLargeVideo } from './large-video.mjs'; -import { spawn } from 'node:child_process'; +import { execFileSync, spawn } from 'node:child_process'; const binary = process.argv[2]; if (!binary) throw new Error('Usage: node scripts/smoke.mjs /path/to/packaged/OpenDirector'); @@ -14,6 +14,12 @@ let mediaProject; let sidebarOpen = false; let largeVideo; try { + const runtime = resolve(dirname(binary), process.platform === 'darwin' ? '../Resources/runtime' : 'resources/runtime'); + const { python } = JSON.parse(await readFile(join(runtime, 'manifest.json'), 'utf8')); + // Give the isolated smoke process a real installed harness for the welcome flow. + const harnessBin = execFileSync(join(runtime, python), ['-I', '-B', '-X', 'utf8', '-c', + 'from opendirector.installation import BUNDLED; print(BUNDLED / "bin")'], { encoding: 'utf8' }).trim(); + await access(join(harnessBin, process.platform === 'win32' ? 'opencode.exe' : 'opencode')); const video = process.platform === 'win32' ? await createLargeVideo(join(directory, 'large-video.mp4')) : null; @@ -21,6 +27,7 @@ try { ['desktop-drop.mp4', '../../../tests/fixtures/timeline-text/visual-a.mp4'], ['desktop-drop.wav', '../../../tests/fixtures/timeline-text/audio-a.wav'], ['desktop-drop.png', '../../../src/assets/open_director_logo.png'], + ['desktop-welcome.wav', '../../../tests/fixtures/timeline-text/audio-b.wav'], ]; for (const [name, source] of fixtures) { await copyFile(fileURLToPath(new URL(source, import.meta.url)), join(directory, name)); @@ -29,6 +36,9 @@ try { const child = spawn(binary, ['--smoke'], { env: { ...process.env, + PATH: [harnessBin, process.env.PATH].filter(Boolean).join(delimiter), + OPENCODE_DISABLE_MODELS_FETCH: '1', + OPENCODE_PURE: '1', OPENDIRECTOR_DESKTOP_DATA: directory, OPENDIRECTOR_DESKTOP_SMOKE_LARGE_VIDEO: video ? JSON.stringify(video) : '', OPENDIRECTOR_DESKTOP_SMOKE_MEDIA_PROJECT: mediaProject ?? '', @@ -60,5 +70,5 @@ try { if (previous && JSON.stringify(previous) !== JSON.stringify(current)) throw new Error('Reopening changed the project identities'); previous = current; } - process.stdout.write('Packaged canvas, media drag-and-drop, authenticated API, isolation, both locales, hidden-window Host, reopen and sidebar preferences: passed\n'); + process.stdout.write('Packaged first run, canvas, media drag-and-drop, authenticated API, isolation, both locales, hidden-window Host, reopen and sidebar preferences: passed\n'); } finally { await rm(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } diff --git a/docs/development/validation.md b/docs/development/validation.md index 13c985ce6..b037e9bad 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -309,6 +309,7 @@ node tests/browser/reference_reconnect.mjs # 参考连线删除后重连 node tests/browser/context_menu_dismissal.mjs # 右键菜单关闭 node tests/browser/mp4_export.mjs # 合成 MP4(WebCodecs + 软件 AAC) node tests/browser/new_image_node_outputs.mjs # 新建图片节点采用所选适配器的比例与尺寸 +node tests/browser/canvas_progressive_load.mjs # 画布结构先可用,节点媒体独立加载、失败重试且不改写内容 ``` 历史版本预览回归([#393](https://github.com/ThinkFlowLab/OpenDirector/issues/393))沿用上述隔离服务:运行 `node tests/browser/node_versions.mjs`;设置 `HISTORY_PREVIEW_PROBE=delay` 会延迟目标缩略图一秒,完整旅程应通过。设置 `HISTORY_PREVIEW_PROBE=missing` 会注入缩略图 404,预期脚本失败并输出 `History preview unavailable`、目标资产 ID、HTTP 状态和媒体提示;它是故障诊断检查,不是成功旅程。清除变量后恢复正常运行。布局断言必须等待预期资产的图片加载成功,不能以提示词出现代替预览就绪。 diff --git a/docs/guides/installation.md b/docs/guides/installation.md index 92939cd1d..2a653b829 100644 --- a/docs/guides/installation.md +++ b/docs/guides/installation.md @@ -2,6 +2,26 @@ [English](installation.md) · [简体中文](installation.zh-CN.md) · [Back to README](../../README.md) + + +## First launch on macOS + +The desktop DMG is for Apple silicon Macs. Download it from [OpenDirector's official GitHub Releases](https://github.com/ThinkFlowLab/OpenDirector/releases). + +1. Open the DMG in Finder. Drag **OpenDirector** into **Applications**. +2. In Finder, open **Applications** and double-click **OpenDirector**. +3. This build is not notarized by Apple. If macOS says it can't verify OpenDirector or its developer, confirm that the DMG came from the official release. Dismiss the alert, then go to **System Settings → Privacy & Security**, scroll to **Security**, and click **Open Anyway** for OpenDirector. Follow the confirmation prompt. [Apple's first-launch instructions](https://support.apple.com/en-us/102445) + +If **Open Anyway** is missing, try opening OpenDirector from **Applications** once and return to **Privacy & Security**. If your organization manages the Mac, contact your administrator. + +If Finder can't open the DMG, download it again and compare its SHA-256 with the `.sha256` file next to that exact installer on GitHub Releases. Run `shasum -a 256` followed by the path to the downloaded DMG to print its checksum. If the DMG still won't open, report the exact message and the macOS version. + +If macOS says the **app** is damaged, reports malware, or says the app will damage your computer, stop and report the alert. + + + +## Install from source or a wheel + ### 1. Prepare your environment | Dependency | Requirement | diff --git a/docs/guides/installation.zh-CN.md b/docs/guides/installation.zh-CN.md index 121183388..6089683a0 100644 --- a/docs/guides/installation.zh-CN.md +++ b/docs/guides/installation.zh-CN.md @@ -2,6 +2,26 @@ [English](installation.md) · [简体中文](installation.zh-CN.md) · [返回首页](../../README.zh-CN.md) + + +## macOS 首次打开 + +桌面版 DMG 适用于搭载 Apple 芯片的 Mac。请从 [OpenDirector 官方 GitHub Releases](https://github.com/ThinkFlowLab/OpenDirector/releases) 下载安装包。 + +1. 在访达中打开 DMG,把 **OpenDirector** 拖入「应用程序」。 +2. 在访达的「应用程序」中双击 **OpenDirector**。 +3. 此版本未经 Apple 公证。若 macOS 提示无法验证 OpenDirector 或其开发者,先确认 DMG 来自官方 Release。关闭提示后,打开「系统设置 → 隐私与安全性」(部分版本称「隐私与安全」),向下滚动到「安全性」,找到 OpenDirector,点按「仍要打开」并按提示确认。[Apple 的首次打开说明](https://support.apple.com/zh-cn/102445) + +如果看不到「仍要打开」,请先从「应用程序」尝试打开 OpenDirector 一次,再回到「隐私与安全性」。如果 Mac 由单位管理,请联系管理员。 + +如果访达无法打开 DMG,请重新下载,并用 GitHub Releases 上对应安装包旁的 `.sha256` 文件核对校验值。在终端输入 `shasum -a 256` 和下载的 DMG 路径,即可查看校验值。如果 DMG 仍打不开,请反馈原始提示和 macOS 版本。 + +如果 macOS 提示 **App** 已损坏、识别到恶意软件,或提示 App 会损坏电脑,请停止并反馈原始提示。 + + + +## 通过源码或 wheel 安装 + ### 1. 准备环境 | 依赖 | 要求 | diff --git a/packages/core/src/opendirector/application/creation_assets.py b/packages/core/src/opendirector/application/creation_assets.py index fbee3f0ab..6b5b6948b 100644 --- a/packages/core/src/opendirector/application/creation_assets.py +++ b/packages/core/src/opendirector/application/creation_assets.py @@ -210,8 +210,10 @@ def open_media(self, project_id, asset_id, *, snapshot=None): with self.projects.local.transaction() as db: self.projects._recover() if snapshot is None: - path, _, records = self.projects._load(db, project_id) - snapshot = records[0].snapshot + # A head whose chain was already proven needs no replay per read. + path, manifest = self.projects._find(db, project_id) + record, validated = self.projects._current_record(db, project_id, path, manifest) + snapshot = (record if validated else self.projects._load(db, project_id)[2][0]).snapshot else: if snapshot.project.id != UUID(str(project_id)): raise ProjectError('素材读取快照不属于当前工程。', 409) diff --git a/packages/core/src/opendirector/application/creation_canvas.py b/packages/core/src/opendirector/application/creation_canvas.py index bac550dc1..a93ed0c98 100644 --- a/packages/core/src/opendirector/application/creation_canvas.py +++ b/packages/core/src/opendirector/application/creation_canvas.py @@ -826,6 +826,24 @@ def check_asset(asset): return check_asset + def text_contents(self, snapshot): + """Text shown by canvas items, read with the snapshot that opens the canvas. + + An unreadable body is left out so only that item reports it. + """ + contents = {} + for item in snapshot.canvasItems: + asset = current_asset(snapshot, item) + if asset is None or asset.kind != 'text' or str(asset.id) in contents: + continue + try: + stream, _ = self.assets.open_media(asset.projectId, asset.id, snapshot=snapshot) + with stream: + contents[str(asset.id)] = stream.read().decode('utf-8-sig', 'replace') + except (ContractError, ProjectError, OSError): + continue + return contents + def reference_edges(self, project_id, snapshot=None, check_asset=None): """Authoritative canvas reference states for one snapshot. diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index abf3ef9f8..a48f5a693 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -125,7 +125,7 @@ def reference_catalog(self, project_id): for asset in snapshot.assets: file_available = True try: - service.reference_available(project_id, asset.id) + service.reference_available(project_id, asset.id, snapshot=snapshot) except (ContractError, ProjectError, OSError, ValueError): file_available = False available = file_available and (asset.id in listed or asset.id in owners) diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index 7f1c43be0..9545f3f56 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -60,6 +60,10 @@ const workflows = [ name: "canvas switch", script: "tests/browser/canvas_switch.mjs", }, + { + name: "canvas progressive load", + script: "tests/browser/canvas_progressive_load.mjs", + }, { name: "structured editors", script: "tests/browser/structured_editors.mjs", diff --git a/src/backend/assetSource.ts b/src/backend/assetSource.ts new file mode 100644 index 000000000..93620c372 --- /dev/null +++ b/src/backend/assetSource.ts @@ -0,0 +1,17 @@ +/** A stable reference to a saved asset in a node's media fields. + * + * Object URLs depend on what this page has loaded, so they cannot describe + * project content. This value stays the same before and after the bytes arrive + * and is resolved only where media is displayed or read. */ +const PREFIX = "opendirector-asset://"; + +export const assetSource = (projectId: string, assetId: string) => + `${PREFIX}${projectId}/${assetId}`; + +export function parseAssetSource(src: string | null | undefined) { + if (!src?.startsWith(PREFIX)) return undefined; + const [projectId, assetId, extra] = src.slice(PREFIX.length).split("/"); + return projectId && assetId && extra === undefined + ? { projectId, assetId } + : undefined; +} diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index 3f769045a..5ece5164d 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -22,6 +22,8 @@ import { storageRequest, } from "./api.ts"; import { tNow } from "../i18n/messages.ts"; +import { parseAssetSource } from "./assetSource.ts"; +import { PriorityLimiter } from "./priorityLimiter.ts"; import { abortable, resilientRead, type ReadOptions } from "./resilientRead.ts"; export type CreationOperation = BatchPayloadInput["operations"][number]; @@ -36,6 +38,11 @@ export const assetReference = (asset: Asset): AssetRef => ({ kind: asset.kind, }); export const creationPath = (id: string) => `/creation/projects/${id}`; + +/** Leaves browser connections free for saves, opening a canvas and live events. */ +const MEDIA_READ_LIMIT = 3; +export const MEDIA_PRIORITY = { action: 0, visible: 1 } as const; +type MediaReadOptions = ReadOptions & { priority?: number }; const viewClientId = (() => { try { const key = "opendirector.creation.viewClientId"; @@ -77,6 +84,15 @@ export class CreationClient { private subscription: AbortController | undefined; private media = new Map>(); private sourceAssets = new Map(); + /** Bytes behind each object URL. The desktop CSP does not allow fetching blob URLs. */ + private mediaBytes = new Map(); + private readonly mediaReader = new PriorityLimiter(MEDIA_READ_LIMIT); + private mediaReads = new Map< + string, + { controller: AbortController; waiting: number; retained: boolean } + >(); + private unavailableMedia = new Set(); + private mediaListeners = new Set<() => void>(); private text = new Map>(); private submissions: Promise = Promise.resolve(); private deliveries = new Map>(); @@ -134,6 +150,7 @@ export class CreationClient { referenceId: string; state: "used" | "pending" | "unknown" | "unavailable"; }[]; + texts?: Record; } | undefined; for (let attempt = 0; ; attempt++) { @@ -146,6 +163,7 @@ export class CreationClient { referenceId: string; state: "used" | "pending" | "unknown" | "unavailable"; }[]; + texts?: Record; } >(`${creationPath(this.id)}/open-canvas`, { method: "POST" }); // The open-canvas response carries the one authoritative snapshot plus @@ -158,6 +176,10 @@ export class CreationClient { this.referenceStates = new Map( canvas.edges.map((edge) => [edge.referenceId, edge.state]), ); + // Text is part of what the structure shows, so projecting it never + // waits for a separate read per node. + for (const [assetId, text] of Object.entries(canvas?.texts ?? {})) + this.text.set(assetId, Promise.resolve(text)); this.install(canvas ? canvas.snapshot : (opened as ProjectSnapshot)); break; } catch (error) { @@ -362,7 +384,7 @@ export class CreationClient { } async blob( assetId: string, - options: ReadOptions & { browserImage?: boolean } = {}, + options: MediaReadOptions & { browserImage?: boolean; readKey?: string } = {}, ) { const mime = this.snapshot?.assets.find((asset) => asset.id === assetId) ?.metadata.mimeType; @@ -370,56 +392,133 @@ export class CreationClient { options.browserImage && (mime === "image/heic" || mime === "image/heif") ? "browser-image" : "content"; - return resilientRead( - async (signal) => { - const response = await fetch( - `/api${creationPath(this.id)}/assets/${assetId}/${representation}`, - { headers, signal }, - ); - if (!response.ok) throw await responseError(response); - return response.blob(); + return this.mediaReader.run( + () => + resilientRead( + async (signal) => { + const response = await fetch( + `/api${creationPath(this.id)}/assets/${assetId}/${representation}`, + { headers, signal }, + ); + if (!response.ok) throw await responseError(response); + return response.blob(); + }, + { timeoutMs: 120_000, attempts: 3, ...options }, + ), + { + priority: options.priority ?? MEDIA_PRIORITY.action, + key: options.readKey, + signal: options.signal, }, - { timeoutMs: 120_000, attempts: 3, ...options }, ); } - mediaUrl(assetId: string, options: ReadOptions = {}) { + mediaUrl(assetId: string, options: MediaReadOptions = {}) { options.signal?.throwIfAborted(); + const priority = options.priority ?? MEDIA_PRIORITY.action; let pending = this.media.get(assetId); - if (!pending) { - // Cached reads have their own bounded lifetime. Cancelling one history - // consumer must not abort the same media read used by the visible node. - pending = this.blob(assetId, { + if (pending) this.mediaReader.prioritize(assetId, priority); + else { + const read = { + controller: new AbortController(), + waiting: 0, + retained: false, + }; + this.mediaReads.set(assetId, read); + const started: Promise = this.blob(assetId, { ...options, - signal: undefined, + priority, + readKey: assetId, + signal: read.controller.signal, browserImage: true, }) .then((blob) => { const url = URL.createObjectURL(blob); this.sourceAssets.set(url, assetId); + this.mediaBytes.set(assetId, blob); + if (this.mediaReads.get(assetId) === read) + this.mediaReads.delete(assetId); + this.markMedia(assetId, true); return url; }) .catch((error) => { - this.media.delete(assetId); + if (this.mediaReads.get(assetId) === read) + this.mediaReads.delete(assetId); + if (this.media.get(assetId) === started) this.media.delete(assetId); + // Nobody needing this read any more says nothing about the file. + if (!read.controller.signal.aborted) this.markMedia(assetId, false); throw error; }); - this.media.set(assetId, pending); + pending = started; + this.media.set(assetId, started); } + this.holdMediaRead( + assetId, + pending, + priority === MEDIA_PRIORITY.visible ? options.signal : undefined, + ); return abortable(pending, options.signal); } + /** Only on-screen display can abandon a shared read, once every such consumer + * has left. Other callers keep it, so cancelling one history consumer never + * aborts the media another consumer is about to use. */ + private holdMediaRead( + assetId: string, + pending: Promise, + signal?: AbortSignal, + ) { + const read = this.mediaReads.get(assetId); + if (!read) return; + if (!signal) { + read.retained = true; + return; + } + read.waiting += 1; + const release = () => { + read.waiting -= 1; + if (read.waiting || read.retained || this.mediaReads.get(assetId) !== read) + return; + this.mediaReads.delete(assetId); + if (this.media.get(assetId) === pending) this.media.delete(assetId); + read.controller.abort(signal.reason); + }; + signal.addEventListener("abort", release, { once: true }); + const settled = () => signal.removeEventListener("abort", release); + pending.then(settled, settled); + } + private markMedia(assetId: string, available: boolean) { + if (available === !this.unavailableMedia.has(assetId)) return; + if (available) this.unavailableMedia.delete(assetId); + else this.unavailableMedia.add(assetId); + for (const listener of this.mediaListeners) listener(); + } + /** Whether the last read of this asset's media failed. */ + mediaUnavailable(assetId: string) { + return this.unavailableMedia.has(assetId); + } + listenMedia(listener: () => void) { + this.mediaListeners.add(listener); + return () => { + this.mediaListeners.delete(listener); + }; + } thumbnailUrl(assetId: string) { const key = `thumbnail:${assetId}`; let pending = this.media.get(key); if (!pending) { - pending = resilientRead( - async (signal) => { - const response = await fetch( - `/api${creationPath(this.id)}/assets/${assetId}/thumbnail`, - { headers, signal }, - ); - if (!response.ok) throw await responseError(response); - return URL.createObjectURL(await response.blob()); - }, - { timeoutMs: 120_000, attempts: 3 }, + pending = this.mediaReader.run( + () => + resilientRead( + async (signal) => { + const response = await fetch( + `/api${creationPath(this.id)}/assets/${assetId}/thumbnail`, + { headers, signal }, + ); + if (!response.ok) throw await responseError(response); + return URL.createObjectURL(await response.blob()); + }, + { timeoutMs: 120_000, attempts: 3 }, + ), + { priority: MEDIA_PRIORITY.visible }, ).catch((error) => { this.media.delete(key); throw error; @@ -445,15 +544,36 @@ export class CreationClient { this.sourceAssets.set(src, assetId); } assetForSource(src: string) { - const id = this.sourceAssets.get(src); + const source = parseAssetSource(src); + const id = + source?.projectId === this.id + ? source.assetId + : this.sourceAssets.get(src); return this.snapshot.assets.find((asset) => asset.id === id); } - async originalMedia(src: string, mimeType?: string, signal?: AbortSignal) { + async originalMedia( + src: string, + mimeType?: string, + signal?: AbortSignal, + ): Promise { + const source = parseAssetSource(src); + if (source && source.projectId !== this.id) + return creationClient(source.projectId).originalMedia(src, mimeType, signal); const asset = this.assetForSource(src); if (asset && ["image/heic", "image/heif"].includes(asset.metadata.mimeType)) return this.blob(asset.id, { signal }); if (["image/heic", "image/heif"].includes(mimeType ?? "")) throw new Error(tNow("errors.archive.readMedia")); + if (source) { + // A saved asset that is not on screen is read without retaining a preview. + if (!this.media.has(source.assetId)) + return this.blob(source.assetId, { signal }); + await this.mediaUrl(source.assetId, { signal }); + return ( + this.mediaBytes.get(source.assetId) ?? + this.blob(source.assetId, { signal }) + ); + } const response = await fetch(src, { signal }); if (!response.ok) throw new Error(tNow("errors.archive.readMedia")); return response.blob(); @@ -750,9 +870,13 @@ export class CreationClient { } close() { this.subscription?.abort(); + for (const read of this.mediaReads.values()) read.controller.abort(); + this.mediaReads.clear(); for (const pending of this.media.values()) void pending.then(URL.revokeObjectURL, () => {}); this.media.clear(); + this.mediaBytes.clear(); + this.unavailableMedia.clear(); this.sourceAssets.clear(); this.text.clear(); } @@ -768,6 +892,31 @@ export const creationClient = (id: string) => { return client; }; +/** The browser URL for a media field. Inline and object URLs are returned as is. */ +export async function resolveMediaSource(src: string, signal?: AbortSignal) { + const source = parseAssetSource(src); + return source + ? creationClient(source.projectId).mediaUrl(source.assetId, { signal }) + : src; +} + +/** Reads a media field. A saved asset is read through its project, and an + * object URL is read immediately, before its owner can revoke it. */ +export function fetchMediaSource( + src: string, + init?: RequestInit & { signal?: AbortSignal }, +): Promise { + const source = parseAssetSource(src); + return source + ? creationClient(source.projectId) + .originalMedia(src, undefined, init?.signal) + .then( + (blob) => + new Response(blob, { headers: { "Content-Type": blob.type } }), + ) + : fetch(src, init); +} + export function currentAsset( snapshot: ProjectSnapshot, item: CanvasItem, diff --git a/src/backend/creationProjection.ts b/src/backend/creationProjection.ts index d6975ba06..e68ed479c 100644 --- a/src/backend/creationProjection.ts +++ b/src/backend/creationProjection.ts @@ -46,6 +46,7 @@ import { visibleItems, type CreationOperation, } from "./creationClient.ts"; +import { assetSource } from "./assetSource.ts"; import { sameJsonValue } from "./sameJsonValue.ts"; import { classifyImportFile, readEditorResource } from "../canvas/editorMedia.ts"; @@ -125,7 +126,7 @@ export class CreationProjection { byteSize: asset.metadata.size, kind: asset.kind as CanvasResource["kind"], title: title ?? asset.name, - src: await this.client.mediaUrl(asset.id).catch(() => undefined), + src: assetSource(this.client.id, asset.id), mimeType: asset.metadata.mimeType, width: asset.metadata.width ?? undefined, height: asset.metadata.height ?? undefined, @@ -244,9 +245,7 @@ export class CreationProjection { title: title ?? asset?.name ?? ref.assetId, asset: { ...ref }, mimeType: asset?.metadata.mimeType ?? "application/octet-stream", - src: asset - ? await this.client.mediaUrl(asset.id).catch(() => undefined) - : undefined, + src: asset ? assetSource(this.client.id, asset.id) : undefined, }; } @@ -395,7 +394,8 @@ export class CreationProjection { ? { name: doc.data.palette.name ?? undefined, sourceImageUri: doc.data.palette.sourceImage - ? await this.client.mediaUrl( + ? assetSource( + this.client.id, doc.data.palette.sourceImage.assetId, ) : undefined, @@ -431,7 +431,8 @@ export class CreationProjection { kind: "image" as const, width: layer.content.width, height: layer.content.height, - src: await this.client.mediaUrl( + src: assetSource( + this.client.id, layer.content.asset.assetId, ), } @@ -443,7 +444,7 @@ export class CreationProjection { case "image_crop": return { imageCrop: { - src: await this.client.mediaUrl(doc.data.source.assetId), + src: assetSource(this.client.id, doc.data.source.assetId), options: doc.data.options, width: doc.data.width, height: doc.data.height, @@ -565,6 +566,32 @@ export class CreationProjection { }; } + /** Media availability is a read result, so it updates a view without an edit. */ + withMediaAvailability(document: CanvasDocument): CanvasDocument { + const update = (nodes: CanvasNode[]) => { + let changed = false; + const next = nodes.map((node) => { + if ( + !node.data.backendAssetId || + !["image", "video", "audio"].includes(node.type) + ) + return node; + const assetState = this.client.mediaUnavailable(node.data.backendAssetId) + ? ("missing" as const) + : ("ready" as const); + if (node.data.assetState === assetState) return node; + changed = true; + return { ...node, data: { ...node.data, assetState } }; + }); + return changed ? next : nodes; + }; + const nodes = update(document.nodes); + const hiddenNodes = document.hiddenNodes && update(document.hiddenNodes); + return nodes === document.nodes && hiddenNodes === document.hiddenNodes + ? document + : { ...document, nodes, ...(hiddenNodes ? { hiddenNodes } : {}) }; + } + private rememberProjection( snapshot: ProjectSnapshot, document: CanvasDocument, @@ -617,8 +644,10 @@ export class CreationProjection { try { if (asset.kind === "text") node.data.text = await this.client.textContent(asset.id); - else node.data.src = await this.client.mediaUrl(asset.id); - node.data.assetState = "ready"; + else node.data.src = assetSource(snapshot.project.id, asset.id); + node.data.assetState = this.client.mediaUnavailable(asset.id) + ? "missing" + : "ready"; } catch { node.data.assetState = "missing"; } @@ -1405,7 +1434,14 @@ export class CreationProjection { ? node.data.text !== undefined && node.data.text !== old?.data.text && (!!node.data.text || !!old?.data.text) - : !!node.data.src && node.data.src !== old?.data.src; + : !!node.data.src && + node.data.src !== old?.data.src && + // The same saved asset can arrive through another of its URLs. + !( + item && + this.client.assetForSource(node.data.src)?.id === + currentAsset(basis, item)?.id + ); if (materialChanged) { const previous = item && node.type === "text" diff --git a/src/backend/imageSelections.ts b/src/backend/imageSelections.ts index e73aaa9a0..0d12407b6 100644 --- a/src/backend/imageSelections.ts +++ b/src/backend/imageSelections.ts @@ -3,6 +3,7 @@ import type { BackendAsset } from "./generation.ts"; import { requireActiveBackendProject } from "./projects.ts"; import { uploadAsset, type ToolSourceInput } from "./tools.ts"; import { tNow } from "../i18n/messages.ts"; +import { fetchMediaSource } from "./creationClient.ts"; export interface ImageSelectionBox { x: number; @@ -46,7 +47,7 @@ export async function previewImageSelection( signal.throwIfAborted(); let sourceAssetId = value.sourceAssetId; if (!sourceAssetId) { - const response = await fetch(value.source.src, { signal }); + const response = await fetchMediaSource(value.source.src, { signal }); if (!response.ok) throw new Error(tNow("errors.backend.imageRead")); sourceAssetId = await uploadAsset( diff --git a/src/backend/priorityLimiter.ts b/src/backend/priorityLimiter.ts new file mode 100644 index 000000000..1f9e2984e --- /dev/null +++ b/src/backend/priorityLimiter.ts @@ -0,0 +1,71 @@ +type Job = { key?: string; priority: number; start: () => void }; + +/** Runs reads with a fixed concurrency. Lower priority numbers start first, and + * jobs with equal priority keep their order. */ +export class PriorityLimiter { + private readonly queue: Job[] = []; + private active = 0; + private readonly limit: number; + + constructor(limit: number) { + this.limit = limit; + } + + run( + task: () => Promise, + { + priority = 0, + key, + signal, + }: { priority?: number; key?: string; signal?: AbortSignal } = {}, + ): Promise { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason); + return; + } + const cancel = () => { + this.queue.splice(this.queue.indexOf(job), 1); + reject(signal!.reason); + }; + const job: Job = { + key, + priority, + start: () => { + signal?.removeEventListener("abort", cancel); + this.active += 1; + void Promise.resolve() + .then(task) + .then(resolve, reject) + .finally(() => { + this.active -= 1; + this.drain(); + }); + }, + }; + signal?.addEventListener("abort", cancel, { once: true }); + this.enqueue(job); + this.drain(); + }); + } + + /** Moves a queued job forward when a more urgent consumer needs it. */ + prioritize(key: string, priority: number) { + const index = this.queue.findIndex((job) => job.key === key); + if (index < 0 || this.queue[index]!.priority <= priority) return; + const [job] = this.queue.splice(index, 1); + job!.priority = priority; + this.enqueue(job!); + } + + private enqueue(job: Job) { + const index = this.queue.findIndex((item) => item.priority > job.priority); + if (index < 0) this.queue.push(job); + else this.queue.splice(index, 0, job); + } + + private drain() { + while (this.active < this.limit && this.queue.length) + this.queue.shift()!.start(); + } +} diff --git a/src/canvas/AssistantMedia.tsx b/src/canvas/AssistantMedia.tsx index 7bb153465..cb5fffbef 100644 --- a/src/canvas/AssistantMedia.tsx +++ b/src/canvas/AssistantMedia.tsx @@ -1,11 +1,12 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import type { ChatAsset } from "../backend/chat"; -import { creationClient } from "../backend/creationClient"; +import { assetSource } from "../backend/assetSource.ts"; import { useT } from "../i18n/I18nProvider.tsx"; import { CanvasIcon } from "./CanvasIcon"; import { useCanvasPlayback } from "./CanvasMediaPreview"; import { formatMediaTime } from "./mediaPlayback"; import { assetDisplayName } from "./assetNames"; +import { useAssetMedia } from "./useAssetMedia.tsx"; function mediaKind(asset: ChatAsset) { if (asset.type.startsWith("image/") || /\.(png|jpe?g|webp|gif|avif)$/i.test(asset.name)) return "image"; @@ -14,16 +15,9 @@ function mediaKind(asset: ChatAsset) { return "text"; } function useMediaSource(projectId: string, asset: ChatAsset, active: boolean) { - const [src, setSrc] = useState(""); + const media = useAssetMedia(mediaKind(asset) === "text" ? undefined : assetSource(projectId, asset.id), active); const [failed, setFailed] = useState(false); - useEffect(() => { - if (!active || mediaKind(asset) === "text") return; - let current = true; - creationClient(projectId).mediaUrl(asset.id).then(value => {if (current) setSrc(value);}) - .catch(() => {if (current) setFailed(true);}); - return () => {current = false;}; - }, [projectId, asset.id, asset.fingerprint, active]); - return {src, failed, setFailed}; + return {src: media.src ?? "", failed: failed || media.state === "failed", setFailed}; } function AttachmentCard({ projectId, asset }: {projectId: string; asset: ChatAsset}) { diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index d9a80f845..a8df8835a 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -41,6 +41,7 @@ import { useProjectMentionAssets } from "./useProjectMentionAssets"; import { useReferenceUploads } from "./useReferenceUploads.tsx"; import { useT } from "../i18n/I18nProvider.tsx"; import type { MessageKey } from "../i18n/types.ts"; +import { AssetMedia } from "./useAssetMedia.tsx"; function kindOf(asset: ChatAsset) { return asset.type.startsWith("image/") @@ -578,7 +579,7 @@ export function AssistantPanel({ title={item.error ?? item.title} > {item.thumbnail && !item.error ? ( - + ) : ( )} diff --git a/src/canvas/CanvasMediaPreview.tsx b/src/canvas/CanvasMediaPreview.tsx index 41cd1eaca..ce6838b62 100644 --- a/src/canvas/CanvasMediaPreview.tsx +++ b/src/canvas/CanvasMediaPreview.tsx @@ -10,6 +10,7 @@ import { type ReactNode, } from "react"; import { VideoControls } from "./CanvasVideoControls"; +import { useAssetMedia } from "./useAssetMedia.tsx"; /** Milliseconds a pointer must rest on a node before preview playback starts. */ const HOVER_PLAY_DELAY_MS = 300; @@ -77,6 +78,7 @@ export function CanvasVideoPreview({ ...props }: CanvasVideoPreviewProps) { const playback = useContext(Playback); + const resolved = useAssetMedia(props.src); const element = useRef(null); const wrapper = useRef(null); const [hovered, setHovered] = useState(false); @@ -255,6 +257,7 @@ export function CanvasVideoPreview({ >