Skip to content
Merged
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
5 changes: 3 additions & 2 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
23 changes: 18 additions & 5 deletions packages/core/src/opendirector/application/creation_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/backend/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export function backgroundRead<T>(task: () => Promise<T>, 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<T>(path: string, options: RequestInit = {}, leaseRenewed = false): Promise<T> {
const run = () => requestNow<T>(path, options, leaseRenewed);
Expand Down
31 changes: 31 additions & 0 deletions src/backend/referenceCatalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,34 @@ export async function loadReferenceCatalog(
): Promise<ReferenceAsset[]> {
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.
*
* 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<ReferenceAsset[]> {
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<ReferenceAsset[]>(
`${creationPath(projectId)}/reference-catalog?${batch
.map((id) => `nodeId=${encodeURIComponent(id)}`)
.join("&")}`,
{ signal },
),
),
);
return pages.flat();
}
6 changes: 4 additions & 2 deletions src/canvas/AssistantPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
27 changes: 11 additions & 16 deletions src/canvas/useAssistantChat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -432,26 +430,23 @@ 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,
);
if (!assets.length)
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,
Expand Down
1 change: 0 additions & 1 deletion src/i18n/messages/en-US/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.",
Expand Down
1 change: 0 additions & 1 deletion src/i18n/messages/zh-CN/assistant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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": "固定参考素材缺失或内容已改变。",
Expand Down
Loading
Loading