From 2046f1984896a3ca759c47cc0bb8e78386875f66 Mon Sep 17 00:00:00 2001 From: allendyu <490124601@qq.com> Date: Tue, 17 Nov 2026 15:12:24 +0800 Subject: [PATCH 1/7] [feat] canvas: resolve and normalize example canvas downloads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary - Add `exampleCatalog.ts`: strict per-row validation (https on an allowlisted host, unique id, bilingual title, digest/byte types, `minAppVersion` gate) with three-tier loading — remote catalog, then the bundled copy, then a compiled-in list — so a missing file or an offline launch still offers the samples. Unusable rows are reported and dropped instead of hiding the rest. - Add `exampleDownload.ts`: https-only allowlist, streaming body read under a byte budget, deadline and caller cancellation, optional outer and inner SHA-256 checks, and content-based format detection. The shipped links deliver a ZIP wrapping exactly one `.canvas`, so the downloader unwraps one level and reports HTML login pages, non-archives and ambiguous containers separately rather than trusting the file name. - Ship both samples in `public/example-canvases.json` with the sizes and digests measured against the live links on 2026-11-17. - Keep the import call site untouched; the dialog that uses these modules and the `readCanvasArchive` hand-off follow in the next commit. ## validation - `node --test tests/exampleCatalog.test.ts tests/exampleDownload.test.ts`: 25 passed. - `tsc --noEmit` clean; `pre-commit run` clean after the hook normalized line endings. - Full frontend suite 856/857; the only failure is the pre-existing `browserHost` CJK temp-path case that also fails on clean `main`. - Manual end-to-end against the shipped links: both downloaded, unwrapped and read by `readCanvasArchive` (image: 12 nodes/5 assets; video: 17 nodes/ 9 assets), which also proves the recorded outer and inner digests. --- public/example-canvases.json | 54 +++ .../workspace/example/exampleCatalog.ts | 400 ++++++++++++++++++ .../workspace/example/exampleDownload.ts | 252 +++++++++++ tests/exampleCatalog.test.ts | 174 ++++++++ tests/exampleDownload.test.ts | 249 +++++++++++ 5 files changed, 1129 insertions(+) create mode 100644 public/example-canvases.json create mode 100644 src/canvas/workspace/example/exampleCatalog.ts create mode 100644 src/canvas/workspace/example/exampleDownload.ts create mode 100644 tests/exampleCatalog.test.ts create mode 100644 tests/exampleDownload.test.ts diff --git a/public/example-canvases.json b/public/example-canvases.json new file mode 100644 index 000000000..543044ccf --- /dev/null +++ b/public/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..c4e05eaef --- /dev/null +++ b/src/canvas/workspace/example/exampleCatalog.ts @@ -0,0 +1,400 @@ +/** + * Remote 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, an in-app copy keeps first launch working offline, and a compiled-in + * list keeps the entry usable when both files are missing. + */ +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" | "builtin" | "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; + +/** Served by the app itself; the build copies `public/` to the site root. */ +export const EXAMPLE_CATALOG_BUILTIN_PATH = "/example-canvases.json"; + +/** + * 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", +]; + +/** + * Compiled-in fallback. Kept in step with `public/example-canvases.json`; the + * sizes and digests here were measured on 2026-11-17 (see the development doc). + */ +export const BUILTIN_EXAMPLE_CATALOG: ExampleCatalog = { + schemaVersion: EXAMPLE_CATALOG_SCHEMA_VERSION, + 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, + }, + }, + ], +}; + +const KINDS = new Set(["auto", "canvas", "zip-wrapper"]); +const HOST_LOCATOR = /^[a-z0-9.-]+$/; +const SHA256 = /^[0-9a-f]{64}$/; +const VERSION = /^\d+(?:\.\d+)*$/; + +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. */ +export function availableExamples( + catalog: ExampleCatalog, + appVersion: string, +): ExampleEntry[] { + return catalog.items.filter( + (item) => + !item.minAppVersion || 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}`); + const parsed: unknown = await response.json(); + return parseExampleCatalog(parsed).catalog; +} + +/** + * Loads the catalog without ever failing: remote, then app copy, then the + * compiled-in list. `rejected` reports rows dropped while validating. + */ +export async function loadExampleCatalog( + options: { + fetchImpl?: typeof fetch; + signal?: AbortSignal; + remoteUrl?: string; + builtinUrl?: string; + appVersion?: string; + } = {}, +): Promise { + const fetchImpl = options.fetchImpl ?? fetch; + const builtinUrl = options.builtinUrl ?? EXAMPLE_CATALOG_BUILTIN_PATH; + const rejected: RejectedEntry[] = []; + for (const [source, url] of [ + ["remote", options.remoteUrl], + ["builtin", builtinUrl], + ] as const) { + if (!url) continue; + try { + const parsed: unknown = await (async () => { + const response = await fetchImpl(url, { + method: "GET", + credentials: "omit", + cache: "no-store", + signal: options.signal, + }); + if (!response.ok) throw new Error(`catalog responded ${response.status}`); + return response.json(); + })(); + const validated = parseExampleCatalog(parsed); + rejected.push(...validated.rejected); + return { catalog: validated.catalog, source, rejected }; + } catch { + /* A missing or malformed copy falls through to the next source. */ + } + } + const fallback = parseExampleCatalog(BUILTIN_EXAMPLE_CATALOG); + 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); +} + +export { readCatalogFile }; diff --git a/src/canvas/workspace/example/exampleDownload.ts b/src/canvas/workspace/example/exampleDownload.ts new file mode 100644 index 000000000..b8efa5233 --- /dev/null +++ b/src/canvas/workspace/example/exampleDownload.ts @@ -0,0 +1,252 @@ +/** + * 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" + | "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; +} + +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; +} + +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, +): Promise { + if (!response.body) { + const buffer = await response.arrayBuffer(); + if (buffer.byteLength > maxBytes) throw new ExampleError("tooLarge"); + return new Uint8Array(buffer); + } + const reader = response.body.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => undefined); + throw new ExampleError("tooLarge"); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(total); + 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); + } 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"); + } + return { ...normalized, outerBytes: outer.byteLength }; +} diff --git a/tests/exampleCatalog.test.ts b/tests/exampleCatalog.test.ts new file mode 100644 index 000000000..bbec393fc --- /dev/null +++ b/tests/exampleCatalog.test.ts @@ -0,0 +1,174 @@ +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"], + ); +}); + +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 broken remote catalog falls back to the bundled copy", async () => { + const result = await loadExampleCatalog({ + remoteUrl: "https://example.test/catalog.json", + builtinUrl: "/example-canvases.json", + fetchImpl: stubFetch({ + "https://example.test/catalog.json": () => json({ schemaVersion: 99, items: [] }), + "/example-canvases.json": () => json(catalogWith([{ ...validItem, id: "bundled" }])), + }), + }); + assert.equal(result.source, "builtin"); + assert.deepEqual( + result.catalog.items.map((item) => item.id), + ["bundled"], + ); +}); + +test("both files missing still leaves the compiled-in samples", async () => { + const result = await loadExampleCatalog({ + remoteUrl: "https://example.test/catalog.json", + fetchImpl: stubFetch({ + "https://example.test/catalog.json": () => { + throw new Error("offline"); + }, + "/example-canvases.json": () => { + throw new Error("offline"); + }, + }), + }); + assert.equal(result.source, "code"); + assert.equal(result.catalog.items.length, 2); +}); diff --git a/tests/exampleDownload.test.ts b/tests/exampleDownload.test.ts new file mode 100644 index 000000000..4b9d3077b --- /dev/null +++ b/tests/exampleDownload.test.ts @@ -0,0 +1,249 @@ +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("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"); +}); From caf91608b8897ac31d50a6bb09a44e57f1e06944 Mon Sep 17 00:00:00 2001 From: allendyu <490124601@qq.com> Date: Tue, 17 Nov 2026 15:30:21 +0800 Subject: [PATCH 2/7] [feat] canvas: offer a picker for the downloadable example canvases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary - Add `ExampleCanvasDialog`: a native `` listing the catalog with the localized title, summary, size and archive version. Each row owns its status, so one failing sample never blocks the others. - Add `useExampleImport` and `runExampleImport`: download, hand the unwrapped archive to the caller's import path, and report `downloading → importing → done`. Cancelling during download returns the row to idle instead of showing an error, and a cancel that lands after the bytes arrive skips the import entirely. - Keep the archive out of component state: the blob is created for the import call and dropped afterwards, so no downloaded copy survives the import. - Classify failures for the reader — HTTP status, blocked page, non-archive, ambiguous container, digest mismatch, untrusted address — instead of showing one generic message. - Add an explicit manual-import fallback per row (share link plus code) for cases the hosted link itself is gone. - Add the 27 bilingual strings and register the catalog's Chinese sample names in `scripts/i18n-baseline.json`: they are data, not translatable UI copy. ## validation - `node --test tests/exampleImport.test.ts tests/exampleCatalog.test.ts tests/exampleDownload.test.ts`: 30 passed. - `tsc --noEmit` clean; `check-i18n` 0 problems; `pre-commit run` clean after the hook normalized line endings. - Full frontend suite 861/862; the only failure is the pre-existing `browserHost` CJK temp-path case that also fails on clean `main`. ## notes - The dialog is not rendered yet; wiring the empty-state button and the `readCanvasArchive` hand-off is the next change. --- scripts/i18n-baseline.json | 10 +- .../workspace/example/ExampleCanvasDialog.tsx | 166 ++++++++++++++++++ .../workspace/example/example-canvas.css | 135 ++++++++++++++ .../workspace/example/exampleDownload.ts | 1 + .../workspace/example/useExampleImport.ts | 131 ++++++++++++++ src/i18n/messages/en-US/canvasWorkspace.ts | 28 +++ src/i18n/messages/zh-CN/canvasWorkspace.ts | 28 +++ tests/exampleImport.test.ts | 136 ++++++++++++++ 8 files changed, 629 insertions(+), 6 deletions(-) create mode 100644 src/canvas/workspace/example/ExampleCanvasDialog.tsx create mode 100644 src/canvas/workspace/example/example-canvas.css create mode 100644 src/canvas/workspace/example/useExampleImport.ts create mode 100644 tests/exampleImport.test.ts diff --git a/scripts/i18n-baseline.json b/scripts/i18n-baseline.json index e62361a7e..6893109ca 100644 --- a/scripts/i18n-baseline.json +++ b/scripts/i18n-baseline.json @@ -1,18 +1,16 @@ { - "total": 168, + "total": 173, "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/example/exampleCatalog.ts": 8, + "src/canvas/workspace/useWorkspaceTransfer.ts": 1 } } diff --git a/src/canvas/workspace/example/ExampleCanvasDialog.tsx b/src/canvas/workspace/example/ExampleCanvasDialog.tsx new file mode 100644 index 000000000..54cdf1d0a --- /dev/null +++ b/src/canvas/workspace/example/ExampleCanvasDialog.tsx @@ -0,0 +1,166 @@ +import { useEffect, useRef } from "react"; +import { useI18n, useT, type Translate } from "../../../i18n/I18nProvider.tsx"; +import type { ExampleEntry } from "./exampleCatalog.ts"; +import { useExampleImport, type ExampleStatus } from "./useExampleImport.ts"; +import "./example-canvas.css"; + +function megabytes(bytes: number | undefined): string | null { + if (!bytes) return null; + return `${(bytes / 1024 / 1024).toFixed(1)} MB`; +} + +/** One sentence per failure, chosen by code so the cause stays recognizable. */ +function failureText(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: + return t("canvas.example.error.unknown"); + } +} + +/** + * Picks an example canvas, downloads it and hands the archive to the caller's + * import path. Every row owns its own status, so one failure cannot block the + * others. + */ +export function ExampleCanvasDialog({ + entries, + onClose, + onImport, +}: { + entries: ExampleEntry[]; + onClose: () => 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 version = entry.inner?.archiveVersion ?? entry.archiveVersion; + return ( +
  • +
    + {entry.title[locale]} + + {t("canvas.example.item.meta", { + size: size ?? t("canvas.example.item.metaUnknown"), + version: version ?? "-", + })} + +
    + {entry.summary &&

    {entry.summary[locale]}

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

    + {failureText(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..bf990c7c0 --- /dev/null +++ b/src/canvas/workspace/example/example-canvas.css @@ -0,0 +1,135 @@ +/* Example canvas picker: download progress, failure reason and manual fallback. */ +.cw-example-dialog { + width: min(680px, calc(100vw - 48px)); + max-height: min(78vh, 720px); + padding: 20px; + border-radius: 16px; + border: 1px solid var(--cw-control-border); + background: var(--cw-control-surface); + color: var(--cw-control-fg); + box-shadow: var(--cw-control-shadow); + overflow: auto; +} + +.cw-example-dialog::backdrop { + background: #0007; +} + +.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: var(--cw-control-muted, #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 var(--cw-control-border); + border-radius: 12px; + background: color-mix(in srgb, var(--cw-control-surface) 88%, #fff 12%); +} + +.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: var(--cw-control-muted, #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 { + padding: 5px 12px; + border-radius: 8px; + border: 1px solid var(--cw-control-border); + background: transparent; + color: inherit; + font-size: 12px; + cursor: pointer; +} + +.cw-example-actions button:hover { + background: color-mix(in srgb, var(--cw-control-fg) 8%, transparent); +} + +.cw-example-error { + margin: 0; + font-size: 12px; + color: #e08a8a; +} + +.cw-example-manual { + font-size: 12px; +} + +.cw-example-manual summary { + color: var(--cw-control-muted, #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; + border-radius: 8px; + border: 1px solid var(--cw-control-border); + background: transparent; + color: inherit; + font-size: 13px; + cursor: pointer; +} + +.cw-example-dialog-actions button:disabled { + opacity: 0.5; + cursor: not-allowed; +} diff --git a/src/canvas/workspace/example/exampleDownload.ts b/src/canvas/workspace/example/exampleDownload.ts index b8efa5233..9ad882728 100644 --- a/src/canvas/workspace/example/exampleDownload.ts +++ b/src/canvas/workspace/example/exampleDownload.ts @@ -15,6 +15,7 @@ export type ExampleErrorCode = | "html" | "notArchive" | "ambiguous" + | "notCanvas" | "integrity"; /** A classified failure; the UI owns the wording for each code. */ diff --git a/src/canvas/workspace/example/useExampleImport.ts b/src/canvas/workspace/example/useExampleImport.ts new file mode 100644 index 000000000..8566d42ca --- /dev/null +++ b/src/canvas/workspace/example/useExampleImport.ts @@ -0,0 +1,131 @@ +/** + * 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; +} + +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 }; + return { phase: "failed", code: "unknown" }; +} + +/** + * Runs one import and reports every phase transition. + * + * 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 }); + } catch (error) { + const status = failure(error); + report(status); + throw error; + } + if (signal.aborted) { + const aborted = new ExampleError("aborted"); + report({ phase: "failed", code: "aborted" }); + throw aborted; + } + report({ phase: "importing" }); + try { + await deps.importCanvas( + new Blob([download.bytes as unknown as BlobPart], { + type: "application/octet-stream", + }), + ); + } catch (error) { + const status = failure(error); + report(status); + throw error; + } + report({ phase: "done", title: entry.title["zh-CN"] }); + return download; +} + +/** 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) => { + if (controllers.current.has(entry.id)) return; + 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); + }); + } catch { + /* The inline status already explains the failure. */ + } 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/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index cc20376d0..ac8e2c242 100644 --- a/src/i18n/messages/en-US/canvasWorkspace.ts +++ b/src/i18n/messages/en-US/canvasWorkspace.ts @@ -423,4 +423,32 @@ 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.item.meta": "{size} · v{version}", + "canvas.example.item.metaUnknown": "Size unknown", + "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})", } as const; diff --git a/src/i18n/messages/zh-CN/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index fa6931ac0..ce2ab041b 100644 --- a/src/i18n/messages/zh-CN/canvasWorkspace.ts +++ b/src/i18n/messages/zh-CN/canvasWorkspace.ts @@ -378,4 +378,32 @@ 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.item.meta": "{size} · 版本 {version}", + "canvas.example.item.metaUnknown": "大小未知", + "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})", } as const; diff --git a/tests/exampleImport.test.ts b/tests/exampleImport.test.ts new file mode 100644 index 000000000..efa545ac4 --- /dev/null +++ b/tests/exampleImport.test.ts @@ -0,0 +1,136 @@ +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; + const result = await runExampleImport( + entry, + { + fetchCanvas: async () => ({ bytes: archive, kind: "zip-wrapper", outerBytes: 9 }), + 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.ok(received instanceof Blob); + assert.deepEqual(new Uint8Array(await received!.arrayBuffer()), archive); +}); + +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 }), + 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("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 }; + }, + 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"); +}); From fd748a7bb67eb23d22efb67f6cd40d6b0d8175ae Mon Sep 17 00:00:00 2001 From: allendyu <490124601@qq.com> Date: Tue, 17 Nov 2026 15:45:03 +0800 Subject: [PATCH 3/7] [feat] canvas: open the example picker from the empty canvas ## summary - Wire the empty-state button to the picker: clicking "try the example canvas" loads the catalog and opens the dialog directly, so a fresh install with no local sample still has something to open. - Split the archive import in `useWorkspaceTransfer`: `importCanvasArchive` reads the archive, lands it as a project and returns the title/asset count while throwing on failure; `importDocument` keeps the toast-and-notify behaviour the file drop path already had. The picker uses the throwing variant so its own classifier can name the cause. - Leave the running version out of the `minAppVersion` gate: the frontend does not expose its own version yet, and filtering on an absent value would hide every sample. The gate still applies once a version is supplied. - Show the localized archive error when a failure has no dedicated code (for example "archive is newer than this app") instead of a generic message. - Keep the in-browser generated example and its `openExampleWorkspaceProject` recovery path intact for the paths that still use them. ## validation - `node --test tests/*.test.ts`: 862/863 passed. The only failure is the pre-existing `browserHost` CJK temp-path case that also fails on `main`. - `node --test` on the three example suites: 31 passed. - `tsc --noEmit` clean; `check-i18n` 0 problems; `pre-commit run` clean. - `vite build` succeeds and the output contains the dialog markup, the built-in catalog and `dist/example-canvases.json` with both entries, so the compiled fallback ships with the app. ## notes - The picker is clickable from the empty canvas now; a browser test that drives the download, the failure codes and the cache release follows next. --- src/canvas/workspace/WorkspaceView.tsx | 47 ++++++++++++++----- .../workspace/example/ExampleCanvasDialog.tsx | 3 +- .../workspace/example/exampleCatalog.ts | 12 +++-- .../workspace/example/useExampleImport.ts | 10 +++- src/canvas/workspace/useWorkspaceTransfer.ts | 28 +++++++---- tests/exampleCatalog.test.ts | 10 ++++ 6 files changed, 83 insertions(+), 27 deletions(-) diff --git a/src/canvas/workspace/WorkspaceView.tsx b/src/canvas/workspace/WorkspaceView.tsx index 73ca99a34..360a49aa9 100644 --- a/src/canvas/workspace/WorkspaceView.tsx +++ b/src/canvas/workspace/WorkspaceView.tsx @@ -1,7 +1,7 @@ import { Background, BackgroundVariant, MiniMap, SelectionMode, ViewportPortal } from "@xyflow/react"; import "@xyflow/react/dist/style.css"; -import { Suspense, useEffect, type CSSProperties } from "react"; +import { Suspense, useEffect, useState, type CSSProperties } from "react"; import { createNode } from "../model.ts"; import { NodeVersionHistory } from "../NodeVersionHistory"; @@ -17,8 +17,14 @@ import { TimelinePackageImport, exportTimelinePackage as exportNativeTimelinePac import { readLocalResource } from "../timelineExport.ts"; import { timelinePublication } from "../../backend/timelinePublication"; import { acknowledgeToolPlacement, cancelToolTask } from "../../backend/tools.ts"; -import { createWorkspaceProject, listWorkspaceProjects, openExampleWorkspaceProject, openWorkspaceProject, saveWorkspaceDocument, workspaceProjection } from "../../backend/workspace"; -import { exampleDocument, exampleProjectTitle, studyImage } from "../assets"; +import { createWorkspaceProject, listWorkspaceProjects, openWorkspaceProject, saveWorkspaceDocument, workspaceProjection } from "../../backend/workspace"; +import { studyImage } from "../assets"; +import { ExampleCanvasDialog } from "./example/ExampleCanvasDialog.tsx"; +import { + availableExamples, + loadExampleCatalog, + type ExampleEntry, +} from "./example/exampleCatalog.ts"; import { AssistantPanel } from "../AssistantPanel"; import { CanvasActionsContext } from "../CanvasActionsContext"; @@ -167,6 +173,7 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { historyReplaying, importActionResultFiles, importActionResults, + importCanvasArchive, importCanvasSource, importDocument, importFiles, @@ -301,6 +308,21 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { } = rt; + /** Example picker: open immediately, then fill from the catalog. */ + const [exampleEntries, setExampleEntries] = useState(null); + const [exampleLoading, setExampleLoading] = useState(false); + const openExamplePicker = async () => { + if (exampleLoading) return; + setExampleLoading(true); + try { + const result = await loadExampleCatalog(); + setExampleEntries(availableExamples(result.catalog)); + } finally { + setExampleLoading(false); + } + }; + + const outputState = timelineOutput.state; const outputSource = outputState ? doc.nodes.find((node) => node.id === outputState.itemId) : undefined; const existingOutput = outputState ? projected.nodes.find((node: { id: string }) => node.id === outputState.output.id) : undefined; @@ -1009,16 +1031,8 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { {t("canvas.workspace.empty.configureModels")} @@ -2728,6 +2742,13 @@ export function WorkspaceView({ rt }: { rt: WorkspaceRuntime }) { onClose={() => { dismissModelSetup(); setSettingsOpen(false); }} /> )} + {exampleEntries && ( + setExampleEntries(null)} + onImport={(archive) => importCanvasArchive(archive)} + /> + )} {help && (
setHelp(false)}>
- !item.minAppVersion || compareAppVersions(appVersion, item.minAppVersion) >= 0, + !item.minAppVersion || + !appVersion || + compareAppVersions(appVersion, item.minAppVersion) >= 0, ); } diff --git a/src/canvas/workspace/example/useExampleImport.ts b/src/canvas/workspace/example/useExampleImport.ts index 8566d42ca..3c634d495 100644 --- a/src/canvas/workspace/example/useExampleImport.ts +++ b/src/canvas/workspace/example/useExampleImport.ts @@ -22,6 +22,8 @@ export interface ExampleStatus { httpStatus?: number; /** The imported title, when `phase` is `done`. */ title?: string; + /** The original message, for failures the codes cannot describe. */ + message?: string; } export interface ExampleImportDeps { @@ -33,7 +35,13 @@ export interface ExampleImportDeps { function failure(error: unknown): ExampleStatus { if (error instanceof ExampleError) return { phase: "failed", code: error.code, httpStatus: error.status }; - return { phase: "failed", code: "unknown" }; + // 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, + }; } /** 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/tests/exampleCatalog.test.ts b/tests/exampleCatalog.test.ts index bbec393fc..a3c79de89 100644 --- a/tests/exampleCatalog.test.ts +++ b/tests/exampleCatalog.test.ts @@ -108,6 +108,16 @@ test("newer samples stay out of older builds", () => { ); }); +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 { From fed874ce04004a66f5cc215edaf062c0e92b3381 Mon Sep 17 00:00:00 2001 From: allendyu <490124601@qq.com> Date: Tue, 17 Nov 2026 16:04:10 +0800 Subject: [PATCH 4/7] [feat] canvas: release the example download and cover the picker in the gate lane ## summary - Release the download explicitly: `fetchExampleCanvas` now returns a `release` handle that zeroes the wrapper and the unwrapped buffers, and `runExampleImport` calls it in a `finally`, so success, failure and cancel all leave no archive copy behind. The import result carries only metadata (`kind`, `innerEntry`, `outerBytes`), never the bytes. - Add `tests/browser/example_canvas_picker.mjs` and run it from `scripts/run-browser-suite.mjs` in the `gate` lane. It builds the fixture with the real exporter, serves it as a ZIP around one `.canvas`, and asserts: the empty canvas opens the picker, the wrapped download imports and switches to a two-node canvas, and an HTML page is reported without creating a project while the manual-import fallback stays reachable. Both the catalog and the sample are routed in-page, so the check needs no external host. - Document the picker in both user guides, including the ZIP-around-`.canvas` unwrapping and the manual fallback. ## validation - `node --test tests/*.test.ts`: 864/865. The only failure is the pre-existing `browserHost` CJK temp-path case that also fails on `main`. - The three example suites: 33 passed, including the new release assertions (buffers zeroed, idempotent, released on success and on import failure). - `tsc --noEmit` clean; `check-i18n` 0 problems; `check-browser-manifest` `80 entries, gate=24`; `check-browser-locale` 0 problems; `pre-commit` clean. ## verification limit - The browser check was **not executed here**: this machine cannot download a Chromium build (the Playwright CDN is unreachable and the cached archive is truncated). The manifest and locale checks confirm it is registered and synthesised correctly; the gate lane runs it on CI. --- docs/guides/user-guide.md | 1 + docs/guides/user-guide.zh-CN.md | 1 + scripts/run-browser-suite.mjs | 4 + .../workspace/example/exampleDownload.ts | 16 +- .../workspace/example/useExampleImport.ts | 36 +++-- tests/browser/example_canvas_picker.mjs | 143 ++++++++++++++++++ tests/browser/manifest.json | 8 + tests/exampleDownload.test.ts | 12 ++ tests/exampleImport.test.ts | 52 ++++++- 9 files changed, 255 insertions(+), 18 deletions(-) create mode 100644 tests/browser/example_canvas_picker.mjs 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/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/workspace/example/exampleDownload.ts b/src/canvas/workspace/example/exampleDownload.ts index 9ad882728..34c39dd46 100644 --- a/src/canvas/workspace/example/exampleDownload.ts +++ b/src/canvas/workspace/example/exampleDownload.ts @@ -55,6 +55,11 @@ export interface NormalizedCanvas { 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]; @@ -249,5 +254,14 @@ export async function fetchExampleCanvas( if (digest && digest !== entry.inner.sha256) throw new ExampleError("integrity"); } - return { ...normalized, outerBytes: outer.byteLength }; + // 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/useExampleImport.ts b/src/canvas/workspace/example/useExampleImport.ts index 3c634d495..1b4f4d635 100644 --- a/src/canvas/workspace/example/useExampleImport.ts +++ b/src/canvas/workspace/example/useExampleImport.ts @@ -44,8 +44,15 @@ function failure(error: unknown): ExampleStatus { }; } +export interface ExampleImportResult { + kind: ExampleDownload["kind"]; + innerEntry?: string; + outerBytes: number; +} + /** - * Runs one import and reports every phase transition. + * 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. @@ -55,35 +62,36 @@ export async function runExampleImport( deps: ExampleImportDeps, signal: AbortSignal, report: (status: ExampleStatus) => void, -): Promise { +): Promise { report({ phase: "downloading" }); let download: ExampleDownload; try { download = await (deps.fetchCanvas ?? fetchExampleCanvas)(entry, { signal }); } catch (error) { - const status = failure(error); - report(status); + report(failure(error)); throw error; } - if (signal.aborted) { - const aborted = new ExampleError("aborted"); - report({ phase: "failed", code: "aborted" }); - throw aborted; - } - report({ phase: "importing" }); 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) { - const status = failure(error); - report(status); + report(failure(error)); throw error; + } finally { + // No download survives the call: this is the cache release the feature needs. + download.release(); } - report({ phase: "done", title: entry.title["zh-CN"] }); - return download; } /** Per-entry status plus the controls the dialog needs. */ diff --git a/tests/browser/example_canvas_picker.mjs b/tests/browser/example_canvas_picker.mjs new file mode 100644 index 000000000..0be3038e5 --- /dev/null +++ b/tests/browser/example_canvas_picker.mjs @@ -0,0 +1,143 @@ +/** + * Isolated UI regression: the empty canvas offers the example picker, imports a + * wrapped `.canvas` download, and reports a blocked page instead of importing it. + * + * 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: "fixture-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 }, + }, + ], +}; +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 })); + await page.route(sampleUrl, (route) => + 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(); + await page.getByRole("button", { name: /体验示例画布/ }).click(); + await page.locator(".cw-example-dialog").waitFor(); + }; + + // 1. The picker lists the catalog entry with its measured size. + await openCanvas(); + const dialog = page.locator(".cw-example-dialog"); + await dialog.getByText(document.title, { exact: true }).waitFor(); + assert.match(await dialog.locator(".cw-example-item small").first().innerText(), /MB|KB/); + + // 2. Downloading the wrapped archive imports it and switches the canvas. + await dialog.getByRole("button", { name: "下载并导入" }).click(); + await dialog.getByText(/已导入/).waitFor(); + await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); + assert.equal(await page.locator(".react-flow__node").count(), 2); + await dialog.getByRole("button", { name: "关闭", exact: true }).first().click(); + + // 3. A page instead of an archive is reported, 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.locator(".cw-example-dialog").getByRole("button", { name: "下载并导入" }).click(); + await page.getByText(/服务器返回的是网页/).waitFor(); + assert.equal(await page.locator(".react-flow__node").count(), 0); + // The manual fallback stays available for a blocked link. + assert.equal( + await page.locator(".cw-example-manual").count(), + 1, + ); + + 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/exampleDownload.test.ts b/tests/exampleDownload.test.ts index 4b9d3077b..ee91ed8a5 100644 --- a/tests/exampleDownload.test.ts +++ b/tests/exampleDownload.test.ts @@ -226,6 +226,18 @@ test("the inner digest is checked after unwrapping", async () => { assert.equal(failure.code, "integrity"); }); +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) => { diff --git a/tests/exampleImport.test.ts b/tests/exampleImport.test.ts index efa545ac4..ab7aa85f9 100644 --- a/tests/exampleImport.test.ts +++ b/tests/exampleImport.test.ts @@ -24,10 +24,18 @@ function recorder(): { phases: string[]; statuses: ExampleStatus[] } { 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 }), + fetchCanvas: async () => ({ + bytes: archive, + kind: "zip-wrapper", + outerBytes: 9, + release: () => { + released = true; + }, + }), importCanvas: async (blob) => { received = blob; }, @@ -41,8 +49,11 @@ test("a successful import reports every phase and hands over the archive", async ); 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 () => { @@ -93,7 +104,12 @@ test("an unexpected import failure is reported as unknown", async () => { runExampleImport( entry, { - fetchCanvas: async () => ({ bytes: archive, kind: "canvas", outerBytes: 7 }), + fetchCanvas: async () => ({ + bytes: archive, + kind: "canvas", + outerBytes: 7, + release: () => {}, + }), importCanvas: async () => { throw new Error("switch failed"); }, @@ -110,6 +126,31 @@ test("an unexpected import failure is reported as unknown", async () => { assert.equal(statuses.at(-1)?.code, "unknown"); }); +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[] = []; @@ -120,7 +161,12 @@ test("cancelling after the download skips the import entirely", async () => { { fetchCanvas: async () => { controller.abort(); - return { bytes: archive, kind: "canvas", outerBytes: 7 }; + return { + bytes: archive, + kind: "canvas", + outerBytes: 7, + release: () => {}, + }; }, importCanvas: async () => { imported = true; From 164e4eb831a8ba45f0962d79ee87fa687b492f41 Mon Sep 17 00:00:00 2001 From: allendyu <490124601@qq.com> Date: Tue, 17 Nov 2026 16:18:19 +0800 Subject: [PATCH 5/7] [bugfix] canvas: make the example picker readable in dark mode and show progress ## summary - Fix the dark-mode overlap: the picker used `--cw-control-*`, which the app only defines under `[data-theme="light"]`, so in the default dark theme the dialog had no background and the empty canvas showed through its text. Dark colours are now the base and the light theme overrides them, matching how the other dialogs are themed. The backdrop is opaque enough to stop the bleed. - Drop the archive version from each row; the row now shows only the measured size. The size/version message keys are removed in both locales. - Show real download progress: the streaming reader reports received bytes and the declared total, the import status carries them, and the row renders a native `` bar with a percentage. When the server sends no `content-length` the bar stays indeterminate instead of inventing a total. - Release the download as soon as the import settles (success, failure or cancel), so the progress work does not leave a second copy behind. ## validation - `node --test tests/*.test.ts`: 867/868. The only failure is the pre-existing `browserHost` CJK temp-path case that also fails on `main`. - The three example suites: 36 passed, including new assertions that progress starts at 0 with the declared total, ends at the full size, and reports an unknown total when the header is absent. - `tsc --noEmit` clean; `check-i18n` 0 problems; `check-browser-manifest` and `check-browser-locale` clean; `vite build` succeeds and the emitted CSS now carries `background:#23242b` for the dialog. ## notes - The browser check still runs only on CI; this machine cannot fetch a Chromium build. --- .../workspace/example/ExampleCanvasDialog.tsx | 28 ++-- .../workspace/example/example-canvas.css | 120 ++++++++++++++---- .../workspace/example/exampleDownload.ts | 18 ++- .../workspace/example/useExampleImport.ts | 10 +- src/i18n/messages/en-US/canvasWorkspace.ts | 5 +- src/i18n/messages/zh-CN/canvasWorkspace.ts | 5 +- tests/exampleDownload.test.ts | 32 +++++ tests/exampleImport.test.ts | 31 +++++ 8 files changed, 208 insertions(+), 41 deletions(-) diff --git a/src/canvas/workspace/example/ExampleCanvasDialog.tsx b/src/canvas/workspace/example/ExampleCanvasDialog.tsx index cb00815e4..66bdfb569 100644 --- a/src/canvas/workspace/example/ExampleCanvasDialog.tsx +++ b/src/canvas/workspace/example/ExampleCanvasDialog.tsx @@ -9,6 +9,12 @@ function megabytes(bytes: number | undefined): string | null { return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } +/** Completion percentage, or null while the server has not declared a size. */ +function percentOf(status: ExampleStatus): number | null { + if (!status.total || !status.received) return null; + return Math.min(100, Math.round((status.received / status.total) * 100)); +} + /** One sentence per failure, chosen by code so the cause stays recognizable. */ function failureText(t: Translate, status: ExampleStatus): string { switch (status.code) { @@ -91,26 +97,32 @@ export function ExampleCanvasDialog({ const status = statuses[entry.id] ?? { phase: "idle" as const }; const running = isRunning(entry.id); const size = megabytes(entry.bytes); - const version = entry.inner?.archiveVersion ?? entry.archiveVersion; + const percent = percentOf(status); return (
  • {entry.title[locale]} - - {t("canvas.example.item.meta", { - size: size ?? t("canvas.example.item.metaUnknown"), - version: version ?? "-", - })} - + {size && {size}}
    {entry.summary &&

    {entry.summary[locale]}

    }
    {running ? ( <> + {status.phase === "downloading" && ( + + )} {status.phase === "importing" ? t("canvas.example.state.importing") - : t("canvas.example.state.downloading")} + : percent === null + ? t("canvas.example.state.downloading") + : t("canvas.example.state.downloadingPercent", { percent })} )} + {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")}
  • )} diff --git a/src/canvas/workspace/example/ExampleCanvasDialog.tsx b/src/canvas/workspace/example/ExampleCanvasDialog.tsx index 66bdfb569..3293fcf24 100644 --- a/src/canvas/workspace/example/ExampleCanvasDialog.tsx +++ b/src/canvas/workspace/example/ExampleCanvasDialog.tsx @@ -1,7 +1,8 @@ import { useEffect, useRef } from "react"; -import { useI18n, useT, type Translate } from "../../../i18n/I18nProvider.tsx"; +import { useI18n, useT } from "../../../i18n/I18nProvider.tsx"; import type { ExampleEntry } from "./exampleCatalog.ts"; -import { useExampleImport, type ExampleStatus } from "./useExampleImport.ts"; +import { useExampleImport } from "./useExampleImport.ts"; +import { exampleFailureText, examplePercent } from "./exampleFailure.ts"; import "./example-canvas.css"; function megabytes(bytes: number | undefined): string | null { @@ -9,41 +10,6 @@ function megabytes(bytes: number | undefined): string | null { return `${(bytes / 1024 / 1024).toFixed(1)} MB`; } -/** Completion percentage, or null while the server has not declared a size. */ -function percentOf(status: ExampleStatus): number | null { - if (!status.total || !status.received) return null; - return Math.min(100, Math.round((status.received / status.total) * 100)); -} - -/** One sentence per failure, chosen by code so the cause stays recognizable. */ -function failureText(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"); - } -} - /** * Picks an example canvas, downloads it and hands the archive to the caller's * import path. Every row owns its own status, so one failure cannot block the @@ -97,7 +63,7 @@ export function ExampleCanvasDialog({ const status = statuses[entry.id] ?? { phase: "idle" as const }; const running = isRunning(entry.id); const size = megabytes(entry.bytes); - const percent = percentOf(status); + const percent = examplePercent(status); return (
  • @@ -152,7 +118,7 @@ export function ExampleCanvasDialog({
    {status.phase === "failed" && (

    - {failureText(t, status)} + {exampleFailureText(t, status)}

    )} {entry.manual?.shareUrl && ( diff --git a/public/example-canvases.json b/src/canvas/workspace/example/example-canvases.json similarity index 100% rename from public/example-canvases.json rename to src/canvas/workspace/example/example-canvases.json diff --git a/src/canvas/workspace/example/exampleCatalog.ts b/src/canvas/workspace/example/exampleCatalog.ts index 7b739bf72..b4a2c5ba4 100644 --- a/src/canvas/workspace/example/exampleCatalog.ts +++ b/src/canvas/workspace/example/exampleCatalog.ts @@ -1,10 +1,13 @@ /** - * Remote example canvases: catalog parsing, validation and the fallback order. + * 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, an in-app copy keeps first launch working offline, and a compiled-in - * list keeps the entry usable when both files are missing. + * 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; @@ -49,7 +52,7 @@ export interface ExampleCatalog { items: ExampleEntry[]; } -export type CatalogSource = "remote" | "builtin" | "code"; +export type CatalogSource = "remote" | "code"; export interface RejectedEntry { /** The offending id when it parsed well enough to be reported. */ @@ -65,8 +68,9 @@ export interface ExampleCatalogResult { export const EXAMPLE_CATALOG_SCHEMA_VERSION = 1; -/** Served by the app itself; the build copies `public/` to the site root. */ -export const EXAMPLE_CATALOG_BUILTIN_PATH = "/example-canvases.json"; +/** 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 @@ -82,74 +86,21 @@ export const EXAMPLE_ALLOWED_HOSTS: readonly string[] = [ "qbox.me", ]; -/** - * Compiled-in fallback. Kept in step with `public/example-canvases.json`; the - * sizes and digests here were measured on 2026-11-17 (see the development doc). - */ -export const BUILTIN_EXAMPLE_CATALOG: ExampleCatalog = { - schemaVersion: EXAMPLE_CATALOG_SCHEMA_VERSION, - 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, - }, - }, - ], -}; - 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); } @@ -339,7 +290,7 @@ async function readCatalogFile( fetchImpl: typeof fetch, url: string, signal: AbortSignal | undefined, -): Promise { +): Promise { const response = await fetchImpl(url, { method: "GET", credentials: "omit", @@ -347,50 +298,39 @@ async function readCatalogFile( signal, }); if (!response.ok) throw new Error(`catalog responded ${response.status}`); - const parsed: unknown = await response.json(); - return parseExampleCatalog(parsed).catalog; + return response.json(); } /** - * Loads the catalog without ever failing: remote, then app copy, then the - * compiled-in list. `rejected` reports rows dropped while validating. + * 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; - builtinUrl?: string; appVersion?: string; } = {}, ): Promise { - const fetchImpl = options.fetchImpl ?? fetch; - const builtinUrl = options.builtinUrl ?? EXAMPLE_CATALOG_BUILTIN_PATH; const rejected: RejectedEntry[] = []; - for (const [source, url] of [ - ["remote", options.remoteUrl], - ["builtin", builtinUrl], - ] as const) { - if (!url) continue; + if (options.remoteUrl) { try { - const parsed: unknown = await (async () => { - const response = await fetchImpl(url, { - method: "GET", - credentials: "omit", - cache: "no-store", - signal: options.signal, - }); - if (!response.ok) throw new Error(`catalog responded ${response.status}`); - return response.json(); - })(); + 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, rejected }; + return { catalog: validated.catalog, source: "remote", rejected }; } catch { - /* A missing or malformed copy falls through to the next source. */ + /* A missing or malformed remote copy falls through to the bundled one. */ } } - const fallback = parseExampleCatalog(BUILTIN_EXAMPLE_CATALOG); + const fallback = parseExampleCatalog(bundledCatalog); rejected.push(...fallback.rejected); return { catalog: fallback.catalog, source: "code", rejected }; } @@ -403,4 +343,3 @@ export function exampleById( return catalog.items.find((item) => item.id === id); } -export { readCatalogFile }; 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 index bff694331..86c6769ac 100644 --- a/src/canvas/workspace/example/useExampleImport.ts +++ b/src/canvas/workspace/example/useExampleImport.ts @@ -119,8 +119,8 @@ export function useExampleImport(deps: ExampleImportDeps) { }, []); const start = useCallback( - async (entry: ExampleEntry) => { - if (controllers.current.has(entry.id)) return; + async (entry: ExampleEntry): Promise => { + if (controllers.current.has(entry.id)) return false; const controller = new AbortController(); controllers.current.set(entry.id, controller); try { @@ -129,8 +129,10 @@ export function useExampleImport(deps: ExampleImportDeps) { 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); } diff --git a/src/i18n/messages/en-US/canvasWorkspace.ts b/src/i18n/messages/en-US/canvasWorkspace.ts index cb4561a90..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", @@ -452,4 +451,7 @@ export const canvasWorkspace = { // 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/canvasWorkspace.ts b/src/i18n/messages/zh-CN/canvasWorkspace.ts index f13b0246e..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": "正在打开画布…", @@ -407,4 +406,7 @@ export const canvasWorkspace = { // 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 index 83fa105c5..fcc57cef6 100644 --- a/tests/browser/example_canvas_picker.mjs +++ b/tests/browser/example_canvas_picker.mjs @@ -1,6 +1,7 @@ /** - * Isolated UI regression: the empty canvas offers the example picker, imports a - * wrapped `.canvas` download, and reports a blocked page instead of importing it. + * 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. @@ -51,7 +52,7 @@ const catalog = { schemaVersion: 1, items: [ { - id: "fixture-canvas", + id: "image-canvas", title: { "zh-CN": document.title, "en-US": "Fixture example canvas" }, url: sampleUrl, filename: `${document.title}.zip`, @@ -59,6 +60,14 @@ const catalog = { 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 = { @@ -90,45 +99,39 @@ try { page.on("pageerror", (error) => errors.push(error.message)); await page.route("**/example-canvases.json", (route) => route.fulfill({ json: catalog })); - await page.route(sampleUrl, (route) => - route.fulfill({ + // 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(); - await page.getByRole("button", { name: /体验示例画布/ }).click(); - await page.locator(".cw-example-dialog").waitFor(); }; - // 1. The picker lists the catalog entry with its measured size. + // 1. The empty-state button downloads, shows progress, imports and closes the bar. await openCanvas(); - const dialog = page.locator(".cw-example-dialog"); - await dialog.getByText(document.title, { exact: true }).waitFor(); - assert.match(await dialog.locator(".cw-example-item small").first().innerText(), /MB|KB/); + 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); - // 1b. The project menu reaches the same picker without returning to an empty canvas. - await dialog.getByRole("button", { name: "关闭", exact: true }).first().click(); + // 2. The project menu still reaches the full picker. await page.getByRole("button", { name: "切换项目", exact: true }).click(); await page.getByRole("menuitem", { name: /示例画布/ }).click(); - await page.locator(".cw-example-dialog").waitFor(); - await page - .locator(".cw-example-dialog") - .getByText(document.title, { exact: true }) - .waitFor(); - - // 2. Downloading the wrapped archive imports it and switches the canvas. - await dialog.getByRole("button", { name: "下载并导入" }).click(); - await dialog.getByText(/已导入/).waitFor(); - await page.waitForFunction(() => document.querySelectorAll(".react-flow__node").length === 2); - assert.equal(await page.locator(".react-flow__node").count(), 2); + 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, and nothing is imported. + // 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({ @@ -138,14 +141,9 @@ try { }), ); await openCanvas(); - await page.locator(".cw-example-dialog").getByRole("button", { name: "下载并导入" }).click(); + await page.getByRole("button", { name: "体验图片画布" }).click(); await page.getByText(/服务器返回的是网页/).waitFor(); assert.equal(await page.locator(".react-flow__node").count(), 0); - // The manual fallback stays available for a blocked link. - assert.equal( - await page.locator(".cw-example-manual").count(), - 1, - ); assert.deepEqual(errors, []); } finally { diff --git a/tests/exampleCatalog.test.ts b/tests/exampleCatalog.test.ts index a3c79de89..e899b00ea 100644 --- a/tests/exampleCatalog.test.ts +++ b/tests/exampleCatalog.test.ts @@ -151,34 +151,39 @@ test("the remote catalog wins when it is usable", async () => { ); }); -test("a broken remote catalog falls back to the bundled copy", async () => { +test("a malformed remote catalog falls back to the bundled copy", async () => { const result = await loadExampleCatalog({ remoteUrl: "https://example.test/catalog.json", - builtinUrl: "/example-canvases.json", fetchImpl: stubFetch({ "https://example.test/catalog.json": () => json({ schemaVersion: 99, items: [] }), - "/example-canvases.json": () => json(catalogWith([{ ...validItem, id: "bundled" }])), }), }); - assert.equal(result.source, "builtin"); + assert.equal(result.source, "code"); assert.deepEqual( result.catalog.items.map((item) => item.id), - ["bundled"], + ["image-canvas", "video-canvas"], ); }); -test("both files missing still leaves the compiled-in samples", async () => { +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"); }, - "/example-canvases.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, []); +});