Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
1 change: 1 addition & 0 deletions docs/development/validation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 状态和媒体提示;它是故障诊断检查,不是成功旅程。清除变量后恢复正常运行。布局断言必须等待预期资产的图片加载成功,不能以提示词出现代替预览就绪。
Expand Down
18 changes: 18 additions & 0 deletions packages/core/src/opendirector/application/creation_canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions scripts/run-browser-suite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
17 changes: 17 additions & 0 deletions src/backend/assetSource.ts
Original file line number Diff line number Diff line change
@@ -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;
}
82 changes: 80 additions & 2 deletions src/backend/creationClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
storageRequest,
} from "./api.ts";
import { tNow } from "../i18n/messages.ts";
import { parseAssetSource } from "./assetSource.ts";
import { abortable, resilientRead, type ReadOptions } from "./resilientRead.ts";

export type CreationOperation = BatchPayloadInput["operations"][number];
Expand Down Expand Up @@ -77,6 +78,10 @@
private subscription: AbortController | undefined;
private media = new Map<string, Promise<string>>();
private sourceAssets = new Map<string, string>();
/** Bytes behind each object URL. The desktop CSP does not allow fetching blob URLs. */
private mediaBytes = new Map<string, Blob>();
private unavailableMedia = new Set<string>();
private mediaListeners = new Set<() => void>();
private text = new Map<string, Promise<string>>();
private submissions: Promise<unknown> = Promise.resolve();
private deliveries = new Map<string, Record<string, unknown>>();
Expand Down Expand Up @@ -134,6 +139,7 @@
referenceId: string;
state: "used" | "pending" | "unknown" | "unavailable";
}[];
texts?: Record<string, string>;
}
| undefined;
for (let attempt = 0; ; attempt++) {
Expand All @@ -146,6 +152,7 @@
referenceId: string;
state: "used" | "pending" | "unknown" | "unavailable";
}[];
texts?: Record<string, string>;
}
>(`${creationPath(this.id)}/open-canvas`, { method: "POST" });
// The open-canvas response carries the one authoritative snapshot plus
Expand All @@ -158,6 +165,10 @@
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) {
Expand Down Expand Up @@ -313,7 +324,7 @@
while (!controller.signal.aborted) {
try {
const response = await fetch(
`/api${creationPath(this.id)}/subscribe?after=${this.snapshot.eventCursor}`,

Check warning

Code scanning / CodeQL

File data in outbound network request Medium

Outbound network request depends on
file data
.
{ headers, signal: controller.signal },
);
if (!response.ok || !response.body)
Expand Down Expand Up @@ -373,7 +384,7 @@
return resilientRead(
async (signal) => {
const response = await fetch(
`/api${creationPath(this.id)}/assets/${assetId}/${representation}`,

Check warning

Code scanning / CodeQL

File data in outbound network request Medium

Outbound network request depends on
file data
.
Outbound network request depends on file data.
Outbound network request depends on file data.
Outbound network request depends on file data.
Outbound network request depends on file data.
Outbound network request depends on file data.
Outbound network request depends on file data.
Outbound network request depends on file data.
{ headers, signal },
);
if (!response.ok) throw await responseError(response);
Expand All @@ -396,16 +407,35 @@
.then((blob) => {
const url = URL.createObjectURL(blob);
this.sourceAssets.set(url, assetId);
this.mediaBytes.set(assetId, blob);
this.markMedia(assetId, true);
return url;
})
.catch((error) => {
this.media.delete(assetId);
this.markMedia(assetId, false);
throw error;
});
this.media.set(assetId, pending);
}
return abortable(pending, options.signal);
}
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);
Expand All @@ -413,7 +443,7 @@
pending = resilientRead(
async (signal) => {
const response = await fetch(
`/api${creationPath(this.id)}/assets/${assetId}/thumbnail`,

Check warning

Code scanning / CodeQL

File data in outbound network request Medium

Outbound network request depends on
file data
.
{ headers, signal },
);
if (!response.ok) throw await responseError(response);
Expand Down Expand Up @@ -445,16 +475,37 @@
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<Blob> {
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 });

Check warning

Code scanning / CodeQL

File data in outbound network request Medium

Outbound network request depends on
file data
.
if (!response.ok) throw new Error(tNow("errors.archive.readMedia"));
return response.blob();
}
Expand Down Expand Up @@ -753,6 +804,8 @@
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();
}
Expand All @@ -768,6 +821,31 @@
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<Response> {
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,
Expand Down
56 changes: 46 additions & 10 deletions src/backend/creationProjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
};
}

Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
),
}
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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";
}
Expand Down Expand Up @@ -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"
Expand Down
3 changes: 2 additions & 1 deletion src/backend/imageSelections.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading