diff --git a/src/canvas/CreationAssetList.tsx b/src/canvas/CreationAssetList.tsx index 9a8193d6a..5940a7b23 100644 --- a/src/canvas/CreationAssetList.tsx +++ b/src/canvas/CreationAssetList.tsx @@ -1,5 +1,17 @@ -import { useCallback, useEffect, useId, useRef, useState } from "react"; -import type { Asset, CanvasItem } from "../contracts/generated.ts"; +import { + useCallback, + useDeferredValue, + useEffect, + useId, + useMemo, + useRef, + useState, +} from "react"; +import type { + Asset, + CanvasItem, + ProjectSnapshot, +} from "../contracts/generated.ts"; import { assetReference, creationClient, @@ -59,6 +71,42 @@ interface Listing { eventCursor: number; counts: Record; } +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; @@ -95,8 +143,10 @@ export function CreationAssetList({ return key ? t(key) : label; }; const [text, setText] = useState(""), - [visibility, setVisibility] = useState("all"), - [query, setQuery] = useState(""); + [visibility, setVisibility] = useState("all"); + // Filtering runs in the browser over the loaded list, so typing never waits + // for the server; the deferred value keeps long lists from blocking input. + const query = useDeferredValue(text); const [category, setCategory] = useState("all"); const [preview, setPreview] = useState(null); const previewTimer = useRef(undefined); @@ -131,8 +181,30 @@ export function CreationAssetList({ }; const rowsId = useId(); const [loading, setLoading] = useState(true); - const [listing, setListing] = useState(null), + // The whole unfiltered listing; search, visibility and type only narrow it. + const [loaded, setLoaded] = useState(null), [error, setError] = useState(""); + const [revision, setRevision] = useState(0); + // The project whose complete list is on screen, and whether it changed + // again while a load was already running. + 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); @@ -175,60 +247,157 @@ export function CreationAssetList({ document.removeEventListener("keydown", escape, true); }; }, [anchor, busy, onClose]); - useEffect(() => { - const timer = window.setTimeout(() => setQuery(text), 200); - return () => window.clearTimeout(timer); - }, [text]); useEffect(() => { const controller = new AbortController(); let active = true; - setListing(null); + // A refresh keeps the current rows on screen until the new list is whole. + const refreshing = shown.current === projectId; + 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); setError(""); void (async () => { - const rows: Row[] = []; - const nodes: NodeRow[] = []; + let rows: Row[] = []; + let nodes: NodeRow[] = []; let total = Infinity, - cursor = 0; + cursor = 0, + retries = 0; while (rows.length + nodes.length < total) { const page = await request( - `${creationPath(projectId)}/asset-list?text=${encodeURIComponent(query)}&visibility=${visibility}&category=${category}&offset=${rows.length + nodes.length}&limit=200`, + `${creationPath(projectId)}/asset-list?offset=${rows.length + nodes.length}&limit=200`, { signal: controller.signal }, ); - if ((rows.length || nodes.length) && page.eventCursor !== cursor) - throw new Error(t("canvasNodes.assets.changed")); + if ((rows.length || nodes.length) && page.eventCursor !== cursor) { + // Pages from different project revisions never form one list. + if (retries++ >= CHANGED_RETRIES) + throw new Error(t("canvasNodes.assets.changed")); + rows = []; + nodes = []; + total = Infinity; + continue; + } rows.push(...page.items); nodes.push(...(page.nodes ?? [])); total = page.total; cursor = page.eventCursor; - if (active) - setListing({ + if (active && !refreshing) + setLoaded({ items: [...rows], nodes: [...nodes], total, eventCursor: cursor, - counts: page.counts, }); if (!page.items.length && !page.nodes?.length) break; } if (active) { + setLoaded({ items: rows, nodes, total, eventCursor: cursor }); + shown.current = projectId; + reading.current = false; + loadFinished.current = Date.now(); setLoading(false); - setSelected((ids) => - ids.filter((id) => rows.some((row) => row.asset.id === id)), - ); + setOutdated(false); + if (stale.current) scheduleRefresh(); } })().catch((reason) => { - if (active) { - setListing(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, query, visibility, category, attempt]); + }, [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 ? 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) scheduleRefresh(); + }); + return () => { + stop(); + window.clearTimeout(refreshTimer.current); + refreshTimer.current = undefined; + }; + }, [projectId, scheduleRefresh]); + const listing = useMemo(() => { + if (!loaded) return null; + // 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) => + (visibility === "all" || + row.owners.some((owner) => owner.visible) === + (visibility === "visible")) && + (row.asset.name.toLowerCase().includes(needle) || + row.owners.some((owner) => + owner.title.toLowerCase().includes(needle), + )), + ); + const nodes = loaded.nodes.filter( + (row) => + (visibility === "all" || row.visible === (visibility === "visible")) && + row.title.toLowerCase().includes(needle), + ); + const counts = Object.fromEntries( + CATEGORIES.map((entry) => [entry.id, 0]), + ) as Record; + counts.all = items.length + nodes.length; + for (const row of items) + for (const kind of row.categories) + if (kind !== "all" && kind in counts) counts[kind as Category] += 1; + for (const row of nodes) counts[row.kind] += 1; + return { + items: + category === "all" + ? items + : items.filter((row) => row.categories.includes(category)), + nodes: + category === "all" + ? nodes + : nodes.filter((row) => row.kind === category), + counts, + }; + }, [loaded, query, visibility, category]); + useEffect(() => { + if (loading || !listing) return; + setSelected((ids) => { + const next = ids.filter((id) => + listing.items.some((row) => row.asset.id === id), + ); + return next.length === ids.length ? ids : next; + }); + }, [listing, loading]); useEffect(clearPreview, [category, query, visibility, clearPreview]); const perform = async (action: () => Promise) => { setBusy(true); @@ -278,6 +447,18 @@ export function CreationAssetList({ deleting.impact.fingerprint, ); if (alive.current) { + // The receipt confirms the deletion; drop the rows now instead of + // leaving them on screen until the refreshed list arrives. + const removed = new Set(deleting.ids); + setLoaded((current) => { + if (!current) return current; + const items = current.items.filter((row) => !removed.has(row.asset.id)); + return { + ...current, + items, + total: current.total - (current.items.length - items.length), + }; + }); setDeleting(null); setSelected([]); setAttempt((n) => n + 1); @@ -519,13 +700,25 @@ export function CreationAssetList({ {loading && !error && (

{t("canvasNodes.assets.loading")} - {listing && + {loaded && + loaded.items.length + loaded.nodes.length < loaded.total && t("canvasNodes.assets.progress", { - shown: listing.items.length + listing.nodes.length, - total: listing.total, + shown: loaded.items.length + loaded.nodes.length, + total: loaded.total, })}

)} + {outdated && !loading && !error && ( +

+ {t("canvasNodes.assets.outdated")} + +

+ )}
(); 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/src/i18n/messages/en-US/canvasNodes.ts b/src/i18n/messages/en-US/canvasNodes.ts index 33d876246..ab41992e9 100644 --- a/src/i18n/messages/en-US/canvasNodes.ts +++ b/src/i18n/messages/en-US/canvasNodes.ts @@ -167,6 +167,7 @@ export const canvasNodes = { "canvasNodes.assets.subject": "Subjects", "canvasNodes.assets.timeline": "Timelines", "canvasNodes.assets.changed": "The asset list changed. Read it again.", + "canvasNodes.assets.outdated": "The asset list may be out of date.", "canvasNodes.assets.versionChanged": "This asset's current version changed. Choose from the updated list.", "canvasNodes.assets.nodeChanged": diff --git a/src/i18n/messages/zh-CN/canvasNodes.ts b/src/i18n/messages/zh-CN/canvasNodes.ts index e0226be16..f890ba4df 100644 --- a/src/i18n/messages/zh-CN/canvasNodes.ts +++ b/src/i18n/messages/zh-CN/canvasNodes.ts @@ -161,6 +161,7 @@ export const canvasNodes = { "canvasNodes.assets.subject": "主体", "canvasNodes.assets.timeline": "时间线", "canvasNodes.assets.changed": "资产列表已变化,请重新读取。", + "canvasNodes.assets.outdated": "资产列表可能已过期。", "canvasNodes.assets.versionChanged": "资产的当前版本已变化,请从更新后的列表选择。", "canvasNodes.assets.nodeChanged": "节点已变化,请从更新后的列表选择。", "canvasNodes.assets.role.visibleCanvasItem": "画布中显示的节点", diff --git a/tests/browser/creation_asset_list.mjs b/tests/browser/creation_asset_list.mjs index 3cc246da9..8c8ff1b56 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(); @@ -609,11 +622,116 @@ try { assert.equal(savedSubject.length, 1); assert.equal(savedSubject[0].id, subjectId); assert.equal(savedSubject[0].visible, true); + // An open list ignores project changes it is not computed from, and changes + // arriving one after another read it at most once per refresh gap. + const listReads = []; + const countRead = (request) => { + if (request.url().includes(`/creation/projects/${projectId}/asset-list?`)) + listReads.push(request.url()); + }; + page.on("request", countRead); + const writeText = (name) => + page.evaluate( + async ({ projectId, name }) => { + const { creationClient } = + await import("/src/backend/creationClient.ts"); + await creationClient(projectId).command("asset.writeText", { + name, + text: name, + }); + }, + { projectId, name }, + ); + await page.getByRole("button", { name: "资产列表", exact: true }).click(); + await dialog.getByRole("checkbox").first().waitFor(); + await dialog + .getByRole("status") + .filter({ hasText: "正在读取资产列表" }) + .waitFor({ state: "detached" }); + listReads.length = 0; + const moved = await page.evaluate(async (projectId) => { + const { creationClient, objectVersion } = + await import("/src/backend/creationClient.ts"); + const client = creationClient(projectId); + const before = client.snapshot.eventCursor; + for (let step = 0; step < 5; step += 1) { + const item = client.snapshot.canvasItems[0]; + await client.command( + "canvas.move", + { + items: [ + { + itemId: item.id, + position: { x: item.position.x + 10, y: item.position.y }, + }, + ], + }, + [objectVersion("canvas_item", item)], + ); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + return client.snapshot.eventCursor - before; + }, projectId); + assert.ok(moved >= 5, "Moves must produce project events"); + await page.waitForTimeout(2500); + assert.deepEqual(listReads, [], "Moving nodes must not reread the list"); + // Eight writes 300 ms apart, as an agent adding media one at a time. + const burstStarted = Date.now(); + for (let n = 1; n <= 8; n += 1) { + await writeText(`Burst ${n}.md`); + await page.waitForTimeout(300); + } + await dialog + .getByRole("checkbox", { name: "选择资产:Burst 8.md", exact: true }) + .waitFor(); + await page.waitForTimeout(2500); + const burstReads = listReads.length, + burstSeconds = (Date.now() - burstStarted) / 1000; + assert.ok( + burstReads <= Math.ceil(burstSeconds / 2) + 1, + `${burstReads} list reads in ${burstSeconds}s`, + ); + // A failed background refresh keeps the rows and says they may be old; + // the next change refreshes the list again. + await page.route(`**/creation/projects/${projectId}/asset-list?*`, (route) => + route.fulfill({ status: 503, json: { detail: "unavailable" } }), + ); + await writeText("Offline 1.md"); + await dialog + .getByRole("status") + .filter({ hasText: "资产列表可能已过期" }) + .waitFor(); + assert.equal(await dialog.getByRole("alert").count(), 0); + assert.equal( + await dialog + .getByRole("checkbox", { name: "选择资产:Burst 8.md", exact: true }) + .count(), + 1, + ); + await page.unroute(`**/creation/projects/${projectId}/asset-list?*`); + await writeText("Offline 2.md"); + await dialog + .getByRole("checkbox", { name: "选择资产:Offline 2.md", exact: true }) + .waitFor(); + await dialog + .getByRole("checkbox", { name: "选择资产:Offline 1.md", exact: true }) + .waitFor(); + assert.equal( + await dialog + .getByRole("status") + .filter({ hasText: "资产列表可能已过期" }) + .count(), + 0, + ); + page.off("request", countRead); + await dialog + .getByRole("button", { name: "关闭资产列表", exact: true }) + .click(); assert.deepEqual(errors, []); console.log( JSON.stringify({ firstPageBeforeCompletion: true, - debouncedSearch: true, + searchWithoutRequests: true, cursorConflictDiscarded: true, retry: true, realAssetQuery: true, @@ -628,6 +746,10 @@ try { hiddenSubjectRestoredAndLocated: true, selectedDeletionOnly: true, visibleAssetProtected: true, + layoutChangesIgnored: true, + burstListReads: burstReads, + burstSeconds, + failedRefreshKeepsRows: true, errors, }), );