Skip to content

armgit / fuobe

Public Imported from GitHub
0

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.

Canvas: visitor boards show Example, keep drafts in step, and list saved boards lightly

Adarsh30c5178e0ef6
diff --git a/docs/public-signup.md b/docs/public-signup.md
index 289f61a5..5f470194 100644
--- a/docs/public-signup.md
+++ b/docs/public-signup.md
@@ -96,7 +96,8 @@ An account is signed in, but it sees the owner's studio as a guest does:
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
+ links the Video effect that makes the same film in one step (or the studios); its steps name no
+ price or run state, and a ready board's last step says Example. 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 and
Marketing Studio show their ready-made starters the same way (`<studio>/start/<id>`); making one
diff --git a/src/app/(studio)/canvas/draft/[id]/page.tsx b/src/app/(studio)/canvas/draft/[id]/page.tsx
index 3e28a7fe..72c5cb11 100644
--- a/src/app/(studio)/canvas/draft/[id]/page.tsx
+++ b/src/app/(studio)/canvas/draft/[id]/page.tsx
@@ -7,7 +7,7 @@ export const metadata: Metadata = { title: "Canvas", robots: { index: false, fol
async function Board({ params }: { params: PageProps<"/canvas/draft/[id]">["params"] }) {
const { id } = await params;
- return <DraftBoard id={id} boards={boardExtras()} />;
+ return <DraftBoard key={id} id={id} boards={boardExtras()} />;
}
/** A board kept in this browser (a visitor's draft): its pages are read from the browser, never the server. */
diff --git a/src/app/(studio)/canvas/saved/[id]/page.tsx b/src/app/(studio)/canvas/saved/[id]/page.tsx
index f688747e..4cbd08b1 100644
--- a/src/app/(studio)/canvas/saved/[id]/page.tsx
+++ b/src/app/(studio)/canvas/saved/[id]/page.tsx
@@ -7,7 +7,7 @@ export const metadata: Metadata = { title: "Canvas", robots: { index: false, fol
async function Board({ params }: { params: PageProps<"/canvas/saved/[id]">["params"] }) {
const { id } = await params;
- return <SavedBoard id={id} boards={boardExtras()} />;
+ return <SavedBoard key={id} id={id} boards={boardExtras()} />;
}
/** An account's own canvas: the browser asks /api/account/canvases/<id>, which answers that account only. */
diff --git a/src/components/canvas/canvas-context.tsx b/src/components/canvas/canvas-context.tsx
index 8736b016..fa441d80 100644
--- a/src/components/canvas/canvas-context.tsx
+++ b/src/components/canvas/canvas-context.tsx
@@ -99,6 +99,9 @@ export interface NodeView {
export const EMPTY_VIEW: NodeView = { counts: {}, costUsd: null, step: null, reused: false, results: EMPTY_RESULTS };
+/** The `feature` of the stand-in result a visitor's ready board shows on its last step (its published example). */
+export const EXAMPLE_FEATURE = "canvas-example";
+
/** Board-wide settings the nodes read (they change rarely). */
export interface EditorGlobals {
canvasId: string;
@@ -110,6 +113,8 @@ export interface EditorGlobals {
running: boolean;
/** True when this model would run on the demo provider (no key / no ComfyUI). */
isDemo: (m: ModelDef) => boolean;
+ /** A visitor's board (visitor-canvas.tsx): it never runs here, so nodes show no price and no run state. */
+ visitor?: boolean;
}
export interface EditorSnapshot {
diff --git a/src/components/canvas/canvas-editor.tsx b/src/components/canvas/canvas-editor.tsx
index 4b77c058..8589c2d9 100644
--- a/src/components/canvas/canvas-editor.tsx
+++ b/src/components/canvas/canvas-editor.tsx
@@ -387,7 +387,11 @@ function Editor({ id, initial, view, host }: { id: string; initial: Canvas; view
},
[status],
);
- const globals = useMemo<EditorGlobals>(() => ({ canvasId: id, engine, mode, readOnly: isMobile, running: runM.isPending, isDemo }), [id, engine, mode, isMobile, runM.isPending, isDemo]);
+ const isVisitor = !!host.visitor;
+ const globals = useMemo<EditorGlobals>(
+ () => ({ canvasId: id, engine, mode, readOnly: isMobile, running: runM.isPending, isDemo, visitor: isVisitor }),
+ [id, engine, mode, isMobile, runM.isPending, isDemo, isVisitor],
+ );
const snapshot = useMemo<EditorSnapshot>(() => ({ graph, byId, plan, views, globals }), [graph, byId, plan, views, globals]);
store.prime(snapshot);
useLayoutEffect(() => store.set(snapshot), [store, snapshot]);
@@ -1286,11 +1290,14 @@ function Editor({ id, initial, view, host }: { id: string; initial: Canvas; view
// A Translate (video) on an open-only install dubs in Translate & dub: nothing to fix on the board.
const attention = new Set(plan.errors.filter((e) => e.message !== OPEN_DUB_HINT).map((e) => e.nodeId)).size;
const summary = [
- plan.steps.length
- ? `${plan.steps.length} to run · ${planDemo ? "Placeholder · free" : plan.costUnknown ? "price unknown" : plan.costUsd === 0 ? "Free" : `≈ ${formatCost(plan.costUsd)}`}`
- : generators.length && !attention
- ? "Up to date"
- : "",
+ // A visitor's board doesn't run here: no count of steps to run and no price, only what needs attention.
+ visitor
+ ? ""
+ : plan.steps.length
+ ? `${plan.steps.length} to run · ${planDemo ? "Placeholder · free" : plan.costUnknown ? "price unknown" : plan.costUsd === 0 ? "Free" : `≈ ${formatCost(plan.costUsd)}`}`
+ : generators.length && !attention
+ ? "Up to date"
+ : "",
attention ? `${attention} need${attention === 1 ? "s" : ""} attention` : "",
]
.filter(Boolean)
diff --git a/src/components/canvas/node-list.tsx b/src/components/canvas/node-list.tsx
index 0b977bfe..3c33e714 100644
--- a/src/components/canvas/node-list.tsx
+++ b/src/components/canvas/node-list.tsx
@@ -126,7 +126,8 @@ function NodeCard({ node, index }: { node: CanvasNode; index: number }) {
{gen && (
<>
<p className="text-[12px] text-muted-foreground">
- {model?.name ?? "No model"} · {costLabel(globals.isDemo, model, v.costUsd)}
+ {model?.name ?? "No model"}
+ {!globals.visitor && ` · ${costLabel(globals.isDemo, model, v.costUsd)}`}
</p>
{node.data.prompt !== undefined || node.type === "model" ? (
<textarea
diff --git a/src/components/canvas/nodes.tsx b/src/components/canvas/nodes.tsx
index 0afcae37..5735df78 100644
--- a/src/components/canvas/nodes.tsx
+++ b/src/components/canvas/nodes.tsx
@@ -132,7 +132,7 @@ import { KineticNodeBody } from "./kinetic-node";
import { ExactOrbitControls } from "@/components/exact-orbit-controls";
import { PATH_PRESETS } from "@/lib/camera-path";
import { exactDefaults } from "@/lib/exact-orbit";
-import { NodeIcon, PORT_COLOR, useEditorActions, useEditorGlobals, useEditorSelector, useNodeResults, useNodeView, type EditorSnapshot, type NodeResults } from "./canvas-context";
+import { EXAMPLE_FEATURE, NodeIcon, PORT_COLOR, useEditorActions, useEditorGlobals, useEditorSelector, useNodeResults, useNodeView, type EditorSnapshot, type NodeResults } from "./canvas-context";
/** A node on the board: a graph node, or a group, comment pin or drawing (./board.tsx). */
export type FlowNode = Node<CanvasNodeData, CanvasNodeType | BoardType>;
@@ -796,23 +796,27 @@ const GeneratorNode = memo(function GeneratorNode({ id, type: flowType, data, se
const [addWords, setAddWords] = useState(false);
const showPrompt = !!promptPort && (!v.counts.prompt || !!data.prompt || addWords);
const step = v.step;
+ // A ready board's last step on a visitor's board shows the board's published example until it is changed.
+ const example = !!g.visitor && r.outputs[0]?.g.feature === EXAMPLE_FEATURE;
const stateHint = data.pinned
? "Pinned"
: running
? "Running"
: step === "changed"
? "Changed"
- : r.state === "failed"
- ? "Failed"
- : r.state === "canceled"
- ? "Canceled"
- : step === "upstream"
- ? "Inputs changed"
- : step
- ? "Not run yet"
- : v.reused
- ? "Up to date"
- : "";
+ : example
+ ? "Example"
+ : r.state === "failed"
+ ? "Failed"
+ : r.state === "canceled"
+ ? "Canceled"
+ : step === "upstream"
+ ? "Inputs changed"
+ : step
+ ? "Not run yet"
+ : v.reused
+ ? "Up to date"
+ : "";
return (
<NodeShell
@@ -839,7 +843,7 @@ const GeneratorNode = memo(function GeneratorNode({ id, type: flowType, data, se
footer={
<div className="flex h-10 items-center gap-2 border-t px-3">
<span className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground">
- {[stateHint, step || r.state === "idle" ? costLabel(g.isDemo, model, v.costUsd) : ""].filter(Boolean).join(" · ")}
+ {[stateHint, !g.visitor && (step || r.state === "idle") ? costLabel(g.isDemo, model, v.costUsd) : ""].filter(Boolean).join(" · ")}
</span>
{!g.readOnly && (
<Tooltip>
diff --git a/src/components/canvas/use-canvas.ts b/src/components/canvas/use-canvas.ts
index 5bf822cc..df39f8fe 100644
--- a/src/components/canvas/use-canvas.ts
+++ b/src/components/canvas/use-canvas.ts
@@ -166,7 +166,7 @@ export function useAccountCanvas(id: string, { enabled }: { enabled: boolean })
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 })),
+ json<{ id: string; name: string; updatedAt: number }>(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-canvas.tsx b/src/components/canvas/visitor-canvas.tsx
index 983544a8..22a4c4cf 100644
--- a/src/components/canvas/visitor-canvas.tsx
+++ b/src/components/canvas/visitor-canvas.tsx
@@ -4,7 +4,7 @@ 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 { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
import { NotFoundState } from "@/components/empty-state";
import { Button } from "@/components/ui/button";
@@ -14,9 +14,10 @@ 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 { deleteDraft, draftName, 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 { EXAMPLE_FEATURE } from "./canvas-context";
import { accountCanvasApi, useAccountCanvas, useCanvasActions, type CanvasView } from "./use-canvas";
/**
@@ -54,7 +55,7 @@ function exampleView(c: Canvas, example: VisitorBoardData["example"]): CanvasVie
const g = {
id,
batchId: null,
- feature: "canvas-example",
+ feature: EXAMPLE_FEATURE,
presetId: null,
modelId: "",
engine: "open",
@@ -178,8 +179,8 @@ function VisitorEditor({
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>;
+ /** An account's board not saved to it yet: Save moves it there (`saved` runs once the account has it). */
+ saveToAccount?: (now: BoardNow, saved: () => void) => Promise<void>;
example?: VisitorBoardData["example"];
oneStep?: VisitorBoardData["oneStep"];
}) {
@@ -187,6 +188,9 @@ function VisitorEditor({
const [signUpOpen, setSignUpOpen] = useState(false);
const [saving, setSaving] = useState(false);
const isMobile = useIsMobile();
+ // Saved to the account: this browser stops keeping the board (the editor's last flush as it closes would make it
+ // again, as a second board, and move the address back to it).
+ const moved = useRef(false);
const keepRef = useRef({ keep, rename, saveToAccount });
useEffect(() => {
keepRef.current = { keep, rename, saveToAccount };
@@ -197,7 +201,7 @@ function VisitorEditor({
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>
+ <Cloud /> Save
</Button>
);
if (!keepRef.current.saveToAccount) return null;
@@ -209,13 +213,14 @@ function VisitorEditor({
data-visitor-save
onClick={() => {
setSaving(true);
- void keepRef.current.saveToAccount!(now()).catch((e) => {
+ void keepRef.current.saveToAccount!(now(), () => (moved.current = true)).catch((e) => {
toastError(e);
setSaving(false);
});
}}
>
- {saving ? <Loader2 className="animate-spin" /> : <Cloud />} <span className="max-sm:sr-only">Save to account</span>
+ {saving ? <Loader2 className="animate-spin" /> : <Cloud />} <span className="sm:hidden">Save</span>
+ <span className="max-sm:hidden">Save to account</span>
</Button>
);
},
@@ -223,8 +228,8 @@ function VisitorEditor({
);
const host = useMemo<BoardHost>(
() => ({
- save: (pages, keepalive) => keepRef.current.keep(pages, keepalive),
- rename: (name) => keepRef.current.rename(name),
+ save: async (pages, keepalive) => void (moved.current || (await keepRef.current.keep(pages, keepalive))),
+ rename: async (name) => void (moved.current || (await keepRef.current.rename(name))),
visitor: {
savedLabel,
run: () => setRunOpen(true),
@@ -248,8 +253,9 @@ function useSaveToAccount(draftId: () => string | null) {
const router = useRouter();
const qc = useQueryClient();
return useCallback(
- async (now: BoardNow, templateId: string | null) => {
+ async (now: BoardNow, templateId: string | null, saved: () => void) => {
const c = await accountCanvasApi.create({ name: now.name, templateId, pages: now.pages });
+ saved();
const d = draftId();
if (d) deleteDraft(d);
void qc.invalidateQueries({ queryKey: ["account-canvases"], exact: true });
@@ -268,6 +274,8 @@ function draftKeeper(id: string, base: { name: string; templateId: string | null
return {
keep: async (p: CanvasPage[]) => {
pages = p;
+ // A rename from the Canvas list while this board was open stays.
+ name = draftName(id) ?? name;
put();
},
rename: async (n: string) => {
@@ -328,25 +336,20 @@ export function TryBoard({ board }: { board: VisitorBoardData }) {
await keepFirst().rename(name);
afterFirst();
}}
- saveToAccount={who === "account" ? (now) => saveToAccount(now, board.templateId) : undefined}
+ saveToAccount={who === "account" ? (now, saved) => saveToAccount(now, board.templateId, saved) : 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,
- );
+ // Read as this page opens, so it is the board as last kept (the server can't see this browser's storage, and the
+ // page shows a skeleton until hydrated, so what the server drew and the first render match).
+ const [draft] = useState(() => getDraft(id));
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]);
@@ -365,20 +368,13 @@ export function DraftBoard({ id, boards }: { id: string; boards: Record<string,
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}
+ saveToAccount={who === "account" ? (now, saved) => saveToAccount(now, draft.templateId, saved) : 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();
diff --git a/src/lib/canvas-drafts.ts b/src/lib/canvas-drafts.ts
index b715f087..422c6551 100644
--- a/src/lib/canvas-drafts.ts
+++ b/src/lib/canvas-drafts.ts
@@ -62,6 +62,11 @@ export function listDrafts(): DraftSummary[] {
return readIndex().sort((a, b) => b.updatedAt - a.updatedAt);
}
+/** A draft's name as last kept (the list may rename it while the board is open), or null. */
+export function draftName(id: string): string | null {
+ return readIndex().find((d) => d.id === id)?.name ?? null;
+}
+
export function getDraft(id: string): CanvasDraft | null {
if (!isDraftId(id)) return null;
try {
diff --git a/src/server/account-canvas.ts b/src/server/account-canvas.ts
index e188b106..fee60507 100644
--- a/src/server/account-canvas.ts
+++ b/src/server/account-canvas.ts
@@ -1,6 +1,6 @@
import "server-only";
import { nanoid } from "nanoid";
-import { outline, type CanvasSummary } from "@/lib/catalog/canvas";
+import { outline, type CanvasSummary, type Outline } from "@/lib/catalog/canvas";
import { FIRST_PAGE_ID, pageName, readPages, type CanvasPage } from "@/lib/catalog/canvas-board";
import { db } from "./db";
@@ -30,6 +30,22 @@ interface Row {
template_id: string | null;
created_at: number;
updated_at: number;
+ /** What its list shows (Summary), kept with each save so the list never reads every board's pages. */
+ summary_json: string | null;
+}
+
+/** A board's line in its list. */
+interface Summary {
+ nodeCount: number;
+ pageCount: number;
+ outline: Outline;
+}
+
+/** What a save answers: the board's name and when it changed (the editor keeps its pages). */
+export interface AccountCanvasSaved {
+ id: string;
+ name: string;
+ updatedAt: number;
}
/** An account's board as the editor opens it. */
@@ -69,23 +85,33 @@ function pagesJson(pages: CanvasPage[]): string {
return json;
}
+const summaryJson = (pages: CanvasPage[]): string =>
+ JSON.stringify({ nodeCount: pages.reduce((n, p) => n + p.graph.nodes.length, 0), pageCount: pages.length, outline: outline(pages[0].graph) } satisfies Summary);
+
+/** A board's summary; a row saved before summaries were kept gets one now, from its pages (once). */
+function summaryOf(accountId: string, r: Pick<Row, "id" | "summary_json">): Summary {
+ if (r.summary_json) return JSON.parse(r.summary_json) as Summary;
+ const row = db().prepare("SELECT pages_json FROM account_canvases WHERE id = ? AND account_id = ?").get(r.id, accountId) as Pick<Row, "pages_json"> | undefined;
+ const json = summaryJson(readPages(JSON.parse(row?.pages_json ?? "{}")));
+ db().prepare("UPDATE account_canvases SET summary_json = ? WHERE id = ? AND account_id = ?").run(json, r.id, accountId);
+ return JSON.parse(json) as Summary;
+}
+
+/** The account's boards, newest first: each one's summary, never its pages. */
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,
- };
- });
+ const rows = db()
+ .prepare("SELECT id, name, template_id, created_at, updated_at, summary_json FROM account_canvases WHERE account_id = ? ORDER BY updated_at DESC LIMIT ?")
+ .all(accountId, ACCOUNT_CANVAS_LIMITS.boards) as Omit<Row, "account_id" | "pages_json">[];
+ return rows.map((r) => ({
+ id: r.id,
+ name: r.name,
+ ...summaryOf(accountId, r),
+ templateId: r.template_id,
+ preview: null,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ editedAt: r.updated_at,
+ }));
}
/** One of the account's boards, or null (another account's board, or none, reads the same). */
@@ -107,6 +133,7 @@ export function createAccountCanvas(accountId: string, input: { name?: string; p
template_id: input.templateId?.slice(0, 60) ?? null,
created_at: now,
updated_at: now,
+ summary_json: summaryJson(pages),
};
db()
.prepare(`INSERT INTO account_canvases (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((k) => `@${k}`).join(", ")})`)
@@ -114,14 +141,23 @@ export function createAccountCanvas(accountId: string, input: { name?: string; p
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);
+/**
+ * A new name and/or pages for one of the account's boards; null when it has no such board. Only what changed is
+ * written, and the answer is small (the editor's autosave sends here often).
+ */
+export function updateAccountCanvas(accountId: string, id: string, patch: { name?: string; pages?: CanvasPage[] }): AccountCanvasSaved | null {
+ const name = patch.name?.trim() ? cleanName(patch.name, "") : null;
+ const pages = patch.pages?.length ? patch.pages : null;
+ const json = pages ? pagesJson(pages) : null;
+ const now = Date.now();
+ const done = db()
+ .prepare(
+ "UPDATE account_canvases SET name = COALESCE(?, name), pages_json = COALESCE(?, pages_json), summary_json = COALESCE(?, summary_json), updated_at = ? WHERE id = ? AND account_id = ?",
+ )
+ .run(name, json, pages && summaryJson(pages), now, id, accountId);
+ if (!done.changes) return null;
+ const r = db().prepare("SELECT name FROM account_canvases WHERE id = ? AND account_id = ?").get(id, accountId) as Pick<Row, "name">;
+ return { id, name: r.name, updatedAt: now };
}
export function deleteAccountCanvas(accountId: string, id: string): boolean {
diff --git a/src/server/db.ts b/src/server/db.ts
index 13bb1435..5301c583 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1068,6 +1068,10 @@ function open(): Database.Database {
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);
+ // Its list reads this small summary, never every board's pages (a table made before it had the column gets it).
+ if (!(db.prepare("PRAGMA table_info(account_canvases)").all() as { name: string }[]).some((c) => c.name === "summary_json")) {
+ addColumn(db, "ALTER TABLE account_canvases ADD COLUMN summary_json TEXT");
+ }
// 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");
@@ -1093,7 +1097,8 @@ const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases (
pages_json TEXT NOT NULL,
template_id TEXT,
created_at INTEGER NOT NULL,
- updated_at INTEGER NOT NULL
+ updated_at INTEGER NOT NULL,
+ summary_json TEXT
);
CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;
diff --git a/tests/canvas-public.test.ts b/tests/canvas-public.test.ts
index 82688e08..3a5622b3 100644
--- a/tests/canvas-public.test.ts
+++ b/tests/canvas-public.test.ts
@@ -144,9 +144,22 @@ describe("an account's own canvases", () => {
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 } }[] } }[] };
+ // A save answers small: the name and when it changed, not the pages.
+ expect(await r2.json()).toEqual({ id, name: "Renamed", updatedAt: expect.any(Number) });
+ const c = (await (await oneRoute.GET(req(`/api/account/canvases/${id}`, "GET"), ctx(id))).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");
+ // The list reads the summary kept with the save.
+ const list = (await (await listRoute.GET(req("/api/account/canvases", "GET"))).json()) as { items: { id: string; nodeCount: number; outline: { boxes: unknown[] } }[] };
+ expect(list.items[0]).toEqual(expect.objectContaining({ id, nodeCount: 1 }));
+ expect(list.items[0].outline.boxes).toHaveLength(1);
+ });
+
+ it("lists a board saved before summaries were kept, and keeps its summary from then on", async () => {
+ db().prepare("UPDATE account_canvases SET summary_json = NULL WHERE id = ?").run(id);
+ const list = (await (await listRoute.GET(req("/api/account/canvases", "GET"))).json()) as { items: { id: string; nodeCount: number }[] };
+ expect(list.items.find((x) => x.id === id)).toEqual(expect.objectContaining({ nodeCount: 1 }));
+ expect((db().prepare("SELECT summary_json FROM account_canvases WHERE id = ?").get(id) as { summary_json: string | null }).summary_json).toContain('"nodeCount":1');
});
it("is another account's to neither read, change nor delete (it reads as not found), and a guest's to none", async () => {
diff --git a/tests/e2e/canvas-public.mjs b/tests/e2e/canvas-public.mjs
index 811efdbe..b420dd16 100644
--- a/tests/e2e/canvas-public.mjs
+++ b/tests/e2e/canvas-public.mjs
@@ -105,6 +105,10 @@ try {
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}`);
+ // A visitor's board doesn't run here: its film says Example, and no step names a price, a GPU or a run state.
+ const nodeText = (await page.locator(".react-flow__node").allInnerTexts()).join(" | ");
+ const header = await page.locator("header").filter({ has: page.locator("[data-visitor-run]") }).innerText();
+ check(`${tag}: the film says Example, with no price or run state`, /\bExample\b/.test(nodeText) && !/your GPU|Inputs changed|≈ \$/.test(nodeText) && !/to run/.test(header), header.replace(/\s+/g, " ").slice(0, 120));
check(`${tag}: no sideways scroll in the editor`, (await sideways()) <= 1, `${await sideways()} px`);
await shot("try-board");
@@ -165,6 +169,20 @@ try {
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");
+ // Renamed in the list, the draft opens with its new name.
+ const dcard = page.locator("[data-visitor-board='browser']", { hasText: `My pearl ${persona} ${size}` });
+ await dcard.getByRole("button", { name: /^Actions for/ }).click();
+ await page.getByRole("menuitem", { name: "Rename" }).click();
+ await page.getByRole("dialog").getByRole("textbox").fill(`Draft renamed ${size}`);
+ await page.getByRole("dialog").getByRole("button", { name: "Save" }).click();
+ const rcard = page.locator("[data-visitor-board='browser']", { hasText: `Draft renamed ${size}` });
+ await rcard.waitFor();
+ await rcard.locator("a").first().click();
+ await page.waitForURL(/\/canvas\/draft\/[^/]+$/);
+ await page.getByText("Set the scene").first().waitFor({ timeout: 60_000 });
+ check(`${tag}: a draft renamed in the list opens with its new name`, (await nameField.inputValue()) === `Draft renamed ${size}`, await nameField.inputValue());
+ await page.goto(`${app}/canvas`, { waitUntil: "load" });
+ await page.getByRole("heading", { name: "Your canvases" }).waitFor();
// 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()];
@@ -177,12 +195,16 @@ try {
await shot("blank");
} else {
// ---- An account saves it to its account, reopens it, renames and deletes it
+ // An edit just before Save (still waiting to be kept) goes with it, and leaves no second board in this browser.
+ const field = page.locator(phone ? "[data-testid^='canvas-card-'] textarea" : ".react-flow__node textarea").first();
+ await field.fill("A pearl earring, saved at once");
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 });
+ await page.waitForTimeout(1500);
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();
+ check(`${tag}: Save to account takes the last edit and stays on the saved board`, /\/canvas\/saved\//.test(page.url()) && /saved at once/.test(await field.inputValue()), page.url());
await field.fill("A pearl earring, saved to my account");
await page.waitForTimeout(2000);
await page.reload({ waitUntil: "load" });