The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Canvas: visitors open ready boards in the editor, keep drafts and save boards
Adarshade18d8e5c68
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 1beecc0e..289f61a5 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -83,8 +83,21 @@ An account is signed in, but it sees the owner's studio as a guest does:A Canvas Kinetic node renders in the owner's browser; keeping its run on the board(`PUT /api/canvases/<id>/runs/<node>`) is a canvas change like any other (403 `library` for an account, 401for a guest), and it takes only the owner's own finished Kinetic Motion results.- Canvas shows its ready boards to guests and accounts as read-only pages (`/canvas/start/<id>`):- what goes in, the steps and what comes out. Only the owner makes boards. Assist, Cinema Studio,+ **Canvas is open to build in.** Each ready board has its page (`/canvas/start/<id>`: what goes in, the+ steps and what comes out), and **Use this board** opens it in the Canvas editor (`/canvas/try/<id>`,+ or `/canvas/try/blank` for a blank one) with every node and link in place, its inputs holding+ Fuobe's published example files (by their public path, never a copy in anyone's storage) and its+ last step showing the board's own published film. A guest builds and changes boards there; the+ first change keeps the board in that browser only (`/canvas/draft/<id>`, localStorage, up to 20,+ nothing sent to the server), and **Save** offers a free account. An account saves its boards to its+ account (`/canvas/saved/<id>`; `GET`/`POST /api/account/canvases`, `GET`/`PATCH`/`DELETE+ /api/account/canvases/<id>`): its own boards only (another account's reads as 404, a guest gets+ 401), up to 50 boards of 1 MB each and 120 saves a minute, deleted with the account. Its inputs+ take its own uploads or Fuobe's published example files, nothing else. The owner's canvases+ (`/api/canvases`) stay the owner's (403 `library` for an account). **Run** on a visitor's board+ never runs: a canvas plans with the studio's own AI helpers, so it says what running needs and+ links the Video effect that makes the same film in one step (or the studios). On a phone the+ board shows read-only with its steps editable in Nodes. Assist, Cinema Studio,Storyboard, Elements, Faceless Studio, Content Factory, Explainer, Ads Studio, Click to Ad andMarketing Studio show their ready-made starters the same way (`<studio>/start/<id>`); making one(`POST /api/starters/<id>`) is the owner's, and an account gets 403 `library`. A starter without itsdiff --git a/src/app/(studio)/canvas/draft/[id]/page.tsx b/src/app/(studio)/canvas/draft/[id]/page.tsxnew file mode 100644index 00000000..3e28a7fe--- /dev/null+++ b/src/app/(studio)/canvas/draft/[id]/page.tsx@@ -0,0 +1,20 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { DraftBoard } from "@/components/canvas/visitor-canvas";+import { boardExtras } from "@/server/visitor-board";++export const metadata: Metadata = { title: "Canvas", robots: { index: false, follow: false } };++async function Board({ params }: { params: PageProps<"/canvas/draft/[id]">["params"] }) {+ const { id } = await params;+ return <DraftBoard id={id} boards={boardExtras()} />;+}++/** A board kept in this browser (a visitor's draft): its pages are read from the browser, never the server. */+export default function Page({ params }: PageProps<"/canvas/draft/[id]">) {+ return (+ <Suspense fallback={null}>+ <Board params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/canvas/saved/[id]/page.tsx b/src/app/(studio)/canvas/saved/[id]/page.tsxnew file mode 100644index 00000000..f688747e--- /dev/null+++ b/src/app/(studio)/canvas/saved/[id]/page.tsx@@ -0,0 +1,20 @@+import type { Metadata } from "next";+import { Suspense } from "react";+import { SavedBoard } from "@/components/canvas/visitor-canvas";+import { boardExtras } from "@/server/visitor-board";++export const metadata: Metadata = { title: "Canvas", robots: { index: false, follow: false } };++async function Board({ params }: { params: PageProps<"/canvas/saved/[id]">["params"] }) {+ const { id } = await params;+ return <SavedBoard id={id} boards={boardExtras()} />;+}++/** An account's own canvas: the browser asks /api/account/canvases/<id>, which answers that account only. */+export default function Page({ params }: PageProps<"/canvas/saved/[id]">) {+ return (+ <Suspense fallback={null}>+ <Board params={params} />+ </Suspense>+ );+}diff --git a/src/app/(studio)/canvas/try/[id]/page.tsx b/src/app/(studio)/canvas/try/[id]/page.tsxnew file mode 100644index 00000000..27eb6939--- /dev/null+++ b/src/app/(studio)/canvas/try/[id]/page.tsx@@ -0,0 +1,32 @@+import type { Metadata } from "next";+import { notFound } from "next/navigation";+import { Suspense } from "react";+import { TryBoard } from "@/components/canvas/visitor-canvas";+import { visitorBoard, visitorBoardIds } from "@/server/visitor-board";++export function generateStaticParams() {+ return visitorBoardIds().map((id) => ({ id }));+}++export async function generateMetadata({ params }: PageProps<"/canvas/try/[id]">): Promise<Metadata> {+ const { id } = await params;+ const b = visitorBoard(id);+ // A board in the editor is a working page, not one to find in search (its template page is).+ return { title: b ? `${b.name} · Canvas` : "Not found", robots: { index: false, follow: true } };+}++async function Board({ params }: { params: PageProps<"/canvas/try/[id]">["params"] }) {+ const { id } = await params;+ const b = visitorBoard(id);+ if (!b) notFound();+ return <TryBoard board={{ id: `try-${id}`, ...b }} />;+}++/** A ready board (or a blank one) open in the Canvas editor, for anyone: see src/components/canvas/visitor-canvas.tsx. */+export default function Page({ params }: PageProps<"/canvas/try/[id]">) {+ return (+ <Suspense fallback={null}>+ <Board params={params} />+ </Suspense>+ );+}diff --git a/src/app/api/account/canvases/[id]/route.ts b/src/app/api/account/canvases/[id]/route.tsnew file mode 100644index 00000000..ea48de02--- /dev/null+++ b/src/app/api/account/canvases/[id]/route.ts@@ -0,0 +1,48 @@+import { connection } from "next/server";+import { z } from "zod";+import { deleteAccountCanvas, getAccountCanvas, updateAccountCanvas } from "@/server/account-canvas";+import { parseVisitorPages } from "@/server/canvas";+import { accountOf, badPages, notAccount, refused, tooMany } from "@/server/account-canvas-http";++const NOT_FOUND = { error: "This canvas isn't here" };++const Patch = z.object({+ name: z.string().trim().min(1).max(200).optional(),+ pages: z.unknown().optional(),+});++/** One of the account's own boards (another account's reads as not found). */+export async function GET(request: Request, ctx: RouteContext<"/api/account/canvases/[id]">) {+ await connection();+ const a = accountOf(request);+ if (!a) return notAccount();+ const { id } = await ctx.params;+ const c = getAccountCanvas(a.id, id);+ return c ? Response.json(c) : Response.json(NOT_FOUND, { status: 404 });+}++/** Rename and/or save the pages (the editor's autosave). */+export async function PATCH(request: Request, ctx: RouteContext<"/api/account/canvases/[id]">) {+ const a = accountOf(request);+ if (!a) return notAccount();+ const limited = tooMany(a.id);+ if (limited) return limited;+ const { id } = await ctx.params;+ const parsed = Patch.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "Give the canvas a name" }, { status: 400 });+ const pages = parsed.data.pages === undefined ? undefined : parseVisitorPages(parsed.data.pages);+ if (pages === null) return badPages(parsed.data.pages);+ try {+ const c = updateAccountCanvas(a.id, id, { name: parsed.data.name, pages });+ return c ? Response.json(c) : Response.json(NOT_FOUND, { status: 404 });+ } catch (e) {+ return refused(e);+ }+}++export async function DELETE(request: Request, ctx: RouteContext<"/api/account/canvases/[id]">) {+ const a = accountOf(request);+ if (!a) return notAccount();+ const { id } = await ctx.params;+ return deleteAccountCanvas(a.id, id) ? new Response(null, { status: 204 }) : Response.json(NOT_FOUND, { status: 404 });+}diff --git a/src/app/api/account/canvases/route.ts b/src/app/api/account/canvases/route.tsnew file mode 100644index 00000000..5bfa5823--- /dev/null+++ b/src/app/api/account/canvases/route.ts@@ -0,0 +1,36 @@+import { connection } from "next/server";+import { z } from "zod";+import { createAccountCanvas, listAccountCanvases } from "@/server/account-canvas";+import { parseVisitorPages } from "@/server/canvas";+import { accountOf, badPages, notAccount, refused, tooMany } from "@/server/account-canvas-http";++const Body = z.object({+ name: z.string().max(200).optional(),+ templateId: z.string().max(60).nullish(),+ pages: z.unknown(),+});++/** The account's own canvases, newest first. */+export async function GET(request: Request) {+ await connection();+ const a = accountOf(request);+ if (!a) return notAccount();+ return Response.json({ items: listAccountCanvases(a.id) });+}++/** Save a board (a draft from this browser, a ready board, or a blank one) to the account. */+export async function POST(request: Request) {+ const a = accountOf(request);+ if (!a) return notAccount();+ const limited = tooMany(a.id);+ if (limited) return limited;+ const parsed = Body.safeParse(await request.json().catch(() => null));+ if (!parsed.success) return Response.json({ error: "That board couldn't be read" }, { status: 400 });+ const pages = parsed.data.pages === undefined ? undefined : parseVisitorPages(parsed.data.pages);+ if (pages === null) return badPages(parsed.data.pages);+ try {+ return Response.json(createAccountCanvas(a.id, { name: parsed.data.name, templateId: parsed.data.templateId, pages }), { status: 201 });+ } catch (e) {+ return refused(e);+ }+}diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsxindex 67cf71c5..4b77c058 100644--- a/src/components/canvas/canvas-editor.tsx+++ b/src/components/canvas/canvas-editor.tsx@@ -194,8 +194,44 @@ function framed(g: FlowNode, nodes: FlowNode[]): FlowNode[] {// ---------------------------------------------------------------------------+/**+ * Where a board is kept and what its Run does. The owner's canvases save to the studio (/api/canvases) and run there;+ * a visitor's board (src/components/canvas/visitor-canvas.tsx) saves in this browser or to its account, and its Run+ * explains what running needs instead (`visitor`).+ */+export interface BoardHost {+ /** Saves every page (the autosave); `keepalive` while leaving the page. */+ save: (pages: CanvasPage[], keepalive: boolean) => Promise<void>;+ rename: (name: string) => Promise<void>;+ visitor?: VisitorHost;+}++export interface VisitorHost {+ /** Where the board is kept, said where the owner's editor says "Saved" ("Saved in this browser"). */+ savedLabel: string;+ /** Run, Run selected and ⌘↵: what running a board needs, said plainly (it never runs). */+ run: () => void;+ /** Beside Run: Save to your account, or Sign up to save; `now` gives the board as it is on screen. */+ action?: (now: () => BoardNow) => React.ReactNode;+ /** A note under the header (on a phone: build on a larger screen). */+ note?: React.ReactNode;+}++/** The board as it is on screen: every page and its name. */+export interface BoardNow {+ pages: CanvasPage[];+ name: string;+}+export function CanvasEditor({ id }: { id: string }) {const view = useCanvasView(id);+ const host = useMemo<BoardHost>(+ () => ({+ save: async (pages, keepalive) => void (await saveCanvas(id, { pages }, keepalive)),+ rename: async (name) => void (await saveCanvas(id, { name })),+ }),+ [id],+ );if (view.isLoading) return <EditorSkeleton />;if (!view.data) {// A canvas that isn't there gets the shared 404 state; a request that failed otherwise can be retried.@@ -204,12 +240,21 @@ export function CanvasEditor({ id }: { id: string }) {}return (<ReactFlowProvider>- <Editor key={id} id={id} initial={view.data.canvas} view={view.data} />+ <Editor key={id} id={id} initial={view.data.canvas} view={view.data} host={host} /></ReactFlowProvider>);}-function EditorSkeleton() {+/** A visitor's board in the same editor: `initial` from this browser, the account or a ready board; `host` keeps it. */+export function BoardEditor({ id, initial, view, host }: { id: string; initial: Canvas; view: CanvasView; host: BoardHost }) {+ return (+ <ReactFlowProvider>+ <Editor key={id} id={id} initial={initial} view={view} host={host} />+ </ReactFlowProvider>+ );+}++export function EditorSkeleton() {return (<div className="flex h-content flex-col"><div className="flex h-14 items-center gap-3 border-b px-3 sm:px-4">@@ -233,8 +278,14 @@ interface MenuState {connect?: { nodeId: string; handleId: string | null; from: "source" | "target"; type: PortType };}-function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvasView }) {+function Editor({ id, initial, view, host }: { id: string; initial: Canvas; view: CanvasView; host: BoardHost }) {const qc = useQueryClient();+ // The host's latest functions, for the autosave and the handlers (a new host object never re-arms them).+ const hostNow = useRef(host);+ useLayoutEffect(() => {+ hostNow.current = host;+ }, [host]);+ const visitor = host.visitor;const rf = useReactFlow<FlowNode, Edge>();const { resolvedTheme } = useTheme();const isMobile = useIsMobile();@@ -392,7 +443,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvif (at === savedRev.current) return;setSaveState("saving");try {- await saveCanvas(id, { pages: docOf() }, keepalive);+ await hostNow.current.save(docOf(), keepalive);savedRev.current = Math.max(savedRev.current, at);setSaveState("saved");setSaveRefused(false);@@ -444,13 +495,14 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvconst at = latest.current.rev;if (at === savedRev.current) return;savedRev.current = at;- void saveCanvas(id, { pages: docOf() }, true)+ void hostNow.current+ .save(docOf(), true).then(() => qc.invalidateQueries({ queryKey: ["canvases"], exact: true })).catch(() => {// Not saved after all: the next edit (or the next visit) saves again.savedRev.current = -1;});- }, [id, qc, docOf]);+ }, [qc, docOf]);useEffect(() => flushOnLeave, [flushOnLeave]);const rename = async (next: string) => {@@ -458,7 +510,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvif (!v) return setName(savedName.current);if (v === savedName.current) return;try {- await saveCanvas(id, { name: v });+ await hostNow.current.rename(v);savedName.current = v;void qc.invalidateQueries({ queryKey: ["canvases"], exact: true });} catch (e) {@@ -725,6 +777,8 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canv// ---- running (the page on the board)const run = useCallback((targets?: string[], force?: boolean, group?: string) => {+ // A visitor's board never runs here: its Run says what running needs.+ if (hostNow.current.visitor) return hostNow.current.visitor.run();const go = (t?: string[], f?: boolean) => {const at = latest.current.rev;runMutate(@@ -1250,9 +1304,10 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: Canvrename: typeof rename;addAtCenter: typeof addAtCenter;saveAsSkill: typeof saveAsSkill;+ snapshot: () => BoardNow;} | null>(null);useLayoutEffect(() => {- uiHandlers.current = { run, runSelection, switchEngine, rename, addAtCenter, saveAsSkill };+ uiHandlers.current = { run, runSelection, switchEngine, rename, addAtCenter, saveAsSkill, snapshot: () => ({ pages: docOf(), name: name.trim() || savedName.current }) };});const ui = useMemo<HeaderUi>(() => ({@@ -1262,6 +1317,7 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvswitchEngine: (e) => uiHandlers.current!.switchEngine(e),rename: (v) => void uiHandlers.current!.rename(v),addAtCenter: (p) => uiHandlers.current!.addAtCenter(p),+ snapshot: () => uiHandlers.current!.snapshot(),}),[],);@@ -1287,7 +1343,9 @@ function Editor({ id, initial, view }: { id: string; initial: Canvas; view: CanvcanRun={generators.length > 0 || graph.nodes.some((n) => n.type === "kinetic")}mode={mode}ui={ui}+ visitor={visitor}/>+ {visitor?.note}{isMobile && (<div className="flex shrink-0 items-center gap-2 border-b px-4 py-2">@@ -1501,6 +1559,7 @@ interface HeaderUi {switchEngine: (e: Engine) => void;rename: (name: string) => void;addAtCenter: (p: PaletteItem) => void;+ snapshot: () => BoardNow;}const EditorHeader = memo(function EditorHeader({@@ -1516,6 +1575,7 @@ const EditorHeader = memo(function EditorHeader({canRun,mode,ui,+ visitor,}: {name: string;setName: (v: string) => void;@@ -1529,8 +1589,10 @@ const EditorHeader = memo(function EditorHeader({canRun: boolean;mode: EngineMode;ui: HeaderUi;+ visitor?: VisitorHost;}) {const mod = useModKey();+ const savedText = visitor?.savedLabel ?? "Saved";return (<header className="z-20 flex h-14 shrink-0 items-center gap-2 border-b bg-background px-2 sm:px-4"><Tooltip>@@ -1552,7 +1614,7 @@ const EditorHeader = memo(function EditorHeader({/><span className={cn("shrink-0 items-center gap-1 text-[12px] text-muted-foreground", saveState === "error" ? "inline-flex" : "hidden sm:inline-flex")} aria-live="polite">{saveState === "saving" ? <Loader2 className="size-3 animate-spin" /> : saveState === "error" ? <TriangleAlert className="size-3 text-warning" /> : <Check className="size-3" />}- <span className={cn(saveState === "error" && "max-sm:sr-only")}>{saveState === "saving" ? "Saving…" : saveState === "error" ? (saveRefused ? "Not saved" : "Not saved — retrying") : "Saved"}</span>+ <span className={cn(saveState === "error" && "max-sm:sr-only")}>{saveState === "saving" ? "Saving…" : saveState === "error" ? (saveRefused ? "Not saved" : "Not saved — retrying") : savedText}</span></span><div className="ml-auto flex shrink-0 items-center gap-2">{busy > 0 && (@@ -1564,6 +1626,20 @@ const EditorHeader = memo(function EditorHeader({<div className="hidden md:block"><EngineSwitch value={boardEngine} onChange={ui.switchEngine} size="sm" /></div>+ {visitor ? (+ <>+ {visitor.action?.(ui.snapshot)}+ <Tooltip>+ <TooltipTrigger asChild>+ <Button size="sm" variant="secondary" className="h-8 rounded-full px-3" onClick={() => ui.run()} disabled={!canRun} data-visitor-run>+ <Play /> Run+ </Button>+ </TooltipTrigger>+ <TooltipContent>What running a board needs</TooltipContent>+ </Tooltip>+ </>+ ) : (+ <>{selectedCount > 0 && (<Button variant="secondary" size="sm" className="h-8 rounded-full px-3" onClick={() => ui.runSelected()} disabled={running}><Play /> Run selected <span className="font-mono text-muted-foreground">{selectedCount}</span>@@ -1619,6 +1695,8 @@ const EditorHeader = memo(function EditorHeader({</DropdownMenuContent></DropdownMenu></div>+ </>+ )}</div><PhoneNavButton /></header>diff --git a/src/components/canvas/canvas-list.tsx b/src/components/canvas/canvas-list.tsxindex 9b724e02..f97e9198 100644--- a/src/components/canvas/canvas-list.tsx+++ b/src/components/canvas/canvas-list.tsx@@ -14,7 +14,7 @@ import { Skeleton } from "@/components/ui/skeleton";import { EngineSwitch } from "@/components/studio/engine-switch";import { PageShell } from "@/components/page-shell";import { CoverArt, CoverImg, useCoverPlayback } from "@/components/template-cover";-import { useEngine, useHydrated, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { useEngine, useHydrated, useIsAccount, useIsOwner, useLikelyVisitor, useModelAccess } from "@/lib/api";// Types only: the catalog (models, templates) stays on the server; the page passes slim template cards.import type { CanvasSummary } from "@/lib/catalog/canvas";import { firstTemplates, moreTemplates, templateSections, type CanvasIntro, type TemplateCardData, type Viewing } from "@/lib/canvas-sections";@@ -25,6 +25,7 @@ import { toastError } from "@/lib/refusals";import { SkillCanvases } from "./skill-canvases";import { Schematic, TemplateCard } from "./template-card";import { useCanvasActions, useCanvases } from "./use-canvas";+import { VisitorBoards } from "./visitor-boards";export type { TemplateCardData } from "@/lib/canvas-sections";@@ -164,9 +165,11 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?const params = useSearchParams();const askedTemplates = params.get("tab") === "templates";const askedSkills = params.get("tab") === "skills";- // A canvas is saved to the studio's library, which is its owner's: a guest or an account can look, not start one.+ // The owner's canvases are the studio's. A guest or an account opens ready boards (and blank ones) in the same editor:+ // a guest keeps them in this browser, an account saves them to its account (visitor-canvas.tsx).// Until the viewer is known to be the owner, the page is a visitor's: only ready boards with their real cover show.const owner = useIsOwner();+ const account = useIsAccount();// In a browser the owner used last, their boards are on the way: a skeleton until they come, not the visitor's page.const likelyOwner = !useLikelyVisitor();const hydrated = useHydrated();@@ -213,7 +216,7 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?};const card = (t: TemplateCardData) => (- <TemplateCard key={t.id} t={t} engine={engine} access={access} owner={owner} busy={creating === t.id} onUse={owner ? () => void start(t.id, { templateId: t.id, engine }) : undefined} />+ <TemplateCard key={t.id} t={t} engine={engine} access={access} owner={owner} busy={creating === t.id} onUse={owner ? () => void start(t.id, { templateId: t.id, engine }) : undefined} tryHref={owner ? undefined : `/canvas/try/${t.id}`} />);const sections = templateSections(templates, viewing);const more = moreTemplates(templates, viewing);@@ -277,7 +280,13 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?<Button className="w-fit rounded-full" onClick={() => void start("new", {})} disabled={!!creating}>{creating === "new" ? <Loader2 className="animate-spin" /> : <Plus />} New canvas</Button>- ) : null}+ ) : (+ <Button asChild className="w-fit rounded-full">+ <Link href="/canvas/try/blank">+ <Plus /> New canvas+ </Link>+ </Button>+ )}</div>{loadingMine ? (@@ -331,11 +340,12 @@ function ListInner({ templates, intro }: { templates: TemplateCardData[]; intro?{/* Before hydration, a browser the owner used last shows the skeleton (html[data-viewer]), not the visitor's page. */}{!hydrated && <MineSkeleton className="hidden [html[data-viewer='owner']_&]:grid" />}<div className={cn(!hydrated && "[html[data-viewer='owner']_&]:hidden")}>+ {hydrated && !owner && <VisitorBoards account={account} />}<WhatsACanvas intro={intro} /><section id="templates" ref={gallery} aria-labelledby="templates-title" className="mt-8 scroll-mt-20">{galleryHeading("Start from a ready board",- owner ? "Every step, word and file is already in place. Press Run all, or change anything first." : "See how each one is built, then make it in Video with your own photo.",+ owner ? "Every step, word and file is already in place. Press Run all, or change anything first." : "Every step, word and photo is already in place. Open one in the editor and change anything.",)}{fullGallery}</section>diff --git a/src/components/canvas/template-card.tsx b/src/components/canvas/template-card.tsxindex 2a7c1413..eab31011 100644--- a/src/components/canvas/template-card.tsx+++ b/src/components/canvas/template-card.tsx@@ -1,6 +1,7 @@"use client";import { ArrowRight, ChevronRight, Cloud, Cpu, Loader2, Plus, Workflow } from "lucide-react";+import Link from "next/link";import { Fragment } from "react";import { Button } from "@/components/ui/button";import { StarterCard } from "@/components/starters/starter-card";@@ -131,7 +132,24 @@ export function ModelLine({ t, engine, access, className }: { t: TemplateCardDat* A Canvas template as a starter card. Everyone opens its page from the card; the owner makes the board from it in* one tap (onUse) and sees what it runs on, and "No cover yet" on a card that visitors don't get to see.*/-export function TemplateCard({ t, engine, onUse, busy, access, owner = false }: { t: TemplateCardData; engine: Engine; onUse?: () => void; busy: boolean; access?: AccessSummary; owner?: boolean }) {+export function TemplateCard({+ t,+ engine,+ onUse,+ busy,+ access,+ owner = false,+ tryHref,+}: {+ t: TemplateCardData;+ engine: Engine;+ onUse?: () => void;+ busy: boolean;+ access?: AccessSummary;+ owner?: boolean;+ /** A visitor's "Use this board": the board open in the editor. */+ tryHref?: string;+}) {const cover = templateCover("canvas", t.id);return (<StarterCard@@ -151,6 +169,12 @@ export function TemplateCard({ t, engine, onUse, busy, access, owner = false }:<Button size="sm" className="w-fit rounded-full" onClick={onUse} disabled={busy}>{busy ? <Loader2 className="animate-spin" /> : <Plus />} Use template</Button>+ ) : tryHref ? (+ <Button asChild size="sm" className="w-fit rounded-full">+ <Link href={tryHref} data-use-board>+ <Workflow /> Use this board+ </Link>+ </Button>) : (<span className="inline-flex items-center gap-1 text-[13px] font-medium text-foreground">See how it works <ArrowRight className="size-3.5 transition-transform group-hover/starter:translate-x-0.5" />diff --git a/src/components/canvas/template-page.tsx b/src/components/canvas/template-page.tsxindex 1dcdc1ca..e3c3dad8 100644--- a/src/components/canvas/template-page.tsx+++ b/src/components/canvas/template-page.tsx@@ -1,12 +1,11 @@"use client";-import { ArrowLeft, ArrowRight, Loader2, Plus } from "lucide-react";+import { ArrowLeft, ArrowRight, Loader2, Plus, Workflow } from "lucide-react";import Link from "next/link";import { useRouter } from "next/navigation";import { useState } from "react";import { Button } from "@/components/ui/button";import { PageShell } from "@/components/page-shell";-import { SelfHostNote } from "@/components/self-host-note";import { EngineSwitch } from "@/components/studio/engine-switch";import { CoverArt, CoverImg, useCoverPlayback } from "@/components/template-cover";import { useEngine, useIsOwner, useIsVisitor, useModelAccess } from "@/lib/api";@@ -64,8 +63,8 @@ function Input({ input }: { input: TemplateInput }) {/*** A Canvas template's page (/canvas/start/<id>): what it makes, what goes in, the steps and what comes out, for- * everyone. The owner makes the board from here; a guest or an account (who can't save a board here) gets, for an- * effect film, the Video effect that makes the same in one step with its example loaded, else the studios they can use.+ * everyone. The owner makes the board from here; a guest or an account opens it in the editor ("Use this board",+ * /canvas/try/<id>), and for an effect film also gets the Video effect that makes the same in one step.*/export function TemplatePage({ t }: { t: TemplateDetail }) {const router = useRouter();@@ -159,21 +158,28 @@ export function TemplatePage({ t }: { t: TemplateDetail }) {<EngineSwitch value={engine} onChange={setEngine} size="sm" /></>) : (- t.oneStep && (+ <><Button asChild className="rounded-full">- <Link href={t.oneStep.href}>- {t.oneStep.label} <ArrowRight />+ <Link href={`/canvas/try/${t.id}`} data-use-board>+ <Workflow /> Use this board</Link></Button>- )+ {t.oneStep && (+ <Button asChild variant="secondary" className="rounded-full">+ <Link href={t.oneStep.href}>+ {t.oneStep.label} <ArrowRight />+ </Link>+ </Button>+ )}+ </>)}</div>- {!owner &&- (t.oneStep ? (- <p className="mt-2 text-[13px] text-pretty text-muted-foreground [html[data-viewer='owner']_&]:hidden">One tap opens it with a photo ready. Change anything, then make your own.</p>- ) : (- <SelfHostNote className="mt-2" />- ))}+ {!owner && (+ <p className="mt-2 text-[13px] text-pretty text-muted-foreground [html[data-viewer='owner']_&]:hidden">+ Opens the board in the editor with every step and photo in place. Change anything and keep it.+ {t.oneStep && " The effect in Video makes the same film in one step."}+ </p>+ )}<section aria-labelledby="goes-in" className="mt-8"><h2 id="goes-in" className={heading}>diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.tsindex 60bbede2..5bf822cc 100644--- a/src/components/canvas/use-canvas.ts+++ b/src/components/canvas/use-canvas.ts@@ -128,3 +128,47 @@ export function useRunCanvas(id: string) {},});}++// ---------------------------------------------------------------------------+// An account's own canvases (/api/account/canvases): boards it keeps, never the owner's.++/** An account's board as the editor opens it. */+export interface AccountCanvas {+ id: string;+ name: string;+ pages: CanvasPage[];+ templateId: string | null;+ createdAt: number;+ updatedAt: number;+}++/** The account's own canvases; `enabled: false` (a guest, or the owner) asks for nothing. */+export function useAccountCanvases({ enabled }: { enabled: boolean }) {+ return useQuery({+ queryKey: ["account-canvases"],+ enabled,+ queryFn: async () => (await json<{ items: CanvasSummary[] }>(await fetch("/api/account/canvases"))).items,+ });+}++export function useAccountCanvas(id: string, { enabled }: { enabled: boolean }) {+ return useQuery({+ queryKey: ["account-canvases", id],+ enabled,+ retry: false,+ // The editor owns the board once loaded.+ refetchOnWindowFocus: false,+ staleTime: Infinity,+ queryFn: async () => json<AccountCanvas>(await fetch(`/api/account/canvases/${encodeURIComponent(id)}`)),+ });+}++export const accountCanvasApi = {+ create: async (body: { name: string; templateId: string | null; pages: CanvasPage[] }) => json<AccountCanvas>(await send("/api/account/canvases", "POST", body)),+ save: async (id: string, patch: { name?: string; pages?: CanvasPage[] }, keepalive = false) =>+ json<AccountCanvas>(await send(`/api/account/canvases/${encodeURIComponent(id)}`, "PATCH", patch, { keepalive })),+ remove: async (id: string) => {+ const res = await fetch(`/api/account/canvases/${encodeURIComponent(id)}`, { method: "DELETE" });+ if (!res.ok && res.status !== 404) throw responseError(res, "Couldn't delete it. Please try again.");+ },+};diff --git a/src/components/canvas/visitor-boards.tsx b/src/components/canvas/visitor-boards.tsxnew file mode 100644index 00000000..a7f4471a--- /dev/null+++ b/src/components/canvas/visitor-boards.tsx@@ -0,0 +1,210 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { Cloud, HardDrive, MoreHorizontal, Pencil, Plus, Trash2, Workflow } from "lucide-react";+import Link from "next/link";+import { useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from "@/components/ui/alert-dialog";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { Input } from "@/components/ui/input";+import { Skeleton } from "@/components/ui/skeleton";+import type { CanvasSummary } from "@/lib/catalog/canvas";+import { deleteDraft, DRAFT_EVENT, getDraft, listDrafts, putDraft, type DraftSummary } from "@/lib/canvas-drafts";+import { timeAgo } from "@/lib/format";+import { toastError } from "@/lib/refusals";+import { Schematic } from "./template-card";+import { accountCanvasApi, useAccountCanvases } from "./use-canvas";++/** A visitor's board in the list: saved to its account, or kept in this browser. */+type Board = { where: "account"; c: CanvasSummary } | { where: "browser"; d: DraftSummary };++const idOf = (b: Board) => (b.where === "account" ? b.c.id : b.d.id);+const nameOf = (b: Board) => (b.where === "account" ? b.c.name : b.d.name);++function subscribe(onChange: () => void) {+ window.addEventListener(DRAFT_EVENT, onChange);+ window.addEventListener("storage", onChange);+ return () => {+ window.removeEventListener(DRAFT_EVENT, onChange);+ window.removeEventListener("storage", onChange);+ };+}+let cached: { key: string; list: DraftSummary[] } = { key: "[]", list: [] };+/** This browser's drafts, the same array while nothing changed (useSyncExternalStore). */+function draftsSnapshot(): DraftSummary[] {+ const list = listDrafts();+ const key = JSON.stringify(list);+ if (key !== cached.key) cached = { key, list };+ return cached.list;+}+const NONE: DraftSummary[] = [];++function BoardCard({ b, onRename, onDelete }: { b: Board; onRename: () => void; onDelete: () => void }) {+ const href = b.where === "account" ? `/canvas/saved/${b.c.id}` : `/canvas/draft/${b.d.id}`;+ const nodes = b.where === "account" ? b.c.nodeCount : b.d.nodeCount;+ const when = b.where === "account" ? b.c.updatedAt : b.d.updatedAt;+ return (+ <article className="group/card relative min-w-0" data-visitor-board={b.where}>+ <Link href={href} className="block rounded-xl outline-none focus-visible:ring-4 focus-visible:ring-brand-faint">+ <div className="aspect-[16/10] overflow-hidden rounded-xl border bg-muted/50 transition-shadow group-hover/card:shadow-normal">+ {b.where === "account" ? (+ <Schematic outline={b.c.outline} className="p-3" />+ ) : (+ <div className="grid size-full place-items-center text-subtle-foreground">+ <Workflow className="size-8" />+ </div>+ )}+ </div>+ <h3 className="mt-2 truncate pr-9 text-[14px] font-medium">{nameOf(b)}</h3>+ <p className="flex items-center gap-1 text-[12px] text-muted-foreground">+ {b.where === "account" ? <Cloud className="size-3" aria-hidden /> : <HardDrive className="size-3" aria-hidden />}+ {b.where === "account" ? "Saved" : "In this browser"} · Edited {timeAgo(when)} · {nodes} node{nodes === 1 ? "" : "s"}+ </p>+ </Link>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <button+ className="absolute right-0 bottom-5 grid size-8 place-items-center rounded-md text-muted-foreground opacity-100 hover:bg-accent hover:text-foreground focus-visible:opacity-100 sm:opacity-0 sm:group-hover/card:opacity-100 data-[state=open]:opacity-100"+ aria-label={`Actions for ${nameOf(b)}`}+ >+ <MoreHorizontal className="size-4" />+ </button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end" className="w-44">+ <DropdownMenuItem onSelect={onRename}>+ <Pencil /> Rename+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem variant="destructive" onSelect={onDelete}>+ <Trash2 /> Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </article>+ );+}++/**+ * "Your canvases" for a guest or an account: the boards it saved to its account and the ones kept in this browser,+ * each opening in the editor, with Rename and Delete; and "Start blank". Nothing shows while it has none.+ */+export function VisitorBoards({ account }: { account: boolean }) {+ const qc = useQueryClient();+ const drafts = useSyncExternalStore(subscribe, draftsSnapshot, () => NONE);+ const saved = useAccountCanvases({ enabled: account });+ const [renaming, setRenaming] = useState<Board | null>(null);+ const [draft, setDraft] = useState("");+ const [deleting, setDeleting] = useState<Board | null>(null);+ const boards: Board[] = [...(saved.data ?? []).map((c) => ({ where: "account" as const, c })), ...drafts.map((d) => ({ where: "browser" as const, d }))];+ const refresh = () => void qc.invalidateQueries({ queryKey: ["account-canvases"], exact: true });++ const rename = async (b: Board, name: string) => {+ if (b.where === "account") {+ await accountCanvasApi.save(b.c.id, { name });+ refresh();+ } else {+ const d = getDraft(b.d.id);+ if (d) putDraft({ ...d, name, updatedAt: Date.now() });+ }+ };+ const remove = async (b: Board) => {+ if (b.where === "account") {+ qc.setQueryData<CanvasSummary[]>(["account-canvases"], (old) => old?.filter((c) => c.id !== b.c.id));+ await accountCanvasApi.remove(b.c.id);+ qc.removeQueries({ queryKey: ["account-canvases", b.c.id] });+ refresh();+ } else deleteDraft(b.d.id);+ };++ if (account && saved.isPending && !drafts.length)+ return (+ <div className="mt-6 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {Array.from({ length: 2 }, (_, i) => (+ <Skeleton key={i} className="aspect-[16/10] rounded-xl" />+ ))}+ </div>+ );+ if (!boards.length) return null;+ return (+ <section aria-labelledby="your-canvases" className="mt-6">+ <div className="flex flex-wrap items-center gap-3">+ <h2 id="your-canvases" className="font-heading text-[22px] leading-tight">+ Your canvases+ </h2>+ {!account && <p className="text-[13px] text-muted-foreground">Kept in this browser. Create a free account to keep them anywhere.</p>}+ </div>+ <div className="mt-4 grid grid-cols-1 gap-x-4 gap-y-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4">+ {boards.map((b) => (+ <BoardCard+ key={`${b.where}-${idOf(b)}`}+ b={b}+ onRename={() => {+ setDraft(nameOf(b));+ setRenaming(b);+ }}+ onDelete={() => setDeleting(b)}+ />+ ))}+ <Link+ href="/canvas/try/blank"+ className="flex aspect-[16/10] flex-col items-center justify-center gap-2 rounded-xl border border-dashed text-[14px] font-medium text-muted-foreground transition-colors hover:border-border-strong hover:text-foreground"+ >+ <Plus className="size-5" /> Start blank+ </Link>+ </div>++ <Dialog open={!!renaming} onOpenChange={(o) => !o && setRenaming(null)}>+ <DialogContent className="sm:max-w-sm">+ <DialogHeader>+ <DialogTitle>Rename canvas</DialogTitle>+ <DialogDescription className="sr-only">Give this canvas a new name</DialogDescription>+ </DialogHeader>+ <form+ onSubmit={(e) => {+ e.preventDefault();+ const b = renaming!;+ const name = draft.trim();+ setRenaming(null);+ if (name && name !== nameOf(b)) void rename(b, name).then(() => toast.success("Renamed", { duration: 1500 }), (err) => toastError(err));+ }}+ >+ <Input autoFocus value={draft} maxLength={80} onChange={(e) => setDraft(e.target.value)} aria-label="Name" />+ <DialogFooter className="mt-4">+ <Button type="button" variant="ghost" onClick={() => setRenaming(null)}>+ Cancel+ </Button>+ <Button type="submit" disabled={!draft.trim()}>+ Save+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>++ <AlertDialog open={!!deleting} onOpenChange={(o) => !o && setDeleting(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete “{deleting ? nameOf(deleting) : ""}”?</AlertDialogTitle>+ <AlertDialogDescription>The board is removed for good.</AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ const b = deleting!;+ setDeleting(null);+ void remove(b).then(() => toast("Deleted", { duration: 1500 }), (e) => toastError(e));+ }}+ >+ Delete+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ </section>+ );+}diff --git a/src/components/canvas/visitor-canvas.tsx b/src/components/canvas/visitor-canvas.tsxnew file mode 100644index 00000000..983544a8--- /dev/null+++ b/src/components/canvas/visitor-canvas.tsx@@ -0,0 +1,412 @@+"use client";++import { useQueryClient } from "@tanstack/react-query";+import { ArrowRight, Cloud, Loader2, LogIn, Monitor, UserPlus } from "lucide-react";+import Link from "next/link";+import { usePathname, useRouter } from "next/navigation";+import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from "react";+import { toast } from "sonner";+import { NotFoundState } from "@/components/empty-state";+import { Button } from "@/components/ui/button";+import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { useIsMobile } from "@/hooks/use-mobile";+import { signInHref, useEngine, useHydrated, useViewer } from "@/lib/api";+import type { Canvas } from "@/lib/catalog/canvas";+import type { CanvasPage } from "@/lib/catalog/canvas-board";+import type { Generation } from "@/lib/catalog/types";+import { deleteDraft, getDraft, newDraftId, putDraft, type CanvasDraft } from "@/lib/canvas-drafts";+import { toastError } from "@/lib/refusals";+import { BoardEditor, EditorSkeleton, type BoardHost, type BoardNow } from "./canvas-editor";+import { accountCanvasApi, useAccountCanvas, useCanvasActions, type CanvasView } from "./use-canvas";++/**+ * A visitor's canvas (public sign-up): the owner's editor on a board a guest or an account builds. A ready board or a+ * blank one opens at /canvas/try/<id>; the first change keeps it in this browser (/canvas/draft/<id>); an account+ * saves it to its account (/canvas/saved/<id>), where every change saves. Run never runs here: it says what running+ * a board needs (an account's own GPU doesn't run a canvas yet, and a guest never runs on the studio's), with the+ * Video effect that makes the same in one step where the board has one.+ */++/** A ready board as the server builds it for a visitor (src/server/visitor-board.ts), sent with its page. */+export interface VisitorBoardData {+ id: string;+ name: string;+ templateId: string | null;+ pages: CanvasPage[];+ example?: { nodeId: string; kind: "image" | "video"; url: string; poster: string };+ oneStep?: { href: string; label: string };+}++type Who = "guest" | "account" | "owner";++/** Who is looking, once known (null before hydration and the viewer's answer). */+function useWho(): Who | null {+ const hydrated = useHydrated();+ const v = useViewer().data;+ if (!hydrated || !v) return null;+ return v.owner ? "owner" : v.signedIn ? "account" : "guest";+}++/** The board's example result (the template's own published film or picture), shown on its last step until it runs. */+function exampleView(c: Canvas, example: VisitorBoardData["example"]): CanvasView {+ if (!example) return { canvas: c, generations: [] };+ const id = `example-${c.templateId ?? c.id}`;+ const g = {+ id,+ batchId: null,+ feature: "canvas-example",+ presetId: null,+ modelId: "",+ engine: "open",+ provider: "comfyui",+ op: example.kind === "video" ? "image-to-video" : "text-to-image",+ kind: example.kind,+ status: "succeeded",+ progress: null,+ message: null,+ prompt: null,+ request: {},+ outputs: [{ url: example.url, kind: example.kind, ...(example.kind === "video" && { meta: { poster: example.poster } }) }],+ error: null,+ costUsd: null,+ favorite: false,+ createdAt: 0,+ updatedAt: 0,+ completedAt: 0,+ } as unknown as Generation;+ return { canvas: { ...c, runs: { [example.nodeId]: { sig: "example", ids: [id], at: 0 } } }, generations: [g] };+}++const asCanvas = (b: { id: string; name: string; templateId: string | null; pages: CanvasPage[] }): Canvas => ({+ id: b.id,+ name: b.name,+ pages: b.pages,+ runs: {},+ templateId: b.templateId,+ createdAt: 0,+ updatedAt: 0,+ editedAt: null,+});++// ---------------------------------------------------------------------------+// What running needs, and saving to an account++function RunNeeds({ open, onOpenChange, who, oneStep }: { open: boolean; onOpenChange: (o: boolean) => void; who: Who; oneStep?: VisitorBoardData["oneStep"] }) {+ const here = usePathname();+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Running a board isn't available here</DialogTitle>+ <DialogDescription>+ You can build, change and keep boards here.{" "}+ {oneStep ? "To make this result now, use the same effect in the Video studio: it runs every step at once." : "To make something now, use the Image, Video or Audio studio, or an app, effect or camera motion."}+ </DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-2 sm:justify-start">+ <Button asChild className="rounded-full">+ <Link href={oneStep?.href ?? "/video"}>+ {oneStep?.label ?? "Open the Video studio"} <ArrowRight />+ </Link>+ </Button>+ {who === "guest" && (+ <Button asChild variant="secondary" className="rounded-full">+ <Link href={signInHref("signup", here)}>+ <UserPlus /> Sign up to save boards+ </Link>+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/** A guest's Save: the board is kept in this browser; an account keeps it everywhere. */+function SignUpToSave({ open, onOpenChange }: { open: boolean; onOpenChange: (o: boolean) => void }) {+ const here = usePathname();+ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-md">+ <DialogHeader>+ <DialogTitle>Keep this board in an account</DialogTitle>+ <DialogDescription>Your board is kept in this browser for now. Create a free account to save your canvases and open them anywhere.</DialogDescription>+ </DialogHeader>+ <DialogFooter className="gap-2 sm:justify-start">+ <Button asChild className="rounded-full">+ <Link href={signInHref("signup", here)}>+ <UserPlus /> Sign up+ </Link>+ </Button>+ <Button asChild variant="secondary" className="rounded-full">+ <Link href={signInHref("login", here)}>+ <LogIn /> Log in+ </Link>+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}++/** The phone's line under the header: wiring new steps takes a larger screen; the board is kept. */+function PhoneNote({ kept }: { kept: string }) {+ return (+ <p className="flex shrink-0 items-center gap-2 border-b bg-muted/40 px-4 py-2 text-[12px] text-muted-foreground" data-phone-note>+ <Monitor className="size-3.5 shrink-0" aria-hidden />+ <span className="min-w-0">Change any step in Nodes. To add and wire new steps, open this board on a larger screen. {kept}</span>+ </p>+ );+}++/**+ * The editor with a visitor's host: `keep` saves the pages and name where this board lives; `onSaveToAccount` (an+ * account's board kept in this browser) moves it to the account.+ */+function VisitorEditor({+ board,+ who,+ savedLabel,+ keep,+ rename,+ saveToAccount,+ example,+ oneStep,+}: {+ board: Canvas;+ who: Who;+ savedLabel: string;+ keep: (pages: CanvasPage[], keepalive: boolean) => Promise<void>;+ rename: (name: string) => Promise<void>;+ /** An account's board not saved to it yet: Save moves it there. */+ saveToAccount?: (now: BoardNow) => Promise<void>;+ example?: VisitorBoardData["example"];+ oneStep?: VisitorBoardData["oneStep"];+}) {+ const [runOpen, setRunOpen] = useState(false);+ const [signUpOpen, setSignUpOpen] = useState(false);+ const [saving, setSaving] = useState(false);+ const isMobile = useIsMobile();+ const keepRef = useRef({ keep, rename, saveToAccount });+ useEffect(() => {+ keepRef.current = { keep, rename, saveToAccount };+ });+ const view = useMemo(() => exampleView(board, example), [board, example]);+ const action = useCallback(+ (now: () => BoardNow) => {+ if (who === "guest")+ return (+ <Button size="sm" className="h-8 rounded-full px-3" onClick={() => setSignUpOpen(true)} data-visitor-save>+ <Cloud /> <span className="max-sm:sr-only">Save</span>+ </Button>+ );+ if (!keepRef.current.saveToAccount) return null;+ return (+ <Button+ size="sm"+ className="h-8 rounded-full px-3"+ disabled={saving}+ data-visitor-save+ onClick={() => {+ setSaving(true);+ void keepRef.current.saveToAccount!(now()).catch((e) => {+ toastError(e);+ setSaving(false);+ });+ }}+ >+ {saving ? <Loader2 className="animate-spin" /> : <Cloud />} <span className="max-sm:sr-only">Save to account</span>+ </Button>+ );+ },+ [who, saving],+ );+ const host = useMemo<BoardHost>(+ () => ({+ save: (pages, keepalive) => keepRef.current.keep(pages, keepalive),+ rename: (name) => keepRef.current.rename(name),+ visitor: {+ savedLabel,+ run: () => setRunOpen(true),+ action,+ note: isMobile ? <PhoneNote kept={savedLabel === "Saved" ? "Your changes save to your account." : "Your board is kept in this browser."} /> : undefined,+ },+ }),+ [savedLabel, action, isMobile],+ );+ return (+ <>+ <BoardEditor id={board.id} initial={board} view={view} host={host} />+ <RunNeeds open={runOpen} onOpenChange={setRunOpen} who={who} oneStep={oneStep} />+ <SignUpToSave open={signUpOpen} onOpenChange={setSignUpOpen} />+ </>+ );+}++/** An account's board kept in this browser goes to the account: the draft is removed once it is saved there. */+function useSaveToAccount(draftId: () => string | null) {+ const router = useRouter();+ const qc = useQueryClient();+ return useCallback(+ async (now: BoardNow, templateId: string | null) => {+ const c = await accountCanvasApi.create({ name: now.name, templateId, pages: now.pages });+ const d = draftId();+ if (d) deleteDraft(d);+ void qc.invalidateQueries({ queryKey: ["account-canvases"], exact: true });+ toast.success("Saved to your account", { duration: 1800 });+ router.replace(`/canvas/saved/${c.id}`);+ },+ [router, qc, draftId],+ );+}++/** Keeps a board in this browser under `id`, made on its first change. */+function draftKeeper(id: string, base: { name: string; templateId: string | null; pages: CanvasPage[] }, createdAt: number) {+ let name = base.name;+ let pages = base.pages;+ const put = () => putDraft({ id, name, templateId: base.templateId, pages, createdAt, updatedAt: Date.now() } satisfies CanvasDraft);+ return {+ keep: async (p: CanvasPage[]) => {+ pages = p;+ put();+ },+ rename: async (n: string) => {+ name = n;+ put();+ },+ };+}++// ---------------------------------------------------------------------------+// The three pages++/** /canvas/try/<id>: a ready board (or a blank one). The owner gets a board of their own in the studio at once. */+export function TryBoard({ board }: { board: VisitorBoardData }) {+ const who = useWho();+ const router = useRouter();+ const { create } = useCanvasActions();+ const [engine] = useEngine();+ const started = useRef(false);+ // The owner's boards are the studio's: make one from the template, as "Use template" does.+ useEffect(() => {+ if (who !== "owner" || started.current) return;+ started.current = true;+ create(board.templateId ? { templateId: board.templateId, engine } : {}).then(+ (c) => router.replace(`/canvas/${c.id}`),+ (e) => toastError(e),+ );+ }, [who, board.templateId, engine, create, router]);+ // The draft this board becomes on its first change (its address changes to it, without reloading).+ const draft = useRef<string | null>(null);+ const keeper = useRef<ReturnType<typeof draftKeeper> | null>(null);+ const keepFirst = useCallback(() => {+ if (!keeper.current) {+ draft.current = newDraftId();+ keeper.current = draftKeeper(draft.current, board, Date.now());+ }+ return keeper.current;+ }, [board]);+ const moved = useRef(false);+ const afterFirst = useCallback(() => {+ if (moved.current || !draft.current) return;+ moved.current = true;+ window.history.replaceState(null, "", `/canvas/draft/${draft.current}`);+ }, []);+ const saveToAccount = useSaveToAccount(useCallback(() => draft.current, []));+ const canvas = useMemo(() => asCanvas(board), [board]);+ if (!who || who === "owner") return <EditorSkeleton />;+ return (+ <VisitorEditor+ board={canvas}+ who={who}+ savedLabel="Kept in this browser"+ keep={async (pages) => {+ await keepFirst().keep(pages);+ afterFirst();+ }}+ rename={async (name) => {+ await keepFirst().rename(name);+ afterFirst();+ }}+ saveToAccount={who === "account" ? (now) => saveToAccount(now, board.templateId) : undefined}+ example={board.example}+ oneStep={board.oneStep}+ />+ );+}++const subscribeNothing = () => () => {};++/** /canvas/draft/<id>: a board kept in this browser. */+export function DraftBoard({ id, boards }: { id: string; boards: Record<string, Pick<VisitorBoardData, "example" | "oneStep">> }) {+ const who = useWho();+ const hydrated = useHydrated();+ // Read once, after hydration (the server can't see this browser's storage).+ const draft = useSyncExternalStore(+ subscribeNothing,+ () => draftOnce(id),+ () => undefined,+ );+ const saveToAccount = useSaveToAccount(useCallback(() => id, [id]));+ const keeper = useMemo(() => (draft ? draftKeeper(id, draft, draft.createdAt) : null), [id, draft]);+ const canvas = useMemo(() => (draft ? asCanvas(draft) : null), [draft]);+ if (!hydrated || !who) return <EditorSkeleton />;+ if (!draft || !keeper || !canvas)+ return (+ <NotFoundState title="This board isn’t in this browser">+ A board you haven't saved to an account stays in the browser you made it in. Start a new one from Canvas.+ </NotFoundState>+ );+ const extra = draft.templateId ? boards[draft.templateId] : undefined;+ return (+ <VisitorEditor+ board={canvas}+ who={who === "owner" ? "account" : who}+ savedLabel="Kept in this browser"+ keep={async (pages) => keeper.keep(pages)}+ rename={async (name) => keeper.rename(name)}+ saveToAccount={who === "account" ? (now) => saveToAccount(now, draft.templateId) : undefined}+ example={extra?.example}+ oneStep={extra?.oneStep}+ />+ );+}++/** One read of a draft per id for the page's life (useSyncExternalStore needs the same object each time). */+const drafts = new Map<string, CanvasDraft | null>();+function draftOnce(id: string): CanvasDraft | undefined {+ if (!drafts.has(id)) drafts.set(id, getDraft(id));+ return drafts.get(id) ?? undefined;+}++/** /canvas/saved/<id>: an account's own board; every change saves to the account. */+export function SavedBoard({ id, boards }: { id: string; boards: Record<string, Pick<VisitorBoardData, "example" | "oneStep">> }) {+ const who = useWho();+ const here = usePathname();+ const q = useAccountCanvas(id, { enabled: who === "account" });+ const canvas = useMemo(() => (q.data ? asCanvas(q.data) : null), [q.data]);+ if (!who || (who === "account" && q.isPending)) return <EditorSkeleton />;+ if (who === "guest")+ return (+ <NotFoundState title="Log in to open this canvas">+ <span className="block">Your saved canvases open when you're logged in.</span>+ <Link href={signInHref("login", here)} className="mt-2 inline-flex items-center gap-1 font-medium text-foreground underline underline-offset-4">+ <LogIn className="size-3.5" /> Log in+ </Link>+ </NotFoundState>+ );+ if (!canvas) return <NotFoundState title="This canvas isn’t here">It may have been deleted.</NotFoundState>;+ const extra = canvas.templateId ? boards[canvas.templateId] : undefined;+ return (+ <VisitorEditor+ board={canvas}+ who="account"+ savedLabel="Saved"+ keep={async (pages, keepalive) => void (await accountCanvasApi.save(id, { pages }, keepalive))}+ rename={async (name) => void (await accountCanvasApi.save(id, { name }))}+ example={extra?.example}+ oneStep={extra?.oneStep}+ />+ );+}+diff --git a/src/lib/canvas-drafts.ts b/src/lib/canvas-drafts.tsnew file mode 100644index 00000000..b715f087--- /dev/null+++ b/src/lib/canvas-drafts.ts@@ -0,0 +1,127 @@+/**+ * A visitor's canvases kept in this browser (localStorage): a guest's boards, and an account's before it saves them to+ * its account. Nothing here reaches the server. Each draft is its own key, with a small index for the list; storage+ * that is full, blocked or missing (a private window) reads as no drafts and refuses a save with a plain message.+ */+import type { CanvasPage } from "@/lib/catalog/canvas-board";++export interface CanvasDraft {+ id: string;+ name: string;+ templateId: string | null;+ pages: CanvasPage[];+ createdAt: number;+ updatedAt: number;+}++export interface DraftSummary {+ id: string;+ name: string;+ templateId: string | null;+ nodeCount: number;+ updatedAt: number;+}++/** Drafts this browser keeps; the oldest goes when a new one would pass it. */+export const MAX_DRAFTS = 20;+const INDEX = "fuobe.canvas.drafts";+const KEY = (id: string) => `fuobe.canvas.draft.${id}`;+/** Said when this browser won't keep it (full, or storage is off). */+export const DRAFT_STORAGE_MESSAGE = "This browser couldn't keep your board. Free some space or allow site data, or create a free account to save it.";+export const DRAFT_EVENT = "fuobe:canvas-drafts";++const ID = /^[A-Za-z0-9_-]{6,40}$/;+export const isDraftId = (id: string) => ID.test(id);++export function newDraftId(): string {+ const bytes = new Uint8Array(9);+ crypto.getRandomValues(bytes);+ return `d${Array.from(bytes, (b) => b.toString(36).padStart(2, "0")).join("").slice(0, 14)}`;+}++function store(): Storage | null {+ try {+ return typeof window === "undefined" ? null : window.localStorage;+ } catch {+ return null;+ }+}++function readIndex(): DraftSummary[] {+ try {+ const raw = store()?.getItem(INDEX);+ const list = raw ? (JSON.parse(raw) as unknown) : [];+ return Array.isArray(list) ? list.filter((d): d is DraftSummary => !!d && typeof d === "object" && isDraftId((d as DraftSummary).id)) : [];+ } catch {+ return [];+ }+}++/** This browser's drafts, newest first. */+export function listDrafts(): DraftSummary[] {+ return readIndex().sort((a, b) => b.updatedAt - a.updatedAt);+}++export function getDraft(id: string): CanvasDraft | null {+ if (!isDraftId(id)) return null;+ try {+ const raw = store()?.getItem(KEY(id));+ if (!raw) return null;+ const d = JSON.parse(raw) as CanvasDraft;+ return d && Array.isArray(d.pages) && d.pages.length ? { ...d, id } : null;+ } catch {+ return null;+ }+}++const summary = (d: CanvasDraft): DraftSummary => ({+ id: d.id,+ name: d.name,+ templateId: d.templateId,+ nodeCount: d.pages.reduce((n, p) => n + (p.graph?.nodes?.length ?? 0), 0),+ updatedAt: d.updatedAt,+});++const changed = () => {+ try {+ window.dispatchEvent(new Event(DRAFT_EVENT));+ } catch {+ // No window (tests): nothing listens.+ }+};++/** Keeps a draft (new or changed). Throws DRAFT_STORAGE_MESSAGE when this browser won't keep it. */+export function putDraft(d: CanvasDraft): void {+ const s = store();+ if (!s || !isDraftId(d.id)) throw new Error(DRAFT_STORAGE_MESSAGE);+ const index = readIndex().filter((x) => x.id !== d.id);+ // The oldest drafts make room for this one.+ const keep = index.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_DRAFTS - 1);+ const dropped = index.filter((x) => !keep.includes(x));+ try {+ s.setItem(KEY(d.id), JSON.stringify(d));+ s.setItem(INDEX, JSON.stringify([summary(d), ...keep]));+ } catch {+ throw new Error(DRAFT_STORAGE_MESSAGE);+ }+ for (const x of dropped) {+ try {+ s.removeItem(KEY(x.id));+ } catch {+ // Left behind: the index no longer lists it.+ }+ }+ changed();+}++export function deleteDraft(id: string): void {+ const s = store();+ if (!s) return;+ try {+ s.removeItem(KEY(id));+ s.setItem(INDEX, JSON.stringify(readIndex().filter((x) => x.id !== id)));+ } catch {+ // Storage is off: there was nothing to delete.+ }+ changed();+}diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex d4f0ee60..af850000 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -170,9 +170,12 @@ export function accountGeneration(method: string, pathname: string): string | un*/export function accountOwnRead(pathname: string): boolean {if (ACCOUNT_LISTS.has(pathname)) return true;- return pathname === "/api/generations" || pathname === "/api/account/gpu" || pathname === "/api/account/keys" || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname) || PAIRING_READS.has(pathname);+ return pathname === "/api/generations" || pathname === "/api/account/gpu" || pathname === "/api/account/keys" || ACCOUNT_CANVASES.test(pathname) || GPU_READS.has(pathname) || COMPUTER_READ.test(pathname) || PAIRING_READS.has(pathname);}+/** An account's own canvases (src/app/api/account/canvases): the routes read and change its own boards only. */+const ACCOUNT_CANVASES = /^\/api\/account\/canvases(\/[^/]+)?$/;+/** The Library's counts and its Uploads (its stored files): each route answers an account with its own only. */const ACCOUNT_LISTS = new Set(["/api/generations/facets", "/api/assets"]);@@ -208,6 +211,8 @@ export function accountMayChange(method: string, pathname: string, search: strinif (COMPUTER_CHANGES.some(([m, p]) => m === method && p.test(pathname))) return true;if ((method === "POST" && pathname === "/api/gpu/pair") || (method === "DELETE" && /^\/api\/gpu\/paired\/[^/]+$/.test(pathname))) return true;if (method === "POST" && (pathname === "/api/uploads" || pathname === "/api/media/probe")) return true;+ // Its own canvases: save a board, rename it, save its pages, delete it (the routes take its own boards only).+ if ((method === "POST" && pathname === "/api/account/canvases") || ((method === "PATCH" || method === "DELETE") && /^\/api\/account\/canvases\/[^/]+$/.test(pathname))) return true;// "Report this result", and a click on an offer the billing service sent (each route checks the rest).if (method === "POST" && (pathname === "/api/reports" || pathname === "/api/billing/interest")) return true;// Like, pin or review many of its own runs at once (the route checks each is its own, and refuses the rest).diff --git a/src/lib/template-covers.ts b/src/lib/template-covers.tsindex ef834cb5..9db52ce8 100644--- a/src/lib/template-covers.ts+++ b/src/lib/template-covers.ts@@ -66,21 +66,15 @@ function read(key: string, entry: TemplateCoverEntry): TemplateCover {};}-/**- * How much of a clip around its peak frame a template cover plays (s): the finished scene only. An effect clip opens on- * the photo that went in and fades back to it at the end, so a card that played it whole would show that photo most- * of the time.- */-export const PEAK_WINDOW = { before: 0.6, after: 0.6 } as const;-/** A still taken from the middle of an effect's clip (its peak: /previews/presets/peak/), not a reveal's last frame. */const PEAK_STILL = /^\/previews\/presets\/peak\//;/*** A cover as the preset previews take it (PresetPreview, usePreviewPlayback): its poster and clip, and for a clip* whose poster is a later frame, a rest on it. A reveal (its poster is the last frame) starts there and loops from 0.- * An effect's clip shown by its peak (the finished scene) plays only the stretch around it: a hover starts a little- * before the peak, and the loop comes back there, never to the clip's start (the photo that went in).+ * An effect's clip shown by its peak (the finished scene) rests on that still and, when it plays, plays the effect's+ * whole published clip from its first frame, as the effect's own gallery card does: the photo that went in, the+ * change, and the finished scene, looping. (A stretch around the peak alone showed the effect for a moment only.)*/export function templatePreview(c: TemplateCover): PresetPreview {const at = c.at;@@ -88,12 +82,7 @@ export function templatePreview(c: TemplateCover): PresetPreview {return {poster: c.poster,...(c.video && { video: c.video }),- ...(c.video &&- at !== undefined && {- rest: peak- ? { src: c.poster, at, from: Math.max(0, +(at - PEAK_WINDOW.before).toFixed(3)), until: +(at + PEAK_WINDOW.after).toFixed(3) }- : { src: c.poster, at, from: 0 },- }),+ ...(c.video && at !== undefined && !peak && { rest: { src: c.poster, at, from: 0 } }),scene: "product",};}diff --git a/src/server/account-canvas-http.ts b/src/server/account-canvas-http.tsnew file mode 100644index 00000000..1b8c2967--- /dev/null+++ b/src/server/account-canvas-http.ts@@ -0,0 +1,28 @@+import "server-only";+import { requestAccount } from "@/server/auth";+import { ACCOUNT_CANVAS_LIMITS, AccountCanvasError } from "@/server/account-canvas";+import { pagesProblem } from "@/server/canvas";+import { hit } from "@/server/rate";++/**+ * An account's own canvases (public sign-up, src/server/account-canvas.ts). Only a signed-in account reaches its own+ * boards here: a guest is answered by the proxy (401, sign up to save), and the owner keeps boards in /api/canvases.+ */+export function accountOf(request: Request) {+ return requestAccount(request);+}++export const notAccount = () => Response.json({ error: "Create a free account to save your canvases." }, { status: 401 });++/** Saves a minute per account: a runaway tab can't fill the database. */+export function tooMany(accountId: string): Response | null {+ const rate = hit(`account-canvas:${accountId}`, ACCOUNT_CANVAS_LIMITS.savesPerMinute, 60_000);+ return rate.ok ? null : Response.json({ error: "Saving too often. Wait a moment, then try again." }, { status: 429, headers: { "Retry-After": String(rate.retryAfterS) } });+}++export function refused(e: unknown): Response {+ if (e instanceof AccountCanvasError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+}++export const badPages = (input: unknown) => Response.json({ error: pagesProblem(input) }, { status: 400 });diff --git a/src/server/account-canvas.ts b/src/server/account-canvas.tsnew file mode 100644index 00000000..e188b106--- /dev/null+++ b/src/server/account-canvas.ts@@ -0,0 +1,134 @@+import "server-only";+import { nanoid } from "nanoid";+import { outline, type CanvasSummary } from "@/lib/catalog/canvas";+import { FIRST_PAGE_ID, pageName, readPages, type CanvasPage } from "@/lib/catalog/canvas-board";+import { db } from "./db";++/**+ * An account's own canvases (public sign-up): boards it builds and keeps, in a table of their own, never in the owner's+ * `canvases`. Every read and change names the account, so one account never reaches another's board, and the owner's+ * boards are never in reach. A board here holds only its pages: running a canvas stays the owner's (an account's Run+ * says so), so there are no runs to keep.+ */++export const ACCOUNT_CANVAS_LIMITS = {+ /** Boards an account keeps. */+ boards: 50,+ /** A board's pages as JSON (characters). */+ bytes: 1_000_000,+ /** Saves a minute (the editor's autosave is debounced, so this is far above what editing sends). */+ savesPerMinute: 120,+} as const;++// The table is made in db.ts (ACCOUNT_CANVAS_TABLES).++interface Row {+ id: string;+ account_id: string;+ name: string;+ pages_json: string;+ template_id: string | null;+ created_at: number;+ updated_at: number;+}++/** An account's board as the editor opens it. */+export interface AccountCanvas {+ id: string;+ name: string;+ pages: CanvasPage[];+ templateId: string | null;+ createdAt: number;+ updatedAt: number;+}++/** Why a change was refused, with the status the route answers. */+export class AccountCanvasError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++const toCanvas = (r: Row): AccountCanvas => ({+ id: r.id,+ name: r.name,+ pages: readPages(JSON.parse(r.pages_json)),+ templateId: r.template_id,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++const cleanName = (name: string | undefined, fallback: string) => (name?.trim() || fallback).slice(0, 80);++function pagesJson(pages: CanvasPage[]): string {+ const json = JSON.stringify({ pages });+ if (json.length > ACCOUNT_CANVAS_LIMITS.bytes) throw new AccountCanvasError("This board is too big to save. Remove a few nodes or pages, then try again.", 413);+ return json;+}++export function listAccountCanvases(accountId: string): CanvasSummary[] {+ const rows = db().prepare("SELECT * FROM account_canvases WHERE account_id = ? ORDER BY updated_at DESC LIMIT ?").all(accountId, ACCOUNT_CANVAS_LIMITS.boards) as Row[];+ return rows.map((r) => {+ const c = toCanvas(r);+ return {+ id: c.id,+ name: c.name,+ nodeCount: c.pages.reduce((n, p) => n + p.graph.nodes.length, 0),+ pageCount: c.pages.length,+ templateId: c.templateId,+ preview: null,+ outline: outline(c.pages[0].graph),+ createdAt: c.createdAt,+ updatedAt: c.updatedAt,+ editedAt: c.updatedAt,+ };+ });+}++/** One of the account's boards, or null (another account's board, or none, reads the same). */+export function getAccountCanvas(accountId: string, id: string): AccountCanvas | null {+ const r = db().prepare("SELECT * FROM account_canvases WHERE id = ? AND account_id = ?").get(id, accountId) as Row | undefined;+ return r ? toCanvas(r) : null;+}++export function createAccountCanvas(accountId: string, input: { name?: string; pages?: CanvasPage[]; templateId?: string | null }): AccountCanvas {+ const count = (db().prepare("SELECT COUNT(*) AS n FROM account_canvases WHERE account_id = ?").get(accountId) as { n: number }).n;+ if (count >= ACCOUNT_CANVAS_LIMITS.boards) throw new AccountCanvasError(`You can keep up to ${ACCOUNT_CANVAS_LIMITS.boards} canvases. Delete one to save another.`, 409);+ const pages = input.pages?.length ? input.pages : [{ id: FIRST_PAGE_ID, name: pageName(0), graph: { nodes: [], edges: [] } }];+ const now = Date.now();+ const row: Row = {+ id: nanoid(12),+ account_id: accountId,+ name: cleanName(input.name, "Untitled canvas"),+ pages_json: pagesJson(pages),+ template_id: input.templateId?.slice(0, 60) ?? null,+ created_at: now,+ updated_at: now,+ };+ db()+ .prepare(`INSERT INTO account_canvases (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)+ .run(row);+ return toCanvas(row);+}++/** A new name and/or pages for one of the account's boards; null when it has no such board. */+export function updateAccountCanvas(accountId: string, id: string, patch: { name?: string; pages?: CanvasPage[] }): AccountCanvas | null {+ const current = getAccountCanvas(accountId, id);+ if (!current) return null;+ const name = cleanName(patch.name, current.name);+ const json = patch.pages?.length ? pagesJson(patch.pages) : JSON.stringify({ pages: current.pages });+ db().prepare("UPDATE account_canvases SET name = ?, pages_json = ?, updated_at = ? WHERE id = ? AND account_id = ?").run(name, json, Date.now(), id, accountId);+ return getAccountCanvas(accountId, id);+}++export function deleteAccountCanvas(accountId: string, id: string): boolean {+ return db().prepare("DELETE FROM account_canvases WHERE id = ? AND account_id = ?").run(id, accountId).changes > 0;+}++/** Every board of an account, when the account is deleted. */+export function deleteAccountCanvases(accountId: string): number {+ return db().prepare("DELETE FROM account_canvases WHERE account_id = ?").run(accountId).changes;+}diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.tsindex fdb8f381..d7c85914 100644--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@ -2,6 +2,7 @@ import "server-only";import fs from "node:fs";import path from "node:path";import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";+import { deleteAccountCanvases } from "./account-canvas";import { clearAccountLoras } from "./account-loras";import { accountById, deleteAccount, readAccountIds, setAccountDisabled } from "./auth";import { strayAccountIds } from "./auth-store";@@ -43,6 +44,7 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: nconst files = (db().prepare("SELECT id FROM assets WHERE account_id = ?").all(id) as { id: string }[]).map((r) => r.id);for (const f of files) deleteAsset(f);clearAccountLoras(id);+ deleteAccountCanvases(id);await runAccountDeletedHooks(id);return { runs, files: files.length };}diff --git a/src/server/canvas-samples.ts b/src/server/canvas-samples.tsindex a41470ee..bbf9c369 100644--- a/src/server/canvas-samples.ts+++ b/src/server/canvas-samples.ts@@ -49,7 +49,7 @@ export function adoptSample(src: string): string | null {* The board with its starting files in place: each input node a sample names gets the stored copy and a plain name. A* sample whose file isn't there leaves its input empty (the board still opens, and asks for that one file).*/-export function fillSamples(graph: CanvasGraph, samples: CanvasTemplate["samples"]): CanvasGraph {+export function fillSamples(graph: CanvasGraph, samples: CanvasTemplate["samples"], copy = true): CanvasGraph {if (!samples) return graph;return {...graph,@@ -58,7 +58,13 @@ export function fillSamples(graph: CanvasGraph, samples: CanvasTemplate["samplesif (!s || n.data.url) return n;const abs = sampleFile(s.src);if (!abs) return n;- return { ...n, data: { ...n.data, url: storedSample(abs), name: s.name } };+ return { ...n, data: { ...n.data, url: copy ? storedSample(abs) : s.src, name: s.name } };}),};}++/**+ * Whether a board's file is one of Fuobe's published example files, named by its plain public path: a visitor's board+ * (a guest's draft, an account's own canvas) keeps it as it is, never a copy in anyone's storage.+ */+export const isPublishedSample = (src: string): boolean => sampleFile(src) !== null;diff --git a/src/server/canvas.ts b/src/server/canvas.tsindex e11178e3..3a425939 100644--- a/src/server/canvas.ts+++ b/src/server/canvas.ts@@ -58,7 +58,7 @@ import { createGenerations, getGeneration } from "./generations";import { silentWav } from "./marketing";import { engineMode } from "./settings";import { absolutePath, saveFile } from "./storage";-import { fillSamples } from "./canvas-samples";+import { fillSamples, isPublishedSample } from "./canvas-samples";/*** Canvas boards (Higgsfield Canvas): the pages the user edits (each a graph, with its groups, comments and@@ -159,15 +159,28 @@ const LayoutData = z: undefined,);-const NodeData = z.object({+/** Media on the owner's boards: Fuobe's own storage (uploads, the library, generated outputs). */+const OWN_MEDIA = z.string().startsWith("/api/files/").max(2000);++/**+ * Media on an account's own board: a stored file (the file route checks whose it is when it is read), or one of Fuobe's+ * published example files a ready board starts with (/examples/…, /samples/…, /previews/presets/…, /starters/…), as a+ * plain path that never steps out of its folder.+ */+const VISITOR_MEDIA = z+ .string()+ .max(2000)+ .refine((u) => u.startsWith("/api/files/") || isPublishedSample(u), "Not a file this board can hold");++const nodeData = (media: z.ZodType<string>) =>+ z.object({label: clamped(80).optional(),text: clamped(TEXT_MAX).optional(),- // Media comes from Fuobe's own storage (uploads, the library, generated outputs).- url: z.string().startsWith("/api/files/").max(2000).optional(),+ url: media.optional(),name: clamped(200).optional(),elementId: z.string().max(40).optional(),handle: Handle.optional(),- preview: z.string().startsWith("/api/files/").max(2000).optional(),+ preview: media.optional(),modelId: z.string().max(120).optional(),// A Fuobe Original (runs on both engines): the engine the node runs it on.engine: z.enum(["open", "cloud"]).optional(),@@ -252,14 +265,15 @@ const Shape = z.object({points: z.array(z.tuple([z.number().min(-1).max(2), z.number().min(-1).max(2)])).max(BOARD_LIMITS.penPoints).optional(),});-export const GraphSchema = z.object({+const graphSchema = (media: z.ZodType<string>) =>+ z.object({nodes: z.array(z.object({id: z.string().min(1).max(80),type: z.enum(NODE_TYPES),position: z.object({ x: Num, y: Num }),- data: NodeData,+ data: nodeData(media),width: Num.positive().max(4000).optional(),height: Num.positive().max(4000).optional(),}),@@ -282,10 +296,17 @@ export const GraphSchema = z.object({shapes: z.array(Shape).max(BOARD_LIMITS.shapes).optional(),});-export const PagesSchema = z- .array(z.object({ id: z.string().min(1).max(40), name: clamped(60), graph: GraphSchema }))- .min(1)- .max(BOARD_LIMITS.pages);+export const GraphSchema = graphSchema(OWN_MEDIA);++const pagesSchema = (graph: typeof GraphSchema) =>+ z+ .array(z.object({ id: z.string().min(1).max(40), name: clamped(60), graph }))+ .min(1)+ .max(BOARD_LIMITS.pages);++export const PagesSchema = pagesSchema(GraphSchema);+/** An account's own board (account-canvas.ts): the same limits, and Fuobe's published example files may stay in it. */+const VisitorPagesSchema = pagesSchema(graphSchema(VISITOR_MEDIA));/** Why a graph from the browser was refused, naming the node (the editor shows it in a toast). */export function graphProblem(input: unknown): string {@@ -343,8 +364,8 @@ export function parseGraph(input: unknown): CanvasGraph | null {* Parsed pages: page ids made unique, and a node id used on an earlier page dropped from later ones* (results are kept by node id, so two pages can't share one).*/-export function parsePages(input: unknown): CanvasPage[] | null {- const parsed = PagesSchema.safeParse(input);+export function parsePages(input: unknown, schema: typeof PagesSchema = PagesSchema): CanvasPage[] | null {+ const parsed = schema.safeParse(input);if (!parsed.success) return null;const ids = new Set<string>();const nodeIds = new Set<string>();@@ -358,6 +379,11 @@ export function parsePages(input: unknown): CanvasPage[] | null {});}+/** An account's own pages (parsePages, where Fuobe's published example files may stay in an input). */+export function parseVisitorPages(input: unknown): CanvasPage[] | null {+ return parsePages(input, VisitorPagesSchema);+}+// ---------------------------------------------------------------------------// CRUDdiff --git a/src/server/db.ts b/src/server/db.tsindex 13475144..13bb1435 100644--- a/src/server/db.ts+++ b/src/server/db.ts@@ -1066,6 +1066,8 @@ function open(): Database.Database {db.exec(ADMIN_TABLES);// Skills: the runs that wait across studios.db.exec(SKILL_TABLES);+ // An account's own canvases (account-canvas.ts): not a numbered migration, so branches never clash over its place.+ db.exec(ACCOUNT_CANVAS_TABLES);// A billing hold's rows are found through this index (only rows that have one are in it).try {db.exec("CREATE INDEX IF NOT EXISTS generations_hold ON generations(json_extract(request_json, '$.hold')) WHERE json_extract(request_json, '$.hold') IS NOT NULL");@@ -1083,6 +1085,18 @@ function open(): Database.Database {return db;}+/** An account's own canvases (public sign-up, src/server/account-canvas.ts), never in the owner's `canvases`. */+const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ name TEXT NOT NULL,+ pages_json TEXT NOT NULL,+ template_id TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;+export function db(): Database.Database {globalThis.__fuobeDb ??= open();return globalThis.__fuobeDb;diff --git a/src/server/visitor-board.ts b/src/server/visitor-board.tsnew file mode 100644index 00000000..7a4cfc7d--- /dev/null+++ b/src/server/visitor-board.ts@@ -0,0 +1,82 @@+import "server-only";+import { cleanGraph, EMPTY_GRAPH, getTemplate, isGenerator, outputType, type CanvasGraph } from "@/lib/catalog/canvas";+import { FIRST_PAGE_ID, pageName, type CanvasPage } from "@/lib/catalog/canvas-board";+import { shownTo } from "@/lib/canvas-sections";+import { templateDetail, templateIds } from "@/lib/canvas-template-cards";+import { templateCover } from "@/lib/template-covers";+import { fillSamples } from "./canvas-samples";++/** "Start blank": the one board that isn't a template. */+export const BLANK_BOARD = "blank";++/** The result a ready board shows on its last step before anyone runs it: the template's own published example. */+export interface BoardExample {+ nodeId: string;+ kind: "image" | "video";+ url: string;+ poster: string;+}++/** A board as a visitor opens it in the editor: nothing stored yet, its files Fuobe's own published examples. */+export interface VisitorBoard {+ name: string;+ templateId: string | null;+ pages: CanvasPage[];+ example?: BoardExample;+ /** The Video effect that makes the same in one step (an effect film's), for a visitor's Run. */+ oneStep?: { href: string; label: string };+}++const hasCover = (id: string) => !!templateCover("canvas", id);++/** The ready boards a visitor may open in the editor (the ones whose card they see), and "blank". */+export function visitorBoardIds(): string[] {+ // The same rule as the cards a visitor's /canvas shows (shownTo).+ return [BLANK_BOARD, ...templateIds().filter((id) => visible(id))];+}++function visible(id: string): boolean {+ const d = templateDetail(id);+ return !!d && shownTo(d, { visitor: true, hasCover });+}++/**+ * The last step that makes the board's film (or picture): the generator whose result is the board's example. A board's+ * nodes are built in order, so the last generator of that kind is the one at the end of the chain.+ */+function exampleNode(graph: CanvasGraph, kind: "image" | "video"): string | undefined {+ return graph.nodes.filter((n) => isGenerator(n) && outputType(graph, n) === kind).at(-1)?.id;+}++/**+ * A board for a visitor's editor: a ready board (the open-source variant, as a visitor's studio runs it) with its+ * starting files as Fuobe's published example paths (never a copy in anyone's storage), or a blank one. Null for a+ * board a visitor doesn't see (no real cover yet, or not a ready board).+ */+export function visitorBoard(id: string): VisitorBoard | null {+ if (id === BLANK_BOARD) return { name: "Untitled canvas", templateId: null, pages: [{ id: FIRST_PAGE_ID, name: pageName(0), graph: EMPTY_GRAPH }] };+ const t = getTemplate(id);+ const detail = templateDetail(id);+ if (!t || !detail || !visible(id)) return null;+ const graph = cleanGraph(fillSamples(t.build("open"), t.samples, false));+ const cover = templateCover("canvas", id);+ const kind = cover?.video ? "video" : "image";+ const nodeId = cover && exampleNode(graph, kind);+ return {+ name: t.name,+ templateId: t.id,+ pages: [{ id: FIRST_PAGE_ID, name: pageName(0), graph }],+ ...(cover && nodeId && { example: { nodeId, kind, url: cover.video ?? cover.poster, poster: cover.poster } }),+ ...(detail.oneStep && { oneStep: detail.oneStep }),+ };+}++/** Each ready board's example and one-step effect, by template id: a saved board shows them as its ready board did. */+export function boardExtras(): Record<string, Pick<VisitorBoard, "example" | "oneStep">> {+ const out: Record<string, Pick<VisitorBoard, "example" | "oneStep">> = {};+ for (const id of visitorBoardIds()) {+ const b = id === BLANK_BOARD ? null : visitorBoard(id);+ if (b && (b.example || b.oneStep)) out[id] = { ...(b.example && { example: b.example }), ...(b.oneStep && { oneStep: b.oneStep }) };+ }+ return out;+}diff --git a/tests/canvas-public.test.ts b/tests/canvas-public.test.tsnew file mode 100644index 00000000..82688e08--- /dev/null+++ b/tests/canvas-public.test.ts@@ -0,0 +1,185 @@+import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++/**+ * The public Canvas: a guest or an account opens ready boards (and blank ones) in the editor, keeps a guest's in the+ * browser, and an account saves its own canvases to its account (/api/account/canvases), never anyone else's, and never+ * the owner's. A ready board for a visitor names Fuobe's published example files, never a copy in anyone's storage.+ */+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));+vi.mock("next/headers", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/headers")>()), cookies: async () => ({ delete: () => {}, get: () => undefined }) }));++const dir = tempDir("fuobe-canvas-public-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ENGINE_MODE;++const auth = await import("@/server/auth");+const listRoute = await import("@/app/api/account/canvases/route");+const oneRoute = await import("@/app/api/account/canvases/[id]/route");+const { proxy } = await import("@/proxy");+const { resetRates } = await import("@/server/rate");+const { accountMayChange, accountOwnRead, guestRead } = await import("@/lib/guest-access");+const { visitorBoard, visitorBoardIds, BLANK_BOARD } = await import("@/server/visitor-board");+const { parseVisitorPages, parsePages, listCanvases } = await import("@/server/canvas");+const { purgeAccount } = await import("@/server/account-sweep");+const { db } = await import("@/server/db");+const { CANVAS_TEMPLATES } = await import("@/lib/catalog/canvas");+const { templateCover } = await import("@/lib/template-covers");++let A = "";+let B = "";+let cookieA = "";+let cookieB = "";+beforeAll(() => {+ auth.setPassword("install password");+ A = auth.createAccount("[email protected]", "long enough").id;+ B = auth.createAccount("[email protected]", "long enough").id;+ cookieA = `${auth.SESSION_COOKIE}=${auth.createSession(A).value}`;+ cookieB = `${auth.SESSION_COOKIE}=${auth.createSession(B).value}`;+});+beforeEach(() => resetRates());++const req = (url: string, method: string, body?: unknown, cookie = cookieA) =>+ new Request(`http://localhost:3000${url}`, { method, headers: { cookie, host: "localhost:3000", "content-type": "application/json" }, ...(body !== undefined && { body: JSON.stringify(body) }) });+const ctx = (id: string) => ({ params: Promise.resolve({ id }) });+const page = (nodes: unknown[] = []) => [{ id: "page-1", name: "Page 1", graph: { nodes, edges: [] } }];+const prompt = (text: string) => ({ id: "p1", type: "prompt", position: { x: 0, y: 0 }, data: { text } });++describe("a ready board for a visitor's editor", () => {+ const visible = visitorBoardIds().filter((id) => id !== BLANK_BOARD);++ it("opens every ready board a visitor's /canvas shows, and a blank one", () => {+ expect(visitorBoardIds()[0]).toBe(BLANK_BOARD);+ expect(visible.length).toBeGreaterThan(5);+ expect(visitorBoard(BLANK_BOARD)!.pages[0].graph.nodes).toEqual([]);+ for (const id of visible) {+ const b = visitorBoard(id)!;+ expect(b.templateId).toBe(id);+ expect(b.pages[0].graph.nodes.length, id).toBeGreaterThan(1);+ expect(b.pages[0].graph.edges.length, id).toBeGreaterThan(0);+ }+ });++ it("is null for a board a visitor doesn't see (no real cover yet, or not a ready board)", () => {+ const hidden = CANVAS_TEMPLATES.filter((t) => t.starter === false || !templateCover("canvas", t.id));+ expect(hidden.length).toBeGreaterThan(0);+ for (const t of hidden) expect(visitorBoard(t.id), t.id).toBeNull();+ expect(visitorBoard("no-such-board")).toBeNull();+ });++ it("starts with Fuobe's published example files in place, never a copy in anyone's storage", () => {+ let withFiles = 0;+ for (const id of visible) {+ for (const n of visitorBoard(id)!.pages[0].graph.nodes) {+ if (!n.data.url) continue;+ withFiles++;+ expect(n.data.url, id).toMatch(/^\/(examples|samples|previews\/presets|starters)\//);+ }+ }+ expect(withFiles).toBeGreaterThan(0);+ // Nothing was stored for it.+ expect((db().prepare("SELECT COUNT(*) AS n FROM assets").get() as { n: number }).n).toBe(0);+ });++ it("shows the template's own published film on the step that makes it, and its one-step effect", () => {+ const b = visitorBoard("effect-chain-pearl-earring")!;+ expect(b.example).toMatchObject({ kind: "video", url: templateCover("canvas", "effect-chain-pearl-earring")!.video });+ const node = b.pages[0].graph.nodes.find((n) => n.id === b.example!.nodeId)!;+ expect(node.type).not.toBe("output");+ expect(b.oneStep?.href).toMatch(/^\/video/);+ });++ it("an account may keep those example paths on its own board; the owner's boards and anything else stay refused", () => {+ const board = visitorBoard("effect-chain-pearl-earring")!.pages;+ expect(parseVisitorPages(board)).not.toBeNull();+ expect(parsePages(board)).toBeNull();+ const withUrl = (url: string) => page([{ id: "i1", type: "image-input", position: { x: 0, y: 0 }, data: { url } }]);+ for (const url of ["https://evil.example/x.jpg", "/examples/../../.env", "/examples/nope.jpg", "/api/../secret", "data:image/png;base64,AAAA", "/samples/%2e%2e/x"]) expect(parseVisitorPages(withUrl(url)), url).toBeNull();+ expect(parseVisitorPages(withUrl("/api/files/abc.png"))).not.toBeNull();+ });+});++describe("the access rules for an account's own canvases", () => {+ it("an account reads and changes its own boards there; a guest is asked to sign up", () => {+ expect(accountOwnRead("/api/account/canvases")).toBe(true);+ expect(accountOwnRead("/api/account/canvases/abc")).toBe(true);+ expect(accountOwnRead("/api/account/canvases/abc/x")).toBe(false);+ expect(accountMayChange("POST", "/api/account/canvases", "")).toBe(true);+ expect(accountMayChange("PATCH", "/api/account/canvases/abc", "")).toBe(true);+ expect(accountMayChange("DELETE", "/api/account/canvases/abc", "")).toBe(true);+ expect(accountMayChange("PUT", "/api/account/canvases/abc", "")).toBe(false);+ expect(guestRead("/api/account/canvases")).toEqual({ kind: "closed" });+ });++ it("through the proxy: a guest gets 401, an account passes, the owner's canvases stay 403 for an account", async () => {+ const at = (url: string, method: string, cookie?: string) => proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: cookie ? { cookie } : {}, ...(method !== "GET" && { body: "{}" }) }));+ expect((await at("/api/account/canvases", "GET")).status).toBe(401);+ expect((await at("/api/account/canvases", "POST")).status).toBe(401);+ const passed = await at("/api/account/canvases", "POST", cookieA);+ expect(passed.headers.get("x-middleware-next")).toBe("1");+ expect((await at("/api/canvases", "POST", cookieA)).status).toBe(403);+ });+});++describe("an account's own canvases", () => {+ let id = "";++ it("saves a board (a ready board's example paths kept), lists it, and opens it", async () => {+ const res = await listRoute.POST(req("/api/account/canvases", "POST", { name: "My pearl", templateId: "effect-chain-pearl-earring", pages: visitorBoard("effect-chain-pearl-earring")!.pages }));+ expect(res.status).toBe(201);+ id = ((await res.json()) as { id: string }).id;+ const list = (await (await listRoute.GET(req("/api/account/canvases", "GET"))).json()) as { items: { id: string; name: string; nodeCount: number }[] };+ expect(list.items).toEqual([expect.objectContaining({ id, name: "My pearl" })]);+ expect(list.items[0].nodeCount).toBeGreaterThan(1);+ const one = (await (await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET"), ctx(id))).json()) as { pages: unknown[]; templateId: string };+ expect(one.templateId).toBe("effect-chain-pearl-earring");+ // Never in the owner's canvases.+ expect(listCanvases()).toEqual([]);+ });++ it("renames it and saves its pages", async () => {+ const r1 = await oneRoute.PATCH(req(`/api/account/canvases/${id}`, "PATCH", { name: "Renamed" }), ctx(id));+ expect(r1.status).toBe(200);+ const r2 = await oneRoute.PATCH(req(`/api/account/canvases/${id}`, "PATCH", { pages: page([prompt("a red coat")]) }), ctx(id));+ const c = (await r2.json()) as { name: string; pages: { graph: { nodes: { data: { text: string } }[] } }[] };+ expect(c.name).toBe("Renamed");+ expect(c.pages[0].graph.nodes[0].data.text).toBe("a red coat");+ });++ it("is another account's to neither read, change nor delete (it reads as not found), and a guest's to none", async () => {+ expect((await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET", undefined, cookieB), ctx(id))).status).toBe(404);+ expect((await oneRoute.PATCH(req(`/api/account/canvases/${id}`, "PATCH", { name: "Taken" }, cookieB), ctx(id))).status).toBe(404);+ expect((await oneRoute.DELETE(req(`/api/account/canvases/${id}`, "DELETE", undefined, cookieB), ctx(id))).status).toBe(404);+ expect(((await (await listRoute.GET(req("/api/account/canvases", "GET", undefined, cookieB))).json()) as { items: unknown[] }).items).toEqual([]);+ expect((await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET", undefined, ""), ctx(id))).status).toBe(401);+ expect((await listRoute.POST(req("/api/account/canvases", "POST", { pages: page() }, ""))).status).toBe(401);+ // Still A's, unchanged.+ const mine = (await (await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET"), ctx(id))).json()) as { name: string };+ expect(mine.name).toBe("Renamed");+ });++ it("refuses a board it can't read, one too big, and more than the limit", async () => {+ expect((await listRoute.POST(req("/api/account/canvases", "POST", { pages: [{ id: "x", name: "x", graph: { nodes: "no" } }] }))).status).toBe(400);+ const huge = page(Array.from({ length: 300 }, (_, i) => ({ ...prompt("x".repeat(20_000)), id: `n${i}` })));+ expect((await listRoute.POST(req("/api/account/canvases", "POST", { pages: huge }))).status).toBe(413);+ const { ACCOUNT_CANVAS_LIMITS } = await import("@/server/account-canvas");+ for (let i = 1; i < ACCOUNT_CANVAS_LIMITS.boards; i++) {+ resetRates();+ expect((await listRoute.POST(req("/api/account/canvases", "POST", { name: `b${i}`, pages: page() }))).status).toBe(201);+ }+ const over = await listRoute.POST(req("/api/account/canvases", "POST", { pages: page() }));+ expect(over.status).toBe(409);+ });++ it("deletes it, and every board goes with the account", async () => {+ expect((await oneRoute.DELETE(req(`/api/account/canvases/${id}`, "DELETE"), ctx(id))).status).toBe(204);+ expect((await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET"), ctx(id))).status).toBe(404);+ await listRoute.POST(req("/api/account/canvases", "POST", { pages: page() }, cookieB));+ await purgeAccount(A);+ const left = db().prepare("SELECT account_id, COUNT(*) AS n FROM account_canvases GROUP BY account_id").all() as { account_id: string; n: number }[];+ expect(left).toEqual([{ account_id: B, n: 1 }]);+ });+});diff --git a/tests/e2e/canvas-public.mjs b/tests/e2e/canvas-public.mjsnew file mode 100644index 00000000..811efdbe--- /dev/null+++ b/tests/e2e/canvas-public.mjs@@ -0,0 +1,252 @@+// The public Canvas, as a guest, a fresh account and the owner, at 390 and 1440 px: "Use this board" opens a ready board+// in the editor with its nodes, links and example film; "New canvas" opens a blank one; a guest's change is kept in the+// browser (it survives a reload at /canvas/draft/<id>) and Save offers an account; an account saves to its account+// (/canvas/saved/<id>), reopens it after a reload, renames and deletes it from /canvas; Run on a visitor's board says+// what running needs and never runs; the owner's "Use this board" makes a studio board. Then the previews: each Canvas+// preview plays its effect's whole clip (currentTime passes 2 s and comes back round: it loops), on /canvas, on a+// board's page and on the board's last step in the editor.+//+// node tests/e2e/canvas-public.mjs <app address> <owner password> [screenshot folder]+// Against `next start` with a fresh data dir, FUOBE_PUBLIC_SIGNUP=1 and COMFYUI_URL pointing at nothing.+import fs from "node:fs";+import path from "node:path";+import { launch, PHONE, DESKTOP } from "./_browser.mjs";++const [app, password, shots] = process.argv.slice(2);+if (!app || !password) throw new Error("usage: node tests/e2e/canvas-public.mjs <app address> <owner password> [screenshot folder]");+if (shots) fs.mkdirSync(shots, { recursive: true });++const BOARD = "effect-chain-pearl-earring";+const failures = [];+const check = (name, ok, detail = "") => {+ console.log(`${ok ? "ok " : "FAIL"} ${name}${detail ? ` (${detail})` : ""}`);+ if (!ok) failures.push(name);+};++async function signIn(ctx, persona) {+ if (persona === "owner") {+ const r = await ctx.request.post(`${app}/api/auth/login`, { data: { password } });+ if (!r.ok()) throw new Error(`owner login ${r.status()}`);+ } else if (persona === "account") {+ const email = `canvas-public-${Date.now()}-${Math.random().toString(36).slice(2, 6)}@example.com`;+ const r = await ctx.request.post(`${app}/api/auth/signup`, { data: { email, password: "canvas-public-pw-123" } });+ if (!r.ok()) throw new Error(`signup ${r.status()}`);+ }+}++/** Every <video> in `scope` sampled for `ms`: the largest time reached, and whether it came back round (a loop). */+async function playback(page, selector, ms = 9000) {+ const seen = new Map();+ const t0 = Date.now();+ while (Date.now() - t0 < ms) {+ const now = await page.evaluate((sel) => [...document.querySelectorAll(sel)].map((v) => ({ src: (v.currentSrc || v.src).split("?")[0].split("/").pop(), t: v.currentTime, d: v.duration })), selector);+ for (const v of now) {+ const s = seen.get(v.src) ?? { max: 0, last: 0, loops: 0, d: v.d };+ if (v.t + 0.5 < s.last) s.loops++;+ s.max = Math.max(s.max, v.t);+ s.last = v.t;+ s.d = v.d;+ seen.set(v.src, s);+ }+ await page.waitForTimeout(200);+ }+ return [...seen.entries()].map(([src, s]) => ({ src, ...s }));+}++const browser = await launch();+try {+ for (const persona of ["guest", "account", "owner"]) {+ for (const [size, device] of [+ ["1440", DESKTOP],+ ["390", PHONE],+ ]) {+ const tag = `${persona} ${size}`;+ const phone = size === "390";+ const ctx = await browser.newContext({ ...device, colorScheme: size === "390" ? "dark" : "light" });+ await signIn(ctx, persona);+ const page = await ctx.newPage();+ page.setDefaultTimeout(30_000);+ const errors = [];+ page.on("pageerror", (e) => errors.push(`${page.url()} :: ${String(e).slice(0, 200)}`));+ page.on("console", (m) => m.type() === "error" && /hydrat/i.test(m.text()) && errors.push(`hydration: ${m.text().slice(0, 200)}`));+ const runs = [];+ page.on("request", (r) => /\/api\/(canvases\/[^/]+\/run|generations)$/.test(new URL(r.url()).pathname) && r.method() === "POST" && runs.push(r.url()));+ const shot = async (name) => shots && page.screenshot({ path: path.join(shots, `${name}--${persona}--${size}.png`) });+ const sideways = () => page.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);++ // ---- /canvas: every ready board's action opens it in the editor+ await page.goto(`${app}/canvas`, { waitUntil: "load", timeout: 180_000 });+ await page.getByRole("heading", { name: persona === "owner" ? "Canvas" : "What's a canvas?", exact: true }).first().waitFor();+ await page.waitForTimeout(1200);+ if (persona !== "owner") {+ const use = page.locator(`#templates article a[href='/canvas/try/${BOARD}']`);+ check(`${tag}: a ready board's card says Use this board`, (await use.count()) === 1 && /Use this board/.test(await use.innerText()));+ check(`${tag}: New canvas opens a blank board`, (await page.getByRole("link", { name: "New canvas" }).getAttribute("href")) === "/canvas/try/blank");+ await use.click();+ } else {+ await page.goto(`${app}/canvas/try/${BOARD}`, { waitUntil: "load" });+ }++ // ---- The board in the editor+ if (persona === "owner") {+ await page.waitForURL(/\/canvas\/(?!try|start|draft|saved)[^/?]+$/, { timeout: 60_000 });+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });+ check(`${tag}: the owner's Use this board makes a studio board`, (await page.getByRole("button", { name: /^Run all$/ }).count()) === 1);+ await shot("owner-board");+ check(`${tag}: no page errors`, errors.length === 0, errors[0]);+ await ctx.close();+ continue;+ }+ await page.waitForURL(new RegExp(`/canvas/try/${BOARD}$`));+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });+ const nodes = await page.locator(".react-flow__node").count();+ const edges = await page.locator(".react-flow__edge").count();+ if (!phone) check(`${tag}: the board opens with all its nodes and links`, nodes >= 4 && edges >= 3, `${nodes} nodes, ${edges} links`);+ else check(`${tag}: the phone shows the board and says where to wire new steps`, nodes >= 4 && (await page.locator("[data-phone-note]").count()) === 1, `${nodes} nodes`);+ const exampleImgs = await page.locator(".react-flow__node img[src*='/examples/'], .react-flow__node img[src*='/previews/'], .react-flow__node video").count();+ check(`${tag}: the board shows its own example photo and film`, exampleImgs >= 2, `${exampleImgs}`);+ check(`${tag}: no sideways scroll in the editor`, (await sideways()) <= 1, `${await sideways()} px`);+ await shot("try-board");++ // The film on its last step plays its whole clip.+ if (!phone) {+ const vid = page.locator(".react-flow__node video").first();+ if (await vid.count()) {+ await vid.evaluate((v) => {+ v.muted = true;+ v.loop = true;+ return v.play();+ }).catch(() => {});+ const p = await playback(page, ".react-flow__node video", 6000);+ check(`${tag}: the board's example film plays past 2 s`, p.some((x) => x.max > 2), JSON.stringify(p.map((x) => [x.src, +x.max.toFixed(2), +x.d.toFixed(2)])));+ }+ }++ // ---- Run says what running needs, and never runs+ await page.locator("[data-visitor-run]").click();+ await page.getByRole("heading", { name: "Running a board isn't available here" }).waitFor();+ const dlg = await page.getByRole("dialog").innerText();+ check(`${tag}: Run says plainly what it needs, with the one-step effect`, /Video studio/.test(dlg) && (await page.getByRole("dialog").getByRole("link", { name: /Try this effect in Video/ }).count()) === 1);+ check(`${tag}: a guest's Run dialog offers an account`, persona !== "guest" || /Sign up to save boards/.test(dlg));+ await shot("run-needs");+ await page.keyboard.press("Escape");++ // ---- A change keeps the board (in this browser, at /canvas/draft/<id>)+ const nameField = page.getByRole("textbox", { name: "Canvas name" });+ await nameField.fill(`My pearl ${persona} ${size}`);+ await nameField.press("Enter");+ if (phone) {+ await page.getByRole("tab", { name: "Nodes" }).click();+ const field = page.locator("[data-testid^='canvas-card-'] textarea").first();+ await field.fill("A pearl earring, warm window light, a soft smile");+ } else {+ const field = page.locator(".react-flow__node textarea").first();+ await field.fill("A pearl earring, warm window light, a soft smile");+ }+ await page.waitForURL(/\/canvas\/draft\/[^/]+$/, { timeout: 10_000 });+ await page.waitForTimeout(1500);+ const draftUrl = page.url();+ check(`${tag}: the first change keeps the board at /canvas/draft/<id>`, /\/canvas\/draft\//.test(draftUrl), draftUrl);+ await page.reload({ waitUntil: "load" });+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });+ if (phone) await page.getByRole("tab", { name: "Nodes" }).click();+ const kept = await page.locator(phone ? "[data-testid^='canvas-card-'] textarea" : ".react-flow__node textarea").first().inputValue();+ check(`${tag}: the draft survives a reload`, /warm window light/.test(kept) && (await nameField.inputValue()) === `My pearl ${persona} ${size}`, kept.slice(0, 60));+ await shot("draft-reloaded");++ if (persona === "guest") {+ await page.locator("[data-visitor-save]").click();+ await page.getByRole("heading", { name: "Keep this board in an account" }).waitFor();+ const href = await page.getByRole("dialog").getByRole("link", { name: "Sign up" }).getAttribute("href");+ check(`${tag}: Save offers an account and comes back to this board`, /signup=1/.test(href ?? "") && /canvas%2Fdraft/.test(href ?? ""), href);+ await shot("guest-save");+ await page.keyboard.press("Escape");+ await page.goto(`${app}/canvas`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "Your canvases" }).waitFor();+ check(`${tag}: the draft is listed under Your canvases`, (await page.locator("[data-visitor-board='browser']", { hasText: `My pearl ${persona} ${size}` }).count()) === 1);+ await shot("guest-list");+ // A guest can't read or write anyone's saved canvases.+ // (Asked outside the page: a refused fetch in the page opens the sign-up card.)+ const api = [(await page.request.get(`${app}/api/account/canvases`)).status(), (await page.request.post(`${app}/api/account/canvases`, { data: {} })).status(), (await page.request.get(`${app}/api/canvases`)).status()];+ check(`${tag}: a guest gets 401 from the account canvases`, api[0] === 401 && api[1] === 401, JSON.stringify(api));+ // Start blank.+ await page.getByRole("link", { name: "New canvas" }).click();+ await page.waitForURL(/\/canvas\/try\/blank$/);+ await page.getByText(/Wire models together/).waitFor();+ check(`${tag}: New canvas opens an empty editor`, (await page.locator(".react-flow__node").count()) === 0);+ await shot("blank");+ } else {+ // ---- An account saves it to its account, reopens it, renames and deletes it+ await page.locator("[data-visitor-save]").click();+ await page.waitForURL(/\/canvas\/saved\/[^/]+$/, { timeout: 20_000 });+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });+ const savedUrl = page.url();+ if (phone) await page.getByRole("tab", { name: "Nodes" }).click();+ const field = page.locator(phone ? "[data-testid^='canvas-card-'] textarea" : ".react-flow__node textarea").first();+ await field.fill("A pearl earring, saved to my account");+ await page.waitForTimeout(2000);+ await page.reload({ waitUntil: "load" });+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });+ if (phone) await page.getByRole("tab", { name: "Nodes" }).click();+ check(`${tag}: a saved board reopens with its changes`, /saved to my account/.test(await page.locator(phone ? "[data-testid^='canvas-card-'] textarea" : ".react-flow__node textarea").first().inputValue()), savedUrl);+ await shot("saved-board");+ await page.goto(`${app}/canvas`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "Your canvases" }).waitFor();+ const card = page.locator("[data-visitor-board='account']", { hasText: `My pearl ${persona} ${size}` });+ await card.waitFor();+ check(`${tag}: the saved board is listed, and its draft is gone`, (await card.count()) === 1 && (await page.locator("[data-visitor-board='browser']", { hasText: `My pearl ${persona} ${size}` }).count()) === 0);+ await shot("account-list");+ await card.getByRole("button", { name: /^Actions for/ }).click();+ await page.getByRole("menuitem", { name: "Rename" }).click();+ await page.getByRole("dialog").getByRole("textbox").fill(`Renamed ${size}`);+ await page.getByRole("dialog").getByRole("button", { name: "Save" }).click();+ await page.locator("[data-visitor-board='account']", { hasText: `Renamed ${size}` }).waitFor();+ await page.reload({ waitUntil: "load" });+ const renamed = page.locator("[data-visitor-board='account']", { hasText: `Renamed ${size}` });+ await renamed.waitFor();+ check(`${tag}: rename sticks`, (await renamed.count()) === 1);+ await renamed.getByRole("button", { name: /^Actions for/ }).click();+ await page.getByRole("menuitem", { name: "Delete" }).click();+ await page.getByRole("alertdialog").getByRole("button", { name: "Delete" }).click();+ await page.waitForTimeout(1500);+ await page.reload({ waitUntil: "load" });+ await page.waitForTimeout(2500);+ check(`${tag}: delete removes it`, (await page.locator("[data-visitor-board='account']", { hasText: `Renamed ${size}` }).count()) === 0);+ // The owner's canvases stay closed to an account.+ const api = [(await page.request.post(`${app}/api/canvases`, { data: {} })).status()];+ check(`${tag}: an account can't make the owner's canvases`, api[0] === 403, JSON.stringify(api));+ }+ check(`${tag}: nothing was sent to run`, runs.length === 0, runs[0]);++ // ---- Previews play the whole effect: the board's page (hover), and /canvas (by itself)+ if (!phone) {+ await page.goto(`${app}/canvas/start/${BOARD}`, { waitUntil: "load" });+ await page.getByRole("heading", { name: "What goes in" }).waitFor();+ await page.locator(".aspect-\\[16\\/9\\]").first().hover();+ const p = await playback(page, "video", 10_000);+ const film = p.find((x) => /effect-pearl-earring/.test(x.src));+ check(`${tag}: the board's page plays the whole effect, looping`, !!film && film.max > 3 && film.loops >= 1 && film.d >= 3.9, JSON.stringify(film));+ }+ check(`${tag}: no page errors`, errors.length === 0, errors[0]);+ await ctx.close();+ }+ }++ // ---- /canvas cards play by themselves, the whole clip (a fresh guest, a wide screen)+ const ctx = await browser.newContext({ ...DESKTOP });+ const page = await ctx.newPage();+ await page.goto(`${app}/canvas`, { waitUntil: "load" });+ await page.locator("#templates").scrollIntoViewIfNeeded();+ await page.waitForTimeout(1500);+ const p = await playback(page, "#templates video", 10_000);+ check("guest 1440: the board cards play their whole clips, looping", p.length > 0 && p.every((x) => x.max > 2) && p.some((x) => x.loops >= 1), JSON.stringify(p.map((x) => [x.src, +x.max.toFixed(2), x.loops])));+ await ctx.close();+} finally {+ await browser.close();+}++if (failures.length) {+ console.log(`\n${failures.length} check(s) failed`);+ process.exit(1);+}+console.log("\nall checks passed");diff --git a/tests/e2e/canvas-starters.mjs b/tests/e2e/canvas-starters.mjsindex 75593204..a6f3f17f 100644--- a/tests/e2e/canvas-starters.mjs+++ b/tests/e2e/canvas-starters.mjs@@ -73,7 +73,7 @@ try {check(`${tag}: a visitor sees only boards with a real cover`, n > 0 && covered === n, `${covered}/${n}`);check(`${tag}: no model or engine words for a visitor`, !ENGINE_WORDS.test(t), (t.match(ENGINE_WORDS) ?? [""])[0]);check(`${tag}: no "No cover yet" or More templates for a visitor`, !/No cover yet|More templates|Use template/.test(t));- check(`${tag}: the visitor's action is to see how it works`, (await page.getByText("See how it works").count()) === n);+ check(`${tag}: the visitor's action opens the board in the editor`, (await page.locator("#templates a[data-use-board]").count()) === n);check(`${tag}: no "isn't available here" note for a visitor`, !/isn.t available here/.test(t));const firstCard = await cards.first().evaluate((e) => e.getBoundingClientRect().top);const vh = await page.evaluate(() => window.innerHeight);@@ -95,7 +95,8 @@ try {check(`${tag}: the owner can use the board from its page`, (await page.getByRole("button", { name: "Use template" }).count()) === 1);} else {check(`${tag}: no model or engine words on the board's page`, !ENGINE_WORDS.test(pt), (pt.match(ENGINE_WORDS) ?? [""])[0]);- check(`${tag}: the page has no "isn't available here" note, one quiet line instead`, !/isn.t available here/.test(pt) && /One tap opens it with a photo ready/.test(pt));+ check(`${tag}: the page has no "isn't available here" note, one quiet line instead`, !/isn.t available here/.test(pt) && /Opens the board in the editor/.test(pt));+ check(`${tag}: Use this board leads on the board's page`, (await page.getByRole("link", { name: "Use this board" }).getAttribute("href")) === "/canvas/try/effect-chain-pearl-earring");await page.getByRole("link", { name: "Try this effect in Video" }).click();await page.waitForURL(/\/video\?preset=effect-pearl-earring&example=effect-pearl-earring\.1/);await page.getByText("Pearl Earring").first().waitFor({ timeout: 60_000 }).catch(() => {});diff --git a/tests/record-pages.test.ts b/tests/record-pages.test.tsindex 4768d367..39b73168 100644--- a/tests/record-pages.test.ts+++ b/tests/record-pages.test.ts@@ -54,8 +54,10 @@ describe("record pages (real 404s)", () => {walk(app, []);expect(routes.length).toBeGreaterThan(40);// Ids the catalog answers for (apps, hub modes, Canvas templates, ready-made starters' pages), not stored records, and- // share tokens: the proxy checks those itself.- const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/start)\/\[|\/start\/\[id\]$/;+ // share tokens: the proxy checks those itself. A visitor's Canvas boards aren't records either: a ready board is the+ // catalog's (/canvas/try), a draft lives in the browser (/canvas/draft) and an account's board is checked by its API+ // (/canvas/saved).+ const catalog = /^\/(apps|audio|video-tools|upscale|s|canvas\/(start|try|draft|saved))\/\[|\/start\/\[id\]$/;for (const route of routes) {if (!route.includes("[")) {expect(recordForPath(route), route).toBeNull();diff --git a/tests/template-covers.test.ts b/tests/template-covers.test.tsindex ad9da2c3..f7506304 100644--- a/tests/template-covers.test.ts+++ b/tests/template-covers.test.ts@@ -265,8 +265,9 @@ describe.skipIf(!hasFfmpeg)("pnpm eval:covers --templates", () => {});describe("a template cover that rests on its peak", () => {- it("plays only the finished scene around it: a hover and every loop start just before the peak, never at the clip's start", async () => {- const { PEAK_WINDOW, templatePreview } = await import("@/lib/template-covers");+ it("rests on the finished scene and plays the effect's whole published clip, the same one its gallery card plays, looping", async () => {+ const { templatePreview } = await import("@/lib/template-covers");+ const { PRESET_PREVIEWS } = await import("@/lib/preset-previews.generated");const cover = (k: string) => templateCover(k.split("/")[0] as TemplateGroup, k.split("/")[1]);const rests = Object.keys(TEMPLATE_COVERS).filter((k) => cover(k)?.at !== undefined);const withPeak = rests.filter((k) => cover(k)!.poster.startsWith("/previews/presets/peak/"));@@ -278,11 +279,13 @@ describe("a template cover that rests on its peak", () => {for (const key of withPeak) {const [group, id] = key.split("/") as [TemplateGroup, string];const c = templateCover(group, id)!;- const rest = templatePreview(c).rest!;- expect(rest.at, key).toBe(c.at);- expect(rest.from, key).toBeCloseTo(Math.max(0, c.at! - PEAK_WINDOW.before), 3);- expect(rest.from, key).toBeGreaterThan(0);- expect(rest.until, key).toBeCloseTo(c.at! + PEAK_WINDOW.after, 3);+ const p = templatePreview(c);+ // At rest: the finished scene. Playing: the clip from its first frame to its end, looped (no window, no seek).+ expect(p.poster, key).toBe(c.poster);+ expect(p.rest, key).toBeUndefined();+ // The clip is the effect's own published cover clip, the very file (and version) its gallery card plays.+ const effect = /\/previews\/presets\/peak\/([a-z0-9-]+)\.jpg/.exec(c.poster)![1];+ expect(p.video, key).toBe((PRESET_PREVIEWS as Record<string, { video?: string }>)[effect]?.video);// Each canvas clip is 4 s long and its peak is within it.if (group === "canvas") expect(c.at!, key).toBeLessThan(4);}