Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions scripts/run-browser-suite.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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" },
{
Expand Down
35 changes: 26 additions & 9 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
currentReferences,
fingerprintMatches,
referenceContent,
referencedCanvasNodeIds,
type ReferenceAsset,
} from "./chatReferenceContent.ts";
import {
Expand All @@ -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";
Expand Down Expand Up @@ -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<AbortController | null>(null);
// Keep the canvas defaulting new nodes to the model this dialog is using.
Expand Down Expand Up @@ -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;
Expand All @@ -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 {
Expand Down Expand Up @@ -655,7 +672,7 @@ export function AssistantPanel({
void chat.send();
}}
>
{pending && (
{stagedCount > 0 && staged && (
<div
className="cw-pending-references"
data-pending-references
Expand All @@ -664,7 +681,7 @@ export function AssistantPanel({
>
<div className="cw-pending-reference-heading">
<span role="status">
{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")}
Expand All @@ -678,7 +695,7 @@ export function AssistantPanel({
</button>
</div>
<div className="cw-pending-reference-list">
{pending.items.map((item) => (
{staged.items.map((item) => (
<div
key={item.nodeId}
className={`cw-pending-reference${item.error ? " is-invalid" : ""}`}
Expand Down Expand Up @@ -786,7 +803,7 @@ export function AssistantPanel({
loading={false}
loadError=""
onConfirmPending={
pending ? (at) => void confirmPending(at.end) : undefined
stagedCount > 0 ? (at) => void confirmPending(at.end) : undefined
}
onChange={chat.setContent}
onPasteFiles={(files) => void upload(files)}
Expand Down
26 changes: 22 additions & 4 deletions src/canvas/chatReferenceContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,18 +40,36 @@ export type ReferenceAsset = ChatAsset & {
height?: number | null;
durationSeconds?: number | null;
};
export function referenceNodeId(
part: Extract<ContentPart, { type: "reference" }>,
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<ContentPart, { type: "reference" }>,
asset: ReferenceAsset | undefined,
visibleNodeIds: ReadonlySet<string>,
) {
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<string>();
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)
Expand Down
18 changes: 18 additions & 0 deletions src/canvas/pendingCanvasReferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,3 +122,21 @@ export function pendingReferenceInsertion(
);
return { value: next, start, inserted, caret: start + inserted.length };
}

export function unreferencedPendingItems(
items: readonly PendingCanvasReference[],
referenced: ReadonlySet<string>,
) {
return items.filter((item) => !referenced.has(item.nodeId));
}

export function sameStagedPendingReferences(
selected: readonly CanvasNode[],
referenced: ReadonlySet<string>,
batch: readonly PendingCanvasReference[],
) {
return samePendingReferences(
unreferencedPendingItems(pendingCanvasReferences(selected), referenced),
batch,
);
}
161 changes: 161 additions & 0 deletions tests/browser/assistant_reference_dedupe.mjs
Original file line number Diff line number Diff line change
@@ -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();
}
6 changes: 6 additions & 0 deletions tests/browser/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,12 @@
"gate"
]
},
{
"file": "assistant_reference_dedupe.mjs",
"lanes": [
"gate"
]
},
{
"file": "creation_ripple.mjs",
"lanes": [
Expand Down
26 changes: 26 additions & 0 deletions tests/chatReferenceContent.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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);
Expand Down
Loading
Loading