The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.
TypeScript ai-videocomfyuicreative-toolsgenerative-aiideogramimage-generationimage-to-3dimage-to-videoltx-videominimax-h3nextjsopen-sourceopen-weightsqwen-imagetext-to-imagevideo-generationwan
Hosted runs: a tool's new press id keeps a run once on this install's GPUs only
Adarshcb01be8666ac
diff --git a/src/app/api/audio-tools/route.ts b/src/app/api/audio-tools/route.tsindex b81af843..d2c34b4f 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, requestIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, poolPress, 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,11 +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.+ // A repeated requestId (a resend of the same press) gets the run the first one started on this install's GPUs.return onceForAccount(viewer.account,"audio-tools",- requestIdOf(raw),+ poolPress(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.tsindex 7284e653..1b7b8ce8 100644--- a/src/app/api/cinema/projects/[id]/generate/route.ts+++ b/src/app/api/cinema/projects/[id]/generate/route.ts@@ -1,4 +1,4 @@-import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolPriceCheck, toolViewer } from "@/server/account-tool-run";+import { bodyTooBig, guestRun, onceForAccount, poolPress, runAccountTool, toolPriceCheck, toolViewer } from "@/server/account-tool-run";import { cinemaSteps, generateInProject, prepareCinemaRun, startCinemaRun, type CinemaRun } from "@/server/cinema-generate";import { GenerateBody, body, fileRefs, handle, withStatus } from "@/server/cinema-schemas";@@ -31,7 +31,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projreturn onceForAccount(viewer.account,`cinema:${id}`,- b.requestId,+ poolPress(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.tsindex f72206d2..87a600ed 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, requestIdOf, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { guestRun, onceForAccount, poolPress, 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,12 +13,12 @@ export async function POST(request: Request, ctx: RouteContext<"/api/cinema/projconst { 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.+ // The page's id for this press (an optional body): a resend of it gets the first retry on this install's GPUs.const sent: unknown = await request.json().catch(() => null);return onceForAccount(viewer.account,`cinema-retry:${id}:${generationId}`,- requestIdOf(sent),+ poolPress(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.tsindex a370ce09..dc1b342b 100644--- a/src/app/api/content-factory/series/[id]/read/route.ts+++ b/src/app/api/content-factory/series/[id]/read/route.ts@@ -18,7 +18,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/content-facconst { 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));- // A resend of the same press (the page's id in its header) gets the reading the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the reading the first one started.return onceForAccount(viewer.account,`content-factory-read:${id}`,diff --git a/src/app/api/content-factory/series/route.ts b/src/app/api/content-factory/series/route.tsindex 60c7e800..2e0fe8fe 100644--- a/src/app/api/content-factory/series/route.ts+++ b/src/app/api/content-factory/series/route.ts@@ -38,7 +38,7 @@ 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;- // A resend of the same press (the page's id in its header) gets the series the first one made.+ // On this install's GPUs, a resend of this press (its id in the header) gets the series the first one made.return onceForAccount(viewer.account,"content-factory",diff --git a/src/app/api/dub/[id]/voice/route.ts b/src/app/api/dub/[id]/voice/route.tsindex af011a40..590fa02f 100644--- a/src/app/api/dub/[id]/voice/route.ts+++ b/src/app/api/dub/[id]/voice/route.ts@@ -1,5 +1,5 @@import { z } from "zod";-import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { asViewer, bodyTooBig, guestRun, onceForAccount, poolPress, runAccountTool, toolViewer } from "@/server/account-tool-run";import { CueSchema, getDubSession, planVoiceDub, previewVoiceDub, startVoiceDub, voiceDub, voicePlanSteps, type VoicePlan } from "@/server/dub";import { poolPricedCheck } from "@/server/tool-runs";@@ -28,7 +28,7 @@ async function post(request: Request, ctx: RouteContext<"/api/dub/[id]/voice">,return onceForAccount(viewer.account,`dub-voice:${id}`,- parsed.data.requestId,+ poolPress(parsed.data.requestId),() =>runAccountTool(request, viewer.account, {tool: "dub",diff --git a/src/app/api/dub/route.ts b/src/app/api/dub/route.tsindex 1d1f767f..01067466 100644--- a/src/app/api/dub/route.ts+++ b/src/app/api/dub/route.ts@@ -1,7 +1,7 @@import { connection } from "next/server";import { z } from "zod";import { ONE_SHOT_MODELS, VOICE_SPLIT_IDS, type VoiceSplit } from "@/lib/av/dub";-import { asViewer, bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";+import { asViewer, bodyTooBig, guestRun, onceForAccount, poolPress, runAccountTool, toolViewer } from "@/server/account-tool-run";import { createDubSession, dubPlanSteps, dubRoomProblem, listDubSessions, planDub, previewDub, startDub, type DubPlan } from "@/server/dub";import { connectRefusal } from "@/server/connect-refusal";import { ShortsError } from "@/server/shorts";@@ -50,7 +50,7 @@ async function post(request: Request, preview: boolean) {return onceForAccount(viewer.account,"dub",- input.requestId,+ poolPress(input.requestId),() =>runAccountTool(request, viewer.account, {tool: "dub",diff --git a/src/app/api/explainer/route.ts b/src/app/api/explainer/route.tsindex e0916309..d031b615 100644--- a/src/app/api/explainer/route.ts+++ b/src/app/api/explainer/route.ts@@ -50,7 +50,7 @@ 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 });- // A resend of the same press (the page's id in its header) gets the episode the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the episode the first one started.return onceForAccount(viewer.account,"explainer",diff --git a/src/app/api/faceless/channels/[id]/avatar/route.ts b/src/app/api/faceless/channels/[id]/avatar/route.tsindex 47ecca95..afb13e34 100644--- a/src/app/api/faceless/channels/[id]/avatar/route.ts+++ b/src/app/api/faceless/channels/[id]/avatar/route.ts@@ -12,7 +12,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/chreturn handle(async () => {const { id } = await ctx.params;if (viewer.kind === "owner") return Response.json(makeAvatar(id), { status: 201 });- // A resend of the same press (the page's id in its header) gets the avatar the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the avatar the first one started.return onceForAccount(viewer.account,`faceless-avatar:${id}`,diff --git a/src/app/api/faceless/channels/route.ts b/src/app/api/faceless/channels/route.tsindex 5b9a940d..5e3f10e9 100644--- a/src/app/api/faceless/channels/route.ts+++ b/src/app/api/faceless/channels/route.ts@@ -37,7 +37,7 @@ export async function POST(request: Request) {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 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.+ // On this install's GPUs, a resend of this press (its id in the header) gets the first one's channel and avatar.return onceForAccount(account,"faceless-channel",diff --git a/src/app/api/faceless/episodes/[id]/[action]/route.ts b/src/app/api/faceless/episodes/[id]/[action]/route.tsindex 240d988e..1626d1a6 100644--- a/src/app/api/faceless/episodes/[id]/[action]/route.ts+++ b/src/app/api/faceless/episodes/[id]/[action]/route.ts@@ -77,7 +77,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/ep}),);}- // A resend of the same press (the page's id in its header) gets the run the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the run the first one started.return onceForAccount(viewer.account,`faceless-${action}:${id}`,diff --git a/src/app/api/faceless/episodes/[id]/change/route.ts b/src/app/api/faceless/episodes/[id]/change/route.tsindex 870bb699..dc8818a7 100644--- a/src/app/api/faceless/episodes/[id]/change/route.ts+++ b/src/app/api/faceless/episodes/[id]/change/route.ts@@ -20,7 +20,7 @@ export async function POST(request: Request, ctx: RouteContext<"/api/faceless/epreturn Response.json(episodeView(id), { status: 201 });}const graph = asViewer(viewer, () => changeGraph(id, c));- // A resend of the same press (the page's id in its header) gets the change the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the change the first one started.return onceForAccount(viewer.account,`faceless-change:${id}`,diff --git a/src/app/api/faceless/voices/preview/route.ts b/src/app/api/faceless/voices/preview/route.tsindex b043086a..ddf9d001 100644--- a/src/app/api/faceless/voices/preview/route.ts+++ b/src/app/api/faceless/voices/preview/route.ts@@ -18,7 +18,7 @@ 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);- // A resend of the same press (the page's id in its header) gets the sample the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the sample the first one started.return onceForAccount(viewer.account,`faceless-voice:${voice.id}`,diff --git a/src/app/api/genjutsu/scene/route.ts b/src/app/api/genjutsu/scene/route.tsindex 973ad30f..768e4f1e 100644--- a/src/app/api/genjutsu/scene/route.ts+++ b/src/app/api/genjutsu/scene/route.ts@@ -16,7 +16,7 @@ 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 });- // A resend of the same press (the page's id in its header) gets the describer the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the describer the first one started.return onceForAccount(viewer.account,"genjutsu-scene",diff --git a/src/app/api/genjutsu/transcribe/route.ts b/src/app/api/genjutsu/transcribe/route.tsindex 1c02bb0c..06b04c58 100644--- a/src/app/api/genjutsu/transcribe/route.ts+++ b/src/app/api/genjutsu/transcribe/route.ts@@ -17,7 +17,7 @@ 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 });- // A resend of the same press (the page's id in its header) gets the transcription the first one started.+ // On this install's GPUs, a resend of this press (its id in the header) gets the first one's transcription.return onceForAccount(viewer.account,"genjutsu-transcribe",diff --git a/src/server/account-tool-run.ts b/src/server/account-tool-run.tsindex fe06c395..57bbbe3b 100644--- a/src/server/account-tool-run.ts+++ b/src/server/account-tool-run.ts@@ -143,16 +143,20 @@ async function awaitPress(look: () => PressClaim | null): Promise<Extract<PressC* gets it as well, and the run 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) is a new try then, with a new hold. A run on the account's own GPU or key keeps nothing, as before.- * `ok` turns the started run into the route's answer.+ * An id given as a PoolPress (poolPress, pressIdOf) is kept for a run on this install's GPUs only: on the account's own+ * GPU or key each send of it makes its run, as it did before the page sent one. `ok` turns the started run into the+ * route's answer.*/export async function onceForAccount<T>(account: Account,scope: string,- id: string | undefined,+ id: string | PoolPress | undefined,fn: () => Promise<AccountToolResult<T>>,ok: (r: { value: T; gpuWarning?: string }) => Response,): Promise<Response> {- const key = id && hostedRunsOn() ? toolPressKey(scope, id) : null;+ const poolOnly = typeof id === "object";+ const sent = poolOnly ? id.poolOnly : id;+ const key = sent && hostedRunsOn() ? toolPressKey(scope, sent) : null;const attempt = async (): Promise<PressAnswer> => {// A press another server process answered (or is starting) is that answer.const before = key ? await awaitPress(() => toolPressSeen(account.id, key)) : null;@@ -175,7 +179,9 @@ export async function onceForAccount<T>(}};try {- return fromAnswer(await once(`${scope}:acct:${account.id}`, id, attempt));+ // (Once per server process for every run: a plain id only. A PoolPress is kept by the database alone, for a run on+ // this install's GPUs.)+ return fromAnswer(await once(`${scope}:acct:${account.id}`, poolOnly ? undefined : sent, attempt));} catch (e) {if (e instanceof Refused) return fromAnswer(e.answer);throw e;@@ -206,8 +212,17 @@ export function requestIdOf(body: unknown): string | 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) });+/**+ * A page's id for a press of Run that keeps the run once on this install's GPUs only (onceForAccount): for a tool whose+ * route made a run for every send before its page sent an id. A run on the account's own GPU or key is made as before.+ */+export type PoolPress = { readonly poolOnly: string | undefined };++/** A press id kept for a run on this install's GPUs only (PoolPress). */+export const poolPress = (id: string | undefined): PoolPress => ({ poolOnly: id });++/** A page's id for a press of Run, from the request's PRESS_HEADER (kept for a run on this install's GPUs only), or none. */+export const pressIdOf = (request: Request): PoolPress => poolPress(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 letdiff --git a/tests/hosted-tool-runs.test.ts b/tests/hosted-tool-runs.test.tsindex 6993575c..854eea4f 100644--- a/tests/hosted-tool-runs.test.ts+++ b/tests/hosted-tool-runs.test.ts@@ -127,6 +127,22 @@ describe("hosted runs off (the default): tool runs are as before", () => {expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(account.id)).toEqual({ n: 0 });});+ it("a press id kept for this install's GPUs only makes a run for every send, as before the page sent one", async () => {+ const account = auth.accountById(ids.none)!;+ let called = 0;+ const press = () =>+ toolRun.onceForAccount(+ account,+ "test-off-pool-only",+ toolRun.poolPress("press-off-pool-01"),+ 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: 2 });+ expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests 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" });@@ -340,6 +356,43 @@ describe("hosted runs on", () => {expect(reserves()).toBe(before);});+ it("a press id kept for this install's GPUs only: one run and one hold there; on the account's own GPU a run per send", async () => {+ useBilling();+ const plan = [{ request: { feature: "image", modelId: "oss-z-image-turbo", prompt: "a fox" } }];+ const shown = { amount: fake.price.amount, priceVersion: fake.price.version };+ const pressAs = (who: string, id: string) => {+ const account = auth.accountById(ids[who])!;+ return toolRun.onceForAccount(+ account,+ "test-pool-only",+ toolRun.poolPress(id),+ () => toolRun.runAccountTool(json("/api/x", "POST", {}, who), account, { tool: "test", files: [], shown, plan: () => plan, start: () => createGenerations(plan[0].request) }),+ ({ value }) => Response.json({ ids: (value as { id: string }[]).map((g) => g.id) }, { status: 201 }),+ );+ };+ const before = reserves();+ // On this install's GPUs: sent twice in this server process, one run and one hold.+ const first = await pressAs("none", "press-pool-only-1");+ expect(first.status, await first.clone().text()).toBe(201);+ const again = await pressAs("none", "press-pool-only-1");+ expect(await again.json()).toEqual(await first.json());+ expect(reserves() - before).toBe(1);+ expect(fake.calls_of("/v1/reserve").at(-1)!.body).toMatchObject({ requestId: pressRequestId(ids.none, "test-pool-only\npress-pool-only-1") });+ // On the account's own GPU: each send makes its run, nothing kept, nothing held.+ const own = auth.accountById(ids.gpu)!;+ expect(await toolRun.placeOf(own, plan)).toEqual({ kind: "own" });+ const made: string[][] = [];+ for (let i = 0; i < 2; i++) {+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ const r = await pressAs("gpu", "press-pool-only-2");+ expect(r.status, await r.clone().text()).toBe(201);+ made.push(((await r.json()) as { ids: string[] }).ids);+ }+ expect(made[1]).not.toEqual(made[0]);+ expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(own.id)).toEqual({ n: 0 });+ expect(reserves() - before).toBe(1);+ });+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, presses.toolPressKey("test-wait", "press-wait-0001")).kind).toBe("claimed");diff --git a/tests/hosted-video-audio-tools.test.ts b/tests/hosted-video-audio-tools.test.tsindex 39da1c74..e4cfc8d9 100644--- a/tests/hosted-video-audio-tools.test.ts+++ b/tests/hosted-video-audio-tools.test.ts@@ -250,6 +250,25 @@ describe("hosted runs on: one press of Run is one run and one hold, however ofteexpect(reserves() - before).toBe(1);expect(places("none", since)).toHaveLength(rows);});++ it(`${name}: on an account's own GPU every send of a press makes its run, as before, and nothing of it is kept`, async () => {+ const f = await filesOf("gpu");+ const before = reserves();+ const since = Date.now();+ const counts: number[] = [];+ for (let i = 0; i < 2; i++) {+ // One at a time, as the account's limit on runs going at once asks.+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+ const r = await send(() => call("gpu", run(f)));+ expect(r.status, await r.clone().text()).toBe(201);+ counts.push(places("gpu", since).length);+ }+ expect(counts[0]).toBeGreaterThan(0);+ expect(counts[1]).toBe(counts[0] * 2);+ expect(places("gpu", since).every((p) => p === "own")).toBe(true);+ expect(db().prepare("SELECT COUNT(*) AS n FROM run_requests WHERE account = ?").get(ids.gpu)).toEqual({ n: 0 });+ expect(reserves()).toBe(before);+ });}});