)}
diff --git a/src/canvas/CreationAssetPreview.tsx b/src/canvas/CreationAssetPreview.tsx
index 8fd8142fe..9e24ead8d 100644
--- a/src/canvas/CreationAssetPreview.tsx
+++ b/src/canvas/CreationAssetPreview.tsx
@@ -1,7 +1,7 @@
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { createPortal } from "react-dom";
import type { Asset } from "../contracts/generated.ts";
-import { creationClient } from "../backend/creationClient.ts";
+import { creationClient, MEDIA_PRIORITY } from "../backend/creationClient.ts";
import { CanvasIcon } from "./CanvasIcon.tsx";
import { useT } from "../i18n/I18nProvider.tsx";
@@ -26,28 +26,32 @@ export function HoverPreview({
const [content, setContent] = useState();
const [failed, setFailed] = useState(false);
useEffect(() => {
- let active = true;
const asset = preview.asset;
if (!asset) return;
+ const controller = new AbortController();
const client = creationClient(projectId);
+ // A video preview reads the whole file. Read it like on-screen canvas media
+ // so leaving the row abandons it; otherwise moving the pointer down a list
+ // of videos queues every file ahead of the canvas's own media.
const pending =
asset.kind === "image"
? client.thumbnailUrl(asset.id)
: asset.kind === "text" && asset.metadata.size <= 65536
? client.textContent(asset.id)
: asset.kind === "video"
- ? client.mediaUrl(asset.id)
+ ? client.mediaUrl(asset.id, {
+ signal: controller.signal,
+ priority: MEDIA_PRIORITY.visible,
+ })
: Promise.resolve("");
void pending
.then((value) => {
- if (active) setContent(value);
+ if (!controller.signal.aborted) setContent(value);
})
.catch(() => {
- if (active) setFailed(true);
+ if (!controller.signal.aborted) setFailed(true);
});
- return () => {
- active = false;
- };
+ return () => controller.abort();
}, [projectId, preview.asset]);
useLayoutEffect(() => {
const element = panel.current!;
diff --git a/tests/browser/creation_asset_list.mjs b/tests/browser/creation_asset_list.mjs
index 3cc246da9..db82e5975 100644
--- a/tests/browser/creation_asset_list.mjs
+++ b/tests/browser/creation_asset_list.mjs
@@ -223,6 +223,7 @@ try {
owners: [],
specId: null,
createdOrder: index,
+ categories: ["text"],
}));
let cursorMismatch = false;
const queries = [];
@@ -231,18 +232,17 @@ try {
`**/creation/projects/${projectId}/asset-list?*`,
async (route) => {
const params = new URL(route.request().url()).searchParams;
- const query = params.get("text");
- queries.push(query);
+ queries.push(params.toString());
const offset = Number(params.get("offset"));
if (offset && !cursorMismatch) await secondPage;
await route.fulfill({
json: {
- items: query ? [rows[200]] : rows.slice(offset, offset + 200),
- total: query ? 1 : rows.length,
+ items: rows.slice(offset, offset + 200),
+ total: rows.length,
eventCursor: cursorMismatch && offset ? 2 : 1,
counts: {
- all: query ? 1 : rows.length,
- text: query ? 1 : rows.length,
+ all: rows.length,
+ text: rows.length,
image: 0,
video: 0,
audio: 0,
@@ -304,10 +304,19 @@ try {
await page.waitForFunction(
() => document.querySelectorAll(".cw-creation-asset-row").length === 1,
);
- assert.deepEqual(queries.slice(count), ["Asset 200"]);
- // Pages from different project revisions must never form a usable list.
- cursorMismatch = true;
+ await dialog.getByRole("tab", { name: "文本 1", exact: true }).click();
await search.fill("");
+ await page.waitForFunction(
+ () => document.querySelectorAll(".cw-creation-asset-row").length === 201,
+ );
+ // Search and type filters narrow the loaded list without asking the server.
+ assert.deepEqual(queries.slice(count), []);
+ await dialog.getByRole("tab", { name: "全部 201", exact: true }).click();
+ // Pages from different project revisions must never form a usable list,
+ // even after the list has read every page again.
+ cursorMismatch = true;
+ await dialog.getByRole("button", { name: "关闭资产列表" }).click();
+ await page.getByRole("button", { name: "资产列表", exact: true }).click();
await dialog
.getByRole("alert")
.filter({ hasText: "资产列表已变化" })
@@ -321,6 +330,11 @@ try {
assert.equal(await dialog.getByRole("checkbox").count(), 201);
await dialog.getByRole("button", { name: "关闭资产列表" }).click();
await page.unroute(`**/creation/projects/${projectId}/asset-list?*`);
+ await page.getByRole("button", { name: "资产列表", exact: true }).click();
+ await dialog
+ .getByRole("checkbox", { name: "选择资产:画布图片", exact: true })
+ .waitFor();
+ // Media added while the list is open appears without reopening it.
await page.evaluate(async (projectId) => {
const { creationClient } = await import("/src/backend/creationClient.ts");
await creationClient(projectId).command("asset.writeText", {
@@ -328,7 +342,6 @@ try {
text: "Asset list integration check",
});
}, projectId);
- await page.getByRole("button", { name: "资产列表", exact: true }).click();
await dialog
.getByRole("checkbox", { name: "选择资产:Actual asset.md", exact: true })
.waitFor();
@@ -613,7 +626,7 @@ try {
console.log(
JSON.stringify({
firstPageBeforeCompletion: true,
- debouncedSearch: true,
+ searchWithoutRequests: true,
cursorConflictDiscarded: true,
retry: true,
realAssetQuery: true,
From 58ff07858c6034ecd015e406fb5c271a1b925089 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?=
Date: Sun, 29 Nov 2026 16:20:00 +0000
Subject: [PATCH 2/2] [perf] canvas: refresh the open asset list only for
changes it shows
The open list reread every page whenever the project's event cursor moved,
so moving nodes or an agent adding media one item at a time kept it reading,
and each read recomputes inventory and usage over the commit history. It now
compares a fingerprint of the snapshot parts the list is computed from
(assets, owning nodes' titles, visibility and bindings, current results,
pinned references, editor documents) and ignores other events, and refreshes
start at least 2 s after the previous read ends.
With the list open in the browser test, five node moves caused five list
reads before and none now; eight text writes 300 ms apart caused 13 reads
before and 3 now.
A failed background refresh no longer empties the list: the rows stay, a
notice says the list may be out of date, and the next change refreshes it
again. Only a failed first read clears the list and shows the error.
Co-Authored-By: Claude Opus 5.5
---
src/canvas/CreationAssetList.tsx | 123 +++++++++++++++++++++----
src/i18n/messages/en-US/canvasNodes.ts | 1 +
src/i18n/messages/zh-CN/canvasNodes.ts | 1 +
tests/browser/creation_asset_list.mjs | 109 ++++++++++++++++++++++
4 files changed, 215 insertions(+), 19 deletions(-)
diff --git a/src/canvas/CreationAssetList.tsx b/src/canvas/CreationAssetList.tsx
index 9fa08ed3c..5940a7b23 100644
--- a/src/canvas/CreationAssetList.tsx
+++ b/src/canvas/CreationAssetList.tsx
@@ -7,7 +7,11 @@ import {
useRef,
useState,
} from "react";
-import type { Asset, CanvasItem } from "../contracts/generated.ts";
+import type {
+ Asset,
+ CanvasItem,
+ ProjectSnapshot,
+} from "../contracts/generated.ts";
import {
assetReference,
creationClient,
@@ -71,6 +75,38 @@ type Loaded = Omit;
/** Pages from different project revisions are retried this many times before
* the list reports that the project changed. */
const CHANGED_RETRIES = 2;
+/** A refresh of the open list waits this long after the previous read ends,
+ * so a busy project reads it at most once per gap instead of once per event. */
+const REFRESH_GAP_MS = 2000;
+/** The parts of a snapshot the asset list is computed from: assets, the
+ * canvas nodes that own them (title, visibility, binding), current results,
+ * pinned references and the editor documents listed or counted as usage.
+ * Moving, resizing or restyling nodes leaves it unchanged. */
+function listingFingerprint(snapshot: ProjectSnapshot) {
+ return JSON.stringify([
+ snapshot.undoClearedThrough,
+ snapshot.assets.map((asset) => [asset.id, asset.name, asset.kind]),
+ snapshot.canvasItems.map((item) => [
+ item.id,
+ item.kind,
+ item.title,
+ item.visible,
+ item.parentId,
+ item.binding,
+ ]),
+ snapshot.generationSpecs.map((spec) => [spec.id, spec.currentResultId]),
+ snapshot.results.map((result) => [result.id, result.asset.assetId]),
+ snapshot.references.map((ref) => [
+ ref.id,
+ ref.active,
+ ref.binding === "pinned" ? ref.source.assetId : null,
+ ]),
+ snapshot.editorDocuments.map((document) => [
+ document.id,
+ document.revision,
+ ]),
+ ]);
+}
interface NodeRow {
itemId: string;
title: string;
@@ -154,6 +190,21 @@ export function CreationAssetList({
const shown = useRef(null);
const reading = useRef(false),
stale = useRef(false);
+ // A background refresh failed; the rows on screen are kept but may be old.
+ const [outdated, setOutdated] = useState(false);
+ const loadFinished = useRef(0);
+ const refreshTimer = useRef(undefined);
+ const scheduleRefresh = useCallback(() => {
+ if (refreshTimer.current !== undefined) return;
+ refreshTimer.current = window.setTimeout(
+ () => {
+ refreshTimer.current = undefined;
+ if (reading.current) stale.current = true;
+ else if (shown.current === projectId) setRevision((n) => n + 1);
+ },
+ Math.max(0, loadFinished.current + REFRESH_GAP_MS - Date.now()),
+ );
+ }, [projectId]);
const [selected, setSelected] = useState([]),
[busy, setBusy] = useState(false),
[attempt, setAttempt] = useState(0);
@@ -204,7 +255,12 @@ export function CreationAssetList({
if (!refreshing) {
shown.current = null;
setLoaded(null);
+ setOutdated(false);
}
+ // This read sees every change made so far, so a refresh waiting for the
+ // gap is no longer needed.
+ window.clearTimeout(refreshTimer.current);
+ refreshTimer.current = undefined;
reading.current = true;
stale.current = false;
setLoading(true);
@@ -246,39 +302,57 @@ export function CreationAssetList({
setLoaded({ items: rows, nodes, total, eventCursor: cursor });
shown.current = projectId;
reading.current = false;
+ loadFinished.current = Date.now();
setLoading(false);
- if (stale.current) setRevision((n) => n + 1);
+ setOutdated(false);
+ if (stale.current) scheduleRefresh();
}
})().catch((reason) => {
- if (active) {
- shown.current = null;
- reading.current = false;
- setLoaded(null);
- setLoading(false);
- setError(errorMessage(reason));
+ if (!active) return;
+ reading.current = false;
+ loadFinished.current = Date.now();
+ setLoading(false);
+ if (refreshing) {
+ // A failed refresh keeps the list on screen and marks it as possibly
+ // old; the next project change refreshes it again.
+ setOutdated(true);
+ if (stale.current) scheduleRefresh();
+ return;
}
+ shown.current = null;
+ setLoaded(null);
+ setError(errorMessage(reason));
});
return () => {
active = false;
controller.abort();
};
- }, [projectId, attempt, revision]);
- // Reload when the project changes while the list is open, e.g. an agent adds
- // media. A change during a load reloads once that load is done, so a busy
- // project cannot keep restarting the list.
+ }, [projectId, attempt, revision, scheduleRefresh]);
+ // Reload when a change to the project can change the list while it is open,
+ // e.g. an agent adds media. Other events, such as moving nodes, are ignored.
+ // A change during a load reloads once that load is done, and reloads keep
+ // REFRESH_GAP_MS apart, so a busy project cannot keep the list reading.
useEffect(() => {
const client = creationClient(projectId);
- let seen = client.snapshot?.eventCursor;
- return client.listen((snapshot) => {
- if (snapshot.eventCursor === seen) return;
- seen = snapshot.eventCursor;
+ let seen = client.snapshot ? listingFingerprint(client.snapshot) : "";
+ const stop = client.listen((snapshot) => {
+ const next = listingFingerprint(snapshot);
+ if (next === seen) return;
+ seen = next;
if (reading.current) stale.current = true;
- else if (shown.current === projectId) setRevision((n) => n + 1);
+ else if (shown.current === projectId) scheduleRefresh();
});
- }, [projectId]);
+ return () => {
+ stop();
+ window.clearTimeout(refreshTimer.current);
+ refreshTimer.current = undefined;
+ };
+ }, [projectId, scheduleRefresh]);
const listing = useMemo(() => {
if (!loaded) return null;
- // Same matching as the server's asset search: name or owning node title.
+ // Like the server's asset search: name or owning node title, ignoring
+ // case. toLowerCase is close to Python's casefold but not identical
+ // (casefold also folds "ß" to "ss").
const needle = query.toLowerCase();
const items = loaded.items.filter(
(row) =>
@@ -634,6 +708,17 @@ export function CreationAssetList({
})}