e.stopPropagation()}>
{preview.type === "image" && preview.data.src ? (
-

+
) : preview.type === "video" && preview.data.src ? (
-
+
) : preview.type === "audio" && preview.data.src ? (
-
+
) : (
{preview.data.text ||
diff --git a/src/canvas/workspace/useWorkspaceDocument.ts b/src/canvas/workspace/useWorkspaceDocument.ts
index 52e37c656..a3b9e837e 100644
--- a/src/canvas/workspace/useWorkspaceDocument.ts
+++ b/src/canvas/workspace/useWorkspaceDocument.ts
@@ -609,6 +609,23 @@ export function useWorkspaceDocument(rt: WorkspaceRuntime) {
unsubscribe();
};
}, [doc.id, ready, notify, historyRenderVersion]);
+ useEffect(() => {
+ if (!ready) return;
+ const projection = workspaceProjection(doc.id);
+ return creationClient(doc.id).listenMedia(() => {
+ if (projection.baseline)
+ projection.baseline = projection.withMediaAvailability(projection.baseline);
+ const apply = (document: CanvasDocument) =>
+ document.id === doc.id ? projection.withMediaAvailability(document) : document;
+ setHistory((history) => ({
+ ...history,
+ present: apply(history.present),
+ past: history.past.map(apply),
+ future: history.future.map(apply),
+ transaction: history.transaction ? apply(history.transaction) : null,
+ }));
+ });
+ }, [doc.id, ready]);
useEffect(() => {
if (!ready) return;
let active = true,
diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts
index e969d9839..6cab05ebe 100644
--- a/src/canvas/workspace/useWorkspaceTransfer.ts
+++ b/src/canvas/workspace/useWorkspaceTransfer.ts
@@ -53,6 +53,7 @@ import { importedNodeIds, uploadPickerPlan, uploadTargetUnchanged } from "./entr
import { assertUpload } from "../uploadPolicy.ts";
import { prefetchLibrary } from "../library/libraryPrefetch";
import type { WorkspaceRuntime } from "./runtimeTypes.ts";
+import { parseAssetSource } from "../../backend/assetSource.ts";
export function useWorkspaceTransfer(rt: WorkspaceRuntime) {
const {
@@ -567,7 +568,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime) {
try {
if (node.data.src)
downloadFile(
- ["image/heic", "image/heif"].includes(node.data.mimeType ?? "")
+ ["image/heic", "image/heif"].includes(node.data.mimeType ?? "") || parseAssetSource(node.data.src)
? await creationClient(historyRef.current.present.id).originalMedia(node.data.src, node.data.mimeType)
: node.data.src,
downloadFilename(node.data.title, node.data.mimeType),
@@ -606,7 +607,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime) {
members.map(async (node) => {
let blob: Blob;
if (node.data.src) {
- const source = ["image/heic", "image/heif"].includes(node.data.mimeType ?? "")
+ const source = ["image/heic", "image/heif"].includes(node.data.mimeType ?? "") || parseAssetSource(node.data.src)
? await creationClient(document.id).originalMedia(node.data.src, node.data.mimeType)
: node.data.src;
if (source instanceof Blob) blob = source;
diff --git a/src/i18n/messages/en-US/canvasNodes.ts b/src/i18n/messages/en-US/canvasNodes.ts
index 17cba2543..a9e04b7f2 100644
--- a/src/i18n/messages/en-US/canvasNodes.ts
+++ b/src/i18n/messages/en-US/canvasNodes.ts
@@ -21,6 +21,9 @@ export const canvasNodes = {
"canvasNodes.file.local": "Local file",
"canvasNodes.file.open": "Open preview",
"canvasNodes.upload.missing": "Media not found. Choose it again.",
+ "canvasNodes.media.loading": "Loading media",
+ "canvasNodes.media.failed": "Could not load media",
+ "canvasNodes.media.retry": "Retry",
"canvasNodes.upload.aria": "Upload {kind}",
"canvasNodes.upload.local": "Upload from computer",
diff --git a/src/i18n/messages/zh-CN/canvasNodes.ts b/src/i18n/messages/zh-CN/canvasNodes.ts
index 4113439f6..85722941b 100644
--- a/src/i18n/messages/zh-CN/canvasNodes.ts
+++ b/src/i18n/messages/zh-CN/canvasNodes.ts
@@ -21,6 +21,9 @@ export const canvasNodes = {
"canvasNodes.file.local": "本地文件",
"canvasNodes.file.open": "打开预览",
"canvasNodes.upload.missing": "素材未找到,请重新选择",
+ "canvasNodes.media.loading": "素材加载中",
+ "canvasNodes.media.failed": "素材加载失败",
+ "canvasNodes.media.retry": "重试",
"canvasNodes.upload.aria": "上传{kind}",
"canvasNodes.upload.local": "本地上传",
diff --git a/tests/browser/canvas_progressive_load.mjs b/tests/browser/canvas_progressive_load.mjs
new file mode 100644
index 000000000..1c5ae22d5
--- /dev/null
+++ b/tests/browser/canvas_progressive_load.mjs
@@ -0,0 +1,183 @@
+/** Isolated fixture only: canvas structure first, independent node media, retained content. */
+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 headers = { "X-OpenDirector-Request": "1" };
+const health = await fetch(`${base}/api/creation-test-health`, { headers });
+assert.ok(health.ok && (await health.json()).isolated, "Requires an isolated creation API");
+
+const copy = {
+ "en-US": { loading: "Loading media", failed: "Could not load media", retry: "Retry", picker: "Switch project" },
+ "zh-CN": { loading: "素材加载中", failed: "素材加载失败", retry: "重试", picker: "切换项目" },
+};
+const snapshot = async (id) =>
+ (await fetch(`${base}/api/creation/projects/${id}`, { headers })).json();
+const assetOf = (project, itemId) =>
+ project.canvasItems.find((item) => item.id === itemId).binding.objectRef.assetId;
+const itemOf = (project, itemId) =>
+ project.canvasItems.find((item) => item.id === itemId);
+
+async function seedProjects(browser) {
+ const seed = await browser.newPage({ locale: "en-US" });
+ await seed.route((url) => url.pathname === "/", (route) =>
+ route.fulfill({ contentType: "text/html", body: "
" }));
+ await seed.goto(`${base}/`);
+ const fixture = await seed.evaluate(async () => {
+ const { createDocument, createNode } = await import("/src/canvas/model.ts");
+ const { importWorkspaceDocument } = await import("/src/backend/workspace.ts");
+ const { releaseBackendProject } = await import("/src/backend/projects.ts");
+ const picture = (hue) => {
+ const canvas = document.createElement("canvas");
+ canvas.width = canvas.height = 96;
+ const context = canvas.getContext("2d");
+ context.fillStyle = `hsl(${hue},60%,45%)`;
+ context.fillRect(0, 0, 96, 96);
+ return canvas.toDataURL("image/png");
+ };
+ const image = (title, x, hue) =>
+ createNode("image", { x, y: 80 }, {
+ title, mediaRole: "asset", src: picture(hue), mimeType: "image/png", assetState: "ready",
+ });
+ const suffix = crypto.randomUUID().slice(0, 8);
+ const first = createDocument(`Progressive A ${suffix}`);
+ const delayed = image("Delayed", 40, 10 + Math.random() * 40);
+ const failed = image("Failed", 460, 90 + Math.random() * 40);
+ const ready = image("Ready", 880, 170 + Math.random() * 40);
+ const hidden = image("Hidden", 40, 250 + Math.random() * 40);
+ const text = createNode("text", { x: 40, y: 520 }, { title: "Words", text: "Authoritative text" });
+ const far = image("Far", 3000, 45 + Math.random() * 20);
+ first.nodes = [delayed, failed, ready, text, far];
+ first.hiddenNodes = [hidden];
+ const second = createDocument(`Progressive B ${suffix}`);
+ const other = image("Other", 40, 320 + Math.random() * 30);
+ second.nodes = [other];
+ const a = await importWorkspaceDocument(first);
+ // A saved viewport keeps the far node off screen when the canvas opens.
+ const { creationClient } = await import("/src/backend/creationClient.ts");
+ await creationClient(a.id).view({ viewport: { x: 0, y: 0, zoom: 1 } });
+ const b = await importWorkspaceDocument(second);
+ // Importing leaves this page's lease on B; closing the page must not be the only release.
+ await releaseBackendProject();
+ return {
+ viewClientId: sessionStorage.getItem("opendirector.creation.viewClientId"),
+ a: { id: a.id, name: a.title }, b: { id: b.id, name: b.title },
+ delayed: delayed.id, failed: failed.id, ready: ready.id, hidden: hidden.id, far: far.id, text: text.id, other: other.id,
+ };
+ });
+ await seed.close();
+ return fixture;
+}
+
+async function verifyLocale(browser, locale) {
+ const text = copy[locale];
+ const fixture = await seedProjects(browser);
+ const before = await snapshot(fixture.a.id);
+ const delayedAsset = assetOf(before, fixture.delayed);
+ const failedAsset = assetOf(before, fixture.failed);
+ const hiddenAsset = assetOf(before, fixture.hidden);
+ const farAsset = assetOf(before, fixture.far);
+ const context = await browser.newContext({ locale, viewport: { width: 1500, height: 1000 } });
+ const page = await context.newPage();
+ page.setDefaultTimeout(20000);
+ const errors = [];
+ page.on("pageerror", (error) => errors.push(error.message));
+ await page.addInitScript((id) => {
+ localStorage.setItem("opendirector.modelSetup.v1", "dismissed");
+ sessionStorage.setItem("opendirector.creation.viewClientId", id);
+ }, fixture.viewClientId);
+ const release = Promise.withResolvers();
+ const failing = new Set([failedAsset]);
+ const requested = new Set();
+ await page.route(/\/api\/creation\/projects\/[^/]+\/assets\/[^/]+\/content$/, async (route) => {
+ const assetId = new URL(route.request().url()).pathname.split("/").at(-2);
+ requested.add(assetId);
+ if (failing.has(assetId))
+ return route.fulfill({ status: 409, json: { detail: "unavailable", code: "storage_unavailable" } });
+ if (assetId === delayedAsset) await release.promise;
+ return route.continue().catch(() => {});
+ });
+ const node = (id) => page.locator(`.react-flow__node[data-id="${id}"]`);
+ const decoded = (id) =>
+ page.waitForFunction((nodeId) => {
+ const picture = document.querySelector(`.react-flow__node[data-id="${nodeId}"] img`);
+ return Boolean(picture?.complete && picture.naturalWidth > 0);
+ }, id);
+ const open = async (project) => {
+ await page.getByRole("button", { name: text.picker, exact: true }).click();
+ await page.getByRole("menuitemradio", { name: project.name, exact: true }).click();
+ await page.locator(".cw-project-name").getByText(project.name, { exact: true }).waitFor();
+ };
+
+ await page.goto(`${base}/ai-tool/ai-canvas/${fixture.a.id}`);
+ // One held read must not delay the structure or any other node.
+ await page.waitForFunction(() => {
+ const element = document.querySelector(".cw-workspace");
+ return element?.getAttribute("aria-busy") === "false" && !element.inert;
+ });
+ await node(fixture.delayed).getByRole("status").getByText(text.loading).waitFor();
+ assert.equal(await node(fixture.delayed).locator(".cw-placeholder-upload").count(), 0);
+ await decoded(fixture.ready);
+ await node(fixture.text).getByText("Authoritative text").waitFor();
+ await node(fixture.failed).getByText(text.failed).waitFor();
+ assert.equal(await node(fixture.hidden).count(), 0);
+ assert.ok(!requested.has(hiddenAsset), "A hidden node must not read its media");
+ assert.ok(!requested.has(farAsset), "An off-screen node must wait for the viewport");
+
+ // Editing while media loads saves structure only.
+ const box = await node(fixture.delayed).boundingBox();
+ const start = { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+ await page.mouse.move(start.x, start.y);
+ await page.mouse.down();
+ await page.mouse.move(start.x + 30, start.y + 24, { steps: 5 });
+ await page.mouse.up();
+ const original = itemOf(before, fixture.delayed).position;
+ let moved;
+ for (let attempt = 0; attempt < 100; attempt++) {
+ moved = await snapshot(fixture.a.id);
+ if (itemOf(moved, fixture.delayed).position.x !== original.x) break;
+ await page.waitForTimeout(100);
+ }
+ assert.notEqual(itemOf(moved, fixture.delayed).position.x, original.x, "The move must save");
+ assert.equal(assetOf(moved, fixture.delayed), delayedAsset, "Unloaded media must keep its asset");
+ assert.equal(moved.assets.length, before.assets.length, "Saving must not create assets");
+
+ // A failed read recovers on its own node.
+ failing.delete(failedAsset);
+ await node(fixture.failed).getByRole("button", { name: text.retry }).click();
+ await decoded(fixture.failed);
+
+ // A late read belongs to its project and cannot appear in another one.
+ await open(fixture.b);
+ await decoded(fixture.other);
+ release.resolve();
+ await page.waitForTimeout(250);
+ assert.equal(await node(fixture.delayed).count(), 0);
+ assert.equal(await node(fixture.other).locator("img").count(), 1);
+ await open(fixture.a);
+ await decoded(fixture.delayed);
+ await decoded(fixture.failed);
+ const after = await snapshot(fixture.a.id);
+ for (const id of [fixture.delayed, fixture.failed, fixture.ready, fixture.hidden, fixture.far])
+ assert.equal(assetOf(after, id), assetOf(before, id), "Reopening must keep every asset binding");
+ assert.equal(after.assets.length, before.assets.length);
+
+ // Media loads when its node reaches the viewport.
+ assert.ok(!requested.has(farAsset));
+ await page.mouse.move(750, 500);
+ for (let step = 0; step < 12 && !requested.has(farAsset); step++) {
+ await page.mouse.wheel(1200, 0);
+ await page.waitForTimeout(120);
+ }
+ await decoded(fixture.far);
+ assert.deepEqual(errors, []);
+ await context.close();
+}
+
+const browser = await launchBrowser();
+try {
+ for (const locale of ["en-US", "zh-CN"]) await verifyLocale(browser, locale);
+ console.log("canvas progressive load: ok");
+} finally {
+ await browser.close();
+}
diff --git a/tests/browser/double_shift_chat.mjs b/tests/browser/double_shift_chat.mjs
index 3b108ecba..ababd2006 100644
--- a/tests/browser/double_shift_chat.mjs
+++ b/tests/browser/double_shift_chat.mjs
@@ -33,7 +33,8 @@ try {
await page.keyboard.insertText("Keep this draft");
await tap();
await page.waitForFunction(() => document.querySelector("#canvas-assistant").hidden);
- assert.equal(await trigger.evaluate(element => document.activeElement === element), true);
+ // Focus returns in the effect after the panel hides.
+ await page.waitForFunction(() => document.activeElement?.classList.contains("cw-project-chevron"));
await tap();
await editor.waitFor();
assert.ok((await editor.textContent()).includes("Keep this draft"));
diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json
index da72ffc51..43c346644 100644
--- a/tests/browser/manifest.json
+++ b/tests/browser/manifest.json
@@ -170,6 +170,11 @@
"gate"
]
},
+ {
+ "file": "canvas_progressive_load.mjs",
+ "lanes": ["gate"],
+ "note": "Bilingual structure-first opening with one held and one failed media read, retained asset bindings, retry and late reads across a project switch. Seeds projects through /src on Vite."
+ },
{
"file": "canvas_wheel.mjs",
"previewSafe": true,
diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts
index 15c320b05..37d6f4f68 100644
--- a/tests/creationClient.test.ts
+++ b/tests/creationClient.test.ts
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import test from "node:test";
import { readFileSync } from "node:fs";
+import { assetSource } from "../src/backend/assetSource.ts";
import type {
ProjectSnapshot,
ObjectVersion,
@@ -13,6 +14,7 @@ import type {
import {
CreationClient,
CreationCommandError,
+ MEDIA_PRIORITY,
assetReference,
type CreationOperation,
} from "../src/backend/creationClient.ts";
@@ -1550,7 +1552,116 @@ test("canvas video and audio import upload the original File and use Host media
const resource = await projection.importFile(file, signal);
assert.equal(resource.assetId, asset.id);
assert.equal(resource.durationSeconds, 2);
- assert.equal(resource.src, "blob:registered-media");
+ assert.equal(resource.src, assetSource(client.id, asset.id));
+ }
+});
+
+function mediaFixture() {
+ const snapshot = JSON.parse(
+ readFileSync(
+ new URL("./fixtures/creation-project.json", import.meta.url),
+ "utf8",
+ ),
+ ) as ProjectSnapshot;
+ const client = new CreationClient(snapshot.project.id);
+ client.install(snapshot);
+ client.textContent = async () => "fixture text";
+ client.view = async () => ({
+ projectId: client.id,
+ clientId: "fixture",
+ viewport: { x: 0, y: 0, zoom: 1 },
+ selectedItemIds: [],
+ activeEditorId: null,
+ playheads: [],
+ generationCounts: {},
+ });
+ return { client, snapshot };
+}
+
+test("canvas structure is projected without waiting for any node media", async () => {
+ const { client, snapshot } = mediaFixture();
+ let mediaReads = 0;
+ client.mediaUrl = () => {
+ mediaReads += 1;
+ return new Promise
(() => {});
+ };
+ const document = await new CreationProjection(client).read();
+ assert.equal(mediaReads, 0);
+ assert.equal(
+ document.nodes.length + (document.hiddenNodes?.length ?? 0),
+ snapshot.canvasItems.length,
+ );
+ const image = document.nodes.find(
+ (node) => node.type === "image" && node.data.backendAssetId,
+ )!;
+ assert.equal(
+ image.data.src,
+ assetSource(client.id, image.data.backendAssetId!),
+ );
+ assert.equal(image.data.assetState, "ready");
+});
+
+test("a display URL for the current asset is not saved as new material", async () => {
+ const { client, snapshot } = mediaFixture();
+ const operations: CreationOperation[] = [];
+ client.batch = async (next) => {
+ operations.push(...next);
+ return undefined;
+ };
+ const projection = new CreationProjection(client);
+ const document = await projection.read();
+ projection.baseline = document;
+ projection.basis = snapshot;
+ const edited = structuredClone(document);
+ const image = edited.nodes.find(
+ (node) => node.type === "image" && node.data.backendAssetId,
+ )!;
+ client.rememberSource("blob:displayed", image.data.backendAssetId!);
+ image.data.src = "blob:displayed";
+ await projection.save(edited, { saveView: false });
+ assert.ok(!operations.some((op) => op.type === "canvas.materialize"));
+});
+
+test("opening a canvas keeps text with the snapshot and reads originals by asset", async () => {
+ const original = globalThis.fetch;
+ const { snapshot } = mediaFixture();
+ const text = snapshot.assets.find((asset) => asset.kind === "text")!;
+ const image = snapshot.assets.find((asset) => asset.kind === "image")!;
+ const paths: string[] = [];
+ globalThis.fetch = async (url) => {
+ const path = String(url);
+ paths.push(path);
+ if (path.endsWith("/open-canvas"))
+ return Response.json({
+ snapshot,
+ edges: [],
+ texts: { [text.id]: "kept with structure" },
+ });
+ if (path.includes("/views/")) return new Response(null, { status: 204 });
+ if (path.includes("/subscribe"))
+ return new Response(new ReadableStream({ start() {} }));
+ if (path.endsWith(`/assets/${image.id}/content`))
+ return new Response("original", { status: 200 });
+ throw new Error(`Unexpected request ${path}`);
+ };
+ const client = new CreationClient(snapshot.project.id);
+ try {
+ await client.open();
+ assert.equal(await client.textContent(text.id), "kept with structure");
+ assert.ok(!paths.some((path) => path.includes(`/assets/${text.id}/`)));
+ const source = assetSource(client.id, image.id);
+ assert.equal(client.assetForSource(source)?.id, image.id);
+ assert.equal(client.assetForSource(assetSource("other", image.id)), undefined);
+ assert.equal(await (await client.originalMedia(source)).text(), "original");
+ // Displayed bytes are reused directly: the desktop CSP blocks fetching blob URLs.
+ const url = await client.mediaUrl(image.id);
+ const reads = paths.length;
+ assert.equal(await (await client.originalMedia(source)).text(), "original");
+ assert.equal(paths.length, reads);
+ assert.ok(!paths.includes(url));
+ } finally {
+ client.close();
+ globalThis.fetch = original;
}
});
@@ -1598,3 +1709,69 @@ test("an upload rejected for a lapsed lease is renewed and resent with the same
setLeaseRecovery(undefined);
}
});
+
+test("display reads stop only after every on-screen consumer leaves", async () => {
+ const original = globalThis.fetch;
+ const { client, snapshot } = mediaFixture();
+ const image = snapshot.assets.find((asset) => asset.kind === "image")!;
+ const signals: AbortSignal[] = [];
+ globalThis.fetch = (async (_url, options) => {
+ signals.push(options!.signal!);
+ return new Promise((_, reject) => {
+ options!.signal!.addEventListener("abort", () =>
+ reject(options!.signal!.reason),
+ );
+ });
+ }) as typeof fetch;
+ try {
+ const first = new AbortController();
+ const second = new AbortController();
+ const visible = { priority: MEDIA_PRIORITY.visible };
+ const reads = [
+ client.mediaUrl(image.id, { ...visible, signal: first.signal }),
+ client.mediaUrl(image.id, { ...visible, signal: second.signal }),
+ ];
+ const settled = Promise.allSettled(reads);
+ await new Promise((resolve) => setTimeout(resolve));
+ assert.equal(signals.length, 1);
+ first.abort();
+ await new Promise((resolve) => setTimeout(resolve));
+ assert.equal(signals[0]!.aborted, false);
+ second.abort();
+ await settled;
+ await new Promise((resolve) => setTimeout(resolve));
+ assert.equal(signals[0]!.aborted, true);
+ // Scrolling away says nothing about the file, so the node stays available.
+ assert.equal(client.mediaUnavailable(image.id), false);
+ } finally {
+ client.close();
+ globalThis.fetch = original;
+ }
+});
+
+test("a failed display read is reported and recovers on retry", async () => {
+ const original = globalThis.fetch;
+ const { client, snapshot } = mediaFixture();
+ const image = snapshot.assets.find((asset) => asset.kind === "image")!;
+ let healthy = false;
+ let notifications = 0;
+ client.listenMedia(() => (notifications += 1));
+ globalThis.fetch = (async () =>
+ healthy
+ ? new Response("bytes", { headers: { "content-type": "image/png" } })
+ : Response.json(
+ { code: "storage_unavailable", detail: "missing" },
+ { status: 409 },
+ )) as typeof fetch;
+ try {
+ await assert.rejects(client.mediaUrl(image.id));
+ assert.equal(client.mediaUnavailable(image.id), true);
+ healthy = true;
+ assert.match(await client.mediaUrl(image.id), /^blob:/);
+ assert.equal(client.mediaUnavailable(image.id), false);
+ assert.equal(notifications, 2);
+ } finally {
+ client.close();
+ globalThis.fetch = original;
+ }
+});
diff --git a/tests/creationEditorSession.test.ts b/tests/creationEditorSession.test.ts
index ffb6f8bd4..66275f5e3 100644
--- a/tests/creationEditorSession.test.ts
+++ b/tests/creationEditorSession.test.ts
@@ -5,6 +5,7 @@ import {
CreationClient,
CreationCommandError,
} from "../src/backend/creationClient.ts";
+import { assetSource } from "../src/backend/assetSource.ts";
import { CreationProjection } from "../src/backend/creationProjection.ts";
import { CreationEditorSession } from "../src/backend/creationEditorSession.ts";
import type {
@@ -25,7 +26,9 @@ async function fixture() {
client.mediaUrl = async (id) => `blob:${id}`;
client.textContent = async () => "fixture text";
client.assetForSource = (src) =>
- snapshot.assets.find((a) => `blob:${a.id}` === src);
+ snapshot.assets.find(
+ (a) => `blob:${a.id}` === src || assetSource(client.id, a.id) === src,
+ );
client.view = async () => ({
projectId: client.id,
clientId: "fixture",
@@ -261,7 +264,7 @@ test("timeline text fonts and immutable sources project both ways through the sh
},
};
const view = await projection.editorData(enriched as never);
- assert.equal(view.timeline!.fonts![0]!.src, `blob:${font.id}`);
+ assert.equal(view.timeline!.fonts![0]!.src, assetSource(client.id, font.id));
assert.deepEqual(view.timeline!.overlays![0]!.source!.asset, ref(source));
const node = document.nodes.find((n) => n.id === item.id)!;
Object.assign(node.data, view);
diff --git a/tests/creationLayers.test.ts b/tests/creationLayers.test.ts
index 4bb5ee56f..70ec0fde8 100644
--- a/tests/creationLayers.test.ts
+++ b/tests/creationLayers.test.ts
@@ -5,6 +5,7 @@ import {
CreationClient,
type CreationOperation,
} from "../src/backend/creationClient.ts";
+import { assetSource } from "../src/backend/assetSource.ts";
import { CreationProjection } from "../src/backend/creationProjection.ts";
import type {
EditorDocument,
@@ -38,7 +39,10 @@ function fixture(generated = false) {
client.install(snapshot);
client.mediaUrl = async (id) => `blob:${id}`;
client.assetForSource = (src) =>
- source.assets.find((asset) => src === `blob:${asset.id}`);
+ source.assets.find(
+ (asset) =>
+ src === `blob:${asset.id}` || src === assetSource(client.id, asset.id),
+ );
client.view = async () => ({
projectId: client.id,
clientId: crypto.randomUUID(),
@@ -238,7 +242,7 @@ for (const generated of [false, true]) {
const node = edited.nodes[0]!;
const source = node.data.src;
const output = snapshot.assets.find(
- (a) => a.kind === "image" && `blob:${a.id}` !== source,
+ (a) => a.kind === "image" && assetSource(client.id, a.id) !== source,
)!;
node.data.src = `blob:${output.id}`;
node.data.layers = {
@@ -255,7 +259,7 @@ for (const generated of [false, true]) {
const applied = operations.find((op) => op.type === "canvas.applyEdit");
assert.ok(applied && applied.type === "canvas.applyEdit");
assert.equal(applied.payload.asset.assetId, output.id);
- assert.equal(`blob:${applied.payload.source.assetId}`, source);
+ assert.equal(assetSource(client.id, applied.payload.source.assetId), source);
assert.ok(
operations.findIndex((op) => op.type === "canvas.attachEditor") <
operations.indexOf(applied),
@@ -305,7 +309,7 @@ test("crop projection reopens original inputs and copies independent documents a
projection.basis = attached;
assert.equal(
document.nodes[0]!.data.imageCrop!.src,
- `blob:${source.assetId}`,
+ assetSource(client.id, source.assetId),
);
assert.equal(document.nodes[0]!.data.imageCrop!.options.rotation, 90);
const copied = pasteFragment(document, copySelection(document, [item.id]));
diff --git a/tests/priorityLimiter.test.ts b/tests/priorityLimiter.test.ts
new file mode 100644
index 000000000..e776b7792
--- /dev/null
+++ b/tests/priorityLimiter.test.ts
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { PriorityLimiter } from "../src/backend/priorityLimiter.ts";
+
+const tick = () => new Promise((resolve) => setTimeout(resolve));
+
+function gate() {
+ let resolve!: () => void;
+ const promise = new Promise((done) => {
+ resolve = done;
+ });
+ return { promise, resolve };
+}
+
+test("reads stay within the limit and urgent work starts first", async () => {
+ const limiter = new PriorityLimiter(1);
+ const blocker = gate();
+ const order: string[] = [];
+ const run = (name: string, priority: number, key?: string) =>
+ limiter.run(async () => {
+ order.push(name);
+ }, { priority, key });
+ const first = limiter.run(() => blocker.promise);
+ const reads = [run("visible-1", 1), run("visible-2", 1, "two"), run("action", 0)];
+ limiter.prioritize("two", 0);
+ await tick();
+ assert.deepEqual(order, []);
+ blocker.resolve();
+ await Promise.all([first, ...reads]);
+ assert.deepEqual(order, ["action", "visible-2", "visible-1"]);
+});
+
+test("a cancelled queued read never starts and frees its place", async () => {
+ const limiter = new PriorityLimiter(1);
+ const blocker = gate();
+ const controller = new AbortController();
+ let started = false;
+ const first = limiter.run(() => blocker.promise);
+ const cancelled = limiter.run(async () => {
+ started = true;
+ }, { signal: controller.signal });
+ const next = limiter.run(async () => "next");
+ controller.abort();
+ await assert.rejects(cancelled, { name: "AbortError" });
+ blocker.resolve();
+ await first;
+ assert.equal(await next, "next");
+ assert.equal(started, false);
+});
+
+test("a failed read releases its slot", async () => {
+ const limiter = new PriorityLimiter(1);
+ await assert.rejects(limiter.run(async () => {
+ throw new Error("failed");
+ }));
+ assert.equal(await limiter.run(async () => "after"), "after");
+});
diff --git a/tests/test_creation_api.py b/tests/test_creation_api.py
index 3af318a79..aae68d84c 100644
--- a/tests/test_creation_api.py
+++ b/tests/test_creation_api.py
@@ -299,6 +299,7 @@ def counting_snapshot(self, project_id_value):
assert body['edges'] == projection['edges']
assert body['edges'] == [dict(referenceId=reference['id'], sourceItemId=source_item,
targetSpecId=target_spec, state='pending')]
+ assert body['texts'] == {asset['id']: 'v1'}
# The no-flag open keeps its established bare snapshot response.
plain = client.post(path + '/open').json()
assert plain == body['snapshot']
diff --git a/tests/test_creation_assets.py b/tests/test_creation_assets.py
index dd0f6cf40..600880cf8 100644
--- a/tests/test_creation_assets.py
+++ b/tests/test_creation_assets.py
@@ -642,3 +642,27 @@ def test_imported_assets_record_the_archive_source_they_came_from():
# A generated asset still needs real job evidence, not just a claim.
with pytest.raises(ValueError, match='job and input identity'):
AssetProvenance(source='generated', importedFrom='generated')
+
+
+def test_media_reads_replay_a_chain_once_and_keep_rejecting_a_damaged_ancestor(storage):
+ projects, project_id, _ = storage
+ asset, *_ = import_asset(storage)
+ replays = []
+ fresh = CreationProjects(LocalProjects(projects.local.repository))
+ fresh._schedule_warm = lambda *args: None
+ original_fresh = fresh._history
+ fresh._history = lambda *args: (replays.append(1), original_fresh(*args))[1]
+ reader = CreationAssets(fresh)
+ for _ in range(3):
+ stream, _asset = reader.open_media(project_id, asset.id)
+ stream.close()
+ assert len(replays) == 1
+ root = projects.root / 'Assets' / 'commits'
+ head = json.loads((projects.root / 'Assets' / 'project.json').read_text())['head']
+ ancestor = next(path for path in root.iterdir() if path.stem != head)
+ ancestor.write_bytes(ancestor.read_bytes().replace(b'Assets', b'Corrupt', 1))
+ cold = CreationProjects(LocalProjects(projects.local.repository))
+ cold._schedule_warm = lambda *args: None
+ with pytest.raises(ProjectError) as damaged:
+ CreationAssets(cold).open_media(project_id, asset.id)
+ assert damaged.value.code == 'storage_unavailable'
diff --git a/tests/test_creation_canvas_service.py b/tests/test_creation_canvas_service.py
index 965f333fc..e7f6385f7 100644
--- a/tests/test_creation_canvas_service.py
+++ b/tests/test_creation_canvas_service.py
@@ -619,3 +619,11 @@ def test_job_status_includes_delivery_from_the_same_snapshot():
assert view['delivery']['adopted'] is True
assert [item['id'] for item in view['delivery']['canvasItems']] == [str(snapshot.canvasItems[-3].id)]
assert 'Inspect this existing asset directly' in view['delivery']['guidance']
+
+
+def test_open_text_contents_isolate_one_unreadable_body(project):
+ store, pid, _ = project
+ _, readable = text_material(project, title='Readable', text='\ufeffkept')
+ _, broken = text_material(project, title='Broken', text='lost')
+ (store.root / 'Unified' / 'assets' / str(broken.id)).write_text('changed')
+ assert CreationCanvas(store).text_contents(store.snapshot(pid)) == {str(readable.id): 'kept'}
diff --git a/tests/test_creation_history_service.py b/tests/test_creation_history_service.py
index 01bd16c60..f16a7b0e5 100644
--- a/tests/test_creation_history_service.py
+++ b/tests/test_creation_history_service.py
@@ -551,3 +551,16 @@ def catalog():
assert not catalog()['available']
# Delete protection is unchanged: the derived version and history still depend on it.
assert service.usage(store.snapshot(pid), source.id)['used']
+
+
+def test_reference_catalog_checks_files_against_its_one_snapshot(project, monkeypatch):
+ store, pid, _ = project
+ text_material(project, title='First')
+ text_material(project, title='Second')
+ loads = []
+ original = store._load
+ monkeypatch.setattr(store, '_load', lambda *args: (loads.append(args), original(*args))[1])
+ rows = CreationHistory(store).reference_catalog(pid)
+ assert len(rows) == 2 and all(row['fileAvailable'] for row in rows)
+ # Replaying the commit chain per asset held the catalog lock across a whole switch.
+ assert loads == []