Skip to content

armgit / fuobe

Public Imported from GitHub
0

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

Admin: re-run an account's failed or cancelled run

Adarsh4724a5b925f9
diff --git a/docs/admin-api.md b/docs/admin-api.md
index cf95a068..aaf137e4 100644
--- a/docs/admin-api.md
+++ b/docs/admin-api.md
@@ -38,6 +38,7 @@ Keep the token out of URLs, logs and shared files. Send it only in the `Authoriz
| `accounts:write` | `PATCH /api/admin/accounts/{id}` with `{ "disabled": true \| false }` or `{ "signOut": true }` (its paired ComfyUIs stop too) |
| `accounts:delete` | `DELETE /api/admin/accounts/{id}`: its runs, files and record go. It can't be undone |
| `runs:read` | `GET /api/admin/generations`: runs, each one's facts only (when, which model and app, how it ended, how many results). Accounts' and guests' runs by default; the owner's own with `whose=ours` or `whose=everyone`. With `outputs:view`, `GET /api/admin/generations/{id}` too |
+| `runs:write` | `POST /api/admin/generations/{id}/rerun`: a new run in an account, made from its run that failed or was cancelled |
| `runs:delete` | `DELETE /api/admin/generations/{id}`: a run still going is canceled first |
| `outputs:view` | `GET /api/admin/files/{path}`: a stored file, an account's or the owner's own, held ones too. Each view is logged. With `runs:read`, the runs' prompts, inputs and results too, and one run in full |
| `outputs:hide` | `POST /api/admin/outputs/hide` |
@@ -108,8 +109,9 @@ Times are epoch milliseconds and sizes are bytes. Every answer is `Cache-Control
| `PATCH /api/admin/accounts/{id}` | exactly one of `{ disabled: boolean }`, `{ signOut: true }`, `{ password: string }` or `{ email: string }` | the account (no numbers). `password`: a new password of at least 8 characters (400 otherwise), hashed as at sign-up. `email`: a new sign-in email, lower-cased as at sign-up (400 for one that isn't an email address, 409 when another account uses it). Either one ends every sign-in of the account, so it logs in again; its paired ComfyUIs stay paired. The log row names the account only, never the password or the email |
| `DELETE /api/admin/accounts/{id}` | | 204 |
| `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 |
+| `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. `rerunOf` and `rerunAs` (also on each run of the list): the run it is a re-run of, and the run it was re-run as. 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}/rerun` | `{ reason? }`: a sentence for the admin log (up to 300 characters) | 201 `{ run, account, ids, held? }`: a new run in the same account with the same request (feature, model, words, settings and files), sent through the account's own Run: the same checks, limits and services, queued and priced the same way, on the place the run went before when it can go there. The account sees it as any run of its own. `held`: why it waits to enter the line. 404 for an unknown run, the owner's own or a deleted account; 409 for a run that didn't fail and wasn't cancelled, one in the Trash, a step of a longer run, an account switched off, a run re-run already (with `rerunAs`), or input files that are gone (`code: "input-gone"`); any other refusal (a limit, a service) is the Run's own answer, with its status and `code` |
| `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 +142,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.password`, `account.email`,
`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.rerun` (the run as its target, with the account, the new run's `ids` and the `reason`), `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 action
diff --git a/src/app/api/admin/generations/[id]/rerun/route.ts b/src/app/api/admin/generations/[id]/rerun/route.ts
new file mode 100644
index 00000000..23083c62
--- /dev/null
+++ b/src/app/api/admin/generations/[id]/rerun/route.ts
@@ -0,0 +1,52 @@
+import { POST as submitRun } from "@/app/api/generations/route";
+import { adminAccess, audit } from "@/server/admin-tokens";
+import { rerunFor, RerunError } from "@/server/admin-rerun";
+
+const NO_STORE = { "Cache-Control": "no-store" };
+
+/** The longest reason the admin log keeps. */
+const REASON_MAX = 300;
+
+/**
+ * Re-run an account's run that failed or was cancelled (owner only, or an admin token with runs:write): `{ reason? }`.
+ * A new run is made in the same account with the same request, through the account's own Run, so it meets the same
+ * checks, limits and services and is queued the same way; the account sees it as any run of its own. 201
+ * `{ run, account, ids, held? }`. 404 for no such run, the owner's own run or a deleted account; 409 for a run still
+ * going or done, one in the Trash, a step of a longer run, a switched-off account, a run re-run already (`rerunAs`) or
+ * input files that are gone; any other refusal is the Run's own answer. Each call is in the admin log, with the reason.
+ */
+export async function POST(request: Request, ctx: RouteContext<"/api/admin/generations/[id]/rerun">) {
+ const access = adminAccess(request, "runs:write", "Only the studio's owner re-runs a person's run");
+ if (access instanceof Response) return access;
+ const { id } = await ctx.params;
+ if (!/^[\w-]{1,80}$/.test(id)) {
+ audit(access.actor, "run.rerun", 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.rerun", id, null, 400);
+ return Response.json({ error: "Send JSON: { reason? }" }, { status: 400, headers: NO_STORE });
+ }
+ const raw = body && typeof body === "object" ? (body as { reason?: unknown }).reason : undefined;
+ if (raw !== undefined && raw !== null && typeof raw !== "string") {
+ audit(access.actor, "run.rerun", id, null, 400);
+ return Response.json({ error: "reason is a sentence" }, { status: 400, headers: NO_STORE });
+ }
+ const reason = typeof raw === "string" ? raw.replace(/\s+/g, " ").trim().slice(0, REASON_MAX) : "";
+ try {
+ const made = await rerunFor(id, submitRun);
+ audit(access.actor, "run.rerun", id, { account: made.account, ids: made.ids, ...(made.held && { held: made.held }), ...(reason && { reason }) }, 201);
+ return Response.json({ run: id, account: made.account, ids: made.ids, ...(made.held && { held: made.held }) }, { status: 201, headers: NO_STORE });
+ } catch (e) {
+ const status = e instanceof RerunError ? e.status : 500;
+ const error = e instanceof RerunError ? e.message : "The run couldn't be made";
+ const code = e instanceof RerunError ? e.code : undefined;
+ const extra = e instanceof RerunError ? e.extra : {};
+ audit(access.actor, "run.rerun", id, { error: error.slice(0, 200), ...(code && { code }), ...(reason && { reason }) }, status);
+ return Response.json({ error, ...(code && { code }), ...extra }, { status, headers: NO_STORE });
+ }
+}
diff --git a/src/app/api/admin/generations/[id]/route.ts b/src/app/api/admin/generations/[id]/route.ts
index 9f3a1af2..219fd736 100644
--- a/src/app/api/admin/generations/[id]/route.ts
+++ b/src/app/api/admin/generations/[id]/route.ts
@@ -2,6 +2,7 @@ import { connection } from "next/server";
import { generationAccount } from "@/server/account-library";
import { actorHas, adminAccess, audit, auditContentRead, lacksScope } from "@/server/admin-tokens";
import { deleteForever } from "@/server/library";
+import { rerunLinks } from "@/server/admin-rerun";
import { runDetails } from "@/server/run-details";
const NO_STORE = { "Cache-Control": "no-store" };
@@ -11,7 +12,7 @@ const NO_STORE = { "Cache-Control": "no-store" };
* only, or an admin token with runs:read and outputs:view): what it asked for (each setting beside its default), its
* files, where it ran, what came back and what the account was shown, its batch, its chain's earlier and later steps,
* and the runs around it. Keys, tokens and a GPU's address never are part of it (src/server/run-details.ts). The
- * account's email needs accounts:read. Each read is in the admin log with the account (or "owner") as its target.
+ * account's email needs accounts:read. `rerunOf` and `rerunAs`: the run an admin re-ran it from, or as. Each read is in the admin log with the account (or "owner") as its target.
*/
export async function GET(request: Request, ctx: RouteContext<"/api/admin/generations/[id]">) {
await connection();
@@ -23,7 +24,7 @@ export async function GET(request: Request, ctx: RouteContext<"/api/admin/genera
const details = runDetails(id, { emails: actorHas(access.actor, "accounts:read") });
if (!details) return Response.json({ error: "No such run" }, { status: 404, headers: NO_STORE });
auditContentRead(access.actor, "runs.content", [details.run.account?.id ?? "owner"], { run: id });
- return Response.json(details, { headers: NO_STORE });
+ return Response.json({ ...details, ...rerunLinks([id]).get(id) }, { headers: NO_STORE });
}
/**
diff --git a/src/app/api/admin/generations/route.ts b/src/app/api/admin/generations/route.ts
index 70e4ccf2..41d061ed 100644
--- a/src/app/api/admin/generations/route.ts
+++ b/src/app/api/admin/generations/route.ts
@@ -1,6 +1,7 @@
import { connection } from "next/server";
import { accountRunOptions, listAdminRuns } from "@/server/account-admin";
import { actorHas, adminAccess, auditContentRead, auditRead } from "@/server/admin-tokens";
+import { rerunLinks } from "@/server/admin-rerun";
const NO_STORE = { "Cache-Control": "no-store" };
@@ -11,7 +12,8 @@ const NO_STORE = { "Cache-Control": "no-store" };
* `started`, `running`: waiting and started), `kind` (image, video, audio, model3d, text), `model` (letters of the model
* id), `from` and `to` (yyyy-mm-dd, UTC, both included), `q` (words of the prompt, or a run id), `before=<createdAt>:<id>`
* (the `next` of the last page) and `limit` (≤ 100). Each run says `whose` it is (`account`, `guest`, `owner`); the
- * owner's own have `account: null` and their `source`.
+ * owner's own have `account: null` and their `source`. A run an admin re-ran has `rerunAs` (the new run's id), and the
+ * new run has `rerunOf`.
*
* A token with runs:read alone gets each run's facts (when, which model, how it ended); its prompt, inputs and results
* need outputs:view, and the accounts' emails need accounts:read. Every read of runs' content, the owner's too, is in
@@ -40,5 +42,6 @@ export async function GET(request: Request) {
};
auditRead(access.actor, "runs.list", filters);
if (show.content) auditContentRead(access.actor, "runs.content", page.items.map((r) => r.account?.id ?? "owner"), filters);
- return Response.json(page, { headers: NO_STORE });
+ const links = rerunLinks(page.items.map((r) => r.id));
+ return Response.json({ ...page, items: page.items.map((r) => ({ ...r, ...links.get(r.id) })) }, { headers: NO_STORE });
}
diff --git a/src/server/admin-rerun.ts b/src/server/admin-rerun.ts
new file mode 100644
index 00000000..c8a57930
--- /dev/null
+++ b/src/server/admin-rerun.ts
@@ -0,0 +1,151 @@
+import "server-only";
+import type { GenerationRequest } from "@/lib/catalog/types";
+import { accountInputProblem } from "./account-inputs";
+import { accountById, accountRequest } from "./auth";
+import { db } from "./db";
+import { stampOf, withoutStamp } from "./run-stamp";
+
+/**
+ * An admin's re-run of an account's run that failed or was cancelled (POST /api/admin/generations/{id}/rerun): a new
+ * run in the same account with the same request (feature, model, words, settings and files), sent through the account's
+ * own Run (POST /api/generations) as if its page had sent it. So it meets every check a press of Run meets (the limits,
+ * the moderation and billing services, the policy of this install's GPUs), and it is queued, priced and set aside the
+ * same way. To the account it is a run like any other. Which run re-ran which is kept here for the admin API only.
+ */
+
+/** How a run must have ended to be re-run. */
+export const RERUN_STATUSES = ["failed", "canceled"] as const;
+
+/** A re-run being made that long ago and never finished (a server stopped in the middle): another may be made. */
+const PENDING_MS = 2 * 60_000;
+
+export const INPUTS_GONE = "Its input files are no longer here";
+
+export class RerunError extends Error {
+ constructor(
+ readonly status: number,
+ message: string,
+ readonly code?: string,
+ readonly extra: Record<string, unknown> = {},
+ ) {
+ super(message);
+ }
+}
+
+/** The account's Run: the run route's POST, given as an argument so this module never imports a route. */
+export type SubmitRun = (request: Request) => Promise<Response>;
+
+export interface RerunResult {
+ account: string;
+ ids: string[];
+ /** Why the new run waits to enter the line, when it does (the limits or a service). */
+ held?: string;
+}
+
+interface Row {
+ status: string;
+ request_json: string;
+ depends_on: string | null;
+ batch_id: string | null;
+}
+
+/** The new run's ids for a re-run made of `id`, or null (none, or one being made). */
+function madeOf(id: string): { ids: string[] | null; at: number } | undefined {
+ const r = db().prepare("SELECT new_ids_json, at FROM admin_reruns WHERE run_id = ?").get(id) as { new_ids_json: string | null; at: number } | undefined;
+ if (!r) return undefined;
+ return { ids: r.new_ids_json ? (JSON.parse(r.new_ids_json) as string[]) : null, at: r.at };
+}
+
+/**
+ * Re-run run `id` for its account. Throws RerunError with the status to answer: 404 for no such run, the owner's own run
+ * or a deleted account; 409 for a run that hasn't failed or been cancelled, one in the Trash, a step of a longer run, an
+ * account switched off, a run re-run already, or files that are gone; else the account's Run's own answer.
+ */
+export async function rerunFor(id: string, submit: SubmitRun, now = Date.now()): Promise<RerunResult> {
+ const row = db().prepare("SELECT status, request_json, depends_on, batch_id FROM generations WHERE id = ?").get(id) as Row | undefined;
+ if (!row) throw new RerunError(404, "No such run");
+ let stored: GenerationRequest;
+ try {
+ stored = JSON.parse(row.request_json) as GenerationRequest;
+ } catch {
+ throw new RerunError(409, "That run's request can't be read");
+ }
+ const accountId = stored.account;
+ if (!accountId) throw new RerunError(404, "That run is the owner's own, not an account's");
+ if (!(RERUN_STATUSES as readonly string[]).includes(row.status)) throw new RerunError(409, "Only a run that failed or was cancelled can be re-run", "not-ended");
+ if (db().prepare("SELECT 1 FROM generation_trash WHERE generation_id = ?").get(id)) throw new RerunError(409, "That run was deleted", "deleted");
+ const later = db().prepare("SELECT 1 FROM generations WHERE depends_on = @id OR (substr(depends_on, 1, 1) = '[' AND instr(depends_on, @quoted) > 0) LIMIT 1").get({ id, quoted: JSON.stringify(id) });
+ if (row.depends_on || later) throw new RerunError(409, "That run is one step of a longer run, so it can't be re-run on its own", "chained");
+ const account = accountById(accountId);
+ if (!account) throw new RerunError(404, "That run's account is gone");
+ if (account.disabled) throw new RerunError(409, "That account is switched off", "account-off");
+ const made = madeOf(id);
+ if (made?.ids) throw new RerunError(409, `That run was re-run already, as ${made.ids[0]}`, "rerun-already", { rerunAs: made.ids[0] });
+ if (made && now - made.at < PENDING_MS) throw new RerunError(409, "A re-run of that run is being made", "rerun-pending");
+
+ // The request as its page sent it: the server's own stamp and the account are set again by the Run.
+ const base = withoutStamp(stored) as GenerationRequest & Record<string, unknown>;
+ delete base.account;
+ let body: Record<string, unknown> = base;
+ // One job of a batch: its share of the outputs, not the whole batch's again.
+ if (row.batch_id) {
+ const jobs = db().prepare("SELECT COUNT(*) FROM generations WHERE batch_id = ? AND request_json = ? AND depends_on IS NULL").pluck().get(row.batch_id, row.request_json) as number;
+ const asked = Math.max(1, Number(stored.params?.numOutputs) || 1);
+ if (jobs > 1) body = { ...base, params: { ...stored.params, numOutputs: Math.max(1, Math.ceil(asked / jobs)) } };
+ }
+ const files = accountInputProblem(body as unknown as GenerationRequest, accountId);
+ if (files?.code === "input-gone") throw new RerunError(409, INPUTS_GONE, "input-gone");
+ if (files) throw new RerunError(files.status, files.error, files.code);
+
+ // Where it ran before is where it is asked to run again (the Run decides, as for any press).
+ const place = stampOf(stored).place === "pool" ? "pool" : "own";
+ const send = async (preview: boolean, extra: Record<string, unknown>) => {
+ const text = JSON.stringify({ ...body, place, ...extra });
+ const res = await submit(
+ accountRequest(account, `http://localhost/api/generations${preview ? "?preview=1" : ""}`, { method: "POST", headers: { "content-type": "application/json" }, body: text }),
+ );
+ return { status: res.status, json: (await res.json().catch(() => ({}))) as Record<string, unknown> };
+ };
+
+ // Claimed first: two presses make one run.
+ const claimed = db()
+ .prepare("INSERT INTO admin_reruns (run_id, new_ids_json, at) VALUES (?, NULL, ?) ON CONFLICT (run_id) DO UPDATE SET at = excluded.at WHERE admin_reruns.new_ids_json IS NULL AND admin_reruns.at < ?")
+ .run(id, now, now - PENDING_MS);
+ if (claimed.changes === 0) throw new RerunError(409, "A re-run of that run is being made", "rerun-pending");
+ try {
+ // The price its page would show, as a press of Run sends it beside the request.
+ const quote = (await send(true, {})).json.quote as { amount?: unknown; priceVersion?: unknown } | undefined;
+ const shown = quote && typeof quote.amount === "number" && typeof quote.priceVersion === "string" ? { amount: quote.amount, priceVersion: quote.priceVersion } : undefined;
+ const r = await send(false, shown ? { shown } : {});
+ const items = Array.isArray(r.json.items) ? (r.json.items as { id?: unknown }[]) : [];
+ const ids = items.map((g) => g.id).filter((x): x is string => typeof x === "string");
+ if (r.status !== 201 || !ids.length) {
+ const error = typeof r.json.error === "string" ? r.json.error : "The run couldn't be made";
+ throw new RerunError(r.status === 201 ? 500 : r.status, error, typeof r.json.code === "string" ? r.json.code : undefined);
+ }
+ db().prepare("UPDATE admin_reruns SET new_ids_json = ?, at = ? WHERE run_id = ?").run(JSON.stringify(ids), Date.now(), id);
+ const held = (r.json.held as { reason?: unknown } | undefined)?.reason;
+ return { account: accountId, ids, ...(typeof held === "string" && { held }) };
+ } catch (e) {
+ db().prepare("DELETE FROM admin_reruns WHERE run_id = ? AND new_ids_json IS NULL").run(id);
+ if (e instanceof RerunError) throw e;
+ throw new RerunError(500, (e as Error).message || "The run couldn't be made");
+ }
+}
+
+/** For each of `ids`: the run it is a re-run of, and the run it was re-run as (admin API only). */
+export function rerunLinks(ids: string[]): Map<string, { rerunOf?: string; rerunAs?: string }> {
+ const out = new Map<string, { rerunOf?: string; rerunAs?: string }>();
+ if (!ids.length) return out;
+ const set = (id: string, v: { rerunOf?: string; rerunAs?: string }) => out.set(id, { ...out.get(id), ...v });
+ const list = JSON.stringify(ids);
+ const as = db()
+ .prepare("SELECT run_id, json_extract(new_ids_json, '$[0]') AS first FROM admin_reruns WHERE new_ids_json IS NOT NULL AND run_id IN (SELECT value FROM json_each(?))")
+ .all(list) as { run_id: string; first: string }[];
+ for (const r of as) set(r.run_id, { rerunAs: r.first });
+ const of = db()
+ .prepare("SELECT r.run_id, j.value AS id FROM admin_reruns r, json_each(r.new_ids_json) j WHERE r.new_ids_json IS NOT NULL AND j.value IN (SELECT value FROM json_each(?))")
+ .all(list) as { run_id: string; id: string }[];
+ for (const r of of) set(r.id, { rerunOf: r.run_id });
+ return out;
+}
diff --git a/src/server/admin-tokens.ts b/src/server/admin-tokens.ts
index 34e020a7..bb953585 100644
--- a/src/server/admin-tokens.ts
+++ b/src/server/admin-tokens.ts
@@ -23,6 +23,7 @@ export const SCOPES = [
"accounts:write",
"accounts:delete",
"runs:read",
+ "runs:write",
"runs:delete",
"outputs:view",
"outputs:hide",
@@ -48,6 +49,7 @@ export const SCOPE_LABELS: Record<Scope, string> = {
"accounts:write": "Switch accounts off and on, sign them out, set their password or email",
"accounts:delete": "Delete accounts",
"runs:read": "See accounts' runs: when, which model and how they ended (their prompts and results need Open accounts' files; emails need See accounts)",
+ "runs:write": "Re-run an account's run that failed or was cancelled, in its own account (it meets the same checks as the account's Run)",
"runs:delete": "Delete accounts' runs",
"outputs:view": "Open accounts' files, and read their runs' prompts and results",
"outputs:hide": "Hide results",
diff --git a/src/server/auth.ts b/src/server/auth.ts
index 0b191447..baf5ef3a 100644
--- a/src/server/auth.ts
+++ b/src/server/auth.ts
@@ -638,7 +638,23 @@ export function sessionCookieOf(request: Request): string | undefined {
export const ADMIN_BEARER = /^Bearer\s+fuobe_adm_/i;
export const hasAdminBearer = (request: Request) => ADMIN_BEARER.test(request.headers.get("authorization") ?? "");
+/**
+ * Requests this server makes itself on an account's behalf (an admin's re-run of the account's run, admin-rerun.ts):
+ * read as that account's own, as if its signed-in page had sent them. Only server code can make one (accountRequest);
+ * no request that arrives from outside is ever in this map.
+ */
+const ACTING = new WeakMap<Request, Account>();
+
+/** A request read as `account`'s own by requestViewer and requestAccount (never one a client sent). */
+export function accountRequest(account: Account, url: string, init: RequestInit): Request {
+ const request = new Request(url, init);
+ ACTING.set(request, account);
+ return request;
+}
+
export function requestViewer(request: Request, cookie = sessionCookieOf(request)): RequestViewer {
+ const acting = ACTING.get(request);
+ if (acting) return { kind: "account", account: acting };
if (hasAdminBearer(request)) return { kind: "guest" };
if (!authEnabled() || validToken(request.headers.get("authorization"))) return { kind: "owner" };
const v = sessionViewer(cookie);
@@ -649,6 +665,8 @@ export function requestViewer(request: Request, cookie = sessionCookieOf(request
/** The account behind this request's session, while public sign-up is on for its address (null: the owner, a guest, or off). */
export function requestAccount(request: Request, cookie = sessionCookieOf(request)): Account | null {
+ const acting = ACTING.get(request);
+ if (acting) return acting;
if (hasAdminBearer(request) || validToken(request.headers.get("authorization"))) return null;
const v = sessionViewer(cookie);
return v?.kind === "account" && publicSignup(request.headers.get("host")) ? v.account : null;
diff --git a/src/server/db.ts b/src/server/db.ts
index fa09f9cf..f9742572 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -977,7 +977,12 @@ export const ADMIN_TABLES = `CREATE TABLE IF NOT EXISTS admin_tokens (
detail_json TEXT,
status INTEGER NOT NULL
);
- CREATE INDEX IF NOT EXISTS admin_audit_at ON admin_audit(at);`;
+ CREATE INDEX IF NOT EXISTS admin_audit_at ON admin_audit(at);
+ CREATE TABLE IF NOT EXISTS admin_reruns (
+ run_id TEXT PRIMARY KEY,
+ new_ids_json TEXT,
+ at INTEGER NOT NULL
+ );`;
/**
* Skills (src/server/recipes.ts, src/server/skill-runs.ts): a run of a skill whose steps wait for each other across
diff --git a/tests/admin-rerun.test.ts b/tests/admin-rerun.test.ts
new file mode 100644
index 00000000..262c8037
--- /dev/null
+++ b/tests/admin-rerun.test.ts
@@ -0,0 +1,214 @@
+import http from "node:http";
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } 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";
+
+vi.mock("next/server", async (importOriginal) => ({ ...(await importOriginal<typeof import("next/server")>()), connection: async () => {} }));
+
+// POST /api/admin/generations/{id}/rerun: an account's failed or cancelled run made again in its account, through its
+// own Run (the same checks, the billing service's reserve, the line). A stand-in billing service and a stand-in ComfyUI
+// as this install's GPUs.
+const dir = tempDir("fuobe-admin-rerun-");
+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 rerunRoute = await import("@/app/api/admin/generations/[id]/rerun/route");
+const listRoute = await import("@/app/api/admin/generations/route");
+const oneRoute = await import("@/app/api/admin/generations/[id]/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");
+const { getGeneration } = await import("@/server/generations");
+
+let fake: FakeBilling;
+let a = "";
+let cookie = "";
+let owner = "";
+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}`;
+});
+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 rerun = (id: string, body: unknown = {}, headers: Record<string, string> = { cookie: owner }) =>
+ rerunRoute.POST(
+ new Request(`http://localhost:3000/api/admin/generations/${id}/rerun`, { 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 setStatus = (id: string, status: string) => db().prepare("UPDATE generations SET status = ? WHERE id = ?").run(status, id);
+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 };
+
+/** A run the account made with its Run, ended as `status`. */
+async function ended(status: "failed" | "canceled", body: Record<string, unknown> = {}): Promise<string> {
+ 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" }, ...body });
+ expect(r.status).toBe(201);
+ const id = ((await r.json()) as { items: { id: string }[] }).items[0].id;
+ setStatus(id, status);
+ return id;
+}
+
+describe("re-running an account's run for it", () => {
+ it("makes a new run in the same account through its Run: the same request, reserved and queued on this install's GPUs", async () => {
+ const first = await ended("canceled");
+ expect(fake.calls_of("/v1/reserve")).toHaveLength(1);
+
+ const res = await rerun(first, { reason: "It took too long; the person asked again" });
+ expect(res.status).toBe(201);
+ const body = (await res.json()) as { run: string; account: string; ids: string[] };
+ expect(body).toMatchObject({ run: first, account: a });
+ expect(body.ids).toHaveLength(1);
+ expect(body.ids[0]).not.toBe(first);
+
+ const made = stored(body.ids[0]);
+ expect(made).toMatchObject({ account: a, place: "pool", prompt: "a lighthouse at dusk", modelId: "oss-z-image-turbo" });
+ expect(made.params).toMatchObject({ aspectRatio: "16:9", seed: 3 });
+ // Priced and set aside like any press of Run: the billing service's reserve, with the price its page would show.
+ const reserves = fake.calls_of("/v1/reserve");
+ expect(reserves).toHaveLength(2);
+ expect((reserves[1].body as { shown?: unknown }).shown).toEqual({ amount: 7, priceVersion: "v7" });
+ expect(made.hold).toBeTruthy();
+ // To the account it is a run like any other: no word of a re-run or an admin.
+ const g = getGeneration(body.ids[0])!;
+ expect(JSON.stringify(g)).not.toMatch(/rerun|re-run|admin/i);
+ expect(made.notice).toBeUndefined();
+
+ const log = lastAudit();
+ expect(log).toMatchObject({ action: "run.rerun", target: first, status: 201 });
+ expect(JSON.parse(log.detail_json!)).toMatchObject({ account: a, ids: body.ids, reason: "It took too long; the person asked again" });
+ expect(log.detail_json).not.toContain("lighthouse");
+ });
+
+ it("links the two runs in the admin API, and makes one re-run of a run", async () => {
+ const first = await ended("failed");
+ const res = await rerun(first);
+ expect(res.status).toBe(201);
+ const { ids } = (await res.json()) as { ids: string[] };
+ const one = (id: string) => oneRoute.GET(new Request(`http://localhost:3000/api/admin/generations/${id}`, { headers: { cookie: owner, host: "localhost:3000" } }), { params: Promise.resolve({ id }) } as never);
+ expect(await (await one(first)).json()).toMatchObject({ rerunAs: ids[0] });
+ expect(await (await one(ids[0])).json()).toMatchObject({ rerunOf: first });
+ const list = (await (await listRoute.GET(new Request("http://localhost:3000/api/admin/generations?limit=100", { headers: { cookie: owner, host: "localhost:3000" } }))).json()) as { items: { id: string; rerunOf?: string; rerunAs?: string }[] };
+ expect(list.items.find((r) => r.id === first)).toMatchObject({ rerunAs: ids[0] });
+ expect(list.items.find((r) => r.id === ids[0])).toMatchObject({ rerunOf: first });
+ // The account's own list says nothing of it.
+ const mine = await (await generationsRoute.GET(new Request("http://localhost:3000/api/generations", { headers: { cookie, host: "localhost:3000" } }))).text();
+ expect(mine).not.toMatch(/rerun/i);
+
+ const again = await rerun(first);
+ expect(again.status).toBe(409);
+ expect(await again.json()).toMatchObject({ code: "rerun-already", rerunAs: ids[0] });
+ // The new run, once it fails too, can be re-run in turn.
+ setStatus(ids[0], "failed");
+ expect((await rerun(ids[0])).status).toBe(201);
+ });
+
+ it("takes only a run that failed or was cancelled, not in the Trash, and not a step of a longer run", async () => {
+ const id = await ended("failed");
+ for (const s of ["queued", "running", "succeeded"]) {
+ setStatus(id, s);
+ const r = await rerun(id);
+ expect(r.status).toBe(409);
+ expect(await r.json()).toMatchObject({ code: "not-ended" });
+ }
+ setStatus(id, "canceled");
+ db().prepare("INSERT INTO generation_trash (generation_id, deleted_at) VALUES (?, ?)").run(id, Date.now());
+ expect(await (await rerun(id)).json()).toMatchObject({ code: "deleted" });
+ db().prepare("DELETE FROM generation_trash WHERE generation_id = ?").run(id);
+ const step = await ended("failed");
+ db().prepare("UPDATE generations SET depends_on = ? WHERE id = ?").run(id, step);
+ expect(await (await rerun(step)).json()).toMatchObject({ code: "chained" });
+ expect(await (await rerun(id)).json()).toMatchObject({ code: "chained" });
+ expect((await rerun("no-such-run")).status).toBe(404);
+ expect(lastAudit()).toMatchObject({ action: "run.rerun", target: "no-such-run", status: 404 });
+ });
+
+ it("says when its input files are no longer here", async () => {
+ const id = await ended("failed");
+ db()
+ .prepare("UPDATE generations SET request_json = json_set(request_json, '$.inputs', json(?)) WHERE id = ?")
+ .run(JSON.stringify({ image: "/api/files/uploads/gone.png" }), id);
+ const r = await rerun(id);
+ expect(r.status).toBe(409);
+ expect(await r.json()).toMatchObject({ error: "Its input files are no longer here", code: "input-gone" });
+ expect(fake.calls_of("/v1/reserve")).toHaveLength(1);
+ });
+
+ it("answers what the account's Run answers when a service refuses, and makes nothing", async () => {
+ const id = await ended("canceled");
+ const before = (db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n;
+ fake.refuse = { code: "limit", text: "Your plan's runs for today are used up." };
+ const r = await rerun(id);
+ expect(r.status).toBeGreaterThanOrEqual(400);
+ expect(((await r.json()) as { error: string }).error).toBe("Your plan's runs for today are used up.");
+ expect((db().prepare("SELECT COUNT(*) AS n FROM generations").get() as { n: number }).n).toBe(before);
+ // Nothing kept of the try: once the service takes it, the run is made.
+ fake.refuse = null;
+ expect((await rerun(id)).status).toBe(201);
+ });
+
+ it("is the owner's, or an admin token's with runs:write", async () => {
+ const id = await ended("failed");
+ expect((await rerun(id, {}, { cookie })).status).toBe(403);
+ const control = tokens.createAdminToken({ name: "control", scopes: ["queue:control", "runs:read"] }).token;
+ const denied = await rerun(id, {}, { authorization: `Bearer ${control}` });
+ expect(denied.status).toBe(403);
+ expect(await denied.json()).toMatchObject({ code: "scope", scope: "runs:write" });
+ const writer = tokens.createAdminToken({ name: "writer", scopes: ["runs:write"] }).token;
+ const ok = await rerun(id, { reason: "x".repeat(400) }, { authorization: `Bearer ${writer}` });
+ expect(ok.status).toBe(201);
+ const detail = JSON.parse(lastAudit().detail_json!) as { reason: string };
+ expect(detail.reason).toHaveLength(300);
+ for (const bad of [{ reason: 5 }]) expect((await rerun(id, bad)).status).toBe(400);
+ });
+
+ it("never reads a client's request as an account's", async () => {
+ const r = await post({ feature: "image", modelId: "oss-z-image-turbo", prompt: "x" }, "");
+ expect(r.status).toBe(401);
+ });
+});