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/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/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({ >