diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index ec4ccaf17..2170726db 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -37,6 +37,10 @@ const workflows = [ { name: "capability discovery", script: "tests/browser/capability_discovery.mjs" }, { name: "canvas composer placement", script: "tests/browser/canvas_composer_placement.mjs" }, { name: "created node focus", script: "tests/browser/created_node_focus.mjs" }, + { + name: "assistant reference dedupe", + script: "tests/browser/assistant_reference_dedupe.mjs", + }, { name: "cross canvas paste", script: "tests/browser/cross_canvas_paste.mjs" }, { name: "reference reconnect", script: "tests/browser/reference_reconnect.mjs" }, { diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 58f6f6149..600ec6ecf 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -25,6 +25,7 @@ import { currentReferences, fingerprintMatches, referenceContent, + referencedCanvasNodeIds, type ReferenceAsset, } from "./chatReferenceContent.ts"; import { @@ -37,7 +38,8 @@ import type { CanvasNode } from "./model"; import { pendingCanvasReferences, pendingReferenceInsertion, - samePendingReferences, + sameStagedPendingReferences, + unreferencedPendingItems, } from "./pendingCanvasReferences.ts"; import { assetOptionId, referenceCandidates } from "./referenceCandidates.ts"; import { type MentionOption } from "./referenceMentions"; @@ -152,6 +154,17 @@ export function AssistantPanel({ selectionRequest, ); const pending = pendingReferences.pending; + const referencedNodeIds = referencedCanvasNodeIds( + value.draftContent, + chat.referenceAssets, + ); + const staged = pending + ? { + ...pending, + items: unreferencedPendingItems(pending.items, referencedNodeIds), + } + : null; + const stagedCount = staged?.items.length ?? 0; const [checkingReferences, setCheckingReferences] = useState(false); const confirming = useRef(null); // Keep the canvas defaulting new nodes to the model this dialog is using. @@ -275,9 +288,12 @@ export function AssistantPanel({ log.current.scrollTop = log.current.scrollHeight; }, [value.messages, open, results]); useEffect(() => () => confirming.current?.abort(), [pending?.id]); + useEffect(() => { + if (pending && !stagedCount) pendingReferences.cancel(); + }, [pending, stagedCount, pendingReferences.cancel]); const confirmPending = async (end: number) => { - if (!pending || referenceDisabled || confirming.current) return; - const batch = pending, + if (!staged || referenceDisabled || confirming.current) return; + const batch = staged, before = latest.current.value; const abort = new AbortController(); confirming.current = abort; @@ -287,8 +303,9 @@ export function AssistantPanel({ pendingReferences.isCurrent(batch.id) && latest.current.value.draft === before.draft && latest.current.value.draftContent === before.draftContent && - samePendingReferences( - pendingCanvasReferences(latest.current.selectedNodes), + sameStagedPendingReferences( + latest.current.selectedNodes, + referencedNodeIds, batch.items, ); try { @@ -655,7 +672,7 @@ export function AssistantPanel({ void chat.send(); }} > - {pending && ( + {stagedCount > 0 && staged && (
- {t("assistant.panel.pendingCount", { count: pending.items.length })} ·{" "} + {t("assistant.panel.pendingCount", { count: staged.items.length })} ·{" "} {referenceDisabled ? t("assistant.panel.pendingDisabled") : t("assistant.panel.pendingHint")} @@ -678,7 +695,7 @@ export function AssistantPanel({
- {pending.items.map((item) => ( + {staged.items.map((item) => (
void confirmPending(at.end) : undefined + stagedCount > 0 ? (at) => void confirmPending(at.end) : undefined } onChange={chat.setContent} onPasteFiles={(files) => void upload(files)} diff --git a/src/canvas/chatReferenceContent.ts b/src/canvas/chatReferenceContent.ts index 3c990b43e..77907b508 100644 --- a/src/canvas/chatReferenceContent.ts +++ b/src/canvas/chatReferenceContent.ts @@ -40,18 +40,36 @@ export type ReferenceAsset = ChatAsset & { height?: number | null; durationSeconds?: number | null; }; +export function referenceNodeId( + part: Extract, + asset: ReferenceAsset | undefined, +) { + return part.binding === "asset" + ? (asset?.logicalNodeId ?? asset?.nodeId) + : (part.nodeId ?? asset?.nodeId ?? asset?.logicalNodeId); +} /** Visibility is about source identity, never a matching filename or asset. */ export function referenceIsOffCanvas( part: Extract, asset: ReferenceAsset | undefined, visibleNodeIds: ReadonlySet, ) { - const id = - part.binding === "asset" - ? (asset?.logicalNodeId ?? asset?.nodeId) - : (part.nodeId ?? asset?.nodeId ?? asset?.logicalNodeId); + const id = referenceNodeId(part, asset); return !id || !visibleNodeIds.has(id); } +export function referencedCanvasNodeIds( + content: ReferenceContent | null | undefined, + assets: readonly ReferenceAsset[], +) { + const byId = new Map(assets.map((asset) => [asset.id, asset])); + const ids = new Set(); + for (const part of content ?? []) + if (part.type === "reference") { + const id = referenceNodeId(part, byId.get(part.assetId)); + if (id) ids.add(id); + } + return ids; +} export function fingerprintMatches(asset: ReferenceAsset, value: string) { return ( asset.fingerprint === value || !!asset.fingerprintAliases?.includes(value) diff --git a/src/canvas/pendingCanvasReferences.ts b/src/canvas/pendingCanvasReferences.ts index 113e6035b..214519101 100644 --- a/src/canvas/pendingCanvasReferences.ts +++ b/src/canvas/pendingCanvasReferences.ts @@ -122,3 +122,21 @@ export function pendingReferenceInsertion( ); return { value: next, start, inserted, caret: start + inserted.length }; } + +export function unreferencedPendingItems( + items: readonly PendingCanvasReference[], + referenced: ReadonlySet, +) { + return items.filter((item) => !referenced.has(item.nodeId)); +} + +export function sameStagedPendingReferences( + selected: readonly CanvasNode[], + referenced: ReadonlySet, + batch: readonly PendingCanvasReference[], +) { + return samePendingReferences( + unreferencedPendingItems(pendingCanvasReferences(selected), referenced), + batch, + ); +} diff --git a/tests/browser/assistant_reference_dedupe.mjs b/tests/browser/assistant_reference_dedupe.mjs new file mode 100644 index 000000000..00abeb885 --- /dev/null +++ b/tests/browser/assistant_reference_dedupe.mjs @@ -0,0 +1,161 @@ +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 api = process.env.CREATION_API_URL ?? "http://127.0.0.1:8019"; +const headers = { "X-OpenDirector-Request": "1", "Content-Type": "application/json" }; +async function call(path, body) { + const response = await fetch(api + path, { headers, ...(body ? { method: "POST", body: JSON.stringify(body) } : {}) }); + assert.ok(response.ok, await response.clone().text()); + return response.json(); +} +assert.equal((await call("/api/creation-test-health")).isolated, true); +const browser = await launchBrowser(); +const page = await browser.newPage({ locale: "en-US", viewport: { width: 1600, height: 1000 } }); +await page.addInitScript(() => { + try { localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); } catch {} +}); +page.setDefaultTimeout(15000); +const projectId = crypto.randomUUID(); +async function arrange(imageIds) { + await page.evaluate(async ({ pid, ids }) => { + const { creationClient, objectVersion } = await import("/src/backend/creationClient.ts"); + const client = creationClient(pid); + await client.refresh(); + await client.command( + "canvas.move", + { items: client.snapshot.canvasItems.map((item) => ({ + itemId: item.id, + position: ids.includes(item.id) + ? { x: 150 + Math.max(0, ids.indexOf(item.id)) * 300, y: 150 } + : { x: 150, y: 650 }, + })) }, + client.snapshot.canvasItems.map((item) => objectVersion("canvas_item", item)), + ); + }, { pid: projectId, ids: imageIds }); + await page.locator(".cw-workspace").focus(); + await page.keyboard.press("Shift+1"); + await page.waitForTimeout(600); +} +try { + await call(`/api/creation/projects/${projectId}/commands`, { commandId: crypto.randomUUID(), projectId, + type: "project.create", payload: { name: `Reference dedupe ${projectId.slice(0, 8)}` } }); + await page.goto(`${base}/ai-tool/ai-canvas/${projectId}?creation=unified`); + await page.getByText("Saved on this device", { exact: true }).waitFor(); + const chatToggle = page.locator(".cw-chat-button"); + await chatToggle.waitFor(); + const panel = page.locator(".cw-assistant-panel:not([hidden])"); + for (let attempt = 0; attempt < 5 && !(await panel.isVisible().catch(() => false)); attempt++) { + if (await chatToggle.getAttribute("aria-expanded") !== "true") await chatToggle.click(); + await page.waitForTimeout(400); + } + await panel.waitFor(); + await page.waitForFunction(() => !!document.querySelector(".cw-assistant-panel .cw-chat-reference-editor[contenteditable=true]")); + const tray = panel.locator("[data-pending-references]"); + const trayItems = panel.locator("[data-pending-references] .cw-pending-reference"); + const editor = panel.locator(".cw-chat-reference-editor"); + const chips = panel.locator(".cw-chat-reference-editor [data-reference]"); + + await page.getByLabel("Choose local asset files", { exact: true }).setInputFiles({ + name: "note.txt", mimeType: "text/plain", buffer: Buffer.from("Body text"), + }); + let textItem; + for (let attempt = 0; attempt < 150; attempt++) { + const snapshot = await call(`/api/creation/projects/${projectId}`); + textItem = snapshot.canvasItems.find((item) => item.kind === "text"); + if (textItem && snapshot.assets.some((asset) => asset.kind === "text")) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + assert.ok(textItem, "the uploaded text node exists"); + const textNode = page.locator(`.react-flow__node[data-id="${textItem.id}"]`); + await textNode.waitFor(); + await page.waitForTimeout(1000); + await page.mouse.click(400, 800); + await page.waitForTimeout(500); + await textNode.click(); + await tray.waitFor(); + assert.equal(await trayItems.count(), 1, "a text node is staged once"); + await editor.click(); + await chips.first().waitFor(); + await tray.waitFor({ state: "detached" }); + assert.equal(await chips.count(), 1, "the text node is inserted as a single chip"); + await page.waitForTimeout(400); + await textNode.click(); + await page.waitForTimeout(800); + assert.equal(await trayItems.count(), 0, "re-selecting a referenced text node must not restage it"); + assert.equal(await chips.count(), 1, "the composer keeps the single text reference"); + await page.screenshot({ path: "/tmp/assistant-reference-dedupe-text.png" }); + + await page.getByLabel("Choose local asset files", { exact: true }).setInputFiles({ + name: "reference.png", mimeType: "image/png", + buffer: Buffer.from("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAGUlEQVR4nGNsYGhgIAUwkaR6VMOohiGlAQBCPQEgiSD+iQAAAABJRU5ErkJggg==", "base64"), + }); + let source; + for (let attempt = 0; attempt < 150; attempt++) { + const snapshot = await call(`/api/creation/projects/${projectId}`); + source = snapshot.canvasItems.find((item) => item.kind === "image"); + if (source && snapshot.assets.length) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + assert.ok(source, "the uploaded node exists"); + const node = page.locator(`.react-flow__node[data-id="${source.id}"]`); + await node.waitFor(); + await page.waitForTimeout(1000); + await arrange([source.id]); + await page.mouse.click(400, 800); + await page.waitForTimeout(500); + + await node.click(); + await tray.waitFor(); + assert.equal(await trayItems.count(), 1, "an unreferenced node is staged once"); + + await editor.click(); + await chips.nth(1).waitFor(); + await tray.waitFor({ state: "detached" }); + assert.equal(await chips.count(), 2, "the staged node is inserted as a single chip"); + + await page.waitForTimeout(400); + await node.click(); + await page.waitForTimeout(800); + assert.equal(await trayItems.count(), 0, "re-selecting a referenced node must not restage it"); + assert.equal(await chips.count(), 2, "the composer keeps the single inserted reference"); + + await page.getByLabel("Choose local asset files", { exact: true }).setInputFiles({ + name: "reference-2.png", mimeType: "image/png", + buffer: Buffer.from("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAIAAACQkWg2AAAAGUlEQVR4nGNkWBXKQApgIkn1qIZRDUNKAwA+2gEfy6Dt2AAAAABJRU5ErkJggg==", "base64"), + }); + let second; + for (let attempt = 0; attempt < 150; attempt++) { + const snapshot = await call(`/api/creation/projects/${projectId}`); + second = snapshot.canvasItems.find((item) => item.kind === "image" && item.id !== source.id); + if (second && snapshot.assets.length >= 2) break; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + assert.ok(second, "the second uploaded node exists"); + const other = page.locator(`.react-flow__node[data-id="${second.id}"]`); + await other.waitFor(); + await arrange([source.id, second.id]); + await node.click(); + await page.waitForTimeout(600); + await other.click({ modifiers: ["Shift"] }); + await page.waitForTimeout(800); + assert.equal(await trayItems.count(), 1, "a mixed selection stages only the unreferenced node"); + assert.deepEqual( + (await trayItems.allInnerTexts()).map((text) => text.trim()), + ["reference-2.png"], + "the mixed selection keeps only the unreferenced node in the tray", + ); + await editor.click(); + await chips.nth(2).waitFor(); + assert.equal(await chips.count(), 3, "the mixed selection inserts one more chip"); + await page.waitForTimeout(400); + await other.click(); + await page.waitForTimeout(800); + assert.equal(await trayItems.count(), 0, "the second node is filtered once it is referenced"); + assert.equal(await chips.count(), 3); + assert.equal((await call(`/api/creation/projects/${projectId}`)).jobs.length, 0); + + await page.screenshot({ path: "/tmp/assistant-reference-dedupe.png" }); + console.log(JSON.stringify({ passed: true, checks: ["text node staged once", "text node inserted once", "text node re-select stays filtered", "stage once", "insert once", "re-select stays filtered", "mixed selection filtered", "no duplicate chip", "no paid job"] })); +} finally { + await browser.close(); +} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index fc5ca1dcc..b33a369f2 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -336,6 +336,12 @@ "gate" ] }, + { + "file": "assistant_reference_dedupe.mjs", + "lanes": [ + "gate" + ] + }, { "file": "creation_ripple.mjs", "lanes": [ diff --git a/tests/chatReferenceContent.test.ts b/tests/chatReferenceContent.test.ts index 4e65717b2..ae5d2e10a 100644 --- a/tests/chatReferenceContent.test.ts +++ b/tests/chatReferenceContent.test.ts @@ -4,10 +4,12 @@ import { blankContent, contentText, referenceContent, + referencedCanvasNodeIds, referenceIds, type ReferenceAsset, type ReferenceContent, } from "../src/canvas/chatReferenceContent.ts"; + import { editContent, editingText } from "../src/canvas/chatReferenceDOM.ts"; import { referenceInsertion } from "../src/canvas/chatReferenceInsertion.ts"; @@ -131,6 +133,30 @@ test("over-limit and mismatched-version insertions reject the entire batch", () assert.deepEqual(referenceIds(body), ["a"]); }); +test("draft references resolve to their canvas source through the catalog", () => { + const canvasPart: ReferenceContent = [ + { type: "reference", assetId: "c", nodeId: "node-canvas", name: "C.png" }, + { type: "reference", assetId: "d", binding: "asset", name: "D.png" }, + { type: "reference", assetId: "missing", name: "Gone.png" }, + { type: "text", text: "caption" }, + ]; + const assets: ReferenceAsset[] = [ + { ...a, id: "c", nodeId: "node-canvas", logicalNodeId: "node-catalog" }, + { + ...a, + id: "d", + nodeId: "node-pinned-current", + logicalNodeId: "node-pinned-logical", + }, + ]; + assert.deepEqual( + [...referencedCanvasNodeIds(canvasPart, assets)].sort(), + ["node-canvas", "node-pinned-logical"], + ); + assert.equal(referencedCanvasNodeIds(undefined, assets).size, 0); + assert.equal(referencedCanvasNodeIds([], assets).size, 0); +}); + test("line breaks and spaces left by deletion keep the editor empty", () => { assert.equal(blankContent([]), true); assert.equal(blankContent([{ type: "text", text: "\n" }]), true); diff --git a/tests/pendingCanvasReferences.test.ts b/tests/pendingCanvasReferences.test.ts index 3990ae99e..164a4674c 100644 --- a/tests/pendingCanvasReferences.test.ts +++ b/tests/pendingCanvasReferences.test.ts @@ -5,6 +5,8 @@ import { pendingCanvasReferences, pendingReferenceInsertion, samePendingReferences, + sameStagedPendingReferences, + unreferencedPendingItems, } from "../src/canvas/pendingCanvasReferences.ts"; test("staging keeps blank nodes and media information without treating generation prompts as saved text", () => { @@ -117,3 +119,50 @@ test("subjects stage one node with its actual main image; description-only subje assert.equal(staged.thumbnail, subject.data.subject!.main.src); assert.equal(pendingReferenceInsertion("", 0, [staged]).value, "@角色 "); }); + +test("a node already referenced by the composer is not staged a second time", () => { + const text = createNode("text", undefined, { title: "文本 1", text: "正文" }); + const image = createNode("image", undefined, { + title: "图 1", + src: "data:image/png,fixture", + }); + const staged = pendingCanvasReferences([text, image]); + assert.deepEqual( + staged.map((item) => item.nodeId), + [text.id, image.id], + ); + const referenced = new Set([text.id, image.id!]); + assert.deepEqual(unreferencedPendingItems(staged, referenced), []); + assert.deepEqual( + unreferencedPendingItems(staged, new Set([text.id])).map((item) => item.nodeId), + [image.id], + ); + assert.equal(staged.length, 2); +}); + +test("a mixed selection stays fresh while its referenced item is already in the draft", () => { + const referencedNode = createNode("text", undefined, { + title: "已有参考", + text: "正文", + }); + const freshNode = createNode("image", undefined, { + title: "新增参考", + src: "data:image/png,fixture", + }); + const selected = [referencedNode, freshNode]; + const referenced = new Set([referencedNode.id]); + const filtered = unreferencedPendingItems( + pendingCanvasReferences(selected), + referenced, + ); + assert.deepEqual(filtered.map((item) => item.nodeId), [freshNode.id]); + assert.equal(sameStagedPendingReferences(selected, referenced, filtered), true); + assert.equal( + sameStagedPendingReferences( + selected, + referenced, + pendingCanvasReferences(selected), + ), + false, + ); +});