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
Admin: run a person's run again with changes
Adarsh09e4d478c08e
diff --git a/docs/admin-api.md b/docs/admin-api.mdindex d42aa5e3..2e3a8a43 100644--- a/docs/admin-api.md+++ b/docs/admin-api.md@@ -49,7 +49,7 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz| `workers:tokens` | `POST /api/admin/workers`, and `PATCH /api/admin/workers/{id}` with `rotate`: both answer with a worker token. A worker receives accounts' queued jobs with their input files and sends back the results, so give this scope only to a tool you'd trust with those || `queue:read` | `GET /api/admin/queue`, `GET /api/admin/queue/settings`, `GET /api/admin/queue/overrides` || `queue:write` | `PATCH /api/admin/queue/settings`: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget (`pausedBudgetS`: how long a run that has started may spend back in line) |-| `queue:control` | `POST /api/admin/queue/mode`, `POST /api/admin/queue/overrides`, `DELETE /api/admin/queue/overrides/{id}`, `POST /api/admin/queue/cancel`: who the GPUs serve first, runs and people sent first or held, and cancelling a run ([gpu-workers.md](gpu-workers.md#who-goes-first)) |+| `queue:control` | `POST /api/admin/queue/mode`, `POST /api/admin/queue/overrides`, `DELETE /api/admin/queue/overrides/{id}`, `POST /api/admin/queue/cancel`, `POST /api/admin/generations/{id}/again`: who the GPUs serve first, runs and people sent first or held, cancelling a run ([gpu-workers.md](gpu-workers.md#who-goes-first)), and running a person's run again for them || `site:read` | `GET /api/admin/site/uploads`, `GET /api/admin/site/runs` || `site:write` | `PATCH /api/admin/site/uploads`: the upload switches; `PATCH /api/admin/site/runs`: what people read when a run fails || `audit:read` | `GET /api/admin/audit` |@@ -110,6 +110,7 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control| `GET /api/admin/generations` | `account` (one account), else `whose` (`people`: accounts' and guests' runs, the default; `ours`: the owner's own; `everyone`); `source` (the owner's runs only: `hands-on`, or `batch` for any automated run: `batch`, `drill`, `example`, `test`, `api`); `where` (`pool`: this install's GPUs, the owner's runs on its ComfyUI too; `provider`: a cloud provider; `own`: an account's own GPU); `status` (`finished` or `done`, `failed`, `canceled`, `waiting`, `started`, and `running` for waiting and started); `kind` (`image`, `video`, `audio`, `model3d`, `text`); `model` (letters of the model id); `from` and `to` (`yyyy-mm-dd` in UTC, both days included); `q` (words of the prompt, or a run id); `ids` (a comma list of up to 100 run ids: those runs, whoever's they are); `before` (the last page's `next`); `limit` (1 to 100, default 30) | `{ items, next }`; `next` is null on the last page. Each run has `whose`: `account`, `guest` or `owner`. Each output has a `state`: `shown`, `held` (hidden, or waiting for its check) or `removed` (its file is gone). A failed run on this install's GPUs (and the owner's own failed run) also has `detail`: the technical reason, which the account never sees. `account` is `{ id, email }` (`email` null: a deleted account), `{ id, emailHidden: true }` without `accounts:read`, or `null` for the owner's own run, which has `source` too (`hands-on` from the site; `batch`, `drill`, `example`, `test` as its script said; `api` for a run sent with an API token that said none) and `sourceName` when its script gave one || `GET /api/admin/generations/{id}` | needs `runs:read` and `outputs:view` | One run in full, an account's, a guest's or the owner's own: `{ run, stored, fix, trouble, where, model, preset, studio, prompt, negativePrompt, asked, settings, inputs, batch, near, chain, sent, timing, jobs, workerLog, money, madeBy, surface, providerId, progress, checks }`. `stored.detail` is the technical reason for the owner; `comfyReason`, when there is one, is ComfyUI's own reason in one short line (a node that isn't installed, a model file not in its list, an error in a node), and each of `jobs` has it as `comfyWhy`. A job on one of this site's workers may have `nodes`: its slowest nodes, slowest first, each `{ node, type, ms, beforeStepsMs, steps }` (`beforeStepsMs` and `steps` for a node with steps; [gpu-workers.md](gpu-workers.md)). `inputs` lists each input file by slot, with its `state` (`kept` with its `url`, `removed`, `example`, `inline`, `link`). `chain` is `{ before, after }`: the steps it waits for and the steps that wait for it. Keys, tokens and GPU addresses are never part of it. 404 for an unknown run || `DELETE /api/admin/generations/{id}` | | 204; 404 for an unknown run or the owner's own |+| `POST /api/admin/generations/{id}/again` | `{ changes?: { params?, prompt? }, notice? }`: `params` are settings merged over the run's own (`{ "duration": 5 }`), `prompt` new words, `notice` a sentence of up to 300 characters | 201 `{ original, account, place, ids, items }`: a new run in the same account, as if the person pressed Run again: the same feature, model, operation and files, with the changes, on the place the run went (`pool`: this install's GPUs; `own`: the account's own GPU or key). It is free: nothing is set aside for it and it counts against none of the limits on runs. `notice` shows on the new run's result. Each of `items` is `{ id, status, modelId, op, params, notice }`. The changes meet the checks a run's request meets: 400 with the reason (a setting the request doesn't take, a length the model doesn't make, a file that is gone). 404 for an unknown run or the owner's own; 409 for a step of a longer run, an account switched off, or a place that can't take the run now || `POST /api/admin/outputs/hide` | `{ assetIds?, generationIds? }` (up to 500 each) | `{ hidden }` || `POST /api/admin/outputs/unhide` | the same | `{ shown }` || `POST /api/admin/outputs/remove` | the same, and `evidence?: true` to keep the files in a locked folder | `{ removed }` |@@ -140,7 +141,7 @@ A log row is `{ id, at, actor: "owner" | "token" | "system", token: { id, name }`token.name` is the name the token had at the time. Actions: `account.disable`, `account.enable`, `account.signout`,`account.delete`, `run.delete`, `outputs.hide`, `outputs.unhide`, `outputs.remove`, `worker.add`, `worker.change`,`worker.rotate`, `worker.revoke`, `worker.revoke_all` (Sign everyone out with every API token), `queue.settings` (with-the values before and after), `queue.mode`, `queue.override`, `queue.override.end`, `queue.cancel`, `queue.mode.end`+the values before and after), `queue.mode`, `queue.override`, `queue.override.end`, `queue.cancel`, `run.again` (the run as its target, with the account, the new run's `ids`, `place`, the `changed` settings and whether a `notice` was given), `queue.mode.end`(actor `system` when a mode, a hold or a boost ended by itself), `site.uploads` (the upload switches, with the values before and after), `site.runs` (what people read when a run fails, with the values before and after), `token.create`, `token.revoke`,`token.revoke_all`, `settings.comfy_where` (where ComfyUI runs, with the values before and after), `settings.run_failure_detail` (Settings → Failed runs, changed in the owner's browser, with the values before and after); a token's reads`accounts.list`, `accounts.csv`, `account.read`, `runs.list`, `reports.list`, `audit.read` (one row per token and actiondiff --git a/src/app/api/admin/generations/[id]/again/route.ts b/src/app/api/admin/generations/[id]/again/route.tsnew file mode 100644index 00000000..a247ea43--- /dev/null+++ b/src/app/api/admin/generations/[id]/again/route.ts@@ -0,0 +1,55 @@+import { adminAccess, audit } from "@/server/admin-tokens";+import { readAgainBody, runAgainFor, RunAgainError } from "@/server/run-again";++const NO_STORE = { "Cache-Control": "no-store" };++/**+ * Run an account's run again for them (owner only, or an admin token with queue:control): `{ changes?: { params?,+ * prompt? }, notice? }`. The new run is the account's own, made as its Run would make it (the same feature, model,+ * operation and files, with the changes), on the place the run went (this install's GPUs, or its own GPU or key), and+ * free. `notice` is said on its result. The changes meet the checks a run's request meets: 400 with the reason. 404 for+ * no such run or the owner's own; 409 for a step of a longer run, an account switched off, or a place that can't take+ * it now. Each call is in the admin log with the run and the new run's ids.+ */+export async function POST(request: Request, ctx: RouteContext<"/api/admin/generations/[id]/again">) {+ const access = adminAccess(request, "queue:control", "Only the studio's owner runs a person's run again");+ if (access instanceof Response) return access;+ const { id } = await ctx.params;+ if (!/^[\w-]{1,80}$/.test(id)) {+ audit(access.actor, "run.again", null, null, 404);+ return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });+ }+ const text = await request.text().catch(() => "");+ let body: unknown = null;+ try {+ body = text.trim() ? JSON.parse(text) : null;+ } catch {+ audit(access.actor, "run.again", id, null, 400);+ return Response.json({ error: "Send JSON: { changes?: { params?, prompt? }, notice? }" }, { status: 400, headers: NO_STORE });+ }+ try {+ const { changes, notice } = readAgainBody(body);+ const made = await runAgainFor(id, changes, notice);+ const ids = made.items.map((g) => g.id);+ const changed = [...Object.keys(changes.params ?? {}).map((k) => `params.${k}`), ...(changes.prompt !== undefined ? ["prompt"] : [])];+ audit(access.actor, "run.again", id, { account: made.account, ids, place: made.place, changed, ...(changes.params && { params: loggable(changes.params) }), notice: !!notice }, 201);+ return Response.json(+ { original: id, account: made.account, place: made.place, ids, items: made.items.map((g) => ({ id: g.id, status: g.status, modelId: g.modelId, op: g.op, params: g.request.params ?? {}, notice: g.request.notice ?? null })) },+ { status: 201, headers: NO_STORE },+ );+ } catch (e) {+ const status = e instanceof RunAgainError ? e.status : 500;+ const error = e instanceof RunAgainError ? e.message : "Couldn't make the run";+ audit(access.actor, "run.again", id, { error: error.slice(0, 200) }, status);+ return Response.json({ error }, { status, headers: NO_STORE });+ }+}++/** The changed settings for the log: numbers, switches and short words only (never a prompt or a file). */+function loggable(params: Record<string, unknown>): Record<string, unknown> {+ const out: Record<string, unknown> = {};+ for (const [k, v] of Object.entries(params)) {+ if (typeof v === "number" || typeof v === "boolean" || (typeof v === "string" && v.length <= 40 && !v.includes("/"))) out[k] = v;+ }+ return out;+}diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.tsindex 2c1871db..a74a1c57 100644--- a/src/server/admin-tokens.ts+++ b/src/server/admin-tokens.ts@@ -59,7 +59,7 @@ export const SCOPE_LABELS: Record<Scope, string> = {"workers:tokens": "Add workers and give them new tokens (a worker runs accounts' queued jobs, with their files)","queue:read": "See the queue and its settings","queue:write": "Change the queue's settings: the run ceiling, the owner's wait limit, fair share, the pick allowance and the paused budget",- "queue:control": "Choose who the GPUs serve first: the mode (people first, people only, our work first, balanced), a run next, pinned or held, a person's runs first or held, and cancel a waiting run",+ "queue:control": "Choose who the GPUs serve first: the mode (people first, people only, our work first, balanced), a run next, pinned or held, a person's runs first or held, cancel a waiting run, and run a person's run again for them","site:read": "See the site's switches: the upload fitting steps","site:write": "Switch the upload fitting steps off and on: convert, offer a part, offer a crop","audit:read": "See the admin log",diff --git a/src/server/run-again.ts b/src/server/run-again.tsnew file mode 100644index 00000000..687e6519--- /dev/null+++ b/src/server/run-again.ts@@ -0,0 +1,172 @@+import "server-only";+import { getModel } from "@/lib/catalog";+import { lengthRange } from "@/lib/catalog/clip-lengths";+import type { Generation, GenerationRequest } from "@/lib/catalog/types";+import { ACCOUNT_LIMITS, accountTotalBytes, accountUsage, diskHasRoom, filesFullMessage } from "./account-files";+import { accountInputProblem } from "./account-inputs";+import { accountById } from "./auth";+import { db } from "./db";+import { accountRun, AccountRunError, asAccount, captureRun, createGenerations, getGeneration, previewGeneration, stepsOf } from "./generations";+import { poolReady, poolRunsProvider, runOnPool } from "./hosted";+import { GenerationRequestSchema } from "./request-schema";+import { stampOf, withoutStamp, withRunStamp, type RunStamp } from "./run-stamp";++/**+ * Run an account's run again for them (the admin API's POST /api/admin/generations/{id}/again): the same feature,+ * model, operation, words and files, with the changes asked for, in the same account and on the same place it ran+ * (this install's GPUs, or the account's own GPU or key). It is made as that account's own Run would make it, and it+ * meets the same checks of the request (the request schema, the model's lengths, the account's files), but it is free:+ * nothing is set aside for it and it counts against none of the limits on runs. `notice` is said on the new run's+ * result, as a run's notice is.+ */++/** What may change: settings (merged over the run's own) and the words. */+export interface RunChanges {+ params?: Record<string, unknown>;+ prompt?: string;+}++export const NOTICE_MAX = 300;++export class RunAgainError extends Error {+ constructor(+ readonly status: number,+ message: string,+ ) {+ super(message);+ }+}++const isRecord = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);++/** The body as sent, checked for its shape: `{ changes?: { params?, prompt? }, notice? }`. */+export function readAgainBody(body: unknown): { changes: RunChanges; notice?: string } {+ if (body === null || body === undefined) return { changes: {} };+ if (!isRecord(body)) throw new RunAgainError(400, "Send { changes?: { params?, prompt? }, notice? }");+ const extraKeys = Object.keys(body).filter((k) => k !== "changes" && k !== "notice");+ if (extraKeys.length) throw new RunAgainError(400, `Unknown field: ${extraKeys[0]}`);+ const changes: RunChanges = {};+ if (body.changes !== undefined) {+ if (!isRecord(body.changes)) throw new RunAgainError(400, "changes is { params?, prompt? }");+ const extra = Object.keys(body.changes).filter((k) => k !== "params" && k !== "prompt");+ if (extra.length) throw new RunAgainError(400, `Unknown change: ${extra[0]}`);+ if (body.changes.params !== undefined) {+ if (!isRecord(body.changes.params)) throw new RunAgainError(400, "changes.params is an object of settings");+ changes.params = body.changes.params;+ }+ if (body.changes.prompt !== undefined) {+ if (typeof body.changes.prompt !== "string" || !body.changes.prompt.trim()) throw new RunAgainError(400, "changes.prompt is the new words");+ changes.prompt = body.changes.prompt;+ }+ }+ let notice: string | undefined;+ if (body.notice !== undefined && body.notice !== null) {+ if (typeof body.notice !== "string") throw new RunAgainError(400, "notice is a sentence");+ const n = body.notice.replace(/\s+/g, " ").trim();+ if (n.length > NOTICE_MAX) throw new RunAgainError(400, `notice is at most ${NOTICE_MAX} characters`);+ if (n) notice = n;+ }+ return { changes, notice };+}++/** A length the model doesn't make, in words, or null. */+export function durationProblem(modelId: string, duration: unknown): string | null {+ if (duration === undefined) return null;+ const model = getModel(modelId);+ if (typeof duration !== "number" || !Number.isFinite(duration) || duration <= 0) return "duration is a number of seconds";+ if (!model) return null;+ const range = lengthRange(model);+ if (range) {+ return Number.isInteger(duration) && duration >= range[0] && duration <= range[1] ? null : `${model.name} makes clips of ${range[0]} to ${range[1]} seconds, in whole seconds`;+ }+ const list = model.options.durations;+ if (list && list.length && !list.includes(duration)) return `${model.name} makes clips of ${list.join(", ")} seconds`;+ return null;+}++/** The request the new run sends: the run's own as a client would send it again, with the changes. */+export function againRequest(stored: GenerationRequest, changes: RunChanges): GenerationRequest {+ const base = withoutStamp(stored) as GenerationRequest & Record<string, unknown>;+ const params = changes.params+ ? {+ ...base.params,+ ...changes.params,+ ...(isRecord(changes.params.extra) && { extra: { ...base.params?.extra, ...changes.params.extra } }),+ }+ : base.params;+ const body = { ...base, ...(params && { params }), ...(changes.prompt !== undefined && { prompt: changes.prompt }) };+ const parsed = GenerationRequestSchema.safeParse(body);+ if (!parsed.success) throw new RunAgainError(400, parsed.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "));+ const req = parsed.data as GenerationRequest;+ // A setting the request doesn't take is said, never dropped without a word.+ for (const k of Object.keys(changes.params ?? {})) {+ if (!(k in (req.params ?? {}))) throw new RunAgainError(400, `Unknown setting: ${k}`);+ }+ const problem = durationProblem(req.modelId, req.params?.duration);+ if (changes.params && "duration" in changes.params && problem) throw new RunAgainError(400, problem);+ return req;+}++export interface RunAgainResult {+ account: string;+ place: "pool" | "own";+ items: Generation[];+}++/** Make the run again for its account. Throws RunAgainError with the status to answer. */+export async function runAgainFor(id: string, changes: RunChanges, notice: string | undefined): Promise<RunAgainResult> {+ const row = db().prepare("SELECT request_json, depends_on FROM generations WHERE id = ?").get(id) as { request_json: string; depends_on: string | null } | undefined;+ if (!row || !getGeneration(id)) throw new RunAgainError(404, "No such run");+ const stored = JSON.parse(row.request_json) as GenerationRequest;+ const accountId = stored.account;+ if (!accountId) throw new RunAgainError(404, "That run is yours, not an account's. Run it again in the studio.");+ if (row.depends_on) throw new RunAgainError(409, "That run is a step of a longer run: run the whole run again instead.");+ const account = accountById(accountId);+ if (!account) throw new RunAgainError(404, "That run's account is gone");+ if (account.disabled) throw new RunAgainError(409, "That account is switched off");+ if (!diskHasRoom()) throw new RunAgainError(503, "The server is low on space: free some first");+ if (accountUsage(accountId).total >= accountTotalBytes(accountId)) throw new RunAgainError(413, filesFullMessage(accountId));++ let req = againRequest(stored, changes);+ if ((req.params?.numOutputs ?? 1) > ACCOUNT_LIMITS.outputsPerRun) req = { ...req, params: { ...req.params, numOutputs: ACCOUNT_LIMITS.outputsPerRun } };+ const files = accountInputProblem(req, accountId);+ if (files) throw new RunAgainError(400, files.error);+ req = { ...req, account: accountId, ...(notice && { notice }) };++ // What the first run kept of its place in line (its class, its moderation check), with no hold or charge: free, and+ // no limit on how long it waits to start.+ const was = stampOf(stored);+ const kept: RunStamp = { standalone: true, ...(was.checkOutputs && { checkOutputs: true }), ...(was.class && { class: was.class }) };+ const make = () => createGenerations(req);++ try {+ if (was.place === "pool") {+ if (!poolReady()) throw new RunAgainError(409, "This install's GPUs aren't taking runs right now");+ const planned = runOnPool(accountId, () => previewGeneration(req));+ if (planned.route.provider !== "comfyui") throw new RunAgainError(409, "With these changes the run can't go to this install's GPUs");+ const stamp: RunStamp = { ...kept, place: "pool", ...(was.light && { light: true }), waitMs: 0 };+ const items = runOnPool(accountId, () =>+ withRunStamp(stamp, () => {+ // Made in one transaction and sent once kept: a step the GPUs here can't run keeps nothing.+ const run = db().transaction(() => {+ const r = captureRun(make);+ if (stepsOf(r.ids).some((s) => !poolRunsProvider(s.provider))) throw new RunAgainError(409, "With these changes the run can't go to this install's GPUs");+ return r;+ })();+ run.start();+ return run.value;+ }),+ );+ return { account: accountId, place: "pool", items };+ }+ const planned = asAccount(accountId, () => previewGeneration(req));+ const own = accountRun(accountId, planned.route.provider, "submit");+ if ("error" in own) throw new RunAgainError(409, own.error);+ const items = own.run(() => withRunStamp(kept, make));+ return { account: accountId, place: "own", items };+ } catch (e) {+ if (e instanceof RunAgainError) throw e;+ if (e instanceof AccountRunError) throw new RunAgainError(409, e.refusal.error);+ throw new RunAgainError(400, (e as Error).message);+ }+}diff --git a/tests/admin-run-again.test.ts b/tests/admin-run-again.test.tsnew file mode 100644index 00000000..251a0fb5--- /dev/null+++ b/tests/admin-run-again.test.ts@@ -0,0 +1,205 @@+import http from "node:http";+import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";+import { listenOnFreePort, startFakeBilling, type FakeBilling } from "./helpers/fake-billing";+import { startFakeComfy, type FakeComfy } from "./helpers/fake-comfy-runner";+import { tempDir } from "./helpers/temp-dir";++// POST /api/admin/generations/{id}/again: an account's run made again for it, with changes and a notice, on the place+// it ran, free. A stand-in billing service and a stand-in ComfyUI as this install's GPUs.+const dir = tempDir("fuobe-run-again-");+process.env.FUOBE_DATA_DIR = dir;+process.env.FUOBE_PUBLIC_SIGNUP = "1";+delete process.env.FUOBE_PASSWORD;+delete process.env.FUOBE_ALLOW_PRIVATE_URLS;+delete process.env.FUOBE_MODERATION_URL;+globalThis.__fuobeTestDiskFree = 1e13;++const probe = http.createServer();+const comfyPort = await listenOnFreePort(probe);+await new Promise<void>((r) => probe.close(() => r()));+const comfy: FakeComfy = await startFakeComfy({ output: "image", delayMs: 0 }, comfyPort);+process.env.COMFYUI_URL = comfy.url;++const auth = await import("@/server/auth");+const generationsRoute = await import("@/app/api/generations/route");+const againRoute = await import("@/app/api/admin/generations/[id]/again/route");+const { db } = await import("@/server/db");+const { resetRates } = await import("@/server/rate");+const billing = await import("@/server/billing");+const tokens = await import("@/server/admin-tokens");++let fake: FakeBilling;+let a = "";+let cookie = "";+let owner = "";+let withGpu = "";+let gpuCookie = "";+beforeAll(async () => {+ fake = await startFakeBilling();+ globalThis.__fuobeTestGpuPort = comfy.port;+ auth.setPassword("install password");+ owner = `${auth.SESSION_COOKIE}=${auth.createSession().value}`;+ a = auth.createAccount("[email protected]", "long enough").id;+ cookie = `${auth.SESSION_COOKIE}=${auth.createSession(a).value}`;+ withGpu = auth.createAccount("[email protected]", "long enough").id;+ auth.setAccountGpu(withGpu, { mode: "link", url: comfy.url } as never);+ gpuCookie = `${auth.SESSION_COOKIE}=${auth.createSession(withGpu).value}`;+});+afterAll(async () => {+ globalThis.__fuobeTestGpuPort = undefined;+ globalThis.__fuobeTestDiskFree = undefined;+ delete process.env.FUOBE_HOSTED_RUNS;+ delete process.env.FUOBE_BILLING_URL;+ delete process.env.FUOBE_BILLING_TOKEN;+ delete process.env.FUOBE_PUBLIC_SIGNUP;+ await fake.close();+ await comfy.close();+});++beforeEach(() => {+ resetRates();+ billing.resetBillingCache();+ fake.calls.length = 0;+ fake.down = false;+ fake.refuse = null;+ fake.price = { amount: 7, version: "v7" };+ process.env.FUOBE_HOSTED_RUNS = "1";+ process.env.FUOBE_BILLING_URL = fake.url;+ process.env.FUOBE_BILLING_TOKEN = "test-billing-token";+ db().prepare("UPDATE generations SET status = 'canceled' WHERE status IN ('queued', 'running')").run();+});++const post = (body: unknown, c = cookie) => {+ const text = JSON.stringify(body);+ return generationsRoute.POST(+ new Request("http://localhost:3000/api/generations", { method: "POST", headers: { cookie: c, host: "localhost:3000", "content-type": "application/json", "content-length": String(Buffer.byteLength(text)) }, body: text }),+ );+};+const again = (id: string, body: unknown, headers: Record<string, string> = { cookie: owner }) =>+ againRoute.POST(+ new Request(`http://localhost:3000/api/admin/generations/${id}/again`, { method: "POST", headers: { host: "localhost:3000", "content-type": "application/json", ...headers }, body: body === undefined ? "" : JSON.stringify(body) }),+ { params: Promise.resolve({ id }) } as never,+ );+const stored = (id: string) => JSON.parse((db().prepare("SELECT request_json FROM generations WHERE id = ?").get(id) as { request_json: string }).request_json) as Record<string, unknown> & { params?: Record<string, unknown> };+const admissions = () => (db().prepare("SELECT COUNT(*) AS n FROM pool_admissions").get() as { n: number }).n;+const lastAudit = () => db().prepare("SELECT action, target, detail_json, status FROM admin_audit ORDER BY id DESC LIMIT 1").get() as { action: string; target: string | null; detail_json: string | null; status: number };+const NOTICE = "We had an issue making the 15-second version, so here is a 5-second version of your video.";++let seq = 0;+/** A run as the runner stores it (an account's on this install's GPUs unless said). */+function stash(request: Record<string, unknown>, o: { dependsOn?: string } = {}): string {+ const id = `stash-${++seq}`;+ const now = Date.now();+ db()+ .prepare(+ "INSERT INTO generations (id, feature, model_id, engine, provider, op, kind, status, request_json, outputs_json, created_at, updated_at, depends_on) VALUES (?, 'video', ?, 'open', 'comfyui', ?, 'video', 'canceled', ?, '[]', ?, ?, ?)",+ )+ .run(id, request.modelId, request.op ?? "t2v", JSON.stringify(request), now, now, o.dependsOn ?? null);+ return id;+}+const h3 = (extra: Record<string, unknown> = {}) => ({ feature: "video", modelId: "oss-minimax-h3", op: "t2v", prompt: "a model walks a runway in silver light", params: { duration: 15, resolution: "768p", aspectRatio: "16:9" }, account: a, place: "pool", hold: "old-hold", charge: "7 units", charged: true, ...extra });++describe("running an account's run again for it", () => {+ it("makes a new run in the same account on this install's GPUs, with the changes and the notice, and free", async () => {+ const r = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a lighthouse at dusk", params: { aspectRatio: "16:9", seed: 3 }, shown: { amount: 7, priceVersion: "v7" } });+ expect(r.status).toBe(201);+ const first = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ expect(fake.calls_of("/v1/reserve")).toHaveLength(1);+ const admitted = admissions();++ const res = await again(first, { changes: { params: { seed: 11 } }, notice: NOTICE });+ expect(res.status).toBe(201);+ const body = (await res.json()) as { original: string; account: string; place: string; ids: string[]; items: { id: string; notice: string; params: Record<string, unknown> }[] };+ expect(body).toMatchObject({ original: first, account: a, place: "pool" });+ expect(body.ids).toHaveLength(1);+ expect(body.ids[0]).not.toBe(first);+ expect(body.items[0].notice).toBe(NOTICE);+ expect(body.items[0].params).toMatchObject({ seed: 11, aspectRatio: "16:9" });++ const made = stored(body.ids[0]);+ expect(made.account).toBe(a);+ expect(made.place).toBe("pool");+ expect(made.notice).toBe(NOTICE);+ expect(made.prompt).toBe("a lighthouse at dusk");+ expect(made.modelId).toBe("oss-z-image-turbo");+ // Free: nothing set aside, no charge, and not counted against the limits on runs here.+ expect(made.hold).toBeUndefined();+ expect(made.charge).toBeUndefined();+ expect(fake.calls_of("/v1/reserve")).toHaveLength(1);+ expect(admissions()).toBe(admitted);++ const log = lastAudit();+ expect(log).toMatchObject({ action: "run.again", target: first, status: 201 });+ const detail = JSON.parse(log.detail_json!) as Record<string, unknown>;+ expect(detail).toMatchObject({ account: a, ids: body.ids, place: "pool", changed: ["params.seed"], params: { seed: 11 }, notice: true });+ expect(log.detail_json).not.toContain("lighthouse");+ });++ it("changes a MiniMax H3 clip's length to one the model makes, and keeps everything else", async () => {+ const id = stash(h3());+ const res = await again(id, { changes: { params: { duration: 5 } }, notice: NOTICE });+ expect(res.status).toBe(201);+ const { ids } = (await res.json()) as { ids: string[] };+ const made = stored(ids[0]);+ expect(made.params).toMatchObject({ duration: 5, resolution: "768p", aspectRatio: "16:9" });+ expect(made).toMatchObject({ modelId: "oss-minimax-h3", op: "t2v", account: a, place: "pool", notice: NOTICE });+ expect(made.hold).toBeUndefined();+ expect(made.charged).toBeUndefined();+ });++ it("refuses a length the model doesn't make, and a setting the request doesn't take, with the reason", async () => {+ const id = stash(h3());+ for (const duration of [20, 4.5, 0]) {+ const res = await again(id, { changes: { params: { duration } } });+ expect(res.status).toBe(400);+ expect(((await res.json()) as { error: string }).error).toMatch(/duration|seconds/);+ }+ const typo = await again(id, { changes: { params: { durration: 5 } } });+ expect(typo.status).toBe(400);+ expect(((await typo.json()) as { error: string }).error).toBe("Unknown setting: durration");+ for (const bad of [{ changes: { model: "x" } }, { other: 1 }, { notice: 5 }, { notice: "x".repeat(301) }, { changes: { prompt: " " } }, [1]]) {+ expect((await again(id, bad)).status).toBe(400);+ }+ expect(lastAudit()).toMatchObject({ action: "run.again", target: id, status: 400 });+ });++ it("answers 404 for no such run and for the owner's own, and 409 for a step of a longer run", async () => {+ expect((await again("no-such-run", {})).status).toBe(404);+ const mine = stash({ ...h3(), account: undefined, place: undefined });+ const res = await again(mine, {});+ expect(res.status).toBe(404);+ expect(((await res.json()) as { error: string }).error).toMatch(/yours/);+ const step = stash(h3(), { dependsOn: mine });+ expect((await again(step, {})).status).toBe(409);+ expect(lastAudit()).toMatchObject({ action: "run.again", target: step, status: 409 });+ });++ it("is the owner's, or an admin token's with queue:control", async () => {+ const id = stash(h3());+ expect((await again(id, {}, { cookie })).status).toBe(403);+ const reader = tokens.createAdminToken({ name: "reader", scopes: ["runs:read", "outputs:view"] }).token;+ const denied = await again(id, {}, { authorization: `Bearer ${reader}` });+ expect(denied.status).toBe(403);+ expect(((await denied.json()) as { code: string }).code).toBe("scope");+ const control = tokens.createAdminToken({ name: "control", scopes: ["queue:control"] }).token;+ const ok = await again(id, { changes: { params: { duration: 5 } } }, { authorization: `Bearer ${control}` });+ expect(ok.status).toBe(201);+ const { ids } = (await ok.json()) as { ids: string[] };+ expect(stored(ids[0]).notice).toBeUndefined();+ });++ it("runs a run that went to the account's own GPU there again", async () => {+ const r = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "a quiet harbour", params: { seed: 1 } }, gpuCookie);+ expect(r.status).toBe(201);+ const first = ((await r.json()) as { items: { id: string }[] }).items[0].id;+ expect(stored(first).place).toBeUndefined();+ const res = await again(first, { changes: { prompt: "a quiet harbour at dawn" }, notice: NOTICE });+ expect(res.status).toBe(201);+ const body = (await res.json()) as { place: string; ids: string[] };+ expect(body.place).toBe("own");+ const made = stored(body.ids[0]);+ expect(made).toMatchObject({ account: withGpu, prompt: "a quiet harbour at dawn", notice: NOTICE });+ expect(made.place).toBeUndefined();+ expect(JSON.parse(lastAudit().detail_json!)).toMatchObject({ changed: ["prompt"], place: "own" });+ });+});