diff --git a/docs/guides/user-guide.md b/docs/guides/user-guide.md index 11597b2f2..1cbdf469f 100644 --- a/docs/guides/user-guide.md +++ b/docs/guides/user-guide.md @@ -71,6 +71,7 @@ The first launch creates an untitled canvas. Later launches can restore the most - Click the project name at the top left to rename it. Press `Enter` or click elsewhere to save, or press `Esc` to cancel. - Click the arrow next to the name to switch projects. Choose **New canvas project** to create one. - On an empty canvas, click **Configure models** to open **Settings → Model connections**. +- Click **Try the example canvas** to pick a hosted sample. The picker lists the samples it can reach; choosing one downloads it, imports it as a new project and opens it. A download that is a ZIP around a single `.canvas` file is unwrapped automatically, and a page returned instead of a file is reported rather than imported. If the download fails, use the row's **Import manually** link, then drop the `.canvas` file on the canvas. - Use the left toolbar or double-click empty canvas space to create text, image, video, audio, timeline, or subject nodes. - Right-click empty canvas space to create a node, paste, undo, or redo. - Click **Upload** on the left or drag files onto the canvas to add assets. Use **Asset library** to choose existing assets. diff --git a/docs/guides/user-guide.zh-CN.md b/docs/guides/user-guide.zh-CN.md index a5fd095e2..90e5d05bf 100644 --- a/docs/guides/user-guide.zh-CN.md +++ b/docs/guides/user-guide.zh-CN.md @@ -71,6 +71,7 @@ vLLM-Omni 视频连接支持直接输入小数秒,例如 `6.583333`。CLI 可 - 点击左上角项目名称修改名称,按 `Enter` 或点击其他位置保存,按 `Esc` 取消。 - 点击名称右侧的箭头切换项目,选择“新建画布项目”创建项目。 - 在空白画布点击“配置模型”,可直接打开“设置 → 模型接入”。 +- 点击“体验示例画布”可选择官方托管示例:弹窗列出当前可用的示例,选中后会下载、导入为新工程并打开。若下载到的是包裹单个 `.canvas` 的 ZIP,会自动解开;若返回的是网页而不是文件,会明确提示而不会导入。下载失败时可用该行的“无法下载?手动导入”链接,再手动把 `.canvas` 文件拖入画布。 - 通过左侧工具栏或双击空白画布创建文本、图片、视频、音频、时间线或主体节点。 - 右键空白画布可新建节点、粘贴、撤销或重做。 - 点击左侧“上传”或将文件拖入画布添加素材;“资产库”可选择已有素材。 diff --git a/scripts/i18n-baseline.json b/scripts/i18n-baseline.json index e62361a7e..8be74c132 100644 --- a/scripts/i18n-baseline.json +++ b/scripts/i18n-baseline.json @@ -1,18 +1,15 @@ { - "total": 168, + "total": 165, "counts": { "src/canvas/assets.ts": 14, - "src/canvas/workspace/useWorkspaceTransfer.ts": 1, "src/canvas/dataBoundary.ts": 3, "src/canvas/generationCatalog.ts": 16, "src/canvas/generationSettings.ts": 4, - "src/canvas/library/AssetsPanel.tsx": 1, "src/canvas/library/libraryClient.ts": 1, - "src/canvas/library/SubjectsPanel.tsx": 1, - "src/canvas/library/TrashPanel.tsx": 1, "src/canvas/model.ts": 1, "src/canvas/NodeComposer.tsx": 1, "src/canvas/referenceMentions.ts": 1, - "src/canvas/toolCatalog.ts": 123 + "src/canvas/toolCatalog.ts": 123, + "src/canvas/workspace/useWorkspaceTransfer.ts": 1 } } diff --git a/scripts/run-browser-suite.mjs b/scripts/run-browser-suite.mjs index d129f2345..d4a7307f3 100644 --- a/scripts/run-browser-suite.mjs +++ b/scripts/run-browser-suite.mjs @@ -14,6 +14,10 @@ import { spawnSync } from "node:child_process"; const workflows = [ { name: "timeline node output", script: "tests/browser/timeline_node_output.mjs" }, + { + name: "example canvas picker", + script: "tests/browser/example_canvas_picker.mjs", + }, { name: "locale", script: "tests/browser/locale.mjs" }, { name: "creation closure", script: "scripts/verify_creation_browser.mjs" }, { name: "assistant activity", script: "tests/browser/assistant_activity.mjs" }, diff --git a/src/canvas/ProjectSelector.tsx b/src/canvas/ProjectSelector.tsx index a7d77ccd6..4a538a5ca 100644 --- a/src/canvas/ProjectSelector.tsx +++ b/src/canvas/ProjectSelector.tsx @@ -21,6 +21,7 @@ export function ProjectSelector({ disabled, onSelect, onCreate, + onExamples, onRename, onRenameProject, onDeleteProject, @@ -31,6 +32,8 @@ export function ProjectSelector({ disabled: boolean; onSelect: (project: WorkspaceProject) => Promise; onCreate: () => void; + /** Opens the example canvas picker; omitted where it is not offered. */ + onExamples?: () => void; onRename: (name: string) => Promise; onRenameProject: (project: WorkspaceProject, name: string) => Promise; onDeleteProject: (project: WorkspaceProject) => Promise; @@ -462,6 +465,20 @@ export function ProjectSelector({ )} + {onExamples && ( + + )} + + {exampleBusy && exampleButtonStatus && ( +
+ + + {exampleButtonStatus.phase === "importing" + ? t("canvas.example.state.importing") + : exampleProgress === null + ? t("canvas.example.state.downloading") + : t("canvas.example.state.downloadingPercent", { + percent: exampleProgress, + })} + +
+ )} + {(exampleMissing || exampleButtonStatus?.phase === "failed") && ( + + {exampleMissing + ? t("canvas.example.error.unknown") + : exampleFailureText(t, exampleButtonStatus!)} + + )} {t("canvas.workspace.empty.tagline")} )} @@ -2728,6 +2819,13 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { onClose={() => { dismissModelSetup(); setSettingsOpen(false); }} /> )} + {exampleEntries && ( + setExampleEntries(null)} + onImport={(archive) => importCanvasArchive(archive)} + /> + )} {help && (
setHelp(false)}>
void; + onImport: (archive: Blob) => Promise; +}) { + const t = useT(); + const { locale } = useI18n(); + const dialog = useRef(null); + const { statuses, start, cancel, reset, isRunning } = useExampleImport({ importCanvas: onImport }); + + useEffect(() => { + const element = dialog.current!; + element.showModal(); + return () => element.close(); + }, []); + + const busy = entries.some((entry) => isRunning(entry.id)); + + return ( + { + // Escape must not orphan a running download. + event.preventDefault(); + if (!busy) onClose(); + }} + onClick={(event) => { + if (event.target === event.currentTarget && !busy) onClose(); + }} + > +
+

{t("canvas.example.dialog.title")}

+

{t("canvas.example.dialog.hint")}

+
+ {entries.length === 0 ? ( +

{t("canvas.example.dialog.empty")}

+ ) : ( +
    + {entries.map((entry) => { + const status = statuses[entry.id] ?? { phase: "idle" as const }; + const running = isRunning(entry.id); + const size = megabytes(entry.bytes); + const percent = examplePercent(status); + return ( +
  • +
    + {entry.title[locale]} + {size && {size}} +
    + {entry.summary &&

    {entry.summary[locale]}

    } +
    + {running ? ( + <> + {status.phase === "downloading" && ( + + )} + + {status.phase === "importing" + ? t("canvas.example.state.importing") + : percent === null + ? t("canvas.example.state.downloading") + : t("canvas.example.state.downloadingPercent", { percent })} + + + + ) : status.phase === "done" ? ( + <> + + {t("canvas.example.state.done", { title: status.title ?? entry.title[locale] })} + + + + ) : ( + + )} + {status.phase === "failed" && ( + + )} +
    + {status.phase === "failed" && ( +

    + {exampleFailureText(t, status)} +

    + )} + {entry.manual?.shareUrl && ( +
    + {t("canvas.example.action.manual")} +

    {t("canvas.example.manual.steps")}

    + + {t("canvas.example.manual.share", { code: entry.manual.code ?? "-" })} + +
    + )} +
  • + ); + })} +
+ )} +
+ +
+
+ ); +} diff --git a/src/canvas/workspace/example/example-canvas.css b/src/canvas/workspace/example/example-canvas.css new file mode 100644 index 000000000..67047ce69 --- /dev/null +++ b/src/canvas/workspace/example/example-canvas.css @@ -0,0 +1,209 @@ +/* Example canvas picker: download progress, failure reason and manual fallback. + Dark is the base theme here; `--cw-control-*` only exists under [data-theme="light"]. */ +.cw-example-dialog { + width: min(680px, calc(100vw - 48px)); + max-height: min(78vh, 720px); + padding: 20px; + border-radius: 16px; + /* Opaque: the empty canvas state behind must not show through. */ + border: 1px solid #ffffff1f; + background: #23242b; + color: #ececee; + box-shadow: 0 18px 48px #000000b3; + overflow: auto; +} + +.cw-example-dialog::backdrop { + background: #000000a6; +} + +.cw-example-dialog header h2 { + margin: 0 0 6px; + font-size: 16px; + font-weight: 600; +} + +.cw-example-dialog header p { + margin: 0 0 14px; + font-size: 12px; + color: #9d9da6; +} + +.cw-example-list { + display: flex; + flex-direction: column; + gap: 10px; + margin: 0; + padding: 0; + list-style: none; +} + +.cw-example-item { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 14px; + border: 1px solid #ffffff14; + border-radius: 12px; + background: #2a2b33; +} + +.cw-example-item-heading { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 10px; +} + +.cw-example-item-heading strong { + font-size: 14px; + font-weight: 600; +} + +.cw-example-item-heading small, +.cw-example-summary { + font-size: 12px; + color: #9d9da6; +} + +.cw-example-summary { + margin: 0; +} + +.cw-example-actions { + display: flex; + align-items: center; + gap: 8px; + margin-top: 2px; + font-size: 12px; +} + +.cw-example-actions button, +.cw-example-dialog-actions button { + padding: 5px 12px; + border-radius: 8px; + border: 1px solid #ffffff26; + background: transparent; + color: inherit; + font-size: 12px; + cursor: pointer; +} + +.cw-example-actions button:hover:not(:disabled), +.cw-example-dialog-actions button:hover:not(:disabled) { + background: #ffffff14; +} + +.cw-example-actions button:disabled, +.cw-example-dialog-actions button:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.cw-example-progress { + flex: 1; + min-width: 120px; + height: 6px; + border-radius: 3px; + border: 0; + background: #ffffff1f; + appearance: none; + overflow: hidden; +} + +.cw-example-progress::-webkit-progress-bar { + background: #ffffff1f; + border-radius: 3px; +} + +.cw-example-progress::-webkit-progress-value { + background: #a78bd4; + border-radius: 3px; + transition: width 120ms linear; +} + +.cw-example-progress::-moz-progress-bar { + background: #a78bd4; + border-radius: 3px; +} + +.cw-example-error { + margin: 0; + font-size: 12px; + color: #e08a8a; +} + +.cw-example-manual { + font-size: 12px; +} + +.cw-example-manual summary { + color: #9d9da6; + cursor: pointer; +} + +.cw-example-manual p { + margin: 6px 0; +} + +.cw-example-manual a { + color: #8daed4; +} + +.cw-example-dialog-actions { + display: flex; + justify-content: flex-end; + margin-top: 16px; +} + +.cw-example-dialog-actions button { + padding: 6px 16px; + font-size: 13px; +} + +/* Light theme: the page ships dark defaults, so every colour needs an override. */ +:root[data-theme="light"] .cw-example-dialog { + border-color: #dfe2e7; + background: #fff; + color: #30343c; + box-shadow: 0 18px 48px #30374426; +} + +:root[data-theme="light"] .cw-example-dialog::backdrop { + background: #1a1c2266; +} + +:root[data-theme="light"] .cw-example-dialog header p, +:root[data-theme="light"] .cw-example-item-heading small, +:root[data-theme="light"] .cw-example-summary, +:root[data-theme="light"] .cw-example-manual summary { + color: #6b7280; +} + +:root[data-theme="light"] .cw-example-item { + border-color: #e6e8ec; + background: #f7f8fa; +} + +:root[data-theme="light"] .cw-example-actions button, +:root[data-theme="light"] .cw-example-dialog-actions button { + border-color: #d6dae1; +} + +:root[data-theme="light"] .cw-example-actions button:hover:not(:disabled), +:root[data-theme="light"] .cw-example-dialog-actions button:hover:not(:disabled) { + background: #eef1f5; +} + +:root[data-theme="light"] .cw-example-progress, +:root[data-theme="light"] .cw-example-progress::-webkit-progress-bar { + background: #e3e6ec; +} + +:root[data-theme="light"] .cw-example-error { + color: #b4453f; +} + +:root[data-theme="light"] .cw-example-manual a { + color: #2f5fbf; +} diff --git a/src/canvas/workspace/example/example-canvases.json b/src/canvas/workspace/example/example-canvases.json new file mode 100644 index 000000000..543044ccf --- /dev/null +++ b/src/canvas/workspace/example/example-canvases.json @@ -0,0 +1,54 @@ +{ + "schemaVersion": 1, + "updatedAt": "2026-11-17T06:40:00Z", + "items": [ + { + "id": "image-canvas", + "title": { + "zh-CN": "图像创作示例画布", + "en-US": "Image creation example canvas" + }, + "summary": { + "zh-CN": "图片生成、主体替换与参考素材的入门示例", + "en-US": "Image generation, subject replacement and references" + }, + "url": "https://lz.qaiu.top/parser?url=https://wwbks.lanzouv.com/i1BWT4ga8c6h&pwd=4b6t", + "filename": "图像创作示例画布.zip", + "sha256": "12566c858dab7a4ccbefa757a0d69965b526b9c253b472034137445f1c93b0cb", + "bytes": 27582888, + "contentKind": "zip-wrapper", + "inner": { + "entry": "图像创作示例画布.canvas", + "sha256": "60f40d2aaa54b65724081efab1b58b0e41f0dd78d6793dcf95ea9ee3dd97f911", + "bytes": 27689522, + "archiveVersion": 2, + "assets": 5, + "nodes": 12 + } + }, + { + "id": "video-canvas", + "title": { + "zh-CN": "视频创作示例画布", + "en-US": "Video creation example canvas" + }, + "summary": { + "zh-CN": "时间线、文生视频与图生视频的组合示例", + "en-US": "Timeline with text-to-video and image-to-video" + }, + "url": "https://lz.qaiu.top/parser?url=https://wwbks.lanzouv.com/iUPML4ga8bch&pwd=905a", + "filename": "视频创作示例画布.zip", + "sha256": "9c1662d6eec2ee1f9765ca53473cd1a93ab0ceeb841e8c0db895cd522a0bb13e", + "bytes": 26086524, + "contentKind": "zip-wrapper", + "inner": { + "entry": "视频创作示例画布.canvas", + "sha256": "76b10a86f0900816095c2b03c7533514db7fbe4ee968fe8338da55905e1cd8e5", + "bytes": 26128975, + "archiveVersion": 2, + "assets": 9, + "nodes": 17 + } + } + ] +} diff --git a/src/canvas/workspace/example/exampleCatalog.ts b/src/canvas/workspace/example/exampleCatalog.ts new file mode 100644 index 000000000..b4a2c5ba4 --- /dev/null +++ b/src/canvas/workspace/example/exampleCatalog.ts @@ -0,0 +1,345 @@ +/** + * Example canvases: catalog parsing, validation and the fallback order. + * + * The catalog is data, never code: a remote copy may be updated without an app + * release, and the bundled copy (imported below) keeps a first launch working + * offline. `public/` is not an option here — the packaged server only mounts + * `/assets` and `/fonts`. + */ +import bundledCatalog from "./example-canvases.json" with { type: "json" }; + +export interface ExampleText { + "zh-CN": string; + "en-US": string; +} + +/** What the downloader is expected to find behind `url`. Content wins over this hint. */ +export type ExampleContentKind = "auto" | "canvas" | "zip-wrapper"; + +/** Observed metadata for a `.canvas` entry wrapped inside an outer ZIP. */ +export interface ExampleInner { + entry: string; + sha256?: string; + bytes?: number; + archiveVersion?: number; + assets?: number; + nodes?: number; +} + +export interface ExampleManualDownload { + shareUrl?: string; + code?: string; +} + +export interface ExampleEntry { + id: string; + title: ExampleText; + summary?: ExampleText; + url: string; + filename?: string; + sha256?: string; + bytes?: number; + contentKind?: ExampleContentKind; + archiveVersion?: number; + minAppVersion?: string; + manual?: ExampleManualDownload; + inner?: ExampleInner; +} + +export interface ExampleCatalog { + schemaVersion: number; + updatedAt?: string; + items: ExampleEntry[]; +} + +export type CatalogSource = "remote" | "code"; + +export interface RejectedEntry { + /** The offending id when it parsed well enough to be reported. */ + id?: string; + reason: string; +} + +export interface ExampleCatalogResult { + catalog: ExampleCatalog; + source: CatalogSource; + rejected: RejectedEntry[]; +} + +export const EXAMPLE_CATALOG_SCHEMA_VERSION = 1; + +/** The two stable ids the empty-state buttons import directly. */ +export const IMAGE_EXAMPLE_ID = "image-canvas"; +export const VIDEO_EXAMPLE_ID = "video-canvas"; + +/** + * Hosts a catalog may download from. Suffix entries match their subdomains, so + * one object-storage line covers every regional bucket endpoint. + */ +export const EXAMPLE_ALLOWED_HOSTS: readonly string[] = [ + "lz.qaiu.top", + "webgetstore.com", + "aliyuncs.com", + "myqcloud.com", + "volces.com", + "qiniucdn.com", + "qbox.me", +]; + +const KINDS = new Set(["auto", "canvas", "zip-wrapper"]); +const HOST_LOCATOR = /^[a-z0-9.-]+$/; +const SHA256 = /^[0-9a-f]{64}$/; +const VERSION = /^\d+(?:\.\d+)*$/; + +/** + * Compiled-in fallback: the same file a remote catalog would serve, imported so + * the build bundles it. `public/` is not reachable from the packaged server, + * which only mounts `/assets` and `/fonts`. + */ +export const BUILTIN_EXAMPLE_CATALOG: ExampleCatalog = parseExampleCatalog( + bundledCatalog, +).catalog; + + +function record(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function text(value: unknown): value is ExampleText { + return ( + record(value) && + typeof value["zh-CN"] === "string" && + !!value["zh-CN"].trim() && + typeof value["en-US"] === "string" && + !!value["en-US"].trim() + ); +} + +function optionalText(value: unknown): ExampleText | undefined { + if (value === undefined) return undefined; + return text(value) ? value : undefined; +} + +function optionalString(value: unknown): string | undefined { + return typeof value === "string" && !!value.trim() ? value : undefined; +} + +function optionalDigest(value: unknown): string | undefined { + return typeof value === "string" && SHA256.test(value) ? value : undefined; +} + +function optionalCount(value: unknown): number | undefined { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 + ? value + : undefined; +} + +/** Exact host, or a suffix entry such as `aliyuncs.com` covering its subdomains. */ +export function exampleHostAllowed(host: string): boolean { + const name = host.toLowerCase(); + return EXAMPLE_ALLOWED_HOSTS.some( + (allowed) => name === allowed || name.endsWith(`.${allowed}`), + ); +} + +/** HTTPS only, and only to a host the catalog is allowed to reach. */ +export function exampleUrlAllowed(value: string): boolean { + let parsed: URL; + try { + parsed = new URL(value); + } catch { + return false; + } + return ( + parsed.protocol === "https:" && + !!parsed.hostname && + HOST_LOCATOR.test(parsed.hostname) && + exampleHostAllowed(parsed.hostname) + ); +} + +function parseInner(value: unknown): ExampleInner | undefined { + if (value === undefined) return undefined; + if (!record(value)) return undefined; + const entry = optionalString(value.entry); + if (!entry) return undefined; + return { + entry, + sha256: optionalDigest(value.sha256), + bytes: optionalCount(value.bytes), + archiveVersion: optionalCount(value.archiveVersion), + assets: optionalCount(value.assets), + nodes: optionalCount(value.nodes), + }; +} + +function parseManual(value: unknown): ExampleManualDownload | undefined { + if (!record(value)) return undefined; + const shareUrl = optionalString(value.shareUrl); + const code = optionalString(value.code); + if (!shareUrl && !code) return undefined; + return { shareUrl, code }; +} + +/** Returns the entry, or the reason it cannot be used. */ +export function parseExampleEntry( + value: unknown, +): { entry: ExampleEntry } | { id?: string; reason: string } { + if (!record(value)) return { reason: "entry is not an object" }; + const id = optionalString(value.id); + if (!id) return { reason: "missing id" }; + if (!text(value.title)) return { id, reason: "title must fill zh-CN and en-US" }; + const url = optionalString(value.url); + if (!url) return { id, reason: "missing url" }; + if (!exampleUrlAllowed(url)) return { id, reason: "url must be https on an allowed host" }; + const sha256 = optionalDigest(value.sha256); + if (value.sha256 !== undefined && !sha256) + return { id, reason: "sha256 must be 64 lowercase hex characters" }; + const bytes = optionalCount(value.bytes); + if (value.bytes !== undefined && bytes === undefined) + return { id, reason: "bytes must be a non-negative integer" }; + const contentKind = + typeof value.contentKind === "string" && KINDS.has(value.contentKind as ExampleContentKind) + ? (value.contentKind as ExampleContentKind) + : "auto"; + const minAppVersion = optionalString(value.minAppVersion); + if (minAppVersion && !VERSION.test(minAppVersion)) + return { id, reason: "minAppVersion must be dotted digits" }; + return { + entry: { + id, + title: value.title, + summary: optionalText(value.summary), + url, + filename: optionalString(value.filename), + sha256, + bytes, + contentKind, + archiveVersion: optionalCount(value.archiveVersion), + minAppVersion, + manual: parseManual(value.manual), + inner: parseInner(value.inner), + }, + }; +} + +/** + * Validates a catalog document. Unusable entries are reported and dropped + * rather than failing the whole list, so one bad row cannot hide the others. + */ +export function parseExampleCatalog(value: unknown): { + catalog: ExampleCatalog; + rejected: RejectedEntry[]; +} { + if (!record(value)) throw new Error("catalog is not an object"); + if (value.schemaVersion !== EXAMPLE_CATALOG_SCHEMA_VERSION) + throw new Error("unsupported catalog schemaVersion"); + if (!Array.isArray(value.items)) throw new Error("catalog items must be an array"); + const items: ExampleEntry[] = []; + const rejected: RejectedEntry[] = []; + const seen = new Set(); + for (const raw of value.items) { + const parsed = parseExampleEntry(raw); + if (!("entry" in parsed)) { + rejected.push({ id: "id" in parsed ? parsed.id : undefined, reason: parsed.reason }); + continue; + } + if (seen.has(parsed.entry.id)) { + rejected.push({ id: parsed.entry.id, reason: "duplicate id" }); + continue; + } + seen.add(parsed.entry.id); + items.push(parsed.entry); + } + return { + catalog: { schemaVersion: EXAMPLE_CATALOG_SCHEMA_VERSION, updatedAt: optionalString(value.updatedAt), items }, + rejected, + }; +} + +/** Dotted numeric comparison; unparsable input sorts below any real version. */ +export function compareAppVersions(left: string, right: string): number { + const a = VERSION.test(left) ? left.split(".").map(Number) : []; + const b = VERSION.test(right) ? right.split(".").map(Number) : []; + const length = Math.max(a.length, b.length); + for (let index = 0; index < length; index++) { + const difference = (a[index] ?? 0) - (b[index] ?? 0); + if (difference !== 0) return difference < 0 ? -1 : 1; + } + return 0; +} + +/** + * Entries this build can import. `minAppVersion` keeps newer samples out of + * older apps; when the running version is unknown the gate is skipped rather + * than hiding every sample. + */ +export function availableExamples( + catalog: ExampleCatalog, + appVersion?: string, +): ExampleEntry[] { + return catalog.items.filter( + (item) => + !item.minAppVersion || + !appVersion || + compareAppVersions(appVersion, item.minAppVersion) >= 0, + ); +} + +async function readCatalogFile( + fetchImpl: typeof fetch, + url: string, + signal: AbortSignal | undefined, +): Promise { + const response = await fetchImpl(url, { + method: "GET", + credentials: "omit", + cache: "no-store", + signal, + }); + if (!response.ok) throw new Error(`catalog responded ${response.status}`); + return response.json(); +} + +/** + * Loads the catalog without ever failing: the remote copy when one is + * configured, otherwise the bundled one. `rejected` reports rows dropped while + * validating. + */ +export async function loadExampleCatalog( + options: { + fetchImpl?: typeof fetch; + signal?: AbortSignal; + remoteUrl?: string; + appVersion?: string; + } = {}, +): Promise { + const rejected: RejectedEntry[] = []; + if (options.remoteUrl) { + try { + const fetchImpl = options.fetchImpl ?? fetch; + const parsed = await readCatalogFile( + fetchImpl, + options.remoteUrl, + options.signal, + ); + const validated = parseExampleCatalog(parsed); + rejected.push(...validated.rejected); + return { catalog: validated.catalog, source: "remote", rejected }; + } catch { + /* A missing or malformed remote copy falls through to the bundled one. */ + } + } + const fallback = parseExampleCatalog(bundledCatalog); + rejected.push(...fallback.rejected); + return { catalog: fallback.catalog, source: "code", rejected }; +} + +/** One entry by id, for reopening a sample the user already imported. */ +export function exampleById( + catalog: ExampleCatalog, + id: string, +): ExampleEntry | undefined { + return catalog.items.find((item) => item.id === id); +} + diff --git a/src/canvas/workspace/example/exampleDownload.ts b/src/canvas/workspace/example/exampleDownload.ts new file mode 100644 index 000000000..5191692de --- /dev/null +++ b/src/canvas/workspace/example/exampleDownload.ts @@ -0,0 +1,275 @@ +/** + * Downloads an example canvas and normalizes whatever arrived into a `.canvas` + * archive. The served file is frequently a ZIP that wraps a single `.canvas`, + * so the bytes — not the file name — decide what was downloaded. + */ +import { readZip } from "../../zipArchive.ts"; +import { exampleUrlAllowed, type ExampleEntry } from "./exampleCatalog.ts"; + +export type ExampleErrorCode = + | "invalidUrl" + | "aborted" + | "network" + | "http" + | "tooLarge" + | "html" + | "notArchive" + | "ambiguous" + | "notCanvas" + | "integrity"; + +/** A classified failure; the UI owns the wording for each code. */ +export class ExampleError extends Error { + readonly code: ExampleErrorCode; + readonly status?: number; + + constructor(code: ExampleErrorCode, message?: string, status?: number) { + super(message ?? code); + this.name = "ExampleError"; + this.code = code; + this.status = status; + } +} + +/** Upper bound for one download; the shipped samples are ~26 MB. */ +export const EXAMPLE_MAX_BYTES = 256 * 1024 * 1024; + +/** Whole-request deadline, including the streaming body read. */ +export const EXAMPLE_TIMEOUT_MS = 120_000; + +export interface ExampleDownloadOptions { + fetchImpl?: typeof fetch; + signal?: AbortSignal; + maxBytes?: number; + timeoutMs?: number; + /** Bytes received so far, plus the declared total when the server sent one. */ + onProgress?: (received: number, total: number | null) => void; +} + +export interface NormalizedCanvas { + /** Bytes of the `.canvas` archive itself, ready for `readCanvasArchive`. */ + bytes: Uint8Array; + kind: "canvas" | "zip-wrapper"; + /** Outer entry that was unwrapped, when `kind` is `zip-wrapper`. */ + innerEntry?: string; +} + +export interface ExampleDownload extends NormalizedCanvas { + /** Size of the response body before unwrapping. */ + outerBytes: number; + /** + * Zeroes the downloaded buffers and drops this object's claim on them. + * Idempotent, so a failure path and a success path can both call it. + */ + release: () => void; +} + +const ZIP_MAGIC = [0x50, 0x4b, 0x03, 0x04]; +const HTML_MARKERS = new Set([0x3c /* < */, 0x7b /* { */]); +const CANVAS_ENTRY = /\.canvas$/i; + +function isZip(bytes: Uint8Array): boolean { + return ZIP_MAGIC.every((value, index) => bytes[index] === value); +} + +/** Login pages and JSON error bodies are the usual "download" of a blocked link. */ +function looksLikeMarkup(bytes: Uint8Array): boolean { + for (const byte of bytes.subarray(0, 512)) { + // Skip a UTF-8 BOM and leading whitespace before judging the first byte. + if (byte === 0xef || byte === 0xbb || byte === 0xbf) continue; + if (byte === 0x20 || byte === 0x09 || byte === 0x0a || byte === 0x0d) continue; + return HTML_MARKERS.has(byte); + } + return false; +} + +async function sha256Hex(bytes: Uint8Array): Promise { + const subtle = globalThis.crypto?.subtle; + if (!subtle) return undefined; + const digest = await subtle.digest("SHA-256", bytes as BufferSource); + return Array.from(new Uint8Array(digest), (byte) => + byte.toString(16).padStart(2, "0"), + ).join(""); +} + +/** Links the caller's signal with the deadline, without leaking a listener. */ +function withDeadline( + signal: AbortSignal | undefined, + timeoutMs: number, +): { signal: AbortSignal; dispose: () => void } { + const aborter = new AbortController(); + const forward = () => aborter.abort(); + if (signal) { + if (signal.aborted) aborter.abort(); + else signal.addEventListener("abort", forward, { once: true }); + } + const timer = setTimeout(() => aborter.abort(), timeoutMs); + return { + signal: aborter.signal, + dispose: () => { + clearTimeout(timer); + signal?.removeEventListener("abort", forward); + }, + }; +} + +function abortedError(cause: unknown): ExampleError { + if (cause instanceof ExampleError) return cause; + return new ExampleError("aborted", "the download was cancelled"); +} + +/** Distinguishes a cancelled request from a transport failure. */ +function transportError(cause: unknown, cancelled: boolean): ExampleError { + if (cause instanceof ExampleError) return cause; + if (cancelled) return abortedError(cause); + return new ExampleError( + "network", + cause instanceof Error ? cause.message : undefined, + ); +} + +/** Reads the body under a byte budget so a huge file cannot fill memory first. */ +async function readLimited( + response: Response, + maxBytes: number, + onProgress?: (received: number, total: number | null) => void, +): Promise { + const declared = Number(response.headers.get("content-length") ?? ""); + const total = Number.isFinite(declared) && declared > 0 ? declared : null; + if (!response.body) { + const buffer = await response.arrayBuffer(); + if (buffer.byteLength > maxBytes) throw new ExampleError("tooLarge"); + onProgress?.(buffer.byteLength, total); + return new Uint8Array(buffer); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let received = 0; + onProgress?.(0, total); + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + received += value.byteLength; + if (received > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new ExampleError("tooLarge"); + } + chunks.push(value); + onProgress?.(received, total); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(received); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; + } + return bytes; +} + +/** Fetches the entry's URL and returns the raw response bytes. */ +export async function fetchExampleBytes( + entry: ExampleEntry, + options: ExampleDownloadOptions = {}, +): Promise { + if (!exampleUrlAllowed(entry.url)) + throw new ExampleError("invalidUrl", entry.url); + const fetchImpl = options.fetchImpl ?? fetch; + const maxBytes = options.maxBytes ?? EXAMPLE_MAX_BYTES; + const deadline = withDeadline(options.signal, options.timeoutMs ?? EXAMPLE_TIMEOUT_MS); + try { + let response: Response; + try { + response = await fetchImpl(entry.url, { + method: "GET", + mode: "cors", + // Never send cookies to a third-party origin; the hosted copy is public. + credentials: "omit", + redirect: "follow", + // The link resolves to a short-lived CDN path; a cached body would rot. + cache: "no-store", + signal: deadline.signal, + }); + } catch (cause) { + throw transportError(cause, deadline.signal.aborted); + } + if (!response.ok) + throw new ExampleError("http", `status ${response.status}`, response.status); + const declared = Number(response.headers.get("content-length") ?? ""); + if (Number.isFinite(declared) && declared > maxBytes) + throw new ExampleError("tooLarge"); + let bytes: Uint8Array; + try { + bytes = await readLimited(response, maxBytes, options.onProgress); + } catch (cause) { + throw transportError(cause, deadline.signal.aborted); + } + if (bytes.byteLength === 0) throw new ExampleError("notArchive"); + if (entry.sha256) { + const digest = await sha256Hex(bytes); + if (digest && digest !== entry.sha256) throw new ExampleError("integrity"); + } + return bytes; + } finally { + deadline.dispose(); + } +} + +/** + * Turns the downloaded bytes into the `.canvas` archive to import. + * + * - a plain archive (its manifest sits at the ZIP root) is returned untouched + * - a ZIP holding exactly one `.canvas` entry is unwrapped one level + * - anything else is reported, never guessed + */ +export async function normalizeToCanvas( + bytes: Uint8Array, +): Promise { + if (!bytes.byteLength) throw new ExampleError("notArchive"); + if (looksLikeMarkup(bytes)) throw new ExampleError("html"); + if (!isZip(bytes)) throw new ExampleError("notArchive"); + let files: Map; + try { + files = await readZip(bytes); + } catch { + // A truncated or damaged container is a download problem, not a canvas one. + throw new ExampleError("notArchive"); + } + if (files.has("manifest.json")) return { bytes, kind: "canvas" }; + const canvases = [...files.keys()].filter( + (name) => !name.endsWith("/") && CANVAS_ENTRY.test(name), + ); + if (canvases.length !== 1) throw new ExampleError("ambiguous"); + const innerEntry = canvases[0]!; + const inner = files.get(innerEntry)!; + if (!inner.byteLength) throw new ExampleError("notArchive"); + return { bytes: inner, kind: "zip-wrapper", innerEntry }; +} + +/** Download plus normalization, with the optional inner digest checked. */ +export async function fetchExampleCanvas( + entry: ExampleEntry, + options: ExampleDownloadOptions = {}, +): Promise { + const outer = await fetchExampleBytes(entry, options); + const normalized = await normalizeToCanvas(outer); + if (entry.inner?.sha256) { + const digest = await sha256Hex(normalized.bytes); + if (digest && digest !== entry.inner.sha256) + throw new ExampleError("integrity"); + } + // Both buffers are ours: the wrapper's bytes and, when unwrapped, the inner + // entry copy. Zeroing them is the only copy this module ever creates. + const buffers = [outer, normalized.bytes]; + let released = false; + const release = () => { + if (released) return; + released = true; + for (const buffer of buffers) buffer.fill(0); + }; + return { ...normalized, outerBytes: outer.byteLength, release }; +} diff --git a/src/canvas/workspace/example/exampleFailure.ts b/src/canvas/workspace/example/exampleFailure.ts new file mode 100644 index 000000000..46ba0c90d --- /dev/null +++ b/src/canvas/workspace/example/exampleFailure.ts @@ -0,0 +1,37 @@ +/** One sentence per example failure, shared by the picker and the empty-state buttons. */ +import type { Translate } from "../../../i18n/I18nProvider.tsx"; +import type { ExampleStatus } from "./useExampleImport.ts"; + +export function exampleFailureText(t: Translate, status: ExampleStatus): string { + switch (status.code) { + case "http": + return t("canvas.example.error.http", { status: status.httpStatus ?? 0 }); + case "network": + return t("canvas.example.error.network"); + case "html": + return t("canvas.example.error.html"); + case "notArchive": + return t("canvas.example.error.notArchive"); + case "ambiguous": + return t("canvas.example.error.ambiguous"); + case "notCanvas": + return t("canvas.example.error.notCanvas"); + case "tooLarge": + return t("canvas.example.error.tooLarge"); + case "integrity": + return t("canvas.example.error.integrity"); + case "invalidUrl": + return t("canvas.example.error.invalidUrl"); + case "aborted": + return t("canvas.example.error.aborted"); + default: + // Archive validation fails with an already-localized message. + return status.message || t("canvas.example.error.unknown"); + } +} + +/** Completion percentage, or null while the server has not declared a size. */ +export function examplePercent(status: ExampleStatus): number | null { + if (!status.total || !status.received) return null; + return Math.min(100, Math.round((status.received / status.total) * 100)); +} diff --git a/src/canvas/workspace/example/useExampleImport.ts b/src/canvas/workspace/example/useExampleImport.ts new file mode 100644 index 000000000..86c6769ac --- /dev/null +++ b/src/canvas/workspace/example/useExampleImport.ts @@ -0,0 +1,157 @@ +/** + * Import orchestration for one example canvas: download, hand the bytes to the + * existing import path, and report progress. The bytes never outlive the call, + * so there is no archive copy left behind once the import finishes. + */ +import { useCallback, useRef, useState } from "react"; +import { + ExampleError, + fetchExampleCanvas, + type ExampleDownload, + type ExampleErrorCode, +} from "./exampleDownload.ts"; +import type { ExampleEntry } from "./exampleCatalog.ts"; + +export type ExamplePhase = "idle" | "downloading" | "importing" | "done" | "failed"; + +export interface ExampleStatus { + phase: ExamplePhase; + /** Present when `phase` is `failed`. */ + code?: ExampleErrorCode | "unknown"; + /** HTTP status for `http` failures. */ + httpStatus?: number; + /** The imported title, when `phase` is `done`. */ + title?: string; + /** The original message, for failures the codes cannot describe. */ + message?: string; + /** Bytes received while `phase` is `downloading`. */ + received?: number; + /** Declared download size, when the server sent a `content-length`. */ + total?: number | null; +} + +export interface ExampleImportDeps { + fetchCanvas?: typeof fetchExampleCanvas; + /** Receives the unwrapped `.canvas` archive; must not retain it. */ + importCanvas: (archive: Blob) => Promise; +} + +function failure(error: unknown): ExampleStatus { + if (error instanceof ExampleError) + return { phase: "failed", code: error.code, httpStatus: error.status }; + // Archive validation (version too new, damaged manifest) arrives as a plain + // localized Error; keep its wording instead of flattening it to "unknown". + return { + phase: "failed", + code: "unknown", + message: error instanceof Error ? error.message : undefined, + }; +} + +export interface ExampleImportResult { + kind: ExampleDownload["kind"]; + innerEntry?: string; + outerBytes: number; +} + +/** + * Runs one import, reports every phase transition, and always releases the + * downloaded buffers afterwards. + * + * Throws after reporting `failed`, so a caller can decide whether to surface a + * toast in addition to the inline status. + */ +export async function runExampleImport( + entry: ExampleEntry, + deps: ExampleImportDeps, + signal: AbortSignal, + report: (status: ExampleStatus) => void, +): Promise { + report({ phase: "downloading" }); + let download: ExampleDownload; + try { + download = await (deps.fetchCanvas ?? fetchExampleCanvas)(entry, { + signal, + onProgress: (received, total) => + report({ phase: "downloading", received, total }), + }); + } catch (error) { + report(failure(error)); + throw error; + } + try { + if (signal.aborted) throw new ExampleError("aborted"); + report({ phase: "importing" }); + await deps.importCanvas( + new Blob([download.bytes as unknown as BlobPart], { + type: "application/octet-stream", + }), + ); + report({ phase: "done", title: entry.title["zh-CN"] }); + return { + kind: download.kind, + innerEntry: download.innerEntry, + outerBytes: download.outerBytes, + }; + } catch (error) { + report(failure(error)); + throw error; + } finally { + // No download survives the call: this is the cache release the feature needs. + download.release(); + } +} + +/** Per-entry status plus the controls the dialog needs. */ +export function useExampleImport(deps: ExampleImportDeps) { + const [statuses, setStatuses] = useState>({}); + const controllers = useRef(new Map()); + const depsRef = useRef(deps); + depsRef.current = deps; + + const update = useCallback((id: string, status: ExampleStatus | null) => { + setStatuses((current) => { + const next = { ...current }; + if (status) next[id] = status; + else delete next[id]; + return next; + }); + }, []); + + const start = useCallback( + async (entry: ExampleEntry): Promise => { + if (controllers.current.has(entry.id)) return false; + const controller = new AbortController(); + controllers.current.set(entry.id, controller); + try { + await runExampleImport(entry, depsRef.current, controller.signal, (status) => { + // A cancelled download returns to idle instead of showing an error. + if (status.code === "aborted") update(entry.id, null); + else update(entry.id, status); + }); + return true; + } catch { + /* The inline status already explains the failure. */ + return false; + } finally { + controllers.current.delete(entry.id); + } + }, + [update], + ); + + const cancel = useCallback((id: string) => { + controllers.current.get(id)?.abort(); + }, []); + + const reset = useCallback((id: string) => update(id, null), [update]); + + return { + statuses, + start, + cancel, + reset, + isRunning: (id: string) => + statuses[id]?.phase === "downloading" || statuses[id]?.phase === "importing", + }; +} diff --git a/src/canvas/workspace/useWorkspaceTransfer.ts b/src/canvas/workspace/useWorkspaceTransfer.ts index 48d743697..7b08523a1 100644 --- a/src/canvas/workspace/useWorkspaceTransfer.ts +++ b/src/canvas/workspace/useWorkspaceTransfer.ts @@ -593,19 +593,28 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime) { notify(errorMessage(error)); } }; + /** Reads an archive and lands it as a new project. Throws so callers can classify. */ + const importCanvasArchive = async (archive: Blob) => { + const contents = await readCanvasArchive(archive); + const switched = await switchDocument( + () => importWorkspaceDocument(contents.document), + true, + true, + ); + return { + title: contents.document.title, + assets: contents.assets, + switched, + }; + }; const importDocument = async (file: File) => { try { - const contents = await readCanvasArchive(file); - const switched = await switchDocument( - () => importWorkspaceDocument(contents.document), - true, - true, - ); - if (switched) + const result = await importCanvasArchive(file); + if (result.switched) notify( t("canvas.workspace.toast.archiveImported", { - title: contents.document.title, - count: contents.assets, + title: result.title, + count: result.assets, }), ); } catch (error) { @@ -879,6 +888,7 @@ export function useWorkspaceTransfer(rt: WorkspaceRuntime) { rt.downloadNode = downloadNode; rt.exportDocument = exportDocument; rt.importDocument = importDocument; + rt.importCanvasArchive = importCanvasArchive; rt.openFilePicker = openFilePicker; rt.importFiles = importFiles; } diff --git a/src/i18n/messages/en-US/canvasShell.ts b/src/i18n/messages/en-US/canvasShell.ts index ff6ce1035..0185b6487 100644 --- a/src/i18n/messages/en-US/canvasShell.ts +++ b/src/i18n/messages/en-US/canvasShell.ts @@ -148,4 +148,5 @@ export const canvasShell = { one: "{count} character", other: "{count} characters", }, + "canvas.project.examples": "Example canvases", } as const; diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index cc20376d0..a0ca5732b 100644 --- a/src/i18n/messages/en-US/canvasWorkspace.ts +++ b/src/i18n/messages/en-US/canvasWorkspace.ts @@ -87,7 +87,6 @@ export const canvasWorkspace = { "canvas.workspace.empty.hint": "Double-click the canvas to create a node, or drop in your assets", "canvas.workspace.empty.configureModels": "Configure models", - "canvas.workspace.empty.example": "Try the example canvas", "canvas.workspace.empty.tagline": "Reference connections · Free arrangement · Autosaved locally", @@ -423,4 +422,36 @@ export const canvasWorkspace = { "A subject video cannot exceed 15 seconds", "canvas.workspace.referenceIssue.sourceDurationMissing": "Read the actual video or audio duration before adding it to the target node", + // Example canvas picker: download and import a hosted sample. + "canvas.example.dialog.title": "Choose an example canvas", + "canvas.example.dialog.hint": "The canvas is downloaded and imported locally; keep editing once it opens.", + "canvas.example.dialog.empty": "No example canvas is available right now.", + "canvas.example.action.import": "Download and import", + "canvas.example.action.retry": "Retry", + "canvas.example.action.cancelDownload": "Cancel download", + "canvas.example.action.close": "Close", + "canvas.example.action.dismiss": "Dismiss", + "canvas.example.action.manual": "Can't download? Import manually", + "canvas.example.state.downloading": "Downloading…", + "canvas.example.state.importing": "Importing…", + "canvas.example.state.done": "Imported “{title}”", + "canvas.example.error.http": "Download failed (HTTP {status}). Retry, or import it manually.", + "canvas.example.error.network": "The network dropped. Try again.", + "canvas.example.error.html": "The server returned a web page instead of a canvas file; the request may be blocked.", + "canvas.example.error.notArchive": "The download is not a ZIP canvas package; it may be blocked or damaged.", + "canvas.example.error.ambiguous": "The archive does not contain exactly one .canvas file.", + "canvas.example.error.notCanvas": "That file is not an OpenDirector canvas.", + "canvas.example.error.tooLarge": "The file exceeds the size limit; the download was stopped.", + "canvas.example.error.integrity": "The file failed its integrity check and was discarded.", + "canvas.example.error.invalidUrl": "This example points at an untrusted address; the download was blocked.", + "canvas.example.error.aborted": "The download was cancelled.", + "canvas.example.error.unknown": "The import failed. Try again, or import it manually.", + "canvas.example.manual.steps": "After downloading, drop the .canvas file on the canvas or use Import canvas.", + "canvas.example.manual.share": "Open the share link (code {code})", + // The download reports live progress; sizes render as plain data. + "canvas.example.state.downloadingPercent": "Downloading… {percent}%", + "canvas.example.progress.label": "Download progress", + // The empty canvas imports the two hosted samples directly. + "canvas.workspace.empty.tryImage": "Try image canvas", + "canvas.workspace.empty.tryVideo": "Try video canvas", } as const; diff --git a/src/i18n/messages/zh-CN/canvasShell.ts b/src/i18n/messages/zh-CN/canvasShell.ts index 6ac08b69a..d6e86859e 100644 --- a/src/i18n/messages/zh-CN/canvasShell.ts +++ b/src/i18n/messages/zh-CN/canvasShell.ts @@ -141,4 +141,5 @@ export const canvasShell = { "canvas.textWindow.hint": "编辑内容会实时同步到画布节点", "canvas.textWindow.locked": "节点已锁定,仅可查看", "canvas.textWindow.count": "{count} 字", + "canvas.project.examples": "示例画布", } as const; diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index fa6931ac0..247e08138 100644 --- a/src/i18n/messages/zh-CN/canvasWorkspace.ts +++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts @@ -87,7 +87,6 @@ export const canvasWorkspace = { "canvas.workspace.empty.title": "你的故事,由你执导", "canvas.workspace.empty.hint": "双击画布创建节点,或拖入你的素材", "canvas.workspace.empty.configureModels": "配置模型", - "canvas.workspace.empty.example": "体验示例画布", "canvas.workspace.empty.tagline": "参考连接 · 自由编排 · 本机自动保存", "canvas.workspace.loading.opening": "正在打开画布…", @@ -378,4 +377,36 @@ export const canvasWorkspace = { "主体视频不能超过 15 秒", "canvas.workspace.referenceIssue.sourceDurationMissing": "请先读取视频或音频的实际时长,再添加到目标节点", + // Example canvas picker: download and import a hosted sample. + "canvas.example.dialog.title": "选择示例画布", + "canvas.example.dialog.hint": "选中后会下载并导入到你的本机,导入完成即可继续编辑。", + "canvas.example.dialog.empty": "暂时没有可用的示例画布。", + "canvas.example.action.import": "下载并导入", + "canvas.example.action.retry": "重试", + "canvas.example.action.cancelDownload": "取消下载", + "canvas.example.action.close": "关闭", + "canvas.example.action.dismiss": "忽略", + "canvas.example.action.manual": "无法下载?手动导入", + "canvas.example.state.downloading": "正在下载…", + "canvas.example.state.importing": "正在导入…", + "canvas.example.state.done": "已导入「{title}」", + "canvas.example.error.http": "下载失败(HTTP {status}),请稍后重试或手动导入。", + "canvas.example.error.network": "网络中断,请重试。", + "canvas.example.error.html": "服务器返回的是网页而不是画布文件,可能被拦截。", + "canvas.example.error.notArchive": "下载到的不是 ZIP 画布包,可能被拦截或已损坏。", + "canvas.example.error.ambiguous": "压缩包里没有唯一的 .canvas 画布文件。", + "canvas.example.error.notCanvas": "该文件不是 OpenDirector 画布。", + "canvas.example.error.tooLarge": "文件超过大小上限,已中止。", + "canvas.example.error.integrity": "文件校验不一致,已丢弃。", + "canvas.example.error.invalidUrl": "该示例的地址不受信任,已阻止下载。", + "canvas.example.error.aborted": "已取消下载。", + "canvas.example.error.unknown": "导入失败,请重试或手动导入。", + "canvas.example.manual.steps": "下载后把 .canvas 文件拖入画布,或使用「导入画布」。", + "canvas.example.manual.share": "打开分享链接(提取码 {code})", + // The download reports live progress; sizes render as plain data. + "canvas.example.state.downloadingPercent": "正在下载… {percent}%", + "canvas.example.progress.label": "下载进度", + // The empty canvas imports the two hosted samples directly. + "canvas.workspace.empty.tryImage": "体验图片画布", + "canvas.workspace.empty.tryVideo": "体验视频画布", } as const; diff --git a/tests/browser/example_canvas_picker.mjs b/tests/browser/example_canvas_picker.mjs new file mode 100644 index 000000000..fcc57cef6 --- /dev/null +++ b/tests/browser/example_canvas_picker.mjs @@ -0,0 +1,151 @@ +/** + * Isolated UI regression: the empty canvas imports the two hosted samples + * directly with a progress bar, the project menu still opens the full picker, + * and a blocked page is reported instead of imported. + * + * Both samples ship as a ZIP around one `.canvas`, so the fixture mirrors that + * shape; the failure case serves HTML like a blocked share link does. + */ +import assert from "node:assert/strict"; +import { buildCanvasArchive } from "../../src/canvas/canvasArchive.ts"; +import { createDocument, createNode } from "../../src/canvas/model.ts"; +import { createZip } from "../../src/canvas/zipArchive.ts"; + +const { chromium } = await import(process.env.PLAYWRIGHT_MODULE ?? "playwright-core"); +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"; + +async function call(path, body) { + const response = await fetch(api + path, { + headers: { + "X-OpenDirector-Request": "1", + "Content-Type": "application/json", + }, + ...(body ? { method: "POST", body: JSON.stringify(body) } : {}), + }); + assert.ok(response.ok, `${response.status}: ${await response.clone().text()}`); + return response.json(); +} + +assert.equal((await call("/api/creation-test-health")).isolated, true); + +// The fixture canvas has two nodes, so the import is observable by node count. +const document = { + ...createDocument("测试示例画布"), + nodes: [ + createNode("text", { x: 80, y: 120 }, { title: "说明", text: "示例文本" }), + createNode("text", { x: 420, y: 120 }, { title: "备注", text: "另一个节点" }), + ], +}; +const archive = await buildCanvasArchive(document, { + read: async () => { + throw new Error("the fixture has no media"); + }, +}); +const wrapper = await createZip([ + { path: `${document.title}.canvas`, data: new Uint8Array(await archive.blob.arrayBuffer()) }, +]); +const wrapperBytes = Buffer.from(await wrapper.arrayBuffer()); + +const sampleUrl = "https://lz.qaiu.top/fixture/example.zip"; +const catalog = { + schemaVersion: 1, + items: [ + { + id: "image-canvas", + title: { "zh-CN": document.title, "en-US": "Fixture example canvas" }, + url: sampleUrl, + filename: `${document.title}.zip`, + contentKind: "zip-wrapper", + bytes: wrapperBytes.byteLength, + inner: { entry: `${document.title}.canvas`, archiveVersion: 2, nodes: 2 }, + }, + { + id: "video-canvas", + title: { "zh-CN": "视频示例画布", "en-US": "Fixture video canvas" }, + url: sampleUrl, + filename: `${document.title}.zip`, + contentKind: "zip-wrapper", + bytes: wrapperBytes.byteLength, + }, + ], +}; +const downloadHeaders = { + // A cross-origin route still needs CORS headers: the app fetches, not navigates. + "access-control-allow-origin": "*", + "content-disposition": `attachment; filename="${document.title}.zip"`, +}; + +const projectId = crypto.randomUUID(); +await call(`/api/creation/projects/${projectId}/commands`, { + projectId, + commandId: crypto.randomUUID(), + type: "project.create", + payload: { name: `Example picker ${projectId.slice(0, 8)}` }, +}); + +const browser = await chromium.launch({ + headless: true, + ...(process.env.CHROMIUM_PATH ? { executablePath: process.env.CHROMIUM_PATH } : {}), + args: ["--no-sandbox"], +}); +try { + const page = await browser.newPage({ locale: "zh-CN", viewport: { width: 1500, height: 1000 } }); + await page.addInitScript(() => + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"), + ); + page.setDefaultTimeout(15000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + + await page.route("**/example-canvases.json", (route) => route.fulfill({ json: catalog })); + // A short delay makes the streaming progress observable on a ~1 KB fixture. + await page.route(sampleUrl, async (route) => { + await new Promise((resolve) => setTimeout(resolve, 300)); + await route.fulfill({ + status: 200, + headers: { ...downloadHeaders, "content-type": "application/octet-stream" }, + body: wrapperBytes, + }); + }); + + const openCanvas = async () => { + await page.goto(`${base}/ai-tool/ai-canvas/${projectId}`); + await page.getByText("已保存到本机", { exact: true }).waitFor(); + }; + + // 1. The empty-state button downloads, shows progress, imports and closes the bar. + await openCanvas(); + await page.getByRole("button", { name: "体验图片画布" }).click(); + await page.locator(".cw-empty-example-status").waitFor(); + await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); + assert.equal(await page.locator(".react-flow__node").count(), 2); + // The progress block lives in the empty state, which the imported canvas replaces. + assert.equal(await page.locator(".cw-empty-example-status").count(), 0); + + // 2. The project menu still reaches the full picker. + await page.getByRole("button", { name: "切换项目", exact: true }).click(); + await page.getByRole("menuitem", { name: /示例画布/ }).click(); + const dialog = page.locator(".cw-example-dialog"); + await dialog.waitFor(); + await dialog.getByText(document.title, { exact: true }).waitFor(); + await dialog.getByRole("button", { name: "关闭", exact: true }).first().click(); + + // 3. A page instead of an archive is reported inline, and nothing is imported. + await page.unroute(sampleUrl); + await page.route(sampleUrl, (route) => + route.fulfill({ + status: 200, + headers: { ...downloadHeaders, "content-type": "text/html" }, + body: "请登录", + }), + ); + await openCanvas(); + await page.getByRole("button", { name: "体验图片画布" }).click(); + await page.getByText(/服务器返回的是网页/).waitFor(); + assert.equal(await page.locator(".react-flow__node").count(), 0); + + assert.deepEqual(errors, []); +} finally { + await browser.close(); +} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index ea78287e6..c75fabdcf 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -514,6 +514,14 @@ ], "previewSafe": false, "note": "Canvas timeline output button and shortcut publish real MP4 results in both locales without opening the editor." + }, + { + "file": "example_canvas_picker.mjs", + "lanes": [ + "gate" + ], + "previewSafe": false, + "note": "Empty-canvas example picker: a wrapped .canvas download imports through the shared archive path, and an HTML page is reported without creating a project. The catalog and the sample are routed in-page, so no external host is needed." } ] } diff --git a/tests/exampleCatalog.test.ts b/tests/exampleCatalog.test.ts new file mode 100644 index 000000000..e899b00ea --- /dev/null +++ b/tests/exampleCatalog.test.ts @@ -0,0 +1,189 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + BUILTIN_EXAMPLE_CATALOG, + EXAMPLE_CATALOG_SCHEMA_VERSION, + availableExamples, + compareAppVersions, + exampleById, + exampleUrlAllowed, + loadExampleCatalog, + parseExampleCatalog, + parseExampleEntry, +} from "../src/canvas/workspace/example/exampleCatalog.ts"; + +const validItem = { + id: "image-canvas", + title: { "zh-CN": "图像示例", "en-US": "Image example" }, + url: "https://lz.qaiu.top/parser?url=https://example.test/x&pwd=1", + bytes: 1024, + sha256: "a".repeat(64), +}; + +function catalogWith(items: unknown[]) { + return { schemaVersion: EXAMPLE_CATALOG_SCHEMA_VERSION, items }; +} + +test("the shipped catalog is valid and offers both samples", () => { + const parsed = parseExampleCatalog(BUILTIN_EXAMPLE_CATALOG); + assert.deepEqual(parsed.rejected, []); + assert.equal(parsed.catalog.items.length, 2); + assert.deepEqual( + parsed.catalog.items.map((item) => item.id), + ["image-canvas", "video-canvas"], + ); + assert.equal(exampleById(parsed.catalog, "video-canvas")?.contentKind, "zip-wrapper"); +}); + +test("only https on an allowed host is downloadable", () => { + assert.equal(exampleUrlAllowed("https://lz.qaiu.top/parser?url=x"), true); + assert.equal(exampleUrlAllowed("https://bucket.oss-cn-hangzhou.aliyuncs.com/a.canvas"), true); + assert.equal(exampleUrlAllowed("http://lz.qaiu.top/parser?url=x"), false); + assert.equal(exampleUrlAllowed("https://evil.test/a.canvas"), false); + assert.equal(exampleUrlAllowed("not a url"), false); +}); + +test("a bad row is dropped without hiding the good ones", () => { + const parsed = parseExampleCatalog( + catalogWith([ + validItem, + { ...validItem, id: "insecure", url: "http://lz.qaiu.top/x" }, + { ...validItem, id: "foreign", url: "https://evil.test/x" }, + { ...validItem, id: "image-canvas" }, + { ...validItem, id: "no-title", title: { "zh-CN": "" } }, + { ...validItem, id: "bad-digest", sha256: "xyz" }, + { ...validItem, id: "bad-version", minAppVersion: "v1" }, + ]), + ); + assert.deepEqual( + parsed.catalog.items.map((item) => item.id), + ["image-canvas"], + ); + const reasons = parsed.rejected.map((entry) => entry.reason); + assert.ok(reasons.some((reason) => reason.includes("allowed host"))); + assert.ok(reasons.includes("duplicate id")); + assert.ok(reasons.some((reason) => reason.includes("zh-CN"))); + assert.ok(reasons.some((reason) => reason.includes("sha256"))); + assert.ok(reasons.some((reason) => reason.includes("minAppVersion"))); +}); + +test("structural problems reject the document instead of half-parsing it", () => { + assert.throws(() => parseExampleCatalog(null), /not an object/); + assert.throws( + () => parseExampleCatalog({ schemaVersion: 2, items: [] }), + /schemaVersion/, + ); + assert.throws( + () => parseExampleCatalog({ schemaVersion: 1, items: "nope" }), + /items must be an array/, + ); +}); + +test("an entry keeps its optional hints and defaults contentKind to auto", () => { + const parsed = parseExampleEntry({ ...validItem, sha256: undefined }); + assert.ok("entry" in parsed); + assert.equal(parsed.entry.contentKind, "auto"); + assert.equal(parsed.entry.sha256, undefined); + assert.equal(parsed.entry.inner, undefined); +}); + +test("versions compare numerically, not as strings", () => { + assert.equal(compareAppVersions("0.1.4", "0.1.4"), 0); + assert.equal(compareAppVersions("0.1.10", "0.1.9"), 1); + assert.equal(compareAppVersions("0.2", "0.10"), -1); + assert.equal(compareAppVersions("1", "1.0.0"), 0); +}); + +test("newer samples stay out of older builds", () => { + const catalog = parseExampleCatalog( + catalogWith([validItem, { ...validItem, id: "future", minAppVersion: "0.2.0" }]), + ).catalog; + assert.deepEqual( + availableExamples(catalog, "0.1.4").map((item) => item.id), + ["image-canvas"], + ); + assert.deepEqual( + availableExamples(catalog, "0.2.0").map((item) => item.id), + ["image-canvas", "future"], + ); +}); + +test("an unknown app version skips the gate instead of hiding every sample", () => { + const catalog = parseExampleCatalog( + catalogWith([validItem, { ...validItem, id: "future", minAppVersion: "0.2.0" }]), + ).catalog; + assert.deepEqual( + availableExamples(catalog).map((item) => item.id), + ["image-canvas", "future"], + ); +}); + +function stubFetch( + responses: Record Promise | Response>, +): typeof fetch { + return (async (input: RequestInfo | URL) => { + const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url; + const handler = responses[url]; + if (!handler) throw new Error(`unexpected url ${url}`); + return handler(); + }) as typeof fetch; +} + +function json(body: unknown): Response { + return new Response(JSON.stringify(body), { + status: 200, + headers: { "content-type": "application/json" }, + }); +} + +test("the remote catalog wins when it is usable", async () => { + const result = await loadExampleCatalog({ + remoteUrl: "https://example.test/catalog.json", + fetchImpl: stubFetch({ + "https://example.test/catalog.json": () => + json(catalogWith([{ ...validItem, id: "remote-only" }])), + }), + }); + assert.equal(result.source, "remote"); + assert.deepEqual( + result.catalog.items.map((item) => item.id), + ["remote-only"], + ); +}); + +test("a malformed remote catalog falls back to the bundled copy", async () => { + const result = await loadExampleCatalog({ + remoteUrl: "https://example.test/catalog.json", + fetchImpl: stubFetch({ + "https://example.test/catalog.json": () => json({ schemaVersion: 99, items: [] }), + }), + }); + assert.equal(result.source, "code"); + assert.deepEqual( + result.catalog.items.map((item) => item.id), + ["image-canvas", "video-canvas"], + ); +}); + +test("an unreachable remote still leaves the bundled samples", async () => { + const result = await loadExampleCatalog({ + remoteUrl: "https://example.test/catalog.json", + fetchImpl: stubFetch({ + "https://example.test/catalog.json": () => { + throw new Error("offline"); + }, + }), + }); + assert.equal(result.source, "code"); + assert.equal(result.catalog.items.length, 2); +}); + +test("the bundled copy is the one the build ships", async () => { + const result = await loadExampleCatalog(); + assert.equal(result.source, "code"); + assert.deepEqual( + result.catalog.items.map((item) => item.id), + ["image-canvas", "video-canvas"], + ); + assert.deepEqual(result.rejected, []); +}); diff --git a/tests/exampleDownload.test.ts b/tests/exampleDownload.test.ts new file mode 100644 index 000000000..d83c9ed63 --- /dev/null +++ b/tests/exampleDownload.test.ts @@ -0,0 +1,293 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { createZip } from "../src/canvas/zipArchive.ts"; +import { + EXAMPLE_MAX_BYTES, + ExampleError, + fetchExampleBytes, + fetchExampleCanvas, + normalizeToCanvas, +} from "../src/canvas/workspace/example/exampleDownload.ts"; +import type { ExampleEntry } from "../src/canvas/workspace/example/exampleCatalog.ts"; + +const encoder = new TextEncoder(); +const decoder = new TextDecoder(); + +/** A minimal but structurally valid `.canvas` archive. */ +async function canvasArchive(title = "示例"): Promise { + return createZip([ + { + path: "manifest.json", + data: encoder.encode( + JSON.stringify({ + magic: "opendirector-canvas", + formatVersion: 2, + document: "canvas.json", + assets: [], + }), + ), + compress: true, + }, + { + path: "canvas.json", + data: encoder.encode(JSON.stringify({ title, nodes: [] })), + compress: true, + }, + ]); +} + +/** The shipped samples: an outer ZIP holding exactly one `.canvas`. */ +async function wrappedArchive(): Promise { + const inner = new Uint8Array(await (await canvasArchive("包裹")).arrayBuffer()); + return createZip([{ path: "图像创作示例画布.canvas", data: inner }]); +} + +async function bytesOf(blob: Blob): Promise { + return new Uint8Array(await blob.arrayBuffer()); +} + +function entry(overrides: Partial = {}): ExampleEntry { + return { + id: "test", + title: { "zh-CN": "测试", "en-US": "Test" }, + url: "https://lz.qaiu.top/parser?url=x", + ...overrides, + }; +} + +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + assert.ok(error instanceof ExampleError, `expected ExampleError, got ${error}`); + return error; + } + throw new Error("expected the call to fail"); +} + +test("a plain archive passes through untouched", async () => { + const archive = await bytesOf(await canvasArchive()); + const normalized = await normalizeToCanvas(archive); + assert.equal(normalized.kind, "canvas"); + assert.equal(normalized.innerEntry, undefined); + assert.deepEqual(normalized.bytes, archive); +}); + +test("a ZIP wrapping one .canvas is unwrapped exactly one level", async () => { + const outer = await bytesOf(await wrappedArchive()); + const normalized = await normalizeToCanvas(outer); + assert.equal(normalized.kind, "zip-wrapper"); + assert.equal(normalized.innerEntry, "图像创作示例画布.canvas"); + assert.notDeepEqual(normalized.bytes, outer); + // The unwrapped bytes are themselves a readable archive. + const inner = await normalizeToCanvas(normalized.bytes); + assert.equal(inner.kind, "canvas"); + assert.match(decoder.decode(normalized.bytes.subarray(0, 2)), /PK/); +}); + +test("a ZIP with two .canvas entries is ambiguous, never guessed", async () => { + const one = new Uint8Array(await (await canvasArchive("a")).arrayBuffer()); + const two = new Uint8Array(await (await canvasArchive("b")).arrayBuffer()); + const outer = await bytesOf( + await createZip([ + { path: "a.canvas", data: one }, + { path: "b.canvas", data: two }, + ]), + ); + assert.equal((await rejection(normalizeToCanvas(outer))).code, "ambiguous"); +}); + +test("a ZIP without any .canvas entry is ambiguous", async () => { + const outer = await bytesOf( + await createZip([{ path: "readme.txt", data: encoder.encode("nothing here") }]), + ); + assert.equal((await rejection(normalizeToCanvas(outer))).code, "ambiguous"); +}); + +test("an HTML login page is reported as html, not as a damaged archive", async () => { + const page = encoder.encode("请登录"); + assert.equal((await rejection(normalizeToCanvas(page))).code, "html"); +}); + +test("JSON error bodies and plain text are rejected as HTML-ish markup", async () => { + const body = encoder.encode('{"errno":-62,"error":"need login"}'); + assert.equal((await rejection(normalizeToCanvas(body))).code, "html"); +}); + +test("non-ZIP bytes and truncated archives are notArchive", async () => { + assert.equal( + (await rejection(normalizeToCanvas(encoder.encode("plain text, no markup")))).code, + "notArchive", + ); + assert.equal((await rejection(normalizeToCanvas(new Uint8Array()))).code, "notArchive"); + const archive = await bytesOf(await canvasArchive()); + const truncated = archive.subarray(0, Math.floor(archive.length / 2)); + assert.equal((await rejection(normalizeToCanvas(truncated))).code, "notArchive"); +}); + +function respond( + body: BodyInit | null, + init: ResponseInit = {}, +): () => Response { + return () => new Response(body, { status: 200, ...init }); +} + +test("the shipped shape downloads end to end", async () => { + const outer = await wrappedArchive(); + const result = await fetchExampleCanvas(entry(), { + fetchImpl: (async () => respond(outer)()) as typeof fetch, + }); + assert.equal(result.kind, "zip-wrapper"); + assert.equal(result.innerEntry, "图像创作示例画布.canvas"); + assert.equal(result.outerBytes, (await outer.arrayBuffer()).byteLength); + assert.equal((await normalizeToCanvas(result.bytes)).kind, "canvas"); +}); + +test("a disallowed URL never reaches the network", async () => { + let called = false; + const failure = await rejection( + fetchExampleBytes(entry({ url: "http://lz.qaiu.top/x" }), { + fetchImpl: (async () => { + called = true; + return respond(new Blob())(); + }) as typeof fetch, + }), + ); + assert.equal(failure.code, "invalidUrl"); + assert.equal(called, false); +}); + +test("an HTTP error keeps its status", async () => { + const failure = await rejection( + fetchExampleBytes(entry(), { + fetchImpl: (async () => + new Response("nope", { status: 403 })) as typeof fetch, + }), + ); + assert.equal(failure.code, "http"); + assert.equal(failure.status, 403); +}); + +test("a body larger than the budget is stopped while streaming", async () => { + const failure = await rejection( + fetchExampleBytes(entry(), { + maxBytes: 1024, + fetchImpl: (async () => respond(new Blob([new Uint8Array(4096)]))()) as typeof fetch, + }), + ); + assert.equal(failure.code, "tooLarge"); +}); + +test("a declared content-length over the budget fails before reading", async () => { + let read = false; + const body = new ReadableStream( + { + pull(controller) { + read = true; + controller.close(); + }, + }, + // Without this the stream prefetches one chunk on creation (default 1). + { highWaterMark: 0 }, + ); + const response = { + ok: true, + status: 200, + headers: new Headers({ "content-length": String(EXAMPLE_MAX_BYTES + 1) }), + body, + } as unknown as Response; + const failure = await rejection( + fetchExampleBytes(entry(), { + fetchImpl: (async () => response) as typeof fetch, + }), + ); + assert.equal(failure.code, "tooLarge"); + assert.equal(read, false); +}); + +test("an integrity mismatch discards the download", async () => { + const outer = await wrappedArchive(); + const failure = await rejection( + fetchExampleBytes(entry({ sha256: "b".repeat(64) }), { + fetchImpl: (async () => respond(outer)()) as typeof fetch, + }), + ); + assert.equal(failure.code, "integrity"); +}); + +test("the inner digest is checked after unwrapping", async () => { + const outer = await wrappedArchive(); + const failure = await rejection( + fetchExampleCanvas( + entry({ inner: { entry: "x.canvas", sha256: "c".repeat(64) } }), + { fetchImpl: (async () => respond(outer)()) as typeof fetch }, + ), + ); + assert.equal(failure.code, "integrity"); +}); + +test("progress reports received bytes against the declared total", async () => { + const outer = await wrappedArchive(); + const bytes = new Uint8Array(await outer.arrayBuffer()); + const response = { + ok: true, + status: 200, + headers: new Headers({ "content-length": String(bytes.byteLength) }), + body: new Blob([bytes]).stream(), + } as unknown as Response; + const events: [number, number | null][] = []; + const received = await fetchExampleBytes(entry(), { + fetchImpl: (async () => response) as typeof fetch, + onProgress: (progress, total) => events.push([progress, total]), + }); + assert.equal(received.byteLength, bytes.byteLength); + assert.equal(events[0]?.[0], 0); + assert.equal(events[0]?.[1], bytes.byteLength); + assert.equal(events.at(-1)?.[0], bytes.byteLength); + assert.equal(events.at(-1)?.[1], bytes.byteLength); +}); + +test("progress falls back to an unknown total without content-length", async () => { + const outer = await wrappedArchive(); + const events: (number | null)[] = []; + await fetchExampleBytes(entry(), { + fetchImpl: (async () => respond(outer)()) as typeof fetch, + onProgress: (_received, total) => events.push(total), + }); + assert.ok(events.length > 0); + assert.equal(events.at(-1), null); +}); + +test("release zeroes the downloaded buffers and is idempotent", async () => { + const outer = await wrappedArchive(); + const result = await fetchExampleCanvas(entry(), { + fetchImpl: (async () => respond(outer)()) as typeof fetch, + }); + assert.ok(result.bytes.some((byte) => byte !== 0), "expected a real archive"); + result.release(); + assert.ok(result.bytes.every((byte) => byte === 0)); + result.release(); + assert.ok(result.bytes.every((byte) => byte === 0)); +}); + +test("cancellation and the deadline both surface as aborted", async () => { + const hanging = ((_url: string, init?: RequestInit) => + new Promise((_resolve, rejectPlaceholder) => { + const fail = () => rejectPlaceholder(new DOMException("aborted", "AbortError")); + // An already-aborted signal never fires the event again. + if (init?.signal?.aborted) return fail(); + init?.signal?.addEventListener("abort", fail); + })) as unknown as typeof fetch; + + const controller = new AbortController(); + controller.abort(); + const cancelled = await rejection( + fetchExampleBytes(entry(), { fetchImpl: hanging, signal: controller.signal }), + ); + assert.equal(cancelled.code, "aborted"); + + const timedOut = await rejection( + fetchExampleBytes(entry(), { fetchImpl: hanging, timeoutMs: 10 }), + ); + assert.equal(timedOut.code, "aborted"); +}); diff --git a/tests/exampleImport.test.ts b/tests/exampleImport.test.ts new file mode 100644 index 000000000..786063ba3 --- /dev/null +++ b/tests/exampleImport.test.ts @@ -0,0 +1,213 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { ExampleError } from "../src/canvas/workspace/example/exampleDownload.ts"; +import type { ExampleEntry } from "../src/canvas/workspace/example/exampleCatalog.ts"; +import { + runExampleImport, + type ExampleStatus, +} from "../src/canvas/workspace/example/useExampleImport.ts"; + +const entry: ExampleEntry = { + id: "image-canvas", + title: { "zh-CN": "图像创作示例画布", "en-US": "Image creation example canvas" }, + url: "https://lz.qaiu.top/parser?url=x", + bytes: 2048, +}; + +const archive = new Uint8Array([0x50, 0x4b, 0x03, 0x04, 1, 2, 3]); + +function recorder(): { phases: string[]; statuses: ExampleStatus[] } { + const statuses: ExampleStatus[] = []; + return { statuses, phases: [] as string[] }; +} + +test("a successful import reports every phase and hands over the archive", async () => { + const statuses: ExampleStatus[] = []; + let received: Blob | undefined; + let released = false; + const result = await runExampleImport( + entry, + { + fetchCanvas: async () => ({ + bytes: archive, + kind: "zip-wrapper", + outerBytes: 9, + release: () => { + released = true; + }, + }), + importCanvas: async (blob) => { + received = blob; + }, + }, + new AbortController().signal, + (status) => statuses.push(status), + ); + assert.deepEqual( + statuses.map((status) => status.phase), + ["downloading", "importing", "done"], + ); + assert.equal(statuses[2]?.title, entry.title["zh-CN"]); + assert.equal(result.kind, "zip-wrapper"); + assert.equal(result.outerBytes, 9); + assert.ok(received instanceof Blob); + assert.deepEqual(new Uint8Array(await received!.arrayBuffer()), archive); + // The download is released once the import settles. + assert.equal(released, true); +}); + +test("a download failure is classified and rethrown", async () => { + const statuses: ExampleStatus[] = []; + await assert.rejects( + runExampleImport( + entry, + { + fetchCanvas: async () => { + throw new ExampleError("html"); + }, + importCanvas: async () => {}, + }, + new AbortController().signal, + (status) => statuses.push(status), + ), + (error: unknown) => error instanceof ExampleError && error.code === "html", + ); + assert.deepEqual( + statuses.map((status) => status.phase), + ["downloading", "failed"], + ); + assert.deepEqual(statuses.at(-1), { phase: "failed", code: "html", httpStatus: undefined }); +}); + +test("an HTTP failure keeps its status for the message", async () => { + const statuses: ExampleStatus[] = []; + await assert.rejects( + runExampleImport( + entry, + { + fetchCanvas: async () => { + throw new ExampleError("http", "status 403", 403); + }, + importCanvas: async () => {}, + }, + new AbortController().signal, + (status) => statuses.push(status), + ), + ); + assert.equal(statuses.at(-1)?.code, "http"); + assert.equal(statuses.at(-1)?.httpStatus, 403); +}); + +test("an unexpected import failure is reported as unknown", async () => { + const statuses: ExampleStatus[] = []; + await assert.rejects( + runExampleImport( + entry, + { + fetchCanvas: async () => ({ + bytes: archive, + kind: "canvas", + outerBytes: 7, + release: () => {}, + }), + importCanvas: async () => { + throw new Error("switch failed"); + }, + }, + new AbortController().signal, + (status) => statuses.push(status), + ), + /switch failed/, + ); + assert.deepEqual( + statuses.map((status) => status.phase), + ["downloading", "importing", "failed"], + ); + assert.equal(statuses.at(-1)?.code, "unknown"); +}); + +test("download progress reaches the status before the import starts", async () => { + const statuses: ExampleStatus[] = []; + await runExampleImport( + entry, + { + fetchCanvas: async (_entry, options) => { + options?.onProgress?.(64, 256); + options?.onProgress?.(256, 256); + return { + bytes: archive, + kind: "canvas", + outerBytes: 256, + release: () => {}, + }; + }, + importCanvas: async () => {}, + }, + new AbortController().signal, + (status) => statuses.push(status), + ); + const downloading = statuses.filter((status) => status.phase === "downloading"); + assert.deepEqual( + downloading.map((status) => [status.received, status.total]), + [ + [undefined, undefined], + [64, 256], + [256, 256], + ], + ); +}); + +test("a failed import still releases the download", async () => { + let released = false; + await assert.rejects( + runExampleImport( + entry, + { + fetchCanvas: async () => ({ + bytes: archive, + kind: "canvas", + outerBytes: 7, + release: () => { + released = true; + }, + }), + importCanvas: async () => { + throw new Error("boom"); + }, + }, + new AbortController().signal, + () => {}, + ), + ); + assert.equal(released, true); +}); + +test("cancelling after the download skips the import entirely", async () => { + const controller = new AbortController(); + const statuses: ExampleStatus[] = []; + let imported = false; + await assert.rejects( + runExampleImport( + entry, + { + fetchCanvas: async () => { + controller.abort(); + return { + bytes: archive, + kind: "canvas", + outerBytes: 7, + release: () => {}, + }; + }, + importCanvas: async () => { + imported = true; + }, + }, + controller.signal, + (status) => statuses.push(status), + ), + (error: unknown) => error instanceof ExampleError && error.code === "aborted", + ); + assert.equal(imported, false); + assert.equal(statuses.at(-1)?.code, "aborted"); +});