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
Buttons say what they cost, and accounts delete for good
Adarsh2757e4b41ce3
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 1d6d8698..0eebe413 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -91,7 +91,8 @@ An account is signed in, but it sees the owner's studio as a guest does:(`GET /api/generations`), and it can open, cancel and delete them and download their files. Theystay out of the owner's Library and live feed, and no other account can open them. The studio'sowner can see them, open their files and delete them ([Managing accounts](#managing-accounts));- the sign-up form says so. An account's delete is for good (it has no Trash), so its space comes+ the sign-up form says so. An account's delete is for good (it has no Trash): a result's ⋯ menu and the+ Library's selection bar say **Delete for good…** and ask first, and its space comesback at once. The live-updates stream isn't sent to accounts: their studios poll instead.- **Its own uploads are its own.** Only the account that uploaded a file can use it in a run, andno other account can open it. See [Uploads](#uploads).diff --git a/src/app/providers.tsx b/src/app/providers.tsxindex e921e06d..baaecd2d 100644--- a/src/app/providers.tsx+++ b/src/app/providers.tsx@@ -5,6 +5,7 @@ import { ThemeProvider } from "next-themes";import { useEffect, useState } from "react";import dynamic from "next/dynamic";import { GuestPrompt } from "@/components/guest-prompt";+import { DeleteForGoodHost } from "@/components/studio/delete-for-good";import { AddKeyPrompt } from "@/components/keys/your-keys";import { toast } from "sonner";import { AUTH_CHANNEL, takeNotice, type ViewerInfo } from "@/lib/api";@@ -57,6 +58,7 @@ export function Providers({ children }: { children: React.ReactNode }) {{/* Below the top bar on a desktop (56 px and a gap), near the top on a phone (its tabs are at the bottom). */}<Toaster position="top-center" gap={8} offset={{ top: 68 }} mobileOffset={{ top: 12 }} /><GuestPrompt />+ <DeleteForGoodHost /><AddKeyPrompt /><BillingCard /><GuidedFixHost />diff --git a/src/components/any-angle/any-angle-tool.tsx b/src/components/any-angle/any-angle-tool.tsxindex 86250af7..e96ff6aa 100644--- a/src/components/any-angle/any-angle-tool.tsx+++ b/src/components/any-angle/any-angle-tool.tsx@@ -39,7 +39,7 @@ import type { Generation, GenerationRequest } from "@/lib/catalog/types";import { downloadHref } from "@/lib/library";import { presetCover } from "@/lib/preset-covers";import { toastError } from "@/lib/refusals";-import { againWhere, placeholdersOn } from "@/lib/demo-mode";+import { againPrice, againWhere, placeholdersOn } from "@/lib/demo-mode";import { cn } from "@/lib/utils";/**@@ -348,7 +348,7 @@ function ShotCard({ g, original, onAgain }: { g: Generation; original: string; o{(out || g.status === "failed") && (<Button variant="outline" size="sm" className="rounded-full" onClick={() => onAgain(g)}><RefreshCw className="size-3.5" /> {out ? "Make another" : "Try again"}- {againWhere(g, { placeholders })}+ {againWhere(g, { placeholders }, againPrice([g]))}</Button>)}{out && (diff --git a/src/components/assist/run-skill-dialog.tsx b/src/components/assist/run-skill-dialog.tsxindex e86caf8f..96843601 100644--- a/src/components/assist/run-skill-dialog.tsx+++ b/src/components/assist/run-skill-dialog.tsx@@ -238,7 +238,7 @@ function Loaded({ view, onClose, examples, intro, csv: rowsCsv }: { view: RecipeNeeds a new test run: {recheck[0]}</Notice>) : null}- {recipe.source?.demo && !Object.values(recipe.verified ?? {}).some((v) => v?.real) && <Notice tone="info">{DEMO_NOTE}.</Notice>}+ {recipe.source?.demo && !view.madeReal && !Object.values(recipe.verified ?? {}).some((v) => v?.real) && <Notice tone="info">{DEMO_NOTE}.</Notice>}{problems.length > 0 && (<div role="alert" className="space-y-1 rounded-xl bg-destructive/10 px-3 py-2 text-[13px] text-destructive">{problems.slice(0, 6).map((p, i) => (diff --git a/src/components/cinema/scene-actions.tsx b/src/components/cinema/scene-actions.tsxindex 60cba9b7..596f7604 100644--- a/src/components/cinema/scene-actions.tsx+++ b/src/components/cinema/scene-actions.tsx@@ -47,7 +47,9 @@ export function usePlanPrice(plan: CinemaPlan): { cost: number | null; label: stconst status = useStatus().data;const demo = placeholdersOn(status?.demoMode);const cost = demo ? 0 : plan.costUsd;- return { cost, demo, label: demo ? "Placeholder · free" : cost === 0 ? "Free" : cost != null ? `≈ ${formatCost(cost)}` : "Price unknown" };+ // Free on the GPU says where it runs, like every other price on it.+ const free = plan.model.engine === "open" ? "Free · your GPU" : "Free";+ return { cost, demo, label: demo ? "Placeholder · free" : cost === 0 ? free : cost != null ? `≈ ${formatCost(cost)}` : "Price unknown" };}const SKIP_KEY = "fuobe.cinema.sceneConfirm";diff --git a/src/components/cinema/soul-builders.tsx b/src/components/cinema/soul-builders.tsxindex 2caf69cc..ac3159f7 100644--- a/src/components/cinema/soul-builders.tsx+++ b/src/components/cinema/soul-builders.tsx@@ -199,10 +199,11 @@ function useBuilderRun(projectId: string) {return { generate, results, setIds, current };}-function CostLabel({ plan }: { plan: { costUsd: number | null } }) {+/** A builder's price: "Free · your GPU" on the GPU, like every other price on it. */+function CostLabel({ plan }: { plan: { costUsd: number | null; model: { engine: Engine } } }) {const status = useStatus().data;const demo = placeholdersOn(status?.demoMode);- return <span className="font-mono text-[12px] whitespace-nowrap text-muted-foreground">{demo ? "Placeholder · free" : plan.costUsd === 0 ? "Free" : plan.costUsd != null ? `≈ ${formatCost(plan.costUsd)}` : ""}</span>;+ return <span className="font-mono text-[12px] whitespace-nowrap text-muted-foreground">{demo ? "Placeholder · free" : plan.costUsd === 0 ? (plan.model.engine === "open" ? "Free · your GPU" : "Free") : plan.costUsd != null ? `≈ ${formatCost(plan.costUsd)}` : ""}</span>;}function SaveElement({ kind, defaultName, picked, description, onSaved }: { kind: "character" | "location"; defaultName: string; picked: string[]; description: string; onSaved: () => void }) {diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 193a1b79..7f875b2a 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -1284,6 +1284,11 @@ function RunPanel({ run, onAgain, finish = [], onFinish }: { run: Run; onAgain:const byId = useMemo(() => new Map((list ?? []).map((g) => [g.id, g])), [list]);const final = byId.get(run.final);const placeholders = placeholdersOn(useStatus().data?.demoMode);+ // Run again sends the run's own request again (a new seed): on the cloud it says that request's price, from the same+ // estimate the Generate button showed ("· paid" until it's known, or when it can't be priced).+ const priced = !!final && final.engine !== "open" && final.place !== "pool" && !placeholders;+ const againEst = useGenjutsuEstimate(priced ? run.body : null);+ const againCost = againEst.data && !againEst.isError && !againEst.data.demo ? againEst.data.costUsd : null;const rows: StepRow[] = run.ids.map((id) => {const g = byId.get(id);return { key: id, label: g?.request.step?.label ?? "A step", g };@@ -1315,7 +1320,7 @@ function RunPanel({ run, onAgain, finish = [], onFinish }: { run: Run; onAgain:{(out || state.status === "failed") && (<Button size="sm" variant="outline" className="rounded-full" onClick={onAgain}><RotateCcw className="size-3.5" /> {state.status === "failed" ? "Try again" : "Run again"}- {againWhere(final, { placeholders })}+ {againWhere(final, { placeholders }, againCost)}</Button>)}</div>diff --git a/src/components/katana/katana-studio.tsx b/src/components/katana/katana-studio.tsxindex 8d53338b..facf49fa 100644--- a/src/components/katana/katana-studio.tsx+++ b/src/components/katana/katana-studio.tsx@@ -21,9 +21,9 @@ import { Panel, ToolHero, ToolShell } from "@/components/av/tool-shell";import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";import { useEngine, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";-import { againWhere, placeholdersOn } from "@/lib/demo-mode";+import { againPrice, againWhere, placeholdersOn } from "@/lib/demo-mode";import { formatCueTime } from "@/lib/av/cue-edit";-import { detectCutIndices, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, OPEN_KEYFRAME_PHOTOS, planSegments, refineCut, refineTimes, type KatanaJobView, type Segment } from "@/lib/av/katana";+import { againKeys, detectCutIndices, KATANA_LIMITS, katanaProgress, katanaStage, motionModel, MOTION_MODELS, nearestAspect, OPEN_KEYFRAME_PHOTOS, planSegments, refineCut, refineTimes, type KatanaJobView, type Segment } from "@/lib/av/katana";import { keepOffered, offered } from "@/lib/model-access";import type { ExampleRowData } from "@/lib/examples/types";import { cn } from "@/lib/utils";@@ -356,7 +356,11 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {const { remove, retry } = useKatanaActions();// A run again is a new run: where it runs (or that it's paid) is said on the button before the tap.const placeholders = placeholdersOn(useStatus().data?.demoMode);- const where = (j: KatanaJobView) => againWhere(j, { placeholders });+ // On the cloud it says the price: the estimates of the steps it makes again (all of them, or the failed ones and after).+ const where = (j: KatanaJobView, all: boolean) => {+ const keys = j.engine === "open" || placeholders ? null : againKeys(j, all);+ return againWhere(j, { placeholders }, keys && againPrice(keys.map((k) => j.generations[j.steps[k]])));+ };const again = (id: string, all: boolean) =>retry.mutate({ id, all },@@ -389,8 +393,9 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {{out ? <video src={out.url} controls playsInline preload="metadata" className="size-full object-contain" /> : <div className="grid size-full place-items-center text-muted-foreground">{stage === "failed" ? <Film className="size-6" /> : <Loader2 className="size-6 animate-spin" />}</div>}</div><div className="min-w-0">- <div className="flex min-w-0 items-center gap-2">- <p className="min-w-0 flex-1 truncate text-[15px] font-medium">{j.title}</p>+ {/* On a phone the title has its own line, so the buttons (Run again says its price) never squeeze it away. */}+ <div className="flex min-w-0 flex-wrap items-center gap-2 sm:flex-nowrap">+ <p className="min-w-0 flex-1 truncate text-[15px] font-medium max-sm:basis-full">{j.title}</p>{out && (<Button asChild variant="outline" size="sm" className="rounded-full"><a href={out.url} download={`${j.title}.mp4`}>@@ -401,7 +406,7 @@ function Runs({ jobs, loading }: { jobs?: KatanaJobView[]; loading: boolean }) {{stage !== "running" && (<Button variant="ghost" size="sm" className="rounded-full" disabled={retry.isPending} onClick={() => again(j.id, stage === "done")}><RotateCcw className="size-3.5" /> {stage === "failed" ? "Retry failed steps" : "Run again"}- {where(j)}+ {where(j, stage === "done")}</Button>)}<AlertDialog>diff --git a/src/components/library-view.tsx b/src/components/library-view.tsxindex 9b2680bc..5138a4be 100644--- a/src/components/library-view.tsx+++ b/src/components/library-view.tsx@@ -11,6 +11,7 @@ import { SkillSuggestions } from "@/components/skills/skill-suggestions";import { FolderDialog, FolderHeader, FolderStrip, MoveMenuItems } from "@/components/library/folders";import { ReviewMenuItems } from "@/components/library/review";import { UploadDeleteProvider } from "@/components/library/upload-delete";+import { askDeleteForGood } from "@/components/studio/delete-for-good";import { useViewPrefs, ViewOptions, type ViewPrefs } from "@/components/library/view-options";import { openAddKey } from "@/components/keys/your-keys";import { PageShell } from "@/components/page-shell";@@ -937,6 +938,16 @@ function Inner({ starters: given }: { starters: StarterCardData[] }) {/></>)}+ {/* An account has no Trash: what it deletes goes for good, so it says so and asks first. */}+ {account && !owner && !uploadsTab && (+ <BarButton+ icon={Trash2}+ label="Delete for good…"+ destructive+ disabled={!selectedGens.some((g) => g.feature !== "upload")}+ onClick={() => askDeleteForGood(selectedGens.filter((g) => g.feature !== "upload"), clear)}+ />+ )}</>)}<span className="mx-1 h-5 w-px shrink-0 bg-border" />diff --git a/src/components/mixed-media/mixed-studio.tsx b/src/components/mixed-media/mixed-studio.tsxindex a1c14048..81f06b1b 100644--- a/src/components/mixed-media/mixed-studio.tsx+++ b/src/components/mixed-media/mixed-studio.tsx@@ -15,7 +15,8 @@ import { LookCard } from "@/components/shorts/preset-card";import { useSubmitGuard } from "@/components/shorts/hooks";import { ClipBar, ClipDrop, costText, Field, Segmented, tabKeys } from "@/components/shorts/ui";import { clipDuration, clipSize, useSourceClip } from "@/components/shorts/use-source-clip";-import { uploadFile, useEngine, useLikelyVisitor, useModelAccess } from "@/lib/api";+import { uploadFile, useEngine, useLikelyVisitor, useModelAccess, useStatus } from "@/lib/api";+import { paidSuffix, placeholdersOn } from "@/lib/demo-mode";import { keepOffered, offered } from "@/lib/model-access";import {clampFps,@@ -429,6 +430,10 @@ function Editor({: null;const estimate = useMixedEstimate(body);const est = estimate.data;+ // The preview frame is a run of its own: on the cloud its button says its price (the estimate's, per frame), else "· paid";+ // nothing on your GPU (free) or while placeholders are on.+ const placeholders = placeholdersOn(useStatus().data?.demoMode);+ const previewPaid = cloud && !visitor && !(est ? est.demo : placeholders) ? paidSuffix(est?.previewUsd) : "";// A new clip, preset or engine starts without a preview (and so does another frame editor: the preview is its own work).const key = `${preset?.id}|${clip?.preview}|${engine}|${mode === "fast" ? "" : modelId}`;@@ -699,7 +704,10 @@ function Editor({)}>{previewBusy ? <Loader2 className="size-4 animate-spin" /> : <ImageIcon className="size-4" />}- {preview ? "Generate another preview frame" : "Generate preview frame"}+ <span>+ {preview ? "Generate another preview frame" : "Generate preview frame"}+ {previewPaid}+ </span></button></div>diff --git a/src/components/photodump/results.tsx b/src/components/photodump/results.tsxindex 94c5e101..aa6ca05d 100644--- a/src/components/photodump/results.tsx+++ b/src/components/photodump/results.tsx@@ -6,7 +6,8 @@ import { useMemo, useState } from "react";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";import { MediaThumb, PendingTile } from "@/components/studio/feed";import { Viewer } from "@/components/studio/viewer";-import { useGenerationActions } from "@/lib/api";+import { askDeleteForGood } from "@/components/studio/delete-for-good";+import { useGenerationActions, useIsAccount } from "@/lib/api";import type { Generation, OutputFile } from "@/lib/catalog/types";import { cn } from "@/lib/utils";import { toastError } from "@/lib/refusals";@@ -114,6 +115,8 @@ export function ResultsGrid({const done = tiles.filter((t) => t.o);const [open, setOpen] = useState<number | null>(null);const { trash } = useGenerationActions();+ // An account has no Trash: its delete is for good, so it says so and asks first.+ const account = useIsAccount();const retry = useRetryPhoto();const viewing = open !== null ? done[open] : undefined;return (@@ -160,7 +163,7 @@ export function ResultsGrid({{onPick && <IconLink label="View" icon={Maximize2} onClick={() => setOpen(idx)} />}<IconLink href={`/video?image=${encodeURIComponent(url)}`} label="Animate" icon={Film} /><IconLink href={`/edit?image=${encodeURIComponent(url)}`} label="Edit" icon={Pencil} />- <IconLink label="Move to Trash" icon={Trash2} onClick={() => void trash([t.g])} />+ <IconLink label={account ? "Delete for good…" : "Move to Trash"} icon={Trash2} onClick={() => (account ? askDeleteForGood([t.g]) : void trash([t.g]))} /></div>{t.g.request.step && <span className="pointer-events-none absolute bottom-2 left-2 rounded-full bg-background/85 px-2 py-0.5 text-[11px] font-medium">{t.g.request.step.label}</span>}</div>diff --git a/src/components/share/publish-wizard.tsx b/src/components/share/publish-wizard.tsxindex 75c59494..7565500e 100644--- a/src/components/share/publish-wizard.tsx+++ b/src/components/share/publish-wizard.tsx@@ -78,7 +78,7 @@ export function PublishWizard({ items, onClose, onPublished }: { items: Generati<DialogHeader><DialogTitle>Publish {pieces(order.length)}</DialogTitle><DialogDescription>- A read-only page anyone with the link can open.+ A read-only page anyone with the link can open. It isn't listed anywhere.{unfinished > 0 && ` ${unfinished} of your selection ${unfinished === 1 ? "isn't" : "aren't"} finished, so ${unfinished === 1 ? "it stays" : "they stay"} out.`}{over > 0 && ` A page holds up to ${MAX_PUBLISH_ITEMS}, so the last ${over === 1 ? "one stays" : `${over} stay`} out.`}</DialogDescription>diff --git a/src/components/storyboard-view.tsx b/src/components/storyboard-view.tsxindex 3339377a..e7eda94d 100644--- a/src/components/storyboard-view.tsx+++ b/src/components/storyboard-view.tsx@@ -20,7 +20,8 @@ import { fileToSlot, MediaSlot, type SlotValue } from "@/components/studio/mediaimport { Viewer } from "@/components/studio/viewer";import { StarterParam } from "@/components/starters/starter-param";import { StarterSection, useStarters } from "@/components/starters/starter-section";-import { useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsVisitor, useStatus } from "@/lib/api";+import { useCreateGeneration, useEngine, useGenerationActions, useGenerations, useHydrated, useIsAccount, useIsVisitor, useStatus } from "@/lib/api";+import { askDeleteForGood } from "@/components/studio/delete-for-good";import { MAX_FRAMES, STORYBOARD_ASPECTS, STORYBOARD_PARTNER_IDS, type StoryboardNextScene, type StoryboardPartner } from "@/lib/catalog/storyboard";import { lookCard } from "@/lib/catalog/soul-cards";import type { Engine, Generation } from "@/lib/catalog/types";@@ -232,6 +233,8 @@ function Board({names: Record<string, string>;}) {const { trash } = useGenerationActions();+ // An account has no Trash: its board goes for good, so it says so and asks first.+ const account = useIsAccount();const qc = useQueryClient();const first = frames[0];const done = frames.filter((f) => f.status === "succeeded").length;@@ -305,11 +308,11 @@ function Board({variant="ghost"size="sm"className="text-muted-foreground hover:text-destructive"- aria-label="Move storyboard to Trash"+ aria-label={account ? "Delete storyboard for good" : "Move storyboard to Trash"}// One bulk call, and the shared toast with Undo (the frames go to the Trash).- onClick={() => void trash([...frames, ...film], "Storyboard moved to Trash")}+ onClick={() => (account ? askDeleteForGood([...frames, ...film]) : void trash([...frames, ...film], "Storyboard moved to Trash"))}>- <Trash2 /> <span className="hidden sm:inline">Move to Trash</span>+ <Trash2 /> <span className="hidden sm:inline">{account ? "Delete for good…" : "Move to Trash"}</span></Button></div></header>diff --git a/src/components/studio/delete-for-good.tsx b/src/components/studio/delete-for-good.tsxnew file mode 100644index 00000000..bc28812a--- /dev/null+++ b/src/components/studio/delete-for-good.tsx@@ -0,0 +1,73 @@+"use client";++import { useEffect, useState } from "react";+import { toast } from "sonner";+import {+ AlertDialog,+ AlertDialogAction,+ AlertDialogCancel,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from "@/components/ui/alert-dialog";+import { useGenerationActions } from "@/lib/api";+import type { Generation } from "@/lib/catalog/types";++/**+ * An account's "Delete for good…" on a result (its ⋯ menu, in any feed or the viewer): an account has no Trash, so the+ * delete can't be undone, and it is asked first. One host (in the app's providers) answers every menu.+ */++const EVENT = "fuobe:delete-for-good";++interface Ask {+ gs: Generation[];+ after?: () => void;+}++/** Ask before an account's results are deleted for good; `after` runs once it's confirmed (a viewer closes). */+export function askDeleteForGood(gs: Generation[], after?: () => void): void {+ if (gs.length) window.dispatchEvent(new CustomEvent<Ask>(EVENT, { detail: { gs, after } }));+}++const running = (g: Generation) => g.status === "queued" || g.status === "running";++export function DeleteForGoodHost() {+ const actions = useGenerationActions();+ const [ask, setAsk] = useState<Ask | null>(null);+ useEffect(() => {+ const on = (e: Event) => setAsk((e as CustomEvent<Ask>).detail);+ window.addEventListener(EVENT, on);+ return () => window.removeEventListener(EVENT, on);+ }, []);+ const n = ask?.gs.length ?? 0;+ const active = ask?.gs.some(running) ?? false;+ return (+ <AlertDialog open={!!ask} onOpenChange={(v) => !v && setAsk(null)}>+ <AlertDialogContent>+ <AlertDialogHeader>+ <AlertDialogTitle>Delete {n === 1 ? "this for good" : `${n} results for good`}?</AlertDialogTitle>+ <AlertDialogDescription>+ {n === 1 ? "It's" : "They're"} removed with {n === 1 ? "its" : "their"} files and can't be recovered.+ {active && (n === 1 ? " It's still running, so it's stopped first." : " Any still running are stopped first.")}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancel>Cancel</AlertDialogCancel>+ <AlertDialogAction+ variant="destructive"+ onClick={() => {+ if (!ask) return;+ void actions.deleteOwn(ask.gs).then((done) => done && toast(done === 1 ? "Deleted for good" : `Deleted ${done} for good`));+ ask.after?.();+ }}+ >+ Delete for good+ </AlertDialogAction>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog>+ );+}diff --git a/src/components/studio/result-actions.tsx b/src/components/studio/result-actions.tsxindex 576333a1..b0514881 100644--- a/src/components/studio/result-actions.tsx+++ b/src/components/studio/result-actions.tsx@@ -74,7 +74,8 @@ import { useShare } from "@/components/share/share-provider";import { useSkillBuilder } from "@/components/skills/skill-builder-provider";import { Popover, PopoverAnchor, PopoverContent } from "@/components/ui/popover";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { useCreateGeneration, useEngineMode, useGenerationActions, useLikelyVisitor, useSaveElement, useStatus } from "@/lib/api";+import { useCreateGeneration, useEngineMode, useGenerationActions, useIsAccount, useLikelyVisitor, useSaveElement, useStatus } from "@/lib/api";+import { askDeleteForGood } from "@/components/studio/delete-for-good";import { placeholdersOn } from "@/lib/demo-mode";import { ELEMENT_KINDS, type ElementKind } from "@/lib/catalog/elements";import { OPERATION_LABELS, type Generation, type OutputFile } from "@/lib/catalog/types";@@ -132,6 +133,7 @@ export const ACTION_ICONS: Record<OutputActionId, LucideIcon> = {review: CircleDot,delete: Trash2,"delete-upload": Trash2,+ "delete-own": Trash2,restore: ArchiveRestore,"restore-video": Palette,"extend-song": ListMusic,@@ -276,6 +278,8 @@ export function useActionRunner(opts: RunnerOptions = {}) {case "pin":void actions.pin([g], !g.pinnedAt);return void toast(g.pinnedAt ? "Unpinned" : "Pinned to the top of the Library", { id: "pin" });+ case "delete-own":+ return askDeleteForGood([g], opts.onDeleted);case "delete-upload":return deleteUpload?.(g, opts.onDeleted);case "delete":@@ -419,7 +423,8 @@ export function TileActions({const engineMode = useEngineMode();const visitor = useLikelyVisitor();const placeholders = placeholdersOn(useStatus().data?.demoMode);- const list = useMemo(() => outputActions(g, index, { ...ctx, engineMode, visitor, placeholders }), [g, index, ctx, engineMode, visitor, placeholders]);+ const account = useIsAccount();+ const list = useMemo(() => outputActions(g, index, { ...ctx, engineMode, visitor, placeholders, account }), [g, index, ctx, engineMode, visitor, placeholders, account]);const [saving, setSaving] = useState(false);const strip = useRef<HTMLDivElement>(null);const [narrow, setNarrow] = useState(false);diff --git a/src/components/studio/viewer.tsx b/src/components/studio/viewer.tsxindex c251dd3a..676bb107 100644--- a/src/components/studio/viewer.tsx+++ b/src/components/studio/viewer.tsx@@ -13,7 +13,7 @@ import { formatCost, timeAgo } from "@/lib/format";import { PRESETS as GRADE_PRESETS } from "@/lib/grade";import { trashDaysLeft, userTitle } from "@/lib/library";import { editOnlyFormat, isLayered, layerInfo, outputActions, type OutputAction } from "@/lib/output-actions";-import { useEngineMode, useLikelyVisitor, useStatus } from "@/lib/api";+import { useEngineMode, useIsAccount, useLikelyVisitor, useStatus } from "@/lib/api";import { placeholdersOn } from "@/lib/demo-mode";import { cn } from "@/lib/utils";import { copyWithToast } from "@/lib/clipboard";@@ -171,7 +171,8 @@ export function Viewer({const engineMode = useEngineMode();const visitor = useLikelyVisitor();const placeholders = placeholdersOn(useStatus().data?.demoMode);- const list = useMemo(() => outputActions(g, index, { reuse: !!onReuse, compare: !!source, inViewer: true, engineMode, visitor, placeholders }), [g, index, onReuse, source, engineMode, visitor, placeholders]);+ const account = useIsAccount();+ const list = useMemo(() => outputActions(g, index, { reuse: !!onReuse, compare: !!source, inViewer: true, engineMode, visitor, placeholders, account }), [g, index, onReuse, source, engineMode, visitor, placeholders, account]);// Read the latest values from the key handler without re-subscribing on every render.const latest = useRef({ list, run, g, index, onPrev, onNext, source });diff --git a/src/lib/api.ts b/src/lib/api.tsindex 8516a8cd..bc6d8c16 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -620,6 +620,28 @@ export function useGenerationActions() {trash,restore,deleteForever: (gs: Generation[]) => run(gs, null, "delete"),+ /**+ * An account's own runs, deleted for good (an account has no Trash): DELETE /api/generations/<id> one by one, which+ * the proxy lets through for the account's own runs only. Optimistic, then the server; on a refusal the caches are+ * refetched and its words shown. How many went.+ */+ deleteOwn: async (gs: Generation[]) => {+ if (!gs.length) return 0;+ local(gs, null);+ let n = 0;+ try {+ for (const g of gs) {+ const res = await fetch(`/api/generations/${encodeURIComponent(g.id)}?forever=1`, { method: "DELETE" });+ if (!res.ok) throw new Error(((await res.json().catch(() => ({}))) as { error?: string }).error ?? "It couldn't be deleted. Try again.");+ n++;+ }+ } catch (e) {+ toast.error((e as Error).message);+ } finally {+ refresh();+ }+ return n;+ },emptyTrash: async () => {await fetch("/api/generations/trash", { method: "DELETE" });refresh();diff --git a/src/lib/av/katana.ts b/src/lib/av/katana.tsindex 095f8886..8a06e1ad 100644--- a/src/lib/av/katana.ts+++ b/src/lib/av/katana.ts@@ -294,6 +294,25 @@ export function stepsToRedo(steps: KatanaStep[], failed: string[]): string[] {return steps.filter((st) => redo.has(st.key)).map((st) => st.key);}+/**+ * The steps a one-tap button makes again: every step for Run again (a new run of the same input), else the failed ones+ * and every step after them, as retryKatana does (Retry failed steps). Null when the plan can't be read again.+ */+export function againKeys(j: KatanaJobView, all: boolean): string[] | null {+ if (all) return Object.keys(j.steps);+ const failed = Object.entries(j.steps)+ .filter(([, id]) => {+ const g = j.generations[id];+ return !g || g.status === "failed" || g.status === "canceled";+ })+ .map(([k]) => k);+ try {+ return stepsToRedo(katanaSteps(j), failed);+ } catch {+ return null;+ }+}+/** The key of the step that makes the finished video. */export function finalKey(steps: KatanaStep[]): string {return steps.some((s) => s.key === "final") ? "final" : steps.some((s) => s.key === "join") ? "join" : "move0";diff --git a/src/lib/demo-mode.ts b/src/lib/demo-mode.tsindex 0886d5c0..0226d23e 100644--- a/src/lib/demo-mode.ts+++ b/src/lib/demo-mode.ts@@ -8,6 +8,8 @@* demoMode "off"), so only the owner is offered a way out.*/+import { formatCost } from "@/lib/format";+/** Settings' switch. */export const PLACEHOLDER_SETTING = "Show placeholder results (for a tour)";@@ -30,14 +32,42 @@ export const isPlaceholder = (g: { provider?: string | null } | null | undefined/*** What a one-tap "Run again" adds to its label, so a new run never starts unannounced: " on your GPU", " on the- * studio's GPUs" (a hosted run) or " · paid" (a cloud run is billed), nothing before the run is known. The new run- * follows the placeholder switch as it is now (`now.placeholders`, from the status), not the old result: nothing while- * placeholders are on, even after a real result, and a real run's words after an old placeholder once they're off.+ * studio's GPUs" (a hosted run) or, for a cloud run (billed), its price (" · ≈ $0.42") when `price` says it, else+ * " · paid"; nothing before the run is known. The new run follows the placeholder switch as it is now+ * (`now.placeholders`, from the status), not the old result: nothing while placeholders are on, even after a real+ * result, and a real run's words after an old placeholder once they're off.+ *+ * `price`: what the new run costs in US dollars, from the estimate the original run was priced at (againPrice or the+ * studio's own estimate), or null when that isn't known.*/-export function againWhere(g: { engine: string; place?: "pool" } | null | undefined, now: { placeholders: boolean }): string {+export function againWhere(g: { engine: string; place?: "pool" } | null | undefined, now: { placeholders: boolean }, price?: number | null): string {if (!g || now.placeholders) return "";if (g.place === "pool") return " on the studio's GPUs";- return g.engine === "open" ? " on your GPU" : " · paid";+ if (g.engine === "open") return " on your GPU";+ return paidSuffix(price);+}++/**+ * What a one-tap paid (cloud) run adds to its button: its price (" · ≈ $0.42", " · under $0.01") when it is known,+ * else " · paid".+ */+export function paidSuffix(price?: number | null): string {+ if (price == null || !(price > 0)) return " · paid";+ return price < 0.01 ? " · under $0.01" : ` · ≈ ${formatCost(price)}`;+}++/**+ * A new run's price from the runs it makes again (each keeps the estimate it was priced at, `costUsd`): their sum, or+ * null when one is missing, unpriced or a placeholder (a stand-in's estimate says nothing about the real run).+ */+export function againPrice(gs: readonly ({ costUsd: number | null; provider?: string | null } | null | undefined)[]): number | null {+ if (!gs.length) return null;+ let sum = 0;+ for (const g of gs) {+ if (!g || isPlaceholder(g) || g.costUsd == null) return null;+ sum += g.costUsd;+ }+ return Math.round(sum * 1000) / 1000;}/** Whether the owner's runs make placeholders now: only with the switch on ("on"; anything else is off). */diff --git a/src/lib/output-actions.ts b/src/lib/output-actions.tsindex e0f036ce..fe8ef2eb 100644--- a/src/lib/output-actions.ts+++ b/src/lib/output-actions.ts@@ -67,6 +67,7 @@ export type OutputActionId =| "review"| "delete"| "delete-upload"+ | "delete-own"| "restore"| "restore-video"| "delete-forever";@@ -96,6 +97,8 @@ export interface ActionContext {engineMode?: "both" | "open" | "cloud";/** A guest or an account: hand-offs to the tools that run on a self-hosted Fuobe only are left out. */visitor?: boolean;+ /** A signed-in account (public sign-up): it has no Trash, so a delete is for good ("Delete for good…", asked first). */+ account?: boolean;/** Placeholder results are on (Settings): a new render is a free stand-in, so "paid" is left out. */placeholders?: boolean;}@@ -245,8 +248,10 @@ export function outputActions(g: Generation, index: number, ctx: ActionContext =if (g.status === "succeeded" && g.outputs.some((x) => storedPath(x.url))) out.push({ id: "share", label: "Share link…", placement: "menu" });// Library: pinned results stay at the top of their view; the review status is a sub-menu of its own.out.push({ id: "pin", label: g.pinnedAt ? "Unpin" : "Pin to top", placement: "menu" }, { id: "review", label: "Review status", placement: "menu" });- // It goes to the Trash (restorable for 30 days), so it says so; a run still going is canceled first.- out.push({ id: "delete", label: "Move to Trash", placement: "menu", destructive: true });+ // The owner's goes to the Trash (restorable for 30 days), so it says so; a run still going is canceled first. An+ // account has no Trash: its delete is for good, so it says that and asks first.+ if (ctx.account) out.push({ id: "delete-own", label: "Delete for good…", placement: "menu", destructive: true });+ else out.push({ id: "delete", label: "Move to Trash", placement: "menu", destructive: true });return out;}diff --git a/src/lib/recipe.ts b/src/lib/recipe.tsindex 99778aaa..583ac2f5 100644--- a/src/lib/recipe.ts+++ b/src/lib/recipe.ts@@ -1033,6 +1033,11 @@ export interface RecipeView {line: string;/** Why it runs nowhere on this install. */why?: string;+ /**+ * Made from placeholder results (recipe.source.demo), and a run of it has since made a real result (every step+ * succeeded, none a placeholder): "Made from placeholder results" isn't said any more.+ */+ madeReal?: true;/** Each step's model and its licence on each engine, as information. */models: { engine: RecipeEngine; name: string; licence: string }[];}diff --git a/src/server/recipes.ts b/src/server/recipes.tsindex 28918cab..45324ee0 100644--- a/src/server/recipes.ts+++ b/src/server/recipes.ts@@ -52,6 +52,7 @@ import { cancelGeneration, createGenerations, currentRequest, getGeneration, preimport { trashGenerations } from "./library";import { isOffered, modelLicence } from "./model-access";import { GenerationRequestSchema } from "./request-schema";+import { db } from "./db";import { engineMode } from "./settings";import { createSkill, deleteSkill, getSkill, setSkillFile, skillFile, SkillError } from "./skills";import { beginSkillRun, stagedDryRun } from "./skill-runs";@@ -478,10 +479,26 @@ export function recipeView(name: string): RecipeView {recheck: needsRecheck(recipe, ready),line: verifiedLine(recipe, engines),...(!engines.length && { why: noEngine(recipe) }),+ ...(recipe.source?.demo && madeRealResult(skill.name) && { madeReal: true as const }),models: [...new Map(models.map((x) => [`${x.engine}:${x.name}`, x])).values()],};}+/**+ * Whether a skill has made a real result: one of its runs (its steps share `request.skill.run`, else a batch) whose+ * every step succeeded and none was a placeholder. A free test run's steps are placeholders, so they never count.+ * Only the owner's runs count (an account's stay out of the owner's skills).+ */+export function madeRealResult(name: string): boolean {+ return !!db()+ .prepare(+ `SELECT 1 FROM generations WHERE json_valid(request_json) AND json_extract(request_json, '$.skill.name') = ? AND json_extract(request_json, '$.account') IS NULL+ GROUP BY COALESCE(json_extract(request_json, '$.skill.run'), batch_id, id)+ HAVING SUM(status != 'succeeded') = 0 AND SUM(provider = 'mock') = 0 LIMIT 1`,+ )+ .get(name);+}+/*** Why a checked recipe should be checked again, per engine (none: it's fine): a step's model moved by REPLACED_BY, a* model switched off in Settings → Models & licences, a plan that no longer passes, or a plan hash (models, routes,diff --git a/tests/again-where.test.ts b/tests/again-where.test.tsindex dd4f378f..cca7cff0 100644--- a/tests/again-where.test.ts+++ b/tests/again-where.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vitest";-import { againWhere } from "@/lib/demo-mode";+import { againKeys, katanaSteps, type KatanaJobView } from "@/lib/av/katana";+import type { Generation } from "@/lib/catalog/types";+import { againPrice, againWhere, paidSuffix } from "@/lib/demo-mode";import { draftRenderPaid } from "@/lib/output-actions";describe("a one-tap Run again says what it spends", () => {@@ -12,6 +14,21 @@ describe("a one-tap Run again says what it spends", () => {expect(againWhere({ engine: "cloud" }, off)).toBe(" · paid");});+ it("says the cloud price when the estimate is known, else paid", () => {+ expect(againWhere({ engine: "cloud" }, off, 0.42)).toBe(" · ≈ $0.42");+ expect(againWhere({ engine: "cloud" }, off, 0.045)).toBe(" · ≈ $0.045");+ expect(againWhere({ engine: "cloud" }, off, 3.5)).toBe(" · ≈ $3.50");+ expect(againWhere({ engine: "cloud" }, off, 0.004)).toBe(" · under $0.01");+ expect(againWhere({ engine: "cloud" }, off, null)).toBe(" · paid");+ expect(againWhere({ engine: "cloud" }, off, 0)).toBe(" · paid");+ // A price never shows on your GPU, on a studio's GPUs, or while placeholders are on.+ expect(againWhere({ engine: "open" }, off, 0.42)).toBe(" on your GPU");+ expect(againWhere({ engine: "cloud", place: "pool" }, off, 0.42)).toBe(" on the studio's GPUs");+ expect(againWhere({ engine: "cloud" }, on, 0.42)).toBe("");+ expect(paidSuffix(undefined)).toBe(" · paid");+ expect(paidSuffix(0.04)).toBe(" · ≈ $0.04");+ });+it("follows the placeholder switch as it is now, not the old result", () => {// An old placeholder result, placeholders now off: the rerun is real and says so.expect(againWhere({ engine: "cloud", provider: "mock" } as { engine: string }, off)).toBe(" · paid");@@ -31,3 +48,51 @@ describe("a one-tap Run again says what it spends", () => {expect(draftRenderPaid(true)).toBe("");});});++describe("a rerun's price comes from the estimates its runs were priced at", () => {+ it("sums them, and knows nothing when one is missing, unpriced or a placeholder", () => {+ expect(againPrice([{ costUsd: 0.1, provider: "fal" }, { costUsd: 0.25, provider: "fal" }])).toBe(0.35);+ expect(againPrice([{ costUsd: 0.1, provider: "fal" }, { costUsd: 0, provider: "fal" }])).toBe(0.1);+ expect(againPrice([{ costUsd: 0.1, provider: "fal" }, { costUsd: null, provider: "fal" }])).toBeNull();+ expect(againPrice([{ costUsd: 0.1, provider: "fal" }, undefined])).toBeNull();+ // A placeholder's estimate says nothing about the real run.+ expect(againPrice([{ costUsd: 0, provider: "mock" }])).toBeNull();+ expect(againPrice([])).toBeNull();+ });++ it("prices a Katana Run again on every step, and Retry failed steps on the failed ones and after", () => {+ const input = {+ engine: "cloud" as const,+ reference: "/api/files/ref.mp4",+ photos: ["/api/files/me.png"],+ segments: [+ { start: 0, end: 4 },+ { start: 4, end: 8 },+ ],+ motionModel: "kling-o3",+ keepAudio: true,+ };+ const steps = katanaSteps(input);+ const prices: Record<string, number> = { key0: 0.15, move0: 1.2, key1: 0.15, move1: 1.2 };+ const gen = (key: string, status: Generation["status"]): Generation => ({ id: `g-${key}`, status, provider: "fal", engine: "cloud", costUsd: prices[key] ?? 0 }) as Generation;+ const job = (failed: string[]): KatanaJobView => {+ const ids = Object.fromEntries(steps.map((s) => [s.key, `g-${s.key}`]));+ const generations = Object.fromEntries(steps.map((s) => [`g-${s.key}`, gen(s.key, failed.includes(s.key) ? "failed" : "succeeded")]));+ return { ...input, id: "k1", title: "Edit", batchId: "b1", steps: ids, final: "final", createdAt: 1, updatedAt: 1, generations };+ };+ const priceOf = (j: KatanaJobView, all: boolean) => againPrice(againKeys(j, all)!.map((k) => j.generations[j.steps[k]]));+ // Run again: every step.+ expect(priceOf(job([]), true)).toBe(2.7);+ // Segment 2's motion failed: it, the join and the soundtrack are made again.+ expect(againKeys(job(["move1"]), false)).toEqual(["move1", "join", "final"]);+ expect(priceOf(job(["move1"]), false)).toBe(1.2);+ // Its picture failed: the picture and everything after it.+ expect(priceOf(job(["key1"]), false)).toBe(1.35);+ expect(againWhere(job(["move1"]), { placeholders: false }, priceOf(job(["move1"]), false))).toBe(" · ≈ $1.20");+ // A step made as a placeholder: no price, so the button says "· paid".+ const j = job(["move1"]);+ j.generations["g-move1"] = { ...j.generations["g-move1"], provider: "mock" } as Generation;+ expect(priceOf(j, false)).toBeNull();+ expect(againWhere(j, { placeholders: false }, priceOf(j, false))).toBe(" · paid");+ });+});diff --git a/tests/delete-for-good.test.ts b/tests/delete-for-good.test.tsnew file mode 100644index 00000000..a0b8f38d--- /dev/null+++ b/tests/delete-for-good.test.ts@@ -0,0 +1,126 @@+import { beforeAll, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import type { Generation, OutputFile } from "@/lib/catalog/types";+import { outputActions } from "@/lib/output-actions";+import { tempDir } from "./helpers/temp-dir";++// An account has no Trash: its ⋯ menu says "Delete for good…" (asked first) and deletes with DELETE+// /api/generations/<id>, its own runs only. The owner keeps "Move to Trash".++const dir = tempDir("fuobe-delete-for-good-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+process.env.COMFYUI_URL = "http://127.0.0.1:1";+delete process.env.FUOBE_PASSWORD;++const auth = await import("@/server/auth");+const { db } = await import("@/server/db");+const { proxy } = await import("@/proxy");+const one = await import("@/app/api/generations/[id]/route");+const bulk = await import("@/app/api/generations/bulk/route");++const gen = (p: Partial<Generation> = {}): Generation =>+ ({+ id: "g1",+ batchId: null,+ feature: "image",+ presetId: null,+ modelId: "oss-z-image",+ engine: "open",+ provider: "comfyui",+ op: "t2i",+ kind: "image",+ status: "succeeded",+ progress: null,+ message: null,+ prompt: "a perfume bottle on marble",+ request: { feature: "image", modelId: "oss-z-image", prompt: "a perfume bottle on marble" },+ outputs: [{ url: "/api/files/a.png", kind: "image" } as OutputFile],+ error: null,+ costUsd: 0,+ favorite: false,+ createdAt: 1,+ updatedAt: 1,+ completedAt: 1,+ ...p,+ }) as Generation;++describe("the ⋯ menu's delete says what happens, for each audience", () => {+ const del = (ctx = {}) => outputActions(gen(), 0, ctx).filter((a) => a.destructive);++ it("moves the owner's result to the Trash", () => {+ expect(del()).toEqual([expect.objectContaining({ id: "delete", label: "Move to Trash" })]);+ expect(del({ account: false })).toEqual([expect.objectContaining({ id: "delete", label: "Move to Trash" })]);+ });++ it("deletes an account's result for good, asked first, and never offers it the Trash", () => {+ const list = outputActions(gen(), 0, { account: true, visitor: true });+ expect(list.filter((a) => a.destructive)).toEqual([expect.objectContaining({ id: "delete-own", label: "Delete for good…" })]);+ expect(list.map((a) => a.label)).not.toContain("Move to Trash");+ });++ it("keeps an upload's own delete for everyone", () => {+ const up = gen({ feature: "upload", modelId: "upload", provider: "mock" as Generation["provider"], prompt: null, request: { feature: "upload", modelId: "upload" } });+ for (const account of [false, true]) expect(outputActions(up, 0, { account }).filter((a) => a.destructive).map((a) => a.id)).toEqual(["delete-upload"]);+ });+});++describe("DELETE /api/generations/<id> keeps to whose run it is", () => {+ let cookieA = "";+ let cookieB = "";+ let owner = "";+ let a = "";+ beforeAll(() => {+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ const b = auth.createAccount("[email protected]", "long enough").id;+ cookieA = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+ cookieB = `${auth.SESSION_COOKIE}=${auth.createSession(b).value}`;+ owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ });++ const row = (id: string, account?: string) =>+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'oss-z-image', 'open', 'comfyui', 't2i', 'image', 'succeeded', ?, '[]', ?, ?)",+ )+ .run(id, JSON.stringify({ feature: "image", modelId: "oss-z-image", ...(account && { account }) }), Date.now(), Date.now());+ const exists = (id: string) => !!db().prepare("SELECT 1 FROM generations WHERE id = ?").get(id);+ const inTrash = (id: string) => !!db().prepare("SELECT 1 FROM generation_trash WHERE generation_id = ?").get(id);+ const through = (id: string, cookie: string) => proxy(new NextRequest(`http://localhost:3000/api/generations/${id}?forever=1`, { method: "DELETE", headers: { cookie } }));+ const remove = (id: string, cookie: string, forever = true) =>+ one.DELETE(new Request(`http://localhost:3000/api/generations/${id}${forever ? "?forever=1" : ""}`, { method: "DELETE", headers: { cookie, host: "localhost:3000" } }), { params: Promise.resolve({ id }) } as never);++ it("lets an account delete its own run, for good", async () => {+ row("acct-own", a);+ expect(through("acct-own", cookieA).headers.get("x-middleware-next")).toBe("1");+ expect((await remove("acct-own", cookieA)).status).toBe(204);+ expect(exists("acct-own")).toBe(false);+ expect(inTrash("acct-own")).toBe(false);+ });++ it("refuses an account another account's run and the owner's", () => {+ row("acct-other", a);+ row("owner-run");+ expect(through("acct-other", cookieB).status).toBe(403);+ expect(through("owner-run", cookieA).status).toBe(403);+ expect(exists("acct-other")).toBe(true);+ expect(exists("owner-run")).toBe(true);+ });++ it("refuses an account the Trash (the bulk route), so its menu never offers it", async () => {+ row("acct-bulk", a);+ const body = JSON.stringify({ action: "trash", ids: ["acct-bulk"] });+ const r = await bulk.POST(new Request("http://localhost:3000/api/generations/bulk", { method: "POST", headers: { cookie: cookieA, host: "localhost:3000", "content-type": "application/json" }, body }));+ expect(r.status).toBe(403);+ expect(exists("acct-bulk")).toBe(true);+ });++ it("moves the owner's run to the Trash, where it can be restored", async () => {+ row("owner-trash");+ expect(through("owner-trash", owner).headers.get("x-middleware-next")).toBe("1");+ expect((await remove("owner-trash", owner, false)).status).toBe(204);+ expect(exists("owner-trash")).toBe(true);+ expect(inTrash("owner-trash")).toBe(true);+ });+});diff --git a/tests/skill-made-real.test.ts b/tests/skill-made-real.test.tsnew file mode 100644index 00000000..cf5c14c9--- /dev/null+++ b/tests/skill-made-real.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";+import { tempDir } from "./helpers/temp-dir";++// "Made from placeholder results" stays on a skill until one of its runs has made a real result.++process.env.FUOBE_DATA_DIR = tempDir("fuobe-skill-made-real-");+process.env.COMFYUI_URL = "http://127.0.0.1:1";++const { db } = await import("@/server/db");+const { madeRealResult } = await import("@/server/recipes");++let n = 0;+/** One step of a skill's run. */+function step(skill: string, run: string, status: string, provider: string, account?: string) {+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'image', 'flux-2', 'cloud', ?, 't2i', 'image', ?, ?, '[]', ?, ?)",+ )+ .run(`s${++n}`, provider, status, JSON.stringify({ feature: "image", modelId: "flux-2", skill: { name: skill, run }, ...(account && { account }) }), n, n);+}++describe("a skill made from placeholder results", () => {+ it("hasn't made a real result while its runs are placeholders, failed or unfinished", () => {+ expect(madeRealResult("poster")).toBe(false);+ // A free test run: placeholders only.+ step("poster", "check-1", "succeeded", "mock");+ step("poster", "check-1", "succeeded", "mock");+ // A real run whose second step failed, and one still going.+ step("poster", "r1", "succeeded", "fal");+ step("poster", "r1", "failed", "fal");+ step("poster", "r2", "running", "fal");+ // An account's run never counts for the owner's skill.+ step("poster", "acct-1", "succeeded", "fal", "acct-a");+ expect(madeRealResult("poster")).toBe(false);+ });++ it("has, once every step of one real run succeeded", () => {+ step("poster", "r3", "succeeded", "fal");+ step("poster", "r3", "succeeded", "replicate");+ expect(madeRealResult("poster")).toBe(true);+ // Another skill's runs don't count for it.+ expect(madeRealResult("other")).toBe(false);+ });+});