From 2a94f706d234ec794429642aebaba1336b36a58e 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:13:22 +0000 Subject: [PATCH 1/2] [perf] assistant: insert chat references without the project-wide catalog Typing @ in the assistant chat showed only "loading" until the whole reference catalog arrived, although the chat lists the visible canvas nodes it already has. Choosing a node then re-read the canvas, read the whole catalog again (every asset's file checked, plus a scan of the commit history) and downloaded and SHA-256 hashed each referenced file in the browser, all before the reference appeared. - The chat picker no longer waits on the catalog, as the generation composer's picker already does; opening it still prefetches the catalog for draft references in the background. - reference-catalog accepts nodeId filters. Scoped to the chosen nodes it reads only the head snapshot and checks only those nodes' files, with the same rows and availability as the full catalog. The browser reads it in the foreground instead of behind other background reads. - A pick uses that read and drops the canvas re-read and the browser download and hash: the canvas is saved before the pick, the server checks each file against its fingerprint, and media reads refuse changed bytes. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/opendirector_api/creation.py | 5 +- .../application/creation_history.py | 23 ++- src/backend/api.ts | 2 +- src/backend/referenceCatalog.ts | 16 ++ src/canvas/AssistantPanel.tsx | 6 +- src/canvas/useAssistantChat.ts | 27 +-- src/i18n/messages/en-US/assistant.ts | 1 - src/i18n/messages/zh-CN/assistant.ts | 1 - tests/browser/assistant_chat_references.mjs | 194 ++++++++++++++++++ tests/browser/manifest.json | 10 + tests/test_creation_history_service.py | 21 ++ 11 files changed, 278 insertions(+), 28 deletions(-) create mode 100644 tests/browser/assistant_chat_references.mjs diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 556b48648..76d6d100f 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -314,8 +314,9 @@ def operations(project_id: UUID): return history.operations(project_id) @router.get('/projects/{project_id}/reference-catalog') - def reference_catalog(project_id: UUID): - return history.reference_catalog(project_id) + def reference_catalog(project_id: UUID, node_ids: list[UUID] | None = Query(default=None, alias='nodeId', max_length=64)): + # nodeId limits the read to the media of the nodes being referenced. + return history.reference_catalog(project_id, node_ids) @router.get('/projects/{project_id}/specs/{spec_id}/versions') def versions(project_id: UUID, spec_id: UUID): diff --git a/packages/core/src/opendirector/application/creation_history.py b/packages/core/src/opendirector/application/creation_history.py index ffa22bf11..d3af49c9e 100644 --- a/packages/core/src/opendirector/application/creation_history.py +++ b/packages/core/src/opendirector/application/creation_history.py @@ -105,13 +105,24 @@ def _entry_states(cleared, entries): future.discard(target) return states - def reference_catalog(self, project_id): - records, path = self.projects.records_with_path(project_id) - snapshot = records[0].snapshot - current, _, historical = self._inventory(snapshot, records=records) - listed = {a.id for a in snapshot.assets if a.id not in historical or a.id in current} + def reference_catalog(self, project_id, node_ids=None): + """Every referable asset, or with ``node_ids`` only the media those nodes own. + + A node's own media is referable whenever its file is intact, so the + node-scoped read needs neither the commit history nor the other files. + """ + if node_ids is None: + records, path = self.projects.records_with_path(project_id) + snapshot = records[0].snapshot + current, _, historical = self._inventory(snapshot, records=records) + listed = {a.id for a in snapshot.assets if a.id not in historical or a.id in current} + else: + snapshot, path, listed = self.projects.snapshot(project_id), None, set() + node_ids = {UUID(str(value)) for value in node_ids} owners = {} for item in snapshot.canvasItems: + if node_ids is not None and item.id not in node_ids: + continue asset = current_asset(snapshot, item) if asset: owners.setdefault(asset.id, []).append(dict(nodeId=str(item.id), nodeTitle=item.title)) @@ -125,6 +136,8 @@ def reference_catalog(self, project_id): reader = service.snapshot_media_reader(snapshot, resolved_path=path) result = [] for asset in snapshot.assets: + if node_ids is not None and asset.id not in owners: + continue file_available = True try: stream, checked = reader(asset.id) diff --git a/src/backend/api.ts b/src/backend/api.ts index b6e7d9d91..4050dc079 100644 --- a/src/backend/api.ts +++ b/src/backend/api.ts @@ -103,7 +103,7 @@ export function backgroundRead(task: () => Promise, signal?: AbortSignal) return backgroundReads.run(task, { signal }); } -const BACKGROUND_PROJECT_READ = /^\/creation\/projects\/[^/]+\/(?:assistant(?:\/[^?]*)?|reference-catalog|reference-evidence|canvas-texts|history|version-counts)(?:\?|$)/; +const BACKGROUND_PROJECT_READ = /^\/creation\/projects\/[^/]+\/(?:assistant(?:\/[^?]*)?|reference-catalog(?!\?nodeId=)|reference-evidence|canvas-texts|history|version-counts)(?:\?|$)/; export function request(path: string, options: RequestInit = {}, leaseRenewed = false): Promise { const run = () => requestNow(path, options, leaseRenewed); diff --git a/src/backend/referenceCatalog.ts b/src/backend/referenceCatalog.ts index fdaebbb45..57ce04c16 100644 --- a/src/backend/referenceCatalog.ts +++ b/src/backend/referenceCatalog.ts @@ -8,3 +8,19 @@ export async function loadReferenceCatalog( ): Promise { return request(`${creationPath(projectId)}/reference-catalog`, { signal }); } + +/** The media these canvas nodes own, checked by the server against their + * recorded fingerprints. Much cheaper than the whole catalog, and read in the + * foreground because the user is waiting on the reference they just chose. */ +export async function loadNodeReferences( + projectId: string, + nodeIds: readonly string[], + signal?: AbortSignal, +): Promise { + const query = nodeIds + .map((id) => `nodeId=${encodeURIComponent(id)}`) + .join("&"); + return request(`${creationPath(projectId)}/reference-catalog?${query}`, { + signal, + }); +} diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 50ff8d5eb..392fc950c 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -686,8 +686,10 @@ export function AssistantPanel({ return (await chooseMention(option, signal)) ?? []; }} onOpen={projectReferences.load} - loading={projectReferences.loading} - loadError={projectReferences.error} + // Options are the visible canvas nodes, already known here. The + // catalog only refreshes draft references, so it never blocks them. + loading={false} + loadError="" onConfirmPending={ pending ? (at) => void confirmPending(at.end) : undefined } diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts index 0f9eb127c..055c720e2 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -22,11 +22,9 @@ import { conversationIsEmpty, } from "../backend/chat"; import { flushChatDraft, rememberChat } from "../backend/chatDrafts"; -import { creationClient } from "../backend/creationClient.ts"; -import { fingerprint } from "../backend/generation"; import { getActiveLocale } from "../i18n/messages.ts"; import type { BackendModels } from "../backend/models"; -import { loadReferenceCatalog } from "../backend/referenceCatalog.ts"; +import { loadNodeReferences } from "../backend/referenceCatalog.ts"; import { isGenerationModel } from "../backend/rules"; import { resolveGenerationModel } from "./modelResolution.ts"; import { @@ -432,10 +430,16 @@ export function useAssistantChat( }), ); { - const client = creationClient(projectId); - await client.refresh(); - const catalog = await loadReferenceCatalog(projectId, signal); - const selected = nodes.flatMap((node) => { + // The canvas was saved before this, so the server resolves the nodes' + // current media itself and checks each file against its recorded + // fingerprint; media reads also refuse changed bytes. Neither a full + // canvas re-read nor downloading and hashing every file is needed. + const catalog = await loadNodeReferences( + projectId, + nodes.map((node) => node.id), + signal, + ); + return nodes.flatMap((node) => { const assets = catalog.filter( (asset) => asset.nodeId === node.id && asset.available, ); @@ -443,15 +447,6 @@ export function useAssistantChat( throw new Error(t("assistant.error.noUsableAssets")); return assets; }); - for (const asset of selected) { - signal.throwIfAborted(); - if ( - (await fingerprint(await client.blob(asset.id))) !== - asset.fingerprint - ) - throw new Error(t("assistant.error.referenceChangedBatch")); - } - return selected; } }, signal, diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index 769657c90..d49944397 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -256,7 +256,6 @@ export const assistant = { "assistant.error.tooManyReferences": "You can add at most 64 reference assets at a time.", "assistant.error.batchNotInserted": "{detail} Nothing was inserted.", "assistant.error.noUsableAssets": "The selected nodes have no usable assets; nothing was inserted.", - "assistant.error.referenceChangedBatch": "The reference content changed; nothing was inserted.", "assistant.error.referenceChanged": "The reference content changed; copy it again.", "assistant.error.referenceFileChanged": "The reference file changed.", "assistant.error.fixedReferenceMissing": "The pinned reference material is missing or changed.", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 2b1d7cb04..c225e5df2 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -247,7 +247,6 @@ export const assistant = { "assistant.error.tooManyReferences": "每次最多添加 64 份参考素材。", "assistant.error.batchNotInserted": "{detail} 整批未插入。", "assistant.error.noUsableAssets": "所选节点尚无可用素材,整批未插入。", - "assistant.error.referenceChangedBatch": "参考内容已变化,整批未插入。", "assistant.error.referenceChanged": "参考内容已变化,请重新复制。", "assistant.error.referenceFileChanged": "参考文件已改变。", "assistant.error.fixedReferenceMissing": "固定参考素材缺失或内容已改变。", diff --git a/tests/browser/assistant_chat_references.mjs b/tests/browser/assistant_chat_references.mjs new file mode 100644 index 000000000..091f1ffaa --- /dev/null +++ b/tests/browser/assistant_chat_references.mjs @@ -0,0 +1,194 @@ +/** Isolated --assistant-fixture services only: inserting canvas nodes into the + * assistant chat with @ must not wait on the project-wide reference catalog, + * download the referenced files or re-read the canvas. */ +import assert from "node:assert/strict"; +import { execFileSync } from "node:child_process"; +const { chromium } = await import( + process.env.PLAYWRIGHT_MODULE ?? "playwright-core" +); +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:8019"; +const api = process.env.CREATION_API_URL ?? base; +const projectId = crypto.randomUUID(), + seedSession = crypto.randomUUID(); +const headers = { + "X-OpenDirector-Request": "1", + "X-OpenDirector-Session": seedSession, + "Content-Type": "application/json", +}; +async function call(path, body, method = body ? "POST" : "GET") { + const response = await fetch(api + path, { + method, + headers, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + assert.ok(response.ok, `${response.status}: ${await response.clone().text()}`); + return response.status === 204 ? null : response.json(); +} +async function command(type, payload) { + const result = await call(`/api/creation/projects/${projectId}/commands`, { + commandId: crypto.randomUUID(), + projectId, + type, + payload, + }); + assert.equal(result.status, "applied", JSON.stringify(result)); +} +const health = await call("/api/creation-test-health"); +assert.equal(health.isolated, true, "Use the isolated fixture API"); +assert.equal(health.assistantFixture, true, "Start creation_server.py with --assistant-fixture"); +await command("project.create", { name: `Chat references ${projectId.slice(0, 8)}` }); +await call(`/api/creation/projects/${projectId}/open`, null, "POST"); +const video = execFileSync("ffmpeg", [ + "-v", "error", "-f", "lavfi", "-i", "testsrc2=s=160x96:r=12", "-t", "1", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-movflags", "frag_keyframe+empty_moov", + "-f", "mp4", "pipe:1", +]); +const png = Buffer.from( + "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAGUlEQVR4nGNsYGhgIAUwkaR6VMOohiGlAQBCPQEgiSD+iQAAAABJRU5ErkJggg==", + "base64", +); +for (const [name, kind, bytes] of [ + ["镜头.mp4", "video", video], + ["海报.png", "image", png], +]) { + const handle = crypto.randomUUID(); + const upload = await fetch(`${api}/api/creation/projects/${projectId}/uploads/${handle}`, { + method: "PUT", + headers: { + ...headers, + "Content-Type": "application/octet-stream", + "X-Asset-Name": encodeURIComponent(name), + "X-Asset-Kind": kind, + }, + body: bytes, + }); + assert.ok(upload.ok, await upload.text()); + await command("asset.import", { uploadHandle: handle, name, expectedKind: kind }); +} +const seeded = await call(`/api/creation/projects/${projectId}`); +const nodes = {}; +for (const [index, asset] of seeded.assets.entries()) { + const id = crypto.randomUUID(); + nodes[asset.kind] = { id, asset }; + await command("canvas.show", { + item: { + id, + projectId, + kind: asset.kind, + title: asset.name, + visible: true, + position: { x: 150 + index * 260, y: 150 }, + width: 220, + height: 160, + binding: { + role: "material", + objectRef: { + assetId: asset.id, + revision: asset.revision, + fingerprint: asset.fingerprint, + kind: asset.kind, + }, + }, + }, + }); +} +await call(`/api/creation/sessions/${seedSession}`, null, "DELETE"); + +const browser = await chromium.launch({ + headless: true, + ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}), +}); +try { + const page = await browser.newPage({ locale: "zh-CN", viewport: { width: 1600, height: 1000 } }); + // Skip the first-run model setup welcome; it covers the canvas. + await page.addInitScript(() => localStorage.setItem("opendirector.modelSetup.v1", "dismissed")); + page.setDefaultTimeout(15000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + const requests = []; + page.on("request", (request) => { + const url = new URL(request.url()); + if (url.pathname.startsWith("/api/")) requests.push(url.pathname + url.search); + }); + // Hold the project-wide catalog for the whole test. The picker lists the + // visible canvas nodes and a pick reads only the chosen nodes' media. + let releaseCatalog; + const catalogGate = new Promise((resolve) => (releaseCatalog = resolve)); + page.on("close", () => releaseCatalog()); + await page.route(`**/projects/${projectId}/reference-catalog`, async (route) => { + await catalogGate; + await route.fulfill({ status: 503, json: { detail: "Fixture catalog unavailable" } }); + }); + await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`); + await page.getByText("已保存到本机", { exact: true }).waitFor(); + const panel = page.getByRole("complementary", { name: "AI 对话", exact: true }); + if (!(await panel.isVisible())) + await page.getByRole("button", { name: "与 AI 对话", exact: true }).click(); + const editor = panel.getByRole("textbox", { name: "消息内容", exact: true }); + await editor.waitFor(); + const picker = page.getByRole("dialog", { name: "引用项目资产", exact: true }); + + await editor.click(); + await editor.pressSequentially("参考 @"); + await picker.getByRole("option").first().waitFor(); + assert.equal(await picker.getByRole("status").count(), 0, "The picker must not wait on the catalog"); + assert.equal(await picker.getByRole("option").count(), 2); + const before = requests.length; + await picker.getByRole("option", { name: /^镜头\.mp4/ }).click(); + await picker.waitFor({ state: "hidden" }); + const chip = editor.locator("[data-reference]"); + await chip.waitFor(); + const reference = JSON.parse(await chip.getAttribute("data-reference")); + assert.equal(reference.assetId, nodes.video.asset.id); + assert.equal(reference.nodeId, nodes.video.id); + const pick = requests.slice(before); + assert.deepEqual( + pick.filter((path) => path.includes("/reference-catalog")), + [`/api/creation/projects/${projectId}/reference-catalog?nodeId=${nodes.video.id}`], + ); + assert.deepEqual( + pick.filter((path) => /\/assets\/[^/]+\/content$|\/canvas$/.test(path)), + [], + "A pick must not download the media or re-read the canvas", + ); + + // A node whose file the server reports unusable is refused as a whole. + await page.route(`**/projects/${projectId}/reference-catalog?nodeId=*`, async (route) => { + const response = await route.fetch(); + const rows = await response.json(); + await route.fulfill({ response, json: rows.map((row) => ({ ...row, available: false, fileAvailable: false })) }); + }); + await editor.press("End"); + await editor.pressSequentially(" @"); + await picker.getByRole("option", { name: /^海报\.png/ }).click(); + await page.getByText("所选节点尚无可用素材,整批未插入。", { exact: true }).waitFor(); + assert.equal(await editor.locator("[data-reference]").count(), 1); + await page.unroute(`**/projects/${projectId}/reference-catalog?nodeId=*`); + await editor.press("Escape"); + + // The referenced media reaches the assistant turn with its fingerprint. + await panel.getByRole("button", { name: "发送消息", exact: true }).click(); + const deadline = Date.now() + 15000; + let state; + do { + state = await call(`/api/creation/projects/${projectId}/assistant`); + if (state.messages.length) break; + await new Promise((resolve) => setTimeout(resolve, 200)); + } while (Date.now() < deadline); + const sent = state.messages[0]; + assert.ok(sent, "The message with the reference was not sent"); + assert.deepEqual( + sent.assets.map((asset) => [asset.id, asset.fingerprint]), + [[nodes.video.asset.id, nodes.video.asset.fingerprint]], + ); + assert.deepEqual(errors, []); + console.log(JSON.stringify({ + pickerWithoutCatalog: true, + nodeScopedRead: true, + noDownloadOrCanvasRead: true, + unusableNodeRefused: true, + referenceSent: true, + })); +} finally { + await browser.close(); +} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 6f0f6c200..ed6da9bc3 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -104,6 +104,16 @@ ], "note": "Needs --assistant-fixture services." }, + { + "file": "assistant_chat_references.mjs", + "fixture": true, + "previewSafe": true, + "lanes": [ + "extendedFixture", + "production" + ], + "note": "Needs --assistant-fixture services and ffmpeg. Chat @ picker without the project-wide catalog, node-scoped reference read without media download or canvas re-read, refusal of an unusable node, and the reference reaching the assistant turn." + }, { "file": "assistant_sessions.mjs", "fixture": true, diff --git a/tests/test_creation_history_service.py b/tests/test_creation_history_service.py index a6407a692..e8005b82e 100644 --- a/tests/test_creation_history_service.py +++ b/tests/test_creation_history_service.py @@ -1,6 +1,7 @@ from uuid import uuid4 import pytest +from opendirector.application.creation_assets import CreationAssets from opendirector.application.creation_history import CreationHistory from opendirector.domain.creation.commands import parse_command from opendirector.infrastructure.creation_projects import CreationProjects @@ -553,6 +554,26 @@ def catalog(): assert service.usage(store.snapshot(pid), source.id)['used'] +def test_node_reference_catalog_reads_only_the_chosen_nodes_media(project, monkeypatch): + store, pid, _ = project + first, first_asset = text_material(project, title='First') + text_material(project, title='Second') + service = CreationHistory(store) + full = [row for row in service.reference_catalog(pid) if row['nodeId'] == str(first.id)] + reads, opened = [], [] + monkeypatch.setattr(store, 'records_with_path', lambda *args: reads.append(args)) + original_open = CreationAssets._open_asset_file + monkeypatch.setattr(CreationAssets, '_open_asset_file', staticmethod( + lambda folder, asset: (opened.append(asset.id), original_open(folder, asset))[1])) + rows = service.reference_catalog(pid, [first.id]) + # Choosing one node in the chat must not replay the history or check every file. + assert rows == full and len(rows) == 1 and rows[0]['available'] + assert reads == [] and opened == [first_asset.id] + assert service.reference_catalog(pid, [uuid4()]) == [] + (store.root / 'Unified' / first_asset.path).write_bytes(b'tampered') + assert not service.reference_catalog(pid, [first.id])[0]['available'] + + def test_reference_catalog_checks_files_against_its_one_snapshot(project, monkeypatch): store, pid, _ = project text_material(project, title='First') From 54fc5f7f73e5c3c24374b1d0c59520afe8afc2db 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:40:21 +0000 Subject: [PATCH 2/2] [perf] assistant: read node references in server-sized batches Review of this PR found that the node-scoped catalog read accepts at most 64 nodeId values and answers more with a generic validation error. Through the chat UI a selection is already refused above 64 nodes before any read (pendingReferenceInsertion, unchanged from main), so no current caller sends more. loadNodeReferences now splits longer lists into reads of 64 anyway, so the function is correct for any caller. The browser test now also selects 65 canvas nodes and checks that the chat shows its own limit message, inserts nothing and reads no node references; a unit test covers the batching. Co-Authored-By: Claude Opus 5.5 --- src/backend/referenceCatalog.ts | 29 +++++++--- tests/browser/assistant_chat_references.mjs | 60 +++++++++++++++++++++ tests/nodeReferences.test.ts | 28 ++++++++++ 3 files changed, 110 insertions(+), 7 deletions(-) create mode 100644 tests/nodeReferences.test.ts diff --git a/src/backend/referenceCatalog.ts b/src/backend/referenceCatalog.ts index 57ce04c16..3e424acbe 100644 --- a/src/backend/referenceCatalog.ts +++ b/src/backend/referenceCatalog.ts @@ -9,18 +9,33 @@ export async function loadReferenceCatalog( return request(`${creationPath(projectId)}/reference-catalog`, { signal }); } +/** The most nodeId values one catalog read accepts (the server's limit). */ +export const NODE_REFERENCE_BATCH = 64; + /** The media these canvas nodes own, checked by the server against their * recorded fingerprints. Much cheaper than the whole catalog, and read in the - * foreground because the user is waiting on the reference they just chose. */ + * foreground because the user is waiting on the reference they just chose. + * + * A large canvas selection is read in batches. Several nodes can share one + * asset, so the node count alone does not decide whether the selection fits + * the chat's reference limit; the caller checks the distinct assets. */ export async function loadNodeReferences( projectId: string, nodeIds: readonly string[], signal?: AbortSignal, ): Promise { - const query = nodeIds - .map((id) => `nodeId=${encodeURIComponent(id)}`) - .join("&"); - return request(`${creationPath(projectId)}/reference-catalog?${query}`, { - signal, - }); + const batches: string[][] = []; + for (let start = 0; start < nodeIds.length; start += NODE_REFERENCE_BATCH) + batches.push(nodeIds.slice(start, start + NODE_REFERENCE_BATCH)); + const pages = await Promise.all( + batches.map((batch) => + request( + `${creationPath(projectId)}/reference-catalog?${batch + .map((id) => `nodeId=${encodeURIComponent(id)}`) + .join("&")}`, + { signal }, + ), + ), + ); + return pages.flat(); } diff --git a/tests/browser/assistant_chat_references.mjs b/tests/browser/assistant_chat_references.mjs index 091f1ffaa..17bdaea90 100644 --- a/tests/browser/assistant_chat_references.mjs +++ b/tests/browser/assistant_chat_references.mjs @@ -94,6 +94,48 @@ for (const [index, asset] of seeded.assets.entries()) { } await call(`/api/creation/sessions/${seedSession}`, null, "DELETE"); +/** A project of `count` text nodes, each with its own asset. */ +async function textProject(count) { + const id = crypto.randomUUID(), + session = crypto.randomUUID(); + const own = { ...headers, "X-OpenDirector-Session": session }; + const send = async (type, payload) => { + const response = await fetch(`${api}/api/creation/projects/${id}/commands`, { + method: "POST", + headers: own, + body: JSON.stringify({ commandId: crypto.randomUUID(), projectId: id, type, payload }), + }); + const result = await response.json(); + assert.equal(result.status, "applied", JSON.stringify(result)); + }; + await send("project.create", { name: `Chat selection ${id.slice(0, 8)}` }); + assert.ok((await fetch(`${api}/api/creation/projects/${id}/open`, { method: "POST", headers: own })).ok); + for (let index = 0; index < count; index++) + await send("asset.writeText", { name: `片段 ${index}.md`, text: `片段内容 ${index}` }); + const snapshot = await (await fetch(`${api}/api/creation/projects/${id}`, { headers: own })).json(); + for (const [index, asset] of snapshot.assets.entries()) + await send("canvas.show", { + item: { + id: crypto.randomUUID(), + projectId: id, + kind: "text", + title: `片段 ${index}`, + visible: true, + position: { x: 100 + (index % 13) * 240, y: 100 + Math.floor(index / 13) * 200 }, + width: 200, + height: 140, + binding: { + role: "material", + objectRef: { assetId: asset.id, revision: asset.revision, fingerprint: asset.fingerprint, kind: asset.kind }, + }, + }, + }); + await fetch(`${api}/api/creation/sessions/${session}`, { method: "DELETE", headers: own }); + return id; +} +// One more node than the chat accepts in one insertion. +const oversizedSelection = await textProject(65); + const browser = await chromium.launch({ headless: true, ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}), @@ -181,8 +223,26 @@ try { sent.assets.map((asset) => [asset.id, asset.fingerprint]), [[nodes.video.asset.id, nodes.video.asset.fingerprint]], ); + + // Selecting more nodes than one insertion accepts is refused with the chat's + // own message before any node reference is read. + await page.goto(`${base}/ai-tool/ai-canvas/${oversizedSelection}`); + await page.getByText("已保存到本机", { exact: true }).waitFor(); + if (!(await panel.isVisible())) + await page.getByRole("button", { name: "与 AI 对话", exact: true }).click(); + await editor.waitFor(); + await page.locator(".cw-workspace").focus(); + await page.keyboard.press("Control+a"); + await page.waitForFunction(() => document.querySelectorAll(".react-flow__node.selected").length === 65); + await panel.locator("[data-pending-references]").waitFor(); + const selectionReads = requests.length; + await editor.click(); + await panel.getByText("每次最多添加 64 份参考素材,整批未插入。", { exact: true }).waitFor(); + assert.equal(await editor.locator("[data-reference]").count(), 0); + assert.deepEqual(requests.slice(selectionReads).filter((path) => path.includes("/reference-catalog")), []); assert.deepEqual(errors, []); console.log(JSON.stringify({ + oversizedSelectionRefused: true, pickerWithoutCatalog: true, nodeScopedRead: true, noDownloadOrCanvasRead: true, diff --git a/tests/nodeReferences.test.ts b/tests/nodeReferences.test.ts new file mode 100644 index 000000000..04ec26820 --- /dev/null +++ b/tests/nodeReferences.test.ts @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + loadNodeReferences, + NODE_REFERENCE_BATCH, +} from "../src/backend/referenceCatalog.ts"; + +test("a large canvas selection reads its node references in server-sized batches", async () => { + const original = globalThis.fetch; + const reads: string[][] = []; + globalThis.fetch = async (url) => { + const ids = new URL(String(url), "http://local").searchParams.getAll("nodeId"); + reads.push(ids); + return Response.json(ids.map((nodeId) => ({ id: `asset-${nodeId}`, nodeId, available: true }))); + }; + try { + const ids = Array.from({ length: NODE_REFERENCE_BATCH * 2 + 1 }, (_, index) => `node-${index}`); + const rows = await loadNodeReferences("project", ids); + // The server accepts at most 64 nodeId values per read. + assert.deepEqual(reads.map((batch) => batch.length), [64, 64, 1]); + assert.deepEqual(rows.map((row) => row.nodeId), ids); + reads.length = 0; + await loadNodeReferences("project", ids.slice(0, 1)); + assert.deepEqual(reads, [["node-0"]]); + } finally { + globalThis.fetch = original; + } +});