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
2 changes: 2 additions & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ For GPT Image models, open **Generation settings** and choose **Quality** from *

After typing `@`, use the up and down arrow keys to select an asset, the left and right arrow keys to switch categories, `Enter` to insert, and `Esc` to close the picker. References are inserted into the text as single units. Removing the last reference to a source also removes its corresponding reference connection.

The picker shows the first frame for saved video nodes. If a preview is unavailable, the video icon appears and the reference remains selectable.

When an image or video node is connected to a text node with content, the prompt may stay blank: generation uses the text as is as the prompt, and anything typed in the prompt is added to it. Connected text carries no "Reference N: title" label; only text inserted with `@` keeps its label so the inline mention points at it. One text node can feed several generation nodes that use different models, and they all pick up edits to the text. Speech and music never read text references and still need their own text or style.

An empty node must first receive an upload, saved text, or generated content before it can serve as a valid reference for other nodes. When uploading a node's own content, the file type must match the node. To add references, use connections, `@`, or the reference controls in the generation panel.
Expand Down
2 changes: 2 additions & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,8 @@ GPT Image 模型可在“生成参数”中选择“质量”,取值为“自

输入 `@` 后可用上下方向键选择素材、左右方向键切换分类,按 `Enter` 插入,按 `Esc` 关闭选择。引用以整体形式插入正文;删除同一来源的最后一次引用会移除相应参考连线。

选择列表会显示画布上已保存视频的首帧。预览不可用时显示视频图标,仍可选择该素材作为引用。

图片或视频节点连接了有内容的文本节点时,提示词可以留空:生成时直接把文本原样作为提示词,也可以在提示词中补充要求。连线的文本不加“参考N:标题”标签;只有用 `@` 插入的文本保留标签,以便提示词中的引用对应到它。一个文本节点可以同时连到多个使用不同模型的生成节点,修改文本后各节点都会使用新内容。语音和音乐不读取文本参考,仍需填写正文或风格。

空白节点需要先上传、保存文本或生成内容,才能作为其他节点的有效参考。向已有节点上传本体素材时,文件类型应与节点一致;添加参考请使用连线、`@` 或生成面板的添加入口。
Expand Down
7 changes: 4 additions & 3 deletions src/backend/creationClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -639,9 +639,10 @@
this.mediaListeners.delete(listener);
};
}
thumbnailUrl(assetId: string, signal?: AbortSignal) {
thumbnailUrl(assetId: string, signal?: AbortSignal, kind: "image" | "video" = "image") {
signal?.throwIfAborted();
const key = `thumbnail:${assetId}`;
const rendition = kind === "video" ? "preview" : "thumbnail";
const key = `${rendition}:${assetId}`;
let pending = this.media.get(key);
if (!pending) {
const read = { controller: new AbortController(), waiting: 0, retained: false };
Expand All @@ -651,7 +652,7 @@
resilientRead(
async (signal) => {
const response = await fetch(
`/api${creationPath(this.id)}/assets/${assetId}/thumbnail`,
`/api${creationPath(this.id)}/assets/${assetId}/${rendition}`,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I checked the flagged call at this revision. It sends a GET with no request body to the app’s relative project asset API. The rendition is selected from the fixed preview and thumbnail routes, the project and asset IDs identify the requested resource, and the JPEG bytes come back in the response. The CodeQL workflow completed, but alert #91 remains open. The reported source-to-sink path still needs to be checked before deciding whether to change the code or dismiss the alert.

{ headers, signal },
);
if (!response.ok) throw await responseError(response);
Expand Down
54 changes: 45 additions & 9 deletions src/canvas/ChatReferenceEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,37 @@ import "./reference-mentions.css";
import { assetDisplayName } from "./assetNames.ts";
import { useT } from "../i18n/I18nProvider.tsx";
import type { MessageKey } from "../i18n/types.ts";
import { AssetMedia } from "./useAssetMedia.tsx";
import { AssetMedia, useInViewport } from "./useAssetMedia.tsx";
import { parseAssetSource } from "../backend/assetSource.ts";
import { resolveMediaSource } from "../backend/creationClient.ts";
import { creationClient, resolveMediaSource } from "../backend/creationClient.ts";

function MentionVideoPreview({
source,
kind,
}: { source: string; kind: MentionOption["kind"] }) {
const [observe, visible] = useInViewport<HTMLSpanElement>();
const [src, setSrc] = useState<string>();
useEffect(() => {
const asset = parseAssetSource(source);
if (!visible || !asset) return;
const abort = new AbortController();
void creationClient(asset.projectId).thumbnailUrl(asset.assetId, abort.signal, "video")
.then((url) => {
if (!abort.signal.aborted) setSrc(url);
})
.catch(() => {});
return () => abort.abort();
}, [source, visible]);
return (
<span ref={observe} className="cw-reference-mention-thumbnail">
{src ? (
<img src={src} alt="" draggable={false} onError={() => setSrc(undefined)} />
) : (
<CanvasIcon name={kind} size={22} />
)}
</span>
);
}

export interface ChatReferenceEditorHandle {
focus: () => void;
Expand Down Expand Up @@ -1346,13 +1374,21 @@ export function ChatReferenceEditor({
onMouseEnter={() => setActive(index)}
onClick={() => void choose(option)}
>
<span className="cw-reference-mention-thumbnail">
{option.thumbnail ? (
<AssetMedia as="img" src={option.thumbnail} alt="" draggable={false} />
) : (
<CanvasIcon name={option.kind} size={22} />
)}
</span>
{option.videoPreview && !option.disabledReason ? (
<MentionVideoPreview
key={option.videoPreview}
source={option.videoPreview}
kind={option.kind}
/>
) : (
<span className="cw-reference-mention-thumbnail">
{option.thumbnail ? (
<AssetMedia as="img" src={option.thumbnail} alt="" draggable={false} />
) : (
<CanvasIcon name={option.kind} size={22} />
)}
</span>
)}
<span>
<strong>{option.title}</strong>
<small>{option.disabledReason || option.detail}</small>
Expand Down
11 changes: 8 additions & 3 deletions src/canvas/referenceMentions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { canSourceReference } from "./connectionPolicy.ts";
import { assetDisplayName } from "./assetNames.ts";
import { tNow } from "../i18n/messages.ts";
import type { MessageKey } from "../i18n/types.ts";
import { parseAssetSource } from "../backend/assetSource.ts";

export const REFERENCE_CATEGORIES = [
{ id: "all", label: "errors.stats.all" },
Expand All @@ -20,6 +21,7 @@ export interface MentionOption {
title: string;
detail: string;
thumbnail?: string;
videoPreview?: string;
disabledReason?: string | null;
}
export interface MentionRange {
Expand Down Expand Up @@ -83,7 +85,9 @@ export function nodeMentionOptions(
return nodes.flatMap((node) => {
const category = REFERENCE_CATEGORIES.find((item) => item.id === node.type);
if (!category || !canSourceReference(node)) return [];
const image = node.type === "subject" ? node.data.subject?.main : undefined;
const main = node.type === "subject" ? node.data.subject?.main : undefined;
const video =
node.type === "video" ? node.data.src : main?.kind === "video" ? main.src : undefined;
return [
{
id: node.id,
Expand All @@ -93,9 +97,10 @@ export function nodeMentionOptions(
thumbnail:
node.type === "image"
? node.data.src
: image?.kind === "image"
? image.src
: main?.kind === "image"
? main.src
: undefined,
videoPreview: parseAssetSource(video) ? video : undefined,
disabledReason: issue(node),
},
];
Expand Down
30 changes: 27 additions & 3 deletions tests/browser/assistant_chat_references.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,38 @@ try {
const editor = panel.getByRole("textbox", { name: "消息内容", exact: true });
await editor.waitFor();
const picker = page.getByRole("dialog", { name: "引用项目资产", exact: true });
const videoOption = picker.getByRole("option", { name: /^镜头\.mp4/ });
const previewPath = `/api/creation/projects/${projectId}/assets/${nodes.video.asset.id}/preview`;
const previewReads = () => requests.filter((path) => path === previewPath).length;
assert.equal(previewReads(), 0);
await page.route(`**${previewPath}`, (route) => route.fulfill({ status: 422, json: {} }), { times: 1 });

const referenceButton = panel.getByRole("button", { name: "引用项目素材", exact: true });
const unavailable = page.waitForResponse(`**${previewPath}`);
await referenceButton.click();
assert.equal((await unavailable).status(), 422);
await videoOption.locator(".cw-reference-mention-thumbnail svg").waitFor();
assert.notEqual(await videoOption.getAttribute("aria-disabled"), "true");
await page.keyboard.press("Escape");
await picker.waitFor({ state: "hidden" });
await referenceButton.click();
const thumbnail = videoOption.locator("img");
await thumbnail.waitFor();
assert.ok(await thumbnail.evaluate(async (image) => {
await image.decode();
return image.naturalWidth > 0;
}));
assert.equal(previewReads(), 2);
await page.keyboard.press("Escape");
await picker.waitFor({ state: "hidden" });
await editor.click();
await editor.pressSequentially("参考 @");
await picker.getByRole("option").first().waitFor();
await thumbnail.waitFor();
assert.equal(previewReads(), 2, "Reopening must reuse the cached video frame");
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 videoOption.click();
await picker.waitFor({ state: "hidden" });
const chip = editor.locator("[data-reference]");
await chip.waitFor();
Expand All @@ -185,7 +209,7 @@ try {
assert.equal(reference.nodeId, nodes.video.id);
const pick = requests.slice(before);
assert.deepEqual(
pick.filter((path) => path.includes("/reference-catalog")),
pick.filter((path) => path.includes("/reference-catalog?")),
[`/api/creation/projects/${projectId}/reference-catalog?nodeId=${nodes.video.id}`],
);
assert.deepEqual(
Expand Down
32 changes: 32 additions & 0 deletions tests/creationClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1914,6 +1914,38 @@ test("display reads stop only after every on-screen consumer leaves", async () =
}
});

test("video first-frame reads cancel when their last observer leaves", { timeout: 2_000 }, async () => {
const original = globalThis.fetch;
const { client } = mediaFixture();
let requestStarted!: (signal: AbortSignal) => void;
const request = new Promise<AbortSignal>((resolve) => { requestStarted = resolve; });
globalThis.fetch = async (url, options) => {
assert.match(String(url), /\/assets\/video-id\/preview$/);
const signal = options!.signal!;
requestStarted(signal);
return new Promise<Response>((_, reject) => {
signal.addEventListener("abort", () => reject(signal.reason), { once: true });
});
};
try {
const first = new AbortController();
const second = new AbortController();
const reads = [first, second].map(({ signal }) => client.thumbnailUrl("video-id", signal, "video"));
const results = Promise.allSettled(reads);
const underlying = await request;
first.abort();
await assert.rejects(reads[0]!, { name: "AbortError" });
assert.equal(underlying.aborted, false);
second.abort();
await assert.rejects(reads[1]!, { name: "AbortError" });
assert.equal(underlying.aborted, true);
await results;
} finally {
client.close();
globalThis.fetch = original;
}
});

test("a failed display read is reported and recovers on retry", async () => {
const original = globalThis.fetch;
const { client, snapshot } = mediaFixture();
Expand Down
Loading