Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Hosted runs: one press of a tool's Run is one run and one hold, and limits count a run while it is made

Adarshb5d49d95bb81
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.ts
index 5062ad61..b81af843 100644
--- a/src/app/api/audio-tools/route.ts
+++ b/src/app/api/audio-tools/route.ts
@@ -1,4 +1,4 @@
-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, requestIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { AudioToolBody, AudioToolError, audioToolFiles, audioToolSteps, planAudioTool, previewAudioTool, runAudioTool, startAudioTool, type AudioToolPlan } from "@/server/audio-tools";
import { connectRefusal } from "@/server/connect-refusal";
import { ConnectComfyError } from "@/server/generations";
@@ -47,10 +47,11 @@ async function post(request: Request, preview: boolean) {
// An account's run: on its own GPU or key, with its own files, after the checks a studio run gets.
const body = parsed.data;
let planned: AudioToolPlan | null = null;
+ // A repeated requestId (a resend of the same press) gets the run the first one started.
return onceForAccount(
viewer.account,
"audio-tools",
- undefined,
+ requestIdOf(raw),
() =>
runAccountTool(request, viewer.account, {
tool: `audio-${body.tool}`,
diff --git a/src/app/api/cinema/projects/[id]/generate/route.ts b/src/app/api/cinema/projects/[id]/generate/route.ts
index 7a0ade10..7284e653 100644
--- a/src/app/api/cinema/projects/[id]/generate/route.ts
+++ b/src/app/api/cinema/projects/[id]/generate/route.ts
@@ -31,7 +31,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/proj
return onceForAccount(
viewer.account,
`cinema:${id}`,
- undefined,
+ b.requestId,
() =>
runAccountTool(request, viewer.account, {
tool: "cinema",
diff --git a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts
index 05d7a1e6..f72206d2 100644
--- a/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts
+++ b/src/app/api/cinema/projects/[id]/items/[generationId]/retry/route.ts
@@ -1,4 +1,4 @@
-import { guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { guestRun, onceForAccount, requestIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { planRetry, retryItem, retrySteps, startRetry, type RetryPlan } from "@/server/cinema";
import { handle, withStatus } from "@/server/cinema-schemas";
@@ -13,10 +13,12 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/proj
const { id, generationId } = await ctx.params;
if (viewer.kind === "owner") return Response.json({ items: retryItem(id, generationId) }, { status: 201 });
let plan: RetryPlan | null = null;
+ // The page's id for this press (an optional body): a resend of it gets the first retry.
+ const sent: unknown = await request.json().catch(() => null);
return onceForAccount(
viewer.account,
`cinema-retry:${id}:${generationId}`,
- undefined,
+ requestIdOf(sent),
() =>
runAccountTool(request, viewer.account, {
tool: "cinema",
diff --git a/src/app/api/content-factory/series/[id]/read/route.ts b/src/app/api/content-factory/series/[id]/read/route.ts
index d2d63e30..a370ce09 100644
--- a/src/app/api/content-factory/series/[id]/read/route.ts
+++ b/src/app/api/content-factory/series/[id]/read/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { handle, rereadSeries, rereadSteps, seriesClip } from "@/server/content-factory";
import { body } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -18,7 +18,13 @@ export async function POST(request: Request, ctx: RouteContext<"/api/content-fac
const { engine } = await body(request, Read, "Pick an engine");
if (viewer.kind === "owner") return Response.json(await rereadSeries(id, engine));
const clip = asViewer(viewer, () => seriesClip(id));
- const out = await runAccountTool(request, viewer.account, { tool: "content-factory", files: [clip], plan: () => planned(() => rereadSteps(id, engine)), start: () => rereadSeries(id, engine) });
- return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }) : out.response;
+ // A resend of the same press (the page's id in its header) gets the reading the first one started.
+ return onceForAccount(
+ viewer.account,
+ `content-factory-read:${id}`,
+ pressIdOf(request),
+ () => runAccountTool(request, viewer.account, { tool: "content-factory", files: [clip], plan: () => planned(() => rereadSteps(id, engine)), start: () => rereadSeries(id, engine) }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }),
+ );
}, request);
}
diff --git a/src/app/api/content-factory/series/route.ts b/src/app/api/content-factory/series/route.ts
index 6f24edc3..60c7e800 100644
--- a/src/app/api/content-factory/series/route.ts
+++ b/src/app/api/content-factory/series/route.ts
@@ -1,7 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
import { projectSavesLimited } from "@/server/account-projects";
-import { asViewer, guestRun, ownGpuTool, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, ownGpuTool, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { createSeries, handle, listSeries, makeSeries, prepareSeries, ReferenceSchema, seriesReadSteps, seriesReads, type PreparedSeries } from "@/server/content-factory";
import { body } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -38,12 +38,19 @@ export async function POST(request: Request) {
if (viewer.kind === "account" && input.reference?.kind === "link") return ownGpuTool();
if (viewer.kind === "owner" || !seriesReads(input)) return Response.json(await asViewer(viewer, () => createSeries(input)), { status: 201 });
let prepared: PreparedSeries | null = null;
- const out = await runAccountTool(request, viewer.account, {
- tool: "content-factory",
- files: input.reference?.kind === "upload" ? [input.reference.url] : [],
- plan: () => planned(async () => seriesReadSteps((prepared = await prepareSeries(input)))),
- start: () => makeSeries(prepared!),
- });
- return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 }) : out.response;
+ // A resend of the same press (the page's id in its header) gets the series the first one made.
+ return onceForAccount(
+ viewer.account,
+ "content-factory",
+ pressIdOf(request),
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "content-factory",
+ files: input.reference?.kind === "upload" ? [input.reference.url] : [],
+ plan: () => planned(async () => seriesReadSteps((prepared = await prepareSeries(input)))),
+ start: () => makeSeries(prepared!),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.ts
index e09e5a17..af011a40 100644
--- a/src/app/api/dub/[id]/voice/route.ts
+++ b/src/app/api/dub/[id]/voice/route.ts
@@ -8,6 +8,8 @@ const Body = z.object({
/** The reviewed lines (saved with the run); omitted = the saved draft or the translation. */
cues: z.array(CueSchema).max(3000).optional(),
lipsync: z.boolean().optional(),
+ /** The page's id for this press of Run: a resend of it gets the first run. */
+ requestId: z.string().trim().min(8).max(64).optional(),
});
/** Speak one language's reviewed lines in the cloned voice: the voice pipeline; `?preview=1` only prices it. */
@@ -26,7 +28,7 @@ async function post(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">,
return onceForAccount(
viewer.account,
`dub-voice:${id}`,
- undefined,
+ parsed.data.requestId,
() =>
runAccountTool(request, viewer.account, {
tool: "dub",
diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.ts
index cd4bb5ec..1d1f767f 100644
--- a/src/app/api/dub/route.ts
+++ b/src/app/api/dub/route.ts
@@ -19,6 +19,8 @@ const Body = z.object({
duration: z.number().positive().max(36_000).optional(),
/** Open engine: the voice split (MelBand RoFormer or DBS). */
voiceSplit: z.enum(VOICE_SPLIT_IDS as [VoiceSplit, ...VoiceSplit[]]).optional(),
+ /** The page's id for this press of Run: a resend of it gets the first dub. */
+ requestId: z.string().trim().min(8).max(64).optional(),
});
/** Recent dubs with the state of every step: the owner's, or a signed-in account's own (a guest has none). */
@@ -48,7 +50,7 @@ async function post(request: Request, preview: boolean) {
return onceForAccount(
viewer.account,
"dub",
- undefined,
+ input.requestId,
() =>
runAccountTool(request, viewer.account, {
tool: "dub",
diff --git a/src/app/api/explainer/route.ts b/src/app/api/explainer/route.ts
index 082cbd70..e0916309 100644
--- a/src/app/api/explainer/route.ts
+++ b/src/app/api/explainer/route.ts
@@ -2,7 +2,7 @@ import { connection } from "next/server";
import { z } from "zod";
import { MAX_TOPIC } from "@/lib/catalog/faceless";
import { projectSavesLimited } from "@/server/account-projects";
-import { asViewer, bodyTooBig, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, bodyTooBig, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { body, composeScript, createEpisode, draftGraph, FacelessError, graphToolSteps, handle, listEpisodes, SettingsSchema, SourceSchema } from "@/server/faceless";
import { filesRefused, planned, settingsFiles, sourceFiles } from "@/server/faceless-account";
@@ -50,12 +50,19 @@ export async function POST(request: Request) {
const composed = await asViewer(viewer, () => composeScript({ kind: "explainer", channelId: null, topic: input.prompt.trim(), settings: input.settings, sources }, ""));
const ask = { kind: "explainer" as const, topic: input.prompt, sources, settings: input.settings, composed };
if (input.review) return Response.json(asViewer(viewer, () => createEpisode(ask)), { status: 201 });
- const out = await runAccountTool(request, viewer.account, {
- tool: "explainer",
- files,
- plan: () => planned(() => graphToolSteps(draftGraph({ kind: "explainer", title: composed.title ?? input.prompt, settings: input.settings, sources, script: composed }))),
- start: () => createEpisode({ ...ask, autoRender: true }),
- });
- return out.ok ? Response.json({ ...out.value, ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 }) : out.response;
+ // A resend of the same press (the page's id in its header) gets the episode the first one started.
+ return onceForAccount(
+ viewer.account,
+ "explainer",
+ pressIdOf(request),
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "explainer",
+ files,
+ plan: () => planned(() => graphToolSteps(draftGraph({ kind: "explainer", title: composed.title ?? input.prompt, settings: input.settings, sources, script: composed }))),
+ start: () => createEpisode({ ...ask, autoRender: true }),
+ }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.ts
index abc33588..47ecca95 100644
--- a/src/app/api/faceless/channels/[id]/avatar/route.ts
+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts
@@ -1,4 +1,4 @@
-import { guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { avatarRequest, handle, makeAvatar } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -12,7 +12,13 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/ch
return handle(async () => {
const { id } = await ctx.params;
if (viewer.kind === "owner") return Response.json(makeAvatar(id), { status: 201 });
- const run = await runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: avatarRequest(id) }]), start: () => makeAvatar(id) });
- return run.ok ? Response.json({ ...run.value, ...(run.gpuWarning && { gpuWarning: run.gpuWarning }) }, { status: 201 }) : run.response;
+ // A resend of the same press (the page's id in its header) gets the avatar the first one started.
+ return onceForAccount(
+ viewer.account,
+ `faceless-avatar:${id}`,
+ pressIdOf(request),
+ () => runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: avatarRequest(id) }]), start: () => makeAvatar(id) }),
+ ({ value, gpuWarning }) => Response.json({ ...value, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/faceless/channels/route.ts b/src/app/api/faceless/channels/route.ts
index 106eba75..5b9a940d 100644
--- a/src/app/api/faceless/channels/route.ts
+++ b/src/app/api/faceless/channels/route.ts
@@ -1,7 +1,7 @@
import { connection } from "next/server";
import { z } from "zod";
import { projectSavesLimited } from "@/server/account-projects";
-import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { avatarRequest, body, createChannel, EngineSchema, GenreSchema, handle, listChannels, makeAvatar } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -36,13 +36,23 @@ export async function POST(request: Request) {
return handle(async () => {
const input = await body(request, Create, "Describe the channel and pick a genre");
if (viewer.kind === "owner") return Response.json(await createChannel(input), { status: 201 });
- const channel = await asViewer(viewer, () => createChannel(input));
- const avatar = await runAccountTool(request, viewer.account, {
- tool: "faceless",
- files: [],
- plan: () => planned(() => [{ request: avatarRequest(channel.id) }]),
- start: () => makeAvatar(channel.id),
- });
- return Response.json(avatar.ok ? { ...channel, avatarJob: avatar.value.id } : channel, { status: 201 });
+ const account = viewer.account;
+ // A resend of the same press (the page's id in its header) gets the channel, and its avatar, the first one made.
+ return onceForAccount(
+ account,
+ "faceless-channel",
+ pressIdOf(request),
+ async () => {
+ const channel = await asViewer(viewer, () => createChannel(input));
+ const avatar = await runAccountTool(request, account, {
+ tool: "faceless",
+ files: [],
+ plan: () => planned(() => [{ request: avatarRequest(channel.id) }]),
+ start: () => makeAvatar(channel.id),
+ });
+ return { ok: true as const, value: avatar.ok ? { ...channel, avatarJob: avatar.value.id } : channel };
+ },
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.ts
index 10a9aa90..240d988e 100644
--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts
+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts
@@ -1,5 +1,5 @@
import type { GenerationRequest } from "@/lib/catalog/types";
-import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import {
episodeView,
graphFiles,
@@ -77,8 +77,13 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/ep
}),
);
}
- const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: work.files, plan: () => planned(() => checked(id).steps), start: () => run(id) });
- if (!out.ok) return out.response;
- return Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) });
+ // A resend of the same press (the page's id in its header) gets the run the first one started.
+ return onceForAccount(
+ viewer.account,
+ `faceless-${action}:${id}`,
+ pressIdOf(request),
+ () => runAccountTool(request, viewer.account, { tool: "faceless", files: work.files, plan: () => planned(() => checked(id).steps), start: () => run(id) }),
+ ({ gpuWarning }) => Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(gpuWarning && { gpuWarning }) }),
+ );
}, request);
}
diff --git a/src/app/api/faceless/episodes/[id]/change/route.ts b/src/app/api/faceless/episodes/[id]/change/route.ts
index 7203735d..870bb699 100644
--- a/src/app/api/faceless/episodes/[id]/change/route.ts
+++ b/src/app/api/faceless/episodes/[id]/change/route.ts
@@ -1,4 +1,4 @@
-import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { applyChange, body, ChangeSchema, changeGraph, episodeView, graphFiles, graphToolSteps, handle, previewChange } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -20,8 +20,13 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/ep
return Response.json(episodeView(id), { status: 201 });
}
const graph = asViewer(viewer, () => changeGraph(id, c));
- const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: graphFiles(graph), plan: () => planned(() => graphToolSteps(changeGraph(id, c))), start: () => applyChange(id, c) });
- if (!out.ok) return out.response;
- return Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(out.gpuWarning && { gpuWarning: out.gpuWarning }) }, { status: 201 });
+ // A resend of the same press (the page's id in its header) gets the change the first one started.
+ return onceForAccount(
+ viewer.account,
+ `faceless-change:${id}`,
+ pressIdOf(request),
+ () => runAccountTool(request, viewer.account, { tool: "faceless", files: graphFiles(graph), plan: () => planned(() => graphToolSteps(changeGraph(id, c))), start: () => applyChange(id, c) }),
+ ({ gpuWarning }) => Response.json({ ...asViewer(viewer, () => episodeView(id)), ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/faceless/voices/preview/route.ts b/src/app/api/faceless/voices/preview/route.ts
index 7fdf4a44..b043086a 100644
--- a/src/app/api/faceless/voices/preview/route.ts
+++ b/src/app/api/faceless/voices/preview/route.ts
@@ -1,5 +1,5 @@
import { z } from "zod";
-import { asViewer, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { asViewer, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { body, handle, voicePreview, voicePreviewPlan } from "@/server/faceless";
import { planned } from "@/server/faceless-account";
@@ -18,7 +18,13 @@ export async function POST(request: Request) {
if (viewer.kind === "owner") return Response.json(voicePreview(voice));
const p = asViewer(viewer, () => voicePreviewPlan(voice));
if ("made" in p) return Response.json(p.made);
- const out = await runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: p.request }]), start: () => voicePreview(voice) });
- return out.ok ? Response.json(out.value) : out.response;
+ // A resend of the same press (the page's id in its header) gets the sample the first one started.
+ return onceForAccount(
+ viewer.account,
+ `faceless-voice:${voice.id}`,
+ pressIdOf(request),
+ () => runAccountTool(request, viewer.account, { tool: "faceless", files: [], plan: () => planned(() => [{ request: p.request }]), start: () => voicePreview(voice) }),
+ ({ value }) => Response.json(value),
+ );
}, request);
}
diff --git a/src/app/api/genjutsu/scene/route.ts b/src/app/api/genjutsu/scene/route.ts
index a097700c..973ad30f 100644
--- a/src/app/api/genjutsu/scene/route.ts
+++ b/src/app/api/genjutsu/scene/route.ts
@@ -1,4 +1,4 @@
-import { bodyTooBig, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { describeScene, SceneSchema, sceneRequest, startStep } from "@/server/genjutsu";
import { body, handle } from "@/server/shorts-schemas";
@@ -16,12 +16,19 @@ export async function POST(request: Request) {
return handle(async () => {
const input = await body(request, SceneSchema, "Make and pick the first frame first");
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, ownSetup: true }) }],
- start: () => startStep(sceneRequest(input, { owner: false, ownSetup: true })),
- });
- return r.ok ? Response.json(r.value, { status: 201 }) : r.response;
+ // A resend of the same press (the page's id in its header) gets the describer the first one started.
+ return onceForAccount(
+ viewer.account,
+ "genjutsu-scene",
+ pressIdOf(request),
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "genjutsu",
+ files: [input.source.url, input.ownPerson ? undefined : input.frame],
+ plan: () => [{ request: sceneRequest(input, { owner: false, ownSetup: true }) }],
+ start: () => startStep(sceneRequest(input, { owner: false, ownSetup: true })),
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/genjutsu/transcribe/route.ts b/src/app/api/genjutsu/transcribe/route.ts
index 18d191e4..1c02bb0c 100644
--- a/src/app/api/genjutsu/transcribe/route.ts
+++ b/src/app/api/genjutsu/transcribe/route.ts
@@ -1,4 +1,4 @@
-import { bodyTooBig, guestRun, runAccountTool, toolViewer } from "@/server/account-tool-run";
+import { bodyTooBig, guestRun, onceForAccount, pressIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";
import { startStep, transcribeClip, TranscribeSchema, transcribeRequest } from "@/server/genjutsu";
import { body, handle } from "@/server/shorts-schemas";
@@ -17,12 +17,19 @@ export async function POST(request: Request) {
return handle(async () => {
const input = await body(request, TranscribeSchema, "Add a clip first");
if (viewer.kind === "owner") return Response.json(transcribeClip(input), { status: 201 });
- 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;
+ // A resend of the same press (the page's id in its header) gets the transcription the first one started.
+ return onceForAccount(
+ viewer.account,
+ "genjutsu-transcribe",
+ pressIdOf(request),
+ () =>
+ runAccountTool(request, viewer.account, {
+ tool: "genjutsu",
+ files: [input.source.url],
+ plan: () => [{ request: transcribeRequest(input) }],
+ start: () => startStep(transcribeRequest(input)),
+ }),
+ ({ value }) => Response.json(value, { status: 201 }),
+ );
}, request);
}
diff --git a/src/app/api/palettes/lock/route.ts b/src/app/api/palettes/lock/route.ts
index 70b37277..32efb702 100644
--- a/src/app/api/palettes/lock/route.ts
+++ b/src/app/api/palettes/lock/route.ts
@@ -43,8 +43,10 @@ const Body = z.object({
/**
* Make the images, then recolour each one to the palette (open engine: a chained palette-transfer step). The owner's run
- * as always; an account's with only its own pictures, after the checks every tool run gets (src/server/tool-runs.ts),
- * on its own GPU or on this install's GPUs; a guest signs up first.
+ * as always. An account's runs on this install's GPUs only (hosted runs), with only its own pictures, after the checks
+ * every tool run gets (src/server/tool-runs.ts), and with no more pictures at once than a run there makes; on its own
+ * GPU or key its colours go in the prompt instead (the composer sends no lock there), so it is refused here as before.
+ * A guest signs up first.
*/
export async function POST(request: Request) {
const viewer = toolViewer(request);
@@ -58,12 +60,16 @@ export async function POST(request: Request) {
if (!parsed.success) return Response.json({ error: parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; ") }, { status: 400 });
if (viewer.kind === "account") {
const { request: asked, colors, strength, requestId } = parsed.data;
+ const req = asked as Parameters<typeof createLockedRun>[0];
return runToolForAccount(request, viewer.account, {
tool: "palette-lock",
files: asked.inputs?.images ?? [],
requestId,
wishes,
- start: () => createLockedRun(asked as Parameters<typeof createLockedRun>[0], colors, strength),
+ poolOnly: true,
+ start: () => createLockedRun(req, colors, strength),
+ // Each picture is its own image-and-recolour chain: no more of them than a run there makes at once.
+ poolStart: (cap) => () => createLockedRun({ ...req, params: { ...req.params, numOutputs: Math.min(req.params?.numOutputs ?? 1, cap) } }, colors, strength),
ok: ({ items }, gpuWarning) => Response.json({ items, ...(gpuWarning && { gpuWarning }) }, { status: 201 }),
});
}
diff --git a/src/lib/guest-access.ts b/src/lib/guest-access.ts
index a9643987..8dbcb575 100644
--- a/src/lib/guest-access.ts
+++ b/src/lib/guest-access.ts
@@ -102,15 +102,26 @@ export function guestRead(pathname: string): GuestRead {
*/
const PREVIEWS = [/^\/api\/(generations|audio-tools|dub|katana|turnaround|fly-around|influencer|photodump|photodump\/fashion|photodump\/character)$/, /^\/api\/dub\/[^/]+\/voice$/];
+/**
+ * The run routes whose `?preview=1` prices a run on this install's GPUs only (with hosted runs off the route answers at
+ * once that the run stays where it is, and the proxy treats the request as the run it names): Cinema Studio's Generate,
+ * which plans a take in the account's own project (every step planned, nothing kept).
+ */
+const HOSTED_PREVIEWS = [/^\/api\/cinema\/projects\/[^/]+\/generate$/];
+
/** The estimate routes (named: a dynamic segment called "estimate" on another route must not pass for one). */
const ESTIMATES =
/^\/api\/(ads|ads\/multiplier|assist\/skills\/[^/]+|content-factory|evolution|faceless|genjutsu|influencer|marketing|marketing\/click-to-ad|mixed-media|remove-object|restore|shorts|storyboards|turnaround)\/estimate$/;
-/** A POST that only plans and prices a run (an estimate route, or ?preview=1 where PREVIEWS honours it): free, and open to guests. */
-export function isPriceCheck(method: string, pathname: string, search: string): boolean {
+/**
+ * A POST that only plans and prices a run (an estimate route, or ?preview=1 where PREVIEWS honours it): free, and open to
+ * guests. `hosted`: hosted runs are on, so HOSTED_PREVIEWS count too.
+ */
+export function isPriceCheck(method: string, pathname: string, search: string, hosted = false): boolean {
if (method !== "POST") return false;
if (ESTIMATES.test(pathname)) return true;
- return new URLSearchParams(search).get("preview") === "1" && PREVIEWS.some((r) => r.test(pathname));
+ if (new URLSearchParams(search).get("preview") !== "1") return false;
+ return PREVIEWS.some((r) => r.test(pathname)) || (hosted && HOSTED_PREVIEWS.some((r) => r.test(pathname)));
}
/**
@@ -298,8 +309,6 @@ export const ACCOUNT_TOOL_RUNS: readonly RegExp[] = [
/^\/api\/swap-studio\/projects\/[^/]+\/(anchors|assemble|clips|masks|prepare|queue|sharpen|transcribe)$/,
// Cinema Studio: a take in the account's own project, a retry and a 2K finish of one of its takes.
/^\/api\/cinema\/projects\/[^/]+\/(generate|items\/[^/]+\/(retry|finish))$/,
- // The Image studio's palette lock: its images, then each recoloured to the palette (src/server/palettes.ts).
- /^\/api\/palettes\/lock$/,
// The photo apps: Photodump, Fashion Factory, Character Sheet, AI Influencer, and a retry of its own photo.
/^\/api\/(photodump(\/(fashion|character|retry))?|influencer)$/,
// Video tools: Remove object (a mask preview, and "Redo from here" on its own removal), Evolution (its direction is
@@ -367,6 +376,17 @@ export function ownGpuRun(method: string, pathname: string): boolean {
return method === "POST" && (pathname === "/api/generations" || ACCOUNT_TOOL_RUNS.some((r) => r.test(pathname)));
}
+/**
+ * Tool runs an account makes on this install's GPUs only (hosted runs on): the Image studio's palette lock (its images,
+ * then each recoloured to the palette, src/server/palettes.ts). On its own GPU or key the colours go in the prompt
+ * instead, so with hosted runs off these stay refused as a tool that isn't available here.
+ */
+const POOL_TOOL_RUNS: readonly RegExp[] = [/^\/api\/palettes\/lock$/];
+
+export function poolToolRun(method: string, pathname: string): boolean {
+ return method === "POST" && POOL_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. */
export const ACTIVE_RUNS_CODE = "active-runs";
diff --git a/src/proxy.ts b/src/proxy.ts
index 60309f57..28b46f29 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -27,6 +27,7 @@ import {
OWN_GPU_TOOL_MESSAGE,
ownerOnly,
ownGpuRun,
+ poolToolRun,
} from "@/lib/guest-access";
import { ADMIN_BEARER, authEnabled, crossSite, hasCloudKey, hostAllowed, LoginGuard, publicSignup, sessionCookieOf, sessionViewer, validSession, validToken, type Account, type Viewer } from "@/server/auth";
import { fileAccount, generationAccount } from "@/server/account-library";
@@ -212,11 +213,14 @@ function guest(request: NextRequest): NextResponse {
const live = liveRoute(pathname);
if (live && live !== "nodes") return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });
if (method === "GET" || method === "HEAD") return readAsGuest(request, false);
- if (isPriceCheck(method, pathname, search)) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);
+ if (isPriceCheck(method, pathname, search, hostedRunsOn())) return priceCheck(request, `guest:${LoginGuard.clientKey(request.headers)}`);
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) && !accountProjectRoute(pathname)) return ownGpuTool();
+ // A tool run made only on this install's GPUs counts as one of them with hosted runs on, and as a tool that isn't
+ // available here without them.
+ const run = ownGpuRun(method, pathname) || (poolToolRun(method, pathname) && hostedRunsOn());
+ if (!accountMayChange(method, pathname, search) && !isLibraryChange(method, pathname) && !ownerOnly(method, pathname) && !run && !accountProjectRoute(pathname)) return ownGpuTool();
return NextResponse.json({ error: GUEST_RUN_MESSAGE }, { status: 401, headers: guestHeaders });
}
@@ -281,12 +285,14 @@ function account(request: NextRequest, who: Account): NextResponse {
const own = record ? accountRecordExists(record, who.id) : null;
if (own !== null) return own ? NextResponse.next() : notFound(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 (isPriceCheck(request.method, pathname, search, hostedRunsOn())) return priceCheck(request, `account:${who.id}`);
if (accountMayChange(request.method, pathname, search)) return pass(request);
if (isAssistChange(request.method, pathname)) return assistOwner();
if (isLibraryChange(request.method, pathname)) return NextResponse.json({ error: LIBRARY_MESSAGE, code: "library" }, { status: 403 });
- // A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks.
- if (!ownGpuRun(request.method, pathname)) return ownGpuTool();
+ // A tool its own GPU or key wouldn't run says so first: "Connect your GPU" only for what a GPU or a key unlocks. A tool
+ // run made only on this install's GPUs (the palette lock) goes to its route with hosted runs on, and is refused so
+ // without them, as before.
+ if (!ownGpuRun(request.method, pathname) && !(poolToolRun(request.method, pathname) && hostedRunsOn())) return ownGpuTool();
// Neither its own GPU nor its own key: nothing it could run on. (Which one a run needs, the route says.)
// With hosted runs on (FUOBE_HOSTED_RUNS=1), a run in the studios or a tool's run may go to this install's GPUs: the route
// decides (hosted-run.ts decidePlace, account-tool-run.ts placeOf).
diff --git a/src/server/account-sweep.ts b/src/server/account-sweep.ts
index ab345ae7..edefcb1c 100644
--- a/src/server/account-sweep.ts
+++ b/src/server/account-sweep.ts
@@ -15,6 +15,7 @@ import { db } from "./db";
import { handOversDone } from "./generations";
import { deleteForever } from "./library";
import { deleteAsset, scratchDir } from "./storage";
+import { forgetAccountPresses } from "./tool-presses";
/**
* Public sign-up: what an account keeps on this server goes in time. Its uploads after 14 days (even when a run still
@@ -54,6 +55,7 @@ export async function purgeAccount(id: string): Promise<{ runs: number; files: n
deleteAccountSeries(id);
deleteAccountFaceless(id);
deleteAccountProjects(id);
+ forgetAccountPresses(id);
await runAccountDeletedHooks(id);
return { runs, files: files.length };
}
diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.ts
index 6bf0d4be..8e720e11 100644
--- a/src/server/account-tool-run.ts
+++ b/src/server/account-tool-run.ts
@@ -1,4 +1,5 @@
import "server-only";
+import { AsyncLocalStorage } from "node:async_hooks";
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";
@@ -12,20 +13,21 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, disk
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 { BILLING_HEADER, type Quote } from "./billing";
import { queueRelease } from "./billing-outbox";
import { gateGeneration, GPU_SETUP_HEADER } from "./gpu/gate";
import { gpuTargetFor } from "./gpu/target";
import { runOnPool } from "./hosted";
-import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, poolMayTake, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";
+import { decideToolPlace, GUEST_PLAN, madeRunProblem, moderateRun, poolMayTake, poolOutputsCap, readWishes, reservePool, toolPoolQuote, type PlaceWish, type PoolLine, type Refusal, type ToolPoolRun } from "./hosted-run";
import { cancelGeneration, captureRun } from "./generations";
-import { AdmitRefused, admitRun, clientAddress, poolLimitRefusal } from "./pool-limits";
+import { accountActiveRuns, AdmitRefused, admitRun, clientAddress, closeAdmission, forgetAdmission, openAdmission, poolLimitRefusal } from "./pool-limits";
import { hit, unhit } from "./rate";
import { withRunStamp, type RunStamp } from "./run-stamp";
import { once } from "./shorts-schemas";
import { ShortsError } from "./shorts";
+import { hostedRunsOn } from "./hosted-switch";
+import { answerPress, claimPress, releasePress, toolPressId, type PressAnswer } from "./tool-presses";
/**
* A tool's run for a signed-in account (public sign-up): Genjutsu first, then the other tools that plan a run as a
@@ -84,19 +86,67 @@ 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. */
+/** A refused run, kept as its parts so a repeat of the same request id gets its own copy of the answer. `held`: refused after its hold was made. */
class Refused {
constructor(
- readonly status: number,
- readonly headers: [string, string][],
- readonly text: string,
+ readonly answer: PressAnswer,
+ readonly held: boolean,
) {}
}
+const asAnswer = async (r: Response): Promise<PressAnswer> => ({ status: r.status, headers: [...r.headers], text: await r.text() });
+const fromAnswer = (a: PressAnswer): Response => new Response(a.text, { status: a.status, headers: a.headers });
+
+/**
+ * The press of Run a tool's run belongs to (onceForAccount): its id for the billing service's reserve, so every resend
+ * of the press asks for the same hold (hosted-run.ts reservePool). Null: a run with no id from its page.
+ */
+const PRESS = new AsyncLocalStorage<{ pressId: string | null }>();
+
+/** How long a resend waits for its press to be answered by another server process, before it says it is starting. */
+const PRESS_WAIT_MS = 30_000;
+
+/** A resend whose press another server process is still starting, after PRESS_WAIT_MS. */
+const STARTING: PressAnswer = {
+ status: 409,
+ headers: [
+ ["content-type", "application/json"],
+ ["cache-control", "no-store"],
+ ["retry-after", "5"],
+ ],
+ text: JSON.stringify({ error: "This run is starting. It shows in your runs in a moment.", code: "press-starting" }),
+};
+
+/**
+ * A press kept in the database (tool-presses.ts), with hosted runs on: a resend that reaches another server process, or
+ * comes after a restart, gets the first answer (waiting for it while that process starts it), never a second run.
+ */
+async function keptPress(accountId: string, scope: string, clientId: string, attempt: (tries: number) => Promise<PressAnswer>): Promise<PressAnswer> {
+ const until = Date.now() + PRESS_WAIT_MS;
+ let claim = claimPress(accountId, scope, clientId);
+ while (claim.kind === "starting") {
+ if (Date.now() > until) return STARTING;
+ await new Promise((r) => setTimeout(r, 250));
+ claim = claimPress(accountId, scope, clientId);
+ }
+ if (claim.kind === "done") return claim.answer;
+ try {
+ const answer = await attempt(claim.tries);
+ answerPress(accountId, scope, clientId, answer);
+ return answer;
+ } catch (e) {
+ releasePress(accountId, scope, clientId, e instanceof Refused && e.held);
+ throw e;
+ }
+}
+
/**
* 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.
+ * through, a retried POST) gets the first run, and never another account's. With hosted runs on, the press is kept in
+ * the database too (keptPress), so a repeat that reaches another server process gets it as well, and its run on this
+ * install's GPUs asks the billing service for one hold however often it is sent. A refusal isn't kept: sent again
+ * (after the account connects its GPU, say), the run is checked again; one refused after its hold was made (and given
+ * back) asks for a new hold then. `ok` turns the started run into the route's answer.
*/
export async function onceForAccount<T>(
account: Account,
@@ -105,27 +155,38 @@ export async function onceForAccount<T>(
fn: () => Promise<AccountToolResult<T>>,
ok: (r: { value: T; gpuWarning?: string }) => Response,
): Promise<Response> {
+ const attempt = async (tries: number): Promise<PressAnswer> => {
+ const out = await PRESS.run({ pressId: id ? toolPressId(scope, id, tries) : null }, fn);
+ if (out.ok) return asAnswer(ok(out));
+ throw new Refused(await asAnswer(out.response), !!out.held);
+ };
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);
+ const answer = await once(`${scope}:acct:${account.id}`, id, () => (id && hostedRunsOn() ? keptPress(account.id, scope, id, attempt) : attempt(0)));
+ return fromAnswer(answer);
} catch (e) {
- if (e instanceof Refused) return new Response(e.text, { status: e.status, headers: e.headers });
+ if (e instanceof Refused) return fromAnswer(e.answer);
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 page's id for a press of Run, as a tool's body carries it beside its own fields (`requestId`), or none. */
+export function requestIdOf(body: unknown): string | undefined {
+ const v = (body as { requestId?: unknown } | null)?.requestId;
+ return typeof v === "string" && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : undefined;
}
+/** The header a page sends its id for a press of Run in, for a tool whose body has no field for it. */
+export const PRESS_HEADER = "x-request-id";
+
+/** A page's id for a press of Run, from the request's PRESS_HEADER, or none. */
+export const pressIdOf = (request: Request): string | undefined => requestIdOf({ requestId: request.headers.get(PRESS_HEADER) });
+
+/**
+ * An account's runs going now (queued or running), counted as runs: a run's jobs and steps share a batch, and a run let
+ * in whose rows are still being made counts too (pool-limits.ts accountActiveRuns).
+ */
+export const activeAccountRuns = (accountId: string): number => accountActiveRuns(accountId);
+
/** 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;
@@ -253,9 +314,21 @@ export interface AccountToolRun<T> {
place?: PlaceWish;
/** The price the client showed before Run (hosted-run.ts readWishes). */
shown?: { amount: number; priceVersion: string } | null;
+ /**
+ * A run made only on this install's GPUs (hosted runs): wherever else it would go (the account's own GPU or key,
+ * hosted runs off), it is refused as a tool that isn't available here, as before.
+ */
+ poolOnly?: boolean;
+ /**
+ * The run as it is made on this install's GPUs, for a tool that spreads the outputs a person picks over separate jobs
+ * of one output each (the palette lock): no more than `cap` of them, the most a run there makes at once, as a studio
+ * run there is cut to it. Planned, placed and priced again as it is cut.
+ */
+ forPool?: (cap: number) => Pick<AccountToolRun<T>, "plan" | "start">;
}
-export type AccountToolResult<T> = { ok: true; value: T; gpuWarning?: string } | { ok: false; response: Response };
+/** A tool's run: started, or refused (`held`: after its hold on this install's GPUs was made, which goes back). */
+export type AccountToolResult<T> = { ok: true; value: T; gpuWarning?: string } | { ok: false; response: Response; held?: boolean };
type Planned = { step: ToolStep; p: ReturnType<typeof previewChained> };
@@ -307,6 +380,8 @@ export async function runAccountTool<T>(request: Request, account: Account, aske
const sent = headerWishes(request);
const run: AccountToolRun<T> = { ...asked, place: asked.place ?? sent.place, shown: asked.shown ?? sent.shown };
const no = (response: Response): AccountToolResult<T> => ({ ok: false, response });
+ // A run made only on this install's GPUs, that can't go there (hosted runs off, its own GPU first): as before.
+ if (run.poolOnly && !poolMayTake(account, run.place)) return no(ownGpuTool());
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" }));
@@ -330,6 +405,22 @@ export async function runAccountTool<T>(request: Request, account: Account, aske
if (!steps.length) return back(refuse(422, "Nothing to run yet."));
const place = await placeOf(account, steps, run.place);
if (place.kind === "refuse") return back(refuse(place.refusal.status, place.refusal.body.error, place.refusal.body, place.refusal.headers));
+ if (run.poolOnly && place.kind !== "pool") return back(ownGpuTool());
+ if (place.kind === "pool" && run.forPool) {
+ // Cut to the most a run there makes at once, then planned and placed again as it will be made (there, or refused).
+ const cut = run.forPool(poolOutputsCap(place.policy));
+ let cutSteps: ToolStep[];
+ try {
+ cutSteps = await runOnPool(id, cut.plan);
+ } catch (e) {
+ return back(errorResponse(e));
+ }
+ if (!cutSteps.length) return back(refuse(422, "Nothing to run yet."));
+ const there = await placeOf(account, cutSteps, "pool");
+ if (there.kind === "refuse") return back(refuse(there.refusal.status, there.refusal.body.error, there.refusal.body, there.refusal.headers));
+ if (there.kind !== "pool") return back(ownGpuTool());
+ return startOnPool(request, account, { ...run, ...cut }, cutSteps, files, there, back);
+ }
if (place.kind === "pool") return startOnPool(request, account, run, steps, files, place, back);
let gpuWarning: string | undefined;
let kind: MediaKind = "video";
@@ -392,8 +483,8 @@ const isThenable = (v: unknown): v is PromiseLike<unknown> => !!v && typeof (v a
* then the run made as the account's run there (runOnPool, every row stamped with its place and hold) and counted in
* the same transaction (admitRun). Every row it makes is checked again before anything is sent (madeRunProblem): against
* the policy, and against what the run was priced and held for (its jobs, its outputs at once, light work only). A row
- * that doesn't match stops the whole run: its rows are stopped, and its hold goes back. Its own GPU's checks (the
- * pre-flight, its LoRAs) don't apply here.
+ * that doesn't match stops the whole run: its rows are stopped, and their reports close its hold (a run that made no
+ * row gives its hold back). Its own GPU's checks (the pre-flight, its LoRAs) don't apply here.
*/
async function startOnPool<T>(
request: Request,
@@ -414,59 +505,79 @@ async function startOnPool<T>(
let stamp: RunStamp;
if (pool.light) stamp = { place: "pool", light: true, ...(mod.checkOutputs && { checkOutputs: true }) };
else {
- const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps);
+ // One hold per press of Run: every resend of the press asks for it by the same request id.
+ const held = await reservePool(account, pool.main.req, pool.main.planned, run.shown ?? null, mod.checkOutputs, pool.steps, PRESS.getStore()?.pressId ?? null);
if (!held.ok) return back(refuse(held.refusal.status, held.refusal.body.error, held.refusal.body, held.refusal.headers));
stamp = held.stamp;
}
const release = () => {
if (stamp.hold) queueRelease(stamp.hold);
};
+ /** Refused from here on: after its hold was made, when one was (it goes back). */
+ const refused = (response: Response): AccountToolResult<T> => ({ ...back(response), ...(stamp.hold && { held: true }) });
const notOffered = (error: string) => refuse(403, error, { code: "not-offered" }, { [BILLING_HEADER]: "not-offered" });
- type Made = { value: T | Promise<T>; ids: string[]; start: () => void };
+ /** What the start made: its value, its rows (they keep coming while an awaiting start runs) and its open admission. */
+ type Made = { value: T | Promise<T>; ids: string[]; start: () => void; open: string | null };
+ const now = Date.now();
let admitted: { ok: true; value: Made } | { ok: false; refusal: { status: number; error: string; code: string; retryAfterS?: number } };
try {
admitted = runOnPool(id, () =>
withRunStamp(stamp, () =>
- admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr } }, (): Made => {
+ admitRun({ accountId: id, pool: pool.light ? null : { policy: pool.policy, addr }, now }, (): Made => {
const made = captureRun(run.start);
- // A tool that makes its rows as it goes (after an await) is checked once they are all made, below.
- if (!isThenable(made.value)) {
- const problem = madeRunProblem(pool, made.ids);
- if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });
- }
- return made;
+ // A tool that makes its rows as it goes (after an await) is checked once they are all made, below. Until then
+ // it counts as a run going (and in line) for every later request, from this same locked step: requests sent
+ // together can't all pass the limits while its rows aren't made yet.
+ if (isThenable(made.value)) return { ...made, open: openAdmission(id, !pool.light, now) };
+ const problem = madeRunProblem(pool, made.ids);
+ if (problem) throw new AdmitRefused({ status: 403, error: problem, code: "not-offered" });
+ return { ...made, open: null };
}),
),
);
} catch (e) {
release();
- return back(errorResponse(e));
+ return refused(errorResponse(e));
}
if (!admitted.ok) {
release();
const r = admitted.refusal;
- return back(r.code === "not-offered" ? notOffered(r.error) : refuse(r.status, r.error, { code: r.code }, { "Retry-After": String(r.retryAfterS ?? 30) }));
+ return refused(r.code === "not-offered" ? notOffered(r.error) : refuse(r.status, r.error, { code: r.code }, { "Retry-After": String(r.retryAfterS ?? 30) }));
}
const made = admitted.value;
- /** Stop what was made (nothing of it was sent) and give the hold back. */
+ /**
+ * Stop what was made (nothing of it was sent). Each stopped row's report closes the hold (billing-outbox.ts), so the
+ * hold goes back by itself only when no row was made.
+ */
const undo = () => {
for (const g of made.ids) void cancelGeneration(g);
- release();
+ if (!made.ids.length) release();
};
let value: T;
try {
value = await made.value;
} catch (e) {
undo();
- return back(errorResponse(e));
+ return refused(errorResponse(e));
+ } finally {
+ // Its rows exist now and count for themselves (or none will).
+ if (made.open) closeAdmission(made.open);
}
if (isThenable(made.value)) {
const problem = madeRunProblem(pool, made.ids);
if (problem) {
undo();
- return back(notOffered(problem));
+ return refused(notOffered(problem));
}
}
+ // A start that made nothing (a tool that kept its own error, say): nothing runs, so its hold goes back, and it is not
+ // one of the hour's runs.
+ if (!made.ids.length) {
+ release();
+ if (!pool.light) forgetAdmission(id, now);
+ unhit(`run:${id}`);
+ return { ok: true, value };
+ }
made.start();
return { ok: true, value };
}
diff --git a/src/server/cinema-schemas.ts b/src/server/cinema-schemas.ts
index fed4407e..341e2eba 100644
--- a/src/server/cinema-schemas.ts
+++ b/src/server/cinema-schemas.ts
@@ -132,6 +132,8 @@ export const WorldSchema = z.object({
export const GenerateBody = z.object({
folderId: z.string().max(40).nullable().optional(),
+ /** The page's id for this press of Generate: a resend of it gets the first take (an account's run). */
+ requestId: z.string().trim().min(8).max(64).optional(),
input: z.object({
engine: z.enum(["cloud", "open"]),
mode: z.enum(["video", "image"]),
diff --git a/src/server/db.ts b/src/server/db.ts
index dbb9d74c..d53e0997 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -1114,6 +1114,9 @@ function open(): Database.Database {
}
// Admin tokens and the admin API's log.
db.exec(ADMIN_TABLES);
+ // A tool's press of Run, kept so a resend gets its first answer (tool-presses.ts), and the runs let in whose rows are
+ // still being made (pool-limits.ts openAdmission): not a numbered migration either.
+ db.exec(TOOL_PRESS_TABLES);
// Skills: the runs that wait across studios. A data folder that ran claude/fuobe-parity-4's earlier build of this
// feature (its numbered migration at place 27, a skill_runs with no engine column and runs kept in another shape)
// keeps that table under another name, so these runs start from an empty table. Nothing is deleted.
@@ -1157,6 +1160,30 @@ const ACCOUNT_CANVAS_TABLES = `CREATE TABLE IF NOT EXISTS account_canvases (
);
CREATE INDEX IF NOT EXISTS account_canvases_account ON account_canvases(account_id, updated_at DESC);`;
+/**
+ * Each press of a tool's Run an account made with hosted runs on (src/server/tool-presses.ts): by a key made from the
+ * account, the tool and the page's id for the press, with the answer it got once it started (`starting` while it is
+ * being started) and how many of its tries were refused after their hold was made. Kept a day. open_admissions: a run
+ * let in whose rows are still being made (a tool's start that awaits before it makes them), counted until they exist.
+ */
+const TOOL_PRESS_TABLES = `CREATE TABLE IF NOT EXISTS tool_presses (
+ account TEXT NOT NULL,
+ request_id TEXT NOT NULL,
+ answer_json TEXT,
+ tries INTEGER NOT NULL DEFAULT 0,
+ starting INTEGER NOT NULL DEFAULT 0,
+ at INTEGER NOT NULL,
+ PRIMARY KEY (account, request_id)
+ );
+ CREATE INDEX IF NOT EXISTS tool_presses_at ON tool_presses(at);
+ CREATE TABLE IF NOT EXISTS open_admissions (
+ key TEXT PRIMARY KEY,
+ account TEXT NOT NULL,
+ pool INTEGER NOT NULL DEFAULT 0,
+ at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS open_admissions_account ON open_admissions(account, at);`;
+
export function db(): Database.Database {
globalThis.__fuobeDb ??= open();
return globalThis.__fuobeDb;
diff --git a/src/server/generations.ts b/src/server/generations.ts
index a43bd232..2e2b6e21 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -519,6 +519,7 @@ export const ASSET_FREE: Record<string, string> = {
"gpu_snapshots.report_json": "readiness built from that inventory",
"generations.external_meta_json": "the provider's job handles",
"billing_outbox.payload_json": "reports for the billing service: hold and run ids, counts and words, never a file",
+ "tool_presses.answer_json": "a copy of the answer one press of a tool's Run got, for a resend of it: its runs' own rows keep their files",
"reports_inbox.target_json": "what a report is about: a run, asset or share id, never a file",
"admin_tokens.scopes_json": "an admin token's scope names",
"admin_audit.detail_json": "small facts about an admin action: counts, ids and names, never a file's URL",
diff --git a/src/server/hosted-run.ts b/src/server/hosted-run.ts
index 31a51a13..ead8b861 100644
--- a/src/server/hosted-run.ts
+++ b/src/server/hosted-run.ts
@@ -3,7 +3,7 @@ import crypto from "node:crypto";
import { nanoid } from "nanoid";
import type { GenerationRequest } from "@/lib/catalog/types";
import { CONNECT_GPU_HEADER, OWN_GPU_TOOL_MESSAGE } from "@/lib/guest-access";
-import { ownSetupLabel, ownSetupOnly, type OwnSetup } from "@/lib/own-setup";
+import { ownSetupLabel, type OwnSetup } from "@/lib/own-setup";
import { gpuState } from "./account-gpu";
import { accountGpu, type Account } from "./auth";
import {
@@ -38,7 +38,8 @@ import { readRef } from "./storage";
import { ACCOUNT_LIMITS } from "./account-files";
import { poolLimitRefusal } from "./pool-limits";
import { runAsTenant } from "./tenant";
-import { needsGpu, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";
+import { needsGpu, ownSetupHere, poolCardRefuses, requestOwnSetup } from "./pool-own-setup";
+import { reserveRequestId } from "./tool-presses";
import { ADD_KEY_HEADER } from "@/lib/your-keys";
export { poolCardRefuses };
@@ -203,7 +204,7 @@ export function poolSteps(accountId: string, req: GenerationRequest): PlannedSte
*/
export function stepsProblem(p: Policy, steps: PlannedStep[]): string | null {
for (const s of steps) {
- const own = s.provider === "comfyui" ? ownSetupOnly(s.modelId, "open") : null;
+ const own = s.provider === "comfyui" ? ownSetupHere(s.modelId, "open") : null;
if (own) return ownSetupLabel(own);
if (!poolRunsProvider(s.provider)) return HOSTED_WORDS.notOffered;
if (s.provider === "comfyui" && poolCardRefuses(s.modelId)) return HOSTED_WORDS.rtxCard;
@@ -337,7 +338,7 @@ export function poolGate(
// Every step of a chain, not only its first: each one the policy must allow, and the run is priced for all of them.
const steps = planSteps();
for (const s of steps ?? []) {
- const later = s.provider === "comfyui" ? ownSetupOnly(s.modelId, "open") : null;
+ const later = s.provider === "comfyui" ? ownSetupHere(s.modelId, "open") : null;
if (later) return { ok: false, reason: "ownSetup", setup: later };
}
const problem = steps && p ? stepsProblem(p, steps) : null;
@@ -507,7 +508,9 @@ export async function moderateRun(
/**
* Set the run's price aside (no billing service: nothing to set aside; the run is free). Returns the stamp the run's
- * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md).
+ * rows carry, or the refusal (402, 409 with the new price, 429, 503, 403; docs/billing-hook.md). `pressId`: the press of
+ * Run it belongs to (a tool's scope and its page's id for the press), so every resend of that press asks for the same
+ * hold; none, a fresh request id.
*/
export async function reservePool(
account: Account,
@@ -516,12 +519,13 @@ export async function reservePool(
shown: { amount: number; priceVersion: string } | null,
checkOutputs: boolean,
steps?: RunFacts["steps"],
+ pressId: string | null = null,
): Promise<{ ok: true; stamp: RunStamp } | { ok: false; refusal: Refusal }> {
const base: RunStamp = { place: "pool", ...(checkOutputs && { checkOutputs: true }) };
if (!billingConfigured()) return { ok: true, stamp: base };
const kind = outputKind(planned.op, planned.model);
const a = await reserve({
- requestId: nanoid(16),
+ requestId: pressId ? reserveRequestId(account.id, pressId) : nanoid(16),
account: accountFacts(account),
run: { ...runOnPool(account.id, () => runFacts(req, planned, kind)), ...(steps?.length && { steps }) },
queue: queueFacts(account.id, planned.route.endpoint),
diff --git a/src/server/pool-limits.ts b/src/server/pool-limits.ts
index b8f30258..995bbaf3 100644
--- a/src/server/pool-limits.ts
+++ b/src/server/pool-limits.ts
@@ -42,17 +42,51 @@ export interface LimitRefusal {
retryAfterS: number;
}
-/** An account's runs going now (queued or running), wherever they run: a run's jobs and chain steps share a batch. */
+/**
+ * A run let in whose rows are still being made: a tool's start that awaits something (a channel, a plan) before it
+ * makes its rows. It counts as one run going (and, on this install's GPUs, one in line) from the moment it is let in
+ * until its rows exist (closeAdmission), so requests that arrive meanwhile meet the limits with it counted. One whose
+ * process stopped before it closed counts for OPEN_ADMISSION_MS at most.
+ */
+export const OPEN_ADMISSION_MS = 10 * 60_000;
+
+/**
+ * Note a run let in whose rows aren't made yet (call it inside admitRun's `make`, so it is noted in the same locked step
+ * as the count). `pool`: it counts against the policy's limits on runs on this install's GPUs too. Returns its key.
+ */
+export function openAdmission(accountId: string, pool: boolean, now = Date.now()): string {
+ const key = crypto.randomBytes(12).toString("hex");
+ db().prepare("INSERT INTO open_admissions (key, account, pool, at) VALUES (?, ?, ?, ?)").run(key, accountId, pool ? 1 : 0, now);
+ return key;
+}
+
+/** The run's rows exist now (they count from here), or it was never made: it no longer counts as open. */
+export function closeAdmission(key: string): void {
+ db().prepare("DELETE FROM open_admissions WHERE key = ?").run(key);
+}
+
+/** An account's open admissions (all of them, or only those on this install's GPUs). */
+function openCount(accountId: string, poolOnly: boolean, now = Date.now()): number {
+ const r = db()
+ .prepare(`SELECT COUNT(*) AS n FROM open_admissions WHERE account = ? AND at > ?${poolOnly ? " AND pool = 1" : ""}`)
+ .get(accountId, now - OPEN_ADMISSION_MS) as { n: number };
+ return r.n;
+}
+
+/**
+ * An account's runs going now (queued or running), wherever they run: a run's jobs and chain steps share a batch. A run
+ * let in whose rows are still being made counts too (openAdmission).
+ */
export function accountActiveRuns(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;
+ return r.n + openCount(accountId, false);
}
/**
* An account's runs going now on this install's GPUs, and how many of them haven't started yet (no row of theirs has).
- * Runs of light work only (joins, trims) don't count.
+ * Runs of light work only (joins, trims) don't count. A run let in whose rows are still being made counts as one in line.
*/
export function poolRunCounts(accountId: string): { active: number; waiting: number } {
const r = db()
@@ -65,7 +99,16 @@ export function poolRunCounts(accountId: string): { active: number; waiting: num
GROUP BY k)`,
)
.get(accountId) as { active: number; waiting: number };
- return { active: r.active, waiting: r.waiting };
+ const open = openCount(accountId, true);
+ return { active: r.active + open, waiting: r.waiting + open };
+}
+
+/**
+ * Forget one hourly admission (admitRun noted it at `at`) of a run that made nothing: no rows, nothing sent, so it isn't
+ * one of the hour's runs.
+ */
+export function forgetAdmission(accountId: string, at: number): void {
+ db().prepare("DELETE FROM pool_admissions WHERE id = (SELECT id FROM pool_admissions WHERE account = ? AND at = ? ORDER BY id DESC LIMIT 1)").run(accountId, at);
}
declare global {
@@ -82,6 +125,7 @@ declare global {
export function prunePoolAdmissions(now = Date.now(), force = false): number {
if (!force && now - (globalThis.__fuobePoolAdmissionsPruned ?? 0) < 60_000) return 0;
globalThis.__fuobePoolAdmissionsPruned = now;
+ db().prepare("DELETE FROM open_admissions WHERE at < ?").run(now - OPEN_ADMISSION_MS);
return db().prepare("DELETE FROM pool_admissions WHERE at < ?").run(now - KEEP_MS).changes;
}
diff --git a/src/server/pool-own-setup.ts b/src/server/pool-own-setup.ts
index 9faa7144..4ec0c875 100644
--- a/src/server/pool-own-setup.ts
+++ b/src/server/pool-own-setup.ts
@@ -1,17 +1,20 @@
import "server-only";
-import type { GenerationRequest, ModelDef } from "@/lib/catalog/types";
+import fs from "node:fs";
+import path from "node:path";
+import type { Engine, GenerationRequest, ModelDef } from "@/lib/catalog/types";
import { MODELS } from "@/lib/catalog/models";
import { directRunFeatures } from "@/lib/catalog/genjutsu";
import { ENHANCE_FEATURES, REGEN_MODEL, wantsH3TwoK } from "@/lib/catalog/regenerate";
import { RESTORE } from "@/lib/catalog/restore";
import { wantsVoiceFirst } from "@/lib/av/voice-first";
-import { ownSetupOnly, type OwnSetup } from "@/lib/own-setup";
+import { ownSetupGraphs, ownSetupOnly, type OwnSetup } from "@/lib/own-setup";
import { controlSetup } from "@/lib/own-setup-controls";
import { RTX_CLASSES, rtxCardOf } from "@/lib/catalog/rtx-video";
import { gpuFits } from "@/lib/gpu/readiness";
import { loadIndex } from "./gpu/index-file";
import { readSnapshot } from "./gpu/snapshots";
import { poolOnWorkers, poolTakes } from "./hosted";
+import { ownSetupOnlyNow } from "./own-setup-live";
/**
* What a run on this install's GPUs needs instead, in the "own setup" shape (src/lib/own-setup.ts): the visitor's own GPU
@@ -44,11 +47,49 @@ export function requestSetupIds(req: Pick<GenerationRequest, "modelId" | "op" |
return ids;
}
-/** The first static item a request asks for that runs on a visitor's own setup only, or null. */
-export function requestOwnSetup(req: Pick<GenerationRequest, "modelId" | "op" | "feature" | "params" | "engine">): OwnSetup | null {
+const MANIFEST = path.join(process.cwd(), "workflows", "comfyui", "manifest.json");
+
+/** ownSetupOnlyNow's answers, by manifest, item and engine, for the manifest as last modified (it is large: read once). */
+const nowAnswers = new Map<string, { mtimeMs: number; answer: OwnSetup | null }>();
+
+/**
+ * An item's own setup as it stands now, for the pool gate: an item whose graphs the manifest marks validated runs as any
+ * other (own-setup-live.ts ownSetupOnlyNow), so its label leaves the runs on this install's GPUs with the pages' own. An
+ * item with no graphs of its own is ownSetupOnly's answer, with no file read.
+ */
+export function ownSetupHere(id: string, engine?: Engine, manifest = MANIFEST): OwnSetup | null {
+ if (!ownSetupGraphs(id).length) return ownSetupOnly(id, engine);
+ let mtimeMs = 0;
+ try {
+ mtimeMs = fs.statSync(manifest).mtimeMs;
+ } catch {
+ // No manifest: ownSetupOnlyNow keeps the item's own setup.
+ }
+ const key = `${manifest}\n${id}\n${engine ?? ""}`;
+ const kept = nowAnswers.get(key);
+ if (kept && kept.mtimeMs === mtimeMs) return kept.answer;
+ const answer = ownSetupOnlyNow(id, engine, manifest);
+ nowAnswers.set(key, { mtimeMs, answer });
+ return answer;
+}
+
+/**
+ * Items a run on this install's GPUs asks for that only a GPU of the visitor's own runs, whatever else the item names:
+ * Restore & colourise's windows load a gated LoRA that no visitor's key is sent with, so no key runs them.
+ */
+const GPU_ONLY = new Set(["video-tools:restore"]);
+
+/** The first static item a request asks for that runs on a visitor's own setup only (as it stands now), or null. */
+export function requestOwnSetup(req: Pick<GenerationRequest, "modelId" | "op" | "feature" | "params" | "engine">, manifest = MANIFEST): OwnSetup | null {
for (const id of requestSetupIds(req)) {
- const o = ownSetupOnly(id, req.engine);
- if (o) return o;
+ const o = ownSetupHere(id, req.engine, manifest);
+ if (!o) continue;
+ if (GPU_ONLY.has(id) && o.need === "gpu" && o.orKey) {
+ const gpu = { ...o };
+ delete gpu.orKey;
+ return gpu;
+ }
+ return o;
}
return null;
}
diff --git a/src/server/tool-presses.ts b/src/server/tool-presses.ts
new file mode 100644
index 00000000..85b58702
--- /dev/null
+++ b/src/server/tool-presses.ts
@@ -0,0 +1,96 @@
+import "server-only";
+import crypto from "node:crypto";
+import { db } from "./db";
+
+/**
+ * One press of a tool's Run by an account, by the id its page sends with it (the same on every resend of that press),
+ * kept in the database so a resend that reaches another server process (during a deploy), or comes after a restart,
+ * gets the first press's answer instead of a second run. Kept with hosted runs on only; without them a tool's run is
+ * made once per press in each process, as before (shorts-schemas.ts once).
+ *
+ * The press also names its hold for the external billing service: the reserve's request id is made from the account,
+ * the tool's scope and the page's id (reserveRequestId), so the same press always asks for the same hold. A press that
+ * was refused after its hold was made (the hold then goes back) is tried afresh by its next resend, under a new request
+ * id (`tries`), so a later press of the same settings never reuses a hold that was given back.
+ */
+
+/** How long a press is remembered (a resend comes within a minute; a day is plenty). */
+export const PRESS_KEEP_MS = 24 * 3_600_000;
+
+/** A press still starting after this long belongs to a process that stopped: a resend starts it itself. */
+export const PRESS_STARTING_MS = 5 * 60_000;
+
+/**
+ * The reserve's request id for a press: made from the account and the press's id, so the same press always gives the
+ * same one and no other account's press can ever name it. A tool's press id is its scope and the page's id.
+ */
+export const reserveRequestId = (accountId: string, pressId: string): string =>
+ `r_${crypto.createHash("sha256").update(`${accountId}\n${pressId}`).digest("hex").slice(0, 32)}`;
+
+/** A tool's press id: its scope (the tool, and the project or item it runs on) and the page's id for the press. */
+export const toolPressId = (scope: string, clientId: string, tries = 0): string => `${scope}\n${clientId}${tries ? `\n${tries}` : ""}`;
+
+/** What a route answered: kept as its parts, so every resend gets its own copy. */
+export interface PressAnswer {
+ status: number;
+ headers: [string, string][];
+ text: string;
+}
+
+/**
+ * Where a press stands: claimed by this call (`tries`: how many of its earlier tries were refused after their hold was
+ * made), being started by another call (`starting`), or answered already (`done`).
+ */
+export type PressClaim = { kind: "claimed"; tries: number } | { kind: "starting" } | { kind: "done"; answer: PressAnswer };
+
+const key = (accountId: string, scope: string, clientId: string): string => reserveRequestId(accountId, toolPressId(scope, clientId));
+
+/** Claim a press for this call, in one locked step: no two calls (in any process) start the same press. */
+export function claimPress(accountId: string, scope: string, clientId: string, now = Date.now()): PressClaim {
+ const d = db();
+ const id = key(accountId, scope, clientId);
+ return d
+ .transaction((): PressClaim => {
+ d.prepare("DELETE FROM tool_presses WHERE at < ?").run(now - PRESS_KEEP_MS);
+ const r = d.prepare("SELECT answer_json, tries, starting, at FROM tool_presses WHERE account = ? AND request_id = ?").get(accountId, id) as
+ | { answer_json: string | null; tries: number; starting: number; at: number }
+ | undefined;
+ if (!r) {
+ d.prepare("INSERT INTO tool_presses (account, request_id, answer_json, tries, starting, at) VALUES (?, ?, NULL, 0, 1, ?)").run(accountId, id, now);
+ return { kind: "claimed", tries: 0 };
+ }
+ if (r.answer_json) {
+ try {
+ return { kind: "done", answer: JSON.parse(r.answer_json) as PressAnswer };
+ } catch {
+ // An answer that can't be read: started again below, under the same hold.
+ }
+ }
+ if (r.starting && now - r.at < PRESS_STARTING_MS) return { kind: "starting" };
+ d.prepare("UPDATE tool_presses SET answer_json = NULL, starting = 1, at = ? WHERE account = ? AND request_id = ?").run(now, accountId, id);
+ return { kind: "claimed", tries: r.tries };
+ })
+ .immediate();
+}
+
+/** The press's answer, for every resend of it from now on. */
+export function answerPress(accountId: string, scope: string, clientId: string, answer: PressAnswer, now = Date.now()): void {
+ db()
+ .prepare("UPDATE tool_presses SET answer_json = ?, starting = 0, at = ? WHERE account = ? AND request_id = ?")
+ .run(JSON.stringify(answer), now, accountId, key(accountId, scope, clientId));
+}
+
+/**
+ * The press was refused: a resend checks it again. `held`: its hold had been made (and goes back), so its next try asks
+ * for a new one under its own request id.
+ */
+export function releasePress(accountId: string, scope: string, clientId: string, held: boolean, now = Date.now()): void {
+ db()
+ .prepare(`UPDATE tool_presses SET answer_json = NULL, starting = 0, tries = tries + ?, at = ? WHERE account = ? AND request_id = ?`)
+ .run(held ? 1 : 0, now, accountId, key(accountId, scope, clientId));
+}
+
+/** A deleted account's presses go with it. */
+export function forgetAccountPresses(accountId: string): void {
+ db().prepare("DELETE FROM tool_presses WHERE account = ?").run(accountId);
+}
diff --git a/src/server/tool-runs.ts b/src/server/tool-runs.ts
index 134e2a68..3f6d1faf 100644
--- a/src/server/tool-runs.ts
+++ b/src/server/tool-runs.ts
@@ -58,6 +58,10 @@ export interface ToolRoute<T> {
skipGpuCheck?: boolean;
/** The place and price the body carries (account-tool-run.ts toolWishes, read before the route reads the body). */
wishes?: Awaited<ReturnType<typeof toolWishes>>;
+ /** Runs only on this install's GPUs: anywhere else it is refused as before (account-tool-run.ts AccountToolRun). */
+ poolOnly?: boolean;
+ /** The start as it runs on this install's GPUs, with no more outputs at once than `cap` (AccountToolRun.forPool). */
+ poolStart?: (cap: number) => () => T;
}
/** An account's run of such a tool: its steps planned from `start`, checked, placed and started (runAccountTool). */
@@ -74,6 +78,13 @@ export async function runToolForAccount<T>(request: Request, account: Account, o
start: o.start,
skipGpuCheck: o.skipGpuCheck,
...o.wishes,
+ ...(o.poolOnly && { poolOnly: true }),
+ ...(o.poolStart && {
+ forPool: (cap: number) => {
+ const start = o.poolStart!(cap);
+ return { plan: () => dryRunSteps(start), start };
+ },
+ }),
}),
({ value, gpuWarning }) => o.ok(value, gpuWarning),
);
diff --git a/tests/account-genjutsu.test.ts b/tests/account-genjutsu.test.ts
index 093a5791..faa7ecab 100644
--- a/tests/account-genjutsu.test.ts
+++ b/tests/account-genjutsu.test.ts
@@ -314,6 +314,18 @@ describe("an account runs Genjutsu on its own 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");
+ // One press sent twice (the page's id in its header) is one transcription.
+ const press = () => {
+ const req = json("/api/genjutsu/transcribe", "POST", { engine: "open", source: { url: clip, duration: 12 } }, "a");
+ req.headers.set("x-request-id", "press-words-0001");
+ return transcribeRoute.POST(req);
+ };
+ const first = await press();
+ expect(first.status, await first.clone().text()).toBe(201);
+ const n = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ const again = await press();
+ expect(((await again.json()) as { id: string }).id).toBe(((await first.json()) as { id: string }).id);
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(n);
});
it("From picture's describer runs on an account's own GPU before From picture opens here; a first frame counts only for whoever made it", async () => {
diff --git a/tests/genjutsu-openjutsu-access.test.ts b/tests/genjutsu-openjutsu-access.test.ts
index 7d46ceb0..a5439bd1 100644
--- a/tests/genjutsu-openjutsu-access.test.ts
+++ b/tests/genjutsu-openjutsu-access.test.ts
@@ -1,6 +1,6 @@
import fs from "node:fs";
import path from "node:path";
-import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeAll, describe, expect, it, onTestFinished, vi } from "vitest";
import { NextRequest } from "next/server";
import { tempDir } from "./helpers/temp-dir";
@@ -103,6 +103,11 @@ describe("Genjutsu's Openjutsu features before and after they open", () => {
it("the new makers' models sent straight to /api/generations run on an account's own GPU, never this studio's", async () => {
process.env.FUOBE_PUBLIC_SIGNUP = "1";
+ // Room on the server's disk, whatever the machine running this has free: only the place may stop a run here.
+ globalThis.__fuobeTestDiskFree = 1e13;
+ onTestFinished(() => {
+ globalThis.__fuobeTestDiskFree = undefined;
+ });
const account = auth.createAccount(`oj${++n}@example.com`, "long enough").id;
const cookie = auth.createSession(account).value;
const owner = auth.createSession().value;
diff --git a/tests/helpers/fake-billing.ts b/tests/helpers/fake-billing.ts
index 15dae0e2..e92b212c 100644
--- a/tests/helpers/fake-billing.ts
+++ b/tests/helpers/fake-billing.ts
@@ -118,6 +118,8 @@ export async function startFakeBilling(): Promise<FakeBilling> {
if (p === "/v1/settle" || p === "/v1/refund") {
const h = f.holds.get(String(b.holdId));
if (!h) return json(404, { error: "no such hold" });
+ // A released hold is closed: its amount went back, so none of its rows can settle or refund it again.
+ if (h.released) return json(409, { error: "hold released" });
const key = `${b.holdId} ${b.generationId}`;
reportCounts.set(key, (reportCounts.get(key) ?? 0) + 1);
h.reports.set(String(b.generationId), String(b.status));
@@ -125,6 +127,8 @@ export async function startFakeBilling(): Promise<FakeBilling> {
}
if (p === "/v1/release") {
const h = f.holds.get(String(b.holdId));
+ // A release is for a hold whose rows were never made: one whose rows reported is closed by those reports.
+ if (h?.reports.size) return json(409, { error: "hold has reports" });
if (h) h.released = true;
return json(200, { ok: true });
}
diff --git a/tests/hosted-surface-runs.test.ts b/tests/hosted-surface-runs.test.ts
index 9348c84e..c8129fec 100644
--- a/tests/hosted-surface-runs.test.ts
+++ b/tests/hosted-surface-runs.test.ts
@@ -1,3 +1,4 @@
+import crypto from "node:crypto";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
@@ -39,6 +40,7 @@ const sessionsRoute = await import("@/app/api/shorts/sessions/route");
const estimateRoute = await import("@/app/api/shorts/estimate/route");
const projectsRoute = await import("@/app/api/cinema/projects/route");
const generateRoute = await import("@/app/api/cinema/projects/[id]/generate/route");
+const retryRoute = await import("@/app/api/cinema/projects/[id]/items/[generationId]/retry/route");
const lockRoute = await import("@/app/api/palettes/lock/route");
const { proxy } = await import("@/proxy");
const { db } = await import("@/server/db");
@@ -247,6 +249,37 @@ describe("Cinema Studio for an account with no GPU of its own", () => {
expect(runsSince("none", since)).toHaveLength(1);
});
+ it("one press of Generate sent twice is one take and one hold, in this server process or another; a retry too", async () => {
+ hostedOn();
+ const id = await project("none");
+ const press = { input: STILL, requestId: "press-cinema-0001" };
+ const before = reserves();
+ const since = Date.now();
+ const first = await send(() => generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", press, "none", shownHeaders()), params({ id })));
+ expect(first.status, await first.clone().text()).toBe(201);
+ const answer = (await first.json()) as { items: { id: string }[] };
+ const sent = fake.calls_of("/v1/reserve").at(-1)!.body as { requestId: string };
+ expect(sent.requestId).toBe(`r_${crypto.createHash("sha256").update(`${ids.none}\ncinema:${id}\n${press.requestId}`).digest("hex").slice(0, 32)}`);
+ const again = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", press, "none", shownHeaders()), params({ id }));
+ expect(((await again.json()) as { items: { id: string }[] }).items.map((g) => g.id)).toEqual(answer.items.map((g) => g.id));
+ globalThis.__fuobeShortsRequests?.clear();
+ const elsewhere = await generateRoute.POST(json(`/api/cinema/projects/${id}/generate`, "POST", press, "none", shownHeaders()), params({ id }));
+ expect(elsewhere.status).toBe(201);
+ expect(((await elsewhere.json()) as { items: { id: string }[] }).items.map((g) => g.id)).toEqual(answer.items.map((g) => g.id));
+ expect(reserves() - before).toBe(1);
+ expect(runsSince("none", since)).toHaveLength(answer.items.length);
+ // A retry of a take: its own press, sent twice, is one run too.
+ const take = answer.items[0].id;
+ db().prepare("UPDATE generations SET status = 'failed' WHERE id = ?").run(take);
+ const retry = () => retryRoute.POST(json(`/api/cinema/projects/${id}/items/${take}/retry`, "POST", { requestId: "press-retry-0001" }, "none", shownHeaders()), params({ id, generationId: take }));
+ const r1 = await send(retry);
+ expect(r1.status, await r1.clone().text()).toBe(201);
+ globalThis.__fuobeShortsRequests?.clear();
+ const r2 = await retry();
+ expect(await r2.text()).toBe(await r1.text());
+ expect(reserves() - before).toBe(2);
+ });
+
it("an account whose own GPU answers is priced and run there, as before", async () => {
hostedOn();
const id = await project("gpu");
@@ -267,24 +300,65 @@ describe("the Image studio's palette lock for accounts", () => {
json("/api/palettes/lock", "POST", { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a silk scarf on a marble table", params: { numOutputs: 2 }, signature: {} }, colors: ["#112233", "#aabbcc"], ...extra }, who),
);
- it("a guest signs up first; an account reaches the route", async () => {
- const guest = await viaProxy("/api/palettes/lock");
- expect(guest.status).toBe(401);
- expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");
+ it("hosted runs off: refused to every account as before, at the proxy and at the route; nothing runs on its own GPU", async () => {
+ for (const who of ["none", "gpu", undefined]) {
+ const at = await viaProxy("/api/palettes/lock", who);
+ expect(at.status).toBe(403);
+ expect(((await at.json()) as { code: string }).code).toBe("own-gpu-tool");
+ }
+ const since = Date.now();
+ for (const who of ["none", "gpu"]) {
+ const r = await lock(who);
+ expect(r.status).toBe(403);
+ expect(((await r.json()) as { code: string }).code).toBe("own-gpu-tool");
+ }
+ expect(runsSince("gpu", since)).toEqual([]);
+ expect(runsSince("none", since)).toEqual([]);
+ // A guest signs up first at the route.
expect((await lock(undefined)).status).toBe(401);
- expect(passed(await viaProxy("/api/palettes/lock", "gpu"))).toBe(true);
});
- it("hosted runs off: an account with no GPU is asked to connect one; its own GPU runs it", async () => {
- const none = await lock("none");
- expect(none.status).toBe(403);
- expect(((await none.json()) as { code: string }).code).toBe("connect-gpu");
+ it("hosted runs on: an account reaches the route, a guest signs up first; an own GPU that goes first keeps its colours in the prompt", async () => {
+ hostedOn();
+ expect(passed(await viaProxy("/api/palettes/lock", "none"))).toBe(true);
+ expect(passed(await viaProxy("/api/palettes/lock", "gpu"))).toBe(true);
+ const guest = await viaProxy("/api/palettes/lock");
+ expect(guest.status).toBe(401);
+ expect(guest.headers.get(access.GUEST_HEADER)).toBe("1");
+ // Its own GPU goes first: the lock never runs there (the composer sends its colours in the prompt instead).
const since = Date.now();
- const own = await send(() => lock("gpu"));
- expect(own.status, await own.clone().text()).toBe(201);
+ const own = await lock("gpu");
+ expect(own.status).toBe(403);
+ expect(((await own.json()) as { code: string }).code).toBe("own-gpu-tool");
+ expect(runsSince("gpu", since)).toEqual([]);
+ // Asked for this install's GPUs by name, it runs there.
+ const there = await send(() => lock("gpu", { place: "pool", shown: { amount: fake.price.amount, priceVersion: fake.price.version } }));
+ expect(there.status, await there.clone().text()).toBe(201);
const rows = runsSince("gpu", since);
expect(rows.length).toBe(4);
- expect(rows.some((q) => q.place === "pool")).toBe(false);
+ expect(rows.every((q) => q.place === "pool")).toBe(true);
+ });
+
+ it("hosted runs on: no more pictures at once than a run there makes, as a studio run there is cut", async () => {
+ hostedOn();
+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), outputsPerRun: 1 } };
+ const since = Date.now();
+ const r = await send(() =>
+ lockRoute.POST(
+ json(
+ "/api/palettes/lock",
+ "POST",
+ { request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a silk scarf on a marble table", params: { numOutputs: 4 }, signature: {} }, colors: ["#112233"], shown: { amount: fake.price.amount, priceVersion: fake.price.version } },
+ "none",
+ ),
+ ),
+ );
+ expect(r.status, await r.clone().text()).toBe(201);
+ const rows = runsSince("none", since);
+ // One picture and its recolouring.
+ expect(rows.map((q) => q.modelId).sort()).toEqual(["oss-palette-image", "oss-z-image-turbo"]);
+ const reserve = fake.calls_of("/v1/reserve").at(-1)!.body as { run: { steps: { model: string; jobs: number }[] } };
+ expect(reserve.run.steps.find((s) => s.model === "oss-z-image-turbo")?.jobs).toBe(1);
});
it("hosted runs on: an account with no GPU gets both images and their recolouring as one run, held once", async () => {
diff --git a/tests/hosted-tool-runs.test.ts b/tests/hosted-tool-runs.test.ts
index 2c1392b9..1dee2b30 100644
--- a/tests/hosted-tool-runs.test.ts
+++ b/tests/hosted-tool-runs.test.ts
@@ -37,7 +37,9 @@ const hostedRun = await import("@/server/hosted-run");
const toolRun = await import("@/server/account-tool-run");
const { createGenerations } = await import("@/server/generations");
const { OWN_GPU_TOOL_MESSAGE } = await import("@/lib/guest-access");
-const { drainOutbox } = await import("@/server/billing-outbox");
+const { drainOutbox, queueReports } = await import("@/server/billing-outbox");
+const presses = await import("@/server/tool-presses");
+const pressRequestId = presses.reserveRequestId;
let fake: FakeBilling;
const ids: Record<string, string> = {};
@@ -109,6 +111,22 @@ describe("hosted runs off (the default): tool runs are as before", () => {
expect(stored("none")).toEqual([]);
});
+ it("a press is made once per server process, as before, and nothing of it is kept in the database", async () => {
+ const account = auth.accountById(ids.none)!;
+ let called = 0;
+ const press = () =>
+ toolRun.onceForAccount(
+ account,
+ "test-off",
+ "press-off-00001",
+ async () => ({ ok: true as const, value: ++called }),
+ ({ value }) => Response.json({ value }, { status: 201 }),
+ );
+ expect(await (await press()).json()).toEqual({ value: 1 });
+ expect(await (await press()).json()).toEqual({ value: 1 });
+ expect(db().prepare("SELECT COUNT(*) AS n FROM tool_presses WHERE account = ?").get(account.id)).toEqual({ n: 0 });
+ });
+
it("the seam answers its own GPU or key, whatever the steps", async () => {
const place = await toolRun.placeOf(auth.accountById(ids.none)!, [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }]);
expect(place).toEqual({ kind: "own" });
@@ -267,6 +285,140 @@ describe("hosted runs on", () => {
expect(await toolRun.placeOf(auth.accountById(ids.gpu)!, steps)).toEqual({ kind: "own" });
});
+ it("a press refused after its hold was made asks for a new hold on its next try; the first goes back", async () => {
+ useBilling();
+ const account = auth.accountById(ids.none)!;
+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };
+ const press = (start: () => unknown) =>
+ toolRun.onceForAccount(
+ account,
+ "test-press",
+ "press-tries-0001",
+ () => toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start }),
+ () => Response.json({ ok: true }, { status: 201 }),
+ );
+ const before = reserves();
+ // Its start makes more than was priced: refused after the hold was made.
+ const bad = await press(() => [...createGenerations(plan[0].request), ...createGenerations({ ...plan[0].request, prompt: "a fox at dusk" })]);
+ expect(bad.status).toBe(403);
+ const good = await press(() => createGenerations(plan[0].request));
+ expect(good.status, await good.clone().text()).toBe(201);
+ const sent = fake.calls_of("/v1/reserve").slice(before).map((c) => (c.body as { requestId: string }).requestId);
+ expect(sent).toEqual([pressRequestId(account.id, "test-press\npress-tries-0001"), pressRequestId(account.id, "test-press\npress-tries-0001\n1")]);
+ await drainOutbox();
+ const holds = [...fake.holds.values()].filter((h) => sent.includes(h.requestId));
+ expect(holds.map((h) => h.released)).toEqual([true, false]);
+ // The press answered: sent again, it is the same run, with no new hold.
+ expect((await press(() => createGenerations(plan[0].request))).status).toBe(201);
+ expect(reserves() - before).toBe(2);
+ });
+
+ it("a resend while another server process starts the press waits for that answer and makes nothing", async () => {
+ const account = auth.accountById(ids.none)!;
+ expect(presses.claimPress(account.id, "test-wait", "press-wait-0001").kind).toBe("claimed");
+ let called = 0;
+ const resend = toolRun.onceForAccount(
+ account,
+ "test-wait",
+ "press-wait-0001",
+ async () => {
+ called++;
+ return { ok: true as const, value: 1 };
+ },
+ () => Response.json({ here: true }, { status: 201 }),
+ );
+ setTimeout(() => presses.answerPress(account.id, "test-wait", "press-wait-0001", { status: 201, headers: [["content-type", "application/json"]], text: JSON.stringify({ elsewhere: true }) }), 300);
+ const r = await resend;
+ expect(r.status).toBe(201);
+ expect(await r.json()).toEqual({ elsewhere: true });
+ expect(called).toBe(0);
+ });
+
+ it("runs sent together whose start awaits before it makes its rows meet the limits one at a time", async () => {
+ useBilling();
+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), activeRuns: 1 } };
+ const account = auth.accountById(ids.none)!;
+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };
+ const rows = stored("none").length;
+ // A start that waits (a channel made first, say) before it makes its rows.
+ const start = async () => {
+ await new Promise((r) => setTimeout(r, 30));
+ return createGenerations(plan[0].request);
+ };
+ const go = () => toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start });
+ const [a, b] = await Promise.all([go(), go()]);
+ expect([a.ok, b.ok].filter(Boolean)).toHaveLength(1);
+ const no = (a.ok ? b : a) as Extract<typeof a, { ok: false }>;
+ expect(no.response.status).toBe(429);
+ expect(stored("none").length - rows).toBe(1);
+ // Its rows made, the run counts for itself: nothing is left open, and the next press meets the same limit.
+ expect(db().prepare("SELECT COUNT(*) AS n FROM open_admissions WHERE account = ?").get(account.id)).toEqual({ n: 0 });
+ const third = await go();
+ expect(third.ok).toBe(false);
+ // The account's own limit of runs at once counts such a run too, while its rows are being made.
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), activeRuns: 0, waiting: 0 } };
+ const many = await Promise.all(Array.from({ length: 6 }, go));
+ expect(many.filter((r) => r.ok)).toHaveLength(4);
+ });
+
+ it("a start that makes no rows gives its hold back, answers as the tool does, and isn't one of the hour's runs", async () => {
+ useBilling();
+ fake.policy = { ...fake.policy, limits: { ...(fake.policy.limits as object), runsPerHour: 1 } };
+ const account = auth.accountById(ids.none)!;
+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };
+ const hours = () => (db().prepare("SELECT COUNT(*) AS n FROM pool_admissions WHERE account = ?").get(account.id) as { n: number }).n;
+ db().prepare("DELETE FROM pool_admissions WHERE account = ?").run(account.id);
+ for (const start of [() => [], async () => []]) {
+ const before = reserves();
+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start });
+ expect(r.ok).toBe(true);
+ expect(reserves() - before).toBe(1);
+ await drainOutbox();
+ const hold = [...fake.holds.values()].at(-1)!;
+ expect(hold.released).toBe(true);
+ expect(hold.reports.size).toBe(0);
+ expect(hours()).toBe(0);
+ }
+ // The hour still has room for a run that makes something.
+ const real = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, { tool: "test", files: [], shown, plan: () => plan, start: () => createGenerations(plan[0].request) });
+ expect(real.ok).toBe(true);
+ expect(hours()).toBe(1);
+ });
+
+ it("a start that made a row and then failed: the row's report closes the hold, which is never released as well", async () => {
+ useBilling();
+ const account = auth.accountById(ids.none)!;
+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];
+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };
+ const releases = fake.calls_of("/v1/release").length;
+ const r = await toolRun.runAccountTool(json("/api/x", "POST", {}, "none"), account, {
+ tool: "test",
+ files: [],
+ shown,
+ plan: () => plan,
+ start: async () => {
+ createGenerations(plan[0].request);
+ await new Promise((r) => setTimeout(r, 5));
+ throw new Error("The plan changed. Please try again.");
+ },
+ });
+ expect(r.ok).toBe(false);
+ if (!r.ok) expect(r.response.status).toBe(422);
+ const hold = [...fake.holds.entries()].at(-1)!;
+ // The stopped row reports once it is canceled.
+ await expect.poll(() => (db().prepare("SELECT COUNT(*) AS n FROM generations WHERE json_extract(request_json, '$.hold') = ? AND status = 'canceled'").get(hold[0]) as { n: number }).n).toBe(1);
+ queueReports();
+ await drainOutbox();
+ expect(fake.calls_of("/v1/release").length).toBe(releases);
+ expect(hold[1].released).toBe(false);
+ expect([...hold[1].reports.values()]).toEqual(["canceled"]);
+ expect(fake.calls_of("/v1/refund").filter((c) => (c.body as { holdId: string }).holdId === hold[0])).toHaveLength(1);
+ });
+
it("a 3D model stays on an account's own GPU: refused here in the tools' words", async () => {
const steps = [{ request: { feature: "3d", modelId: "oss-pixal3d", op: "image-to-3d" as const, prompt: "", inputs: { images: ["/api/files/x.png"] } } }];
const place = await toolRun.placeOf(auth.accountById(ids.none)!, steps);
diff --git a/tests/hosted-video-audio-tools.test.ts b/tests/hosted-video-audio-tools.test.ts
index ed281cbf..39da1c74 100644
--- a/tests/hosted-video-audio-tools.test.ts
+++ b/tests/hosted-video-audio-tools.test.ts
@@ -1,3 +1,4 @@
+import crypto from "node:crypto";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
@@ -49,6 +50,8 @@ const routes = {
restore: await import("@/app/api/restore/route"),
};
const { ownSetupLabel, ownSetupOnly } = await import("@/lib/own-setup");
+type OwnSetup = import("@/lib/own-setup").OwnSetup;
+const { saveAccountKey } = await import("@/server/account-keys");
const { db } = await import("@/server/db");
const { resetRates } = await import("@/server/rate");
const billing = await import("@/server/billing");
@@ -65,10 +68,12 @@ beforeAll(async () => {
fake = await startFakeBilling();
fake.price = { amount: 0, version: "free" };
auth.setPassword("install password");
- for (const who of ["none", "gpu"]) {
+ for (const who of ["none", "gpu", "key"]) {
ids[who] = auth.createAccount(`tools-${who}@example.com`, "long enough").id;
cookies[who] = `${auth.SESSION_COOKIE}=${auth.createSession(ids[who]).value}`;
}
+ // "key" has a fal.ai key of its own and no GPU.
+ saveAccountKey(ids.key, "fal", "fal-test-key-0001");
globalThis.__fuobeTestGpuPort = comfy.port;
expect((await gpuRoute.PUT(json("/api/account/gpu", "PUT", { url: comfy.url }, "gpu"))).status).toBe(200);
});
@@ -213,12 +218,54 @@ describe("hosted runs on: an account with no GPU of its own runs them on this in
});
});
+describe("hosted runs on: one press of Run is one run and one hold, however often it is sent", () => {
+ beforeEach(hostedOn);
+ const pressed: [string, (f: Files) => [{ POST: (r: Request) => Promise<Response> }, string, unknown], string][] = [
+ ["Split soundtrack", (f) => [routes.audio, "/api/audio-tools", { ...split(f), requestId: "press-split-0001" }], "audio-tools"],
+ ["Translate & dub", (f) => [routes.dub, "/api/dub", { ...dub(f), requestId: "press-dub-00001" }], "dub"],
+ ];
+ for (const [name, run, scope] of pressed) {
+ it(`${name}: a resend gets the first run, in this server process or another`, async () => {
+ const f = await filesOf("none");
+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();
+ const before = reserves();
+ const since = Date.now();
+ const first = await send(() => call("none", run(f)));
+ expect(first.status, await first.clone().text()).toBe(201);
+ const answer = await first.text();
+ const rows = places("none", since).length;
+ expect(rows).toBeGreaterThan(0);
+ // The reserve names the press: the account, the tool and the page's id, never a fresh id.
+ const sent = fake.calls_of("/v1/reserve").at(-1)!.body as { requestId: string };
+ const id = (run(f)[2] as { requestId: string }).requestId;
+ expect(sent.requestId).toBe(`r_${crypto.createHash("sha256").update(`${ids.none}\n${scope}\n${id}`).digest("hex").slice(0, 32)}`);
+ const again = await call("none", run(f));
+ expect(again.status).toBe(201);
+ expect(await again.text()).toBe(answer);
+ // Another server process (nothing of the first press in its memory) answers the same, from the database.
+ globalThis.__fuobeShortsRequests?.clear();
+ const elsewhere = await call("none", run(f));
+ expect(elsewhere.status).toBe(201);
+ expect(await elsewhere.text()).toBe(answer);
+ expect(reserves() - before).toBe(1);
+ expect(places("none", since)).toHaveLength(rows);
+ });
+ }
+});
+
describe("hosted runs on: a tool that runs on a visitor's own setup only", () => {
beforeEach(hostedOn);
const restore = (f: Files) => ({ engine: "open", source: { url: f.clip, name: "old.mp4", ...src } });
+ // A GPU of its own: Restore's gated LoRA goes with no visitor's key, so no key is named.
+ const restoreSetup = () => {
+ const gpu = { ...(ownSetupOnly("video-tools:restore") as Extract<OwnSetup, { need: "gpu" }>) };
+ delete gpu.orKey;
+ return gpu;
+ };
+
it("Restore & colourise: its price check says its setup's label, and Run opens that setup with nothing held or made", async () => {
- const setup = ownSetupOnly("video-tools:restore")!;
+ const setup = restoreSetup();
const f = await filesOf("none");
const check = await routes.restoreEstimate.POST(json("/api/restore/estimate", "POST", restore(f), "none"));
expect(check.status, await check.clone().text()).toBe(200);
@@ -234,6 +281,22 @@ describe("hosted runs on: a tool that runs on a visitor's own setup only", () =>
expect(places("none", since)).toEqual([]);
});
+ it("Restore & colourise: an account with a key of its own and no GPU is sent to a GPU of its own, never to its key", async () => {
+ const setup = restoreSetup();
+ expect(ownSetupLabel(setup)).not.toMatch(/key/i);
+ const f = await filesOf("key");
+ const check = await routes.restoreEstimate.POST(json("/api/restore/estimate", "POST", restore(f), "key"));
+ expect(check.status, await check.clone().text()).toBe(200);
+ expect(((await check.json()) as { quote?: Record<string, unknown> }).quote).toMatchObject({ allowed: false, text: ownSetupLabel(setup), ownSetup: setup });
+ const before = reserves();
+ const since = Date.now();
+ const r = await routes.restore.POST(json("/api/restore", "POST", restore(f), "key"));
+ expect(r.status, await r.clone().text()).toBe(403);
+ expect(await r.json()).toMatchObject({ code: "connect-gpu", error: ownSetupLabel(setup), ownSetup: setup });
+ expect(reserves()).toBe(before);
+ expect(places("key", since)).toEqual([]);
+ });
+
it("Restore & colourise: an account whose own GPU answers runs it there, with no place in its price check", async () => {
const f = await filesOf("gpu");
const check = await routes.restoreEstimate.POST(json("/api/restore/estimate", "POST", restore(f), "gpu"));
diff --git a/tests/pool-own-setup.test.ts b/tests/pool-own-setup.test.ts
index a3d43cb5..267009d4 100644
--- a/tests/pool-own-setup.test.ts
+++ b/tests/pool-own-setup.test.ts
@@ -1,9 +1,12 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
import { describe, expect, it } from "vitest";
import { getModel, PRESETS } from "@/lib/catalog";
-import { ownSetupOnly } from "@/lib/own-setup";
+import { ownSetupGraphs, ownSetupOnly, type OwnSetup } from "@/lib/own-setup";
import { modelOwnSetup, poolOwnSetup, poolRulesOf, poolRunsModel, presetOwnSetup } from "@/lib/pool-rules";
import { poolRunState, type HostedCheck } from "@/lib/hosted";
-import { needsGpu, poolOwnSetups, requestOwnSetup, requestSetupIds } from "@/server/pool-own-setup";
+import { needsGpu, ownSetupHere, poolOwnSetups, requestOwnSetup, requestSetupIds } from "@/server/pool-own-setup";
import { loadIndex } from "@/server/gpu/index-file";
import { planRestore, RESTORE } from "@/lib/catalog/restore";
@@ -33,9 +36,37 @@ describe("a request's own setup", () => {
const plan = planRestore({ engine: "open", title: "R", prompt: "p", negative: "n", source: { url: "/api/files/a.mp4", duration: 12, frames: 192, fps: 16, width: 640, height: 480, hasAudio: true } });
const windows = plan.steps.filter((s) => s.request.modelId === RESTORE.model);
expect(windows.length).toBeGreaterThan(0);
- for (const s of windows) expect(requestOwnSetup({ ...s.request, engine: "open" })).toEqual(ownSetupOnly("video-tools:restore"));
+ // A GPU of the visitor's own only: its gated LoRA goes with no visitor's key, so no key is named.
+ const gpuOnly = { ...(ownSetupOnly("video-tools:restore") as Extract<OwnSetup, { need: "gpu" }>) };
+ delete gpuOnly.orKey;
+ for (const s of windows) expect(requestOwnSetup({ ...s.request, engine: "open" })).toEqual(gpuOnly);
+ expect(gpuOnly).toMatchObject({ need: "gpu" });
+ expect(gpuOnly).not.toHaveProperty("orKey");
for (const s of plan.steps.filter((x) => x.request.modelId !== RESTORE.model)) expect(requestSetupIds(s.request)).not.toContain("video-tools:restore");
- expect(ownSetupOnly("video-tools:restore")).toMatchObject({ need: "gpu" });
+ });
+
+ it("follows the manifest: once an item's graphs are validated it runs here like any other, with no change to the code", () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-pool-own-setup-"));
+ const manifest = path.join(dir, "manifest.json");
+ const graphs = ownSetupGraphs("video-tools:restore");
+ expect(graphs.length).toBeGreaterThan(0);
+ const write = (validated: boolean, at: number) => {
+ fs.writeFileSync(manifest, JSON.stringify({ workflows: graphs.map((id) => ({ id, validated })) }));
+ fs.utimesSync(manifest, at, at);
+ };
+ const window = { feature: RESTORE.feature, modelId: RESTORE.model, op: "restore-video" as const, params: {}, engine: "open" as const };
+ try {
+ write(false, 1_700_000_000);
+ expect(ownSetupHere("video-tools:restore", "open", manifest)).toEqual(ownSetupOnly("video-tools:restore"));
+ expect(requestOwnSetup(window, manifest)).toMatchObject({ need: "gpu" });
+ write(true, 1_700_000_100);
+ expect(ownSetupHere("video-tools:restore", "open", manifest)).toBeNull();
+ expect(requestOwnSetup(window, manifest)).toBeNull();
+ // An item with no graphs of its own keeps its setup, whatever the manifest says.
+ expect(ownSetupHere("regenerate:h3-2k", "open", manifest)).toEqual(ownSetupOnly("regenerate:h3-2k"));
+ } finally {
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
});
});
diff --git a/tests/price-check-reads.test.ts b/tests/price-check-reads.test.ts
index 2843fc74..2bc0fbab 100644
--- a/tests/price-check-reads.test.ts
+++ b/tests/price-check-reads.test.ts
@@ -24,6 +24,7 @@ const { KatanaBody, planKatana } = await import("@/server/katana");
const { videoLength } = await import("@/server/dub");
const { resetRates } = await import("@/server/rate");
const { proxy } = await import("@/proxy");
+const { isPriceCheck } = await import("@/lib/guest-access");
const dubRoute = await import("@/app/api/dub/route");
const audioRoute = await import("@/app/api/audio-tools/route");
const { gpuState } = await import("@/server/account-gpu");
@@ -303,4 +304,23 @@ describe("H-2 / H-3: price checks are rate-limited per visitor", () => {
const owner = auth.createSession().value;
for (let i = 0; i < 200; i++) expect(passed(proxy(post("/api/dub?preview=1", owner)))).toBe(true);
});
+
+ it("with hosted runs on, Cinema Studio's Generate price check counts against the same budget; its run is not a price check", async () => {
+ // With hosted runs off it prices nothing (the route says the run stays where it is): the request is the run it names.
+ expect(isPriceCheck("POST", "/api/cinema/projects/p1/generate", "?preview=1")).toBe(false);
+ expect(isPriceCheck("POST", "/api/cinema/projects/p1/generate", "?preview=1", true)).toBe(true);
+ expect(isPriceCheck("POST", "/api/cinema/projects/p1/generate", "", true)).toBe(false);
+ expect(isPriceCheck("POST", "/api/cinema/projects/p1/items/g1/retry", "?preview=1", true)).toBe(false);
+ process.env.FUOBE_HOSTED_RUNS = "1";
+ try {
+ const account = auth.createSession(b).value;
+ for (let i = 0; i < 120; i++) expect(passed(proxy(post("/api/cinema/projects/p1/generate?preview=1", account))), `check ${i}`).toBe(true);
+ const r = proxy(post("/api/cinema/projects/p1/generate?preview=1", account));
+ expect(r.status).toBe(429);
+ expect(r.headers.get("retry-after")).toBeTruthy();
+ expect((await r.json()).error).toMatch(/Too many price checks/);
+ } finally {
+ delete process.env.FUOBE_HOSTED_RUNS;
+ }
+ });
});