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
Runs on your own GPU or key: a project's take stays in its project, and a waiting run's buttons can act
Adarshd2597874fe77
diff --git a/src/app/api/generations/route.ts b/src/app/api/generations/route.tsindex 47f34cf9..9bd9accc 100644--- a/src/app/api/generations/route.ts+++ b/src/app/api/generations/route.ts@@ -19,7 +19,7 @@ import { ACCOUNT_LIMITS, ACCOUNT_MESSAGES, accountTotalBytes, accountUsage, diskimport { accountInputProblem } from "@/server/account-inputs";import { db } from "@/server/db";import { findView, requestViewKey } from "@/server/any-angle";-import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, CHAINED_RUN, createGenerations, getGeneration, inChain, listGenerations, outputKind, previewGeneration, type AccountRunRefusal } from "@/server/generations";+import { accountLoraFix, accountRun, AccountRunError, asAccount, asVisitor, cancelGeneration, CHAINED_RUN, createGenerations, getGeneration, keyMoveBlock, listGenerations, outputKind, previewGeneration, PROJECT_RUN, type AccountRunRefusal, type KeyMoveBlock } from "@/server/generations";import { ensureTrashPurge, listOptionsFrom } from "@/server/library";import { hit, unhit } from "@/server/rate";import { GenerationRequestSchema } from "@/server/request-schema";@@ -88,17 +88,26 @@ interface Replaced {/** A `replaces` for a run that can't be taken over any more: started on its GPU meanwhile, or stopped already. */const NOT_REPLACEABLE = "This run has already started or stopped, so nothing new was run.";-/** A `replaces` for a waiting step of a longer run: moving it alone would cancel it and leave the rest of the run without it. */-const CHAINED = "chained";+/** What a `replaces` on a waiting run Run with your key can't move on its own answers (409, in plain words). */+const BLOCKED: Record<KeyMoveBlock, { error: string; code: string }> = {+ chained: { error: CHAINED_RUN, code: "chained-run" },+ project: { error: PROJECT_RUN, code: "project-run" },+};++/** A `replaces` that names a waiting run Run with your key can't move on its own: why (generations.ts keyMoveBlock). */+interface Blocked {+ blocked: KeyMoveBlock;+}/*** Beside the request: the account's own run (waiting for its GPU or key, or failed) this one takes the place of ("Run* with your fal.ai key" on it). A waiting run takes its whole batch with it: every job of the same request not handed* over yet stops once this one is made, and this one makes their outputs (never the whole batch again). Undefined: no* `replaces`; null: one that can't be taken over any more (asked again just before the run is made, nothing awaited);- * CHAINED: a waiting step of a longer run (it waits for an earlier step, or a later one waits for it), never moved alone.+ * Blocked: a waiting run never moved alone (a step of a longer run, or a run of one of the account's projects), the same+ * check its tile makes before it offers the button.*/-function replacedRun(body: unknown, accountId: string): Replaced | typeof CHAINED | null | undefined {+function replacedRun(body: unknown, accountId: string): Replaced | Blocked | null | undefined {const id = (body as { replaces?: unknown } | null)?.replaces;if (id === undefined || id === null) return undefined;if (typeof id !== "string" || !/^[A-Za-z0-9_-]{1,40}$/.test(id)) return null;@@ -108,7 +117,8 @@ function replacedRun(body: unknown, accountId: string): Replaced | typeof CHAINEif (!row) return null;if (row.status === "failed") return { ids: [id] };if (row.status !== "queued" || row.external_id) return null;- if (inChain({ id, depends_on: row.depends_on })) return CHAINED;+ const blocked = keyMoveBlock({ id, depends_on: row.depends_on, batch_id: row.batch_id, request_json: row.request_json });+ if (blocked) return { blocked };if (!row.batch_id) return { ids: [id] };// Its batch's jobs (the same request; a chain's later steps have their own), and those not handed over yet.const jobs = db()@@ -116,8 +126,6 @@ function replacedRun(body: unknown, accountId: string): Replaced | typeof CHAINE.all(row.batch_id, row.request_json) as { id: string; status: string; external_id: string | null }[];const ids = jobs.filter((j) => j.status === "queued" && !j.external_id).map((j) => j.id);if (!ids.includes(id)) ids.push(id);- // A job of the batch that a later step waits for: the batch is part of a longer run too.- if (ids.some((j) => j !== id && inChain(j))) return CHAINED;let asked = 1;try {asked = Math.max(1, Number((JSON.parse(row.request_json) as { params?: { numOutputs?: unknown } }).params?.numOutputs) || 1);@@ -204,8 +212,9 @@ export async function POST(request: Request) {const replacing = account && !preview ? replacedRun(body, account.id) : undefined;// A run that started or stopped meanwhile (another tile's press took it already): nothing new runs.if (replacing === null) return refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });- // A waiting step of a longer run: it goes on as it is (moved alone, the rest of the run would go without it).- if (replacing === CHAINED) return refuse(409, CHAINED_RUN, { code: "chained-run" });+ // A waiting step of a longer run, or a run of one of the account's projects: it goes on as it is (moved alone, the rest+ // of the run would go without it, or the project would lose it).+ if (replacing && "blocked" in replacing) return refuse(409, BLOCKED[replacing.blocked].error, { code: BLOCKED[replacing.blocked].code });let replaces = replacing;// It makes the outputs of the jobs it stops, not its whole batch's again.req = withReplacedOutputs(req, replaces);@@ -347,10 +356,10 @@ export async function POST(request: Request) {// of its batch's tiles meanwhile took it already (or it started on its GPU), so nothing new runs.if (replaces && account) {const now = replacedRun(body, account.id);- if (!now || now === CHAINED) {+ if (!now || "blocked" in now) {unhit(`run:${account.id}`);if (stamp?.hold) queueRelease(stamp.hold);- return now === CHAINED ? refuse(409, CHAINED_RUN, { code: "chained-run" }) : refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });+ return now ? refuse(409, BLOCKED[now.blocked].error, { code: BLOCKED[now.blocked].code }) : refuse(409, NOT_REPLACEABLE, { code: "not-replaceable" });}// Fewer of its jobs left to stop (one was handed over meanwhile): fewer outputs. A run on this install's GPUs keeps// the count it was priced and set aside for.@@ -366,9 +375,11 @@ export async function POST(request: Request) {return refuse(429, waitingFull ? ACCOUNT_MESSAGES.waitingRuns : ACCOUNT_MESSAGES.activeRuns, { code: ACTIVE_RUNS_CODE }, { "Retry-After": "30" });}const make = () => createGenerations(req);+ // An account's run made here is its own, in no tool's project: Run with your key may take its place while it waits.+ const alone = (s: RunStamp): RunStamp => ({ ...s, standalone: true });let items: ReturnType<typeof createGenerations>;try {- items = account && onPool ? runOnPool(account.id, () => withRunStamp(stamp ?? { place: "pool" }, make)) : stamp ? onOwn(() => withRunStamp(stamp, make)) : onOwn(make);+ items = account && onPool ? runOnPool(account.id, () => withRunStamp(alone(stamp ?? { place: "pool" }), make)) : account ? onOwn(() => withRunStamp(alone(stamp ?? {}), make)) : onOwn(make);} catch (e) {// Nothing was made: what was set aside goes back.if (stamp?.hold) queueRelease(stamp.hold);diff --git a/src/app/api/image-to-3d/route.ts b/src/app/api/image-to-3d/route.tsindex 08a3ecff..94952620 100644--- a/src/app/api/image-to-3d/route.ts+++ b/src/app/api/image-to-3d/route.ts@@ -7,6 +7,7 @@ import { accountEngineMode } from "@/server/account-keys";import { bodyTooBig, guestRun, onceForAccount, runAccountTool, toolViewer } from "@/server/account-tool-run";import { createGenerations } from "@/server/generations";import { GenerationRequestSchema } from "@/server/request-schema";+import { runStamp, withRunStamp } from "@/server/run-stamp";/*** Image to 3D's runs: a model from a photo, several photos, words or an object in a photo, a splat, and a finished@@ -58,7 +59,8 @@ export async function POST(request: Request) {tool: "image-to-3d",files,plan: () => [{ request: run }],- start: () => createGenerations(run),+ // A model made on its own, as in a studio (no project keeps it): Run with your key may take its place while it waits.+ start: () => withRunStamp({ ...runStamp(), standalone: true }, () => createGenerations(run)),skipGpuCheck: extra.gpuCheck === "skip",}),({ value, gpuWarning }) => {diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.tsindex 817a1277..2d29bc50 100644--- a/src/lib/catalog/types.ts+++ b/src/lib/catalog/types.ts@@ -1185,6 +1185,11 @@ export interface GenerationRequest {checkOutputs?: boolean;/** How long a run on this install's GPUs may wait in line (ms), when the billing service set it. */waitMs?: number;+ /**+ * Server-only too: an account's run made on its own in a studio, not by a tool for one of its projects (a Cinema take,+ * a storyboard). Only such a run can move to the account's key while it waits (Run with your key).+ */+ standalone?: boolean;feature: string;presetId?: string;modelId: string;diff --git a/src/server/generations.ts b/src/server/generations.tsindex 378816bf..b785ca1b 100644--- a/src/server/generations.ts+++ b/src/server/generations.ts@@ -181,8 +181,10 @@ const LIBRARY_JOIN = `generations g ${LIBRARY_JOINS}`;export function toGeneration(r: Row): Generation {const stored = JSON.parse(r.request_json) as GenerationRequest;- // The billing hold is the server's: never sent to a browser or a script.- const { hold, ...request } = stored;+ // The billing hold is the server's: never sent to a browser or a script. (So is `standalone`: what Run with your key+ // may move is said by the run's buttons.)+ const { hold, standalone: _standalone, ...request } = stored;+ void _standalone;const checking = r.stage === "checking";const model = getModel(r.model_id);const ar = request.params?.aspectRatio ?? model?.defaults?.aspectRatio;@@ -271,13 +273,14 @@ function parseTrouble(json: string): { trouble: RunTrouble } | Record<string, ne}/**- * A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. A step of a longer run never offers- * Run with your key (moving it alone would leave the rest of the run without it), also when its wait was kept before.+ * A waiting run's diagnosis (external_meta_json `heal`), as the Generation field. A run Run with your key can't move on+ * its own (keyMoveBlock: a step of a longer run, or a tool's run for one of the account's projects) never offers it,+ * also when its wait was kept before.*/-function waitingOf(r: Pick<Row, "id" | "depends_on" | "external_meta_json">): { waiting: RunTrouble & { until?: number } } | Record<string, never> {+function waitingOf(r: Pick<Row, "id" | "depends_on" | "batch_id" | "request_json" | "external_meta_json">): { waiting: RunTrouble & { until?: number } } | Record<string, never> {const h = readMeta(r.external_meta_json).heal;if (!h?.trouble || typeof h.trouble.cause !== "string" || !Array.isArray(h.trouble.actions)) return {};- const t = h.trouble.actions.some((a) => a.kind === "run-with-key") && inChain(r) ? withoutKeyOffer(h.trouble) : h.trouble;+ const t = h.trouble.actions.some((a) => a.kind === "run-with-key") && keyMoveBlock(r) ? withoutKeyOffer(h.trouble) : h.trouble;return { waiting: { ...t, ...(h.deadline && { until: h.deadline }) } };}@@ -288,17 +291,54 @@ const maybeSent = (r: Pick<Row, "error" | "external_meta_json">): boolean => r.e* A run that is one step of a longer one: it waits for an earlier step, or a later step (queued or running) waits for it.* Run with your key can't move such a step alone (the route answers 409 CHAINED_RUN, and its tile doesn't offer it).*/-export function inChain(r: string | Pick<Row, "id" | "depends_on">): boolean {+function inChain(r: string | Pick<Row, "id" | "depends_on">): boolean {const id = typeof r === "string" ? r : r.id;const dependsOn = typeof r === "string" ? (db().prepare("SELECT depends_on FROM generations WHERE id = ?").pluck().get(id) as string | null | undefined) : r.depends_on;if (dependsOn) return true;return !!db().prepare(`SELECT 1 FROM generations WHERE status IN ('queued', 'running') AND ${DEPENDENTS_OF} LIMIT 1`).get({ id, quoted: JSON.stringify(id) });}+/** Why Run with your key can't take a waiting run's place on its own: a step of a longer run, or a run of a project. */+export type KeyMoveBlock = "chained" | "project";++/**+ * Whether Run with your key can take this waiting run's place on its own (null), and why not. One check for its tile,+ * its next try's words and the route (POST /api/generations with `replaces`), so a button that shows can always act.+ *+ * - "chained": a step of a longer run (it waits for an earlier step, or a later step waits for it), or a job of a batch+ * whose other waiting job a later step waits for (the press moves the whole batch). Moved alone, the rest of the run+ * would go without it.+ * - "project": a run a tool made for one of the account's projects (a Cinema take, a storyboard, a short), even a take of+ * one step. The project keeps the run it made: a run made in its place would be outside it, and the take would show+ * Canceled. Only a run made on its own in a studio (stamped `standalone`, run-stamp.ts) moves.+ */+export function keyMoveBlock(r: string | Pick<Row, "id" | "depends_on" | "batch_id" | "request_json">): KeyMoveBlock | null {+ const row =+ typeof r === "string" ? (db().prepare("SELECT id, depends_on, batch_id, request_json FROM generations WHERE id = ?").get(r) as Pick<Row, "id" | "depends_on" | "batch_id" | "request_json"> | undefined) : r;+ if (!row) return null;+ if (inChain(row)) return "chained";+ if (row.batch_id) {+ // The batch's other jobs the press would stop with it (the same request, not handed over yet).+ const jobs = db()+ .prepare("SELECT id FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL AND status = 'queued' AND external_id IS NULL AND id != ?")+ .pluck()+ .all(row.batch_id, row.request_json, row.id) as string[];+ if (jobs.some((j) => inChain(j))) return "chained";+ }+ let standalone = false;+ try {+ standalone = (JSON.parse(row.request_json) as GenerationRequest).standalone === true;+ } catch {}+ return standalone ? null : "project";+}+/** What a step of a longer run that can't move to a key alone says (POST /api/generations with `replaces` on it). */export const CHAINED_RUN = "This step is part of a longer run, so it can't move to your key on its own. It goes on by itself, or cancel it and run the tool again with your key.";-/** A trouble's buttons without Run with your key (a step of a longer run). */+/** What a run of one of the account's projects says the same way (a Cinema take, a storyboard, a short). */+export const PROJECT_RUN = "This run is part of one of your projects, so it can't move to your key on its own. It goes on by itself, or cancel it and run it again in its project with your key.";++/** A trouble's buttons without Run with your key (a run that can't move to a key on its own). */const withoutKeyOffer = <T extends { actions: TroubleAction[] }>(t: T): T => ({ ...t, actions: t.actions.filter((a) => a.kind !== "run-with-key") });/**@@ -314,6 +354,11 @@ interface PendingMeta {resent?: boolean;/** Which of its batch's jobs it is (its seed is the batch's + this). */jobIndex?: number;+ /**+ * A step of an account's longer run on its first try (nothing waited, so no `heal`): when its job began to be sent.+ * Cleared when the try fails and the step waits; gone once it is handed over (markSending).+ */+ sending?: number;}/** A run's wait for its own GPU or key, kept with it (survives a restart). */@@ -1551,6 +1596,8 @@ const READY_DEPENDENTS = `SELECT g.* FROM generations g/** The error a waiting step gets when an input failed (framesProgress tells these from a step's own failure). */export const waitedOnFailure = (frame?: boolean) => `${frame ? "The previous frame" : "An earlier step"} didn't finish`;+/** Both of waitedOnFailure's sentences: a step that stopped only because an earlier one did. */+const WAITED_ON_FAILURE = new Set([waitedOnFailure(false), waitedOnFailure(true)]);/** What a step dropped by dropUnused says (canceled, not by anyone: the steps it was for failed). */export const DROPPED_UNUSED = "Stopped before it ran: the steps it was for failed";@@ -1625,21 +1672,26 @@ async function advanceDependents(): Promise<void> {const allIds = depIds(r.depends_on);const allSlots = slotsFor(stored, allIds.length);const allDeps = allIds.map(- (id) => db().prepare("SELECT status, provider, outputs_json, request_json FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json" | "request_json"> | undefined,+ (id) =>+ db().prepare("SELECT status, provider, outputs_json, request_json, error FROM generations WHERE id = ?").get(id) as Pick<Row, "status" | "provider" | "outputs_json" | "request_json" | "error"> | undefined,);const earlier = stored.frame ? "The previous frame" : "An earlier step";- const fail = (error: string, cause = "earlier-step") => {+ const fail = (error: string, cause = "earlier-step", logged = true) => {update(r.id, { status: "failed", error, message: null, completed_at: Date.now() });// An account's own step: the owner's log line and note, as for any of its runs.- ownFailed(r.id, ownAccountOf(stored), factsOf(r, { stage: "chain" }), cause);+ if (logged) ownFailed(r.id, ownAccountOf(stored), factsOf(r, { stage: "chain" }), cause);// Steps waiting only to feed this one (the other lanes of a per-frame render) are dropped before they are paid for.dropUnused(allIds);};const broken = (d: (typeof allDeps)[number]) => !d || d.status === "failed" || d.status === "canceled";// An optional input whose step failed is left out (Genjutsu's anchor frame): the step runs without it.const skipped = allSlots.flatMap((s, i) => (s.optional && broken(allDeps[i]) ? [i] : []));- if (allDeps.some((d, i) => broken(d) && !skipped.includes(i))) {- fail(waitedOnFailure(!!stored.frame));+ const failedDeps = allDeps.filter((d, i) => broken(d) && !skipped.includes(i));+ if (failedDeps.length) {+ // The owner's line goes with the first step after the failure: a step whose earlier steps all stopped only because+ // theirs did (a frame-by-frame chain broken at frame 3) writes none of its own.+ const knockOn = failedDeps.every((d) => d?.status === "failed" && WAITED_ON_FAILURE.has(d.error ?? ""));+ fail(waitedOnFailure(!!stored.frame), "earlier-step", !knockOn);continue;}const keep = (_: unknown, i: number) => !skipped.includes(i);@@ -1659,9 +1711,11 @@ async function advanceDependents(): Promise<void> {// Another instance (a deploy's other one) launching this step already: left to it.if (!claim(r.id)) continue;// A step that waited for its own GPU or key, taken over after a restart or a deploy (its wait is kept with it, as a- // run's is: takeOver). One cut off in the middle of its send may have reached its GPU or provider: never sent twice.- const heal = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null).heal;- if (heal && typeof heal.sending === "number") {+ // run's is: takeOver). One cut off in the middle of its send, on a later try or its first (markSending), may have+ // reached its GPU or provider: never sent twice.+ const pending = readMeta(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(r.id) as string | null);+ const heal = pending.heal;+ if ((heal && typeof heal.sending === "number") || typeof pending.sending === "number") {fail(CUT_OFF_SENDING, "interrupted-sending");continue;}@@ -2094,9 +2148,9 @@ async function submitNow(if (now + wait <= heal.deadline) {if (link) noteGpuState(account!, link.url, false, { trouble: asStatus(error, trouble, link) });// Kept with the run (another instance goes on with it after a restart or a deploy), the tile saying what it- // waits for and showing what helps. A step of a longer run doesn't offer Run with your key: moving it alone- // would leave the rest of the run without it.- const shown = trouble.actions.some((a) => a.kind === "run-with-key") && inChain(id) ? withoutKeyOffer(trouble) : trouble;+ // waits for and showing what helps. A step of a longer run, or a run of one of the account's projects, doesn't+ // offer Run with your key: moved alone, it would leave its run or its project (keyMoveBlock).+ const shown = trouble.actions.some((a) => a.kind === "run-with-key") && keyMoveBlock(id) ? withoutKeyOffer(trouble) : trouble;if (!markWaiting(id, heal, shown, now + wait, waitingWords(shown, isCloudProvider(providerId) ? providerId : undefined, pod))) return;if (heal.tries === 1 || heal.firstSeen[trouble.cause] === now) ownEvent(id, account!, error, trouble, facts({ attempt: heal.tries, waitedMs: now - heal.since }), "waiting");if (!(await pause(id, wait))) return;@@ -2124,6 +2178,9 @@ async function submitNow(trouble = { ...again, actions: withKeyOffer(again.actions, account!, req) };}}+ // The provider turned the job down as it was sent (a refused key, an empty balance, a model gone): it never had it,+ // so its card says Not billed again, as on a first try (not after a voice the provider cloned for it: that was billed).+ if (refusedAtSend(error) && !sent.has("voiceEmbedding")) notSending(id);failRun(id, error, trouble, req.account, account ? facts({ attempt: heal.tries, waitedMs: Date.now() - heal.since }) : undefined, !!account);return;}@@ -2151,21 +2208,43 @@ function letGo(id: string): void {/*** Just before a run's job is sent. A run that waited (its `heal` kept with it) is marked as being sent: an instance that* takes the wait over later (this one cut off in the middle of the send, by a restart or a deploy) then doesn't send it- * a second time. Throws LetGo when another instance holds the run, or when this server is stopping and the run waited- * (the next instance goes on with its wait, and sends it).+ * a second time. So is a step of an account's own longer run on its first try (`own`): the instance that launches it+ * after this one was cut off fails it instead of sending it again (advanceDependents). Throws LetGo when another+ * instance holds the run, or when this server is stopping and the run waited (the next instance goes on with its wait,+ * and sends it).*/-function markSending(id: string): void {- const r = db().prepare(`SELECT external_meta_json FROM generations WHERE id = ? AND ${PENDING}`).get(id) as Pick<Row, "external_meta_json"> | undefined;+function markSending(id: string, own: boolean): void {+ const r = db().prepare(`SELECT external_meta_json, depends_on FROM generations WHERE id = ? AND ${PENDING}`).get(id) as Pick<Row, "external_meta_json" | "depends_on"> | undefined;if (!r) throw new Error("Stopped");if (heldElsewhere(r.external_meta_json)) throw new LetGo("Held by another instance");- // A first try (nothing waited): a send cut off here fails at the next instance's look (sweepInterrupted).- if (!readMeta(r.external_meta_json).heal) return;+ if (!readMeta(r.external_meta_json).heal) {+ // A first try (nothing waited): a run's send cut off here fails at the next instance's look (sweepInterrupted).+ if (own && r.depends_on) {+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending', @now) WHERE id = @id AND ${PENDING}`)+ .run({ id, now: Date.now() });+ }+ return;+ }if (draining()) throw new LetGo("Stopping");db().prepare(`UPDATE generations SET external_meta_json = json_set(external_meta_json, '$.heal.sending', @now) WHERE id = @id AND ${PENDING} AND json_type(external_meta_json, '$.heal') = 'object'`).run({ id, now: Date.now() });}+/** A send its provider answered with a refusal (a 4xx): the job was never taken. */+function refusedAtSend(e: unknown): boolean {+ const status = (e as { status?: unknown } | null)?.status;+ return typeof status === "number" && status >= 400 && status < 500;+}++/** A send that is over without a job: the run's mark of being sent goes (it was never handed over). */+function notSending(id: string): void {+ db()+ .prepare(`UPDATE generations SET external_meta_json = json_remove(external_meta_json, '$.heal.sending', '$.sending') WHERE id = ? AND ${PENDING} AND json_valid(external_meta_json)`)+ .run(id);+}+/** Self-healing's clock: tests make it faster (0.001: a 30-minute wait takes 1.8 s). */export const SELF_HEAL = { scale: 1 };@@ -2185,7 +2264,7 @@ function markWaiting(id: string, heal: HealState, trouble: Diagnosis, next: numbdb().prepare(`UPDATE generations SET status = 'queued', message = @message, updated_at = @now,- external_meta_json = json_set(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.heal', json(@heal))+ external_meta_json = json_set(json_remove(CASE WHEN json_valid(external_meta_json) THEN external_meta_json ELSE '{}' END, '$.sending'), '$.heal', json(@heal))WHERE id = @id AND ${PENDING}`,).run({ id, message, now: Date.now(), heal: JSON.stringify(heal) }).changes > 0@@ -2903,7 +2982,7 @@ async function handOver(id: string, route: ModelRoute, providerId: ProviderId, pif (cloned && route.map?.cloneFirst && !input.voiceEmbedding) input.voiceEmbedding = cloned;// Nothing is sent once the run stopped being this one's to send (cancelled, failed, or taken by another instance).if (!going()) throw new Error("Stopped");- markSending(id);+ markSending(id, !!req.account && req.place !== "pool");const res = await adapter.submit({ generationId: id, model: plan.model, route, input });// A saved voice the cloud just cloned keeps the embedding (the owner's runs only), so its next line skips the clone.if (typeof res.meta?.voiceEmbedding === "string" && !req.account) void keepVoiceEmbedding(req.inputs?.voiceAudio, res.meta.voiceEmbedding).catch(() => {});diff --git a/src/server/run-stamp.ts b/src/server/run-stamp.tsindex 930a24a5..2738dfd9 100644--- a/src/server/run-stamp.ts+++ b/src/server/run-stamp.ts@@ -11,6 +11,8 @@ import type { GenerationRequest } from "@/lib/catalog/types";* - `hold`: the billing service's hold for the run (billing.ts reserve); every row reports to it once (billing-outbox.ts).* - `charge`: the words the billing service gave for the charge ("7 units"), shown on the result.* - `checkOutputs`: the moderation service asked to see this run's outputs before they show (moderation.ts).+ * - `standalone`: an account's run made on its own in a studio (POST /api/generations, Image to 3D's route), not by a+ * tool for one of its projects: Run with your key may take its place while it waits (generations.ts keyMoveBlock).*/export interface RunStamp {place?: "pool";@@ -19,6 +21,8 @@ export interface RunStamp {checkOutputs?: boolean;/** How long it may wait in line on this install's GPUs (ms), from the billing service. */waitMs?: number;+ /** Made on its own in a studio, not by a tool for one of the account's projects. */+ standalone?: boolean;}declare global {@@ -34,7 +38,7 @@ export const withRunStamp = <T,>(stamp: RunStamp, fn: () => T): T => store().runexport const runStamp = (): RunStamp | undefined => store().getStore();/** The server-only fields of a request. */-export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs"] as const;+export const STAMP_FIELDS = ["place", "hold", "charge", "checkOutputs", "waitMs", "standalone"] as const;/** A request with the current stamp's fields, and none of a stored request's own. */export function stamped(req: GenerationRequest): GenerationRequest {@@ -49,10 +53,11 @@ export function stamped(req: GenerationRequest): GenerationRequest {...(s.charge && { charge: s.charge }),...(s.checkOutputs && { checkOutputs: true }),...(s.waitMs && s.waitMs > 0 && { waitMs: s.waitMs }),+ ...(s.standalone && { standalone: true }),};}/** A stored request's stamp, to run a later step of it (advanceDependents, polls) as it was decided. */export function stampOf(req: Pick<GenerationRequest, (typeof STAMP_FIELDS)[number]>): RunStamp {- return { ...(req.place === "pool" && { place: "pool" as const }), ...(req.hold && { hold: req.hold }), ...(req.charge && { charge: req.charge }), ...(req.checkOutputs && { checkOutputs: true }), ...(req.waitMs && { waitMs: req.waitMs }) };+ return { ...(req.place === "pool" && { place: "pool" as const }), ...(req.hold && { hold: req.hold }), ...(req.charge && { charge: req.charge }), ...(req.checkOutputs && { checkOutputs: true }), ...(req.waitMs && { waitMs: req.waitMs }), ...(req.standalone && { standalone: true }) };}diff --git a/tests/account-cinema.test.ts b/tests/account-cinema.test.tsindex 9ab835ae..4611de0e 100644--- a/tests/account-cinema.test.ts+++ b/tests/account-cinema.test.ts@@ -51,7 +51,10 @@ const gpuRoute = await import("@/app/api/account/gpu/route");const { proxy } = await import("@/proxy");const access = await import("@/lib/guest-access");const cinema = await import("@/server/cinema");-const { cancelGeneration, getGeneration } = await import("@/server/generations");+const { cancelGeneration, cloudTwin, getGeneration, PROJECT_RUN, SELF_HEAL } = await import("@/server/generations");+const generationsRoute = await import("@/app/api/generations/route");+const { removeAccountKey, saveAccountKey } = await import("@/server/account-keys");+const { onCloudKey } = await import("@/lib/before-run");const { db } = await import("@/server/db");const { resetRates } = await import("@/server/rate");const { clearAccountLoras } = await import("@/server/account-loras");@@ -496,6 +499,57 @@ describe("an account's takes run on its own ComfyUI", () => {});});+describe("a take that waits for the account's GPU stays in its project", () => {+ it("a take of one step doesn't offer Run with your key, and a press on it anyway is refused in plain words", { timeout: 30_000 }, async () => {+ const project = await makeProject("a", "Waiting takes");+ // Its fal.ai key runs the take's cloud version; its GPU is starting up (its last check said so).+ saveAccountKey(a, "fal", "acct-fal-cinema");+ SELF_HEAL.scale = 0.01;+ fake.opts.answer = (_m, p) => (p === "/system_stats" ? { status: 502, body: "<html><title>Bad gateway</title></html>", contentType: "text/html" } : undefined);+ expect((await gpuRoute.PUT(json("/api/account/gpu?test=1", "PUT", { saved: true }, "a"))).status).toBe(422);+ const made: string[] = [];+ try {+ const r = await take(project, STILL, "a");+ expect(r.status, await r.clone().text()).toBe(201);+ const items = ((await r.json()) as { items: { id: string }[] }).items;+ // One step: nothing waits for it, and it waits for nothing.+ expect(items).toHaveLength(1);+ const id = items[0].id;+ made.push(id);+ for (let i = 0; i < 500 && !getGeneration(id)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ const g = getGeneration(id)!;+ expect(g.waiting, g.error ?? g.message ?? "").toBeTruthy();+ const twin = cloudTwin(g.request, a);+ expect(twin).toBeTruthy();+ expect(g.waiting!.actions.map((x) => x.kind)).not.toContain("run-with-key");+ // The same run made on its own in the studio offers it.+ const own = await generationsRoute.POST(json("/api/generations", "POST", g.request, "a"));+ expect(own.status, await own.clone().text()).toBe(201);+ const alone = ((await own.json()) as { items: { id: string }[] }).items[0].id;+ made.push(alone);+ for (let i = 0; i < 500 && !getGeneration(alone)?.waiting; i++) await new Promise((r) => setTimeout(r, 10));+ expect(getGeneration(alone)!.waiting!.actions.map((x) => x.kind)).toContain("run-with-key");+ // Pressed on the take anyway (a tile drawn before): refused in plain words, and nothing is made or stopped.+ const runs = db().prepare("SELECT COUNT(*) FROM generations").pluck().get();+ const press = await generationsRoute.POST(json("/api/generations", "POST", { ...onCloudKey(g.request, twin!), replaces: id }, "a"));+ expect(press.status).toBe(409);+ expect(await press.json()).toEqual({ error: PROJECT_RUN, code: "project-run" });+ expect(PROJECT_RUN).not.toMatch(/\b[1-5]\d\d\b|HTTP|127\.0\.0\.1/);+ expect(db().prepare("SELECT COUNT(*) FROM generations").pluck().get()).toBe(runs);+ expect(getGeneration(id)?.status).toBe("queued");+ // The take is still the project's.+ expect(runAsTenant({ kind: "account", id: a }, () => cinema.listItems(project)).map((x) => x.id)).toContain(id);+ } finally {+ fake.opts.answer = undefined;+ SELF_HEAL.scale = 1;+ removeAccountKey(a, "fal");+ for (const id of made) await cancelGeneration(id);+ // Its GPU is back, as its next check says.+ expect((await gpuRoute.PUT(json("/api/account/gpu?test=1", "PUT", { saved: true }, "a"))).status).toBe(200);+ }+ });+});+describe("a ready film and the account's deletion", () => {it("an account makes Cinema's ready film as its own project; the owner's list never shows it", async () => {const r = await startersRoute.POST(json("/api/starters/cinema.desert-couture", "POST", { engine: "open" }, "b"), params({ id: "cinema.desert-couture" }));diff --git a/tests/own-gpu-graceful.test.ts b/tests/own-gpu-graceful.test.tsindex 381b0189..d82c4417 100644--- a/tests/own-gpu-graceful.test.ts+++ b/tests/own-gpu-graceful.test.ts@@ -547,6 +547,26 @@ describe("what the owner learns of an account's failed run on its own GPU", () =}});+ it("a longer run broken at its first step: the next step writes the owner's line, the steps after it none", async () => {+ const warn = vi.spyOn(console, "warn");+ try {+ fake.opts.answer = (_m, p) => (p === "/upload/image" ? { status: 401, body: "" } : undefined);+ const pic = await uploadPng();+ const first = await startRun();+ const second = laterStep(first, pic);+ const third = laterStep(second, pic);+ expect((await settle(first))?.status).toBe("failed");+ for (const id of [second, third]) expect((await settle(id))?.error).toBe("An earlier step didn't finish");+ const lines = (id: string) => warn.mock.calls.map((c) => String(c[0])).filter((l) => l.includes('"evt":"own-run"') && l.includes(`"run":"${id}"`));+ expect(lines(first)).toHaveLength(1);+ expect(lines(second)).toHaveLength(1);+ expect(JSON.parse(lines(second)[0])).toMatchObject({ run: second, stage: "chain", cause: "earlier-step", outcome: "failed" });+ expect(lines(third)).toHaveLength(0);+ } finally {+ warn.mockRestore();+ }+ });+it("keeps at most 2 KB of what the GPU said, counted in bytes, never cutting a character in two", async () => {const { keptText } = await import("@/server/run-events");const wide = "é".repeat(3000);@@ -862,6 +882,39 @@ describe("a step of a longer run that waited, taken over after a restart", () =>fake.opts.output = undefined;}});++ it("one cut off in the middle of its first send (it never waited) is never sent again either", async () => {+ try {+ const { first, pic } = await firstStepDone();+ // Its first try: marked as being sent just before its job goes, with no wait of its own.+ fake.log.length = 0;+ fake.opts.hold = (m, p) => m === "POST" && p === "/prompt";+ const sending = laterStep(first, pic);+ for (let i = 0; i < 1000 && !fake.log.some((e) => e.path === "/prompt"); i++) {+ await globalThis.__fuobeRunner?.tick();+ await new Promise((r) => setTimeout(r, 10));+ }+ const meta = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(sending))) as { sending?: unknown; heal?: unknown };+ expect(typeof meta.sending).toBe("number");+ expect(meta.heal).toBeUndefined();+ await cancelGeneration(sending);+ fake.opts.hold = undefined;+ fake.dropHeld();+ // The next instance finds such a step once the cut-off one's hold has run out: it fails, and nothing is sent.+ fake.log.length = 0;+ const second = laterStep(first, pic);+ setPending(second, { sending: Date.now() - 1000, lease: { by: "gone", until: Date.now() - 1 } });+ const g = await settle(second);+ expect(g?.status).toBe("failed");+ expect(g?.error).toBe("This run was interrupted while it was being sent. Press Retry.");+ expect(fake.log.filter((e) => e.path === "/prompt" || e.path === "/upload/image")).toHaveLength(0);+ expect(ownRunNote(second)).toMatchObject({ cause: "interrupted-sending", stage: "chain" });+ } finally {+ fake.opts.hold = undefined;+ fake.dropHeld();+ fake.opts.output = undefined;+ }+ });});// Last: the server's own state is replaced here (a new instance of the runner's module on the same database).diff --git a/tests/own-keys-graceful.test.ts b/tests/own-keys-graceful.test.tsindex d62bbe76..1d9aba31 100644--- a/tests/own-keys-graceful.test.ts+++ b/tests/own-keys-graceful.test.ts@@ -235,6 +235,35 @@ describe("an account's run on its own key waits out a busy or down provider", ()for (const id of [g.id, later.id]) await gens.cancelGeneration(id);});+ it("a job of a batch whose other job a later step waits for doesn't offer it either, and a press on it is refused", async () => {+ gens.SELF_HEAL.scale = 0.1;+ // On Replicate, Nano Banana Pro makes one picture a job: two outputs, two jobs of one batch.+ rep.script = (r) => (isSubmit(r) ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "1" } } : null);+ const post = async (body: Record<string, unknown>) => {+ const text = JSON.stringify({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "a quiet harbour at dawn", ...body });+ return generationsRoute.POST(new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: cookies.A, host: "localhost:3000", "content-type": "application/json", "content-length": String(text.length) }, body: text }));+ };+ const made = await post({ prefer: "replicate", params: { numOutputs: 2 } });+ expect(made.status, await made.clone().text()).toBe(201);+ const jobs = ((await made.json()) as { items: { id: string; provider: string }[] }).items;+ expect(jobs.map((j) => j.provider)).toEqual(["replicate", "replicate"]);+ const [one, two] = jobs.map((j) => j.id);+ for (let i = 0; i < 500 && !(gens.getGeneration(one)?.waiting && gens.getGeneration(two)?.waiting); i++) await new Promise((r) => setTimeout(r, 10));+ const offered = (id: string) => (gens.getGeneration(id)?.waiting?.actions ?? []).map((a) => a.kind);+ // On their own, both jobs offer the other key.+ expect(offered(two)).toContain("run-with-key");+ // A later step waits for the batch's first job only (as a pipeline's next step waits for its step's first job).+ const [later] = gens.asAccount(A, () => gens.createGenerations({ feature: "image", modelId: "nano-banana-pro", engine: "cloud", prompt: "the same harbour at night" }, { dependsOn: one }));+ // The press would stop the whole batch, the job the later step waits for with it: neither tile offers it.+ expect(offered(one)).not.toContain("run-with-key");+ expect(offered(two)).not.toContain("run-with-key");+ const r = await post({ replaces: two });+ expect(r.status).toBe(409);+ expect(await r.json()).toEqual({ error: gens.CHAINED_RUN, code: "chained-run" });+ for (const id of [one, two, later.id]) expect(gens.getGeneration(id)?.status).toBe("queued");+ for (const id of [one, two, later.id]) await gens.cancelGeneration(id);+ });+it("a 502 at submit may have started a job already: never sent twice", async () => {fal.script = (r) => (isSubmit(r) ? { status: 502, body: "<!DOCTYPE html><html><head><title>502 Bad gateway</title></head></html>" } : null);const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });@@ -261,6 +290,35 @@ describe("Not billed", () => {stopped("fal.ai is having trouble right now. Press Retry in a few minutes.", { heal: { since: 1, deadline: 2, firstSeen: {}, tries: 1, next: 0, index: 0, sending: Date.now() } });expect(gens.getGeneration(g.id)!.notBilled).toBeUndefined();});++ it("is said of a run fal.ai turned down at its next try after a wait (a refused key): it never had the job", async () => {+ let tries = 0;+ fal.script = (r) =>+ isSubmit(r) ? (tries++ === 0 ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "1" } } : { status: 401, body: { detail: "Invalid credentials" } }) : null;+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(done.error).toBe("fal.ai didn't accept your key. Check it in Settings → Your keys.");+ expect(tries).toBe(2);+ expect(done.notBilled).toBe(true);+ const meta = JSON.parse(String(db().prepare("SELECT external_meta_json FROM generations WHERE id = ?").pluck().get(g.id))) as { heal?: { sending?: number } };+ expect(meta.heal?.sending).toBeUndefined();+ });++ it("isn't said when the next try after a wait may have reached fal.ai (a 502)", async () => {+ let tries = 0;+ fal.script = (r) =>+ isSubmit(r)+ ? tries++ === 0+ ? { status: 429, body: { detail: "Too many requests" }, headers: { "Retry-After": "1" } }+ : { status: 502, body: "<!DOCTYPE html><html><head><title>502 Bad gateway</title></head></html>" }+ : null;+ const g = await run(cookies.A, { modelId: "nano-banana-pro", engine: "cloud" });+ const done = await settle(g.id);+ expect(done.status).toBe("failed");+ expect(tries).toBe(2);+ expect(done.notBilled).toBeUndefined();+ });});describe("what waiting can't fix fails at once, in plain words, with what helps", () => {