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
Genjutsu: accounts run it on their own GPU or key
Adarshae7d415a1611
diff --git a/docs/public-signup.md b/docs/public-signup.mdindex 3c6028ee..9c8061a7 100644--- a/docs/public-signup.md+++ b/docs/public-signup.md@@ -283,6 +283,13 @@ cloudflared tunnel --url http://localhost:8188 # or: ngrok http 8188"Write the lyrics" and "Rewrite my prompt now" use the studio's AI helper and are hidden from guests and accounts.A song's stems come back as one zip: for an account it is fetched from public addresses only, within what its fileshave room for (128 MB at most, 256 MB unpacked), and each stem is saved to disk as it is unpacked.+- **Genjutsu.** An account runs Genjutsu's modes that are open to everyone the same way (`POST /api/genjutsu`, and the+ clip's words for Character swap, `POST /api/genjutsu/transcribe`). Each step of the run (the cut, the swap, the joins,+ the sound) is a run of its own on the account's ComfyUI, or on its own fal.ai or Replicate key on the cloud engine,+ with only its own files, and the whole run counts once against its limits. Its results show under "Your Genjutsu" and+ in its own runs, to open and download. "Describe my character" uses the studio's AI helper, so it isn't offered: the+ account describes the character in its own words. A guest gets the sign-up card. The checks are+ `src/server/account-tool-run.ts`.- **Files a run takes.** A run on your GPU takes only files you uploaded here, or your own results.A link or a `data:` URI answers 400 with `code: "input-not-allowed"`, someone else's file 403(`input-not-yours`), and a file that has expired 404 (`input-gone`, "That file has expired.diff --git a/src/app/api/genjutsu/describe/route.ts b/src/app/api/genjutsu/describe/route.tsindex 47716cc9..5d5d2538 100644--- a/src/app/api/genjutsu/describe/route.ts+++ b/src/app/api/genjutsu/describe/route.ts@@ -1,8 +1,13 @@+import { ownGpuTool, toolViewer } from "@/server/account-tool-run";import { describeCharacter, DescribeSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";-/** "Describe my character": the engine's text model writes what the character looks like from their picture. */+/**+ * "Describe my character": the engine's text model writes what the character looks like from their picture. It runs+ * on the studio's own AI helper, so it is the owner's: a visitor describes the character in its own words.+ */export async function POST(request: Request) {+ if (toolViewer(request).kind !== "owner") return ownGpuTool();return handle(async () => {const input = await body(request, DescribeSchema, "Add a picture of your character first");return Response.json(await describeCharacter(input));diff --git a/src/app/api/genjutsu/estimate/route.ts b/src/app/api/genjutsu/estimate/route.tsindex 70625b30..6141f083 100644--- a/src/app/api/genjutsu/estimate/route.ts+++ b/src/app/api/genjutsu/estimate/route.ts@@ -1,18 +1,19 @@import { requestViewer } from "@/server/auth";+import { priceAsRun } from "@/server/account-tool-run";import { estimateGenjutsu, GenjutsuEstimateSchema } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";-import { priceAs } from "@/server/visitor";-/** The price, the model, the pieces and the notes for the current settings, before anything runs. */-async function post(request: Request) {- return handle(async () => {- const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");- // A feature that hasn't opened is refused to everyone but the owner (src/server/genjutsu-live.ts).- return Response.json(await estimateGenjutsu(input, { owner: requestViewer(request).kind === "owner" }));- });-}--/** A visitor (public sign-up) gets the price of its run on its own GPU, never a demo (src/server/visitor.ts). */+/**+ * The price, the model, the pieces and the notes for the current settings, before anything runs. A visitor (public+ * sign-up) gets the price of its run as it would go: an account's on its own GPU or its own key, a guest's on the open+ * engine; never a demo (src/server/account-tool-run.ts priceAsRun).+ */export async function POST(request: Request) {- return priceAs(request, () => post(request));+ return priceAsRun(request, () =>+ handle(async () => {+ const input = await body(request, GenjutsuEstimateSchema, "Add a clip and pick a mode");+ // A feature that hasn't opened is refused to everyone but the owner (src/server/genjutsu-live.ts).+ return Response.json(await estimateGenjutsu(input, { owner: requestViewer(request).kind === "owner" }));+ }),+ );}diff --git a/src/app/api/genjutsu/route.ts b/src/app/api/genjutsu/route.tsindex f3708371..5c8bbb3b 100644--- a/src/app/api/genjutsu/route.ts+++ b/src/app/api/genjutsu/route.ts@@ -1,13 +1,37 @@-import { requestViewer } from "@/server/auth";-import { createGenjutsu, GenjutsuBodySchema } from "@/server/genjutsu";+import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { createGenjutsu, GenjutsuBodySchema, genjutsuSteps, planGenjutsuRun, startGenjutsu, type GenjutsuRun } from "@/server/genjutsu";import { body, handle, once } from "@/server/shorts-schemas";-/** Run a Genjutsu: the pieces or windows are made, joined, and the clip's sound put back. */+/**+ * Run a Genjutsu: the pieces or windows are made, joined, and the clip's sound put back. The owner's run as always; an+ * account's on its own GPU or its own fal.ai or Replicate key, with its own files, after the checks a studio run gets+ * (src/server/account-tool-run.ts); a guest signs up first.+ */export async function POST(request: Request) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }return handle(async () => {const input = await body(request, GenjutsuBodySchema, "Add a clip, pick a mode and add your references");// A repeated requestId (a second click on Generate) gets the run the first one started.- const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input, { owner: requestViewer(request).kind === "owner" }));- return Response.json({ final, items }, { status: 201 });+ if (viewer.kind === "owner") {+ const { final, items } = await once("genjutsu", input.requestId, () => createGenjutsu(input, { owner: true }));+ return Response.json({ final, items }, { status: 201 });+ }+ const look = input.look?.kind === "custom" ? input.look.images : [];+ let run: GenjutsuRun | null = null;+ // An account's repeat gets its own first run, never another's.+ return onceForAccount(viewer.account, "genjutsu", input.requestId, () =>+ runAccountTool(request, viewer.account, {+ tool: "genjutsu",+ files: [input.source.url, input.mask, input.picture?.frame, ...(input.references ?? []), ...look],+ plan: async () => genjutsuSteps((run = await planGenjutsuRun(input, { owner: false }))),+ start: () => startGenjutsu(run!),+ }),+ ({ value, gpuWarning }) => Response.json({ final: value.final, items: value.items, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),+ );}, request);}diff --git a/src/app/api/genjutsu/scene/route.ts b/src/app/api/genjutsu/scene/route.tsindex fd1cc152..00bcbca1 100644--- a/src/app/api/genjutsu/scene/route.ts+++ b/src/app/api/genjutsu/scene/route.ts@@ -1,11 +1,27 @@-import { requestViewer } from "@/server/auth";-import { describeScene, SceneSchema } from "@/server/genjutsu";+import { bodyTooBig, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { describeScene, SceneSchema, sceneRequest, startStep } from "@/server/genjutsu";import { body, handle } from "@/server/shorts-schemas";-/** From picture's "What happens": starts the describer on the part; the page waits for its text (a generation). */+/**+ * From picture's "What happens": starts the describer on the part; the page waits for its text (a generation). The+ * owner's, or an account's on its own GPU (src/server/account-tool-run.ts) once From picture is open to everyone.+ */export async function POST(request: Request) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }return handle(async () => {const input = await body(request, SceneSchema, "Make and pick the first frame first");- return Response.json(describeScene(input, { owner: requestViewer(request).kind === "owner" }), { status: 201 });+ if (viewer.kind === "owner") return Response.json(describeScene(input, { owner: true }), { status: 201 });+ const r = await runAccountTool(request, viewer.account, {+ tool: "genjutsu",+ files: [input.source.url, input.ownPerson ? undefined : input.frame],+ plan: () => [{ request: sceneRequest(input, { owner: false }) }],+ start: () => startStep(sceneRequest(input, { owner: false })),+ });+ return r.ok ? Response.json(r.value, { status: 201 }) : r.response;}, request);}diff --git a/src/app/api/genjutsu/transcribe/route.ts b/src/app/api/genjutsu/transcribe/route.tsindex 365b820a..e4b72834 100644--- a/src/app/api/genjutsu/transcribe/route.ts+++ b/src/app/api/genjutsu/transcribe/route.ts@@ -1,10 +1,30 @@-import { transcribeClip, TranscribeSchema } from "@/server/genjutsu";+import { bodyTooBig, guestRun, ownGpuTool, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { startStep, transcribeClip, TranscribeSchema, transcribeRequest } from "@/server/genjutsu";+import { soundLive } from "@/server/sound-live";import { body, handle } from "@/server/shorts-schemas";-/** The clip's words for Character swap's "What's said": one transcription the page picks the part's lines from. */+/**+ * The clip's words for Character swap's "What's said": one transcription the page picks the part's lines from. The+ * owner's, or an account's on its own GPU or key (src/server/account-tool-run.ts).+ */export async function POST(request: Request) {+ const viewer = toolViewer(request);+ if (viewer.kind === "guest") return guestRun();+ if (viewer.kind === "account") {+ const big = bodyTooBig(request);+ if (big) return big;+ }return handle(async () => {const input = await body(request, TranscribeSchema, "Add a clip first");- return Response.json(transcribeClip(input), { status: 201 });+ if (viewer.kind === "owner") return Response.json(transcribeClip(input), { status: 201 });+ // "Clean the voice first" opens to visitors once it has passed a real run (src/server/sound-live.ts).+ if (input.cleanVoiceFirst && !soundLive()["clean-voice-first"]) return ownGpuTool();+ const r = await runAccountTool(request, viewer.account, {+ tool: "genjutsu",+ files: [input.source.url],+ plan: () => [{ request: transcribeRequest(input) }],+ start: () => startStep(transcribeRequest(input)),+ });+ return r.ok ? Response.json(r.value, { status: 201 }) : r.response;}, request);}diff --git a/src/components/genjutsu/genjutsu-studio.tsx b/src/components/genjutsu/genjutsu-studio.tsxindex 1ab2f0e6..1e85ff93 100644--- a/src/components/genjutsu/genjutsu-studio.tsx+++ b/src/components/genjutsu/genjutsu-studio.tsx@@ -25,10 +25,9 @@ import { radioKeys, radioTab } from "@/components/studio/radio-keys";import { SketchEditor, type Stroke } from "@/components/studio/sketch-editor";import { VideoTrimmer, type TrimRange, type VideoTrimmerHandle } from "@/components/studio/video-trimmer";import { openInStudio } from "@/components/swap-studio/hooks";-import { SelfHostNote } from "@/components/self-host-note";import { ExampleRow } from "@/components/studio/example-row";import { onAttr, TAB_PILL, TabRow } from "@/components/ui/tab-row";-import { useEngine, useGenerations, useIsOwner, useLikelyVisitor, useModelAccess, useSoundLive, useStatus } from "@/lib/api";+import { useEngine, useGenerations, useIsOwner, useModelAccess, useSoundLive, useStatus } from "@/lib/api";import { CHARACTER_SWAP, cutsInPart, cutWarning, partWords, seedProblem, type CharacterChoice, type CharacterOptions } from "@/lib/catalog/character-swap";import {chooseMaker,@@ -63,7 +62,6 @@ import {type Maker,} from "@/lib/catalog/genjutsu";import { chainState } from "@/lib/catalog/shorts";-import { withoutOwnGpu } from "@/lib/catalog/engines";import type { Generation, PixelPoint } from "@/lib/catalog/types";import { downloadHref, downloadName } from "@/lib/library";import { keepOffered, offered } from "@/lib/model-access";@@ -140,8 +138,6 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: ExstaleTime: Infinity,});const shownExamples = owner && ownerExamples.data ? ownerExamples.data : modeExamples;- // Genjutsu doesn't run on an account's own GPU yet (only the studios' generations do): said here, not after Generate.- const visitor = useLikelyVisitor();const access = useModelAccess();const [mode, setModeState] = useState<GenjutsuMode>("motion");const source = useSourceClip(GENJUTSU.maxBytes);@@ -804,9 +800,9 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Exconst tabs = <ModeTabsRow modes={GENJUTSU_MODES.filter((m) => modeOpen(m.id, open))} mode={mode} onMode={setMode} onlyYou={(m) => owner && !modeOpen(m, (f) => !!live?.[f])} />;return (- <ToolShell title="Genjutsu" tabs={tabs} fadeKey={mode} header={<SetupCode setup={fullSetup} onPaste={(s) => apply(s)} />} wide selfHostedOnly>+ <ToolShell title="Genjutsu" tabs={tabs} fadeKey={mode} header={<SetupCode setup={fullSetup} onPaste={(s) => apply(s)} />} wide>{!clip && (- <ToolHero title={modeInfo.label} subtitle={`${hint}${visitor ? "" : " Free on your own ComfyUI."}`}>+ <ToolHero title={modeInfo.label} subtitle={`${hint} Free on your own ComfyUI.`}>{isCharacter && (<Link href="/character-swap" className="mt-3 inline-flex items-center gap-1 text-[13px] font-medium text-brand-text hover:underline">Whole clips, shot by shot? Open in Character Swap Studio@@ -815,16 +811,13 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex</ToolHero>)}{!clip && example && (- <ModeExample key={example.id} card={example} owner={!visitor} canUse={!visitor} inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} className="mt-6" />+ <ModeExample key={example.id} card={example} owner={owner} canUse inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} className="mt-6" />)}<div id="gj-clip-drop" className={cn("mx-auto scroll-mt-24 rounded-2xl transition-shadow", clip ? "pt-4" : "mt-8 max-w-[640px]", dropRing && "ring-2 ring-primary ring-offset-4 ring-offset-background")}>- {/* Said by the upload box it turns off (after the mode's example, which every viewer can watch). */}- {!clip && visitor && <SelfHostNote className="mb-3">Genjutsu isn't available here.</SelfHostNote>}{!clip ? (<ClipDropaccept={GENJUTSU.accept}limits={limits(mode)}- disabled={visitor}onFile={(f) => {const err = source.pick(f);if (err) toast.error(err);@@ -999,7 +992,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex<Panel id="gj-side" className="space-y-4 lg:sticky lg:top-[calc(var(--chrome-top)+1rem)]">{mode === "picture" && <PictureSteps stage={pictureStage} />}- {example && !visitor && <ModeExampleRow key={example.id} card={example} owner canUse inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} />}+ {example && <ModeExampleRow key={example.id} card={example} owner={owner} canUse inUse={exampleInUse} onlyYou={exampleOnlyYou} onUse={() => pickExample(example)} />}<p className="text-[13px] text-pretty text-muted-foreground">{hint}</p>{mode === "finish" && <FinishFields value={finish} onChange={setFinish} open={open} ownerOnly={ownerOnly} seed={seed} onSeed={setSeed} />}@@ -1135,7 +1128,8 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Exseed={seed}onSeed={setSeed}seedProblem={seedProblem(seedNumber)}- describe={{ run: describeCharacter, busy: describeMutation.isPending, blocked: refs.some((r) => !r.uploading) ? null : "Add your character's picture to describe it" }}+ // Describing uses the studio's own AI helper: the owner's. Everyone else describes the character in words.+ describe={owner ? { run: describeCharacter, busy: describeMutation.isPending, blocked: refs.some((r) => !r.uploading) ? null : "Add your character's picture to describe it" } : undefined}words={{ run: () => void fillClipWords(), busy: listening, blocked: clip?.url && !clip.uploading && range ? null : "Add the clip first" }}voiceFirst={voiceFirstShown ? { on: cleanFirst, onChange: setVoiceFirst, seconds: duration } : undefined}/>@@ -1175,7 +1169,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex)}{maker && options.length <= 1 && (<p className="text-[12px] text-muted-foreground">- <SourceBadge source={maker.source} /> <span className="font-medium text-foreground">{maker.label}</span> · {visitor ? withoutOwnGpu(maker.note) : maker.note}+ <SourceBadge source={maker.source} /> <span className="font-medium text-foreground">{maker.label}</span> · {maker.note}</p>)}@@ -1221,7 +1215,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex) : (<><p className="flex items-center gap-1.5 text-[15px] font-semibold tabular-nums">- {costText(est, engine, visitor)}+ {costText(est, engine)}{estimate.isFetching && <Loader2 className="size-3 animate-spin text-muted-foreground" aria-label="Updating the price" />}</p>{est && (@@ -1232,11 +1226,10 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex</>)}</div>- <Button id="gj-generate" className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending || visitor || describing}>+ <Button id="gj-generate" className="rounded-full" onClick={() => start()} disabled={!!blocker || runMutation.isPending || describing}>{runMutation.isPending ? <Loader2 className="size-4 animate-spin" /> : <Wand2 className="size-4" />} {mode === "picture" ? (pictureStage === "frame" ? "Make the first frame" : "Make the video") : "Generate"}</Button></div>- {visitor && <SelfHostNote>Genjutsu isn't available here.</SelfHostNote>}{est && est.notes.length > 0 && !blocker && (<ul className="space-y-1 text-[12px] leading-snug text-muted-foreground">{est.notes.map((n) => (@@ -1251,7 +1244,8 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Exengine={engine}maker={maker}cut={cut}- onOpenStudio={() => void openStudio()}+ // Character Swap Studio's projects are the owner's for now: anyone else gets the link to the studio.+ onOpenStudio={owner ? () => void openStudio() : undefined}opening={opening}waiting={clip?.uploading || refs.some((x) => x.uploading) ? "waiting for the upload" : null}/>}@@ -1261,7 +1255,7 @@ export function GenjutsuStudio({ examples, modeExamples, live }: { examples?: Ex)}</div>- {examples && !clip && !run && (visitor || (history.isSuccess && !history.data.length)) && <ExampleRow row={examples} layout="column" maxColumns={2} maxWidth={640} className="mt-12" />}+ {examples && !clip && !run && history.isSuccess && !history.data.length && <ExampleRow row={examples} layout="column" maxColumns={2} maxWidth={640} className="mt-12" />}{run && (<RunPanel@@ -1439,8 +1433,6 @@ function SourceBadge({ source }: { source: Maker["source"] }) {/** The models for this mode and engine, one line each (where it comes from, what it's good at, its limits). */function MakerList({ options, value, onChange, onlyYou }: { options: Maker[]; value: string; onChange: (id: string) => void; onlyYou?: (m: Maker) => boolean }) {- // A guest or an account: open weights run on a self-hosted Fuobe only, not on their own GPU yet.- const visitor = useLikelyVisitor();return (<div role="radiogroup" aria-label="Model" onKeyDown={radioKeys} className="space-y-1.5">{options.map((m) => (@@ -1462,7 +1454,7 @@ function MakerList({ options, value, onChange, onlyYou }: { options: Maker[]; va{m.label} <SourceBadge source={m.source} />{onlyYou?.(m) && <OnlyYou />}</span>- <span className="block text-[12px] leading-snug text-muted-foreground">{visitor ? withoutOwnGpu(m.note) : m.note}</span>+ <span className="block text-[12px] leading-snug text-muted-foreground">{m.note}</span></span></button>))}diff --git a/src/components/genjutsu/hooks.ts b/src/components/genjutsu/hooks.tsindex 96ba5db9..ddec2555 100644--- a/src/components/genjutsu/hooks.ts+++ b/src/components/genjutsu/hooks.ts@@ -7,6 +7,13 @@ import type { FinishOptions, GenjutsuLook, GenjutsuMode, GenjutsuTarget, Genjutsimport type { Engine, Generation, PixelPoint } from "@/lib/catalog/types";import { useDebounced } from "@/components/faceless/hooks";import { send } from "@/components/shorts/hooks";+import { COMPUTER_KICK_EVENT } from "@/lib/api";++/**+ * A run started: the tab that runs this person's jobs on the ComfyUI on this computer (an account's "Your GPU") asks for+ * them at once, as after a studio run.+ */+const kick = () => window.dispatchEvent(new Event(COMPUTER_KICK_EVENT));/** React Query hooks for /api/genjutsu/**. */@@ -78,6 +85,7 @@ export function useGenjutsuRun() {return useMutation({mutationFn: (b: GenjutsuBody) => send<{ final: Generation; items: Generation[] }>("/api/genjutsu", "POST", b),onSuccess: (r) => {+ kick();r.items.forEach((g) => qc.setQueryData(["generation", g.id], g));void qc.invalidateQueries({ queryKey: ["generations"] });},@@ -94,12 +102,13 @@ export function useDescribeScene() {return useMutation({mutationFn: (b: { engine: "open"; source: { url: string; duration?: number }; range: { start: number; end: number }; frame?: string; ownPerson?: boolean }) =>send<{ id: string; modelId: string }>("/api/genjutsu/scene", "POST", b),+ onSuccess: kick,});}/** The clip's words (one transcription; the page takes the part's lines from its cues). */export function useTranscribeClip() {- return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number }; cleanVoiceFirst?: boolean }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b) });+ return useMutation({ mutationFn: (b: { engine: Engine; source: { url: string; duration?: number }; cleanVoiceFirst?: boolean }) => send<{ id: string; modelId: string }>("/api/genjutsu/transcribe", "POST", b), onSuccess: kick });}/** Waits for one generation to finish (polling; the page's helpers that fill a field from it). */diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.tsindex 2c327eb9..a3de5d61 100644--- a/src/lib/guest-access.ts+++ b/src/lib/guest-access.ts@@ -266,17 +266,34 @@ export function isLibraryChange(method: string, pathname: string): boolean {export const ACCOUNT_LIBRARY_MESSAGE = "We can't find that.";export const LIBRARY_MESSAGE = "Saving here isn't available. Download what you make from your runs.";+/** A report anyone may send, signed in or not ("Report this result" on a shared link). */+export const anyoneMayReport = (method: string, pathname: string): boolean => method === "POST" && pathname === "/api/reports";++/**+ * The tools an account runs on its own GPU or key, beside the studios' generations. Each route makes an account's checks+ * itself (src/server/account-tool-run.ts: its own files, its limits, its GPU or key for every step) and refuses a guest+ * with the sign-up card. Genjutsu's "Describe my character" isn't here: it uses the studio's own AI helper.+ */+export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [/^\/api\/genjutsu(\/(scene|transcribe))?$/];++/**+ * A tool's project routes that keep each account's projects apart (src/server/account-projects.ts): the proxy lets an+ * account's reads and changes through, and the route answers with its own projects only (another's reads as not found).+ * A guest's change gets the sign-up card; its reads go by guestRead. A tool adds its routes here when it opens to+ * accounts.+ */+export const ACCOUNT_PROJECT_ROUTES: RegExp[] = [];++export const accountProjectRoute = (pathname: string): boolean => ACCOUNT_PROJECT_ROUTES.some((r) => r.test(pathname));+/*** Runs an account may start once it has connected its own ComfyUI ("Your GPU") or added its own fal.ai or Replicate key* ("Your keys"): the studios' generations, camera motions, effects and apps, which the route sends to that ComfyUI or- * that key only, with only its own uploaded files (src/app/api/generations/route.ts, generations.ts accountRun). Other- * tools plan with the install's AI helpers or its own ComfyUI, so they stay refused.+ * that key only, with only its own uploaded files (src/app/api/generations/route.ts, generations.ts accountRun), and+ * the tools in ACCOUNT_TOOL_RUNS. Other tools plan with the install's AI helpers or its own ComfyUI, so they stay refused.*/-/** A report anyone may send, signed in or not ("Report this result" on a shared link). */-export const anyoneMayReport = (method: string, pathname: string): boolean => method === "POST" && pathname === "/api/reports";-export function ownGpuRun(method: string, pathname: string): boolean {- return method === "POST" && pathname === "/api/generations";+ return method === "POST" && (pathname === "/api/generations" || ACCOUNT_TOOL_RUNS.some((r) => r.test(pathname)));}/** The code on an account's run refused because its runs going are at the limit: the next one may wait for a place and send again. */diff --git a/src/proxy.ts b/src/proxy.tsindex 3d847039..a57811db 100644--- a/src/proxy.ts+++ b/src/proxy.ts@@ -11,6 +11,7 @@ import {liveRoute,accountMayChange,accountOwnRead,+ accountProjectRoute,anyoneMayReport,ASSIST_OWNER_MESSAGE,CONNECT_GPU_HEADER,@@ -214,7 +215,7 @@ function guest(request: NextRequest): NextResponse {if (isAssistChange(method, pathname)) return assistOwner();if (anyoneMayReport(method, pathname)) return pass(request);// What an account may send, the library, the owner's settings and the studios' runs: signing up is the next step.- if (!accountMayChange(method, pathname, search) && !isLibraryChange(method, pathname) && !ownerOnly(method, pathname) && !ownGpuRun(method, pathname)) return ownGpuTool();+ if (!accountMayChange(method, pathname, search) && !isLibraryChange(method, pathname) && !ownerOnly(method, pathname) && !ownGpuRun(method, pathname) && !accountProjectRoute(pathname)) return ownGpuTool();return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });}@@ -272,6 +273,8 @@ function account(request: NextRequest, who: Account): NextResponse {if (gen !== undefined) return generationAccount(gen) === who.id ? pass(request) : notYours();const file = request.method === "GET" || request.method === "HEAD" ? /^\/api\/files\/(.+)$/.exec(pathname)?.[1] : undefined;if (file !== undefined) return fileAccount(safeDecode(file)) === who.id ? pass(request) : notYours();+ // A tool's projects, kept per account: the route answers with its own only.+ if (accountProjectRoute(pathname)) return pass(request);if (request.method === "GET" || request.method === "HEAD") return accountOwnRead(pathname) ? pass(request) : readAsGuest(request, true);if (isPriceCheck(request.method, pathname, search)) return priceCheck(request, `account:${who.id}`);if (accountMayChange(request.method, pathname, search)) return pass(request);diff --git a/src/server/account-projects.ts b/src/server/account-projects.tsnew file mode 100644index 00000000..cc7b8082--- /dev/null+++ b/src/server/account-projects.ts@@ -0,0 +1,217 @@+import "server-only";+import type Database from "better-sqlite3";+import { nanoid } from "nanoid";+import { accountInputProblem, type InputProblem } from "./account-inputs";+import { generationAccount } from "./account-library";+import { db } from "./db";+import { hit } from "./rate";++/**+ * An account's own projects (public sign-up), for the tools that keep a project of their own: a Shorts session, a+ * storyboard, a Cinema project, a Character Swap project… One table for every kind, never the owner's tables: every+ * read and change names the account and the kind, so one account never reaches another's project, and the owner's+ * projects are never in reach (an id that is another's reads as "not here", the same as one that doesn't exist).+ *+ * The same pattern as an account's canvases (account-canvas.ts): a project holds its own data as JSON, with a small+ * summary its list reads. A project names only the account's own files and runs (projectRefsProblem); its runs are+ * ordinary generations, started through account-tool-run.ts. Everything goes when the account is deleted+ * (account-sweep.ts purgeAccount).+ */++export const ACCOUNT_PROJECT_LIMITS = {+ /** Projects an account keeps, per kind. */+ projects: 50,+ /** One project's data as JSON (characters). */+ bytes: 1_000_000,+ /** Its list's summary as JSON (characters). */+ summaryBytes: 4_000,+ /** Saves a minute per account, every kind together (an editor's autosave is debounced, so far above what it sends). */+ savesPerMinute: 120,+} as const;++/** A kind: lower case letters, digits and dashes ("shorts", "storyboard", "cinema", "swap"). */+const KIND = /^[a-z][a-z0-9-]{0,31}$/;++const TABLE = `CREATE TABLE IF NOT EXISTS account_projects (+ id TEXT PRIMARY KEY,+ account_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ name TEXT NOT NULL,+ data_json TEXT NOT NULL,+ summary_json TEXT,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE INDEX IF NOT EXISTS account_projects_account ON account_projects(account_id, kind, updated_at DESC);`;++declare global {+ var __fuobeAccountProjects: WeakSet<Database.Database> | undefined;+}++/** The database, with the table made the first time (not a numbered migration: no branch's migrations clash over it). */+function store(): Database.Database {+ const d = db();+ const made = (globalThis.__fuobeAccountProjects ??= new WeakSet());+ if (!made.has(d)) {+ d.exec(TABLE);+ made.add(d);+ }+ return d;+}++interface Row {+ id: string;+ account_id: string;+ kind: string;+ name: string;+ data_json: string;+ summary_json: string | null;+ created_at: number;+ updated_at: number;+}++export interface AccountProject<D = unknown, S = unknown> {+ id: string;+ kind: string;+ name: string;+ data: D;+ summary: S | null;+ createdAt: number;+ updatedAt: number;+}++/** A project's line in its list: never its data. */+export type AccountProjectSummary<S = unknown> = Omit<AccountProject<never, S>, "data">;++/** What a save answers: small (an autosave sends often). */+export interface AccountProjectSaved {+ id: string;+ name: string;+ updatedAt: number;+}++/** Why a change was refused, with the status the route answers. */+export class AccountProjectError extends Error {+ constructor(+ message: string,+ readonly status: number,+ ) {+ super(message);+ }+}++function kindOf(kind: string): string {+ if (!KIND.test(kind)) throw new Error(`Not a project kind: ${kind}`);+ return kind;+}++const cleanName = (name: string | undefined, fallback: string) => (name?.replace(/\s+/g, " ").trim() || fallback).slice(0, 80);++function dataJson(data: unknown): string {+ const json = JSON.stringify(data ?? null);+ if (json.length > ACCOUNT_PROJECT_LIMITS.bytes) throw new AccountProjectError("This project is too big to save. Remove a few parts of it, then try again.", 413);+ return json;+}++function summaryJson(summary: unknown): string | null {+ if (summary === undefined || summary === null) return null;+ const json = JSON.stringify(summary);+ if (json.length > ACCOUNT_PROJECT_LIMITS.summaryBytes) throw new AccountProjectError("This project's summary is too big to save.", 413);+ return json;+}++const toProject = <D, S>(r: Row): AccountProject<D, S> => ({+ id: r.id,+ kind: r.kind,+ name: r.name,+ data: JSON.parse(r.data_json) as D,+ summary: r.summary_json ? (JSON.parse(r.summary_json) as S) : null,+ createdAt: r.created_at,+ updatedAt: r.updated_at,+});++/** The account's projects of one kind, newest first: each one's summary, never its data. */+export function listAccountProjects<S = unknown>(accountId: string, kind: string): AccountProjectSummary<S>[] {+ const rows = store()+ .prepare("SELECT id, kind, name, summary_json, created_at, updated_at FROM account_projects WHERE account_id = ? AND kind = ? ORDER BY updated_at DESC LIMIT ?")+ .all(accountId, kindOf(kind), ACCOUNT_PROJECT_LIMITS.projects) as Omit<Row, "account_id" | "data_json">[];+ return rows.map((r) => ({ id: r.id, kind: r.kind, name: r.name, summary: r.summary_json ? (JSON.parse(r.summary_json) as S) : null, createdAt: r.created_at, updatedAt: r.updated_at }));+}++/** One of the account's projects of that kind, or null (another account's, another kind's or none read the same). */+export function getAccountProject<D = unknown, S = unknown>(accountId: string, kind: string, id: string): AccountProject<D, S> | null {+ const r = store().prepare("SELECT * FROM account_projects WHERE id = ? AND account_id = ? AND kind = ?").get(id, accountId, kindOf(kind)) as Row | undefined;+ return r ? toProject<D, S>(r) : null;+}++export function createAccountProject<D, S = unknown>(accountId: string, kind: string, input: { name?: string; data: D; summary?: S }): AccountProject<D, S> {+ const k = kindOf(kind);+ const count = (store().prepare("SELECT COUNT(*) AS n FROM account_projects WHERE account_id = ? AND kind = ?").get(accountId, k) as { n: number }).n;+ if (count >= ACCOUNT_PROJECT_LIMITS.projects) throw new AccountProjectError(`You can keep up to ${ACCOUNT_PROJECT_LIMITS.projects} of these. Delete one to make another.`, 409);+ const now = Date.now();+ const row: Row = {+ id: nanoid(12),+ account_id: accountId,+ kind: k,+ name: cleanName(input.name, "Untitled"),+ data_json: dataJson(input.data),+ summary_json: summaryJson(input.summary),+ created_at: now,+ updated_at: now,+ };+ store()+ .prepare(`INSERT INTO account_projects (${Object.keys(row).join(", ")}) VALUES (${Object.keys(row).map((c) => `@${c}`).join(", ")})`)+ .run(row);+ return toProject<D, S>(row);+}++/** A new name, data and/or summary for one of the account's projects; null when it has no such project of that kind. */+export function updateAccountProject(accountId: string, kind: string, id: string, patch: { name?: string; data?: unknown; summary?: unknown }): AccountProjectSaved | null {+ const name = patch.name?.trim() ? cleanName(patch.name, "") : null;+ const data = patch.data === undefined ? null : dataJson(patch.data);+ const summary = patch.summary === undefined ? null : summaryJson(patch.summary);+ const now = Date.now();+ const done = store()+ .prepare(+ "UPDATE account_projects SET name = COALESCE(?, name), data_json = COALESCE(?, data_json), summary_json = COALESCE(?, summary_json), updated_at = ? WHERE id = ? AND account_id = ? AND kind = ?",+ )+ .run(name, data, summary, now, id, accountId, kindOf(kind));+ if (!done.changes) return null;+ const r = store().prepare("SELECT name FROM account_projects WHERE id = ?").get(id) as Pick<Row, "name">;+ return { id, name: r.name, updatedAt: now };+}++export function deleteAccountProject(accountId: string, kind: string, id: string): boolean {+ return store().prepare("DELETE FROM account_projects WHERE id = ? AND account_id = ? AND kind = ?").run(id, accountId, kindOf(kind)).changes > 0;+}++/** Every project of an account, when the account is deleted. */+export function deleteAccountProjects(accountId: string): number {+ return store().prepare("DELETE FROM account_projects WHERE account_id = ?").run(accountId).changes;+}++/**+ * The first problem with what a project names, or null: every file must be the account's own upload or result (or one+ * of Fuobe's published example files), and every run its own. Another's run reads as not found, as a gone one.+ */+export function projectRefsProblem(accountId: string, refs: { files?: string[]; runs?: string[] }): InputProblem | null {+ const files = (refs.files ?? []).filter(Boolean);+ const problem = files.length ? accountInputProblem({ inputs: { images: files } }, accountId) : null;+ if (problem) return problem;+ for (const run of refs.runs ?? []) {+ if (generationAccount(run) !== accountId) return { status: 404, code: "input-gone", error: "We can't find that run." };+ }+ return null;+}++/** Saves a minute per account (every kind together): a runaway tab can't fill the database. 429 past it. */+export function projectSavesLimited(accountId: string): Response | null {+ const rate = hit(`account-project:${accountId}`, ACCOUNT_PROJECT_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) } });+}++/** The route's answer to a refused change (AccountProjectError); anything else is thrown on. */+export function projectRefused(e: unknown): Response {+ if (e instanceof AccountProjectError) return Response.json({ error: e.message }, { status: e.status });+ throw e;+}diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.tsindex d7c85914..86e1437c 100644--- a/src/server/account-sweep.ts+++ b/src/server/account-sweep.ts@@ -3,6 +3,7 @@ import fs from "node:fs";import path from "node:path";import { RETENTION_MS, runAccountDeletedHooks } from "./account-files";import { deleteAccountCanvases } from "./account-canvas";+import { deleteAccountProjects } from "./account-projects";import { clearAccountLoras } from "./account-loras";import { accountById, deleteAccount, readAccountIds, setAccountDisabled } from "./auth";import { strayAccountIds } from "./auth-store";@@ -45,6 +46,7 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: nfor (const f of files) deleteAsset(f);clearAccountLoras(id);deleteAccountCanvases(id);+ deleteAccountProjects(id);await runAccountDeletedHooks(id);return { runs, files: files.length };}diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsnew file mode 100644index 00000000..49806d7e--- /dev/null+++ b/src/server/account-tool-run.ts@@ -0,0 +1,292 @@+import "server-only";+import { ACTIVE_RUNS_CODE, CONNECT_GPU_HEADER, GUEST_HEADER, GUEST_RUN_MESSAGE, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";+import { ANY_ANGLE } from "@/lib/catalog/any-angle";+import { graphLoras as h3GraphLoras } from "@/lib/catalog/character-swap";+import { pikaFlexGraphLoras } from "@/lib/catalog/pika-flex";+import { regenerateGraphLoras } from "@/lib/catalog/regenerate";+import type { GenerationRequest, MediaKind } from "@/lib/catalog/types";+import { missingFilesMessage, type MissingFiles } from "@/lib/missing-files";+import { restoreGraphLoras } from "@/lib/restore-graph";+import { ADD_KEY_HEADER } from "@/lib/your-keys";+import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "./account-files";+import { accountInputProblem } from "./account-inputs";+import { checkAccountLoras } from "./account-loras";+import { requestViewer, type Account } from "./auth";+import { db } from "./db";+import { accountRun, AccountRunError, asAccount, asVisitor, outputKind, previewChained, type AccountRunRefusal } from "./generations";+import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";+import { gpuTargetFor } from "./gpu/target";+import { moderateRun } from "./hosted-run";+import { hit, unhit } from "./rate";+import { withRunStamp, type RunStamp } from "./run-stamp";+import { once } from "./shorts-schemas";+import { ShortsError } from "./shorts";++/**+ * A tool's run for a signed-in account (public sign-up): Genjutsu first, then the other tools that plan a run as a+ * pipeline of ordinary generations (createGenerations / createPipeline). It makes the checks POST /api/generations makes+ * for a studio run, for every step of the tool's plan, before anything is queued:+ *+ * - room on the server and in the account's files, its runs going at once and its runs an hour (one tool run is one run:+ * its steps share a batch);+ * - only its own files (uploads and results) or Fuobe's published example files (account-inputs.ts);+ * - each step's provider is one the account has: its own ComfyUI ("Your GPU") or its own fal.ai or Replicate key+ * ("Your keys"); never the install's GPU, keys or AI helper (accountRun: 403 connect-gpu, add-key or own-gpu-tool);+ * - the GPU pre-flight on its own ComfyUI (409 gpu-setup with the guided fix), and the LoRAs a step adds (409+ * comfy_missing_model);+ * - the moderation service's check, when one is set (hosted-run.ts moderateRun).+ *+ * Then the tool's own start runs inside asAccount (tenant.ts): every generation it creates is stamped as the account's,+ * reads only its files and goes to its GPU or key. Where a run goes is decided in one place (`placeOf`): today always the+ * account's own GPU or key. Hosted runs (the install's GPUs) hook in there.+ *+ * The owner's runs never come here: a route runs them as before.+ */++/** Who is asking: the owner, a signed-in account, or a guest (who signs up first). */+export type ToolViewer = { kind: "owner" } | { kind: "account"; account: Account } | { kind: "guest" };++export const toolViewer = (request: Request): ToolViewer => requestViewer(request) as ToolViewer;++const NO_STORE = { "Cache-Control": "no-store" };++/** A guest's run: the "Create a free account to run this" card (the proxy answers it first; this is the route's own). */+export const guestRun = () => Response.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: { [GUEST_HEADER]: "1", ...NO_STORE } });++/** A tool (or a step of one) that doesn't run on an account's own GPU or key: one answer, no sign-up card. */+export const ownGpuTool = () => Response.json({ error: OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" }, { status: 403, headers: NO_STORE });++/**+ * Run `fn` as the viewer's work: the owner's as it is; an account's inside asAccount (its files, its runs, its GPU, its+ * keys and its engine mode). A guest has no work of its own: asVisitor (the open engine, no GPU, no demo).+ */+export function asViewer<T>(v: ToolViewer, fn: () => T): T {+ if (v.kind === "owner") return fn();+ return v.kind === "account" ? asAccount(v.account.id, fn) : asVisitor(null, fn);+}++/**+ * A tool's price check as the asker's run would go: the owner's as always; an account's as its own run (its GPU, its+ * keys, so a paid model on its own key is priced too); a guest's on the open engine with no GPU and no demo. Unlike+ * visitor.ts priceAs (a studio's price check for a visitor, always the open engine), an account with its own key prices+ * the cloud engine. A price check never calls a GPU: the planners read files' headers only.+ */+export function priceAsRun<T>(request: Request, fn: () => T): T {+ return asViewer(toolViewer(request), fn);+}++/** A refused run, kept as its parts so a repeat of the same request id gets its own copy of the answer. */+class Refused {+ constructor(+ readonly status: number,+ readonly headers: [string, string][],+ readonly text: string,+ ) {}+}++/**+ * An account's tool run once per client request id (shorts-schemas.ts once): a repeat of the id (a second click that got+ * through, a retried POST) gets the first run, and never another account's. A refusal isn't kept: sent again (after the+ * account connects its GPU, say), the run is checked again. `ok` turns the started run into the route's answer.+ */+export async function onceForAccount<T>(+ account: Account,+ scope: string,+ id: string | undefined,+ fn: () => Promise<AccountToolResult<T>>,+ ok: (r: { value: T; gpuWarning?: string }) => Response,+): Promise<Response> {+ try {+ const r = await once(`${scope}:acct:${account.id}`, id, async () => {+ const out = await fn();+ if (!out.ok) throw new Refused(out.response.status, [...out.response.headers], await out.response.text());+ return out;+ });+ return ok(r);+ } catch (e) {+ if (e instanceof Refused) return new Response(e.text, { status: e.status, headers: e.headers });+ throw e;+ }+}++/** An account's runs going now (queued or running), counted as runs: a run's jobs and steps share a batch. */+export function activeAccountRuns(accountId: string): number {+ const r = db()+ .prepare("SELECT COUNT(DISTINCT COALESCE(batch_id, id)) AS n FROM generations WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') = ?")+ .get(accountId) as { n: number };+ return r.n;+}++/** A request body over what an account's run may weigh (its files are uploaded first): 413 before it is read. */+export function bodyTooBig(request: Request): Response | null {+ return Number(request.headers.get("content-length") ?? 0) > ACCOUNT_LIMITS.runBodyBytes ? refuse(413, ACCOUNT_MESSAGES.bodyTooBig) : null;+}++const refuse = (status: number, error: string, extra: Record<string, unknown> = {}, headers: Record<string, string> = {}) =>+ Response.json({ error, ...extra }, { status, headers: { ...NO_STORE, ...headers } });++/** An account's step that can't go where it was planned: Connect your GPU, Add your key (the client opens either). */+export function refusalResponse(r: AccountRunRefusal): Response {+ const headers: Record<string, string> = r.code === "connect-gpu" ? { [CONNECT_GPU_HEADER]: "1" } : r.code === "add-key" && r.provider ? { [ADD_KEY_HEADER]: r.provider } : {};+ return refuse(403, r.error, { code: r.code, ...(r.provider && { provider: r.provider }) }, headers);+}++/** One step of a tool's plan: the request it will create, and how many earlier steps it waits for (their outputs go in). */+export interface ToolStep {+ request: GenerationRequest;+ /** Earlier steps it waits for (createPipeline's `after`): 0 for a step that starts at once. */+ deps?: number;+}++/** Where an account's tool run goes. Today always its own GPU or key ("own"); hosted runs add the install's GPUs. */+export type ToolPlace = { kind: "own" };++/**+ * Where this run goes. The one place a tool run's placement is decided: hosted runs (hosted-run.ts decidePlace, the+ * billing hold and runOnPool) hook in here for tools, as POST /api/generations does for the studios. Until then a tool+ * runs on the account's own GPU or key, whatever FUOBE_HOSTED_RUNS says (docs/public-signup.md: "Every other tool still+ * needs the account's own GPU").+ */+export async function placeOf(account: Account, steps: ToolStep[]): Promise<ToolPlace> {+ void account;+ void steps;+ return { kind: "own" };+}++export interface AccountToolRun<T> {+ /** The tool, for the run limit's key and the logs ("genjutsu"). */+ tool: string;+ /** Every file the request names (its clip, pictures, masks…): only the account's own, or Fuobe's example files. */+ files: (string | null | undefined)[];+ /**+ * The run's steps, planned as the account (inside asAccount): what will be created, for the provider, pre-flight and+ * LoRA checks. Throw a ShortsError (its status) or an Error (422) to refuse with its words.+ */+ plan: () => ToolStep[] | Promise<ToolStep[]>;+ /** Creates the run (inside asAccount, after every check): createGenerations / createPipeline, nothing else. */+ start: () => T | Promise<T>;+ /** `gpuCheck: "skip"` from the request (the pre-flight's "Run anyway"). */+ skipGpuCheck?: boolean;+}++export type AccountToolResult<T> = { ok: true; value: T; gpuWarning?: string } | { ok: false; response: Response };++type Planned = { step: ToolStep; p: ReturnType<typeof previewChained> };++/**+ * The LoRA files the run's ComfyUI steps load that the account's ComfyUI doesn't have (call it inside asAccount): each+ * step's added LoRAs and the ones its graph loads itself, as accountLoraFix reads them for a studio run. Null when+ * nothing is missing, or its list couldn't be read.+ */+async function missingLoras(planned: Planned[]): Promise<MissingFiles | null> {+ const items: MissingFiles["items"] = [];+ let workflowId: string | undefined;+ for (const { step, p } of planned) {+ if (p.route.provider !== "comfyui") continue;+ const extra = step.request.params?.extra;+ const needs = [...p.loras.applied, ...h3GraphLoras(p.route.endpoint, extra), ...restoreGraphLoras(p.route.endpoint, extra), ...regenerateGraphLoras(p.route.endpoint, extra), ...pikaFlexGraphLoras(p.route.endpoint, extra)];+ const f = await checkAccountLoras(needs, p.route.endpoint);+ if (!f) continue;+ workflowId ??= f.workflowId;+ for (const i of f.items) if (!items.some((x) => x.file === i.file)) items.push(i);+ }+ return items.length ? { code: "comfy_missing_model", ...(workflowId && { workflowId }), items } : null;+}++const CLIP = /\.(mp4|mov|webm|mkv|avi)$/i;+const SOUND = /\.(mp3|wav|ogg|flac|m4a)$/i;++/** A run's files by kind (by their stored names), for the moderation service. */+function filesAsInputs(files: string[]): GenerationRequest["inputs"] {+ const videos = files.filter((f) => CLIP.test(f));+ const audios = files.filter((f) => SOUND.test(f));+ const images = files.filter((f) => !videos.includes(f) && !audios.includes(f));+ return { ...(images.length && { images }), ...(videos.length && { videos }), ...(audios.length && { audios }) };+}++/** A user-facing error while planning or starting: its status (ShortsError), the account's refusal, or a 422. */+function errorResponse(e: unknown): Response {+ if (e instanceof AccountRunError) return refusalResponse(e.refusal);+ if (e instanceof ShortsError) return refuse(e.status, e.message);+ return refuse(422, (e as Error).message || "Something went wrong. Please try again.");+}++/**+ * Check and start an account's tool run (see the header). The answer is the tool's own value, or the response that+ * refuses it. Nothing is queued unless every check passed; a refused run doesn't count against the account's hour.+ */+export async function runAccountTool<T>(request: Request, account: Account, run: AccountToolRun<T>): Promise<AccountToolResult<T>> {+ const id = account.id;+ const no = (response: Response): AccountToolResult<T> => ({ ok: false, response });+ if (!diskHasRoom()) return no(refuse(503, ACCOUNT_MESSAGES.diskLow));+ if (accountUsage(id).total >= accountTotalBytes(id)) return no(refuse(413, filesFullMessage(id)));+ if (activeAccountRuns(id) >= ACCOUNT_LIMITS.activeRuns) return no(refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" }));+ const rate = hit(`run:${id}`, ACCOUNT_LIMITS.runsPerHour, 60 * 60_000);+ if (!rate.ok) return no(refuse(429, ACCOUNT_MESSAGES.runRate, {}, { "Retry-After": String(rate.retryAfterS) }));+ // From here a refusal gives the run back to the hour.+ const back = (response: Response): AccountToolResult<T> => {+ unhit(`run:${id}`);+ return no(response);+ };+ // Only files it uploaded here, or its own results (no links, no data: URIs, nobody else's).+ const files = run.files.filter((f): f is string => typeof f === "string" && f.length > 0);+ const problem = files.length ? accountInputProblem({ inputs: { images: files } }, id) : null;+ if (problem) return back(refuse(problem.status, problem.error, { code: problem.code }));+ let steps: ToolStep[];+ try {+ steps = await asAccount(id, run.plan);+ } catch (e) {+ return back(errorResponse(e));+ }+ if (!steps.length) return back(refuse(422, "Nothing to run yet."));+ const place = await placeOf(account, steps);+ let gpuWarning: string | undefined;+ let kind: MediaKind = "video";+ let onKey = false;+ try {+ // Each step's provider must be one the account has; a 3D model is finished on the server (not for accounts yet).+ const planned: Planned[] = steps.map((s) => ({ step: s, p: asAccount(id, () => previewChained(s.request, s.deps ?? 0)) }));+ if (place.kind === "own") {+ for (const provider of new Set(planned.map((x) => x.p.route.provider))) {+ const own = accountRun(id, provider, "submit");+ if ("error" in own) return back(refusalResponse(own));+ }+ }+ if (planned.some(({ p }) => outputKind(p.op, p.model) === "model3d" && p.model.id !== ANY_ANGLE.buildModel)) return back(ownGpuTool());+ // GPU pre-flight on its own ComfyUI: a step sure to fail for something missing stops the run with the plan that+ // fixes it (never when the check is unknown). Each workflow once.+ const target = gpuTargetFor(request, "read");+ const seen = new Set<string>();+ for (const { step, p } of planned) {+ if (p.route.provider !== "comfyui" || seen.has(p.route.endpoint)) continue;+ seen.add(p.route.endpoint);+ const gate = await gateGeneration(target, { request: step.request, route: p.route, op: p.op, modelId: p.model.id, gpu: p.gpu, h3: p.h3, skip: run.skipGpuCheck, actor: id });+ if (!gate.ok) return back(refuse(409, gate.message, { code: "gpu-setup", ref: gate.ref, plan: gate.plan }, { [GPU_SETUP_HEADER]: "1" }));+ gpuWarning ??= gate.warning;+ }+ // The LoRAs its steps load (added to the request, or the graph's own) must be on its own ComfyUI: which to download,+ // before anything is queued. The same check runs again when each step is handed over.+ const fix = await asAccount(id, () => missingLoras(planned));+ if (fix) return back(refuse(409, missingFilesMessage(fix), { code: "comfy_missing_model", fix }));+ const last = planned[planned.length - 1].p;+ kind = outputKind(last.op, last.model);+ onKey = planned.some(({ p }) => p.route.provider !== "comfyui");+ } catch (e) {+ return back(errorResponse(e));+ }+ // The moderation service's check (none set: nothing is checked), on the run's words and its files.+ const first = steps.find((s) => !s.deps) ?? steps[0];+ const words = steps.map((s) => s.request.prompt?.trim()).filter(Boolean);+ const checked: GenerationRequest = { ...first.request, prompt: [...new Set(words)].join("\n").slice(0, 8000), inputs: filesAsInputs(files) };+ const mod = await moderateRun(account, checked, null, "own", { kind, place: onKey ? "own-key" : "own-gpu" });+ if (!mod.ok) return back(refuse(mod.refusal.status, mod.refusal.body.error, mod.refusal.body, mod.refusal.headers));+ const stamp: RunStamp | null = mod.checkOutputs ? { checkOutputs: true } : null;+ // Counted again just before the run is stored, with nothing awaited in between.+ if (activeAccountRuns(id) >= ACCOUNT_LIMITS.activeRuns) return back(refuse(429, ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" }));+ try {+ const value = await asAccount(id, () => (stamp ? withRunStamp(stamp, run.start) : run.start()));+ return { ok: true, value, ...(gpuWarning && { gpuWarning }) };+ } catch (e) {+ return back(errorResponse(e));+ }+}diff --git a/src/server/genjutsu.ts b/src/server/genjutsu.tsindex bd77a1c9..b35b7c54 100644--- a/src/server/genjutsu.ts+++ b/src/server/genjutsu.ts@@ -56,11 +56,11 @@ import {} from "@/lib/catalog/genjutsu";import { MASK_TRACKER, REMOVE_TOOLS, scalePoints, wholeClip, type RemoveRange, type RemoveSource } from "@/lib/catalog/remove-object";import { planSegments, type PlanStep } from "@/lib/catalog/shorts";-import type { Engine, Generation, PixelPoint, ProviderId } from "@/lib/catalog/types";+import type { Engine, Generation, GenerationRequest, PixelPoint, ProviderId } from "@/lib/catalog/types";import { silenceWriter } from "./canvas";import { createPipeline } from "./chains";import { llmText, llmTextBackend } from "./enhance";-import { ConnectComfyError, createGenerations, previewChained } from "./generations";+import { AccountRunError, ConnectComfyError, createGenerations, previewChained } from "./generations";import { db } from "./db";import { genjutsuLive } from "./genjutsu-live";import { decodePng } from "./png";@@ -73,6 +73,7 @@ import { pointsFromPaint } from "./remove-object";import { engineMode, getSetting } from "./settings";import { probeSource, ShortsError } from "./shorts";import { readRef } from "./storage";+import { tenantAccount } from "./tenant";/*** Fuobe Genjutsu (/genjutsu): plans, prices and starts a Motion transfer, Character swap, Object swap, Restyle or Insert@@ -357,20 +358,23 @@ async function planInput(body: GenjutsuBody, opts: { probe: boolean; viewer?: Ge};}-/** Whether a first frame is one this install's From picture made (and finished). */+/**+ * Whether a first frame is one this install's From picture made (and finished) for the asker: the owner's own frames, or+ * inside an account's work (tenant.ts) that account's own. Never another's.+ */function madeFrame(url: string | undefined): boolean {if (!url) return false;- // Looked up by its address, however old (not in the Trash, not an account's run).+ // Looked up by its address, however old (not in the Trash).const row = db().prepare(`SELECT 1 FROM generations gWHERE g.model_id = 'oss-from-picture-frame' AND g.status = 'succeeded'- AND json_extract(g.request_json, '$.account') IS NULL+ AND json_extract(g.request_json, '$.account') IS ?AND NOT EXISTS (SELECT 1 FROM generation_trash t WHERE t.generation_id = g.id)AND EXISTS (SELECT 1 FROM json_each(g.outputs_json) o WHERE json_extract(o.value, '$.url') = ?)LIMIT 1`,)- .get(url);+ .get(tenantAccount() ?? null, url);return !!row;}@@ -687,24 +691,54 @@ export async function estimateGenjutsu(body: GenjutsuBody, viewer: GenjutsuViewe};}-/** Start it; returns the finished video's generation (the other steps wait for each other). */-export async function createGenjutsu(body: GenjutsuBody, viewer: GenjutsuViewer = OWNER): Promise<{ final: Generation; items: Generation[] }> {+/** A Genjutsu run planned and checked, not started yet: its steps, and the one that makes the finished video. */+export interface GenjutsuRun {+ steps: PlanStep[];+ final: string;+}++/**+ * Plan a run as it will start (the clip's header read, every step checked and priced): nothing is made yet. An account's+ * run is planned inside its own work (src/server/account-tool-run.ts), so its steps are checked before any starts.+ */+export async function planGenjutsuRun(body: GenjutsuBody, viewer: GenjutsuViewer = OWNER): Promise<GenjutsuRun> {const { input } = await planInput(body, { probe: true, viewer });try {const plan = planGenjutsu(input);// The same check as the estimate: nothing starts when only some of the steps have a provider.price(plan.steps, input);+ return { steps: plan.steps, final: plan.final };+ } catch (e) {+ if (e instanceof ShortsError) throw e;+ if (e instanceof ConnectComfyError) throw e;+ if (e instanceof AccountRunError) throw e;+ throw new ShortsError((e as Error).message, 422);+ }+}++/** A planned run's steps as the requests they make, with how many earlier steps each waits for. */+export const genjutsuSteps = (run: GenjutsuRun): { request: GenerationRequest; deps: number }[] => run.steps.map((s) => ({ request: withChain(s), deps: s.after?.length ?? 0 }));++/** Start a planned run; returns the finished video's generation (the other steps wait for each other). */+export function startGenjutsu(run: GenjutsuRun): { final: Generation; items: Generation[] } {+ try {// A silent clip's cloud swap ends on silence: its WAV is written now (silenceRef, as Canvas mutes a clip).const withSilence = silenceWriter();- const p = createPipeline(plan.steps.map((s) => ({ ...s, request: withSilence(s.request) })));- return { final: p.byKey[plan.final], items: p.items };+ const p = createPipeline(run.steps.map((s) => ({ ...s, request: withSilence(s.request) })));+ return { final: p.byKey[run.final], items: p.items };} catch (e) {if (e instanceof ShortsError) throw e;if (e instanceof ConnectComfyError) throw e;+ if (e instanceof AccountRunError) throw e;throw new ShortsError((e as Error).message, 422);}}+/** Plan and start it (the owner's runs; an account's go through src/server/account-tool-run.ts). */+export async function createGenjutsu(body: GenjutsuBody, viewer: GenjutsuViewer = OWNER): Promise<{ final: Generation; items: Generation[] }> {+ return startGenjutsu(await planGenjutsuRun(body, viewer));+}+// ---------------------------------------------------------------------------// Character swap helpers: "Describe my character" and the part's words (Akatz Labs' description and transcript)@@ -762,6 +796,11 @@ export const SceneSchema = z.object({* frame (a step of its own; the page waits for its text and puts it in an editable box). Owner-only, like the runs.*/export function describeScene(body: z.infer<typeof SceneSchema>, viewer: GenjutsuViewer = OWNER): { id: string; modelId: string } {+ return startStep(sceneRequest(body, viewer));+}++/** The describer's request for "What happens", checked (an account's is checked again by its run's gate first). */+export function sceneRequest(body: z.infer<typeof SceneSchema>, viewer: GenjutsuViewer = OWNER): GenerationRequest {mustMatchMode("open");if (!openFor(viewer)("picture")) throw new ShortsError(NOT_HERE, 422);const len = body.range.end - body.range.start;@@ -770,19 +809,25 @@ export function describeScene(body: z.infer<typeof SceneSchema>, viewer: Genjutsif (!body.ownPerson && !madeFrame(body.frame)) throw new ShortsError("Make and pick the first frame first", 422);const modelId = "oss-scene-describe";if (!isOffered(modelId, "open")) throw new ShortsError(`Describing is switched off in ${ACCESS_PLACE} — write what happens in your own words`, 422);+ return {+ feature: GENJUTSU.stepFeature,+ batchTitle: "Genjutsu · what happens",+ modelId,+ op: "describe-video",+ inputs: { video: body.source.url, ...(body.ownPerson ? {} : { images: [body.frame!] }) },+ params: { startTime: body.range.start, extra: { openjutsu: { seconds: len, ownPerson: !!body.ownPerson } } },+ step: { label: "What happens in the part", index: 0, of: 1 },+ };+}++/** Start a helper step (the clip's words, what happens): one generation the page waits for. */+export function startStep(req: GenerationRequest): { id: string; modelId: string } {try {- const [g] = createGenerations({- feature: GENJUTSU.stepFeature,- batchTitle: "Genjutsu · what happens",- modelId,- op: "describe-video",- inputs: { video: body.source.url, ...(body.ownPerson ? {} : { images: [body.frame!] }) },- params: { startTime: body.range.start, extra: { openjutsu: { seconds: len, ownPerson: !!body.ownPerson } } },- step: { label: "What happens in the part", index: 0, of: 1 },- });- return { id: g.id, modelId };+ const [g] = createGenerations(req);+ return { id: g.id, modelId: req.modelId };} catch (e) {if (e instanceof ConnectComfyError) throw e;+ if (e instanceof AccountRunError) throw e;throw new ShortsError((e as Error).message, 422);}}@@ -802,23 +847,22 @@ export const TranscribeSchema = z.object({* afterwards takes its own lines from it in the browser (partWords). A Genjutsu step: it stays out of the page's feed.*/export function transcribeClip(body: z.infer<typeof TranscribeSchema>): { id: string; modelId: string } {+ return startStep(transcribeRequest(body));+}++/** The transcriber's request for the clip's words, checked (an account's is checked again by its run's gate first). */+export function transcribeRequest(body: z.infer<typeof TranscribeSchema>): GenerationRequest {mustMatchMode(body.engine);const modelId = TRANSCRIBERS[body.engine];if (!isOffered(modelId, body.engine)) throw new ShortsError(`${getModel(modelId)?.name ?? modelId} is switched off in ${ACCESS_PLACE} — type the words instead`, 422);const seconds = body.source.duration;- try {- const [g] = createGenerations({- feature: GENJUTSU.stepFeature,- batchTitle: "Genjutsu · the clip's words",- modelId,- op: "transcribe",- inputs: { video: body.source.url },- ...((seconds || body.cleanVoiceFirst) && { params: { ...(seconds && { duration: seconds, sourceDuration: seconds }), ...(body.cleanVoiceFirst && { extra: { cleanVoiceFirst: true } }) } }),- step: { label: "The clip's words", index: 0, of: 1 },- });- return { id: g.id, modelId };- } catch (e) {- if (e instanceof ConnectComfyError) throw e;- throw new ShortsError((e as Error).message, 422);- }+ return {+ feature: GENJUTSU.stepFeature,+ batchTitle: "Genjutsu · the clip's words",+ modelId,+ op: "transcribe",+ inputs: { video: body.source.url },+ ...((seconds || body.cleanVoiceFirst) && { params: { ...(seconds && { duration: seconds, sourceDuration: seconds }), ...(body.cleanVoiceFirst && { extra: { cleanVoiceFirst: true } }) } }),+ step: { label: "The clip's words", index: 0, of: 1 },+ };}diff --git a/tests/account-genjutsu.test.ts b/tests/account-genjutsu.test.tsnew file mode 100644index 00000000..24975601--- /dev/null+++ b/tests/account-genjutsu.test.ts@@ -0,0 +1,360 @@+import fs from "node:fs";+import path from "node:path";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { startFakeComfy, TINY_PNG, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++/**+ * Genjutsu for a signed-in account (public sign-up): it runs on the account's own ComfyUI (a stand-in here) through the+ * same generations every studio run makes, with only its own files, and its runs stay its own. A guest gets the sign-up+ * card; another account and the owner's Library are never reached.+ */+const dir = tempDir("fuobe-account-genjutsu-");+process.env.FUOBE_DATA_DIR = dir;+process.env.COMFYUI_URL = "http://owner-comfy.test:8188";+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+delete process.env.FUOBE_HOSTED_RUNS;+globalThis.__fuobeTestDiskFree = 1e13;++// Plain fetch is the install's own ComfyUI ("owner-comfy.test"): recorded, so a test sees that nothing reached it.+const realFetch = globalThis.fetch;+const fetched: string[] = [];+globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input instanceof Request ? input.url : input));+ if (url.hostname === "127.0.0.1") return realFetch(input, init);+ fetched.push(url.toString());+ if (url.host !== "owner-comfy.test:8188") return new Response("not stubbed", { status: 599 });+ if (url.pathname === "/system_stats") return Response.json({ system: { comfyui_version: "owner", ram_total: 1 }, devices: [] });+ return Response.json({});+}) as typeof fetch;++const auth = await import("@/server/auth");+const genjutsuRoute = await import("@/app/api/genjutsu/route");+const estimateRoute = await import("@/app/api/genjutsu/estimate/route");+const describeRoute = await import("@/app/api/genjutsu/describe/route");+const transcribeRoute = await import("@/app/api/genjutsu/transcribe/route");+const sceneRoute = await import("@/app/api/genjutsu/scene/route");+const uploadsRoute = await import("@/app/api/uploads/route");+const gpuRoute = await import("@/app/api/account/gpu/route");+const { proxy } = await import("@/proxy");+const access = await import("@/lib/guest-access");+const { getGeneration, listGenerations } = await import("@/server/generations");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const { clearAccountLoras } = await import("@/server/account-loras");+const { saveFile } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { sceneRequest } = await import("@/server/genjutsu");+const { ACCOUNT_LIMITS } = await import("@/server/account-files");++const CLIP = fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4"));+const src = { duration: 12, fps: 16, width: 72, height: 128, hasAudio: true };++let fake: FakeComfy;+let a = "";+let b = "";+let c = "";+const cookies: Record<string, string> = {};+beforeAll(async () => {+ fake = await startFakeComfy({ loras: [], delayMs: 0 });+ globalThis.__fuobeTestGpuPort = fake.port;+ auth.setPassword("install password");+ for (const [k, email] of [+ ["a", "[email protected]"],+ ["b", "[email protected]"],+ ["c", "[email protected]"],+ ] as const) {+ const id = auth.createAccount(email, "long enough").id;+ cookies[k] = `${auth.SESSION_COOKIE}=${auth.createSession(id).value}`;+ if (k === "a") a = id;+ if (k === "b") b = id;+ if (k === "c") c = id;+ }+ cookies.owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ // A and B link their own ComfyUI; C has neither a GPU nor a key.+ for (const who of ["a", "b"]) expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: fake.url }, who))).status).toBe(200);+});+afterAll(async () => {+ globalThis.fetch = realFetch;+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ await fake.close();+});+beforeEach(() => {+ resetRates();+ for (const id of [a, b]) clearAccountLoras(id);+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running') AND json_extract(request_json, '$.account') IS NOT NULL").run();+});++function json(url: string, method: string, body: unknown, who?: string): Request {+ const text = JSON.stringify(body);+ return new Request(`http://localhost:3000${url}`, {+ method,+ headers: { host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)), ...(who && { cookie: cookies[who] }) },+ body: text,+ });+}++const viaProxy = (url: string, method = "GET", who?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(who && { cookie: cookies[who] }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));+const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++async function upload(who: string, data: Buffer, type: string, name: string): Promise<string> {+ const r = await uploadsRoute.POST(new Request("http://localhost:3000/api/uploads", { method: "POST", headers: { host: "localhost:3000", cookie: cookies[who], "content-type": type, "x-file-name": name, "content-length": String(data.length) }, body: new Uint8Array(data) }));+ expect(r.status, await r.clone().text()).toBe(201);+ return ((await r.json()) as { url: string }).url;+}++/** Tick the runner until the row is done (or the time is up). */+async function settle(id: string, ms = 30_000) {+ const end = Date.now() + ms;+ for (;;) {+ await globalThis.__fuobeRunner?.tick();+ const g = getGeneration(id, { includeDeleted: true });+ if (!g || (g.status !== "queued" && g.status !== "running") || Date.now() > end) return g;+ await new Promise((r) => setTimeout(r, 100));+ }+}++/** What GET /api/generations?features=genjutsu lists for an account (the route lists its own runs only). */+const mine = (who: "a" | "b") => listGenerations({ features: ["genjutsu"], account: who === "a" ? a : b });++const motion = (clip: string, pic: string, extra: Record<string, unknown> = {}) => ({ engine: "open", mode: "motion", references: [pic], source: { url: clip, ...src }, range: { start: 0, end: 6 }, ...extra });++/** Start a run; a LoRA its ComfyUI lacks is put there (the 409 names it), then it is sent again. */+async function start(body: unknown, who: string): Promise<Response> {+ let r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", body, who));+ if (r.status === 409) {+ const j = (await r.json()) as { code: string; fix: { items: { file: string }[] } };+ expect(j.code).toBe("comfy_missing_model");+ fake.opts.loras = [...(fake.opts.loras ?? []), ...j.fix.items.map((i) => i.file)];+ for (const id of [a, b]) clearAccountLoras(id);+ r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", body, who));+ }+ return r;+}++describe("the proxy opens Genjutsu's runs to accounts, and keeps the sign-up card for guests", () => {+ it("a guest gets the sign-up card on a run, the part's words and what happens; describing stays the owner's", async () => {+ for (const p of ["/api/genjutsu", "/api/genjutsu/scene", "/api/genjutsu/transcribe"]) {+ const r = viaProxy(p, "POST");+ expect(r.status, p).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER), p).toBe("1");+ expect((await r.json()).error).toBe(access.GUEST_RUN_MESSAGE);+ }+ const d = viaProxy("/api/genjutsu/describe", "POST");+ expect(d.status).toBe(403);+ expect((await d.json()).code).toBe("own-gpu-tool");+ // A price check stays open to everyone.+ expect(passed(viaProxy("/api/genjutsu/estimate", "POST"))).toBe(true);+ });++ it("an account with its own GPU reaches the routes; one with neither a GPU nor a key is asked to connect one", async () => {+ for (const p of ["/api/genjutsu", "/api/genjutsu/scene", "/api/genjutsu/transcribe"]) {+ expect(passed(viaProxy(p, "POST", "a")), p).toBe(true);+ const r = viaProxy(p, "POST", "c");+ expect(r.status, p).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ }+ // Describing uses the studio's own AI helper: never an account's.+ const d = viaProxy("/api/genjutsu/describe", "POST", "a");+ expect(d.status).toBe(403);+ expect((await d.json()).code).toBe("own-gpu-tool");+ expect(access.ownGpuRun("POST", "/api/genjutsu/describe")).toBe(false);+ expect(access.ownGpuRun("GET", "/api/genjutsu")).toBe(false);+ expect(access.ownGpuRun("POST", "/api/genjutsu/examples")).toBe(false);+ });++ it("the routes refuse a guest themselves, and describing refuses anyone but the owner", async () => {+ for (const [route, p] of [+ [genjutsuRoute, "/api/genjutsu"],+ [sceneRoute, "/api/genjutsu/scene"],+ [transcribeRoute, "/api/genjutsu/transcribe"],+ ] as const) {+ const r = await route.POST(json(p, "POST", {}));+ expect(r.status, p).toBe(401);+ expect(r.headers.get(access.GUEST_HEADER)).toBe("1");+ }+ for (const who of [undefined, "a"]) {+ const r = await describeRoute.POST(json("/api/genjutsu/describe", "POST", { engine: "open", image: "/api/files/x.png" }, who));+ expect(r.status).toBe(403);+ expect((await r.json()).code).toBe("own-gpu-tool");+ }+ });+});++describe("an account runs Genjutsu on its own ComfyUI", () => {+ let clip = "";+ let pic = "";+ let final = "";+ beforeAll(async () => {+ clip = await upload("a", CLIP, "video/mp4", "dance.mp4");+ pic = await upload("a", TINY_PNG, "image/png", "me.png");+ });++ it("prices it for its own GPU, never as a demo", async () => {+ const r = await estimateRoute.POST(json("/api/genjutsu/estimate", "POST", motion(clip, pic), "a"));+ expect(r.status, await r.clone().text()).toBe(200);+ const e = (await r.json()) as { demo: boolean; providers: string[] };+ expect(e.demo).toBe(false);+ expect(e.providers).toEqual(["comfyui"]);+ });++ it("runs Motion transfer end to end: every step is its own, on its ComfyUI, and the result is its own file", async () => {+ fake.log.length = 0;+ fetched.length = 0;+ const r = await start(motion(clip, pic, { requestId: "same-request-id-1" }), "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const body = (await r.json()) as { final: { id: string }; items: { id: string; batchId: string | null }[] };+ final = body.final.id;+ expect(body.items.length).toBeGreaterThan(1);+ // One run: its steps share a batch.+ expect(new Set(body.items.map((g) => g.batchId)).size).toBe(1);+ for (const g of body.items) expect(getGeneration(g.id)!.request.account, g.id).toBe(a);+ const done = await settle(final);+ expect(done?.status, done?.error ?? "").toBe("succeeded");+ for (const g of body.items) expect(getGeneration(g.id)!.status, g.id).toBe("succeeded");+ // Every step went to its own ComfyUI; nothing reached the install's.+ expect(fake.log.filter((e) => e.path === "/prompt").length).toBe(body.items.length);+ expect(fetched.filter((u) => !u.endsWith("/system_stats"))).toEqual([]);+ // The result is its own file.+ const out = done!.outputs[0];+ expect(out.url).toMatch(/^\/api\/files\/outputs\//);+ expect((db().prepare("SELECT account_id FROM assets WHERE id = ?").get(out.assetId) as { account_id: string }).account_id).toBe(a);+ expect(passed(viaProxy(out.url, "GET", "a"))).toBe(true);+ // Its list shows it; the result opens for it (and downloads: the file above).+ const list = mine("a");+ expect(list.map((g) => g.id)).toContain(final);+ expect(passed(viaProxy(`/api/generations/${final}`, "GET", "a"))).toBe(true);+ });++ it("a second click with the same request id gets the same run", async () => {+ const r = await start(motion(clip, pic, { requestId: "same-request-id-1" }), "a");+ expect(r.status).toBe(201);+ expect(((await r.json()) as { final: { id: string } }).final.id).toBe(final);+ });++ it("another account never sees, opens or reuses it", async () => {+ // Its runs and files: 403 through the proxy, and not in B's list.+ const out = getGeneration(final)!.outputs[0].url;+ expect(viaProxy(`/api/generations/${final}`, "GET", "b").status).toBe(403);+ expect(viaProxy(out, "GET", "b").status).toBe(403);+ expect(viaProxy(out, "GET").status).toBe(401);+ const list = mine("b");+ expect(list).toEqual([]);+ // A's clip in B's run: refused before anything is planned or sent.+ fake.log.length = 0;+ const own = await upload("b", TINY_PNG, "image/png", "b.png");+ const r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(clip, own), "b"));+ expect(r.status).toBe(403);+ expect((await r.json()).code).toBe("input-not-yours");+ expect(fake.log.some((e) => e.path === "/prompt")).toBe(false);+ // The same request id from B is B's own request, never A's run.+ const bClip = await upload("b", CLIP, "video/mp4", "b.mp4");+ const bRun = await start(motion(bClip, own, { requestId: "same-request-id-1" }), "b");+ expect(bRun.status, await bRun.clone().text()).toBe(201);+ const bFinal = ((await bRun.json()) as { final: { id: string } }).final.id;+ expect(bFinal).not.toBe(final);+ expect(getGeneration(bFinal)!.request.account).toBe(b);+ });++ it("the owner's Library is never reachable: an owner's file is refused, and the owner's runs aren't in its list", async () => {+ const ownerClip = saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "owner.mp4" }).url;+ const r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(ownerClip, pic), "a"));+ expect(r.status).toBe(403);+ expect((await r.json()).code).toBe("input-not-yours");+ // Through the proxy the owner's file and the owner's Genjutsu runs are closed to it, and its list never has them.+ expect(viaProxy(ownerClip, "GET", "a").status).toBe(403);+ const t = Date.now();+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES ('owner-genjutsu', 'genjutsu', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'succeeded', ?, ?, ?, ?)",+ )+ .run(JSON.stringify({ feature: "genjutsu", modelId: "oss-trim" }), JSON.stringify([{ url: ownerClip, kind: "video" }]), t, t);+ expect(viaProxy("/api/generations/owner-genjutsu", "GET", "a").status).toBe(403);+ expect(viaProxy("/api/generations/owner-genjutsu", "DELETE", "a").status).toBe(403);+ const ids = mine("a").map((g) => g.id);+ expect(ids).toContain(final);+ expect(ids).not.toContain("owner-genjutsu");+ // The owner's own result as an input: refused like any file that isn't its own.+ const reuse = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(clip, ownerClip), "a"));+ expect(reuse.status).toBe(403);+ // A link or a data: URI never goes in.+ for (const url of ["https://example.com/a.mp4", "data:video/mp4;base64,AAAA"]) {+ const bad = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(url, pic), "a"));+ expect(bad.status, url).toBe(400);+ }+ });++ it("asks an account with neither a GPU nor a key to connect one, before anything is made", async () => {+ const own = runAsTenant({ kind: "account", id: c }, () => saveFile({ data: CLIP, contentType: "video/mp4", source: "upload", name: "c.mp4" }).url);+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;+ const r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(own, own), "c"));+ expect(r.status).toBe(403);+ expect(r.headers.get(access.CONNECT_GPU_HEADER)).toBe("1");+ expect((await r.json()).code).toBe("connect-gpu");+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);+ });++ it("keeps the account's limits: runs going at once, and a refusal doesn't use up its hour", async () => {+ const now = Date.now();+ const add = db().prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'genjutsu', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'queued', ?, '[]', ?, ?)",+ );+ for (let i = 0; i < ACCOUNT_LIMITS.activeRuns; i++) add.run(`busy-${i}`, JSON.stringify({ feature: "genjutsu", modelId: "oss-trim", account: a }), now, now);+ const r = await genjutsuRoute.POST(json("/api/genjutsu", "POST", motion(clip, pic), "a"));+ expect(r.status).toBe(429);+ expect((await r.json()).code).toBe(access.ACTIVE_RUNS_CODE);+ db().prepare("DELETE FROM generations WHERE id LIKE 'busy-%'").run();+ // A run body over what an account's run may weigh is refused before it is read.+ const big = new Request("http://localhost:3000/api/genjutsu", { method: "POST", headers: { host: "localhost:3000", cookie: cookies.a, "content-type": "application/json", "content-length": String(ACCOUNT_LIMITS.runBodyBytes + 1) }, body: "{}" });+ expect((await genjutsuRoute.POST(big)).status).toBe(413);+ });++ it("transcribes the clip's words on its own ComfyUI, and the clip must be its own", async () => {+ const r = await transcribeRoute.POST(json("/api/genjutsu/transcribe", "POST", { engine: "open", source: { url: clip, duration: 12 } }, "a"));+ expect(r.status, await r.clone().text()).toBe(201);+ const { id } = (await r.json()) as { id: string };+ expect(getGeneration(id)!.request.account).toBe(a);+ expect(getGeneration(id)!.provider).toBe("comfyui");+ const other = await transcribeRoute.POST(json("/api/genjutsu/transcribe", "POST", { engine: "open", source: { url: clip, duration: 12 } }, "b"));+ expect(other.status).toBe(403);+ expect((await other.json()).code).toBe("input-not-yours");+ });++ it("From picture's describer stays closed to visitors until From picture opens; a first frame counts only for whoever made it", async () => {+ const r = await sceneRoute.POST(json("/api/genjutsu/scene", "POST", { engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, ownPerson: true }, "a"));+ expect(r.status).toBe(422);+ // A first frame the owner made is no account's; the account's own is its own.+ const frame = (account: string | null, url: string) => {+ const t = Date.now();+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at) VALUES (?, 'genjutsu-step', 'oss-from-picture-frame', 'open', 'comfyui', 'picture-frame', 'image', 'succeeded', ?, ?, ?, ?)",+ )+ .run(`frame-${url.length}-${t}`, JSON.stringify(account ? { account } : {}), JSON.stringify([{ url, kind: "image" }]), t, t);+ };+ frame(null, "/api/files/owner-frame.png");+ frame(a, "/api/files/a-frame.png");+ const ask = (who: string | null, url: string) => {+ const run = () => {+ try {+ sceneRequest({ engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, frame: url }, { owner: true });+ return "";+ } catch (e) {+ return (e as Error).message;+ }+ };+ return who ? runAsTenant({ kind: "account", id: who }, run) : run();+ };+ expect(ask(a, "/api/files/a-frame.png")).toBe("");+ expect(ask(a, "/api/files/owner-frame.png")).toBe("Make and pick the first frame first");+ expect(ask(b, "/api/files/a-frame.png")).toBe("Make and pick the first frame first");+ expect(ask(null, "/api/files/owner-frame.png")).toBe("");+ expect(ask(null, "/api/files/a-frame.png")).toBe("Make and pick the first frame first");+ });+});diff --git a/tests/account-projects.test.ts b/tests/account-projects.test.tsnew file mode 100644index 00000000..e4bba2e1--- /dev/null+++ b/tests/account-projects.test.ts@@ -0,0 +1,147 @@+import { afterEach, beforeAll, describe, expect, it } from "vitest";+import { NextRequest } from "next/server";+import { tempDir } from "./helpers/temp-dir";++/**+ * An account's own projects (src/server/account-projects.ts): the store the tools that keep projects use once they open+ * to accounts. Every read and change names the account and the kind, so another account's project, another kind's and+ * the owner's are never in reach, and everything goes with the account.+ */+const dir = tempDir("fuobe-account-projects-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;++const auth = await import("@/server/auth");+const store = await import("@/server/account-projects");+const access = await import("@/lib/guest-access");+const { proxy } = await import("@/proxy");+const { saveFile } = await import("@/server/storage");+const { runAsTenant } = await import("@/server/tenant");+const { purgeAccount } = await import("@/server/account-sweep");+const { resetRates } = await import("@/server/rate");+const { db } = await import("@/server/db");++let a = "";+let b = "";+const cookies: Record<string, string> = {};+beforeAll(() => {+ auth.setPassword("install password");+ a = auth.createAccount("[email protected]", "long enough").id;+ b = auth.createAccount("[email protected]", "long enough").id;+ cookies.a = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+});++describe("an account's projects are its own", () => {+ it("one account's project is out of another's reach, and out of another kind's", () => {+ const p = store.createAccountProject(a, "shorts", { name: " My short ", data: { scenes: [1, 2] }, summary: { scenes: 2 } });+ expect(p).toMatchObject({ kind: "shorts", name: "My short", data: { scenes: [1, 2] }, summary: { scenes: 2 } });+ expect(store.getAccountProject(a, "shorts", p.id)?.data).toEqual({ scenes: [1, 2] });+ // B, and A under another kind, read nothing, change nothing and delete nothing.+ expect(store.getAccountProject(b, "shorts", p.id)).toBeNull();+ expect(store.getAccountProject(a, "cinema", p.id)).toBeNull();+ expect(store.updateAccountProject(b, "shorts", p.id, { name: "mine now" })).toBeNull();+ expect(store.updateAccountProject(a, "cinema", p.id, { name: "mine now" })).toBeNull();+ expect(store.deleteAccountProject(b, "shorts", p.id)).toBe(false);+ expect(store.listAccountProjects(b, "shorts")).toEqual([]);+ expect(store.listAccountProjects(a, "cinema")).toEqual([]);+ // Its list holds the summary, never the data.+ const [line] = store.listAccountProjects(a, "shorts");+ expect(line).toMatchObject({ id: p.id, name: "My short", summary: { scenes: 2 } });+ expect(line).not.toHaveProperty("data");+ // Its own changes go through.+ expect(store.updateAccountProject(a, "shorts", p.id, { name: "Renamed", data: { scenes: [] } })).toMatchObject({ id: p.id, name: "Renamed" });+ expect(store.getAccountProject(a, "shorts", p.id)?.data).toEqual({ scenes: [] });+ expect(store.deleteAccountProject(a, "shorts", p.id)).toBe(true);+ expect(store.getAccountProject(a, "shorts", p.id)).toBeNull();+ });++ it("keeps its limits: projects per kind, a project's size and its summary's", () => {+ const k = "storyboard";+ for (let i = 0; i < store.ACCOUNT_PROJECT_LIMITS.projects; i++) store.createAccountProject(a, k, { data: { i } });+ expect(() => store.createAccountProject(a, k, { data: {} })).toThrow(store.AccountProjectError);+ // Another kind, and another account, have room of their own.+ expect(store.createAccountProject(a, "swap", { data: {} }).kind).toBe("swap");+ expect(store.createAccountProject(b, k, { data: {} }).kind).toBe(k);+ const big = "x".repeat(store.ACCOUNT_PROJECT_LIMITS.bytes);+ expect(() => store.createAccountProject(b, "swap", { data: { big } })).toThrow(/too big/);+ expect(() => store.createAccountProject(b, "swap", { data: {}, summary: { big } })).toThrow(/too big/);+ try {+ store.createAccountProject(a, k, { data: {} });+ } catch (e) {+ expect(store.projectRefused(e).status).toBe(409);+ }+ expect(() => store.listAccountProjects(a, "Not a kind")).toThrow();+ });++ it("names only its own files and runs", () => {+ const own = runAsTenant({ kind: "account", id: a }, () => saveFile({ data: Buffer.from("abc"), contentType: "image/png", source: "upload", name: "a.png" }).url);+ const owners = saveFile({ data: Buffer.from("abc"), contentType: "image/png", source: "upload", name: "o.png" }).url;+ const others = runAsTenant({ kind: "account", id: b }, () => saveFile({ data: Buffer.from("abc"), contentType: "image/png", source: "upload", name: "b.png" }).url);+ expect(store.projectRefsProblem(a, { files: [own] })).toBeNull();+ expect(store.projectRefsProblem(a, { files: [owners] })?.code).toBe("input-not-yours");+ expect(store.projectRefsProblem(a, { files: [others] })?.code).toBe("input-not-yours");+ expect(store.projectRefsProblem(a, { files: ["https://example.com/x.png"] })?.code).toBe("input-not-allowed");+ const t = Date.now();+ const run = (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 (?, 'shorts', 'oss-trim', 'open', 'comfyui', 'trim', 'video', 'succeeded', ?, '[]', ?, ?)")+ .run(id, JSON.stringify(account ? { account } : {}), t, t);+ run("proj-run-a", a);+ run("proj-run-b", b);+ run("proj-run-owner");+ expect(store.projectRefsProblem(a, { runs: ["proj-run-a"] })).toBeNull();+ expect(store.projectRefsProblem(a, { runs: ["proj-run-b"] })?.status).toBe(404);+ expect(store.projectRefsProblem(a, { runs: ["proj-run-owner"] })?.status).toBe(404);+ expect(store.projectRefsProblem(a, { runs: ["no-such-run"] })?.status).toBe(404);+ });++ it("limits saves a minute, every kind together", () => {+ resetRates();+ for (let i = 0; i < store.ACCOUNT_PROJECT_LIMITS.savesPerMinute; i++) expect(store.projectSavesLimited(b)).toBeNull();+ expect(store.projectSavesLimited(b)?.status).toBe(429);+ expect(store.projectSavesLimited(a)).toBeNull();+ resetRates();+ });++ it("goes with the account", async () => {+ const gone = auth.createAccount("[email protected]", "long enough").id;+ store.createAccountProject(gone, "cinema", { data: {} });+ store.createAccountProject(gone, "shorts", { data: {} });+ store.createAccountProject(a, "cinema", { data: {} });+ await purgeAccount(gone);+ expect(store.listAccountProjects(gone, "cinema")).toEqual([]);+ expect(store.listAccountProjects(gone, "shorts")).toEqual([]);+ expect(store.listAccountProjects(a, "cinema").length).toBeGreaterThan(0);+ });+});++describe("a tool's project routes go through the proxy for accounts only", () => {+ const route = /^\/api\/test-tool\/projects(\/[^/]+)?$/;+ afterEach(() => {+ access.ACCOUNT_PROJECT_ROUTES.splice(access.ACCOUNT_PROJECT_ROUTES.indexOf(route), 1);+ });+ const call = (method: string, url: string, cookie?: string) =>+ proxy(new NextRequest(`http://localhost:3000${url}`, { method, headers: { host: "localhost:3000", ...(cookie && { cookie }), ...(method !== "GET" && { "content-type": "application/json" }) }, ...(method !== "GET" && { body: "{}" }) }));+ const passed = (r: Response) => r.headers.get("x-middleware-next") === "1";++ it("lets an account's reads and changes reach the route, and gives a guest's change the sign-up card", async () => {+ // Not listed: an account's change to a tool's projects is refused as before.+ expect(passed(call("POST", "/api/test-tool/projects", cookies.a))).toBe(false);+ access.ACCOUNT_PROJECT_ROUTES.push(route);+ for (const [method, url] of [+ ["GET", "/api/test-tool/projects"],+ ["POST", "/api/test-tool/projects"],+ ["GET", "/api/test-tool/projects/p1"],+ ["PATCH", "/api/test-tool/projects/p1"],+ ["DELETE", "/api/test-tool/projects/p1"],+ ] as const) {+ expect(passed(call(method, url, cookies.a)), `${method} ${url}`).toBe(true);+ }+ const g = call("POST", "/api/test-tool/projects");+ expect(g.status).toBe(401);+ expect(g.headers.get(access.GUEST_HEADER)).toBe("1");+ // A guest's read goes by guestRead (closed here: nothing of anyone's).+ expect(call("GET", "/api/test-tool/projects").status).toBe(401);+ });+});diff --git a/tests/e2e/genjutsu-examples.mjs b/tests/e2e/genjutsu-examples.mjsindex bc08a462..8e4d1688 100644--- a/tests/e2e/genjutsu-examples.mjs+++ b/tests/e2e/genjutsu-examples.mjs@@ -3,9 +3,9 @@// only once the card is half in view and plays muted; nothing moves when it arrives; the pause button, the actions and// "How it was made" are 44 px; switching modes drops the loop; the card is the page column's width (640 px) and on a// phone short enough to leave the upload box close. Reduced motion: the finished result as a still, no download until-// Play. Visitors (--viewer guest | account: a studio with a password and public sign-up) see the video and how it was-// made, no action row (nothing there they could run), no model names, no "Only you", and "isn't available" under the-// card by the upload box. The owner: Use this example with no clip marks the card "In use" (the form's setup equals the+// Play. Visitors (--viewer guest | account: a studio with a password and public sign-up) see the video, how it was made,+// Use this example and Copy its setup (an account runs Genjutsu on its own GPU or key; a guest signs up when it adds its+// clip), no model names, no "Only you", and no "isn't available" note. The owner: Use this example with no clip marks the card "In use" (the form's setup equals the// recipe), moves the focus to Choose a video, says what is still needed, and Undo puts the form back; a second mode's// example after the first asks nothing; a clip added after an example takes the example's length, and a mode change// drops it; with a clip and the example's kind of photos the estimate's request body equals the run that made the@@ -166,11 +166,9 @@ try {if (visitor) check(`${tag} ${label}: no seed or "Part" chip for a visitor`, !/Seed \d|Part \d/.test(text), text.replace(/\s+/g, " ").slice(-120));check(`${tag} ${label}: no test words or file paths`, !/\b(test|pass(ed)?|owner|validated|oss-|\/api\/)/i.test(text), text.replace(/\s+/g, " ").slice(0, 160));if (visitor) {- check(`${tag} ${label}: a visitor has no Use this example`, (await c.locator("[data-use-example]").count()) === 0);- check(`${tag} ${label}: a visitor has no action row (only Play/Pause and How it was made)`, (await c.getByRole("button", { name: /Copy its setup/ }).count()) === 0 && (await c.locator("button").count()) === 1);+ check(`${tag} ${label}: a visitor has Use this example and Copy its setup`, (await c.locator("[data-use-example]").count()) === 1 && (await c.getByRole("button", { name: /Copy its setup/ }).count()) === 1);check(`${tag} ${label}: no model names and no "Only you" for a visitor`, !/Group swap|Colour finish|Only you|MiniMax|H3/.test(text));- const noteBox = await page.getByText("Genjutsu isn't available here.").first().boundingBox();- check(`${tag} ${label}: "isn't available" sits under the card, by the upload box`, !!noteBox && noteBox.y > cardBox.y + cardBox.height && noteBox.y < dropBox.y + dropBox.height, noteBox ? `${Math.round(noteBox.y)}` : "none");+ check(`${tag} ${label}: no "isn't available" note`, (await page.getByText("Genjutsu isn't available here.").count()) === 0);} else {check(`${tag} ${label}: the owner has Use this example`, await c.locator("[data-use-example]").isVisible());}diff --git a/tests/genjutsu-openjutsu-access.test.ts b/tests/genjutsu-openjutsu-access.test.tsindex 5b23687a..7926d37a 100644--- a/tests/genjutsu-openjutsu-access.test.ts+++ b/tests/genjutsu-openjutsu-access.test.ts@@ -175,20 +175,34 @@ describe("Genjutsu's Openjutsu features before and after they open", () => {expect(say("/api/files/never-made.png")).toBe("Make and pick the first frame first");});- it("From picture's describer is the owner's, like every Genjutsu run", async () => {+ it("From picture's describer runs for an account (on its own GPU) only once From picture opens; a guest signs up first", async () => {process.env.FUOBE_PUBLIC_SIGNUP = "1";- const cookie = auth.createSession(auth.createAccount(`oj${++n}@example.com`, "long enough").id).value;- for (const who of [undefined, cookie]) {- for (const p of ["/api/genjutsu", "/api/genjutsu/scene"]) {- const r = proxy(req(p, { method: "POST", cookie: who }));- expect(r.status, `${p} ${who ? "account" : "guest"}`).toBe(403);- expect((await r.json()).code).toBe("own-gpu-tool");- }+ const id = auth.createAccount(`oj${++n}@example.com`, "long enough").id;+ const cookie = auth.createSession(id).value;+ for (const p of ["/api/genjutsu", "/api/genjutsu/scene"]) {+ // A guest: the sign-up card. An account with neither a GPU nor a key: Connect your GPU.+ const g = proxy(req(p, { method: "POST" }));+ expect(g.status, `${p} guest`).toBe(401);+ expect((await g.json()).error).toBe(access.GUEST_RUN_MESSAGE);+ const r = proxy(req(p, { method: "POST", cookie }));+ expect(r.status, `${p} account`).toBe(403);+ expect((await r.json()).code).toBe("connect-gpu");}expect(access.isPriceCheck("POST", "/api/genjutsu/scene", "")).toBe(false);- // Behind the proxy the route refuses a visitor too.- const r = await sceneRoute.POST(call("/api/genjutsu/scene", { engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, ownPerson: true }));- expect(r.status).toBe(422);- expect((await r.json()).error).toBe(NOT_HERE);+ // Behind the proxy the route refuses a guest, and an account's describer while From picture hasn't opened.+ const body = { engine: "open", source: { url: clip }, range: { start: 0, end: 6 }, ownPerson: true };+ expect((await sceneRoute.POST(call("/api/genjutsu/scene", body))).status).toBe(401);+ const { runAsTenant } = await import("@/server/tenant");+ const own = runAsTenant({ kind: "account", id }, () => saveFile({ data: fs.readFileSync(path.join(__dirname, "fixtures/shorts-12s.mp4")), contentType: "video/mp4", source: "upload", name: "mine.mp4" }).url);+ globalThis.__fuobeTestDiskFree = 1e13;+ try {+ const r = await sceneRoute.POST(call("/api/genjutsu/scene", { ...body, source: { url: own } }, cookie));+ if (!genjutsuLive().picture) {+ expect(r.status).toBe(422);+ expect((await r.json()).error).toBe(NOT_HERE);+ }+ } finally {+ globalThis.__fuobeTestDiskFree = undefined;+ }});});diff --git a/tests/swap-studio-sharpen.test.ts b/tests/swap-studio-sharpen.test.tsindex 298ac3ff..d405945a 100644--- a/tests/swap-studio-sharpen.test.ts+++ b/tests/swap-studio-sharpen.test.ts@@ -268,13 +268,18 @@ describe("the route under public sign-up", () => {const cookie = auth.createSession(account.id).value;auth.setAccountGpu(account.id, { url: "https://gpu.example" });const at = (url: string, c?: string) => new NextRequest(`http://localhost:3000${url}`, { method: "POST", headers: c ? { cookie: `${auth.SESSION_COOKIE}=${c}` } : {}, body: "{}" });- for (const p of ["/api/swap-studio/projects/swap-1/sharpen", "/api/swap-studio/projects/swap-1/assemble", "/api/genjutsu"]) {+ for (const p of ["/api/swap-studio/projects/swap-1/sharpen", "/api/swap-studio/projects/swap-1/assemble"]) {for (const c of [undefined, cookie]) {const r = proxy(at(p, c));expect(r.status, `${p} ${c ? "account" : "guest"}`).toBe(403);expect(await r.json()).toEqual({ error: access.OWN_GPU_TOOL_MESSAGE, code: "own-gpu-tool" });}}+ // Genjutsu runs on an account's own GPU (its route makes the account's checks); a guest signs up first.+ expect(proxy(at("/api/genjutsu", cookie)).headers.get("x-middleware-next")).toBe("1");+ const guest = proxy(at("/api/genjutsu"));+ expect(guest.status).toBe(401);+ expect((await guest.json()).error).toBe(access.GUEST_RUN_MESSAGE);// Genjutsu's price check (2K included) stays open to visitors.expect(access.isPriceCheck("POST", "/api/genjutsu/estimate", "")).toBe(true);expect(proxy(at("/api/genjutsu/estimate")).headers.get("x-middleware-next")).toBe("1");