diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 44908aea4..18e7e2e22 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -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. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index b246ba3b6..791fdfd5b 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -131,6 +131,8 @@ GPT Image 模型可在“生成参数”中选择“质量”,取值为“自 输入 `@` 后可用上下方向键选择素材、左右方向键切换分类,按 `Enter` 插入,按 `Esc` 关闭选择。引用以整体形式插入正文;删除同一来源的最后一次引用会移除相应参考连线。 +选择列表会显示画布上已保存视频的首帧。预览不可用时显示视频图标,仍可选择该素材作为引用。 + 图片或视频节点连接了有内容的文本节点时,提示词可以留空:生成时直接把文本原样作为提示词,也可以在提示词中补充要求。连线的文本不加“参考N:标题”标签;只有用 `@` 插入的文本保留标签,以便提示词中的引用对应到它。一个文本节点可以同时连到多个使用不同模型的生成节点,修改文本后各节点都会使用新内容。语音和音乐不读取文本参考,仍需填写正文或风格。 空白节点需要先上传、保存文本或生成内容,才能作为其他节点的有效参考。向已有节点上传本体素材时,文件类型应与节点一致;添加参考请使用连线、`@` 或生成面板的添加入口。 diff --git a/src/backend/creationClient.ts b/src/backend/creationClient.ts index df4d88c59..f63cdc192 100644 --- a/src/backend/creationClient.ts +++ b/src/backend/creationClient.ts @@ -639,9 +639,10 @@ export class CreationClient { 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 }; @@ -651,7 +652,7 @@ export class CreationClient { resilientRead( async (signal) => { const response = await fetch( - `/api${creationPath(this.id)}/assets/${assetId}/thumbnail`, + `/api${creationPath(this.id)}/assets/${assetId}/${rendition}`, { headers, signal }, ); if (!response.ok) throw await responseError(response); diff --git a/src/canvas/ChatReferenceEditor.tsx b/src/canvas/ChatReferenceEditor.tsx index 6f073e9bb..9694ae016 100644 --- a/src/canvas/ChatReferenceEditor.tsx +++ b/src/canvas/ChatReferenceEditor.tsx @@ -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(); + const [src, setSrc] = useState(); + 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 ( + + {src ? ( + setSrc(undefined)} /> + ) : ( + + )} + + ); +} export interface ChatReferenceEditorHandle { focus: () => void; @@ -1346,13 +1374,21 @@ export function ChatReferenceEditor({ onMouseEnter={() => setActive(index)} onClick={() => void choose(option)} > - - {option.thumbnail ? ( - - ) : ( - - )} - + {option.videoPreview && !option.disabledReason ? ( + + ) : ( + + {option.thumbnail ? ( + + ) : ( + + )} + + )} {option.title} {option.disabledReason || option.detail} diff --git a/src/canvas/referenceMentions.ts b/src/canvas/referenceMentions.ts index df3bcc3fe..33290c43f 100644 --- a/src/canvas/referenceMentions.ts +++ b/src/canvas/referenceMentions.ts @@ -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" }, @@ -20,6 +21,7 @@ export interface MentionOption { title: string; detail: string; thumbnail?: string; + videoPreview?: string; disabledReason?: string | null; } export interface MentionRange { @@ -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, @@ -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), }, ]; diff --git a/tests/browser/assistant_chat_references.mjs b/tests/browser/assistant_chat_references.mjs index 17bdaea90..16daf9800 100644 --- a/tests/browser/assistant_chat_references.mjs +++ b/tests/browser/assistant_chat_references.mjs @@ -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(); @@ -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( diff --git a/tests/creationClient.test.ts b/tests/creationClient.test.ts index 048e5a1d5..02e60ac41 100644 --- a/tests/creationClient.test.ts +++ b/tests/creationClient.test.ts @@ -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((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((_, 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();